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 + " -`; - } - 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 + ` -`; - } - 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 = '"; - 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 = `${text} { - 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: /^$/, - 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]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|(?=[ \\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", ")|<(?: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", ")|<(?: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", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex() - }; - blockPedantic = { - ...blockNormal, - html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\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: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\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-]*(?: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: /&#x([0-9a-fA-F]{1,6});/g, val: (t3, e3) => rt(e3, 16, "&#x") } }, 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: `); - 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}` : (r2 += d2 + ">", f2 && i3 !== "" && (f2.includes("/>") || f2.includes("`) : 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}` : 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 + "" + t4 + "${t3}`; - else if (typeof t3 == "object" && t3 !== null) { - const n4 = this.buildRawContent(t3), s2 = this.buildAttributesForStopNode(t3); - e2 += n4 === "" ? `<${i3}${s2}/>` : `<${i3}${s2}>${n4}`; - } - } else if (typeof n3 == "object" && n3 !== null) { - const t3 = this.buildRawContent(n3), s2 = this.buildAttributesForStopNode(n3); - e2 += t3 === "" ? `<${i3}${s2}/>` : `<${i3}${s2}>${t3}`; - } else - e2 += `<${i3}>${n3}`; - } - 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 = "` + 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 ? "/" : `>` + 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 + " 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("")}`; - } - } - 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}`, 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`, 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 to execute JavaScript in victim's browser, enabling session hijacking or data theft -* Recommendation: Use Flask's escape() function or Jinja2 templates with auto-escaping enabled for all user inputs rendered in HTML - -SEVERITY GUIDELINES: -- **HIGH**: Directly exploitable vulnerabilities leading to RCE, data breach, or authentication bypass -- **MEDIUM**: Vulnerabilities requiring specific conditions but with significant impact -- **LOW**: Defense-in-depth issues or lower-impact vulnerabilities - -CONFIDENCE SCORING: -- 0.9-1.0: Certain exploit path identified, tested if possible -- 0.8-0.9: Clear vulnerability pattern with known exploitation methods -- 0.7-0.8: Suspicious pattern requiring specific conditions to exploit -- Below 0.7: Don't report (too speculative) - -FINAL REMINDER: -Focus on HIGH and MEDIUM findings only. Better to miss some theoretical issues than flood the report with false positives. Each finding should be something a security engineer would confidently raise in a PR review. - -FALSE POSITIVE FILTERING: - -> You do not need to run commands to reproduce the vulnerability, just read the code to determine if it is a real vulnerability. Do not use the bash tool or write to any files. -> -> HARD EXCLUSIONS - Automatically exclude findings matching these patterns: -> 1. Denial of Service (DOS) vulnerabilities or resource exhaustion attacks. -> 2. Secrets or credentials stored on disk if they are otherwise secured. -> 3. Rate limiting concerns or service overload scenarios. -> 4. Memory consumption or CPU exhaustion issues. -> 5. Lack of input validation on non-security-critical fields without proven security impact. -> 6. Input sanitization concerns for GitHub Action workflows unless they are clearly triggerable via untrusted input. -> 7. A lack of hardening measures. Code is not expected to implement all security best practices, only flag concrete vulnerabilities. -> 8. Race conditions or timing attacks that are theoretical rather than practical issues. Only report a race condition if it is concretely problematic. -> 9. Vulnerabilities related to outdated third-party libraries. These are managed separately and should not be reported here. -> 10. Memory safety issues such as buffer overflows or use-after-free-vulnerabilities are impossible in rust. Do not report memory safety issues in rust or any other memory safe languages. -> 11. Files that are only unit tests or only used as part of running tests. -> 12. Log spoofing concerns. Outputting un-sanitized user input to logs is not a vulnerability. -> 13. SSRF vulnerabilities that only control the path. SSRF is only a concern if it can control the host or protocol. -> 14. Including user-controlled content in AI system prompts is not a vulnerability. -> 15. Regex injection. Injecting untrusted content into a regex is not a vulnerability. -> 16. Regex DOS concerns. -> 16. Insecure documentation. Do not report any findings in documentation files such as markdown files. -> 17. A lack of audit logs is not a vulnerability. -> -> PRECEDENTS - -> 1. Logging high value secrets in plaintext is a vulnerability. Logging URLs is assumed to be safe. -> 2. UUIDs can be assumed to be unguessable and do not need to be validated. -> 3. Environment variables and CLI flags are trusted values. Attackers are generally not able to modify them in a secure environment. Any attack that relies on controlling an environment variable is invalid. -> 4. Resource management issues such as memory or file descriptor leaks are not valid. -> 5. Subtle or low impact web vulnerabilities such as tabnabbing, XS-Leaks, prototype pollution, and open redirects should not be reported unless they are extremely high confidence. -> 6. React and Angular are generally secure against XSS. These frameworks do not need to sanitize or escape user input unless it is using dangerouslySetInnerHTML, bypassSecurityTrustHtml, or similar methods. Do not report XSS vulnerabilities in React or Angular components or tsx files unless they are using unsafe methods. -> 7. Most vulnerabilities in github action workflows are not exploitable in practice. Before validating a github action workflow vulnerability ensure it is concrete and has a very specific attack path. -> 8. A lack of permission checking or authentication in client-side JS/TS code is not a vulnerability. Client-side code is not trusted and does not need to implement these checks, they are handled on the server-side. The same applies to all flows that send untrusted data to the backend, the backend is responsible for validating and sanitizing all inputs. -> 9. Only include MEDIUM findings if they are obvious and concrete issues. -> 10. Most vulnerabilities in ipython notebooks (*.ipynb files) are not exploitable in practice. Before validating a notebook vulnerability ensure it is concrete and has a very specific attack path where untrusted input can trigger the vulnerability. -> 11. Logging non-PII data is not a vulnerability even if the data may be sensitive. Only report logging vulnerabilities if they expose sensitive information such as secrets, passwords, or personally identifiable information (PII). -> 12. Command injection vulnerabilities in shell scripts are generally not exploitable in practice since shell scripts generally do not run with untrusted user input. Only report command injection vulnerabilities in shell scripts if they are concrete and have a very specific attack path for untrusted input. -> -> SIGNAL QUALITY CRITERIA - For remaining findings, assess: -> 1. Is there a concrete, exploitable vulnerability with a clear attack path? -> 2. Does this represent a real security risk vs theoretical best practice? -> 3. Are there specific code locations and reproduction steps? -> 4. Would this finding be actionable for a security team? -> -> For each finding, assign a confidence score from 1-10: -> - 1-3: Low confidence, likely false positive or noise -> - 4-6: Medium confidence, needs investigation -> - 7-10: High confidence, likely true vulnerability - -START ANALYSIS: - -Begin your analysis now. Do this in 3 steps: - -1. Use a sub-task to identify vulnerabilities. Use the repository exploration tools to understand the codebase context, then analyze the PR changes for security implications. In the prompt for this sub-task, include all of the above. -2. Then for each vulnerability identified by the above sub-task, create a new sub-task to filter out false-positives. Launch these sub-tasks as parallel sub-tasks. In the prompt for these sub-tasks, include everything in the "FALSE POSITIVE FILTERING" instructions. -3. Filter out any vulnerabilities where the sub-task reported a confidence less than 8. - -Your final reply must contain the markdown report and nothing else.`, security_review_default; -var init_security_review = __esm(() => { - init_frontmatterParser(); - init_markdownConfigLoader(); - init_promptShellExecution(); - security_review_default = createMovedToPluginCommand({ - name: "security-review", - description: "Complete a security review of the pending changes on the current branch", - progressMessage: "analyzing code changes for security risks", - pluginName: "security-review", - pluginCommand: "security-review", - async getPromptWhileMarketplaceIsPrivate(_args, context7) { - const parsed = parseFrontmatter(SECURITY_REVIEW_MARKDOWN); - const allowedTools = parseSlashCommandToolsFromFrontmatter(parsed.frontmatter["allowed-tools"]); - const processedContent = await executeShellCommandsInPrompt(parsed.content, { - ...context7, - getAppState() { - const appState = context7.getAppState(); - return { - ...appState, - toolPermissionContext: { - ...appState.toolPermissionContext, - alwaysAllowRules: { - ...appState.toolPermissionContext.alwaysAllowRules, - command: allowedTools - } - } - }; - } - }, "security-review"); - return [ - { - type: "text", - text: processedContent - } - ]; - } - }); -}); - -// src/commands/bughunter/index.js -var bughunter_default; -var init_bughunter = __esm(() => { - bughunter_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/commands/terminalSetup/index.ts -var NATIVE_CSIU_TERMINALS2, terminalSetup, terminalSetup_default; -var init_terminalSetup2 = __esm(() => { - init_env(); - NATIVE_CSIU_TERMINALS2 = { - ghostty: "Ghostty", - kitty: "Kitty", - "iTerm.app": "iTerm2", - WezTerm: "WezTerm" - }; - terminalSetup = { - type: "local-jsx", - name: "terminal-setup", - description: env2.terminal === "Apple_Terminal" ? "Enable Option+Enter key binding for newlines and visual bell" : "Install Shift+Enter key binding for newlines", - isHidden: env2.terminal !== null && env2.terminal in NATIVE_CSIU_TERMINALS2, - load: () => Promise.resolve().then(() => (init_terminalSetup(), exports_terminalSetup)) - }; - terminalSetup_default = terminalSetup; -}); - -// src/commands/usage/usage.tsx -var exports_usage = {}; -__export(exports_usage, { - call: () => call37 -}); -var jsx_dev_runtime289, call37 = async (onDone, context7) => { - return /* @__PURE__ */ jsx_dev_runtime289.jsxDEV(Settings, { - onClose: onDone, - context: context7, - defaultTab: "Usage" - }, undefined, false, undefined, this); -}; -var init_usage2 = __esm(() => { - init_Settings(); - jsx_dev_runtime289 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/usage/index.ts -var usage_default; -var init_usage3 = __esm(() => { - usage_default = { - type: "local-jsx", - name: "usage", - description: "Show plan usage limits", - availability: ["claude-ai"], - load: () => Promise.resolve().then(() => (init_usage2(), exports_usage)) - }; -}); - -// src/commands/theme/theme.tsx -var exports_theme = {}; -__export(exports_theme, { - call: () => call38 -}); -function ThemePickerCommand(t0) { - const $2 = import_compiler_runtime228.c(8); - const { - onDone - } = t0; - const [, setTheme] = useTheme(); - let t1; - if ($2[0] !== onDone || $2[1] !== setTheme) { - t1 = (setting) => { - setTheme(setting); - onDone(`Theme set to ${setting}`); - }; - $2[0] = onDone; - $2[1] = setTheme; - $2[2] = t1; - } else { - t1 = $2[2]; - } - let t22; - if ($2[3] !== onDone) { - t22 = () => { - onDone("Theme picker dismissed", { - display: "system" - }); - }; - $2[3] = onDone; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] !== t1 || $2[6] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime290.jsxDEV(Pane, { - color: "permission", - children: /* @__PURE__ */ jsx_dev_runtime290.jsxDEV(ThemePicker, { - onThemeSelect: t1, - onCancel: t22, - skipExitHandling: true - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[5] = t1; - $2[6] = t22; - $2[7] = t32; - } else { - t32 = $2[7]; - } - return t32; -} -var import_compiler_runtime228, jsx_dev_runtime290, call38 = async (onDone, _context) => { - return /* @__PURE__ */ jsx_dev_runtime290.jsxDEV(ThemePickerCommand, { - onDone - }, undefined, false, undefined, this); -}; -var init_theme3 = __esm(() => { - init_Pane(); - init_ThemePicker(); - init_ink2(); - import_compiler_runtime228 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime290 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/theme/index.ts -var theme, theme_default; -var init_theme4 = __esm(() => { - theme = { - type: "local-jsx", - name: "theme", - description: "Change the theme", - load: () => Promise.resolve().then(() => (init_theme3(), exports_theme)) - }; - theme_default = theme; -}); - -// src/commands/vim/vim.ts -var exports_vim = {}; -__export(exports_vim, { - call: () => call39 -}); -var call39 = async () => { - const config10 = getGlobalConfig(); - let currentMode = config10.editorMode || "normal"; - if (currentMode === "emacs") { - currentMode = "normal"; - } - const newMode = currentMode === "normal" ? "vim" : "normal"; - saveGlobalConfig((current) => ({ - ...current, - editorMode: newMode - })); - logEvent("tengu_editor_mode_changed", { - mode: newMode, - source: "command" - }); - return { - type: "text", - value: `Editor mode set to ${newMode}. ${newMode === "vim" ? "Use Escape key to toggle between INSERT and NORMAL modes." : "Using standard (readline) keyboard bindings."}` - }; -}; -var init_vim = __esm(() => { - init_analytics(); - init_config(); -}); - -// src/commands/vim/index.ts -var command16, vim_default; -var init_vim2 = __esm(() => { - command16 = { - name: "vim", - description: "Toggle between Vim and Normal editing modes", - supportsNonInteractive: false, - type: "local", - load: () => Promise.resolve().then(() => (init_vim(), exports_vim)) - }; - vim_default = command16; -}); - -// src/commands/thinkback/thinkback.tsx -var exports_thinkback = {}; -__export(exports_thinkback, { - playAnimation: () => playAnimation, - call: () => call40 -}); -import { readFile as readFile48 } from "fs/promises"; -import { join as join127 } from "path"; -function getMarketplaceName() { - return OFFICIAL_MARKETPLACE_NAME; -} -function getMarketplaceRepo() { - return OFFICIAL_MARKETPLACE_REPO; -} -function getPluginId() { - return `thinkback@${getMarketplaceName()}`; -} -async function getThinkbackSkillDir() { - const { - enabled: enabled2 - } = await loadAllPlugins(); - const thinkbackPlugin = enabled2.find((p4) => p4.name === "thinkback" || p4.source && p4.source.includes(getPluginId())); - if (!thinkbackPlugin) { - return null; - } - const skillDir = join127(thinkbackPlugin.path, "skills", SKILL_NAME); - if (await pathExists(skillDir)) { - return skillDir; - } - return null; -} -async function playAnimation(skillDir) { - const dataPath = join127(skillDir, "year_in_review.js"); - const playerPath = join127(skillDir, "player.js"); - try { - await readFile48(dataPath); - } catch (e4) { - if (isENOENT(e4)) { - return { - success: false, - message: "No animation found. Run /think-back first to generate one." - }; - } - logError2(e4); - return { - success: false, - message: `Could not access animation data: ${toError(e4).message}` - }; - } - try { - await readFile48(playerPath); - } catch (e4) { - if (isENOENT(e4)) { - return { - success: false, - message: "Player script not found. The player.js file is missing from the thinkback skill." - }; - } - logError2(e4); - return { - success: false, - message: `Could not access player script: ${toError(e4).message}` - }; - } - const inkInstance = instances_default.get(process.stdout); - if (!inkInstance) { - return { - success: false, - message: "Failed to access terminal instance" - }; - } - inkInstance.enterAlternateScreen(); - try { - await execa("node", [playerPath], { - stdio: "inherit", - cwd: skillDir, - reject: false - }); - } catch {} finally { - inkInstance.exitAlternateScreen(); - } - const htmlPath = join127(skillDir, "year_in_review.html"); - if (await pathExists(htmlPath)) { - const platform6 = getPlatform(); - const openCmd = platform6 === "macos" ? "open" : platform6 === "windows" ? "start" : "xdg-open"; - execFileNoThrow(openCmd, [htmlPath]); - } - return { - success: true, - message: "Year in review animation complete!" - }; -} -function ThinkbackInstaller({ - onReady, - onError -}) { - const [state3, setState] = import_react166.useState({ - phase: "checking" - }); - const [progressMessage, setProgressMessage] = import_react166.useState(""); - import_react166.useEffect(() => { - async function checkAndInstall() { - try { - const knownMarketplaces = await loadKnownMarketplacesConfig(); - const marketplaceName = getMarketplaceName(); - const marketplaceRepo = getMarketplaceRepo(); - const pluginId = getPluginId(); - const marketplaceInstalled = marketplaceName in knownMarketplaces; - const pluginAlreadyInstalled = isPluginInstalled(pluginId); - if (!marketplaceInstalled) { - setState({ - phase: "installing-marketplace" - }); - logForDebugging(`Installing marketplace ${marketplaceRepo}`); - await addMarketplaceSource({ - source: "github", - repo: marketplaceRepo - }, (message) => { - setProgressMessage(message); - }); - clearAllCaches(); - logForDebugging(`Marketplace ${marketplaceName} installed`); - } else if (!pluginAlreadyInstalled) { - setState({ - phase: "installing-marketplace" - }); - setProgressMessage("Updating marketplace\u2026"); - logForDebugging(`Refreshing marketplace ${marketplaceName}`); - await refreshMarketplace(marketplaceName, (message_0) => { - setProgressMessage(message_0); - }); - clearMarketplacesCache(); - clearAllCaches(); - logForDebugging(`Marketplace ${marketplaceName} refreshed`); - } - if (!pluginAlreadyInstalled) { - setState({ - phase: "installing-plugin" - }); - logForDebugging(`Installing plugin ${pluginId}`); - const result = await installSelectedPlugins([pluginId]); - if (result.failed.length > 0) { - const errorMsg = result.failed.map((f4) => `${f4.name}: ${f4.error}`).join(", "); - throw new Error(`Failed to install plugin: ${errorMsg}`); - } - clearAllCaches(); - logForDebugging(`Plugin ${pluginId} installed`); - } else { - const { - disabled - } = await loadAllPlugins(); - const isDisabled = disabled.some((p4) => p4.name === "thinkback" || p4.source?.includes(pluginId)); - if (isDisabled) { - setState({ - phase: "enabling-plugin" - }); - logForDebugging(`Enabling plugin ${pluginId}`); - const enableResult = await enablePluginOp(pluginId); - if (!enableResult.success) { - throw new Error(`Failed to enable plugin: ${enableResult.message}`); - } - clearAllCaches(); - logForDebugging(`Plugin ${pluginId} enabled`); - } - } - setState({ - phase: "ready" - }); - onReady(); - } catch (error46) { - const err2 = toError(error46); - logError2(err2); - setState({ - phase: "error", - message: err2.message - }); - onError(err2.message); - } - } - checkAndInstall(); - }, [onReady, onError]); - if (state3.phase === "error") { - return /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - color: "error", - children: [ - "Error: ", - state3.message - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - } - if (state3.phase === "ready") { - return null; - } - const statusMessage = state3.phase === "checking" ? "Checking thinkback installation\u2026" : state3.phase === "installing-marketplace" ? "Installing marketplace\u2026" : state3.phase === "enabling-plugin" ? "Enabling thinkback plugin\u2026" : "Installing thinkback plugin\u2026"; - return /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - children: progressMessage || statusMessage - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -function ThinkbackMenu(t0) { - const $2 = import_compiler_runtime229.c(19); - const { - onDone, - onAction, - skillDir, - hasGenerated - } = t0; - const [hasSelected, setHasSelected] = import_react166.useState(false); - let t1; - if ($2[0] !== hasGenerated) { - t1 = hasGenerated ? [{ - label: "Play animation", - value: "play", - description: "Watch your year in review" - }, { - label: "Edit content", - value: "edit", - description: "Modify the animation" - }, { - label: "Fix errors", - value: "fix", - description: "Fix validation or rendering issues" - }, { - label: "Regenerate", - value: "regenerate", - description: "Create a new animation from scratch" - }] : [{ - label: "Let's go!", - value: "regenerate", - description: "Generate your personalized animation" - }]; - $2[0] = hasGenerated; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const options2 = t1; - let t22; - if ($2[2] !== onAction || $2[3] !== onDone || $2[4] !== skillDir) { - t22 = function handleSelect2(value) { - setHasSelected(true); - if (value === "play") { - playAnimation(skillDir).then(() => { - onDone(undefined, { - display: "skip" - }); - }); - } else { - onAction(value); - } - }; - $2[2] = onAction; - $2[3] = onDone; - $2[4] = skillDir; - $2[5] = t22; - } else { - t22 = $2[5]; - } - const handleSelect = t22; - let t32; - if ($2[6] !== onDone) { - t32 = function handleCancel2() { - onDone(undefined, { - display: "skip" - }); - }; - $2[6] = onDone; - $2[7] = t32; - } else { - t32 = $2[7]; - } - const handleCancel = t32; - if (hasSelected) { - return null; - } - let t4; - if ($2[8] !== hasGenerated) { - t4 = !hasGenerated && /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - children: "Relive your year of coding with Claude." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - dimColor: true, - children: "We'll create a personalized ASCII animation celebrating your journey." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[8] = hasGenerated; - $2[9] = t4; - } else { - t4 = $2[9]; - } - let t5; - if ($2[10] !== handleSelect || $2[11] !== options2) { - t5 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - visibleOptionCount: 5 - }, undefined, false, undefined, this); - $2[10] = handleSelect; - $2[11] = options2; - $2[12] = t5; - } else { - t5 = $2[12]; - } - let t6; - if ($2[13] !== t4 || $2[14] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[13] = t4; - $2[14] = t5; - $2[15] = t6; - } else { - t6 = $2[15]; - } - let t7; - if ($2[16] !== handleCancel || $2[17] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(Dialog, { - title: "Think Back on 2025 with Claude Code", - subtitle: "Generate your 2025 Claude Code Think Back (takes a few minutes to run)", - onCancel: handleCancel, - color: "claude", - children: t6 - }, undefined, false, undefined, this); - $2[16] = handleCancel; - $2[17] = t6; - $2[18] = t7; - } else { - t7 = $2[18]; - } - return t7; -} -function ThinkbackFlow(t0) { - const $2 = import_compiler_runtime229.c(27); - const { - onDone - } = t0; - const [installComplete, setInstallComplete] = import_react166.useState(false); - const [installError, setInstallError] = import_react166.useState(null); - const [skillDir, setSkillDir] = import_react166.useState(null); - const [hasGenerated, setHasGenerated] = import_react166.useState(null); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = function handleReady2() { - setInstallComplete(true); - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const handleReady = t1; - let t22; - if ($2[1] !== onDone) { - t22 = (message) => { - setInstallError(message); - onDone(`Error with thinkback: ${message}. Try running /plugin to manually install the think-back plugin.`, { - display: "system" - }); - }; - $2[1] = onDone; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const handleError = t22; - let t32; - let t4; - if ($2[3] !== handleError || $2[4] !== installComplete || $2[5] !== installError || $2[6] !== skillDir) { - t32 = () => { - if (installComplete && !skillDir && !installError) { - getThinkbackSkillDir().then((dir) => { - if (dir) { - logForDebugging(`Thinkback skill directory: ${dir}`); - setSkillDir(dir); - } else { - handleError("Could not find thinkback skill directory"); - } - }); - } - }; - t4 = [installComplete, skillDir, installError, handleError]; - $2[3] = handleError; - $2[4] = installComplete; - $2[5] = installError; - $2[6] = skillDir; - $2[7] = t32; - $2[8] = t4; - } else { - t32 = $2[7]; - t4 = $2[8]; - } - import_react166.useEffect(t32, t4); - let t5; - let t6; - if ($2[9] !== skillDir) { - t5 = () => { - if (!skillDir) { - return; - } - const dataPath = join127(skillDir, "year_in_review.js"); - pathExists(dataPath).then((exists) => { - logForDebugging(`Checking for ${dataPath}: ${exists ? "found" : "not found"}`); - setHasGenerated(exists); - }); - }; - t6 = [skillDir]; - $2[9] = skillDir; - $2[10] = t5; - $2[11] = t6; - } else { - t5 = $2[10]; - t6 = $2[11]; - } - import_react166.useEffect(t5, t6); - let t7; - if ($2[12] !== onDone) { - t7 = function handleAction2(action2) { - const prompts = { - edit: EDIT_PROMPT, - fix: FIX_PROMPT, - regenerate: REGENERATE_PROMPT - }; - onDone(prompts[action2], { - display: "user", - shouldQuery: true - }); - }; - $2[12] = onDone; - $2[13] = t7; - } else { - t7 = $2[13]; - } - const handleAction = t7; - if (installError) { - let t82; - if ($2[14] !== installError) { - t82 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - color: "error", - children: [ - "Error: ", - installError - ] - }, undefined, true, undefined, this); - $2[14] = installError; - $2[15] = t82; - } else { - t82 = $2[15]; - } - let t9; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t9 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - dimColor: true, - children: "Try running /plugin to manually install the think-back plugin." - }, undefined, false, undefined, this); - $2[16] = t9; - } else { - t9 = $2[16]; - } - let t10; - if ($2[17] !== t82) { - t10 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t82, - t9 - ] - }, undefined, true, undefined, this); - $2[17] = t82; - $2[18] = t10; - } else { - t10 = $2[18]; - } - return t10; - } - if (!installComplete) { - let t82; - if ($2[19] !== handleError) { - t82 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThinkbackInstaller, { - onReady: handleReady, - onError: handleError - }, undefined, false, undefined, this); - $2[19] = handleError; - $2[20] = t82; - } else { - t82 = $2[20]; - } - return t82; - } - if (!skillDir || hasGenerated === null) { - let t82; - if ($2[21] === Symbol.for("react.memo_cache_sentinel")) { - t82 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThemedText, { - children: "Loading thinkback skill\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[21] = t82; - } else { - t82 = $2[21]; - } - return t82; - } - let t8; - if ($2[22] !== handleAction || $2[23] !== hasGenerated || $2[24] !== onDone || $2[25] !== skillDir) { - t8 = /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThinkbackMenu, { - onDone, - onAction: handleAction, - skillDir, - hasGenerated - }, undefined, false, undefined, this); - $2[22] = handleAction; - $2[23] = hasGenerated; - $2[24] = onDone; - $2[25] = skillDir; - $2[26] = t8; - } else { - t8 = $2[26]; - } - return t8; -} -async function call40(onDone) { - return /* @__PURE__ */ jsx_dev_runtime291.jsxDEV(ThinkbackFlow, { - onDone - }, undefined, false, undefined, this); -} -var import_compiler_runtime229, import_react166, jsx_dev_runtime291, OFFICIAL_MARKETPLACE_REPO = "anthropics/claude-plugins-official", SKILL_NAME = "thinkback", EDIT_PROMPT = 'Use the Skill tool to invoke the "thinkback" skill with mode=edit to modify my existing Claude Code year in review animation. Ask me what I want to change. When the animation is ready, tell the user to run /think-back again to play it.', FIX_PROMPT = 'Use the Skill tool to invoke the "thinkback" skill with mode=fix to fix validation or rendering errors in my existing Claude Code year in review animation. Run the validator, identify errors, and fix them. When the animation is ready, tell the user to run /think-back again to play it.', REGENERATE_PROMPT = 'Use the Skill tool to invoke the "thinkback" skill with mode=regenerate to create a completely new Claude Code year in review animation from scratch. Delete the existing animation and start fresh. When the animation is ready, tell the user to run /think-back again to play it.'; -var init_thinkback = __esm(() => { - init_execa(); - init_select(); - init_Dialog(); - init_Spinner2(); - init_instances(); - init_ink2(); - init_pluginOperations(); - init_debug(); - init_errors(); - init_execFileNoThrow(); - init_file(); - init_log2(); - init_platform2(); - init_cacheUtils(); - init_installedPluginsManager(); - init_marketplaceManager(); - init_officialMarketplace(); - init_pluginLoader(); - init_pluginStartupCheck(); - import_compiler_runtime229 = __toESM(require_compiler_runtime(), 1); - import_react166 = __toESM(require_react(), 1); - jsx_dev_runtime291 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/thinkback/index.ts -var thinkback, thinkback_default; -var init_thinkback2 = __esm(() => { - init_growthbook(); - thinkback = { - type: "local-jsx", - name: "think-back", - description: "Your 2025 Claude Code Year in Review", - isEnabled: () => checkStatsigFeatureGate_CACHED_MAY_BE_STALE("tengu_thinkback"), - load: () => Promise.resolve().then(() => (init_thinkback(), exports_thinkback)) - }; - thinkback_default = thinkback; -}); - -// src/commands/thinkback-play/thinkback-play.ts -var exports_thinkback_play = {}; -__export(exports_thinkback_play, { - call: () => call41 -}); -import { join as join128 } from "path"; -function getPluginId2() { - const marketplaceName = process.env.USER_TYPE === "ant" ? INTERNAL_MARKETPLACE_NAME : OFFICIAL_MARKETPLACE_NAME; - return `thinkback@${marketplaceName}`; -} -async function call41() { - const v2Data = loadInstalledPluginsV2(); - const pluginId = getPluginId2(); - const installations = v2Data.plugins[pluginId]; - if (!installations || installations.length === 0) { - return { - type: "text", - value: "Thinkback plugin not installed. Run /think-back first to install it." - }; - } - const firstInstall = installations[0]; - if (!firstInstall?.installPath) { - return { - type: "text", - value: "Thinkback plugin installation path not found." - }; - } - const skillDir = join128(firstInstall.installPath, "skills", SKILL_NAME2); - const result = await playAnimation(skillDir); - return { type: "text", value: result.message }; -} -var INTERNAL_MARKETPLACE_NAME = "claude-code-marketplace", SKILL_NAME2 = "thinkback"; -var init_thinkback_play = __esm(() => { - init_installedPluginsManager(); - init_officialMarketplace(); - init_thinkback(); -}); - -// src/commands/thinkback-play/index.ts -var thinkbackPlay, thinkback_play_default; -var init_thinkback_play2 = __esm(() => { - init_growthbook(); - thinkbackPlay = { - type: "local", - name: "thinkback-play", - description: "Play the thinkback animation", - isEnabled: () => checkStatsigFeatureGate_CACHED_MAY_BE_STALE("tengu_thinkback"), - isHidden: true, - supportsNonInteractive: false, - load: () => Promise.resolve().then(() => (init_thinkback_play(), exports_thinkback_play)) - }; - thinkback_play_default = thinkbackPlay; -}); - -// src/utils/autoModeDenials.ts -function getAutoModeDenials() { - return DENIALS; -} -var DENIALS; -var init_autoModeDenials = __esm(() => { - DENIALS = []; -}); - -// src/components/permissions/rules/PermissionRuleDescription.tsx -function PermissionRuleDescription(t0) { - const $2 = import_compiler_runtime230.c(9); - const { - ruleValue - } = t0; - switch (ruleValue.toolName) { - case BashTool.name: { - if (ruleValue.ruleContent) { - if (ruleValue.ruleContent.endsWith(":*")) { - let t1; - if ($2[0] !== ruleValue.ruleContent) { - t1 = ruleValue.ruleContent.slice(0, -2); - $2[0] = ruleValue.ruleContent; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Any Bash command starting with", - " ", - /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - bold: true, - children: t1 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = t1; - $2[3] = t22; - } else { - t22 = $2[3]; - } - return t22; - } else { - let t1; - if ($2[4] !== ruleValue.ruleContent) { - t1 = /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "The Bash command ", - /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - bold: true, - children: ruleValue.ruleContent - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[4] = ruleValue.ruleContent; - $2[5] = t1; - } else { - t1 = $2[5]; - } - return t1; - } - } else { - let t1; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - dimColor: true, - children: "Any Bash command" - }, undefined, false, undefined, this); - $2[6] = t1; - } else { - t1 = $2[6]; - } - return t1; - } - } - default: { - if (!ruleValue.ruleContent) { - let t1; - if ($2[7] !== ruleValue.toolName) { - t1 = /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Any use of the ", - /* @__PURE__ */ jsx_dev_runtime292.jsxDEV(ThemedText, { - bold: true, - children: ruleValue.toolName - }, undefined, false, undefined, this), - " tool" - ] - }, undefined, true, undefined, this); - $2[7] = ruleValue.toolName; - $2[8] = t1; - } else { - t1 = $2[8]; - } - return t1; - } else { - return null; - } - } - } -} -var import_compiler_runtime230, jsx_dev_runtime292; -var init_PermissionRuleDescription = __esm(() => { - init_ink2(); - init_BashTool(); - import_compiler_runtime230 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime292 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/rules/AddPermissionRules.tsx -function optionForPermissionSaveDestination(saveDestination) { - switch (saveDestination) { - case "localSettings": - return { - label: "Project settings (local)", - description: `Saved in ${getRelativeSettingsFilePathForSource("localSettings")}`, - value: saveDestination - }; - case "projectSettings": - return { - label: "Project settings", - description: `Checked in at ${getRelativeSettingsFilePathForSource("projectSettings")}`, - value: saveDestination - }; - case "userSettings": - return { - label: "User settings", - description: `Saved in at ~/.claude/settings.json`, - value: saveDestination - }; - } -} -function AddPermissionRules(t0) { - const $2 = import_compiler_runtime231.c(26); - const { - onAddRules, - onCancel, - ruleValues, - ruleBehavior, - initialContext, - setToolPermissionContext - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = SOURCES.map(optionForPermissionSaveDestination); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const allOptions = t1; - let t22; - if ($2[1] !== initialContext || $2[2] !== onAddRules || $2[3] !== onCancel || $2[4] !== ruleBehavior || $2[5] !== ruleValues || $2[6] !== setToolPermissionContext) { - t22 = (selectedValue) => { - if (selectedValue === "cancel") { - onCancel(); - return; - } else { - if (SOURCES.includes(selectedValue)) { - const destination = selectedValue; - const updatedContext = applyPermissionUpdate(initialContext, { - type: "addRules", - rules: ruleValues, - behavior: ruleBehavior, - destination - }); - persistPermissionUpdate({ - type: "addRules", - rules: ruleValues, - behavior: ruleBehavior, - destination - }); - setToolPermissionContext(updatedContext); - const rules2 = ruleValues.map((ruleValue) => ({ - ruleValue, - ruleBehavior, - source: destination - })); - const sandboxAutoAllowEnabled = SandboxManager.isSandboxingEnabled() && SandboxManager.isAutoAllowBashIfSandboxedEnabled(); - const allUnreachable = detectUnreachableRules(updatedContext, { - sandboxAutoAllowEnabled - }); - const newUnreachable = allUnreachable.filter((u5) => ruleValues.some((rv) => rv.toolName === u5.rule.ruleValue.toolName && rv.ruleContent === u5.rule.ruleValue.ruleContent)); - onAddRules(rules2, newUnreachable.length > 0 ? newUnreachable : undefined); - } - } - }; - $2[1] = initialContext; - $2[2] = onAddRules; - $2[3] = onCancel; - $2[4] = ruleBehavior; - $2[5] = ruleValues; - $2[6] = setToolPermissionContext; - $2[7] = t22; - } else { - t22 = $2[7]; - } - const onSelect = t22; - let t32; - if ($2[8] !== ruleValues.length) { - t32 = plural(ruleValues.length, "rule"); - $2[8] = ruleValues.length; - $2[9] = t32; - } else { - t32 = $2[9]; - } - const title = `Add ${ruleBehavior} permission ${t32}`; - let t4; - if ($2[10] !== ruleValues) { - t4 = ruleValues.map(_temp138); - $2[10] = ruleValues; - $2[11] = t4; - } else { - t4 = $2[11]; - } - let t5; - if ($2[12] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - children: t4 - }, undefined, false, undefined, this); - $2[12] = t4; - $2[13] = t5; - } else { - t5 = $2[13]; - } - const t6 = ruleValues.length === 1 ? "Where should this rule be saved?" : "Where should these rules be saved?"; - let t7; - if ($2[14] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(ThemedText, { - children: t6 - }, undefined, false, undefined, this); - $2[14] = t6; - $2[15] = t7; - } else { - t7 = $2[15]; - } - let t8; - if ($2[16] !== onSelect) { - t8 = /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(Select, { - options: allOptions, - onChange: onSelect - }, undefined, false, undefined, this); - $2[16] = onSelect; - $2[17] = t8; - } else { - t8 = $2[17]; - } - let t9; - if ($2[18] !== t7 || $2[19] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginY: 1, - children: [ - t7, - t8 - ] - }, undefined, true, undefined, this); - $2[18] = t7; - $2[19] = t8; - $2[20] = t9; - } else { - t9 = $2[20]; - } - let t10; - if ($2[21] !== onCancel || $2[22] !== t5 || $2[23] !== t9 || $2[24] !== title) { - t10 = /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(Dialog, { - title, - onCancel, - color: "permission", - children: [ - t5, - t9 - ] - }, undefined, true, undefined, this); - $2[21] = onCancel; - $2[22] = t5; - $2[23] = t9; - $2[24] = title; - $2[25] = t10; - } else { - t10 = $2[25]; - } - return t10; -} -function _temp138(ruleValue_0) { - return /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(ThemedText, { - bold: true, - children: permissionRuleValueToString(ruleValue_0) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime293.jsxDEV(PermissionRuleDescription, { - ruleValue: ruleValue_0 - }, undefined, false, undefined, this) - ] - }, permissionRuleValueToString(ruleValue_0), true, undefined, this); -} -var import_compiler_runtime231, jsx_dev_runtime293; -var init_AddPermissionRules = __esm(() => { - init_select(); - init_ink2(); - init_PermissionUpdate(); - init_permissionRuleParser(); - init_shadowedRuleDetection(); - init_sandbox_adapter(); - init_constants2(); - init_settings2(); - init_stringUtils(); - init_Dialog(); - init_PermissionRuleDescription(); - import_compiler_runtime231 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime293 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/rules/PermissionRuleInput.tsx -function PermissionRuleInput(t0) { - const $2 = import_compiler_runtime232.c(24); - const { - onCancel, - onSubmit, - ruleBehavior - } = t0; - const [inputValue, setInputValue] = import_react167.useState(""); - const [cursorOffset, setCursorOffset] = import_react167.useState(0); - const exitState = useExitOnCtrlCDWithKeybindings(); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - context: "Settings" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - useKeybinding("confirm:no", onCancel, t1); - const { - columns - } = useTerminalSize(); - const textInputColumns = columns - 6; - let t22; - if ($2[1] !== onSubmit || $2[2] !== ruleBehavior) { - t22 = (value) => { - const trimmedValue = value.trim(); - if (trimmedValue.length === 0) { - return; - } - const ruleValue = permissionRuleValueFromString(trimmedValue); - onSubmit(ruleValue, ruleBehavior); - }; - $2[1] = onSubmit; - $2[2] = ruleBehavior; - $2[3] = t22; - } else { - t22 = $2[3]; - } - const handleSubmit = t22; - let t32; - if ($2[4] !== ruleBehavior) { - t32 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: [ - "Add ", - ruleBehavior, - " permission rule" - ] - }, undefined, true, undefined, this); - $2[4] = ruleBehavior; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(Newline, {}, undefined, false, undefined, this); - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - let t6; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - bold: true, - children: permissionRuleValueToString({ - toolName: WebFetchTool.name - }) - }, undefined, false, undefined, this); - t6 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - bold: false, - children: " or " - }, undefined, false, undefined, this); - $2[7] = t5; - $2[8] = t6; - } else { - t5 = $2[7]; - t6 = $2[8]; - } - let t7; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - children: [ - "Permission rules are a tool name, optionally followed by a specifier in parentheses.", - t4, - "e.g.,", - " ", - t5, - t6, - /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - bold: true, - children: permissionRuleValueToString({ - toolName: BashTool.name, - ruleContent: "ls:*" - }) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[9] = t7; - } else { - t7 = $2[9]; - } - let t8; - if ($2[10] !== cursorOffset || $2[11] !== handleSubmit || $2[12] !== inputValue || $2[13] !== textInputColumns) { - t8 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t7, - /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedBox_default, { - borderDimColor: true, - borderStyle: "round", - marginY: 1, - paddingLeft: 1, - children: /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(TextInput, { - showCursor: true, - value: inputValue, - onChange: setInputValue, - onSubmit: handleSubmit, - placeholder: `Enter permission rule${figures_default.ellipsis}`, - columns: textInputColumns, - cursorOffset, - onChangeCursorOffset: setCursorOffset - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[10] = cursorOffset; - $2[11] = handleSubmit; - $2[12] = inputValue; - $2[13] = textInputColumns; - $2[14] = t8; - } else { - t8 = $2[14]; - } - let t9; - if ($2[15] !== t32 || $2[16] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - borderStyle: "round", - paddingLeft: 1, - paddingRight: 1, - borderColor: "permission", - children: [ - t32, - t8 - ] - }, undefined, true, undefined, this); - $2[15] = t32; - $2[16] = t8; - $2[17] = t9; - } else { - t9 = $2[17]; - } - let t10; - if ($2[18] !== exitState.keyName || $2[19] !== exitState.pending) { - t10 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedBox_default, { - marginLeft: 3, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(ThemedText, { - dimColor: true, - children: "Enter to submit \xB7 Esc to cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[18] = exitState.keyName; - $2[19] = exitState.pending; - $2[20] = t10; - } else { - t10 = $2[20]; - } - let t11; - if ($2[21] !== t10 || $2[22] !== t9) { - t11 = /* @__PURE__ */ jsx_dev_runtime294.jsxDEV(jsx_dev_runtime294.Fragment, { - children: [ - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[21] = t10; - $2[22] = t9; - $2[23] = t11; - } else { - t11 = $2[23]; - } - return t11; -} -var import_compiler_runtime232, import_react167, jsx_dev_runtime294; -var init_PermissionRuleInput = __esm(() => { - init_figures(); - init_TextInput(); - init_useExitOnCtrlCDWithKeybindings(); - init_useTerminalSize(); - init_ink2(); - init_useKeybinding(); - init_BashTool(); - init_WebFetchTool(); - init_permissionRuleParser(); - import_compiler_runtime232 = __toESM(require_compiler_runtime(), 1); - import_react167 = __toESM(require_react(), 1); - jsx_dev_runtime294 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/rules/RecentDenialsTab.tsx -function RecentDenialsTab(t0) { - const $2 = import_compiler_runtime233.c(30); - const { - onHeaderFocusChange, - onStateChange - } = t0; - const { - headerFocused, - focusHeader - } = useTabHeaderFocus(); - let t1; - let t22; - if ($2[0] !== headerFocused || $2[1] !== onHeaderFocusChange) { - t1 = () => { - onHeaderFocusChange?.(headerFocused); - }; - t22 = [headerFocused, onHeaderFocusChange]; - $2[0] = headerFocused; - $2[1] = onHeaderFocusChange; - $2[2] = t1; - $2[3] = t22; - } else { - t1 = $2[2]; - t22 = $2[3]; - } - import_react168.useEffect(t1, t22); - const [denials] = import_react168.useState(_temp139); - const [approved, setApproved] = import_react168.useState(_temp256); - const [retry8, setRetry] = import_react168.useState(_temp334); - const [focusedIdx, setFocusedIdx] = import_react168.useState(0); - let t32; - let t4; - if ($2[4] !== approved || $2[5] !== denials || $2[6] !== onStateChange || $2[7] !== retry8) { - t32 = () => { - onStateChange({ - approved, - retry: retry8, - denials - }); - }; - t4 = [approved, retry8, denials, onStateChange]; - $2[4] = approved; - $2[5] = denials; - $2[6] = onStateChange; - $2[7] = retry8; - $2[8] = t32; - $2[9] = t4; - } else { - t32 = $2[8]; - t4 = $2[9]; - } - import_react168.useEffect(t32, t4); - let t5; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t5 = (value) => { - const idx = Number(value); - setApproved((prev) => { - const next2 = new Set(prev); - if (next2.has(idx)) { - next2.delete(idx); - } else { - next2.add(idx); - } - return next2; - }); - }; - $2[10] = t5; - } else { - t5 = $2[10]; - } - const handleSelect = t5; - let t6; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t6 = (value_0) => { - setFocusedIdx(Number(value_0)); - }; - $2[11] = t6; - } else { - t6 = $2[11]; - } - const handleFocus = t6; - let t7; - if ($2[12] !== focusedIdx) { - t7 = (input, _key) => { - if (input === "r") { - setRetry((prev_0) => { - const next_0 = new Set(prev_0); - if (next_0.has(focusedIdx)) { - next_0.delete(focusedIdx); - } else { - next_0.add(focusedIdx); - } - return next_0; - }); - setApproved((prev_1) => { - if (prev_1.has(focusedIdx)) { - return prev_1; - } - const next_1 = new Set(prev_1); - next_1.add(focusedIdx); - return next_1; - }); - } - }; - $2[12] = focusedIdx; - $2[13] = t7; - } else { - t7 = $2[13]; - } - const t8 = denials.length > 0; - let t9; - if ($2[14] !== t8) { - t9 = { - isActive: t8 - }; - $2[14] = t8; - $2[15] = t9; - } else { - t9 = $2[15]; - } - use_input_default(t7, t9); - if (denials.length === 0) { - let t102; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t102 = /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(ThemedText, { - dimColor: true, - children: "No recent denials. Commands denied by the auto mode classifier will appear here." - }, undefined, false, undefined, this); - $2[16] = t102; - } else { - t102 = $2[16]; - } - return t102; - } - let t10; - if ($2[17] !== approved || $2[18] !== denials || $2[19] !== retry8) { - let t112; - if ($2[21] !== approved || $2[22] !== retry8) { - t112 = (d4, idx_0) => { - const isApproved = approved.has(idx_0); - const suffix = retry8.has(idx_0) ? " (retry)" : ""; - return { - label: /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(StatusIcon, { - status: isApproved ? "success" : "error", - withSpace: true - }, undefined, false, undefined, this), - d4.display, - /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(ThemedText, { - dimColor: true, - children: suffix - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: String(idx_0) - }; - }; - $2[21] = approved; - $2[22] = retry8; - $2[23] = t112; - } else { - t112 = $2[23]; - } - t10 = denials.map(t112); - $2[17] = approved; - $2[18] = denials; - $2[19] = retry8; - $2[20] = t10; - } else { - t10 = $2[20]; - } - const options2 = t10; - let t11; - if ($2[24] === Symbol.for("react.memo_cache_sentinel")) { - t11 = /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(ThemedText, { - children: "Commands recently denied by the auto mode classifier." - }, undefined, false, undefined, this); - $2[24] = t11; - } else { - t11 = $2[24]; - } - const t12 = Math.min(10, options2.length); - let t13; - if ($2[25] !== focusHeader || $2[26] !== headerFocused || $2[27] !== options2 || $2[28] !== t12) { - t13 = /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t11, - /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime295.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - onFocus: handleFocus, - visibleOptionCount: t12, - isDisabled: headerFocused, - onUpFromFirstItem: focusHeader - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[25] = focusHeader; - $2[26] = headerFocused; - $2[27] = options2; - $2[28] = t12; - $2[29] = t13; - } else { - t13 = $2[29]; - } - return t13; -} -function _temp334() { - return new Set; -} -function _temp256() { - return new Set; -} -function _temp139() { - return getAutoModeDenials(); -} -var import_compiler_runtime233, import_react168, jsx_dev_runtime295; -var init_RecentDenialsTab = __esm(() => { - init_ink2(); - init_autoModeDenials(); - init_select(); - init_StatusIcon(); - init_Tabs(); - import_compiler_runtime233 = __toESM(require_compiler_runtime(), 1); - import_react168 = __toESM(require_react(), 1); - jsx_dev_runtime295 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/rules/RemoveWorkspaceDirectory.tsx -function RemoveWorkspaceDirectory(t0) { - const $2 = import_compiler_runtime234.c(19); - const { - directoryPath, - onRemove, - onCancel, - permissionContext, - setPermissionContext - } = t0; - let t1; - if ($2[0] !== directoryPath || $2[1] !== onRemove || $2[2] !== permissionContext || $2[3] !== setPermissionContext) { - t1 = () => { - const updatedContext = applyPermissionUpdate(permissionContext, { - type: "removeDirectories", - directories: [directoryPath], - destination: "session" - }); - setPermissionContext(updatedContext); - onRemove(); - }; - $2[0] = directoryPath; - $2[1] = onRemove; - $2[2] = permissionContext; - $2[3] = setPermissionContext; - $2[4] = t1; - } else { - t1 = $2[4]; - } - const handleRemove = t1; - let t22; - if ($2[5] !== handleRemove || $2[6] !== onCancel) { - t22 = (value) => { - if (value === "yes") { - handleRemove(); - } else { - onCancel(); - } - }; - $2[5] = handleRemove; - $2[6] = onCancel; - $2[7] = t22; - } else { - t22 = $2[7]; - } - const handleSelect = t22; - let t32; - if ($2[8] !== directoryPath) { - t32 = /* @__PURE__ */ jsx_dev_runtime296.jsxDEV(ThemedBox_default, { - marginX: 2, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime296.jsxDEV(ThemedText, { - bold: true, - children: directoryPath - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[8] = directoryPath; - $2[9] = t32; - } else { - t32 = $2[9]; - } - let t4; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime296.jsxDEV(ThemedText, { - children: "Claude Code will no longer have access to files in this directory." - }, undefined, false, undefined, this); - $2[10] = t4; - } else { - t4 = $2[10]; - } - let t5; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t5 = [{ - label: "Yes", - value: "yes" - }, { - label: "No", - value: "no" - }]; - $2[11] = t5; - } else { - t5 = $2[11]; - } - let t6; - if ($2[12] !== handleSelect || $2[13] !== onCancel) { - t6 = /* @__PURE__ */ jsx_dev_runtime296.jsxDEV(Select, { - onChange: handleSelect, - onCancel, - options: t5 - }, undefined, false, undefined, this); - $2[12] = handleSelect; - $2[13] = onCancel; - $2[14] = t6; - } else { - t6 = $2[14]; - } - let t7; - if ($2[15] !== onCancel || $2[16] !== t32 || $2[17] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime296.jsxDEV(Dialog, { - title: "Remove directory from workspace?", - onCancel, - color: "error", - children: [ - t32, - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[15] = onCancel; - $2[16] = t32; - $2[17] = t6; - $2[18] = t7; - } else { - t7 = $2[18]; - } - return t7; -} -var import_compiler_runtime234, jsx_dev_runtime296; -var init_RemoveWorkspaceDirectory = __esm(() => { - init_select(); - init_ink2(); - init_PermissionUpdate(); - init_Dialog(); - import_compiler_runtime234 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime296 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/rules/WorkspaceTab.tsx -function WorkspaceTab(t0) { - const $2 = import_compiler_runtime235.c(23); - const { - onExit: onExit2, - toolPermissionContext, - onRequestAddDirectory, - onRequestRemoveDirectory, - onHeaderFocusChange - } = t0; - const { - headerFocused, - focusHeader - } = useTabHeaderFocus(); - let t1; - let t22; - if ($2[0] !== headerFocused || $2[1] !== onHeaderFocusChange) { - t1 = () => { - onHeaderFocusChange?.(headerFocused); - }; - t22 = [headerFocused, onHeaderFocusChange]; - $2[0] = headerFocused; - $2[1] = onHeaderFocusChange; - $2[2] = t1; - $2[3] = t22; - } else { - t1 = $2[2]; - t22 = $2[3]; - } - import_react169.useEffect(t1, t22); - let t32; - if ($2[4] !== toolPermissionContext.additionalWorkingDirectories) { - t32 = Array.from(toolPermissionContext.additionalWorkingDirectories.keys()).map(_temp140); - $2[4] = toolPermissionContext.additionalWorkingDirectories; - $2[5] = t32; - } else { - t32 = $2[5]; - } - const additionalDirectories = t32; - let t4; - if ($2[6] !== additionalDirectories || $2[7] !== onRequestAddDirectory || $2[8] !== onRequestRemoveDirectory) { - t4 = (selectedValue) => { - if (selectedValue === "add-directory") { - onRequestAddDirectory(); - return; - } - const directory = additionalDirectories.find((d4) => d4.path === selectedValue); - if (directory && directory.isDeletable) { - onRequestRemoveDirectory(directory.path); - } - }; - $2[6] = additionalDirectories; - $2[7] = onRequestAddDirectory; - $2[8] = onRequestRemoveDirectory; - $2[9] = t4; - } else { - t4 = $2[9]; - } - const handleDirectorySelect = t4; - let t5; - if ($2[10] !== onExit2) { - t5 = () => onExit2("Workspace dialog dismissed", { - display: "system" - }); - $2[10] = onExit2; - $2[11] = t5; - } else { - t5 = $2[11]; - } - const handleCancel = t5; - let opts; - if ($2[12] !== additionalDirectories) { - opts = additionalDirectories.map(_temp257); - let t62; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t62 = { - label: `Add directory${figures_default.ellipsis}`, - value: "add-directory" - }; - $2[14] = t62; - } else { - t62 = $2[14]; - } - opts.push(t62); - $2[12] = additionalDirectories; - $2[13] = opts; - } else { - opts = $2[13]; - } - const options2 = opts; - let t6; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime297.jsxDEV(ThemedBox_default, { - flexDirection: "row", - marginTop: 1, - marginLeft: 2, - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime297.jsxDEV(ThemedText, { - children: `- ${getOriginalCwd()}` - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime297.jsxDEV(ThemedText, { - dimColor: true, - children: "(Original working directory)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[15] = t6; - } else { - t6 = $2[15]; - } - const t7 = Math.min(10, options2.length); - let t8; - if ($2[16] !== focusHeader || $2[17] !== handleCancel || $2[18] !== handleDirectorySelect || $2[19] !== headerFocused || $2[20] !== options2 || $2[21] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime297.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: [ - t6, - /* @__PURE__ */ jsx_dev_runtime297.jsxDEV(Select, { - options: options2, - onChange: handleDirectorySelect, - onCancel: handleCancel, - visibleOptionCount: t7, - onUpFromFirstItem: focusHeader, - isDisabled: headerFocused - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[16] = focusHeader; - $2[17] = handleCancel; - $2[18] = handleDirectorySelect; - $2[19] = headerFocused; - $2[20] = options2; - $2[21] = t7; - $2[22] = t8; - } else { - t8 = $2[22]; - } - return t8; -} -function _temp257(dir) { - return { - label: dir.path, - value: dir.path - }; -} -function _temp140(path25) { - return { - path: path25, - isCurrent: false, - isDeletable: true - }; -} -var import_compiler_runtime235, import_react169, jsx_dev_runtime297; -var init_WorkspaceTab = __esm(() => { - init_figures(); - init_state(); - init_select(); - init_ink2(); - init_Tabs(); - import_compiler_runtime235 = __toESM(require_compiler_runtime(), 1); - import_react169 = __toESM(require_react(), 1); - jsx_dev_runtime297 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/rules/PermissionRuleList.tsx -function RuleSourceText(t0) { - const $2 = import_compiler_runtime236.c(4); - const { - rule - } = t0; - let t1; - if ($2[0] !== rule.source) { - t1 = permissionRuleSourceDisplayString(rule.source); - $2[0] = rule.source; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const t22 = `From ${t1}`; - let t32; - if ($2[2] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - dimColor: true, - children: t22 - }, undefined, false, undefined, this); - $2[2] = t22; - $2[3] = t32; - } else { - t32 = $2[3]; - } - return t32; -} -function getRuleBehaviorLabel(ruleBehavior) { - switch (ruleBehavior) { - case "allow": - return "allowed"; - case "deny": - return "denied"; - case "ask": - return "ask"; - } -} -function RuleDetails(t0) { - const $2 = import_compiler_runtime236.c(42); - const { - rule, - onDelete, - onCancel - } = t0; - const exitState = useExitOnCtrlCDWithKeybindings(); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - context: "Confirmation" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - useKeybinding("confirm:no", onCancel, t1); - let t22; - if ($2[1] !== rule.ruleValue) { - t22 = permissionRuleValueToString(rule.ruleValue); - $2[1] = rule.ruleValue; - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - bold: true, - children: t22 - }, undefined, false, undefined, this); - $2[3] = t22; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== rule.ruleValue) { - t4 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(PermissionRuleDescription, { - ruleValue: rule.ruleValue - }, undefined, false, undefined, this); - $2[5] = rule.ruleValue; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== rule) { - t5 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(RuleSourceText, { - rule - }, undefined, false, undefined, this); - $2[7] = rule; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== t32 || $2[10] !== t4 || $2[11] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginX: 2, - children: [ - t32, - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[9] = t32; - $2[10] = t4; - $2[11] = t5; - $2[12] = t6; - } else { - t6 = $2[12]; - } - const ruleDescription = t6; - let t7; - if ($2[13] !== exitState.keyName || $2[14] !== exitState.pending) { - t7 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - marginLeft: 3, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - dimColor: true, - children: "Esc to cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[13] = exitState.keyName; - $2[14] = exitState.pending; - $2[15] = t7; - } else { - t7 = $2[15]; - } - const footer = t7; - if (rule.source === "policySettings") { - let t82; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t82 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: "Rule details" - }, undefined, false, undefined, this); - $2[16] = t82; - } else { - t82 = $2[16]; - } - let t92; - if ($2[17] === Symbol.for("react.memo_cache_sentinel")) { - t92 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - italic: true, - children: [ - "This rule is configured by managed settings and cannot be modified.", - ` -`, - "Contact your system administrator for more information." - ] - }, undefined, true, undefined, this); - $2[17] = t92; - } else { - t92 = $2[17]; - } - let t102; - if ($2[18] !== ruleDescription) { - t102 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - borderStyle: "round", - paddingLeft: 1, - paddingRight: 1, - borderColor: "permission", - children: [ - t82, - ruleDescription, - t92 - ] - }, undefined, true, undefined, this); - $2[18] = ruleDescription; - $2[19] = t102; - } else { - t102 = $2[19]; - } - let t112; - if ($2[20] !== footer || $2[21] !== t102) { - t112 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: [ - t102, - footer - ] - }, undefined, true, undefined, this); - $2[20] = footer; - $2[21] = t102; - $2[22] = t112; - } else { - t112 = $2[22]; - } - return t112; - } - let t8; - if ($2[23] !== rule.ruleBehavior) { - t8 = getRuleBehaviorLabel(rule.ruleBehavior); - $2[23] = rule.ruleBehavior; - $2[24] = t8; - } else { - t8 = $2[24]; - } - let t9; - if ($2[25] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - bold: true, - color: "error", - children: [ - "Delete ", - t8, - " tool?" - ] - }, undefined, true, undefined, this); - $2[25] = t8; - $2[26] = t9; - } else { - t9 = $2[26]; - } - let t10; - if ($2[27] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - children: "Are you sure you want to delete this permission rule?" - }, undefined, false, undefined, this); - $2[27] = t10; - } else { - t10 = $2[27]; - } - let t11; - if ($2[28] !== onCancel || $2[29] !== onDelete) { - t11 = (_) => _ === "yes" ? onDelete() : onCancel(); - $2[28] = onCancel; - $2[29] = onDelete; - $2[30] = t11; - } else { - t11 = $2[30]; - } - let t12; - if ($2[31] === Symbol.for("react.memo_cache_sentinel")) { - t12 = [{ - label: "Yes", - value: "yes" - }, { - label: "No", - value: "no" - }]; - $2[31] = t12; - } else { - t12 = $2[31]; - } - let t13; - if ($2[32] !== onCancel || $2[33] !== t11) { - t13 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Select, { - onChange: t11, - onCancel, - options: t12 - }, undefined, false, undefined, this); - $2[32] = onCancel; - $2[33] = t11; - $2[34] = t13; - } else { - t13 = $2[34]; - } - let t14; - if ($2[35] !== ruleDescription || $2[36] !== t13 || $2[37] !== t9) { - t14 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - borderStyle: "round", - paddingLeft: 1, - paddingRight: 1, - borderColor: "error", - children: [ - t9, - ruleDescription, - t10, - t13 - ] - }, undefined, true, undefined, this); - $2[35] = ruleDescription; - $2[36] = t13; - $2[37] = t9; - $2[38] = t14; - } else { - t14 = $2[38]; - } - let t15; - if ($2[39] !== footer || $2[40] !== t14) { - t15 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: [ - t14, - footer - ] - }, undefined, true, undefined, this); - $2[39] = footer; - $2[40] = t14; - $2[41] = t15; - } else { - t15 = $2[41]; - } - return t15; -} -function RulesTabContent(props) { - const $2 = import_compiler_runtime236.c(26); - const { - options: options2, - searchQuery, - isSearchMode, - isFocused, - onSelect, - onCancel, - lastFocusedRuleKey, - cursorOffset, - onHeaderFocusChange - } = props; - const tabWidth = useTabsWidth(); - const { - headerFocused, - focusHeader, - blurHeader - } = useTabHeaderFocus(); - let t0; - let t1; - if ($2[0] !== blurHeader || $2[1] !== headerFocused || $2[2] !== isSearchMode) { - t0 = () => { - if (isSearchMode && headerFocused) { - blurHeader(); - } - }; - t1 = [isSearchMode, headerFocused, blurHeader]; - $2[0] = blurHeader; - $2[1] = headerFocused; - $2[2] = isSearchMode; - $2[3] = t0; - $2[4] = t1; - } else { - t0 = $2[3]; - t1 = $2[4]; - } - import_react170.useEffect(t0, t1); - let t22; - let t32; - if ($2[5] !== headerFocused || $2[6] !== onHeaderFocusChange) { - t22 = () => { - onHeaderFocusChange?.(headerFocused); - }; - t32 = [headerFocused, onHeaderFocusChange]; - $2[5] = headerFocused; - $2[6] = onHeaderFocusChange; - $2[7] = t22; - $2[8] = t32; - } else { - t22 = $2[7]; - t32 = $2[8]; - } - import_react170.useEffect(t22, t32); - const t4 = isSearchMode && !headerFocused; - let t5; - if ($2[9] !== cursorOffset || $2[10] !== isFocused || $2[11] !== searchQuery || $2[12] !== t4 || $2[13] !== tabWidth) { - t5 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(SearchBox, { - query: searchQuery, - isFocused: t4, - isTerminalFocused: isFocused, - width: tabWidth, - cursorOffset - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[9] = cursorOffset; - $2[10] = isFocused; - $2[11] = searchQuery; - $2[12] = t4; - $2[13] = tabWidth; - $2[14] = t5; - } else { - t5 = $2[14]; - } - const t6 = Math.min(10, options2.length); - const t7 = isSearchMode || headerFocused; - let t8; - if ($2[15] !== focusHeader || $2[16] !== lastFocusedRuleKey || $2[17] !== onCancel || $2[18] !== onSelect || $2[19] !== options2 || $2[20] !== t6 || $2[21] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Select, { - options: options2, - onChange: onSelect, - onCancel, - visibleOptionCount: t6, - isDisabled: t7, - defaultFocusValue: lastFocusedRuleKey, - onUpFromFirstItem: focusHeader - }, undefined, false, undefined, this); - $2[15] = focusHeader; - $2[16] = lastFocusedRuleKey; - $2[17] = onCancel; - $2[18] = onSelect; - $2[19] = options2; - $2[20] = t6; - $2[21] = t7; - $2[22] = t8; - } else { - t8 = $2[22]; - } - let t9; - if ($2[23] !== t5 || $2[24] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t5, - t8 - ] - }, undefined, true, undefined, this); - $2[23] = t5; - $2[24] = t8; - $2[25] = t9; - } else { - t9 = $2[25]; - } - return t9; -} -function PermissionRulesTab(t0) { - const $2 = import_compiler_runtime236.c(27); - let T0; - let T1; - let handleToolSelect; - let rulesProps; - let t1; - let t22; - let t32; - let t4; - let tab; - if ($2[0] !== t0) { - const { - tab: t52, - getRulesOptions, - handleToolSelect: t62, - ...t72 - } = t0; - tab = t52; - handleToolSelect = t62; - rulesProps = t72; - T1 = ThemedBox_default; - t22 = "column"; - t32 = tab === "allow" ? 0 : undefined; - let t8; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t8 = { - allow: "Claude Code won't ask before using allowed tools.", - ask: "Claude Code will always ask for confirmation before using these tools.", - deny: "Claude Code will always reject requests to use denied tools." - }; - $2[10] = t8; - } else { - t8 = $2[10]; - } - const t9 = t8[tab]; - if ($2[11] !== t9) { - t4 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - children: t9 - }, undefined, false, undefined, this); - $2[11] = t9; - $2[12] = t4; - } else { - t4 = $2[12]; - } - T0 = RulesTabContent; - t1 = getRulesOptions(tab, rulesProps.searchQuery); - $2[0] = t0; - $2[1] = T0; - $2[2] = T1; - $2[3] = handleToolSelect; - $2[4] = rulesProps; - $2[5] = t1; - $2[6] = t22; - $2[7] = t32; - $2[8] = t4; - $2[9] = tab; - } else { - T0 = $2[1]; - T1 = $2[2]; - handleToolSelect = $2[3]; - rulesProps = $2[4]; - t1 = $2[5]; - t22 = $2[6]; - t32 = $2[7]; - t4 = $2[8]; - tab = $2[9]; - } - let t5; - if ($2[13] !== handleToolSelect || $2[14] !== tab) { - t5 = (v6) => handleToolSelect(v6, tab); - $2[13] = handleToolSelect; - $2[14] = tab; - $2[15] = t5; - } else { - t5 = $2[15]; - } - let t6; - if ($2[16] !== T0 || $2[17] !== rulesProps || $2[18] !== t1.options || $2[19] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(T0, { - options: t1.options, - onSelect: t5, - ...rulesProps - }, undefined, false, undefined, this); - $2[16] = T0; - $2[17] = rulesProps; - $2[18] = t1.options; - $2[19] = t5; - $2[20] = t6; - } else { - t6 = $2[20]; - } - let t7; - if ($2[21] !== T1 || $2[22] !== t22 || $2[23] !== t32 || $2[24] !== t4 || $2[25] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(T1, { - flexDirection: t22, - flexShrink: t32, - children: [ - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[21] = T1; - $2[22] = t22; - $2[23] = t32; - $2[24] = t4; - $2[25] = t6; - $2[26] = t7; - } else { - t7 = $2[26]; - } - return t7; -} -function PermissionRuleList(t0) { - const $2 = import_compiler_runtime236.c(113); - const { - onExit: onExit2, - initialTab, - onRetryDenials - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getAutoModeDenials(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const hasDenials = t1.length > 0; - const defaultTab = initialTab ?? (hasDenials ? "recent" : "allow"); - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = []; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const [changes, setChanges] = import_react170.useState(t22); - const toolPermissionContext = useAppState(_temp141); - const setAppState = useSetAppState(); - const isTerminalFocused = useTerminalFocus(); - let t32; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t32 = { - approved: new Set, - retry: new Set, - denials: [] - }; - $2[2] = t32; - } else { - t32 = $2[2]; - } - const denialStateRef = import_react170.useRef(t32); - let t4; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t4 = (s_0) => { - denialStateRef.current = s_0; - }; - $2[3] = t4; - } else { - t4 = $2[3]; - } - const handleDenialStateChange = t4; - const [selectedRule, setSelectedRule] = import_react170.useState(); - const [lastFocusedRuleKey, setLastFocusedRuleKey] = import_react170.useState(); - const [addingRuleToTab, setAddingRuleToTab] = import_react170.useState(null); - const [validatedRule, setValidatedRule] = import_react170.useState(null); - const [isAddingWorkspaceDirectory, setIsAddingWorkspaceDirectory] = import_react170.useState(false); - const [removingDirectory, setRemovingDirectory] = import_react170.useState(null); - const [isSearchMode, setIsSearchMode] = import_react170.useState(false); - const [headerFocused, setHeaderFocused] = import_react170.useState(true); - let t5; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t5 = (focused) => { - setHeaderFocused(focused); - }; - $2[4] = t5; - } else { - t5 = $2[4]; - } - const handleHeaderFocusChange = t5; - let map8; - if ($2[5] !== toolPermissionContext) { - map8 = new Map; - getAllowRules(toolPermissionContext).forEach((rule) => { - map8.set(jsonStringify(rule), rule); - }); - $2[5] = toolPermissionContext; - $2[6] = map8; - } else { - map8 = $2[6]; - } - const allowRulesByKey = map8; - let map_0; - if ($2[7] !== toolPermissionContext) { - map_0 = new Map; - getDenyRules(toolPermissionContext).forEach((rule_0) => { - map_0.set(jsonStringify(rule_0), rule_0); - }); - $2[7] = toolPermissionContext; - $2[8] = map_0; - } else { - map_0 = $2[8]; - } - const denyRulesByKey = map_0; - let map_1; - if ($2[9] !== toolPermissionContext) { - map_1 = new Map; - getAskRules(toolPermissionContext).forEach((rule_1) => { - map_1.set(jsonStringify(rule_1), rule_1); - }); - $2[9] = toolPermissionContext; - $2[10] = map_1; - } else { - map_1 = $2[10]; - } - const askRulesByKey = map_1; - let t6; - if ($2[11] !== allowRulesByKey || $2[12] !== askRulesByKey || $2[13] !== denyRulesByKey) { - t6 = (tab, t72) => { - const query2 = t72 === undefined ? "" : t72; - const rulesByKey = (() => { - switch (tab) { - case "allow": { - return allowRulesByKey; - } - case "deny": { - return denyRulesByKey; - } - case "ask": { - return askRulesByKey; - } - case "workspace": - case "recent": { - return new Map; - } - } - })(); - const options2 = []; - if (tab !== "workspace" && tab !== "recent" && !query2) { - options2.push({ - label: `Add a new rule${figures_default.ellipsis}`, - value: "add-new-rule" - }); - } - const sortedRuleKeys = Array.from(rulesByKey.keys()).sort((a5, b5) => { - const ruleA = rulesByKey.get(a5); - const ruleB = rulesByKey.get(b5); - if (ruleA && ruleB) { - const ruleAString = permissionRuleValueToString(ruleA.ruleValue).toLowerCase(); - const ruleBString = permissionRuleValueToString(ruleB.ruleValue).toLowerCase(); - return ruleAString.localeCompare(ruleBString); - } - return 0; - }); - const lowerQuery = query2.toLowerCase(); - for (const ruleKey of sortedRuleKeys) { - const rule_2 = rulesByKey.get(ruleKey); - if (rule_2) { - const ruleString = permissionRuleValueToString(rule_2.ruleValue); - if (query2 && !ruleString.toLowerCase().includes(lowerQuery)) { - continue; - } - options2.push({ - label: ruleString, - value: ruleKey - }); - } - } - return { - options: options2, - rulesByKey - }; - }; - $2[11] = allowRulesByKey; - $2[12] = askRulesByKey; - $2[13] = denyRulesByKey; - $2[14] = t6; - } else { - t6 = $2[14]; - } - const getRulesOptions = t6; - const exitState = useExitOnCtrlCDWithKeybindings(); - const isSearchModeActive = !selectedRule && !addingRuleToTab && !validatedRule && !isAddingWorkspaceDirectory && !removingDirectory; - const t7 = isSearchModeActive && isSearchMode; - let t8; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t8 = () => { - setIsSearchMode(false); - }; - $2[15] = t8; - } else { - t8 = $2[15]; - } - let t9; - if ($2[16] !== t7) { - t9 = { - isActive: t7, - onExit: t8 - }; - $2[16] = t7; - $2[17] = t9; - } else { - t9 = $2[17]; - } - const { - query: searchQuery, - setQuery: setSearchQuery, - cursorOffset: searchCursorOffset - } = useSearchInput(t9); - let t10; - if ($2[18] !== isSearchMode || $2[19] !== isSearchModeActive || $2[20] !== setSearchQuery) { - t10 = (e4) => { - if (!isSearchModeActive) { - return; - } - if (isSearchMode) { - return; - } - if (e4.ctrl || e4.meta) { - return; - } - if (e4.key === "/") { - e4.preventDefault(); - setIsSearchMode(true); - setSearchQuery(""); - } else { - if (e4.key.length === 1 && e4.key !== "j" && e4.key !== "k" && e4.key !== "m" && e4.key !== "i" && e4.key !== "r" && e4.key !== " ") { - e4.preventDefault(); - setIsSearchMode(true); - setSearchQuery(e4.key); - } - } - }; - $2[18] = isSearchMode; - $2[19] = isSearchModeActive; - $2[20] = setSearchQuery; - $2[21] = t10; - } else { - t10 = $2[21]; - } - const handleKeyDown = t10; - let t11; - if ($2[22] !== getRulesOptions) { - t11 = (selectedValue, tab_0) => { - const { - rulesByKey: rulesByKey_0 - } = getRulesOptions(tab_0); - if (selectedValue === "add-new-rule") { - setAddingRuleToTab(tab_0); - return; - } else { - setSelectedRule(rulesByKey_0.get(selectedValue)); - return; - } - }; - $2[22] = getRulesOptions; - $2[23] = t11; - } else { - t11 = $2[23]; - } - const handleToolSelect = t11; - let t12; - if ($2[24] === Symbol.for("react.memo_cache_sentinel")) { - t12 = () => { - setAddingRuleToTab(null); - }; - $2[24] = t12; - } else { - t12 = $2[24]; - } - const handleRuleInputCancel = t12; - let t13; - if ($2[25] === Symbol.for("react.memo_cache_sentinel")) { - t13 = (ruleValue, ruleBehavior) => { - setValidatedRule({ - ruleValue, - ruleBehavior - }); - setAddingRuleToTab(null); - }; - $2[25] = t13; - } else { - t13 = $2[25]; - } - const handleRuleInputSubmit = t13; - let t14; - if ($2[26] === Symbol.for("react.memo_cache_sentinel")) { - t14 = (rules2, unreachable) => { - setValidatedRule(null); - for (const rule_3 of rules2) { - setChanges((prev) => [...prev, `Added ${rule_3.ruleBehavior} rule ${source_default.bold(permissionRuleValueToString(rule_3.ruleValue))}`]); - } - if (unreachable && unreachable.length > 0) { - for (const u5 of unreachable) { - const severity = u5.shadowType === "deny" ? "blocked" : "shadowed"; - setChanges((prev_0) => [...prev_0, source_default.yellow(`${figures_default.warning} Warning: ${permissionRuleValueToString(u5.rule.ruleValue)} is ${severity}`), source_default.dim(` ${u5.reason}`), source_default.dim(` Fix: ${u5.fix}`)]); - } - } - }; - $2[26] = t14; - } else { - t14 = $2[26]; - } - const handleAddRulesSuccess = t14; - let t15; - if ($2[27] === Symbol.for("react.memo_cache_sentinel")) { - t15 = () => { - setValidatedRule(null); - }; - $2[27] = t15; - } else { - t15 = $2[27]; - } - const handleAddRuleCancel = t15; - let t16; - if ($2[28] === Symbol.for("react.memo_cache_sentinel")) { - t16 = () => setIsAddingWorkspaceDirectory(true); - $2[28] = t16; - } else { - t16 = $2[28]; - } - const handleRequestAddDirectory = t16; - let t17; - if ($2[29] === Symbol.for("react.memo_cache_sentinel")) { - t17 = (path25) => setRemovingDirectory(path25); - $2[29] = t17; - } else { - t17 = $2[29]; - } - const handleRequestRemoveDirectory = t17; - let t18; - if ($2[30] !== changes || $2[31] !== onExit2 || $2[32] !== onRetryDenials) { - t18 = () => { - const s_1 = denialStateRef.current; - const denialsFor = (set3) => Array.from(set3).map((idx) => s_1.denials[idx]).filter(_temp258); - const retryDenials = denialsFor(s_1.retry); - if (retryDenials.length > 0) { - const commands7 = retryDenials.map(_temp335); - onRetryDenials?.(commands7); - onExit2(undefined, { - shouldQuery: true, - metaMessages: [`Permission granted for: ${commands7.join(", ")}. You may now retry ${commands7.length === 1 ? "this command" : "these commands"} if you would like.`] - }); - return; - } - const approvedDenials = denialsFor(s_1.approved); - if (approvedDenials.length > 0 || changes.length > 0) { - const approvedMsg = approvedDenials.length > 0 ? [`Approved ${approvedDenials.map(_temp426).join(", ")}`] : []; - onExit2([...approvedMsg, ...changes].join(` -`)); - } else { - onExit2("Permissions dialog dismissed", { - display: "system" - }); - } - }; - $2[30] = changes; - $2[31] = onExit2; - $2[32] = onRetryDenials; - $2[33] = t18; - } else { - t18 = $2[33]; - } - const handleRulesCancel = t18; - const t19 = isSearchModeActive && !isSearchMode; - let t20; - if ($2[34] !== t19) { - t20 = { - context: "Settings", - isActive: t19 - }; - $2[34] = t19; - $2[35] = t20; - } else { - t20 = $2[35]; - } - useKeybinding("confirm:no", handleRulesCancel, t20); - let t21; - if ($2[36] !== getRulesOptions || $2[37] !== selectedRule || $2[38] !== setAppState || $2[39] !== toolPermissionContext) { - t21 = () => { - if (!selectedRule) { - return; - } - const { - options: options_0 - } = getRulesOptions(selectedRule.ruleBehavior); - const selectedKey = jsonStringify(selectedRule); - const ruleKeys = options_0.filter(_temp519).map(_temp616); - const currentIndex = ruleKeys.indexOf(selectedKey); - let nextFocusKey; - if (currentIndex !== -1) { - if (currentIndex < ruleKeys.length - 1) { - nextFocusKey = ruleKeys[currentIndex + 1]; - } else { - if (currentIndex > 0) { - nextFocusKey = ruleKeys[currentIndex - 1]; - } - } - } - setLastFocusedRuleKey(nextFocusKey); - deletePermissionRule({ - rule: selectedRule, - initialContext: toolPermissionContext, - setToolPermissionContext(toolPermissionContext_0) { - setAppState((prev_1) => ({ - ...prev_1, - toolPermissionContext: toolPermissionContext_0 - })); - } - }); - setChanges((prev_2) => [...prev_2, `Deleted ${selectedRule.ruleBehavior} rule ${source_default.bold(permissionRuleValueToString(selectedRule.ruleValue))}`]); - setSelectedRule(undefined); - }; - $2[36] = getRulesOptions; - $2[37] = selectedRule; - $2[38] = setAppState; - $2[39] = toolPermissionContext; - $2[40] = t21; - } else { - t21 = $2[40]; - } - const handleDeleteRule = t21; - if (selectedRule) { - let t223; - if ($2[41] === Symbol.for("react.memo_cache_sentinel")) { - t223 = () => setSelectedRule(undefined); - $2[41] = t223; - } else { - t223 = $2[41]; - } - let t232; - if ($2[42] !== handleDeleteRule || $2[43] !== selectedRule) { - t232 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(RuleDetails, { - rule: selectedRule, - onDelete: handleDeleteRule, - onCancel: t223 - }, undefined, false, undefined, this); - $2[42] = handleDeleteRule; - $2[43] = selectedRule; - $2[44] = t232; - } else { - t232 = $2[44]; - } - return t232; - } - if (addingRuleToTab && addingRuleToTab !== "workspace" && addingRuleToTab !== "recent") { - let t223; - if ($2[45] !== addingRuleToTab) { - t223 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(PermissionRuleInput, { - onCancel: handleRuleInputCancel, - onSubmit: handleRuleInputSubmit, - ruleBehavior: addingRuleToTab - }, undefined, false, undefined, this); - $2[45] = addingRuleToTab; - $2[46] = t223; - } else { - t223 = $2[46]; - } - return t223; - } - if (validatedRule) { - let t223; - if ($2[47] !== validatedRule.ruleValue) { - t223 = [validatedRule.ruleValue]; - $2[47] = validatedRule.ruleValue; - $2[48] = t223; - } else { - t223 = $2[48]; - } - let t232; - if ($2[49] !== setAppState) { - t232 = (toolPermissionContext_1) => { - setAppState((prev_3) => ({ - ...prev_3, - toolPermissionContext: toolPermissionContext_1 - })); - }; - $2[49] = setAppState; - $2[50] = t232; - } else { - t232 = $2[50]; - } - let t242; - if ($2[51] !== t223 || $2[52] !== t232 || $2[53] !== toolPermissionContext || $2[54] !== validatedRule.ruleBehavior) { - t242 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(AddPermissionRules, { - onAddRules: handleAddRulesSuccess, - onCancel: handleAddRuleCancel, - ruleValues: t223, - ruleBehavior: validatedRule.ruleBehavior, - initialContext: toolPermissionContext, - setToolPermissionContext: t232 - }, undefined, false, undefined, this); - $2[51] = t223; - $2[52] = t232; - $2[53] = toolPermissionContext; - $2[54] = validatedRule.ruleBehavior; - $2[55] = t242; - } else { - t242 = $2[55]; - } - return t242; - } - if (isAddingWorkspaceDirectory) { - let t223; - if ($2[56] !== setAppState || $2[57] !== toolPermissionContext) { - t223 = (path_0, remember) => { - const destination = remember ? "localSettings" : "session"; - const permissionUpdate = { - type: "addDirectories", - directories: [path_0], - destination - }; - const updatedContext = applyPermissionUpdate(toolPermissionContext, permissionUpdate); - setAppState((prev_4) => ({ - ...prev_4, - toolPermissionContext: updatedContext - })); - if (remember) { - persistPermissionUpdate(permissionUpdate); - } - setChanges((prev_5) => [...prev_5, `Added directory ${source_default.bold(path_0)} to workspace${remember ? " and saved to local settings" : " for this session"}`]); - setIsAddingWorkspaceDirectory(false); - }; - $2[56] = setAppState; - $2[57] = toolPermissionContext; - $2[58] = t223; - } else { - t223 = $2[58]; - } - let t232; - if ($2[59] === Symbol.for("react.memo_cache_sentinel")) { - t232 = () => setIsAddingWorkspaceDirectory(false); - $2[59] = t232; - } else { - t232 = $2[59]; - } - let t242; - if ($2[60] !== t223 || $2[61] !== toolPermissionContext) { - t242 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(AddWorkspaceDirectory, { - onAddDirectory: t223, - onCancel: t232, - permissionContext: toolPermissionContext - }, undefined, false, undefined, this); - $2[60] = t223; - $2[61] = toolPermissionContext; - $2[62] = t242; - } else { - t242 = $2[62]; - } - return t242; - } - if (removingDirectory) { - let t223; - if ($2[63] !== removingDirectory) { - t223 = () => { - setChanges((prev_6) => [...prev_6, `Removed directory ${source_default.bold(removingDirectory)} from workspace`]); - setRemovingDirectory(null); - }; - $2[63] = removingDirectory; - $2[64] = t223; - } else { - t223 = $2[64]; - } - let t232; - if ($2[65] === Symbol.for("react.memo_cache_sentinel")) { - t232 = () => setRemovingDirectory(null); - $2[65] = t232; - } else { - t232 = $2[65]; - } - let t242; - if ($2[66] !== setAppState) { - t242 = (toolPermissionContext_2) => { - setAppState((prev_7) => ({ - ...prev_7, - toolPermissionContext: toolPermissionContext_2 - })); - }; - $2[66] = setAppState; - $2[67] = t242; - } else { - t242 = $2[67]; - } - let t252; - if ($2[68] !== removingDirectory || $2[69] !== t223 || $2[70] !== t242 || $2[71] !== toolPermissionContext) { - t252 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(RemoveWorkspaceDirectory, { - directoryPath: removingDirectory, - onRemove: t223, - onCancel: t232, - permissionContext: toolPermissionContext, - setPermissionContext: t242 - }, undefined, false, undefined, this); - $2[68] = removingDirectory; - $2[69] = t223; - $2[70] = t242; - $2[71] = toolPermissionContext; - $2[72] = t252; - } else { - t252 = $2[72]; - } - return t252; - } - let t222; - if ($2[73] !== getRulesOptions || $2[74] !== handleRulesCancel || $2[75] !== handleToolSelect || $2[76] !== isSearchMode || $2[77] !== isTerminalFocused || $2[78] !== lastFocusedRuleKey || $2[79] !== searchCursorOffset || $2[80] !== searchQuery) { - t222 = { - searchQuery, - isSearchMode, - isFocused: isTerminalFocused, - onCancel: handleRulesCancel, - lastFocusedRuleKey, - cursorOffset: searchCursorOffset, - getRulesOptions, - handleToolSelect, - onHeaderFocusChange: handleHeaderFocusChange - }; - $2[73] = getRulesOptions; - $2[74] = handleRulesCancel; - $2[75] = handleToolSelect; - $2[76] = isSearchMode; - $2[77] = isTerminalFocused; - $2[78] = lastFocusedRuleKey; - $2[79] = searchCursorOffset; - $2[80] = searchQuery; - $2[81] = t222; - } else { - t222 = $2[81]; - } - const sharedRulesProps = t222; - const isHidden = !!selectedRule || !!addingRuleToTab || !!validatedRule || isAddingWorkspaceDirectory || !!removingDirectory; - const t23 = !isSearchMode; - let t24; - if ($2[82] === Symbol.for("react.memo_cache_sentinel")) { - t24 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Tab, { - id: "recent", - title: "Recently denied", - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(RecentDenialsTab, { - onHeaderFocusChange: handleHeaderFocusChange, - onStateChange: handleDenialStateChange - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[82] = t24; - } else { - t24 = $2[82]; - } - let t25; - if ($2[83] !== sharedRulesProps) { - t25 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Tab, { - id: "allow", - title: "Allow", - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(PermissionRulesTab, { - tab: "allow", - ...sharedRulesProps - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[83] = sharedRulesProps; - $2[84] = t25; - } else { - t25 = $2[84]; - } - let t26; - if ($2[85] !== sharedRulesProps) { - t26 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Tab, { - id: "ask", - title: "Ask", - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(PermissionRulesTab, { - tab: "ask", - ...sharedRulesProps - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[85] = sharedRulesProps; - $2[86] = t26; - } else { - t26 = $2[86]; - } - let t27; - if ($2[87] !== sharedRulesProps) { - t27 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Tab, { - id: "deny", - title: "Deny", - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(PermissionRulesTab, { - tab: "deny", - ...sharedRulesProps - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[87] = sharedRulesProps; - $2[88] = t27; - } else { - t27 = $2[88]; - } - let t28; - if ($2[89] === Symbol.for("react.memo_cache_sentinel")) { - t28 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - children: "Claude Code can read files in the workspace, and make edits when auto-accept edits is on." - }, undefined, false, undefined, this); - $2[89] = t28; - } else { - t28 = $2[89]; - } - let t29; - if ($2[90] !== onExit2 || $2[91] !== toolPermissionContext) { - t29 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Tab, { - id: "workspace", - title: "Workspace", - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t28, - /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(WorkspaceTab, { - onExit: onExit2, - toolPermissionContext, - onRequestAddDirectory: handleRequestAddDirectory, - onRequestRemoveDirectory: handleRequestRemoveDirectory, - onHeaderFocusChange: handleHeaderFocusChange - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[90] = onExit2; - $2[91] = toolPermissionContext; - $2[92] = t29; - } else { - t29 = $2[92]; - } - let t30; - if ($2[93] !== defaultTab || $2[94] !== isHidden || $2[95] !== t23 || $2[96] !== t25 || $2[97] !== t26 || $2[98] !== t27 || $2[99] !== t29) { - t30 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Tabs, { - title: "Permissions:", - color: "permission", - defaultTab, - hidden: isHidden, - initialHeaderFocused: !hasDenials, - navFromContent: t23, - children: [ - t24, - t25, - t26, - t27, - t29 - ] - }, undefined, true, undefined, this); - $2[93] = defaultTab; - $2[94] = isHidden; - $2[95] = t23; - $2[96] = t25; - $2[97] = t26; - $2[98] = t27; - $2[99] = t29; - $2[100] = t30; - } else { - t30 = $2[100]; - } - let t31; - if ($2[101] !== defaultTab || $2[102] !== exitState.keyName || $2[103] !== exitState.pending || $2[104] !== headerFocused || $2[105] !== isSearchMode) { - t31 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - marginTop: 1, - paddingLeft: 1, - children: /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedText, { - dimColor: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : headerFocused ? /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: "\u2190/\u2192 tab switch \xB7 \u2193 return \xB7 Esc cancel" - }, undefined, false, undefined, this) : isSearchMode ? /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: "Type to filter \xB7 Enter/\u2193 select \xB7 \u2191 tabs \xB7 Esc clear" - }, undefined, false, undefined, this) : hasDenials && defaultTab === "recent" ? /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: "Enter approve \xB7 r retry \xB7 \u2191\u2193 navigate \xB7 \u2190/\u2192 switch \xB7 Esc cancel" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(jsx_dev_runtime298.Fragment, { - children: "\u2191\u2193 navigate \xB7 Enter select \xB7 Type to search \xB7 \u2190/\u2192 switch \xB7 Esc cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[101] = defaultTab; - $2[102] = exitState.keyName; - $2[103] = exitState.pending; - $2[104] = headerFocused; - $2[105] = isSearchMode; - $2[106] = t31; - } else { - t31 = $2[106]; - } - let t322; - if ($2[107] !== t30 || $2[108] !== t31) { - t322 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(Pane, { - color: "permission", - children: [ - t30, - t31 - ] - }, undefined, true, undefined, this); - $2[107] = t30; - $2[108] = t31; - $2[109] = t322; - } else { - t322 = $2[109]; - } - let t33; - if ($2[110] !== handleKeyDown || $2[111] !== t322) { - t33 = /* @__PURE__ */ jsx_dev_runtime298.jsxDEV(ThemedBox_default, { - flexDirection: "column", - onKeyDown: handleKeyDown, - children: t322 - }, undefined, false, undefined, this); - $2[110] = handleKeyDown; - $2[111] = t322; - $2[112] = t33; - } else { - t33 = $2[112]; - } - return t33; -} -function _temp616(opt_0) { - return opt_0.value; -} -function _temp519(opt) { - return opt.value !== "add-new-rule"; -} -function _temp426(d_1) { - return source_default.bold(d_1.display); -} -function _temp335(d_0) { - return d_0.display; -} -function _temp258(d4) { - return d4 !== undefined; -} -function _temp141(s4) { - return s4.toolPermissionContext; -} -var import_compiler_runtime236, import_react170, jsx_dev_runtime298; -var init_PermissionRuleList = __esm(() => { - init_source(); - init_figures(); - init_AppState(); - init_PermissionUpdate(); - init_select(); - init_useExitOnCtrlCDWithKeybindings(); - init_useSearchInput(); - init_ink2(); - init_useKeybinding(); - init_autoModeDenials(); - init_permissionRuleParser(); - init_permissions2(); - init_slowOperations(); - init_Pane(); - init_Tabs(); - init_SearchBox(); - init_AddPermissionRules(); - init_AddWorkspaceDirectory(); - init_PermissionRuleDescription(); - init_PermissionRuleInput(); - init_RecentDenialsTab(); - init_RemoveWorkspaceDirectory(); - init_WorkspaceTab(); - import_compiler_runtime236 = __toESM(require_compiler_runtime(), 1); - import_react170 = __toESM(require_react(), 1); - jsx_dev_runtime298 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/permissions/permissions.tsx -var exports_permissions = {}; -__export(exports_permissions, { - call: () => call42 -}); -var jsx_dev_runtime299, call42 = async (onDone, context7) => { - return /* @__PURE__ */ jsx_dev_runtime299.jsxDEV(PermissionRuleList, { - onExit: onDone, - onRetryDenials: (commands7) => { - context7.setMessages((prev) => [...prev, createPermissionRetryMessage(commands7)]); - } - }, undefined, false, undefined, this); -}; -var init_permissions3 = __esm(() => { - init_PermissionRuleList(); - init_messages9(); - jsx_dev_runtime299 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/permissions/index.ts -var permissions, permissions_default; -var init_permissions4 = __esm(() => { - permissions = { - type: "local-jsx", - name: "permissions", - aliases: ["allowed-tools"], - description: "Manage allow & deny tool permission rules", - load: () => Promise.resolve().then(() => (init_permissions3(), exports_permissions)) - }; - permissions_default = permissions; -}); - -// src/commands/plan/plan.tsx -var exports_plan = {}; -__export(exports_plan, { - call: () => call43 -}); -function PlanDisplay(t0) { - const $2 = import_compiler_runtime237.c(11); - const { - planContent, - planPath, - editorName - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedText, { - bold: true, - children: "Current Plan" - }, undefined, false, undefined, this); - $2[0] = t1; - } else { - t1 = $2[0]; - } - let t22; - if ($2[1] !== planPath) { - t22 = /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedText, { - dimColor: true, - children: planPath - }, undefined, false, undefined, this); - $2[1] = planPath; - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== planContent) { - t32 = /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedText, { - children: planContent - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[3] = planContent; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== editorName) { - t4 = editorName && /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedText, { - dimColor: true, - children: '"/plan open"' - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedText, { - dimColor: true, - children: " to edit this plan in " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: editorName - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[5] = editorName; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== t22 || $2[8] !== t32 || $2[9] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t1, - t22, - t32, - t4 - ] - }, undefined, true, undefined, this); - $2[7] = t22; - $2[8] = t32; - $2[9] = t4; - $2[10] = t5; - } else { - t5 = $2[10]; - } - return t5; -} -async function call43(onDone, context7, args) { - const { - getAppState, - setAppState - } = context7; - const appState = getAppState(); - const currentMode = appState.toolPermissionContext.mode; - if (currentMode !== "plan") { - handlePlanModeTransition(currentMode, "plan"); - setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdate(prepareContextForPlanMode(prev.toolPermissionContext), { - type: "setMode", - mode: "plan", - destination: "session" - }) - })); - const description = args.trim(); - if (description && description !== "open") { - onDone("Enabled plan mode", { - shouldQuery: true - }); - } else { - onDone("Enabled plan mode"); - } - return null; - } - const planContent = getPlan(); - const planPath = getPlanFilePath(); - if (!planContent) { - onDone("Already in plan mode. No plan written yet."); - return null; - } - const argList = args.trim().split(/\s+/); - if (argList[0] === "open") { - const result = await editFileInEditor(planPath); - if (result.error) { - onDone(`Failed to open plan in editor: ${result.error}`); - } else { - onDone(`Opened plan in editor: ${planPath}`); - } - return null; - } - const editor = getExternalEditor(); - const editorName = editor ? toIDEDisplayName(editor) : undefined; - const display = /* @__PURE__ */ jsx_dev_runtime300.jsxDEV(PlanDisplay, { - planContent, - planPath, - editorName - }, undefined, false, undefined, this); - const output = await renderToString(display); - onDone(output); - return null; -} -var import_compiler_runtime237, jsx_dev_runtime300; -var init_plan = __esm(() => { - init_state(); - init_ink2(); - init_editor(); - init_ide(); - init_PermissionUpdate(); - init_permissionSetup(); - init_plans(); - init_promptEditor(); - init_staticRender(); - import_compiler_runtime237 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime300 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/plan/index.ts -var plan, plan_default; -var init_plan2 = __esm(() => { - plan = { - type: "local-jsx", - name: "plan", - description: "Enable plan mode or view the current session plan", - argumentHint: "[open|]", - load: () => Promise.resolve().then(() => (init_plan(), exports_plan)) - }; - plan_default = plan; -}); - -// src/utils/immediateCommand.ts -function shouldInferenceConfigCommandBeImmediate() { - return process.env.USER_TYPE === "ant" || getFeatureValue_CACHED_MAY_BE_STALE("tengu_immediate_model_command", false); -} -var init_immediateCommand = __esm(() => { - init_growthbook(); -}); - -// src/components/FastIcon.tsx -function FastIcon(t0) { - const $2 = import_compiler_runtime238.c(2); - const { - cooldown - } = t0; - if (cooldown) { - let t12; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime301.jsxDEV(ThemedText, { - color: "promptBorder", - dimColor: true, - children: LIGHTNING_BOLT - }, undefined, false, undefined, this); - $2[0] = t12; - } else { - t12 = $2[0]; - } - return t12; - } - let t1; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime301.jsxDEV(ThemedText, { - color: "fastMode", - children: LIGHTNING_BOLT - }, undefined, false, undefined, this); - $2[1] = t1; - } else { - t1 = $2[1]; - } - return t1; -} -function getFastIconString(applyColor2 = true, cooldown = false) { - if (!applyColor2) { - return LIGHTNING_BOLT; - } - const themeName = resolveThemeSetting(getGlobalConfig().theme); - if (cooldown) { - return source_default.dim(color("promptBorder", themeName)(LIGHTNING_BOLT)); - } - return color("fastMode", themeName)(LIGHTNING_BOLT); -} -var import_compiler_runtime238, jsx_dev_runtime301; -var init_FastIcon = __esm(() => { - init_source(); - init_figures2(); - init_ink2(); - init_config(); - init_color(); - import_compiler_runtime238 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime301 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/fast/fast.tsx -var exports_fast = {}; -__export(exports_fast, { - call: () => call44, - FastModePicker: () => FastModePicker -}); -function applyFastMode(enable2, setAppState) { - clearFastModeCooldown(); - updateSettingsForSource("userSettings", { - fastMode: enable2 ? true : undefined - }); - if (enable2) { - setAppState((prev) => { - const needsModelSwitch = !isFastModeSupportedByModel(prev.mainLoopModel); - return { - ...prev, - ...needsModelSwitch ? { - mainLoopModel: getFastModeModel(), - mainLoopModelForSession: null - } : {}, - fastMode: true - }; - }); - } else { - setAppState((prev) => ({ - ...prev, - fastMode: false - })); - } -} -function FastModePicker(t0) { - const $2 = import_compiler_runtime239.c(30); - const { - onDone, - unavailableReason - } = t0; - const model = useAppState(_temp143); - const initialFastMode = useAppState(_temp259); - const setAppState = useSetAppState(); - const [enableFastMode, setEnableFastMode] = import_react171.useState(initialFastMode ?? false); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getFastModeRuntimeState(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const runtimeState2 = t1; - const isCooldown = runtimeState2.status === "cooldown"; - const isUnavailable = unavailableReason !== null; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = formatModelPricing(getOpus46CostTier(true)); - $2[1] = t22; - } else { - t22 = $2[1]; - } - const pricing = t22; - let t32; - if ($2[2] !== enableFastMode || $2[3] !== isUnavailable || $2[4] !== model || $2[5] !== onDone || $2[6] !== setAppState) { - t32 = function handleConfirm2() { - if (isUnavailable) { - return; - } - applyFastMode(enableFastMode, setAppState); - logEvent("tengu_fast_mode_toggled", { - enabled: enableFastMode, - source: "picker" - }); - if (enableFastMode) { - const fastIcon = getFastIconString(enableFastMode); - const modelUpdated = !isFastModeSupportedByModel(model) ? ` \xB7 model set to ${FAST_MODE_MODEL_DISPLAY}` : ""; - onDone(`${fastIcon} Fast mode ON${modelUpdated} \xB7 ${pricing}`); - } else { - setAppState(_temp336); - onDone("Fast mode OFF"); - } - }; - $2[2] = enableFastMode; - $2[3] = isUnavailable; - $2[4] = model; - $2[5] = onDone; - $2[6] = setAppState; - $2[7] = t32; - } else { - t32 = $2[7]; - } - const handleConfirm = t32; - let t4; - if ($2[8] !== initialFastMode || $2[9] !== isUnavailable || $2[10] !== onDone || $2[11] !== setAppState) { - t4 = function handleCancel2() { - if (isUnavailable) { - if (initialFastMode) { - applyFastMode(false, setAppState); - } - onDone("Fast mode OFF", { - display: "system" - }); - return; - } - const message = initialFastMode ? `${getFastIconString()} Kept Fast mode ON` : "Kept Fast mode OFF"; - onDone(message, { - display: "system" - }); - }; - $2[8] = initialFastMode; - $2[9] = isUnavailable; - $2[10] = onDone; - $2[11] = setAppState; - $2[12] = t4; - } else { - t4 = $2[12]; - } - const handleCancel = t4; - let t5; - if ($2[13] !== isUnavailable) { - t5 = function handleToggle2() { - if (isUnavailable) { - return; - } - setEnableFastMode(_temp427); - }; - $2[13] = isUnavailable; - $2[14] = t5; - } else { - t5 = $2[14]; - } - const handleToggle = t5; - let t6; - if ($2[15] !== handleConfirm || $2[16] !== handleToggle) { - t6 = { - "confirm:yes": handleConfirm, - "confirm:nextField": handleToggle, - "confirm:next": handleToggle, - "confirm:previous": handleToggle, - "confirm:cycleMode": handleToggle, - "confirm:toggle": handleToggle - }; - $2[15] = handleConfirm; - $2[16] = handleToggle; - $2[17] = t6; - } else { - t6 = $2[17]; - } - let t7; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t7 = { - context: "Confirmation" - }; - $2[18] = t7; - } else { - t7 = $2[18]; - } - useKeybindings(t6, t7); - let t8; - if ($2[19] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(FastIcon, { - cooldown: isCooldown - }, undefined, false, undefined, this), - " Fast mode (research preview)" - ] - }, undefined, true, undefined, this); - $2[19] = t8; - } else { - t8 = $2[19]; - } - const title = t8; - let t9; - if ($2[20] !== isUnavailable) { - t9 = (exitState) => exitState.pending ? /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : isUnavailable ? /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - children: "Esc to cancel" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - children: "Tab to toggle \xB7 Enter to confirm \xB7 Esc to cancel" - }, undefined, false, undefined, this); - $2[20] = isUnavailable; - $2[21] = t9; - } else { - t9 = $2[21]; - } - let t10; - if ($2[22] !== enableFastMode || $2[23] !== unavailableReason) { - t10 = unavailableReason ? /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - color: "error", - children: unavailableReason - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(jsx_dev_runtime302.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 0, - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 2, - children: [ - /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - bold: true, - children: "Fast mode" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - color: enableFastMode ? "fastMode" : undefined, - bold: enableFastMode, - children: enableFastMode ? "ON " : "OFF" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - dimColor: true, - children: pricing - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - isCooldown && runtimeState2.status === "cooldown" && /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - color: "warning", - children: [ - runtimeState2.reason === "overloaded" ? "Fast mode overloaded and is temporarily unavailable" : "You've hit your fast limit", - " \xB7 resets in ", - formatDuration(runtimeState2.resetAt - Date.now(), { - hideTrailingZeros: true - }) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[22] = enableFastMode; - $2[23] = unavailableReason; - $2[24] = t10; - } else { - t10 = $2[24]; - } - let t11; - if ($2[25] === Symbol.for("react.memo_cache_sentinel")) { - t11 = /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Learn more:", - " ", - /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/fast-mode", - children: "https://code.claude.com/docs/en/fast-mode" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[25] = t11; - } else { - t11 = $2[25]; - } - let t12; - if ($2[26] !== handleCancel || $2[27] !== t10 || $2[28] !== t9) { - t12 = /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(Dialog, { - title, - subtitle: `High-speed mode for ${FAST_MODE_MODEL_DISPLAY}. Billed as extra usage at a premium rate. Separate rate limits apply.`, - onCancel: handleCancel, - color: "fastMode", - inputGuide: t9, - children: [ - t10, - t11 - ] - }, undefined, true, undefined, this); - $2[26] = handleCancel; - $2[27] = t10; - $2[28] = t9; - $2[29] = t12; - } else { - t12 = $2[29]; - } - return t12; -} -function _temp427(prev_0) { - return !prev_0; -} -function _temp336(prev) { - return { - ...prev, - fastMode: false - }; -} -function _temp259(s_0) { - return s_0.fastMode; -} -function _temp143(s4) { - return s4.mainLoopModel; -} -async function handleFastModeShortcut(enable2, getAppState, setAppState) { - const unavailableReason = getFastModeUnavailableReason(); - if (unavailableReason) { - return `Fast mode unavailable: ${unavailableReason}`; - } - const { - mainLoopModel - } = getAppState(); - applyFastMode(enable2, setAppState); - logEvent("tengu_fast_mode_toggled", { - enabled: enable2, - source: "shortcut" - }); - if (enable2) { - const fastIcon = getFastIconString(true); - const modelUpdated = !isFastModeSupportedByModel(mainLoopModel) ? ` \xB7 model set to ${FAST_MODE_MODEL_DISPLAY}` : ""; - const pricing = formatModelPricing(getOpus46CostTier(true)); - return `${fastIcon} Fast mode ON${modelUpdated} \xB7 ${pricing}`; - } else { - return `Fast mode OFF`; - } -} -async function call44(onDone, context7, args) { - if (!isFastModeEnabled()) { - return null; - } - await prefetchFastModeStatus(); - const arg = args?.trim().toLowerCase(); - if (arg === "on" || arg === "off") { - const result = await handleFastModeShortcut(arg === "on", context7.getAppState, context7.setAppState); - onDone(result); - return null; - } - const unavailableReason = getFastModeUnavailableReason(); - logEvent("tengu_fast_mode_picker_shown", { - unavailable_reason: unavailableReason ?? "" - }); - return /* @__PURE__ */ jsx_dev_runtime302.jsxDEV(FastModePicker, { - onDone, - unavailableReason - }, undefined, false, undefined, this); -} -var import_compiler_runtime239, import_react171, jsx_dev_runtime302; -var init_fast = __esm(() => { - init_Dialog(); - init_FastIcon(); - init_ink2(); - init_useKeybinding(); - init_analytics(); - init_AppState(); - init_fastMode(); - init_format(); - init_modelCost(); - init_settings2(); - import_compiler_runtime239 = __toESM(require_compiler_runtime(), 1); - import_react171 = __toESM(require_react(), 1); - jsx_dev_runtime302 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/fast/index.ts -var fast, fast_default; -var init_fast2 = __esm(() => { - init_fastMode(); - init_immediateCommand(); - fast = { - type: "local-jsx", - name: "fast", - get description() { - return `Toggle fast mode (${FAST_MODE_MODEL_DISPLAY} only)`; - }, - availability: ["claude-ai", "console"], - isEnabled: () => isFastModeEnabled(), - get isHidden() { - return !isFastModeEnabled(); - }, - argumentHint: "[on|off]", - get immediate() { - return shouldInferenceConfigCommandBeImmediate(); - }, - load: () => Promise.resolve().then(() => (init_fast(), exports_fast)) - }; - fast_default = fast; -}); - -// src/components/Passes/Passes.tsx -function Passes({ - onDone -}) { - const [loading, setLoading] = import_react172.useState(true); - const [passStatuses, setPassStatuses] = import_react172.useState([]); - const [isAvailable, setIsAvailable] = import_react172.useState(false); - const [referralLink, setReferralLink] = import_react172.useState(null); - const [referrerReward, setReferrerReward] = import_react172.useState(undefined); - const exitState = useExitOnCtrlCDWithKeybindings(() => onDone("Guest passes dialog dismissed", { - display: "system" - })); - const handleCancel = import_react172.useCallback(() => { - onDone("Guest passes dialog dismissed", { - display: "system" - }); - }, [onDone]); - useKeybinding("confirm:no", handleCancel, { - context: "Confirmation" - }); - use_input_default((_input, key2) => { - if (key2.return && referralLink) { - setClipboard(referralLink).then((raw) => { - if (raw) - process.stdout.write(raw); - logEvent("tengu_guest_passes_link_copied", {}); - onDone(`Referral link copied to clipboard!`); - }); - } - }); - import_react172.useEffect(() => { - async function loadPassesData() { - try { - const eligibilityData = await getCachedOrFetchPassesEligibility(); - if (!eligibilityData || !eligibilityData.eligible) { - setIsAvailable(false); - setLoading(false); - return; - } - setIsAvailable(true); - if (eligibilityData.referral_code_details?.referral_link) { - setReferralLink(eligibilityData.referral_code_details.referral_link); - } - setReferrerReward(eligibilityData.referrer_reward); - const campaign = eligibilityData.referral_code_details?.campaign ?? "claude_code_guest_pass"; - let redemptionsData; - try { - redemptionsData = await fetchReferralRedemptions(campaign); - } catch (err_0) { - logError2(err_0); - setIsAvailable(false); - setLoading(false); - return; - } - const redemptions = redemptionsData.redemptions || []; - const maxRedemptions = redemptionsData.limit || 3; - const statuses = []; - for (let i6 = 0;i6 < maxRedemptions; i6++) { - const redemption = redemptions[i6]; - statuses.push({ - passNumber: i6 + 1, - isAvailable: !redemption - }); - } - setPassStatuses(statuses); - setLoading(false); - } catch (err2) { - logError2(err2); - setIsAvailable(false); - setLoading(false); - } - } - loadPassesData(); - }, []); - if (loading) { - return /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(Pane, { - children: /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - children: "Loading guest pass information\u2026" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(jsx_dev_runtime303.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(jsx_dev_runtime303.Fragment, { - children: "Esc to cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - } - if (!isAvailable) { - return /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(Pane, { - children: /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - children: "Guest passes are not currently available." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(jsx_dev_runtime303.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(jsx_dev_runtime303.Fragment, { - children: "Esc to cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - } - const availableCount = count2(passStatuses, (p4) => p4.isAvailable); - const sortedPasses = [...passStatuses].sort((a5, b5) => +b5.isAvailable - +a5.isAvailable); - const renderTicket = (pass6) => { - const isRedeemed = !pass6.isAvailable; - if (isRedeemed) { - return /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginRight: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - children: "\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2571" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - children: ` ) CC ${TEARDROP_ASTERISK} \u250A\u2571` - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - children: "\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2571" - }, undefined, false, undefined, this) - ] - }, pass6.passNumber, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginRight: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - children: "\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - children: [ - " ) CC ", - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - color: "claude", - children: TEARDROP_ASTERISK - }, undefined, false, undefined, this), - " \u250A ( " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - children: "\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518" - }, undefined, false, undefined, this) - ] - }, pass6.passNumber, true, undefined, this); - }; - return /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(Pane, { - children: /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - color: "permission", - children: [ - "Guest passes \xB7 ", - availableCount, - " left" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "row", - marginLeft: 2, - children: sortedPasses.slice(0, 3).map((pass_0) => renderTicket(pass_0)) - }, undefined, false, undefined, this), - referralLink && /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - children: referralLink - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - children: [ - referrerReward ? `Share a free week of Claude Code with friends. If they love it and subscribe, you'll get ${formatCreditAmount(referrerReward)} of extra usage to keep building. ` : "Share a free week of Claude Code with friends. ", - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(Link, { - url: referrerReward ? "https://support.claude.com/en/articles/13456702-claude-code-guest-passes" : "https://support.claude.com/en/articles/12875061-claude-code-guest-passes", - children: "Terms apply." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(jsx_dev_runtime303.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime303.jsxDEV(jsx_dev_runtime303.Fragment, { - children: "Enter to copy link \xB7 Esc to cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var import_react172, jsx_dev_runtime303; -var init_Passes = __esm(() => { - init_figures2(); - init_useExitOnCtrlCDWithKeybindings(); - init_osc(); - init_ink2(); - init_useKeybinding(); - init_analytics(); - init_referral(); - init_log2(); - init_Pane(); - import_react172 = __toESM(require_react(), 1); - jsx_dev_runtime303 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/passes/passes.tsx -var exports_passes = {}; -__export(exports_passes, { - call: () => call45 -}); -async function call45(onDone) { - const config10 = getGlobalConfig(); - const isFirstVisit = !config10.hasVisitedPasses; - if (isFirstVisit) { - const remaining = getCachedRemainingPasses(); - saveGlobalConfig((current) => ({ - ...current, - hasVisitedPasses: true, - passesLastSeenRemaining: remaining ?? current.passesLastSeenRemaining - })); - } - logEvent("tengu_guest_passes_visited", { - is_first_visit: isFirstVisit - }); - return /* @__PURE__ */ jsx_dev_runtime304.jsxDEV(Passes, { - onDone - }, undefined, false, undefined, this); -} -var jsx_dev_runtime304; -var init_passes = __esm(() => { - init_Passes(); - init_analytics(); - init_referral(); - init_config(); - jsx_dev_runtime304 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/passes/index.ts -var passes_default; -var init_passes2 = __esm(() => { - init_referral(); - passes_default = { - type: "local-jsx", - name: "passes", - get description() { - const reward = getCachedReferrerReward(); - if (reward) { - return "Share a free week of Claude Code with friends and earn extra usage"; - } - return "Share a free week of Claude Code with friends"; - }, - get isHidden() { - const { eligible: eligible2, hasCache } = checkCachedPassesEligibility(); - return !eligible2 || !hasCache; - }, - load: () => Promise.resolve().then(() => (init_passes(), exports_passes)) - }; -}); - -// src/components/grove/Grove.tsx -var exports_Grove = {}; -__export(exports_Grove, { - PrivacySettingsDialog: () => PrivacySettingsDialog, - GroveDialog: () => GroveDialog -}); -function GracePeriodContentBody() { - const $2 = import_compiler_runtime240.c(9); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "An update to our Consumer Terms and Privacy Policy will take effect on", - " ", - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "October 8, 2025" - }, undefined, false, undefined, this), - ". You can accept the updated terms today." - ] - }, undefined, true, undefined, this); - $2[0] = t0; - } else { - t0 = $2[0]; - } - let t1; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "What's changing?" - }, undefined, false, undefined, this); - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - let t32; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "\xB7 " - }, undefined, false, undefined, this); - t32 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "You can help improve Claude " - }, undefined, false, undefined, this); - $2[2] = t22; - $2[3] = t32; - } else { - t22 = $2[2]; - t32 = $2[3]; - } - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - paddingLeft: 1, - children: /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - t22, - t32, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "\u2014 Allow the use of your chats and coding sessions to train and improve Anthropic AI models. Change anytime in your Privacy Settings (", - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://claude.ai/settings/data-privacy-controls" - }, undefined, false, undefined, this), - ")." - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t1, - t4, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - paddingLeft: 1, - children: /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "\xB7 " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "Updates to data retention " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "\u2014 To help us improve our AI models and safety protections, we're extending data retention to 5 years." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[5] = t5; - } else { - t5 = $2[5]; - } - let t6; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://www.anthropic.com/news/updates-to-our-consumer-terms" - }, undefined, false, undefined, this); - $2[6] = t6; - } else { - t6 = $2[6]; - } - let t7; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://anthropic.com/legal/terms" - }, undefined, false, undefined, this); - $2[7] = t7; - } else { - t7 = $2[7]; - } - let t8; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(jsx_dev_runtime305.Fragment, { - children: [ - t0, - t5, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "Learn more (", - t6, - ") or read the updated Consumer Terms (", - t7, - ") and Privacy Policy (", - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://anthropic.com/legal/privacy" - }, undefined, false, undefined, this), - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[8] = t8; - } else { - t8 = $2[8]; - } - return t8; -} -function PostGracePeriodContentBody() { - const $2 = import_compiler_runtime240.c(7); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "We've updated our Consumer Terms and Privacy Policy." - }, undefined, false, undefined, this); - $2[0] = t0; - } else { - t0 = $2[0]; - } - let t1; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "What's changing?" - }, undefined, false, undefined, this); - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "Help improve Claude" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "Allow the use of your chats and coding sessions to train and improve Anthropic AI models. You can change this anytime in Privacy Settings" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://claude.ai/settings/data-privacy-controls" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t1, - t22, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "How this affects data retention" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "Turning ON the improve Claude setting extends data retention from 30 days to 5 years. Turning it OFF keeps the default 30-day data retention. Delete data anytime." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://www.anthropic.com/news/updates-to-our-consumer-terms" - }, undefined, false, undefined, this); - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://anthropic.com/legal/terms" - }, undefined, false, undefined, this); - $2[5] = t5; - } else { - t5 = $2[5]; - } - let t6; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(jsx_dev_runtime305.Fragment, { - children: [ - t0, - t32, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "Learn more (", - t4, - ") or read the updated Consumer Terms (", - t5, - ") and Privacy Policy (", - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://anthropic.com/legal/privacy" - }, undefined, false, undefined, this), - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = t6; - } else { - t6 = $2[6]; - } - return t6; -} -function GroveDialog(t0) { - const $2 = import_compiler_runtime240.c(34); - const { - showIfAlreadyViewed, - location, - onDone - } = t0; - const [shouldShowDialog, setShouldShowDialog] = import_react173.useState(null); - const [groveConfig, setGroveConfig] = import_react173.useState(null); - let t1; - let t22; - if ($2[0] !== location || $2[1] !== onDone || $2[2] !== showIfAlreadyViewed) { - t1 = () => { - const checkGroveSettings = async function checkGroveSettings2() { - const [settingsResult, configResult] = await Promise.all([getGroveSettings(), getGroveNoticeConfig()]); - const config10 = configResult.success ? configResult.data : null; - setGroveConfig(config10); - const shouldShow = calculateShouldShowGrove(settingsResult, configResult, showIfAlreadyViewed); - setShouldShowDialog(shouldShow); - if (!shouldShow) { - onDone("skip_rendering"); - return; - } - markGroveNoticeViewed(); - logEvent("tengu_grove_policy_viewed", { - location, - dismissable: config10?.notice_is_grace_period - }); - }; - checkGroveSettings(); - }; - t22 = [showIfAlreadyViewed, location, onDone]; - $2[0] = location; - $2[1] = onDone; - $2[2] = showIfAlreadyViewed; - $2[3] = t1; - $2[4] = t22; - } else { - t1 = $2[3]; - t22 = $2[4]; - } - import_react173.useEffect(t1, t22); - if (shouldShowDialog === null) { - return null; - } - if (!shouldShowDialog) { - return null; - } - let t32; - if ($2[5] !== groveConfig?.notice_is_grace_period || $2[6] !== onDone) { - t32 = async function onChange2(value) { - bb21: - switch (value) { - case "accept_opt_in": { - await updateGroveSettings(true); - logEvent("tengu_grove_policy_submitted", { - state: true, - dismissable: groveConfig?.notice_is_grace_period - }); - break bb21; - } - case "accept_opt_out": { - await updateGroveSettings(false); - logEvent("tengu_grove_policy_submitted", { - state: false, - dismissable: groveConfig?.notice_is_grace_period - }); - break bb21; - } - case "defer": { - logEvent("tengu_grove_policy_dismissed", { - state: true - }); - break bb21; - } - case "escape": { - logEvent("tengu_grove_policy_escaped", {}); - } - } - onDone(value); - }; - $2[5] = groveConfig?.notice_is_grace_period; - $2[6] = onDone; - $2[7] = t32; - } else { - t32 = $2[7]; - } - const onChange = t32; - let t4; - if ($2[8] !== groveConfig?.domain_excluded) { - t4 = groveConfig?.domain_excluded ? [{ - label: "Accept terms \xB7 Help improve Claude: OFF (for emails with your domain)", - value: "accept_opt_out" - }] : [{ - label: "Accept terms \xB7 Help improve Claude: ON", - value: "accept_opt_in" - }, { - label: "Accept terms \xB7 Help improve Claude: OFF", - value: "accept_opt_out" - }]; - $2[8] = groveConfig?.domain_excluded; - $2[9] = t4; - } else { - t4 = $2[9]; - } - const acceptOptions = t4; - let t5; - if ($2[10] !== groveConfig?.notice_is_grace_period || $2[11] !== onChange) { - t5 = function handleCancel2() { - if (groveConfig?.notice_is_grace_period) { - onChange("defer"); - return; - } - onChange("escape"); - }; - $2[10] = groveConfig?.notice_is_grace_period; - $2[11] = onChange; - $2[12] = t5; - } else { - t5 = $2[12]; - } - const handleCancel = t5; - let t6; - if ($2[13] !== groveConfig?.notice_is_grace_period) { - t6 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - flexGrow: 1, - children: groveConfig?.notice_is_grace_period ? /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(GracePeriodContentBody, {}, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(PostGracePeriodContentBody, {}, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[13] = groveConfig?.notice_is_grace_period; - $2[14] = t6; - } else { - t6 = $2[14]; - } - let t7; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexShrink: 0, - children: /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - color: "professionalBlue", - children: NEW_TERMS_ASCII - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[15] = t7; - } else { - t7 = $2[15]; - } - let t8; - if ($2[16] !== t6) { - t8 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - t6, - t7 - ] - }, undefined, true, undefined, this); - $2[16] = t6; - $2[17] = t8; - } else { - t8 = $2[17]; - } - let t9; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t9 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "Please select how you'd like to continue" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: "Your choice takes effect immediately upon confirmation." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[18] = t9; - } else { - t9 = $2[18]; - } - let t10; - if ($2[19] !== groveConfig?.notice_is_grace_period) { - t10 = groveConfig?.notice_is_grace_period ? [{ - label: "Not now", - value: "defer" - }] : []; - $2[19] = groveConfig?.notice_is_grace_period; - $2[20] = t10; - } else { - t10 = $2[20]; - } - let t11; - if ($2[21] !== acceptOptions || $2[22] !== t10) { - t11 = [...acceptOptions, ...t10]; - $2[21] = acceptOptions; - $2[22] = t10; - $2[23] = t11; - } else { - t11 = $2[23]; - } - let t12; - if ($2[24] !== onChange) { - t12 = (value_0) => onChange(value_0); - $2[24] = onChange; - $2[25] = t12; - } else { - t12 = $2[25]; - } - let t13; - if ($2[26] !== handleCancel || $2[27] !== t11 || $2[28] !== t12) { - t13 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t9, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Select, { - options: t11, - onChange: t12, - onCancel: handleCancel - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[26] = handleCancel; - $2[27] = t11; - $2[28] = t12; - $2[29] = t13; - } else { - t13 = $2[29]; - } - let t14; - if ($2[30] !== handleCancel || $2[31] !== t13 || $2[32] !== t8) { - t14 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Dialog, { - title: "Updates to Consumer Terms and Policies", - color: "professionalBlue", - onCancel: handleCancel, - inputGuide: _temp145, - children: [ - t8, - t13 - ] - }, undefined, true, undefined, this); - $2[30] = handleCancel; - $2[31] = t13; - $2[32] = t8; - $2[33] = t14; - } else { - t14 = $2[33]; - } - return t14; -} -function _temp145(exitState) { - return exitState.pending ? /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "confirm" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(KeyboardShortcutHint, { - shortcut: "Esc", - action: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -function PrivacySettingsDialog(t0) { - const $2 = import_compiler_runtime240.c(17); - const { - settings, - domainExcluded, - onDone - } = t0; - const [groveEnabled, setGroveEnabled] = import_react173.useState(settings.grove_enabled); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = []; - $2[0] = t1; - } else { - t1 = $2[0]; - } - import_react173.default.useEffect(_temp260, t1); - let t22; - if ($2[1] !== domainExcluded || $2[2] !== groveEnabled) { - t22 = async (input, key2) => { - if (!domainExcluded && (key2.tab || key2.return || input === " ")) { - const newValue = !groveEnabled; - setGroveEnabled(newValue); - await updateGroveSettings(newValue); - } - }; - $2[1] = domainExcluded; - $2[2] = groveEnabled; - $2[3] = t22; - } else { - t22 = $2[3]; - } - use_input_default(t22); - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - color: "error", - children: "false" - }, undefined, false, undefined, this); - $2[4] = t32; - } else { - t32 = $2[4]; - } - let valueComponent = t32; - if (domainExcluded) { - let t42; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t42 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - color: "error", - children: "false (for emails with your domain)" - }, undefined, false, undefined, this); - $2[5] = t42; - } else { - t42 = $2[5]; - } - valueComponent = t42; - } else { - if (groveEnabled) { - let t42; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t42 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - color: "success", - children: "true" - }, undefined, false, undefined, this); - $2[6] = t42; - } else { - t42 = $2[6]; - } - valueComponent = t42; - } - } - let t4; - if ($2[7] !== domainExcluded) { - t4 = (exitState) => exitState.pending ? /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : domainExcluded ? /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(KeyboardShortcutHint, { - shortcut: "Esc", - action: "cancel" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter/Tab/Space", - action: "toggle" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(KeyboardShortcutHint, { - shortcut: "Esc", - action: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[7] = domainExcluded; - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - children: [ - "Review and manage your privacy settings at", - " ", - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Link, { - url: "https://claude.ai/settings/data-privacy-controls" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[9] = t5; - } else { - t5 = $2[9]; - } - let t6; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - width: 44, - children: /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedText, { - bold: true, - children: "Help improve Claude" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[10] = t6; - } else { - t6 = $2[10]; - } - let t7; - if ($2[11] !== valueComponent) { - t7 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - children: [ - t6, - /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(ThemedBox_default, { - children: valueComponent - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[11] = valueComponent; - $2[12] = t7; - } else { - t7 = $2[12]; - } - let t8; - if ($2[13] !== onDone || $2[14] !== t4 || $2[15] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime305.jsxDEV(Dialog, { - title: "Data Privacy", - color: "professionalBlue", - onCancel: onDone, - inputGuide: t4, - children: [ - t5, - t7 - ] - }, undefined, true, undefined, this); - $2[13] = onDone; - $2[14] = t4; - $2[15] = t7; - $2[16] = t8; - } else { - t8 = $2[16]; - } - return t8; -} -function _temp260() { - logEvent("tengu_grove_privacy_settings_viewed", {}); -} -var import_compiler_runtime240, import_react173, jsx_dev_runtime305, NEW_TERMS_ASCII = ` _____________ - | \\ \\ - | NEW TERMS \\__\\ - | | - | ---------- | - | ---------- | - | ---------- | - | ---------- | - | ---------- | - | | - |______________|`; -var init_Grove = __esm(() => { - init_analytics(); - init_ink2(); - init_grove(); - init_CustomSelect(); - init_Byline(); - init_Dialog(); - init_KeyboardShortcutHint(); - import_compiler_runtime240 = __toESM(require_compiler_runtime(), 1); - import_react173 = __toESM(require_react(), 1); - jsx_dev_runtime305 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/privacy-settings/privacy-settings.tsx -var exports_privacy_settings = {}; -__export(exports_privacy_settings, { - call: () => call46 -}); -async function call46(onDone) { - const qualified = await isQualifiedForGrove(); - if (!qualified) { - onDone(FALLBACK_MESSAGE); - return null; - } - const [settingsResult, configResult] = await Promise.all([getGroveSettings(), getGroveNoticeConfig()]); - if (!settingsResult.success) { - onDone(FALLBACK_MESSAGE); - return null; - } - const settings = settingsResult.data; - const config10 = configResult.success ? configResult.data : null; - async function onDoneWithDecision(decision) { - if (decision === "escape" || decision === "defer") { - onDone("Privacy settings dialog dismissed", { - display: "system" - }); - return; - } - await onDoneWithSettingsCheck(); - } - async function onDoneWithSettingsCheck() { - const updatedSettingsResult = await getGroveSettings(); - if (!updatedSettingsResult.success) { - onDone("Unable to retrieve updated privacy settings", { - display: "system" - }); - return; - } - const updatedSettings = updatedSettingsResult.data; - const groveStatus = updatedSettings.grove_enabled ? "true" : "false"; - onDone(`"Help improve Claude" set to ${groveStatus}.`); - if (settings.grove_enabled !== null && settings.grove_enabled !== updatedSettings.grove_enabled) { - logEvent("tengu_grove_policy_toggled", { - state: updatedSettings.grove_enabled, - location: "settings" - }); - } - } - if (settings.grove_enabled !== null) { - return /* @__PURE__ */ jsx_dev_runtime306.jsxDEV(PrivacySettingsDialog, { - settings, - domainExcluded: config10?.domain_excluded, - onDone: onDoneWithSettingsCheck - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime306.jsxDEV(GroveDialog, { - showIfAlreadyViewed: true, - onDone: onDoneWithDecision, - location: "settings" - }, undefined, false, undefined, this); -} -var jsx_dev_runtime306, FALLBACK_MESSAGE = "Review and manage your privacy settings at https://claude.ai/settings/data-privacy-controls"; -var init_privacy_settings = __esm(() => { - init_Grove(); - init_analytics(); - init_grove(); - jsx_dev_runtime306 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/privacy-settings/index.ts -var privacySettings, privacy_settings_default; -var init_privacy_settings2 = __esm(() => { - init_auth14(); - privacySettings = { - type: "local-jsx", - name: "privacy-settings", - description: "View and update your privacy settings", - isEnabled: () => { - return isConsumerSubscriber(); - }, - load: () => Promise.resolve().then(() => (init_privacy_settings(), exports_privacy_settings)) - }; - privacy_settings_default = privacySettings; -}); - -// src/utils/hooks/hooksConfigManager.ts -function groupHooksByEventAndMatcher(appState, toolNames) { - const grouped = { - PreToolUse: {}, - PostToolUse: {}, - PostToolUseFailure: {}, - PermissionDenied: {}, - Notification: {}, - UserPromptSubmit: {}, - SessionStart: {}, - SessionEnd: {}, - Stop: {}, - StopFailure: {}, - SubagentStart: {}, - SubagentStop: {}, - PreCompact: {}, - PostCompact: {}, - PermissionRequest: {}, - Setup: {}, - TeammateIdle: {}, - TaskCreated: {}, - TaskCompleted: {}, - Elicitation: {}, - ElicitationResult: {}, - ConfigChange: {}, - WorktreeCreate: {}, - WorktreeRemove: {}, - InstructionsLoaded: {}, - CwdChanged: {}, - FileChanged: {} - }; - const metadata = getHookEventMetadata(toolNames); - getAllHooks(appState).forEach((hook) => { - const eventGroup = grouped[hook.event]; - if (eventGroup) { - const matcherKey = metadata[hook.event].matcherMetadata !== undefined ? hook.matcher || "" : ""; - if (!eventGroup[matcherKey]) { - eventGroup[matcherKey] = []; - } - eventGroup[matcherKey].push(hook); - } - }); - const registeredHooks = getRegisteredHooks(); - if (registeredHooks) { - for (const [event, matchers] of Object.entries(registeredHooks)) { - const hookEvent = event; - const eventGroup = grouped[hookEvent]; - if (!eventGroup) - continue; - for (const matcher of matchers) { - const matcherKey = matcher.matcher || ""; - if ("pluginRoot" in matcher) { - eventGroup[matcherKey] ??= []; - for (const hook of matcher.hooks) { - eventGroup[matcherKey].push({ - event: hookEvent, - config: hook, - matcher: matcher.matcher, - source: "pluginHook", - pluginName: matcher.pluginId - }); - } - } else if (process.env.USER_TYPE === "ant") { - eventGroup[matcherKey] ??= []; - for (const _hook of matcher.hooks) { - eventGroup[matcherKey].push({ - event: hookEvent, - config: { - type: "command", - command: "[ANT-ONLY] Built-in Hook" - }, - matcher: matcher.matcher, - source: "builtinHook" - }); - } - } - } - } - } - return grouped; -} -function getSortedMatchersForEvent(hooksByEventAndMatcher, event) { - const matchers = Object.keys(hooksByEventAndMatcher[event] || {}); - return sortMatchersByPriority(matchers, hooksByEventAndMatcher, event); -} -function getHooksForMatcher(hooksByEventAndMatcher, event, matcher) { - const matcherKey = matcher ?? ""; - return hooksByEventAndMatcher[event]?.[matcherKey] ?? []; -} -function getMatcherMetadata(event, toolNames) { - return getHookEventMetadata(toolNames)[event].matcherMetadata; -} -var getHookEventMetadata; -var init_hooksConfigManager = __esm(() => { - init_memoize(); - init_state(); - init_hooksSettings(); - getHookEventMetadata = memoize_default(function(toolNames) { - return { - PreToolUse: { - summary: "Before tool execution", - description: `Input to command is JSON of tool call arguments. -Exit code 0 - stdout/stderr not shown -Exit code 2 - show stderr to model and block tool call -Other exit codes - show stderr to user only but continue with tool call`, - matcherMetadata: { - fieldToMatch: "tool_name", - values: toolNames - } - }, - PostToolUse: { - summary: "After tool execution", - description: `Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response). -Exit code 0 - stdout shown in transcript mode (ctrl+o) -Exit code 2 - show stderr to model immediately -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "tool_name", - values: toolNames - } - }, - PostToolUseFailure: { - summary: "After tool execution fails", - description: `Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout. -Exit code 0 - stdout shown in transcript mode (ctrl+o) -Exit code 2 - show stderr to model immediately -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "tool_name", - values: toolNames - } - }, - PermissionDenied: { - summary: "After auto mode classifier denies a tool call", - description: `Input to command is JSON with tool_name, tool_input, tool_use_id, and reason. -Return {"hookSpecificOutput":{"hookEventName":"PermissionDenied","retry":true}} to tell the model it may retry. -Exit code 0 - stdout shown in transcript mode (ctrl+o) -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "tool_name", - values: toolNames - } - }, - Notification: { - summary: "When notifications are sent", - description: `Input to command is JSON with notification message and type. -Exit code 0 - stdout/stderr not shown -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "notification_type", - values: [ - "permission_prompt", - "idle_prompt", - "auth_success", - "elicitation_dialog", - "elicitation_complete", - "elicitation_response" - ] - } - }, - UserPromptSubmit: { - summary: "When the user submits a prompt", - description: `Input to command is JSON with original user prompt text. -Exit code 0 - stdout shown to Claude -Exit code 2 - block processing, erase original prompt, and show stderr to user only -Other exit codes - show stderr to user only` - }, - SessionStart: { - summary: "When a new session is started", - description: `Input to command is JSON with session start source. -Exit code 0 - stdout shown to Claude -Blocking errors are ignored -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "source", - values: ["startup", "resume", "clear", "compact"] - } - }, - Stop: { - summary: "Right before Claude concludes its response", - description: `Exit code 0 - stdout/stderr not shown -Exit code 2 - show stderr to model and continue conversation -Other exit codes - show stderr to user only` - }, - StopFailure: { - summary: "When the turn ends due to an API error", - description: "Fires instead of Stop when an API error (rate limit, auth failure, etc.) ended the turn. Fire-and-forget \u2014 hook output and exit codes are ignored.", - matcherMetadata: { - fieldToMatch: "error", - values: [ - "rate_limit", - "authentication_failed", - "billing_error", - "invalid_request", - "server_error", - "max_output_tokens", - "unknown" - ] - } - }, - SubagentStart: { - summary: "When a subagent (Agent tool call) is started", - description: `Input to command is JSON with agent_id and agent_type. -Exit code 0 - stdout shown to subagent -Blocking errors are ignored -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "agent_type", - values: [] - } - }, - SubagentStop: { - summary: "Right before a subagent (Agent tool call) concludes its response", - description: `Input to command is JSON with agent_id, agent_type, and agent_transcript_path. -Exit code 0 - stdout/stderr not shown -Exit code 2 - show stderr to subagent and continue having it run -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "agent_type", - values: [] - } - }, - PreCompact: { - summary: "Before conversation compaction", - description: `Input to command is JSON with compaction details. -Exit code 0 - stdout appended as custom compact instructions -Exit code 2 - block compaction -Other exit codes - show stderr to user only but continue with compaction`, - matcherMetadata: { - fieldToMatch: "trigger", - values: ["manual", "auto"] - } - }, - PostCompact: { - summary: "After conversation compaction", - description: `Input to command is JSON with compaction details and the summary. -Exit code 0 - stdout shown to user -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "trigger", - values: ["manual", "auto"] - } - }, - SessionEnd: { - summary: "When a session is ending", - description: `Input to command is JSON with session end reason. -Exit code 0 - command completes successfully -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "reason", - values: ["clear", "logout", "prompt_input_exit", "other"] - } - }, - PermissionRequest: { - summary: "When a permission dialog is displayed", - description: `Input to command is JSON with tool_name, tool_input, and tool_use_id. -Output JSON with hookSpecificOutput containing decision to allow or deny. -Exit code 0 - use hook decision if provided -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "tool_name", - values: toolNames - } - }, - Setup: { - summary: "Repo setup hooks for init and maintenance", - description: `Input to command is JSON with trigger (init or maintenance). -Exit code 0 - stdout shown to Claude -Blocking errors are ignored -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "trigger", - values: ["init", "maintenance"] - } - }, - TeammateIdle: { - summary: "When a teammate is about to go idle", - description: `Input to command is JSON with teammate_name and team_name. -Exit code 0 - stdout/stderr not shown -Exit code 2 - show stderr to teammate and prevent idle (teammate continues working) -Other exit codes - show stderr to user only` - }, - TaskCreated: { - summary: "When a task is being created", - description: `Input to command is JSON with task_id, task_subject, task_description, teammate_name, and team_name. -Exit code 0 - stdout/stderr not shown -Exit code 2 - show stderr to model and prevent task creation -Other exit codes - show stderr to user only` - }, - TaskCompleted: { - summary: "When a task is being marked as completed", - description: `Input to command is JSON with task_id, task_subject, task_description, teammate_name, and team_name. -Exit code 0 - stdout/stderr not shown -Exit code 2 - show stderr to model and prevent task completion -Other exit codes - show stderr to user only` - }, - Elicitation: { - summary: "When an MCP server requests user input (elicitation)", - description: `Input to command is JSON with mcp_server_name, message, and requested_schema. -Output JSON with hookSpecificOutput containing action (accept/decline/cancel) and optional content. -Exit code 0 - use hook response if provided -Exit code 2 - deny the elicitation -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "mcp_server_name", - values: [] - } - }, - ElicitationResult: { - summary: "After a user responds to an MCP elicitation", - description: `Input to command is JSON with mcp_server_name, action, content, mode, and elicitation_id. -Output JSON with hookSpecificOutput containing optional action and content to override the response. -Exit code 0 - use hook response if provided -Exit code 2 - block the response (action becomes decline) -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "mcp_server_name", - values: [] - } - }, - ConfigChange: { - summary: "When configuration files change during a session", - description: `Input to command is JSON with source (user_settings, project_settings, local_settings, policy_settings, skills) and file_path. -Exit code 0 - allow the change -Exit code 2 - block the change from being applied to the session -Other exit codes - show stderr to user only`, - matcherMetadata: { - fieldToMatch: "source", - values: [ - "user_settings", - "project_settings", - "local_settings", - "policy_settings", - "skills" - ] - } - }, - InstructionsLoaded: { - summary: "When an instruction file (CLAUDE.md or rule) is loaded", - description: `Input to command is JSON with file_path, memory_type (User, Project, Local, Managed), load_reason (session_start, nested_traversal, path_glob_match, include, compact), globs (optional \u2014 the paths: frontmatter patterns that matched), trigger_file_path (optional \u2014 the file Claude touched that caused the load), and parent_file_path (optional \u2014 the file that @-included this one). -Exit code 0 - command completes successfully -Other exit codes - show stderr to user only -This hook is observability-only and does not support blocking.`, - matcherMetadata: { - fieldToMatch: "load_reason", - values: [ - "session_start", - "nested_traversal", - "path_glob_match", - "include", - "compact" - ] - } - }, - WorktreeCreate: { - summary: "Create an isolated worktree for VCS-agnostic isolation", - description: `Input to command is JSON with name (suggested worktree slug). -Stdout should contain the absolute path to the created worktree directory. -Exit code 0 - worktree created successfully -Other exit codes - worktree creation failed` - }, - WorktreeRemove: { - summary: "Remove a previously created worktree", - description: `Input to command is JSON with worktree_path (absolute path to worktree). -Exit code 0 - worktree removed successfully -Other exit codes - show stderr to user only` - }, - CwdChanged: { - summary: "After the working directory changes", - description: `Input to command is JSON with old_cwd and new_cwd. -CLAUDE_ENV_FILE is set \u2014 write bash exports there to apply env to subsequent BashTool commands. -Hook output can include hookSpecificOutput.watchPaths (array of absolute paths) to register with the FileChanged watcher. -Exit code 0 - command completes successfully -Other exit codes - show stderr to user only` - }, - FileChanged: { - summary: "When a watched file changes", - description: `Input to command is JSON with file_path and event (change, add, unlink). -CLAUDE_ENV_FILE is set \u2014 write bash exports there to apply env to subsequent BashTool commands. -The matcher field specifies filenames to watch in the current directory (e.g. ".envrc|.env"). -Hook output can include hookSpecificOutput.watchPaths (array of absolute paths) to dynamically update the watch list. -Exit code 0 - command completes successfully -Other exit codes - show stderr to user only` - } - }; - }, (toolNames) => toolNames.slice().sort().join(",")); -}); - -// src/components/hooks/SelectEventMode.tsx -function SelectEventMode(t0) { - const $2 = import_compiler_runtime241.c(23); - const { - hookEventMetadata, - hooksByEvent, - totalHooksCount, - restrictedByPolicy, - onSelectEvent, - onCancel - } = t0; - let t1; - if ($2[0] !== totalHooksCount) { - t1 = plural(totalHooksCount, "hook"); - $2[0] = totalHooksCount; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const subtitle = `${totalHooksCount} ${t1} configured`; - let t22; - if ($2[2] !== restrictedByPolicy) { - t22 = restrictedByPolicy && /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedText, { - color: "suggestion", - children: [ - figures_default.info, - " Hooks Restricted by Policy" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedText, { - dimColor: true, - children: "Only hooks from managed settings can run. User-defined hooks from ~/.claude/settings.json, .claude/settings.json, and .claude/settings.local.json are blocked." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = restrictedByPolicy; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.info, - " This menu is read-only. To add or modify hooks, edit settings.json directly or ask Claude.", - " ", - /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/hooks", - children: "Learn more" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== onSelectEvent) { - t4 = (value) => { - onSelectEvent(value); - }; - $2[5] = onSelectEvent; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== hookEventMetadata) { - t5 = Object.entries(hookEventMetadata); - $2[7] = hookEventMetadata; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== hooksByEvent || $2[10] !== t5) { - t6 = t5.map((t72) => { - const [name3, metadata] = t72; - const count4 = hooksByEvent[name3] || 0; - return { - label: count4 > 0 ? /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedText, { - children: [ - name3, - " ", - /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedText, { - color: "suggestion", - children: [ - "(", - count4, - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) : name3, - value: name3, - description: metadata.summary - }; - }); - $2[9] = hooksByEvent; - $2[10] = t5; - $2[11] = t6; - } else { - t6 = $2[11]; - } - let t7; - if ($2[12] !== onCancel || $2[13] !== t4 || $2[14] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(Select, { - onChange: t4, - onCancel, - options: t6 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[12] = onCancel; - $2[13] = t4; - $2[14] = t6; - $2[15] = t7; - } else { - t7 = $2[15]; - } - let t8; - if ($2[16] !== t22 || $2[17] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t22, - t32, - t7 - ] - }, undefined, true, undefined, this); - $2[16] = t22; - $2[17] = t7; - $2[18] = t8; - } else { - t8 = $2[18]; - } - let t9; - if ($2[19] !== onCancel || $2[20] !== subtitle || $2[21] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime307.jsxDEV(Dialog, { - title: "Hooks", - subtitle, - onCancel, - children: t8 - }, undefined, false, undefined, this); - $2[19] = onCancel; - $2[20] = subtitle; - $2[21] = t8; - $2[22] = t9; - } else { - t9 = $2[22]; - } - return t9; -} -var import_compiler_runtime241, jsx_dev_runtime307; -var init_SelectEventMode = __esm(() => { - init_figures(); - init_ink2(); - init_stringUtils(); - init_select(); - init_Dialog(); - import_compiler_runtime241 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime307 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/hooks/SelectHookMode.tsx -function SelectHookMode(t0) { - const $2 = import_compiler_runtime242.c(19); - const { - selectedEvent, - selectedMatcher, - hooksForSelectedMatcher, - hookEventMetadata, - onSelect, - onCancel - } = t0; - const title = hookEventMetadata.matcherMetadata !== undefined ? `${selectedEvent} - Matcher: ${selectedMatcher || "(all)"}` : selectedEvent; - if (hooksForSelectedMatcher.length === 0) { - let t12; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(ThemedText, { - dimColor: true, - children: "No hooks configured for this event." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(ThemedText, { - dimColor: true, - children: "To add hooks, edit settings.json directly or ask Claude." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[0] = t12; - } else { - t12 = $2[0]; - } - let t23; - if ($2[1] !== hookEventMetadata.description || $2[2] !== onCancel || $2[3] !== title) { - t23 = /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(Dialog, { - title, - subtitle: hookEventMetadata.description, - onCancel, - inputGuide: _temp146, - children: t12 - }, undefined, false, undefined, this); - $2[1] = hookEventMetadata.description; - $2[2] = onCancel; - $2[3] = title; - $2[4] = t23; - } else { - t23 = $2[4]; - } - return t23; - } - const t1 = hookEventMetadata.description; - let t22; - if ($2[5] !== hooksForSelectedMatcher) { - t22 = hooksForSelectedMatcher.map(_temp261); - $2[5] = hooksForSelectedMatcher; - $2[6] = t22; - } else { - t22 = $2[6]; - } - let t32; - if ($2[7] !== hooksForSelectedMatcher || $2[8] !== onSelect) { - t32 = (value) => { - const index_0 = parseInt(value, 10); - const hook_0 = hooksForSelectedMatcher[index_0]; - if (hook_0) { - onSelect(hook_0); - } - }; - $2[7] = hooksForSelectedMatcher; - $2[8] = onSelect; - $2[9] = t32; - } else { - t32 = $2[9]; - } - let t4; - if ($2[10] !== onCancel || $2[11] !== t22 || $2[12] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(Select, { - options: t22, - onChange: t32, - onCancel - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[10] = onCancel; - $2[11] = t22; - $2[12] = t32; - $2[13] = t4; - } else { - t4 = $2[13]; - } - let t5; - if ($2[14] !== hookEventMetadata.description || $2[15] !== onCancel || $2[16] !== t4 || $2[17] !== title) { - t5 = /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(Dialog, { - title, - subtitle: t1, - onCancel, - children: t4 - }, undefined, false, undefined, this); - $2[14] = hookEventMetadata.description; - $2[15] = onCancel; - $2[16] = t4; - $2[17] = title; - $2[18] = t5; - } else { - t5 = $2[18]; - } - return t5; -} -function _temp261(hook, index2) { - return { - label: `[${hook.config.type}] ${getHookDisplayText(hook.config)}`, - value: index2.toString(), - description: hook.source === "pluginHook" && hook.pluginName ? `${hookSourceHeaderDisplayString(hook.source)} (${hook.pluginName})` : hookSourceHeaderDisplayString(hook.source) - }; -} -function _temp146() { - return /* @__PURE__ */ jsx_dev_runtime308.jsxDEV(ThemedText, { - children: "Esc to go back" - }, undefined, false, undefined, this); -} -var import_compiler_runtime242, jsx_dev_runtime308; -var init_SelectHookMode = __esm(() => { - init_ink2(); - init_hooksSettings(); - init_select(); - init_Dialog(); - import_compiler_runtime242 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime308 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/hooks/SelectMatcherMode.tsx -function SelectMatcherMode(t0) { - const $2 = import_compiler_runtime243.c(25); - const { - selectedEvent, - matchersForSelectedEvent, - hooksByEventAndMatcher, - eventDescription, - onSelect, - onCancel - } = t0; - let t1; - if ($2[0] !== hooksByEventAndMatcher || $2[1] !== matchersForSelectedEvent || $2[2] !== selectedEvent) { - let t23; - if ($2[4] !== hooksByEventAndMatcher || $2[5] !== selectedEvent) { - t23 = (matcher) => { - const hooks = hooksByEventAndMatcher[selectedEvent]?.[matcher] || []; - const sources = Array.from(new Set(hooks.map(_temp147))); - return { - matcher, - sources, - hookCount: hooks.length - }; - }; - $2[4] = hooksByEventAndMatcher; - $2[5] = selectedEvent; - $2[6] = t23; - } else { - t23 = $2[6]; - } - t1 = matchersForSelectedEvent.map(t23); - $2[0] = hooksByEventAndMatcher; - $2[1] = matchersForSelectedEvent; - $2[2] = selectedEvent; - $2[3] = t1; - } else { - t1 = $2[3]; - } - const matchersWithSources = t1; - if (matchersForSelectedEvent.length === 0) { - const t23 = `${selectedEvent} - Matchers`; - let t33; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t33 = /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(ThemedText, { - dimColor: true, - children: "No hooks configured for this event." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(ThemedText, { - dimColor: true, - children: "To add hooks, edit settings.json directly or ask Claude." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[7] = t33; - } else { - t33 = $2[7]; - } - let t42; - if ($2[8] !== eventDescription || $2[9] !== onCancel || $2[10] !== t23) { - t42 = /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(Dialog, { - title: t23, - subtitle: eventDescription, - onCancel, - inputGuide: _temp262, - children: t33 - }, undefined, false, undefined, this); - $2[8] = eventDescription; - $2[9] = onCancel; - $2[10] = t23; - $2[11] = t42; - } else { - t42 = $2[11]; - } - return t42; - } - const t22 = `${selectedEvent} - Matchers`; - let t32; - if ($2[12] !== matchersWithSources) { - t32 = matchersWithSources.map(_temp337); - $2[12] = matchersWithSources; - $2[13] = t32; - } else { - t32 = $2[13]; - } - let t4; - if ($2[14] !== onSelect) { - t4 = (value) => { - onSelect(value); - }; - $2[14] = onSelect; - $2[15] = t4; - } else { - t4 = $2[15]; - } - let t5; - if ($2[16] !== onCancel || $2[17] !== t32 || $2[18] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(Select, { - options: t32, - onChange: t4, - onCancel - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[16] = onCancel; - $2[17] = t32; - $2[18] = t4; - $2[19] = t5; - } else { - t5 = $2[19]; - } - let t6; - if ($2[20] !== eventDescription || $2[21] !== onCancel || $2[22] !== t22 || $2[23] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(Dialog, { - title: t22, - subtitle: eventDescription, - onCancel, - children: t5 - }, undefined, false, undefined, this); - $2[20] = eventDescription; - $2[21] = onCancel; - $2[22] = t22; - $2[23] = t5; - $2[24] = t6; - } else { - t6 = $2[24]; - } - return t6; -} -function _temp337(item) { - const sourceText = item.sources.map(hookSourceInlineDisplayString).join(", "); - const matcherLabel = item.matcher || "(all)"; - return { - label: `[${sourceText}] ${matcherLabel}`, - value: item.matcher, - description: `${item.hookCount} ${plural(item.hookCount, "hook")}` - }; -} -function _temp262() { - return /* @__PURE__ */ jsx_dev_runtime309.jsxDEV(ThemedText, { - children: "Esc to go back" - }, undefined, false, undefined, this); -} -function _temp147(h5) { - return h5.source; -} -var import_compiler_runtime243, jsx_dev_runtime309; -var init_SelectMatcherMode = __esm(() => { - init_ink2(); - init_hooksSettings(); - init_stringUtils(); - init_select(); - init_Dialog(); - import_compiler_runtime243 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime309 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/hooks/ViewHookMode.tsx -function ViewHookMode(t0) { - const $2 = import_compiler_runtime244.c(40); - const { - selectedHook, - eventSupportsMatcher, - onCancel - } = t0; - let t1; - if ($2[0] !== selectedHook.event) { - t1 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: [ - "Event: ", - /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - bold: true, - children: selectedHook.event - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[0] = selectedHook.event; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== eventSupportsMatcher || $2[3] !== selectedHook.matcher) { - t22 = eventSupportsMatcher && /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: [ - "Matcher: ", - /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - bold: true, - children: selectedHook.matcher || "(all)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = eventSupportsMatcher; - $2[3] = selectedHook.matcher; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] !== selectedHook.config.type) { - t32 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: [ - "Type: ", - /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - bold: true, - children: selectedHook.config.type - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[5] = selectedHook.config.type; - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] !== selectedHook.source) { - t4 = hookSourceDescriptionDisplayString(selectedHook.source); - $2[7] = selectedHook.source; - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: [ - "Source:", - " ", - /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - dimColor: true, - children: t4 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[9] = t4; - $2[10] = t5; - } else { - t5 = $2[10]; - } - let t6; - if ($2[11] !== selectedHook.pluginName) { - t6 = selectedHook.pluginName && /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: [ - "Plugin: ", - /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - dimColor: true, - children: selectedHook.pluginName - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[11] = selectedHook.pluginName; - $2[12] = t6; - } else { - t6 = $2[12]; - } - let t7; - if ($2[13] !== t1 || $2[14] !== t22 || $2[15] !== t32 || $2[16] !== t5 || $2[17] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t1, - t22, - t32, - t5, - t6 - ] - }, undefined, true, undefined, this); - $2[13] = t1; - $2[14] = t22; - $2[15] = t32; - $2[16] = t5; - $2[17] = t6; - $2[18] = t7; - } else { - t7 = $2[18]; - } - let t8; - if ($2[19] !== selectedHook.config) { - t8 = getContentFieldLabel(selectedHook.config); - $2[19] = selectedHook.config; - $2[20] = t8; - } else { - t8 = $2[20]; - } - let t9; - if ($2[21] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - dimColor: true, - children: [ - t8, - ":" - ] - }, undefined, true, undefined, this); - $2[21] = t8; - $2[22] = t9; - } else { - t9 = $2[22]; - } - let t10; - if ($2[23] !== selectedHook.config) { - t10 = getContentFieldValue(selectedHook.config); - $2[23] = selectedHook.config; - $2[24] = t10; - } else { - t10 = $2[24]; - } - let t11; - if ($2[25] !== t10) { - t11 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedBox_default, { - borderStyle: "round", - borderDimColor: true, - paddingLeft: 1, - paddingRight: 1, - children: /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: t10 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[25] = t10; - $2[26] = t11; - } else { - t11 = $2[26]; - } - let t12; - if ($2[27] !== t11 || $2[28] !== t9) { - t12 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t9, - t11 - ] - }, undefined, true, undefined, this); - $2[27] = t11; - $2[28] = t9; - $2[29] = t12; - } else { - t12 = $2[29]; - } - let t13; - if ($2[30] !== selectedHook.config) { - t13 = "statusMessage" in selectedHook.config && selectedHook.config.statusMessage && /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: [ - "Status message:", - " ", - /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - dimColor: true, - children: selectedHook.config.statusMessage - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[30] = selectedHook.config; - $2[31] = t13; - } else { - t13 = $2[31]; - } - let t14; - if ($2[32] === Symbol.for("react.memo_cache_sentinel")) { - t14 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - dimColor: true, - children: "To modify or remove this hook, edit settings.json directly or ask Claude to help." - }, undefined, false, undefined, this); - $2[32] = t14; - } else { - t14 = $2[32]; - } - let t15; - if ($2[33] !== t12 || $2[34] !== t13 || $2[35] !== t7) { - t15 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t7, - t12, - t13, - t14 - ] - }, undefined, true, undefined, this); - $2[33] = t12; - $2[34] = t13; - $2[35] = t7; - $2[36] = t15; - } else { - t15 = $2[36]; - } - let t16; - if ($2[37] !== onCancel || $2[38] !== t15) { - t16 = /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(Dialog, { - title: "Hook details", - onCancel, - inputGuide: _temp148, - children: t15 - }, undefined, false, undefined, this); - $2[37] = onCancel; - $2[38] = t15; - $2[39] = t16; - } else { - t16 = $2[39]; - } - return t16; -} -function _temp148() { - return /* @__PURE__ */ jsx_dev_runtime310.jsxDEV(ThemedText, { - children: "Esc to go back" - }, undefined, false, undefined, this); -} -function getContentFieldLabel(config10) { - switch (config10.type) { - case "command": - return "Command"; - case "prompt": - return "Prompt"; - case "agent": - return "Prompt"; - case "http": - return "URL"; - } -} -function getContentFieldValue(config10) { - switch (config10.type) { - case "command": - return config10.command; - case "prompt": - return config10.prompt; - case "agent": - return config10.prompt; - case "http": - return config10.url; - } -} -var import_compiler_runtime244, jsx_dev_runtime310; -var init_ViewHookMode = __esm(() => { - init_ink2(); - init_hooksSettings(); - init_Dialog(); - import_compiler_runtime244 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime310 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/hooks/HooksConfigMenu.tsx -function HooksConfigMenu(t0) { - const $2 = import_compiler_runtime245.c(100); - const { - toolNames, - onExit: onExit2 - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - mode: "select-event" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const [modeState, setModeState] = import_react174.useState(t1); - const [disabledByPolicy, setDisabledByPolicy] = import_react174.useState(_temp149); - const [restrictedByPolicy, setRestrictedByPolicy] = import_react174.useState(_temp263); - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = (source) => { - if (source === "policySettings") { - const settings_0 = getSettings_DEPRECATED(); - const hooksDisabled_0 = settings_0?.disableAllHooks === true; - setDisabledByPolicy(hooksDisabled_0 && getSettingsForSource("policySettings")?.disableAllHooks === true); - setRestrictedByPolicy(getSettingsForSource("policySettings")?.allowManagedHooksOnly === true); - } - }; - $2[1] = t22; - } else { - t22 = $2[1]; - } - useSettingsChange(t22); - const mode = modeState.mode; - const selectedEvent = "event" in modeState ? modeState.event : "PreToolUse"; - const selectedMatcher = "matcher" in modeState ? modeState.matcher : null; - const mcp2 = useAppState(_temp338); - const appStateStore = useAppStateStore(); - let t32; - if ($2[2] !== mcp2.tools || $2[3] !== toolNames) { - t32 = [...toolNames, ...mcp2.tools.map(_temp428)]; - $2[2] = mcp2.tools; - $2[3] = toolNames; - $2[4] = t32; - } else { - t32 = $2[4]; - } - const combinedToolNames = t32; - let t4; - if ($2[5] !== appStateStore || $2[6] !== combinedToolNames) { - t4 = groupHooksByEventAndMatcher(appStateStore.getState(), combinedToolNames); - $2[5] = appStateStore; - $2[6] = combinedToolNames; - $2[7] = t4; - } else { - t4 = $2[7]; - } - const hooksByEventAndMatcher = t4; - let t5; - if ($2[8] !== hooksByEventAndMatcher || $2[9] !== selectedEvent) { - t5 = getSortedMatchersForEvent(hooksByEventAndMatcher, selectedEvent); - $2[8] = hooksByEventAndMatcher; - $2[9] = selectedEvent; - $2[10] = t5; - } else { - t5 = $2[10]; - } - const sortedMatchersForSelectedEvent = t5; - let t6; - if ($2[11] !== hooksByEventAndMatcher || $2[12] !== selectedEvent || $2[13] !== selectedMatcher) { - t6 = getHooksForMatcher(hooksByEventAndMatcher, selectedEvent, selectedMatcher); - $2[11] = hooksByEventAndMatcher; - $2[12] = selectedEvent; - $2[13] = selectedMatcher; - $2[14] = t6; - } else { - t6 = $2[14]; - } - const hooksForSelectedMatcher = t6; - let t7; - if ($2[15] !== onExit2) { - t7 = () => { - onExit2("Hooks dialog dismissed", { - display: "system" - }); - }; - $2[15] = onExit2; - $2[16] = t7; - } else { - t7 = $2[16]; - } - const handleExit = t7; - const t8 = mode === "select-event"; - let t9; - if ($2[17] !== t8) { - t9 = { - context: "Confirmation", - isActive: t8 - }; - $2[17] = t8; - $2[18] = t9; - } else { - t9 = $2[18]; - } - useKeybinding("confirm:no", handleExit, t9); - let t10; - if ($2[19] === Symbol.for("react.memo_cache_sentinel")) { - t10 = () => { - setModeState({ - mode: "select-event" - }); - }; - $2[19] = t10; - } else { - t10 = $2[19]; - } - const t11 = mode === "select-matcher"; - let t12; - if ($2[20] !== t11) { - t12 = { - context: "Confirmation", - isActive: t11 - }; - $2[20] = t11; - $2[21] = t12; - } else { - t12 = $2[21]; - } - useKeybinding("confirm:no", t10, t12); - let t13; - if ($2[22] !== combinedToolNames || $2[23] !== modeState) { - t13 = () => { - if ("event" in modeState) { - if (getMatcherMetadata(modeState.event, combinedToolNames) !== undefined) { - setModeState({ - mode: "select-matcher", - event: modeState.event - }); - } else { - setModeState({ - mode: "select-event" - }); - } - } - }; - $2[22] = combinedToolNames; - $2[23] = modeState; - $2[24] = t13; - } else { - t13 = $2[24]; - } - const t14 = mode === "select-hook"; - let t15; - if ($2[25] !== t14) { - t15 = { - context: "Confirmation", - isActive: t14 - }; - $2[25] = t14; - $2[26] = t15; - } else { - t15 = $2[26]; - } - useKeybinding("confirm:no", t13, t15); - let t16; - if ($2[27] !== modeState) { - t16 = () => { - if (modeState.mode === "view-hook") { - const { - event, - hook - } = modeState; - setModeState({ - mode: "select-hook", - event, - matcher: hook.matcher || "" - }); - } - }; - $2[27] = modeState; - $2[28] = t16; - } else { - t16 = $2[28]; - } - const t17 = mode === "view-hook"; - let t18; - if ($2[29] !== t17) { - t18 = { - context: "Confirmation", - isActive: t17 - }; - $2[29] = t17; - $2[30] = t18; - } else { - t18 = $2[30]; - } - useKeybinding("confirm:no", t16, t18); - let t19; - if ($2[31] !== combinedToolNames) { - t19 = getHookEventMetadata(combinedToolNames); - $2[31] = combinedToolNames; - $2[32] = t19; - } else { - t19 = $2[32]; - } - const hookEventMetadata = t19; - const settings_1 = getSettings_DEPRECATED(); - const hooksDisabled_1 = settings_1?.disableAllHooks === true; - let t20; - if ($2[33] !== hooksByEventAndMatcher) { - const byEvent = {}; - let total = 0; - for (const [event_0, matchers] of Object.entries(hooksByEventAndMatcher)) { - const eventCount = Object.values(matchers).reduce(_temp520, 0); - byEvent[event_0] = eventCount; - total = total + eventCount; - } - t20 = { - hooksByEvent: byEvent, - totalHooksCount: total - }; - $2[33] = hooksByEventAndMatcher; - $2[34] = t20; - } else { - t20 = $2[34]; - } - const { - hooksByEvent, - totalHooksCount - } = t20; - if (hooksDisabled_1) { - let t21; - if ($2[35] === Symbol.for("react.memo_cache_sentinel")) { - t21 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - bold: true, - children: "disabled" - }, undefined, false, undefined, this); - $2[35] = t21; - } else { - t21 = $2[35]; - } - const t222 = disabledByPolicy && " by a managed settings file"; - let t23; - if ($2[36] !== totalHooksCount) { - t23 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - bold: true, - children: totalHooksCount - }, undefined, false, undefined, this); - $2[36] = totalHooksCount; - $2[37] = t23; - } else { - t23 = $2[37]; - } - let t24; - if ($2[38] !== totalHooksCount) { - t24 = plural(totalHooksCount, "hook"); - $2[38] = totalHooksCount; - $2[39] = t24; - } else { - t24 = $2[39]; - } - let t25; - if ($2[40] !== totalHooksCount) { - t25 = plural(totalHooksCount, "is", "are"); - $2[40] = totalHooksCount; - $2[41] = t25; - } else { - t25 = $2[41]; - } - let t26; - if ($2[42] !== t222 || $2[43] !== t23 || $2[44] !== t24 || $2[45] !== t25) { - t26 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - children: [ - "All hooks are currently ", - t21, - t222, - ". You have", - " ", - t23, - " configured", - " ", - t24, - " that", - " ", - t25, - " not running." - ] - }, undefined, true, undefined, this); - $2[42] = t222; - $2[43] = t23; - $2[44] = t24; - $2[45] = t25; - $2[46] = t26; - } else { - t26 = $2[46]; - } - let t27; - let t28; - let t29; - let t30; - if ($2[47] === Symbol.for("react.memo_cache_sentinel")) { - t27 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - dimColor: true, - children: "When hooks are disabled:" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - t28 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - dimColor: true, - children: "\xB7 No hook commands will execute" - }, undefined, false, undefined, this); - t29 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - dimColor: true, - children: "\xB7 StatusLine will not be displayed" - }, undefined, false, undefined, this); - t30 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - dimColor: true, - children: "\xB7 Tool operations will proceed without hook validation" - }, undefined, false, undefined, this); - $2[47] = t27; - $2[48] = t28; - $2[49] = t29; - $2[50] = t30; - } else { - t27 = $2[47]; - t28 = $2[48]; - t29 = $2[49]; - t30 = $2[50]; - } - let t31; - if ($2[51] !== t26) { - t31 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t26, - t27, - t28, - t29, - t30 - ] - }, undefined, true, undefined, this); - $2[51] = t26; - $2[52] = t31; - } else { - t31 = $2[52]; - } - let t322; - if ($2[53] !== disabledByPolicy) { - t322 = !disabledByPolicy && /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - dimColor: true, - children: 'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Claude.' - }, undefined, false, undefined, this); - $2[53] = disabledByPolicy; - $2[54] = t322; - } else { - t322 = $2[54]; - } - let t33; - if ($2[55] !== t31 || $2[56] !== t322) { - t33 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t31, - t322 - ] - }, undefined, true, undefined, this); - $2[55] = t31; - $2[56] = t322; - $2[57] = t33; - } else { - t33 = $2[57]; - } - let t34; - if ($2[58] !== handleExit || $2[59] !== t33) { - t34 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(Dialog, { - title: "Hook Configuration - Disabled", - onCancel: handleExit, - inputGuide: _temp617, - children: t33 - }, undefined, false, undefined, this); - $2[58] = handleExit; - $2[59] = t33; - $2[60] = t34; - } else { - t34 = $2[60]; - } - return t34; - } - switch (modeState.mode) { - case "select-event": { - let t21; - if ($2[61] !== combinedToolNames) { - t21 = (event_2) => { - if (getMatcherMetadata(event_2, combinedToolNames) !== undefined) { - setModeState({ - mode: "select-matcher", - event: event_2 - }); - } else { - setModeState({ - mode: "select-hook", - event: event_2, - matcher: "" - }); - } - }; - $2[61] = combinedToolNames; - $2[62] = t21; - } else { - t21 = $2[62]; - } - let t222; - if ($2[63] !== handleExit || $2[64] !== hookEventMetadata || $2[65] !== hooksByEvent || $2[66] !== restrictedByPolicy || $2[67] !== t21 || $2[68] !== totalHooksCount) { - t222 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(SelectEventMode, { - hookEventMetadata, - hooksByEvent, - totalHooksCount, - restrictedByPolicy, - onSelectEvent: t21, - onCancel: handleExit - }, undefined, false, undefined, this); - $2[63] = handleExit; - $2[64] = hookEventMetadata; - $2[65] = hooksByEvent; - $2[66] = restrictedByPolicy; - $2[67] = t21; - $2[68] = totalHooksCount; - $2[69] = t222; - } else { - t222 = $2[69]; - } - return t222; - } - case "select-matcher": { - const t21 = hookEventMetadata[modeState.event]; - let t222; - if ($2[70] !== modeState.event) { - t222 = (matcher) => { - setModeState({ - mode: "select-hook", - event: modeState.event, - matcher - }); - }; - $2[70] = modeState.event; - $2[71] = t222; - } else { - t222 = $2[71]; - } - let t23; - if ($2[72] === Symbol.for("react.memo_cache_sentinel")) { - t23 = () => { - setModeState({ - mode: "select-event" - }); - }; - $2[72] = t23; - } else { - t23 = $2[72]; - } - let t24; - if ($2[73] !== hooksByEventAndMatcher || $2[74] !== modeState.event || $2[75] !== sortedMatchersForSelectedEvent || $2[76] !== t21.description || $2[77] !== t222) { - t24 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(SelectMatcherMode, { - selectedEvent: modeState.event, - matchersForSelectedEvent: sortedMatchersForSelectedEvent, - hooksByEventAndMatcher, - eventDescription: t21.description, - onSelect: t222, - onCancel: t23 - }, undefined, false, undefined, this); - $2[73] = hooksByEventAndMatcher; - $2[74] = modeState.event; - $2[75] = sortedMatchersForSelectedEvent; - $2[76] = t21.description; - $2[77] = t222; - $2[78] = t24; - } else { - t24 = $2[78]; - } - return t24; - } - case "select-hook": { - const t21 = hookEventMetadata[modeState.event]; - let t222; - if ($2[79] !== modeState.event) { - t222 = (hook_1) => { - setModeState({ - mode: "view-hook", - event: modeState.event, - hook: hook_1 - }); - }; - $2[79] = modeState.event; - $2[80] = t222; - } else { - t222 = $2[80]; - } - let t23; - if ($2[81] !== combinedToolNames || $2[82] !== modeState.event) { - t23 = () => { - if (getMatcherMetadata(modeState.event, combinedToolNames) !== undefined) { - setModeState({ - mode: "select-matcher", - event: modeState.event - }); - } else { - setModeState({ - mode: "select-event" - }); - } - }; - $2[81] = combinedToolNames; - $2[82] = modeState.event; - $2[83] = t23; - } else { - t23 = $2[83]; - } - let t24; - if ($2[84] !== hooksForSelectedMatcher || $2[85] !== modeState.event || $2[86] !== modeState.matcher || $2[87] !== t21 || $2[88] !== t222 || $2[89] !== t23) { - t24 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(SelectHookMode, { - selectedEvent: modeState.event, - selectedMatcher: modeState.matcher, - hooksForSelectedMatcher, - hookEventMetadata: t21, - onSelect: t222, - onCancel: t23 - }, undefined, false, undefined, this); - $2[84] = hooksForSelectedMatcher; - $2[85] = modeState.event; - $2[86] = modeState.matcher; - $2[87] = t21; - $2[88] = t222; - $2[89] = t23; - $2[90] = t24; - } else { - t24 = $2[90]; - } - return t24; - } - case "view-hook": { - const t21 = modeState.hook; - let t222; - if ($2[91] !== combinedToolNames || $2[92] !== modeState.event) { - t222 = getMatcherMetadata(modeState.event, combinedToolNames); - $2[91] = combinedToolNames; - $2[92] = modeState.event; - $2[93] = t222; - } else { - t222 = $2[93]; - } - const t23 = t222 !== undefined; - let t24; - if ($2[94] !== modeState) { - t24 = () => { - const { - event: event_1, - hook: hook_0 - } = modeState; - setModeState({ - mode: "select-hook", - event: event_1, - matcher: hook_0.matcher || "" - }); - }; - $2[94] = modeState; - $2[95] = t24; - } else { - t24 = $2[95]; - } - let t25; - if ($2[96] !== modeState.hook || $2[97] !== t23 || $2[98] !== t24) { - t25 = /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ViewHookMode, { - selectedHook: t21, - eventSupportsMatcher: t23, - onCancel: t24 - }, undefined, false, undefined, this); - $2[96] = modeState.hook; - $2[97] = t23; - $2[98] = t24; - $2[99] = t25; - } else { - t25 = $2[99]; - } - return t25; - } - } -} -function _temp617() { - return /* @__PURE__ */ jsx_dev_runtime311.jsxDEV(ThemedText, { - children: "Esc to close" - }, undefined, false, undefined, this); -} -function _temp520(sum, hooks) { - return sum + hooks.length; -} -function _temp428(tool) { - return tool.name; -} -function _temp338(s4) { - return s4.mcp; -} -function _temp263() { - return getSettingsForSource("policySettings")?.allowManagedHooksOnly === true; -} -function _temp149() { - const settings = getSettings_DEPRECATED(); - const hooksDisabled = settings?.disableAllHooks === true; - return hooksDisabled && getSettingsForSource("policySettings")?.disableAllHooks === true; -} -var import_compiler_runtime245, import_react174, jsx_dev_runtime311; -var init_HooksConfigMenu = __esm(() => { - init_AppState(); - init_useSettingsChange(); - init_ink2(); - init_useKeybinding(); - init_hooksConfigManager(); - init_settings2(); - init_stringUtils(); - init_Dialog(); - init_SelectEventMode(); - init_SelectHookMode(); - init_SelectMatcherMode(); - init_ViewHookMode(); - import_compiler_runtime245 = __toESM(require_compiler_runtime(), 1); - import_react174 = __toESM(require_react(), 1); - jsx_dev_runtime311 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/hooks/hooks.tsx -var exports_hooks2 = {}; -__export(exports_hooks2, { - call: () => call47 -}); -var jsx_dev_runtime312, call47 = async (onDone, context7) => { - logEvent("tengu_hooks_command", {}); - const appState = context7.getAppState(); - const permissionContext = appState.toolPermissionContext; - const toolNames = getTools(permissionContext).map((tool) => tool.name); - return /* @__PURE__ */ jsx_dev_runtime312.jsxDEV(HooksConfigMenu, { - toolNames, - onExit: onDone - }, undefined, false, undefined, this); -}; -var init_hooks4 = __esm(() => { - init_HooksConfigMenu(); - init_analytics(); - init_tools2(); - jsx_dev_runtime312 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/hooks/index.ts -var hooks, hooks_default; -var init_hooks5 = __esm(() => { - hooks = { - type: "local-jsx", - name: "hooks", - description: "View hook configurations for tool events", - immediate: true, - load: () => Promise.resolve().then(() => (init_hooks4(), exports_hooks2)) - }; - hooks_default = hooks; -}); - -// src/commands/files/files.ts -var exports_files4 = {}; -__export(exports_files4, { - call: () => call48 -}); -import { relative as relative26 } from "path"; -async function call48(_args, context7) { - const files2 = context7.readFileState ? cacheKeys(context7.readFileState) : []; - if (files2.length === 0) { - return { type: "text", value: "No files in context" }; - } - const fileList = files2.map((file2) => relative26(getCwd(), file2)).join(` -`); - return { type: "text", value: `Files in context: -${fileList}` }; -} -var init_files6 = __esm(() => { - init_cwd(); - init_fileStateCache(); -}); - -// src/commands/files/index.ts -var files2, files_default; -var init_files7 = __esm(() => { - files2 = { - type: "local", - name: "files", - description: "List all files currently in context", - isEnabled: () => process.env.USER_TYPE === "ant", - supportsNonInteractive: true, - load: () => Promise.resolve().then(() => (init_files6(), exports_files4)) - }; - files_default = files2; -}); - -// src/commands/branch/branch.ts -var exports_branch = {}; -__export(exports_branch, { - deriveFirstPrompt: () => deriveFirstPrompt, - call: () => call49 -}); -import { randomUUID as randomUUID33 } from "crypto"; -import { mkdir as mkdir34, readFile as readFile49, writeFile as writeFile39 } from "fs/promises"; -function deriveFirstPrompt(firstUserMessage) { - const content = firstUserMessage?.message?.content; - if (!content) - return "Branched conversation"; - const raw = typeof content === "string" ? content : content.find((block2) => block2.type === "text")?.text; - if (!raw) - return "Branched conversation"; - return raw.replace(/\s+/g, " ").trim().slice(0, 100) || "Branched conversation"; -} -async function createFork(customTitle) { - const forkSessionId = randomUUID33(); - const originalSessionId = getSessionId(); - const projectDir = getProjectDir2(getOriginalCwd()); - const forkSessionPath = getTranscriptPathForSession(forkSessionId); - const currentTranscriptPath = getTranscriptPath(); - await mkdir34(projectDir, { recursive: true, mode: 448 }); - let transcriptContent; - try { - transcriptContent = await readFile49(currentTranscriptPath); - } catch { - throw new Error("No conversation to branch"); - } - if (transcriptContent.length === 0) { - throw new Error("No conversation to branch"); - } - const entries = parseJSONL(transcriptContent); - const mainConversationEntries = entries.filter((entry) => isTranscriptMessage(entry) && !entry.isSidechain); - const contentReplacementRecords = entries.filter((entry) => entry.type === "content-replacement" && entry.sessionId === originalSessionId).flatMap((entry) => entry.replacements); - if (mainConversationEntries.length === 0) { - throw new Error("No messages to branch"); - } - let parentUuid = null; - const lines2 = []; - const serializedMessages = []; - for (const entry of mainConversationEntries) { - const forkedEntry = { - ...entry, - sessionId: forkSessionId, - parentUuid, - isSidechain: false, - forkedFrom: { - sessionId: originalSessionId, - messageUuid: entry.uuid - } - }; - const serialized = { - ...entry, - sessionId: forkSessionId - }; - serializedMessages.push(serialized); - lines2.push(jsonStringify(forkedEntry)); - if (entry.type !== "progress") { - parentUuid = entry.uuid; - } - } - if (contentReplacementRecords.length > 0) { - const forkedReplacementEntry = { - type: "content-replacement", - sessionId: forkSessionId, - replacements: contentReplacementRecords - }; - lines2.push(jsonStringify(forkedReplacementEntry)); - } - await writeFile39(forkSessionPath, lines2.join(` -`) + ` -`, { - encoding: "utf8", - mode: 384 - }); - return { - sessionId: forkSessionId, - title: customTitle, - forkPath: forkSessionPath, - serializedMessages, - contentReplacementRecords - }; -} -async function getUniqueForkName(baseName) { - const candidateName = `${baseName} (Branch)`; - const existingWithExactName = await searchSessionsByCustomTitle(candidateName, { exact: true }); - if (existingWithExactName.length === 0) { - return candidateName; - } - const existingForks = await searchSessionsByCustomTitle(`${baseName} (Branch`); - const usedNumbers = new Set([1]); - const forkNumberPattern = new RegExp(`^${escapeRegExp(baseName)} \\(Branch(?: (\\d+))?\\)$`); - for (const session2 of existingForks) { - const match = session2.customTitle?.match(forkNumberPattern); - if (match) { - if (match[1]) { - usedNumbers.add(parseInt(match[1], 10)); - } else { - usedNumbers.add(1); - } - } - } - let nextNumber = 2; - while (usedNumbers.has(nextNumber)) { - nextNumber++; - } - return `${baseName} (Branch ${nextNumber})`; -} -async function call49(onDone, context7, args) { - const customTitle = args?.trim() || undefined; - const originalSessionId = getSessionId(); - try { - const { - sessionId, - title, - forkPath, - serializedMessages, - contentReplacementRecords - } = await createFork(customTitle); - const now2 = new Date; - const firstPrompt = deriveFirstPrompt(serializedMessages.find((m4) => m4.type === "user")); - const baseName = title ?? firstPrompt; - const effectiveTitle = await getUniqueForkName(baseName); - await saveCustomTitle(sessionId, effectiveTitle, forkPath); - logEvent("tengu_conversation_forked", { - message_count: serializedMessages.length, - has_custom_title: !!title - }); - const forkLog = { - date: now2.toISOString().split("T")[0], - messages: serializedMessages, - fullPath: forkPath, - value: now2.getTime(), - created: now2, - modified: now2, - firstPrompt, - messageCount: serializedMessages.length, - isSidechain: false, - sessionId, - customTitle: effectiveTitle, - contentReplacements: contentReplacementRecords - }; - const titleInfo = title ? ` "${title}"` : ""; - const resumeHint = ` -To resume the original: claude -r ${originalSessionId}`; - const successMessage = `Branched conversation${titleInfo}. You are now in the branch.${resumeHint}`; - if (context7.resume) { - await context7.resume(sessionId, forkLog, "fork"); - onDone(successMessage, { display: "system" }); - } else { - onDone(`Branched conversation${titleInfo}. Resume with: /resume ${sessionId}`); - } - return null; - } catch (error46) { - const message = error46 instanceof Error ? error46.message : "Unknown error occurred"; - onDone(`Failed to branch conversation: ${message}`); - return null; - } -} -var init_branch = __esm(() => { - init_state(); - init_analytics(); - init_json(); - init_sessionStorage(); - init_slowOperations(); - init_stringUtils(); -}); - -// src/commands/branch/index.ts -var branch, branch_default; -var init_branch2 = __esm(() => { - branch = { - type: "local-jsx", - name: "branch", - aliases: ["fork"], - description: "Create a branch of the current conversation at this point", - argumentHint: "[name]", - load: () => Promise.resolve().then(() => (init_branch(), exports_branch)) - }; - branch_default = branch; -}); - -// node_modules/lodash-es/_arrayAggregator.js -function arrayAggregator(array3, setter, iteratee, accumulator) { - var index2 = -1, length = array3 == null ? 0 : array3.length; - while (++index2 < length) { - var value = array3[index2]; - setter(accumulator, value, iteratee(value), array3); - } - return accumulator; -} -var _arrayAggregator_default; -var init__arrayAggregator = __esm(() => { - _arrayAggregator_default = arrayAggregator; -}); - -// node_modules/lodash-es/_baseAggregator.js -function baseAggregator(collection, setter, iteratee, accumulator) { - _baseEach_default(collection, function(value, key2, collection2) { - setter(accumulator, value, iteratee(value), collection2); - }); - return accumulator; -} -var _baseAggregator_default; -var init__baseAggregator = __esm(() => { - init__baseEach(); - _baseAggregator_default = baseAggregator; -}); - -// node_modules/lodash-es/_createAggregator.js -function createAggregator(setter, initializer3) { - return function(collection, iteratee) { - var func = isArray_default(collection) ? _arrayAggregator_default : _baseAggregator_default, accumulator = initializer3 ? initializer3() : {}; - return func(collection, setter, _baseIteratee_default(iteratee, 2), accumulator); - }; -} -var _createAggregator_default; -var init__createAggregator = __esm(() => { - init__arrayAggregator(); - init__baseAggregator(); - init__baseIteratee(); - init_isArray(); - _createAggregator_default = createAggregator; -}); - -// node_modules/lodash-es/partition.js -var partition5, partition_default; -var init_partition = __esm(() => { - init__createAggregator(); - partition5 = _createAggregator_default(function(result, value, key2) { - result[key2 ? 0 : 1].push(value); - }, function() { - return [[], []]; - }); - partition_default = partition5; -}); - -// src/utils/toolPool.ts -function mergeAndFilterTools(initialTools, assembled, mode) { - const [mcp2, builtIn] = partition_default(uniqBy_default([...initialTools, ...assembled], "name"), isMcpTool); - const byName = (a5, b5) => a5.name.localeCompare(b5.name); - const tools = [...builtIn.sort(byName), ...mcp2.sort(byName)]; - if (false) {} - return tools; -} -var init_toolPool = __esm(() => { - init_partition(); - init_uniqBy(); - init_tools(); - init_utils8(); -}); - -// src/hooks/useMergedTools.ts -function useMergedTools(initialTools, mcpTools, toolPermissionContext) { - let replBridgeEnabled = false; - let replBridgeOutboundOnly = false; - return import_react175.useMemo(() => { - const assembled = assembleToolPool(toolPermissionContext, mcpTools); - return mergeAndFilterTools(initialTools, assembled, toolPermissionContext.mode); - }, [ - initialTools, - mcpTools, - toolPermissionContext, - replBridgeEnabled, - replBridgeOutboundOnly - ]); -} -var import_react175; -var init_useMergedTools = __esm(() => { - init_tools2(); - init_toolPool(); - import_react175 = __toESM(require_react(), 1); -}); - -// src/tools/AgentTool/agentDisplay.ts -function resolveAgentOverrides(allAgents, activeAgents) { - const activeMap = new Map; - for (const agent of activeAgents) { - activeMap.set(agent.agentType, agent); - } - const seen = new Set; - const resolved = []; - for (const agent of allAgents) { - const key2 = `${agent.agentType}:${agent.source}`; - if (seen.has(key2)) - continue; - seen.add(key2); - const active = activeMap.get(agent.agentType); - const overriddenBy = active && active.source !== agent.source ? active.source : undefined; - resolved.push({ ...agent, overriddenBy }); - } - return resolved; -} -function resolveAgentModelDisplay(agent) { - const model = agent.model || getDefaultSubagentModel(); - if (!model) - return; - return model === "inherit" ? "inherit" : model; -} -function getOverrideSourceLabel(source) { - return getSourceDisplayName(source).toLowerCase(); -} -function compareAgentsByName(a5, b5) { - return a5.agentType.localeCompare(b5.agentType, undefined, { - sensitivity: "base" - }); -} -var AGENT_SOURCE_GROUPS; -var init_agentDisplay = __esm(() => { - init_agent(); - init_constants2(); - AGENT_SOURCE_GROUPS = [ - { label: "User agents", source: "userSettings" }, - { label: "Project agents", source: "projectSettings" }, - { label: "Local agents", source: "localSettings" }, - { label: "Managed agents", source: "policySettings" }, - { label: "Plugin agents", source: "plugin" }, - { label: "CLI arg agents", source: "flagSettings" }, - { label: "Built-in agents", source: "built-in" } - ]; -}); - -// src/components/agents/types.ts -var AGENT_PATHS; -var init_types24 = __esm(() => { - AGENT_PATHS = { - FOLDER_NAME: ".claude", - AGENTS_DIR: "agents" - }; -}); - -// src/components/agents/agentFileUtils.ts -import { mkdir as mkdir35, open as open14, unlink as unlink19 } from "fs/promises"; -import { join as join129 } from "path"; -function formatAgentAsMarkdown(agentType, whenToUse, tools, systemPrompt, color3, model, memory2, effort) { - const escapedWhenToUse = whenToUse.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\\\n"); - const isAllTools = tools === undefined || tools.length === 1 && tools[0] === "*"; - const toolsLine = isAllTools ? "" : ` -tools: ${tools.join(", ")}`; - const modelLine = model ? ` -model: ${model}` : ""; - const effortLine = effort !== undefined ? ` -effort: ${effort}` : ""; - const colorLine = color3 ? ` -color: ${color3}` : ""; - const memoryLine = memory2 ? ` -memory: ${memory2}` : ""; - return `--- -name: ${agentType} -description: "${escapedWhenToUse}"${toolsLine}${modelLine}${effortLine}${colorLine}${memoryLine} ---- - -${systemPrompt} -`; -} -function getAgentDirectoryPath(location) { - switch (location) { - case "flagSettings": - throw new Error(`Cannot get directory path for ${location} agents`); - case "userSettings": - return join129(getClaudeConfigHomeDir(), AGENT_PATHS.AGENTS_DIR); - case "projectSettings": - return join129(getCwd(), AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR); - case "policySettings": - return join129(getManagedFilePath(), AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR); - case "localSettings": - return join129(getCwd(), AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR); - } -} -function getRelativeAgentDirectoryPath(location) { - switch (location) { - case "projectSettings": - return join129(".", AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR); - default: - return getAgentDirectoryPath(location); - } -} -function getNewAgentFilePath(agent) { - const dirPath = getAgentDirectoryPath(agent.source); - return join129(dirPath, `${agent.agentType}.md`); -} -function getActualAgentFilePath(agent) { - if (agent.source === "built-in") { - return "Built-in"; - } - if (agent.source === "plugin") { - throw new Error("Cannot get file path for plugin agents"); - } - const dirPath = getAgentDirectoryPath(agent.source); - const filename = agent.filename || agent.agentType; - return join129(dirPath, `${filename}.md`); -} -function getNewRelativeAgentFilePath(agent) { - if (agent.source === "built-in") { - return "Built-in"; - } - const dirPath = getRelativeAgentDirectoryPath(agent.source); - return join129(dirPath, `${agent.agentType}.md`); -} -function getActualRelativeAgentFilePath(agent) { - if (isBuiltInAgent(agent)) { - return "Built-in"; - } - if (isPluginAgent(agent)) { - return `Plugin: ${agent.plugin || "Unknown"}`; - } - if (agent.source === "flagSettings") { - return "CLI argument"; - } - const dirPath = getRelativeAgentDirectoryPath(agent.source); - const filename = agent.filename || agent.agentType; - return join129(dirPath, `${filename}.md`); -} -async function ensureAgentDirectoryExists(source) { - const dirPath = getAgentDirectoryPath(source); - await mkdir35(dirPath, { recursive: true }); - return dirPath; -} -async function saveAgentToFile(source, agentType, whenToUse, tools, systemPrompt, checkExists = true, color3, model, memory2, effort) { - if (source === "built-in") { - throw new Error("Cannot save built-in agents"); - } - await ensureAgentDirectoryExists(source); - const filePath = getNewAgentFilePath({ source, agentType }); - const content = formatAgentAsMarkdown(agentType, whenToUse, tools, systemPrompt, color3, model, memory2, effort); - try { - await writeFileAndFlush(filePath, content, checkExists ? "wx" : "w"); - } catch (e4) { - if (getErrnoCode(e4) === "EEXIST") { - throw new Error(`Agent file already exists: ${filePath}`); - } - throw e4; - } -} -async function updateAgentFile(agent, newWhenToUse, newTools, newSystemPrompt, newColor, newModel, newMemory, newEffort) { - if (agent.source === "built-in") { - throw new Error("Cannot update built-in agents"); - } - const filePath = getActualAgentFilePath(agent); - const content = formatAgentAsMarkdown(agent.agentType, newWhenToUse, newTools, newSystemPrompt, newColor, newModel, newMemory, newEffort); - await writeFileAndFlush(filePath, content); -} -async function deleteAgentFromFile(agent) { - if (agent.source === "built-in") { - throw new Error("Cannot delete built-in agents"); - } - const filePath = getActualAgentFilePath(agent); - try { - await unlink19(filePath); - } catch (e4) { - const code = getErrnoCode(e4); - if (code !== "ENOENT") { - throw e4; - } - } -} -async function writeFileAndFlush(filePath, content, flag = "w") { - const handle = await open14(filePath, flag); - try { - await handle.writeFile(content, { encoding: "utf-8" }); - await handle.datasync(); - } finally { - await handle.close(); - } -} -var init_agentFileUtils = __esm(() => { - init_managedPath(); - init_loadAgentsDir(); - init_cwd(); - init_envUtils(); - init_errors(); - init_types24(); -}); - -// src/components/agents/AgentDetail.tsx -function AgentDetail(t0) { - const $2 = import_compiler_runtime246.c(48); - const { - agent, - tools, - onBack - } = t0; - const resolvedTools = resolveAgentTools(agent, tools, false); - let t1; - if ($2[0] !== agent) { - t1 = getActualRelativeAgentFilePath(agent); - $2[0] = agent; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const filePath = t1; - let t22; - if ($2[2] !== agent.agentType) { - t22 = getAgentColor(agent.agentType); - $2[2] = agent.agentType; - $2[3] = t22; - } else { - t22 = $2[3]; - } - const backgroundColor = t22; - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = { - context: "Confirmation" - }; - $2[4] = t32; - } else { - t32 = $2[4]; - } - useKeybinding("confirm:no", onBack, t32); - let t4; - if ($2[5] !== onBack) { - t4 = (e4) => { - if (e4.key === "return") { - e4.preventDefault(); - onBack(); - } - }; - $2[5] = onBack; - $2[6] = t4; - } else { - t4 = $2[6]; - } - const handleKeyDown = t4; - const renderToolsList = function renderToolsList2() { - if (resolvedTools.hasWildcard) { - return /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: "All tools" - }, undefined, false, undefined, this); - } - if (!agent.tools || agent.tools.length === 0) { - return /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: "None" - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(jsx_dev_runtime313.Fragment, { - children: [ - resolvedTools.validTools.length > 0 && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: resolvedTools.validTools.join(", ") - }, undefined, false, undefined, this), - resolvedTools.invalidTools.length > 0 && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - color: "warning", - children: [ - figures_default.warning, - " Unrecognized:", - " ", - resolvedTools.invalidTools.join(", ") - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - }; - const T0 = ThemedBox_default; - const t5 = "column"; - const t6 = 1; - const t7 = 0; - const t8 = true; - let t9; - if ($2[7] !== filePath) { - t9 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - dimColor: true, - children: filePath - }, undefined, false, undefined, this); - $2[7] = filePath; - $2[8] = t9; - } else { - t9 = $2[8]; - } - let t10; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Description" - }, undefined, false, undefined, this), - " (tells Claude when to use this agent):" - ] - }, undefined, true, undefined, this); - $2[9] = t10; - } else { - t10 = $2[9]; - } - let t11; - if ($2[10] !== agent.whenToUse) { - t11 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t10, - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: agent.whenToUse - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[10] = agent.whenToUse; - $2[11] = t11; - } else { - t11 = $2[11]; - } - const T1 = ThemedBox_default; - let t12; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Tools" - }, undefined, false, undefined, this), - ":", - " " - ] - }, undefined, true, undefined, this); - $2[12] = t12; - } else { - t12 = $2[12]; - } - const t13 = renderToolsList(); - let t14; - if ($2[13] !== T1 || $2[14] !== t12 || $2[15] !== t13) { - t14 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(T1, { - children: [ - t12, - t13 - ] - }, undefined, true, undefined, this); - $2[13] = T1; - $2[14] = t12; - $2[15] = t13; - $2[16] = t14; - } else { - t14 = $2[16]; - } - let t15; - if ($2[17] === Symbol.for("react.memo_cache_sentinel")) { - t15 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Model" - }, undefined, false, undefined, this); - $2[17] = t15; - } else { - t15 = $2[17]; - } - let t16; - if ($2[18] !== agent.model) { - t16 = getAgentModelDisplay(agent.model); - $2[18] = agent.model; - $2[19] = t16; - } else { - t16 = $2[19]; - } - let t17; - if ($2[20] !== t16) { - t17 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - t15, - ": ", - t16 - ] - }, undefined, true, undefined, this); - $2[20] = t16; - $2[21] = t17; - } else { - t17 = $2[21]; - } - let t18; - if ($2[22] !== agent.permissionMode) { - t18 = agent.permissionMode && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Permission mode" - }, undefined, false, undefined, this), - ": ", - agent.permissionMode - ] - }, undefined, true, undefined, this); - $2[22] = agent.permissionMode; - $2[23] = t18; - } else { - t18 = $2[23]; - } - let t19; - if ($2[24] !== agent.memory) { - t19 = agent.memory && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Memory" - }, undefined, false, undefined, this), - ": ", - getMemoryScopeDisplay(agent.memory) - ] - }, undefined, true, undefined, this); - $2[24] = agent.memory; - $2[25] = t19; - } else { - t19 = $2[25]; - } - let t20; - if ($2[26] !== agent.hooks) { - t20 = agent.hooks && Object.keys(agent.hooks).length > 0 && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Hooks" - }, undefined, false, undefined, this), - ": ", - Object.keys(agent.hooks).join(", ") - ] - }, undefined, true, undefined, this); - $2[26] = agent.hooks; - $2[27] = t20; - } else { - t20 = $2[27]; - } - let t21; - if ($2[28] !== agent.skills) { - t21 = agent.skills && agent.skills.length > 0 && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Skills" - }, undefined, false, undefined, this), - ":", - " ", - agent.skills.length > 10 ? `${agent.skills.length} skills` : agent.skills.join(", ") - ] - }, undefined, true, undefined, this); - $2[28] = agent.skills; - $2[29] = t21; - } else { - t21 = $2[29]; - } - let t222; - if ($2[30] !== agent.agentType || $2[31] !== backgroundColor) { - t222 = backgroundColor && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "Color" - }, undefined, false, undefined, this), - ":", - " ", - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - backgroundColor, - color: "inverseText", - children: [ - " ", - agent.agentType, - " " - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[30] = agent.agentType; - $2[31] = backgroundColor; - $2[32] = t222; - } else { - t222 = $2[32]; - } - let t23; - if ($2[33] !== agent) { - t23 = !isBuiltInAgent(agent) && /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(jsx_dev_runtime313.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedText, { - bold: true, - children: "System prompt" - }, undefined, false, undefined, this), - ":" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(ThemedBox_default, { - marginLeft: 2, - marginRight: 2, - children: /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(Markdown, { - children: agent.getSystemPrompt() - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[33] = agent; - $2[34] = t23; - } else { - t23 = $2[34]; - } - let t24; - if ($2[35] !== T0 || $2[36] !== handleKeyDown || $2[37] !== t11 || $2[38] !== t14 || $2[39] !== t17 || $2[40] !== t18 || $2[41] !== t19 || $2[42] !== t20 || $2[43] !== t21 || $2[44] !== t222 || $2[45] !== t23 || $2[46] !== t9) { - t24 = /* @__PURE__ */ jsx_dev_runtime313.jsxDEV(T0, { - flexDirection: t5, - gap: t6, - tabIndex: t7, - autoFocus: t8, - onKeyDown: handleKeyDown, - children: [ - t9, - t11, - t14, - t17, - t18, - t19, - t20, - t21, - t222, - t23 - ] - }, undefined, true, undefined, this); - $2[35] = T0; - $2[36] = handleKeyDown; - $2[37] = t11; - $2[38] = t14; - $2[39] = t17; - $2[40] = t18; - $2[41] = t19; - $2[42] = t20; - $2[43] = t21; - $2[44] = t222; - $2[45] = t23; - $2[46] = t9; - $2[47] = t24; - } else { - t24 = $2[47]; - } - return t24; -} -var import_compiler_runtime246, jsx_dev_runtime313; -var init_AgentDetail = __esm(() => { - init_figures(); - init_ink2(); - init_useKeybinding(); - init_agentColorManager(); - init_agentMemory(); - init_agentToolUtils(); - init_loadAgentsDir(); - init_agent(); - init_Markdown(); - init_agentFileUtils(); - import_compiler_runtime246 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime313 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/ColorPicker.tsx -function ColorPicker(t0) { - const $2 = import_compiler_runtime247.c(17); - const { - agentName, - currentColor: t1, - onConfirm - } = t0; - const currentColor = t1 === undefined ? "automatic" : t1; - let t22; - if ($2[0] !== currentColor) { - t22 = COLOR_OPTIONS.findIndex((opt) => opt === currentColor); - $2[0] = currentColor; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const [selectedIndex, setSelectedIndex] = import_react176.useState(Math.max(0, t22)); - let t32; - if ($2[2] !== onConfirm || $2[3] !== selectedIndex) { - t32 = (e4) => { - if (e4.key === "up") { - e4.preventDefault(); - setSelectedIndex(_temp150); - } else { - if (e4.key === "down") { - e4.preventDefault(); - setSelectedIndex(_temp264); - } else { - if (e4.key === "return") { - e4.preventDefault(); - const selected = COLOR_OPTIONS[selectedIndex]; - onConfirm(selected === "automatic" ? undefined : selected); - } - } - } - }; - $2[2] = onConfirm; - $2[3] = selectedIndex; - $2[4] = t32; - } else { - t32 = $2[4]; - } - const handleKeyDown = t32; - const selectedValue = COLOR_OPTIONS[selectedIndex]; - let t4; - if ($2[5] !== selectedIndex) { - t4 = COLOR_OPTIONS.map((option, index2) => { - const isSelected = index2 === selectedIndex; - return /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - color: isSelected ? "suggestion" : undefined, - children: isSelected ? figures_default.pointer : " " - }, undefined, false, undefined, this), - option === "automatic" ? /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - bold: isSelected, - children: "Automatic color" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedBox_default, { - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - backgroundColor: AGENT_COLOR_TO_THEME_COLOR[option], - color: "inverseText", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - bold: isSelected, - children: capitalize(option) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, option, true, undefined, this); - }); - $2[5] = selectedIndex; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: t4 - }, undefined, false, undefined, this); - $2[7] = t4; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - children: "Preview: " - }, undefined, false, undefined, this); - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] !== agentName || $2[11] !== selectedValue) { - t7 = /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: [ - t6, - selectedValue === undefined || selectedValue === "automatic" ? /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - inverse: true, - bold: true, - children: [ - " ", - "@", - agentName, - " " - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedText, { - backgroundColor: AGENT_COLOR_TO_THEME_COLOR[selectedValue], - color: "inverseText", - bold: true, - children: [ - " ", - "@", - agentName, - " " - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[10] = agentName; - $2[11] = selectedValue; - $2[12] = t7; - } else { - t7 = $2[12]; - } - let t8; - if ($2[13] !== handleKeyDown || $2[14] !== t5 || $2[15] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime314.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - tabIndex: 0, - autoFocus: true, - onKeyDown: handleKeyDown, - children: [ - t5, - t7 - ] - }, undefined, true, undefined, this); - $2[13] = handleKeyDown; - $2[14] = t5; - $2[15] = t7; - $2[16] = t8; - } else { - t8 = $2[16]; - } - return t8; -} -function _temp264(prev_0) { - return prev_0 < COLOR_OPTIONS.length - 1 ? prev_0 + 1 : 0; -} -function _temp150(prev) { - return prev > 0 ? prev - 1 : COLOR_OPTIONS.length - 1; -} -var import_compiler_runtime247, import_react176, jsx_dev_runtime314, COLOR_OPTIONS; -var init_ColorPicker = __esm(() => { - init_figures(); - init_ink2(); - init_agentColorManager(); - init_stringUtils(); - import_compiler_runtime247 = __toESM(require_compiler_runtime(), 1); - import_react176 = __toESM(require_react(), 1); - jsx_dev_runtime314 = __toESM(require_jsx_dev_runtime(), 1); - COLOR_OPTIONS = ["automatic", ...AGENT_COLORS]; -}); - -// src/components/agents/ModelSelector.tsx -function ModelSelector(t0) { - const $2 = import_compiler_runtime248.c(11); - const { - initialModel, - onComplete, - onCancel - } = t0; - let t1; - if ($2[0] !== initialModel) { - bb0: { - const base2 = getAgentModelOptions(); - if (initialModel && !base2.some((o5) => o5.value === initialModel)) { - t1 = [{ - value: initialModel, - label: initialModel, - description: "Current model (custom ID)" - }, ...base2]; - break bb0; - } - t1 = base2; - } - $2[0] = initialModel; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const modelOptions = t1; - const defaultModel = initialModel ?? "sonnet"; - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime315.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime315.jsxDEV(ThemedText, { - dimColor: true, - children: "Model determines the agent's reasoning capabilities and speed." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== onCancel || $2[4] !== onComplete) { - t32 = () => onCancel ? onCancel() : onComplete(undefined); - $2[3] = onCancel; - $2[4] = onComplete; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== defaultModel || $2[7] !== modelOptions || $2[8] !== onComplete || $2[9] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime315.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t22, - /* @__PURE__ */ jsx_dev_runtime315.jsxDEV(Select, { - options: modelOptions, - defaultValue: defaultModel, - onChange: onComplete, - onCancel: t32 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = defaultModel; - $2[7] = modelOptions; - $2[8] = onComplete; - $2[9] = t32; - $2[10] = t4; - } else { - t4 = $2[10]; - } - return t4; -} -var import_compiler_runtime248, jsx_dev_runtime315; -var init_ModelSelector = __esm(() => { - init_ink2(); - init_agent(); - init_select(); - import_compiler_runtime248 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime315 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/ToolSelector.tsx -function getToolBuckets() { - return { - READ_ONLY: { - name: "Read-only tools", - toolNames: new Set([GlobTool.name, GrepTool.name, ExitPlanModeV2Tool.name, FileReadTool.name, WebFetchTool.name, TodoWriteTool.name, WebSearchTool.name, TaskStopTool.name, TaskOutputTool.name, ListMcpResourcesTool.name, ReadMcpResourceTool.name]) - }, - EDIT: { - name: "Edit tools", - toolNames: new Set([FileEditTool.name, FileWriteTool.name, NotebookEditTool.name]) - }, - EXECUTION: { - name: "Execution tools", - toolNames: new Set([BashTool.name, undefined].filter((n5) => n5 !== undefined)) - }, - MCP: { - name: "MCP tools", - toolNames: new Set, - isMcp: true - }, - OTHER: { - name: "Other tools", - toolNames: new Set - } - }; -} -function getMcpServerBuckets(tools) { - const serverMap = new Map; - tools.forEach((tool) => { - if (isMcpTool(tool)) { - const mcpInfo = mcpInfoFromString(tool.name); - if (mcpInfo?.serverName) { - const existing = serverMap.get(mcpInfo.serverName) || []; - existing.push(tool); - serverMap.set(mcpInfo.serverName, existing); - } - } - }); - return Array.from(serverMap.entries()).map(([serverName, tools2]) => ({ - serverName, - tools: tools2 - })).sort((a5, b5) => a5.serverName.localeCompare(b5.serverName)); -} -function ToolSelector(t0) { - const $2 = import_compiler_runtime249.c(69); - const { - tools, - initialTools, - onComplete, - onCancel - } = t0; - let t1; - if ($2[0] !== tools) { - t1 = filterToolsForAgent({ - tools, - isBuiltIn: false, - isAsync: false - }); - $2[0] = tools; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const customAgentTools = t1; - let t22; - if ($2[2] !== customAgentTools || $2[3] !== initialTools) { - t22 = !initialTools || initialTools.includes("*") ? customAgentTools.map(_temp151) : initialTools; - $2[2] = customAgentTools; - $2[3] = initialTools; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const expandedInitialTools = t22; - const [selectedTools, setSelectedTools] = import_react177.useState(expandedInitialTools); - const [focusIndex, setFocusIndex] = import_react177.useState(0); - const [showIndividualTools, setShowIndividualTools] = import_react177.useState(false); - let t32; - if ($2[5] !== customAgentTools) { - t32 = new Set(customAgentTools.map(_temp265)); - $2[5] = customAgentTools; - $2[6] = t32; - } else { - t32 = $2[6]; - } - const toolNames = t32; - let t4; - if ($2[7] !== selectedTools || $2[8] !== toolNames) { - let t52; - if ($2[10] !== toolNames) { - t52 = (name3) => toolNames.has(name3); - $2[10] = toolNames; - $2[11] = t52; - } else { - t52 = $2[11]; - } - t4 = selectedTools.filter(t52); - $2[7] = selectedTools; - $2[8] = toolNames; - $2[9] = t4; - } else { - t4 = $2[9]; - } - const validSelectedTools = t4; - let t5; - if ($2[12] !== validSelectedTools) { - t5 = new Set(validSelectedTools); - $2[12] = validSelectedTools; - $2[13] = t5; - } else { - t5 = $2[13]; - } - const selectedSet = t5; - const isAllSelected = validSelectedTools.length === customAgentTools.length && customAgentTools.length > 0; - let t6; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t6 = (toolName) => { - if (!toolName) { - return; - } - setSelectedTools((current) => current.includes(toolName) ? current.filter((t_1) => t_1 !== toolName) : [...current, toolName]); - }; - $2[14] = t6; - } else { - t6 = $2[14]; - } - const handleToggleTool = t6; - let t7; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t7 = (toolNames_0, select2) => { - setSelectedTools((current_0) => { - if (select2) { - const toolsToAdd = toolNames_0.filter((t_2) => !current_0.includes(t_2)); - return [...current_0, ...toolsToAdd]; - } else { - return current_0.filter((t_3) => !toolNames_0.includes(t_3)); - } - }); - }; - $2[15] = t7; - } else { - t7 = $2[15]; - } - const handleToggleTools = t7; - let t8; - if ($2[16] !== customAgentTools || $2[17] !== onComplete || $2[18] !== validSelectedTools) { - t8 = () => { - const allToolNames = customAgentTools.map(_temp339); - const areAllToolsSelected = validSelectedTools.length === allToolNames.length && allToolNames.every((name_0) => validSelectedTools.includes(name_0)); - const finalTools = areAllToolsSelected ? undefined : validSelectedTools; - onComplete(finalTools); - }; - $2[16] = customAgentTools; - $2[17] = onComplete; - $2[18] = validSelectedTools; - $2[19] = t8; - } else { - t8 = $2[19]; - } - const handleConfirm = t8; - let buckets; - if ($2[20] !== customAgentTools) { - const toolBuckets = getToolBuckets(); - buckets = { - readOnly: [], - edit: [], - execution: [], - mcp: [], - other: [] - }; - customAgentTools.forEach((tool) => { - if (isMcpTool(tool)) { - buckets.mcp.push(tool); - } else { - if (toolBuckets.READ_ONLY.toolNames.has(tool.name)) { - buckets.readOnly.push(tool); - } else { - if (toolBuckets.EDIT.toolNames.has(tool.name)) { - buckets.edit.push(tool); - } else { - if (toolBuckets.EXECUTION.toolNames.has(tool.name)) { - buckets.execution.push(tool); - } else { - if (tool.name !== AGENT_TOOL_NAME) { - buckets.other.push(tool); - } - } - } - } - } - }); - $2[20] = customAgentTools; - $2[21] = buckets; - } else { - buckets = $2[21]; - } - const toolsByBucket = buckets; - let t9; - if ($2[22] !== selectedSet) { - t9 = (bucketTools) => { - const selected = count2(bucketTools, (t_5) => selectedSet.has(t_5.name)); - const needsSelection = selected < bucketTools.length; - return () => { - const toolNames_1 = bucketTools.map(_temp429); - handleToggleTools(toolNames_1, needsSelection); - }; - }; - $2[22] = selectedSet; - $2[23] = t9; - } else { - t9 = $2[23]; - } - const createBucketToggleAction = t9; - let navigableItems; - if ($2[24] !== createBucketToggleAction || $2[25] !== customAgentTools || $2[26] !== focusIndex || $2[27] !== handleConfirm || $2[28] !== isAllSelected || $2[29] !== selectedSet || $2[30] !== showIndividualTools || $2[31] !== toolsByBucket.edit || $2[32] !== toolsByBucket.execution || $2[33] !== toolsByBucket.mcp || $2[34] !== toolsByBucket.other || $2[35] !== toolsByBucket.readOnly) { - navigableItems = []; - navigableItems.push({ - id: "continue", - label: "Continue", - action: handleConfirm, - isContinue: true - }); - let t102; - if ($2[37] !== customAgentTools || $2[38] !== isAllSelected) { - t102 = () => { - const allToolNames_0 = customAgentTools.map(_temp521); - handleToggleTools(allToolNames_0, !isAllSelected); - }; - $2[37] = customAgentTools; - $2[38] = isAllSelected; - $2[39] = t102; - } else { - t102 = $2[39]; - } - navigableItems.push({ - id: "bucket-all", - label: `${isAllSelected ? figures_default.checkboxOn : figures_default.checkboxOff} All tools`, - action: t102 - }); - const toolBuckets_0 = getToolBuckets(); - const bucketConfigs = [{ - id: "bucket-readonly", - name: toolBuckets_0.READ_ONLY.name, - tools: toolsByBucket.readOnly - }, { - id: "bucket-edit", - name: toolBuckets_0.EDIT.name, - tools: toolsByBucket.edit - }, { - id: "bucket-execution", - name: toolBuckets_0.EXECUTION.name, - tools: toolsByBucket.execution - }, { - id: "bucket-mcp", - name: toolBuckets_0.MCP.name, - tools: toolsByBucket.mcp - }, { - id: "bucket-other", - name: toolBuckets_0.OTHER.name, - tools: toolsByBucket.other - }]; - bucketConfigs.forEach((t112) => { - const { - id, - name: name_1, - tools: bucketTools_0 - } = t112; - if (bucketTools_0.length === 0) { - return; - } - const selected_0 = count2(bucketTools_0, (t_8) => selectedSet.has(t_8.name)); - const isFullySelected = selected_0 === bucketTools_0.length; - navigableItems.push({ - id, - label: `${isFullySelected ? figures_default.checkboxOn : figures_default.checkboxOff} ${name_1}`, - action: createBucketToggleAction(bucketTools_0) - }); - }); - const toggleButtonIndex = navigableItems.length; - let t122; - if ($2[40] !== focusIndex || $2[41] !== showIndividualTools || $2[42] !== toggleButtonIndex) { - t122 = () => { - setShowIndividualTools(!showIndividualTools); - if (showIndividualTools && focusIndex > toggleButtonIndex) { - setFocusIndex(toggleButtonIndex); - } - }; - $2[40] = focusIndex; - $2[41] = showIndividualTools; - $2[42] = toggleButtonIndex; - $2[43] = t122; - } else { - t122 = $2[43]; - } - navigableItems.push({ - id: "toggle-individual", - label: showIndividualTools ? "Hide advanced options" : "Show advanced options", - action: t122, - isToggle: true - }); - const mcpServerBuckets = getMcpServerBuckets(customAgentTools); - if (showIndividualTools) { - if (mcpServerBuckets.length > 0) { - navigableItems.push({ - id: "mcp-servers-header", - label: "MCP Servers:", - action: _temp618, - isHeader: true - }); - mcpServerBuckets.forEach((t132) => { - const { - serverName, - tools: serverTools - } = t132; - const selected_1 = count2(serverTools, (t_9) => selectedSet.has(t_9.name)); - const isFullySelected_0 = selected_1 === serverTools.length; - navigableItems.push({ - id: `mcp-server-${serverName}`, - label: `${isFullySelected_0 ? figures_default.checkboxOn : figures_default.checkboxOff} ${serverName} (${serverTools.length} ${plural(serverTools.length, "tool")})`, - action: () => { - const toolNames_2 = serverTools.map(_temp714); - handleToggleTools(toolNames_2, !isFullySelected_0); - } - }); - }); - navigableItems.push({ - id: "tools-header", - label: "Individual Tools:", - action: _temp810, - isHeader: true - }); - } - customAgentTools.forEach((tool_0) => { - let displayName = tool_0.name; - if (tool_0.name.startsWith("mcp__")) { - const mcpInfo = mcpInfoFromString(tool_0.name); - displayName = mcpInfo ? `${mcpInfo.toolName} (${mcpInfo.serverName})` : tool_0.name; - } - navigableItems.push({ - id: `tool-${tool_0.name}`, - label: `${selectedSet.has(tool_0.name) ? figures_default.checkboxOn : figures_default.checkboxOff} ${displayName}`, - action: () => handleToggleTool(tool_0.name) - }); - }); - } - $2[24] = createBucketToggleAction; - $2[25] = customAgentTools; - $2[26] = focusIndex; - $2[27] = handleConfirm; - $2[28] = isAllSelected; - $2[29] = selectedSet; - $2[30] = showIndividualTools; - $2[31] = toolsByBucket.edit; - $2[32] = toolsByBucket.execution; - $2[33] = toolsByBucket.mcp; - $2[34] = toolsByBucket.other; - $2[35] = toolsByBucket.readOnly; - $2[36] = navigableItems; - } else { - navigableItems = $2[36]; - } - let t10; - if ($2[44] !== initialTools || $2[45] !== onCancel || $2[46] !== onComplete) { - t10 = () => { - if (onCancel) { - onCancel(); - } else { - onComplete(initialTools); - } - }; - $2[44] = initialTools; - $2[45] = onCancel; - $2[46] = onComplete; - $2[47] = t10; - } else { - t10 = $2[47]; - } - const handleCancel = t10; - let t11; - if ($2[48] === Symbol.for("react.memo_cache_sentinel")) { - t11 = { - context: "Confirmation" - }; - $2[48] = t11; - } else { - t11 = $2[48]; - } - useKeybinding("confirm:no", handleCancel, t11); - let t12; - if ($2[49] !== focusIndex || $2[50] !== navigableItems) { - t12 = (e4) => { - if (e4.key === "return") { - e4.preventDefault(); - const item = navigableItems[focusIndex]; - if (item && !item.isHeader) { - item.action(); - } - } else { - if (e4.key === "up") { - e4.preventDefault(); - let newIndex = focusIndex - 1; - while (newIndex > 0 && navigableItems[newIndex]?.isHeader) { - newIndex--; - } - setFocusIndex(Math.max(0, newIndex)); - } else { - if (e4.key === "down") { - e4.preventDefault(); - let newIndex_0 = focusIndex + 1; - while (newIndex_0 < navigableItems.length - 1 && navigableItems[newIndex_0]?.isHeader) { - newIndex_0++; - } - setFocusIndex(Math.min(navigableItems.length - 1, newIndex_0)); - } - } - } - }; - $2[49] = focusIndex; - $2[50] = navigableItems; - $2[51] = t12; - } else { - t12 = $2[51]; - } - const handleKeyDown = t12; - const t13 = focusIndex === 0 ? "suggestion" : undefined; - const t14 = focusIndex === 0; - const t15 = focusIndex === 0 ? `${figures_default.pointer} ` : " "; - let t16; - if ($2[52] !== t13 || $2[53] !== t14 || $2[54] !== t15) { - t16 = /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(ThemedText, { - color: t13, - bold: t14, - children: [ - t15, - "[ Continue ]" - ] - }, undefined, true, undefined, this); - $2[52] = t13; - $2[53] = t14; - $2[54] = t15; - $2[55] = t16; - } else { - t16 = $2[55]; - } - let t17; - if ($2[56] === Symbol.for("react.memo_cache_sentinel")) { - t17 = /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(Divider, { - width: 40 - }, undefined, false, undefined, this); - $2[56] = t17; - } else { - t17 = $2[56]; - } - let t18; - if ($2[57] !== navigableItems) { - t18 = navigableItems.slice(1); - $2[57] = navigableItems; - $2[58] = t18; - } else { - t18 = $2[58]; - } - let t19; - if ($2[59] !== focusIndex || $2[60] !== t18) { - t19 = t18.map((item_0, index2) => { - const isCurrentlyFocused = index2 + 1 === focusIndex; - const isToggleButton = item_0.isToggle; - const isHeader = item_0.isHeader; - return /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(import_react177.default.Fragment, { - children: [ - isToggleButton && /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(Divider, { - width: 40 - }, undefined, false, undefined, this), - isHeader && index2 > 0 && /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(ThemedBox_default, { - marginTop: 1 - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(ThemedText, { - color: isHeader ? undefined : isCurrentlyFocused ? "suggestion" : undefined, - dimColor: isHeader, - bold: isToggleButton && isCurrentlyFocused, - children: [ - isHeader ? "" : isCurrentlyFocused ? `${figures_default.pointer} ` : " ", - isToggleButton ? `[ ${item_0.label} ]` : item_0.label - ] - }, undefined, true, undefined, this) - ] - }, item_0.id, true, undefined, this); - }); - $2[59] = focusIndex; - $2[60] = t18; - $2[61] = t19; - } else { - t19 = $2[61]; - } - const t20 = isAllSelected ? "All tools selected" : `${selectedSet.size} of ${customAgentTools.length} tools selected`; - let t21; - if ($2[62] !== t20) { - t21 = /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(ThemedText, { - dimColor: true, - children: t20 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[62] = t20; - $2[63] = t21; - } else { - t21 = $2[63]; - } - let t222; - if ($2[64] !== handleKeyDown || $2[65] !== t16 || $2[66] !== t19 || $2[67] !== t21) { - t222 = /* @__PURE__ */ jsx_dev_runtime316.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - tabIndex: 0, - autoFocus: true, - onKeyDown: handleKeyDown, - children: [ - t16, - t17, - t19, - t21 - ] - }, undefined, true, undefined, this); - $2[64] = handleKeyDown; - $2[65] = t16; - $2[66] = t19; - $2[67] = t21; - $2[68] = t222; - } else { - t222 = $2[68]; - } - return t222; -} -function _temp810() {} -function _temp714(t_10) { - return t_10.name; -} -function _temp618() {} -function _temp521(t_7) { - return t_7.name; -} -function _temp429(t_6) { - return t_6.name; -} -function _temp339(t_4) { - return t_4.name; -} -function _temp265(t_0) { - return t_0.name; -} -function _temp151(t4) { - return t4.name; -} -var import_compiler_runtime249, import_react177, jsx_dev_runtime316; -var init_ToolSelector = __esm(() => { - init_figures(); - init_mcpStringUtils(); - init_utils8(); - init_agentToolUtils(); - init_constants3(); - init_BashTool(); - init_ExitPlanModeV2Tool(); - init_FileEditTool(); - init_FileReadTool(); - init_FileWriteTool(); - init_GlobTool(); - init_GrepTool(); - init_ListMcpResourcesTool(); - init_NotebookEditTool(); - init_ReadMcpResourceTool(); - init_TaskOutputTool(); - init_TaskStopTool(); - init_TodoWriteTool(); - init_WebFetchTool(); - init_WebSearchTool(); - init_ink2(); - init_useKeybinding(); - init_stringUtils(); - init_Divider(); - import_compiler_runtime249 = __toESM(require_compiler_runtime(), 1); - import_react177 = __toESM(require_react(), 1); - jsx_dev_runtime316 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/utils.ts -function getAgentSourceDisplayName(source) { - if (source === "all") { - return "Agents"; - } - if (source === "built-in") { - return "Built-in agents"; - } - if (source === "plugin") { - return "Plugin agents"; - } - return capitalize_default(getSettingSourceName(source)); -} -var init_utils15 = __esm(() => { - init_capitalize(); - init_constants2(); -}); - -// src/components/agents/AgentEditor.tsx -function AgentEditor({ - agent, - tools, - onSaved, - onBack -}) { - const setAppState = useSetAppState(); - const [editMode, setEditMode] = import_react178.useState("menu"); - const [selectedMenuIndex, setSelectedMenuIndex] = import_react178.useState(0); - const [error46, setError] = import_react178.useState(null); - const [selectedColor, setSelectedColor] = import_react178.useState(agent.color); - const handleOpenInEditor = import_react178.useCallback(async () => { - const filePath = getActualAgentFilePath(agent); - const result = await editFileInEditor(filePath); - if (result.error) { - setError(result.error); - } else { - onSaved(`Opened ${agent.agentType} in editor. If you made edits, restart to load the latest version.`); - } - }, [agent, onSaved]); - const handleSave = import_react178.useCallback(async (changes = {}) => { - const { - tools: newTools, - color: newColor, - model: newModel - } = changes; - const finalColor = newColor ?? selectedColor; - const hasToolsChanged = newTools !== undefined; - const hasModelChanged = newModel !== undefined; - const hasColorChanged = finalColor !== agent.color; - if (!hasToolsChanged && !hasModelChanged && !hasColorChanged) { - return false; - } - try { - if (!isCustomAgent(agent) && !isPluginAgent(agent)) { - return false; - } - await updateAgentFile(agent, agent.whenToUse, newTools ?? agent.tools, agent.getSystemPrompt(), finalColor, newModel ?? agent.model); - if (hasColorChanged && finalColor) { - setAgentColor(agent.agentType, finalColor); - } - setAppState((state3) => { - const allAgents = state3.agentDefinitions.allAgents.map((a5) => a5.agentType === agent.agentType ? { - ...a5, - tools: newTools ?? a5.tools, - color: finalColor, - model: newModel ?? a5.model - } : a5); - return { - ...state3, - agentDefinitions: { - ...state3.agentDefinitions, - activeAgents: getActiveAgentsFromList(allAgents), - allAgents - } - }; - }); - onSaved(`Updated agent: ${source_default.bold(agent.agentType)}`); - return true; - } catch (err2) { - setError(err2 instanceof Error ? err2.message : "Failed to save agent"); - return false; - } - }, [agent, selectedColor, onSaved, setAppState]); - const menuItems = import_react178.useMemo(() => [{ - label: "Open in editor", - action: handleOpenInEditor - }, { - label: "Edit tools", - action: () => setEditMode("edit-tools") - }, { - label: "Edit model", - action: () => setEditMode("edit-model") - }, { - label: "Edit color", - action: () => setEditMode("edit-color") - }], [handleOpenInEditor]); - const handleEscape = import_react178.useCallback(() => { - setError(null); - if (editMode === "menu") { - onBack(); - } else { - setEditMode("menu"); - } - }, [editMode, onBack]); - const handleMenuKeyDown = import_react178.useCallback((e4) => { - if (e4.key === "up") { - e4.preventDefault(); - setSelectedMenuIndex((index2) => Math.max(0, index2 - 1)); - } else if (e4.key === "down") { - e4.preventDefault(); - setSelectedMenuIndex((index_0) => Math.min(menuItems.length - 1, index_0 + 1)); - } else if (e4.key === "return") { - e4.preventDefault(); - const selectedItem = menuItems[selectedMenuIndex]; - if (selectedItem) { - selectedItem.action(); - } - } - }, [menuItems, selectedMenuIndex]); - useKeybinding("confirm:no", handleEscape, { - context: "Confirmation" - }); - const renderMenu = () => /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ThemedBox_default, { - flexDirection: "column", - tabIndex: 0, - autoFocus: true, - onKeyDown: handleMenuKeyDown, - children: [ - /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Source: ", - getAgentSourceDisplayName(agent.source) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: menuItems.map((item, index_1) => /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ThemedText, { - color: index_1 === selectedMenuIndex ? "suggestion" : undefined, - children: [ - index_1 === selectedMenuIndex ? `${figures_default.pointer} ` : " ", - item.label - ] - }, item.label, true, undefined, this)) - }, undefined, false, undefined, this), - error46 && /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - switch (editMode) { - case "menu": - return renderMenu(); - case "edit-tools": - return /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ToolSelector, { - tools, - initialTools: agent.tools, - onComplete: async (finalTools) => { - setEditMode("menu"); - await handleSave({ - tools: finalTools - }); - } - }, undefined, false, undefined, this); - case "edit-color": - return /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ColorPicker, { - agentName: agent.agentType, - currentColor: selectedColor || agent.color || "automatic", - onConfirm: async (color3) => { - setSelectedColor(color3); - setEditMode("menu"); - await handleSave({ - color: color3 - }); - } - }, undefined, false, undefined, this); - case "edit-model": - return /* @__PURE__ */ jsx_dev_runtime317.jsxDEV(ModelSelector, { - initialModel: agent.model, - onComplete: async (model) => { - setEditMode("menu"); - await handleSave({ - model - }); - } - }, undefined, false, undefined, this); - default: - return null; - } -} -var import_react178, jsx_dev_runtime317; -var init_AgentEditor = __esm(() => { - init_source(); - init_figures(); - init_AppState(); - init_ink2(); - init_useKeybinding(); - init_agentColorManager(); - init_loadAgentsDir(); - init_promptEditor(); - init_agentFileUtils(); - init_ColorPicker(); - init_ModelSelector(); - init_ToolSelector(); - init_utils15(); - import_react178 = __toESM(require_react(), 1); - jsx_dev_runtime317 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/AgentNavigationFooter.tsx -function AgentNavigationFooter(t0) { - const $2 = import_compiler_runtime250.c(2); - const { - instructions: t1 - } = t0; - const instructions = t1 === undefined ? "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to go back" : t1; - const exitState = useExitOnCtrlCDWithKeybindings(); - const t22 = exitState.pending ? `Press ${exitState.keyName} again to exit` : instructions; - let t32; - if ($2[0] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime318.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime318.jsxDEV(ThemedText, { - dimColor: true, - children: t22 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = t22; - $2[1] = t32; - } else { - t32 = $2[1]; - } - return t32; -} -var import_compiler_runtime250, jsx_dev_runtime318; -var init_AgentNavigationFooter = __esm(() => { - init_useExitOnCtrlCDWithKeybindings(); - init_ink2(); - import_compiler_runtime250 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime318 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/AgentsList.tsx -function AgentsList(t0) { - const $2 = import_compiler_runtime251.c(96); - const { - source, - agents, - onBack, - onSelect, - onCreateNew, - changes - } = t0; - const [selectedAgent, setSelectedAgent] = React96.useState(null); - const [isCreateNewSelected, setIsCreateNewSelected] = React96.useState(true); - let t1; - if ($2[0] !== agents) { - t1 = [...agents].sort(compareAgentsByName); - $2[0] = agents; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const sortedAgents = t1; - const getOverrideInfo = _temp153; - let t22; - if ($2[2] !== isCreateNewSelected) { - t22 = () => /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - color: isCreateNewSelected ? "suggestion" : undefined, - children: isCreateNewSelected ? `${figures_default.pointer} ` : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - color: isCreateNewSelected ? "suggestion" : undefined, - children: "Create new agent" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = isCreateNewSelected; - $2[3] = t22; - } else { - t22 = $2[3]; - } - const renderCreateNewOption = t22; - let t32; - if ($2[4] !== isCreateNewSelected || $2[5] !== selectedAgent?.agentType || $2[6] !== selectedAgent?.source) { - t32 = (agent_0) => { - const isBuiltIn = agent_0.source === "built-in"; - const isSelected = !isBuiltIn && !isCreateNewSelected && selectedAgent?.agentType === agent_0.agentType && selectedAgent?.source === agent_0.source; - const { - isOverridden, - overriddenBy - } = getOverrideInfo(agent_0); - const dimmed = isBuiltIn || isOverridden; - const textColor = !isBuiltIn && isSelected ? "suggestion" : undefined; - const resolvedModel = resolveAgentModelDisplay(agent_0); - return /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: dimmed && !isSelected, - color: textColor, - children: isBuiltIn ? "" : isSelected ? `${figures_default.pointer} ` : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: dimmed && !isSelected, - color: textColor, - children: agent_0.agentType - }, undefined, false, undefined, this), - resolvedModel && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - color: textColor, - children: [ - " \xB7 ", - resolvedModel - ] - }, undefined, true, undefined, this), - agent_0.memory && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - color: textColor, - children: [ - " \xB7 ", - agent_0.memory, - " memory" - ] - }, undefined, true, undefined, this), - overriddenBy && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: !isSelected, - color: isSelected ? "warning" : undefined, - children: [ - " ", - figures_default.warning, - " shadowed by ", - getOverrideSourceLabel(overriddenBy) - ] - }, undefined, true, undefined, this) - ] - }, `${agent_0.agentType}-${agent_0.source}`, true, undefined, this); - }; - $2[4] = isCreateNewSelected; - $2[5] = selectedAgent?.agentType; - $2[6] = selectedAgent?.source; - $2[7] = t32; - } else { - t32 = $2[7]; - } - const renderAgent = t32; - let t4; - if ($2[8] !== sortedAgents || $2[9] !== source) { - bb0: { - const nonBuiltIn = sortedAgents.filter(_temp266); - if (source === "all") { - t4 = AGENT_SOURCE_GROUPS.filter(_temp340).flatMap((t52) => { - const { - source: groupSource - } = t52; - return nonBuiltIn.filter((a_0) => a_0.source === groupSource); - }); - break bb0; - } - t4 = nonBuiltIn; - } - $2[8] = sortedAgents; - $2[9] = source; - $2[10] = t4; - } else { - t4 = $2[10]; - } - const selectableAgentsInOrder = t4; - let t5; - let t6; - if ($2[11] !== isCreateNewSelected || $2[12] !== onCreateNew || $2[13] !== selectableAgentsInOrder || $2[14] !== selectedAgent) { - t5 = () => { - if (!selectedAgent && !isCreateNewSelected && selectableAgentsInOrder.length > 0) { - if (onCreateNew) { - setIsCreateNewSelected(true); - } else { - setSelectedAgent(selectableAgentsInOrder[0] || null); - } - } - }; - t6 = [selectableAgentsInOrder, selectedAgent, isCreateNewSelected, onCreateNew]; - $2[11] = isCreateNewSelected; - $2[12] = onCreateNew; - $2[13] = selectableAgentsInOrder; - $2[14] = selectedAgent; - $2[15] = t5; - $2[16] = t6; - } else { - t5 = $2[15]; - t6 = $2[16]; - } - React96.useEffect(t5, t6); - let t7; - if ($2[17] !== isCreateNewSelected || $2[18] !== onCreateNew || $2[19] !== onSelect || $2[20] !== selectableAgentsInOrder || $2[21] !== selectedAgent) { - t7 = (e4) => { - if (e4.key === "return") { - e4.preventDefault(); - if (isCreateNewSelected && onCreateNew) { - onCreateNew(); - } else { - if (selectedAgent) { - onSelect(selectedAgent); - } - } - return; - } - if (e4.key !== "up" && e4.key !== "down") { - return; - } - e4.preventDefault(); - const hasCreateOption = !!onCreateNew; - const totalItems = selectableAgentsInOrder.length + (hasCreateOption ? 1 : 0); - if (totalItems === 0) { - return; - } - let currentPosition = 0; - if (!isCreateNewSelected && selectedAgent) { - const agentIndex = selectableAgentsInOrder.findIndex((a_1) => a_1.agentType === selectedAgent.agentType && a_1.source === selectedAgent.source); - if (agentIndex >= 0) { - currentPosition = hasCreateOption ? agentIndex + 1 : agentIndex; - } - } - const newPosition = e4.key === "up" ? currentPosition === 0 ? totalItems - 1 : currentPosition - 1 : currentPosition === totalItems - 1 ? 0 : currentPosition + 1; - if (hasCreateOption && newPosition === 0) { - setIsCreateNewSelected(true); - setSelectedAgent(null); - } else { - const agentIndex_0 = hasCreateOption ? newPosition - 1 : newPosition; - const newAgent = selectableAgentsInOrder[agentIndex_0]; - if (newAgent) { - setIsCreateNewSelected(false); - setSelectedAgent(newAgent); - } - } - }; - $2[17] = isCreateNewSelected; - $2[18] = onCreateNew; - $2[19] = onSelect; - $2[20] = selectableAgentsInOrder; - $2[21] = selectedAgent; - $2[22] = t7; - } else { - t7 = $2[22]; - } - const handleKeyDown = t7; - let t8; - if ($2[23] !== renderAgent || $2[24] !== sortedAgents) { - t8 = (t92) => { - const title = t92 === undefined ? "Built-in (always available):" : t92; - const builtInAgents = sortedAgents.filter(_temp430); - return /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - paddingLeft: 2, - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: title - }, undefined, false, undefined, this), - builtInAgents.map(renderAgent) - ] - }, undefined, true, undefined, this); - }; - $2[23] = renderAgent; - $2[24] = sortedAgents; - $2[25] = t8; - } else { - t8 = $2[25]; - } - const renderBuiltInAgentsSection = t8; - let t9; - if ($2[26] !== renderAgent) { - t9 = (title_0, groupAgents) => { - if (!groupAgents.length) { - return null; - } - const folderPath = groupAgents[0]?.baseDir; - return /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - paddingLeft: 2, - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: title_0 - }, undefined, false, undefined, this), - folderPath && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " (", - folderPath, - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - groupAgents.map((agent_1) => renderAgent(agent_1)) - ] - }, undefined, true, undefined, this); - }; - $2[26] = renderAgent; - $2[27] = t9; - } else { - t9 = $2[27]; - } - const renderAgentGroup = t9; - let t10; - if ($2[28] !== source) { - t10 = getAgentSourceDisplayName(source); - $2[28] = source; - $2[29] = t10; - } else { - t10 = $2[29]; - } - const sourceTitle = t10; - let T0; - let T1; - let t11; - let t12; - let t13; - let t14; - let t15; - let t16; - let t17; - let t18; - let t19; - let t20; - let t21; - let t222; - if ($2[30] !== changes || $2[31] !== handleKeyDown || $2[32] !== onBack || $2[33] !== onCreateNew || $2[34] !== renderAgent || $2[35] !== renderAgentGroup || $2[36] !== renderBuiltInAgentsSection || $2[37] !== renderCreateNewOption || $2[38] !== sortedAgents || $2[39] !== source || $2[40] !== sourceTitle) { - t222 = Symbol.for("react.early_return_sentinel"); - bb1: { - const builtInAgents_0 = sortedAgents.filter(_temp522); - const hasNoAgents = !sortedAgents.length || source !== "built-in" && !sortedAgents.some(_temp619); - if (hasNoAgents) { - let t233; - if ($2[55] !== onCreateNew || $2[56] !== renderCreateNewOption) { - t233 = onCreateNew && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - children: renderCreateNewOption() - }, undefined, false, undefined, this); - $2[55] = onCreateNew; - $2[56] = renderCreateNewOption; - $2[57] = t233; - } else { - t233 = $2[57]; - } - let t242; - let t25; - let t26; - if ($2[58] === Symbol.for("react.memo_cache_sentinel")) { - t242 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - children: "No agents found. Create specialized subagents that Claude can delegate to." - }, undefined, false, undefined, this); - t25 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - children: "Each subagent has its own context window, custom system prompt, and specific tools." - }, undefined, false, undefined, this); - t26 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - children: "Try creating: Code Reviewer, Code Simplifier, Security Reviewer, Tech Lead, or UX Reviewer." - }, undefined, false, undefined, this); - $2[58] = t242; - $2[59] = t25; - $2[60] = t26; - } else { - t242 = $2[58]; - t25 = $2[59]; - t26 = $2[60]; - } - let t27; - if ($2[61] !== renderBuiltInAgentsSection || $2[62] !== sortedAgents || $2[63] !== source) { - t27 = source !== "built-in" && sortedAgents.some(_temp715) && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(jsx_dev_runtime319.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(Divider, {}, undefined, false, undefined, this), - renderBuiltInAgentsSection() - ] - }, undefined, true, undefined, this); - $2[61] = renderBuiltInAgentsSection; - $2[62] = sortedAgents; - $2[63] = source; - $2[64] = t27; - } else { - t27 = $2[64]; - } - let t28; - if ($2[65] !== handleKeyDown || $2[66] !== t233 || $2[67] !== t27) { - t28 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - tabIndex: 0, - autoFocus: true, - onKeyDown: handleKeyDown, - children: [ - t233, - t242, - t25, - t26, - t27 - ] - }, undefined, true, undefined, this); - $2[65] = handleKeyDown; - $2[66] = t233; - $2[67] = t27; - $2[68] = t28; - } else { - t28 = $2[68]; - } - let t29; - if ($2[69] !== onBack || $2[70] !== sourceTitle || $2[71] !== t28) { - t29 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(Dialog, { - title: sourceTitle, - subtitle: "No agents found", - onCancel: onBack, - hideInputGuide: true, - children: t28 - }, undefined, false, undefined, this); - $2[69] = onBack; - $2[70] = sourceTitle; - $2[71] = t28; - $2[72] = t29; - } else { - t29 = $2[72]; - } - t222 = t29; - break bb1; - } - T1 = Dialog; - t17 = sourceTitle; - let t232; - if ($2[73] !== sortedAgents) { - t232 = count2(sortedAgents, _temp811); - $2[73] = sortedAgents; - $2[74] = t232; - } else { - t232 = $2[74]; - } - t18 = `${t232} agents`; - t19 = onBack; - t20 = true; - if ($2[75] !== changes) { - t21 = changes && changes.length > 0 && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - children: changes[changes.length - 1] - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[75] = changes; - $2[76] = t21; - } else { - t21 = $2[76]; - } - T0 = ThemedBox_default; - t11 = "column"; - t12 = 0; - t13 = true; - t14 = handleKeyDown; - if ($2[77] !== onCreateNew || $2[78] !== renderCreateNewOption) { - t15 = onCreateNew && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: renderCreateNewOption() - }, undefined, false, undefined, this); - $2[77] = onCreateNew; - $2[78] = renderCreateNewOption; - $2[79] = t15; - } else { - t15 = $2[79]; - } - t16 = source === "all" ? /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(jsx_dev_runtime319.Fragment, { - children: [ - AGENT_SOURCE_GROUPS.filter(_temp910).map((t242) => { - const { - label, - source: groupSource_0 - } = t242; - return /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(React96.Fragment, { - children: renderAgentGroup(label, sortedAgents.filter((a_7) => a_7.source === groupSource_0)) - }, groupSource_0, false, undefined, this); - }), - builtInAgents_0.length > 0 && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - paddingLeft: 2, - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - bold: true, - children: "Built-in agents" - }, undefined, false, undefined, this), - " (always available)" - ] - }, undefined, true, undefined, this), - builtInAgents_0.map(renderAgent) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) : source === "built-in" ? /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(jsx_dev_runtime319.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "Built-in agents are provided by default and cannot be modified." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: sortedAgents.map((agent_2) => renderAgent(agent_2)) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(jsx_dev_runtime319.Fragment, { - children: [ - sortedAgents.filter(_temp04).map((agent_3) => renderAgent(agent_3)), - sortedAgents.some(_temp116) && /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(jsx_dev_runtime319.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(Divider, {}, undefined, false, undefined, this), - renderBuiltInAgentsSection() - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - } - $2[30] = changes; - $2[31] = handleKeyDown; - $2[32] = onBack; - $2[33] = onCreateNew; - $2[34] = renderAgent; - $2[35] = renderAgentGroup; - $2[36] = renderBuiltInAgentsSection; - $2[37] = renderCreateNewOption; - $2[38] = sortedAgents; - $2[39] = source; - $2[40] = sourceTitle; - $2[41] = T0; - $2[42] = T1; - $2[43] = t11; - $2[44] = t12; - $2[45] = t13; - $2[46] = t14; - $2[47] = t15; - $2[48] = t16; - $2[49] = t17; - $2[50] = t18; - $2[51] = t19; - $2[52] = t20; - $2[53] = t21; - $2[54] = t222; - } else { - T0 = $2[41]; - T1 = $2[42]; - t11 = $2[43]; - t12 = $2[44]; - t13 = $2[45]; - t14 = $2[46]; - t15 = $2[47]; - t16 = $2[48]; - t17 = $2[49]; - t18 = $2[50]; - t19 = $2[51]; - t20 = $2[52]; - t21 = $2[53]; - t222 = $2[54]; - } - if (t222 !== Symbol.for("react.early_return_sentinel")) { - return t222; - } - let t23; - if ($2[80] !== T0 || $2[81] !== t11 || $2[82] !== t12 || $2[83] !== t13 || $2[84] !== t14 || $2[85] !== t15 || $2[86] !== t16) { - t23 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(T0, { - flexDirection: t11, - tabIndex: t12, - autoFocus: t13, - onKeyDown: t14, - children: [ - t15, - t16 - ] - }, undefined, true, undefined, this); - $2[80] = T0; - $2[81] = t11; - $2[82] = t12; - $2[83] = t13; - $2[84] = t14; - $2[85] = t15; - $2[86] = t16; - $2[87] = t23; - } else { - t23 = $2[87]; - } - let t24; - if ($2[88] !== T1 || $2[89] !== t17 || $2[90] !== t18 || $2[91] !== t19 || $2[92] !== t20 || $2[93] !== t21 || $2[94] !== t23) { - t24 = /* @__PURE__ */ jsx_dev_runtime319.jsxDEV(T1, { - title: t17, - subtitle: t18, - onCancel: t19, - hideInputGuide: t20, - children: [ - t21, - t23 - ] - }, undefined, true, undefined, this); - $2[88] = T1; - $2[89] = t17; - $2[90] = t18; - $2[91] = t19; - $2[92] = t20; - $2[93] = t21; - $2[94] = t23; - $2[95] = t24; - } else { - t24 = $2[95]; - } - return t24; -} -function _temp116(a_9) { - return a_9.source === "built-in"; -} -function _temp04(a_8) { - return a_8.source !== "built-in"; -} -function _temp910(g_0) { - return g_0.source !== "built-in"; -} -function _temp811(a_6) { - return !a_6.overriddenBy; -} -function _temp715(a_5) { - return a_5.source === "built-in"; -} -function _temp619(a_4) { - return a_4.source !== "built-in"; -} -function _temp522(a_3) { - return a_3.source === "built-in"; -} -function _temp430(a_2) { - return a_2.source === "built-in"; -} -function _temp340(g4) { - return g4.source !== "built-in"; -} -function _temp266(a5) { - return a5.source !== "built-in"; -} -function _temp153(agent) { - return { - isOverridden: !!agent.overriddenBy, - overriddenBy: agent.overriddenBy || null - }; -} -var import_compiler_runtime251, React96, jsx_dev_runtime319; -var init_AgentsList = __esm(() => { - init_figures(); - init_ink2(); - init_agentDisplay(); - init_Dialog(); - init_Divider(); - init_utils15(); - import_compiler_runtime251 = __toESM(require_compiler_runtime(), 1); - React96 = __toESM(require_react(), 1); - jsx_dev_runtime319 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/wizard/WizardProvider.tsx -function WizardProvider(t0) { - const $2 = import_compiler_runtime252.c(38); - const { - steps, - initialData: t1, - onComplete, - onCancel, - children, - title, - showStepCounter: t22 - } = t0; - let t32; - if ($2[0] !== t1) { - t32 = t1 === undefined ? {} : t1; - $2[0] = t1; - $2[1] = t32; - } else { - t32 = $2[1]; - } - const initialData = t32; - const showStepCounter = t22 === undefined ? true : t22; - const [currentStepIndex, setCurrentStepIndex] = import_react179.useState(0); - const [wizardData, setWizardData] = import_react179.useState(initialData); - const [isCompleted, setIsCompleted] = import_react179.useState(false); - let t4; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t4 = []; - $2[2] = t4; - } else { - t4 = $2[2]; - } - const [navigationHistory, setNavigationHistory] = import_react179.useState(t4); - useExitOnCtrlCDWithKeybindings(); - let t5; - let t6; - if ($2[3] !== isCompleted || $2[4] !== onComplete || $2[5] !== wizardData) { - t5 = () => { - if (isCompleted) { - setNavigationHistory([]); - onComplete(wizardData); - } - }; - t6 = [isCompleted, wizardData, onComplete]; - $2[3] = isCompleted; - $2[4] = onComplete; - $2[5] = wizardData; - $2[6] = t5; - $2[7] = t6; - } else { - t5 = $2[6]; - t6 = $2[7]; - } - import_react179.useEffect(t5, t6); - let t7; - if ($2[8] !== currentStepIndex || $2[9] !== navigationHistory || $2[10] !== steps.length) { - t7 = () => { - if (currentStepIndex < steps.length - 1) { - if (navigationHistory.length > 0) { - setNavigationHistory((prev) => [...prev, currentStepIndex]); - } - setCurrentStepIndex(_temp155); - } else { - setIsCompleted(true); - } - }; - $2[8] = currentStepIndex; - $2[9] = navigationHistory; - $2[10] = steps.length; - $2[11] = t7; - } else { - t7 = $2[11]; - } - const goNext = t7; - let t8; - if ($2[12] !== currentStepIndex || $2[13] !== navigationHistory || $2[14] !== onCancel) { - t8 = () => { - if (navigationHistory.length > 0) { - const previousStep = navigationHistory[navigationHistory.length - 1]; - if (previousStep !== undefined) { - setNavigationHistory(_temp267); - setCurrentStepIndex(previousStep); - } - } else { - if (currentStepIndex > 0) { - setCurrentStepIndex(_temp341); - } else { - if (onCancel) { - onCancel(); - } - } - } - }; - $2[12] = currentStepIndex; - $2[13] = navigationHistory; - $2[14] = onCancel; - $2[15] = t8; - } else { - t8 = $2[15]; - } - const goBack = t8; - let t9; - if ($2[16] !== currentStepIndex || $2[17] !== steps.length) { - t9 = (index2) => { - if (index2 >= 0 && index2 < steps.length) { - setNavigationHistory((prev_3) => [...prev_3, currentStepIndex]); - setCurrentStepIndex(index2); - } - }; - $2[16] = currentStepIndex; - $2[17] = steps.length; - $2[18] = t9; - } else { - t9 = $2[18]; - } - const goToStep = t9; - let t10; - if ($2[19] !== onCancel) { - t10 = () => { - setNavigationHistory([]); - if (onCancel) { - onCancel(); - } - }; - $2[19] = onCancel; - $2[20] = t10; - } else { - t10 = $2[20]; - } - const cancel = t10; - let t11; - if ($2[21] === Symbol.for("react.memo_cache_sentinel")) { - t11 = (updates) => { - setWizardData((prev_4) => ({ - ...prev_4, - ...updates - })); - }; - $2[21] = t11; - } else { - t11 = $2[21]; - } - const updateWizardData = t11; - let t12; - if ($2[22] !== cancel || $2[23] !== currentStepIndex || $2[24] !== goBack || $2[25] !== goNext || $2[26] !== goToStep || $2[27] !== showStepCounter || $2[28] !== steps.length || $2[29] !== title || $2[30] !== wizardData) { - t12 = { - currentStepIndex, - totalSteps: steps.length, - wizardData, - setWizardData, - updateWizardData, - goNext, - goBack, - goToStep, - cancel, - title, - showStepCounter - }; - $2[22] = cancel; - $2[23] = currentStepIndex; - $2[24] = goBack; - $2[25] = goNext; - $2[26] = goToStep; - $2[27] = showStepCounter; - $2[28] = steps.length; - $2[29] = title; - $2[30] = wizardData; - $2[31] = t12; - } else { - t12 = $2[31]; - } - const contextValue = t12; - const CurrentStepComponent = steps[currentStepIndex]; - if (!CurrentStepComponent || isCompleted) { - return null; - } - let t13; - if ($2[32] !== CurrentStepComponent || $2[33] !== children) { - t13 = children || /* @__PURE__ */ jsx_dev_runtime320.jsxDEV(CurrentStepComponent, {}, undefined, false, undefined, this); - $2[32] = CurrentStepComponent; - $2[33] = children; - $2[34] = t13; - } else { - t13 = $2[34]; - } - let t14; - if ($2[35] !== contextValue || $2[36] !== t13) { - t14 = /* @__PURE__ */ jsx_dev_runtime320.jsxDEV(WizardContext.Provider, { - value: contextValue, - children: t13 - }, undefined, false, undefined, this); - $2[35] = contextValue; - $2[36] = t13; - $2[37] = t14; - } else { - t14 = $2[37]; - } - return t14; -} -function _temp341(prev_2) { - return prev_2 - 1; -} -function _temp267(prev_1) { - return prev_1.slice(0, -1); -} -function _temp155(prev_0) { - return prev_0 + 1; -} -var import_compiler_runtime252, import_react179, jsx_dev_runtime320, WizardContext; -var init_WizardProvider = __esm(() => { - init_useExitOnCtrlCDWithKeybindings(); - import_compiler_runtime252 = __toESM(require_compiler_runtime(), 1); - import_react179 = __toESM(require_react(), 1); - jsx_dev_runtime320 = __toESM(require_jsx_dev_runtime(), 1); - WizardContext = import_react179.createContext(null); -}); - -// src/components/wizard/useWizard.ts -function useWizard() { - const context7 = import_react180.useContext(WizardContext); - if (!context7) { - throw new Error("useWizard must be used within a WizardProvider"); - } - return context7; -} -var import_react180; -var init_useWizard = __esm(() => { - init_WizardProvider(); - import_react180 = __toESM(require_react(), 1); -}); - -// src/components/wizard/WizardNavigationFooter.tsx -function WizardNavigationFooter({ - instructions = /* @__PURE__ */ jsx_dev_runtime321.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime321.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime321.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime321.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) -}) { - const exitState = useExitOnCtrlCDWithKeybindings(); - return /* @__PURE__ */ jsx_dev_runtime321.jsxDEV(ThemedBox_default, { - marginLeft: 3, - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime321.jsxDEV(ThemedText, { - dimColor: true, - children: exitState.pending ? `Press ${exitState.keyName} again to exit` : instructions - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); -} -var jsx_dev_runtime321; -var init_WizardNavigationFooter = __esm(() => { - init_useExitOnCtrlCDWithKeybindings(); - init_ink2(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - jsx_dev_runtime321 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/wizard/WizardDialogLayout.tsx -function WizardDialogLayout(t0) { - const $2 = import_compiler_runtime253.c(11); - const { - title: titleOverride, - color: t1, - children, - subtitle, - footerText - } = t0; - const color3 = t1 === undefined ? "suggestion" : t1; - const { - currentStepIndex, - totalSteps, - title: providerTitle, - showStepCounter, - goBack - } = useWizard(); - const title = titleOverride || providerTitle || "Wizard"; - const stepSuffix = showStepCounter !== false ? ` (${currentStepIndex + 1}/${totalSteps})` : ""; - const t22 = `${title}${stepSuffix}`; - let t32; - if ($2[0] !== children || $2[1] !== color3 || $2[2] !== goBack || $2[3] !== subtitle || $2[4] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime322.jsxDEV(Dialog, { - title: t22, - subtitle, - onCancel: goBack, - color: color3, - hideInputGuide: true, - isCancelActive: false, - children - }, undefined, false, undefined, this); - $2[0] = children; - $2[1] = color3; - $2[2] = goBack; - $2[3] = subtitle; - $2[4] = t22; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== footerText) { - t4 = /* @__PURE__ */ jsx_dev_runtime322.jsxDEV(WizardNavigationFooter, { - instructions: footerText - }, undefined, false, undefined, this); - $2[6] = footerText; - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] !== t32 || $2[9] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime322.jsxDEV(jsx_dev_runtime322.Fragment, { - children: [ - t32, - t4 - ] - }, undefined, true, undefined, this); - $2[8] = t32; - $2[9] = t4; - $2[10] = t5; - } else { - t5 = $2[10]; - } - return t5; -} -var import_compiler_runtime253, jsx_dev_runtime322; -var init_WizardDialogLayout = __esm(() => { - init_Dialog(); - init_useWizard(); - init_WizardNavigationFooter(); - import_compiler_runtime253 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime322 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/wizard/index.ts -var init_wizard = __esm(() => { - init_useWizard(); - init_WizardDialogLayout(); - init_WizardNavigationFooter(); - init_WizardProvider(); -}); - -// src/components/agents/new-agent-creation/wizard-steps/ColorStep.tsx -function ColorStep() { - const $2 = import_compiler_runtime254.c(14); - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - context: "Confirmation" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - useKeybinding("confirm:no", goBack, t0); - let t1; - if ($2[1] !== goNext || $2[2] !== updateWizardData || $2[3] !== wizardData.agentType || $2[4] !== wizardData.location || $2[5] !== wizardData.selectedModel || $2[6] !== wizardData.selectedTools || $2[7] !== wizardData.systemPrompt || $2[8] !== wizardData.whenToUse) { - t1 = (color3) => { - updateWizardData({ - selectedColor: color3, - finalAgent: { - agentType: wizardData.agentType, - whenToUse: wizardData.whenToUse, - getSystemPrompt: () => wizardData.systemPrompt, - tools: wizardData.selectedTools, - ...wizardData.selectedModel ? { - model: wizardData.selectedModel - } : {}, - ...color3 ? { - color: color3 - } : {}, - source: wizardData.location - } - }); - goNext(); - }; - $2[1] = goNext; - $2[2] = updateWizardData; - $2[3] = wizardData.agentType; - $2[4] = wizardData.location; - $2[5] = wizardData.selectedModel; - $2[6] = wizardData.selectedTools; - $2[7] = wizardData.systemPrompt; - $2[8] = wizardData.whenToUse; - $2[9] = t1; - } else { - t1 = $2[9]; - } - const handleConfirm = t1; - let t22; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[10] = t22; - } else { - t22 = $2[10]; - } - const t32 = wizardData.agentType || "agent"; - let t4; - if ($2[11] !== handleConfirm || $2[12] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(WizardDialogLayout, { - subtitle: "Choose background color", - footerText: t22, - children: /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime323.jsxDEV(ColorPicker, { - agentName: t32, - currentColor: "automatic", - onConfirm: handleConfirm - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[11] = handleConfirm; - $2[12] = t32; - $2[13] = t4; - } else { - t4 = $2[13]; - } - return t4; -} -var import_compiler_runtime254, jsx_dev_runtime323; -var init_ColorStep = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - init_ColorPicker(); - import_compiler_runtime254 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime323 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/validateAgent.ts -function validateAgentType(agentType) { - if (!agentType) { - return "Agent type is required"; - } - if (!/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/.test(agentType)) { - return "Agent type must start and end with alphanumeric characters and contain only letters, numbers, and hyphens"; - } - if (agentType.length < 3) { - return "Agent type must be at least 3 characters long"; - } - if (agentType.length > 50) { - return "Agent type must be less than 50 characters"; - } - return null; -} -function validateAgent(agent, availableTools, existingAgents) { - const errors8 = []; - const warnings = []; - if (!agent.agentType) { - errors8.push("Agent type is required"); - } else { - const typeError = validateAgentType(agent.agentType); - if (typeError) { - errors8.push(typeError); - } - const duplicate = existingAgents.find((a5) => a5.agentType === agent.agentType && a5.source !== agent.source); - if (duplicate) { - errors8.push(`Agent type "${agent.agentType}" already exists in ${getAgentSourceDisplayName(duplicate.source)}`); - } - } - if (!agent.whenToUse) { - errors8.push("Description (description) is required"); - } else if (agent.whenToUse.length < 10) { - warnings.push("Description should be more descriptive (at least 10 characters)"); - } else if (agent.whenToUse.length > 5000) { - warnings.push("Description is very long (over 5000 characters)"); - } - if (agent.tools !== undefined && !Array.isArray(agent.tools)) { - errors8.push("Tools must be an array"); - } else { - if (agent.tools === undefined) { - warnings.push("Agent has access to all tools"); - } else if (agent.tools.length === 0) { - warnings.push("No tools selected - agent will have very limited capabilities"); - } - const resolvedTools = resolveAgentTools(agent, availableTools, false); - if (resolvedTools.invalidTools.length > 0) { - errors8.push(`Invalid tools: ${resolvedTools.invalidTools.join(", ")}`); - } - } - const systemPrompt = agent.getSystemPrompt(); - if (!systemPrompt) { - errors8.push("System prompt is required"); - } else if (systemPrompt.length < 20) { - errors8.push("System prompt is too short (minimum 20 characters)"); - } else if (systemPrompt.length > 1e4) { - warnings.push("System prompt is very long (over 10,000 characters)"); - } - return { - isValid: errors8.length === 0, - errors: errors8, - warnings - }; -} -var init_validateAgent = __esm(() => { - init_agentToolUtils(); - init_utils15(); -}); - -// src/components/agents/new-agent-creation/wizard-steps/ConfirmStep.tsx -function ConfirmStep(t0) { - const $2 = import_compiler_runtime255.c(88); - const { - tools, - existingAgents, - onSave, - onSaveAndEdit, - error: error46 - } = t0; - const { - goBack, - wizardData - } = useWizard(); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - context: "Confirmation" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - useKeybinding("confirm:no", goBack, t1); - let t22; - if ($2[1] !== onSave || $2[2] !== onSaveAndEdit) { - t22 = (e4) => { - if (e4.key === "s" || e4.key === "return") { - e4.preventDefault(); - onSave(); - } else { - if (e4.key === "e") { - e4.preventDefault(); - onSaveAndEdit(); - } - } - }; - $2[1] = onSave; - $2[2] = onSaveAndEdit; - $2[3] = t22; - } else { - t22 = $2[3]; - } - const handleKeyDown = t22; - const agent = wizardData.finalAgent; - let T0; - let T1; - let t10; - let t11; - let t12; - let t13; - let t14; - let t15; - let t16; - let t17; - let t18; - let t19; - let t32; - let t4; - let t5; - let t6; - let t7; - let t8; - let t9; - if ($2[4] !== agent || $2[5] !== existingAgents || $2[6] !== handleKeyDown || $2[7] !== tools || $2[8] !== wizardData.location) { - const validation = validateAgent(agent, tools, existingAgents); - let t202; - if ($2[28] !== agent) { - t202 = truncateToWidth(agent.getSystemPrompt(), 240); - $2[28] = agent; - $2[29] = t202; - } else { - t202 = $2[29]; - } - const systemPromptPreview = t202; - let t212; - if ($2[30] !== agent.whenToUse) { - t212 = truncateToWidth(agent.whenToUse, 240); - $2[30] = agent.whenToUse; - $2[31] = t212; - } else { - t212 = $2[31]; - } - const whenToUsePreview = t212; - const getToolsDisplay = _temp156; - let t223; - if ($2[32] !== agent.memory) { - t223 = isAutoMemoryEnabled() ? /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Memory" - }, undefined, false, undefined, this), - ": ", - getMemoryScopeDisplay(agent.memory) - ] - }, undefined, true, undefined, this) : null; - $2[32] = agent.memory; - $2[33] = t223; - } else { - t223 = $2[33]; - } - const memoryDisplayElement = t223; - T1 = WizardDialogLayout; - t18 = "Confirm and save"; - if ($2[34] === Symbol.for("react.memo_cache_sentinel")) { - t19 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(KeyboardShortcutHint, { - shortcut: "s/Enter", - action: "save" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(KeyboardShortcutHint, { - shortcut: "e", - action: "edit in your editor" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[34] = t19; - } else { - t19 = $2[34]; - } - T0 = ThemedBox_default; - t32 = "column"; - t4 = 0; - t5 = true; - t6 = handleKeyDown; - let t232; - if ($2[35] === Symbol.for("react.memo_cache_sentinel")) { - t232 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Name" - }, undefined, false, undefined, this); - $2[35] = t232; - } else { - t232 = $2[35]; - } - if ($2[36] !== agent.agentType) { - t7 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - t232, - ": ", - agent.agentType - ] - }, undefined, true, undefined, this); - $2[36] = agent.agentType; - $2[37] = t7; - } else { - t7 = $2[37]; - } - let t242; - if ($2[38] === Symbol.for("react.memo_cache_sentinel")) { - t242 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Location" - }, undefined, false, undefined, this); - $2[38] = t242; - } else { - t242 = $2[38]; - } - let t252; - if ($2[39] !== agent.agentType || $2[40] !== wizardData.location) { - t252 = getNewRelativeAgentFilePath({ - source: wizardData.location, - agentType: agent.agentType - }); - $2[39] = agent.agentType; - $2[40] = wizardData.location; - $2[41] = t252; - } else { - t252 = $2[41]; - } - if ($2[42] !== t252) { - t8 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - t242, - ":", - " ", - t252 - ] - }, undefined, true, undefined, this); - $2[42] = t252; - $2[43] = t8; - } else { - t8 = $2[43]; - } - let t26; - if ($2[44] === Symbol.for("react.memo_cache_sentinel")) { - t26 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Tools" - }, undefined, false, undefined, this); - $2[44] = t26; - } else { - t26 = $2[44]; - } - let t27; - if ($2[45] !== agent.tools) { - t27 = getToolsDisplay(agent.tools); - $2[45] = agent.tools; - $2[46] = t27; - } else { - t27 = $2[46]; - } - if ($2[47] !== t27) { - t9 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - t26, - ": ", - t27 - ] - }, undefined, true, undefined, this); - $2[47] = t27; - $2[48] = t9; - } else { - t9 = $2[48]; - } - let t28; - if ($2[49] === Symbol.for("react.memo_cache_sentinel")) { - t28 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Model" - }, undefined, false, undefined, this); - $2[49] = t28; - } else { - t28 = $2[49]; - } - let t29; - if ($2[50] !== agent.model) { - t29 = getAgentModelDisplay(agent.model); - $2[50] = agent.model; - $2[51] = t29; - } else { - t29 = $2[51]; - } - if ($2[52] !== t29) { - t10 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - t28, - ": ", - t29 - ] - }, undefined, true, undefined, this); - $2[52] = t29; - $2[53] = t10; - } else { - t10 = $2[53]; - } - t11 = memoryDisplayElement; - if ($2[54] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Description" - }, undefined, false, undefined, this), - " (tells Claude when to use this agent):" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[54] = t12; - } else { - t12 = $2[54]; - } - if ($2[55] !== whenToUsePreview) { - t13 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginLeft: 2, - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: whenToUsePreview - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[55] = whenToUsePreview; - $2[56] = t13; - } else { - t13 = $2[56]; - } - if ($2[57] === Symbol.for("react.memo_cache_sentinel")) { - t14 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "System prompt" - }, undefined, false, undefined, this), - ":" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[57] = t14; - } else { - t14 = $2[57]; - } - if ($2[58] !== systemPromptPreview) { - t15 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginLeft: 2, - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - children: systemPromptPreview - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[58] = systemPromptPreview; - $2[59] = t15; - } else { - t15 = $2[59]; - } - t16 = validation.warnings.length > 0 && /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - color: "warning", - children: "Warnings:" - }, undefined, false, undefined, this), - validation.warnings.map(_temp268) - ] - }, undefined, true, undefined, this); - t17 = validation.errors.length > 0 && /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - color: "error", - children: "Errors:" - }, undefined, false, undefined, this), - validation.errors.map(_temp342) - ] - }, undefined, true, undefined, this); - $2[4] = agent; - $2[5] = existingAgents; - $2[6] = handleKeyDown; - $2[7] = tools; - $2[8] = wizardData.location; - $2[9] = T0; - $2[10] = T1; - $2[11] = t10; - $2[12] = t11; - $2[13] = t12; - $2[14] = t13; - $2[15] = t14; - $2[16] = t15; - $2[17] = t16; - $2[18] = t17; - $2[19] = t18; - $2[20] = t19; - $2[21] = t32; - $2[22] = t4; - $2[23] = t5; - $2[24] = t6; - $2[25] = t7; - $2[26] = t8; - $2[27] = t9; - } else { - T0 = $2[9]; - T1 = $2[10]; - t10 = $2[11]; - t11 = $2[12]; - t12 = $2[13]; - t13 = $2[14]; - t14 = $2[15]; - t15 = $2[16]; - t16 = $2[17]; - t17 = $2[18]; - t18 = $2[19]; - t19 = $2[20]; - t32 = $2[21]; - t4 = $2[22]; - t5 = $2[23]; - t6 = $2[24]; - t7 = $2[25]; - t8 = $2[26]; - t9 = $2[27]; - } - let t20; - if ($2[60] !== error46) { - t20 = error46 && /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[60] = error46; - $2[61] = t20; - } else { - t20 = $2[61]; - } - let t21; - if ($2[62] === Symbol.for("react.memo_cache_sentinel")) { - t21 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "s" - }, undefined, false, undefined, this); - $2[62] = t21; - } else { - t21 = $2[62]; - } - let t222; - if ($2[63] === Symbol.for("react.memo_cache_sentinel")) { - t222 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "Enter" - }, undefined, false, undefined, this); - $2[63] = t222; - } else { - t222 = $2[63]; - } - let t23; - if ($2[64] === Symbol.for("react.memo_cache_sentinel")) { - t23 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedBox_default, { - marginTop: 2, - children: /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - color: "success", - children: [ - "Press ", - t21, - " or ", - t222, - " to save,", - " ", - /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - bold: true, - children: "e" - }, undefined, false, undefined, this), - " to save and edit" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[64] = t23; - } else { - t23 = $2[64]; - } - let t24; - if ($2[65] !== T0 || $2[66] !== t10 || $2[67] !== t11 || $2[68] !== t12 || $2[69] !== t13 || $2[70] !== t14 || $2[71] !== t15 || $2[72] !== t16 || $2[73] !== t17 || $2[74] !== t20 || $2[75] !== t32 || $2[76] !== t4 || $2[77] !== t5 || $2[78] !== t6 || $2[79] !== t7 || $2[80] !== t8 || $2[81] !== t9) { - t24 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(T0, { - flexDirection: t32, - tabIndex: t4, - autoFocus: t5, - onKeyDown: t6, - children: [ - t7, - t8, - t9, - t10, - t11, - t12, - t13, - t14, - t15, - t16, - t17, - t20, - t23 - ] - }, undefined, true, undefined, this); - $2[65] = T0; - $2[66] = t10; - $2[67] = t11; - $2[68] = t12; - $2[69] = t13; - $2[70] = t14; - $2[71] = t15; - $2[72] = t16; - $2[73] = t17; - $2[74] = t20; - $2[75] = t32; - $2[76] = t4; - $2[77] = t5; - $2[78] = t6; - $2[79] = t7; - $2[80] = t8; - $2[81] = t9; - $2[82] = t24; - } else { - t24 = $2[82]; - } - let t25; - if ($2[83] !== T1 || $2[84] !== t18 || $2[85] !== t19 || $2[86] !== t24) { - t25 = /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(T1, { - subtitle: t18, - footerText: t19, - children: t24 - }, undefined, false, undefined, this); - $2[83] = T1; - $2[84] = t18; - $2[85] = t19; - $2[86] = t24; - $2[87] = t25; - } else { - t25 = $2[87]; - } - return t25; -} -function _temp342(err2, i_0) { - return /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - color: "error", - children: [ - " ", - "\u2022 ", - err2 - ] - }, i_0, true, undefined, this); -} -function _temp268(warning, i6) { - return /* @__PURE__ */ jsx_dev_runtime324.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\u2022 ", - warning - ] - }, i6, true, undefined, this); -} -function _temp156(toolNames) { - if (toolNames === undefined) { - return "All tools"; - } - if (toolNames.length === 0) { - return "None"; - } - if (toolNames.length === 1) { - return toolNames[0] || "None"; - } - if (toolNames.length === 2) { - return toolNames.join(" and "); - } - return `${toolNames.slice(0, -1).join(", ")}, and ${toolNames[toolNames.length - 1]}`; -} -var import_compiler_runtime255, jsx_dev_runtime324; -var init_ConfirmStep = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_paths(); - init_agentMemory(); - init_format(); - init_agent(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - init_agentFileUtils(); - init_validateAgent(); - import_compiler_runtime255 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime324 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/ConfirmStepWrapper.tsx -function ConfirmStepWrapper({ - tools, - existingAgents, - onComplete -}) { - const { - wizardData - } = useWizard(); - const [saveError, setSaveError] = import_react181.useState(null); - const setAppState = useSetAppState(); - const saveAgent = import_react181.useCallback(async (openInEditor) => { - if (!wizardData?.finalAgent) - return; - try { - await saveAgentToFile(wizardData.location, wizardData.finalAgent.agentType, wizardData.finalAgent.whenToUse, wizardData.finalAgent.tools, wizardData.finalAgent.getSystemPrompt(), true, wizardData.finalAgent.color, wizardData.finalAgent.model, wizardData.finalAgent.memory); - setAppState((state3) => { - if (!wizardData.finalAgent) - return state3; - const allAgents = state3.agentDefinitions.allAgents.concat(wizardData.finalAgent); - return { - ...state3, - agentDefinitions: { - ...state3.agentDefinitions, - activeAgents: getActiveAgentsFromList(allAgents), - allAgents - } - }; - }); - if (openInEditor) { - const filePath = getNewAgentFilePath({ - source: wizardData.location, - agentType: wizardData.finalAgent.agentType - }); - await editFileInEditor(filePath); - } - logEvent("tengu_agent_created", { - agent_type: wizardData.finalAgent.agentType, - generation_method: wizardData.wasGenerated ? "generated" : "manual", - source: wizardData.location, - tool_count: wizardData.finalAgent.tools?.length ?? "all", - has_custom_model: !!wizardData.finalAgent.model, - has_custom_color: !!wizardData.finalAgent.color, - has_memory: !!wizardData.finalAgent.memory, - memory_scope: wizardData.finalAgent.memory ?? "none", - ...openInEditor ? { - opened_in_editor: true - } : {} - }); - const message = openInEditor ? `Created agent: ${source_default.bold(wizardData.finalAgent.agentType)} and opened in editor. ` + `If you made edits, restart to load the latest version.` : `Created agent: ${source_default.bold(wizardData.finalAgent.agentType)}`; - onComplete(message); - } catch (err2) { - setSaveError(err2 instanceof Error ? err2.message : "Failed to save agent"); - } - }, [wizardData, onComplete, setAppState]); - const handleSave = import_react181.useCallback(() => saveAgent(false), [saveAgent]); - const handleSaveAndEdit = import_react181.useCallback(() => saveAgent(true), [saveAgent]); - return /* @__PURE__ */ jsx_dev_runtime325.jsxDEV(ConfirmStep, { - tools, - existingAgents, - onSave: handleSave, - onSaveAndEdit: handleSaveAndEdit, - error: saveError - }, undefined, false, undefined, this); -} -var import_react181, jsx_dev_runtime325; -var init_ConfirmStepWrapper = __esm(() => { - init_source(); - init_analytics(); - init_AppState(); - init_loadAgentsDir(); - init_promptEditor(); - init_wizard(); - init_agentFileUtils(); - init_ConfirmStep(); - import_react181 = __toESM(require_react(), 1); - jsx_dev_runtime325 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/DescriptionStep.tsx -function DescriptionStep() { - const $2 = import_compiler_runtime256.c(18); - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - const [whenToUse, setWhenToUse] = import_react182.useState(wizardData.whenToUse || ""); - const [cursorOffset, setCursorOffset] = import_react182.useState(whenToUse.length); - const [error46, setError] = import_react182.useState(null); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - context: "Settings" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - useKeybinding("confirm:no", goBack, t0); - let t1; - if ($2[1] !== whenToUse) { - t1 = async () => { - const result = await editPromptInEditor(whenToUse); - if (result.content !== null) { - setWhenToUse(result.content); - setCursorOffset(result.content.length); - } - }; - $2[1] = whenToUse; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const handleExternalEditor = t1; - let t22; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t22 = { - context: "Chat" - }; - $2[3] = t22; - } else { - t22 = $2[3]; - } - useKeybinding("chat:externalEditor", handleExternalEditor, t22); - let t32; - if ($2[4] !== goNext || $2[5] !== updateWizardData) { - t32 = (value) => { - const trimmedValue = value.trim(); - if (!trimmedValue) { - setError("Description is required"); - return; - } - setError(null); - updateWizardData({ - whenToUse: trimmedValue - }); - goNext(); - }; - $2[4] = goNext; - $2[5] = updateWizardData; - $2[6] = t32; - } else { - t32 = $2[6]; - } - const handleSubmit = t32; - let t4; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(KeyboardShortcutHint, { - shortcut: "Type", - action: "enter text" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "continue" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ConfigurableShortcutHint, { - action: "chat:externalEditor", - context: "Chat", - fallback: "ctrl+g", - description: "open in editor" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Settings", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ThemedText, { - children: "When should Claude use this agent?" - }, undefined, false, undefined, this); - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== cursorOffset || $2[10] !== handleSubmit || $2[11] !== whenToUse) { - t6 = /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(TextInput, { - value: whenToUse, - onChange: setWhenToUse, - onSubmit: handleSubmit, - placeholder: "e.g., use this agent after you're done writing code...", - columns: 80, - cursorOffset, - onChangeCursorOffset: setCursorOffset, - focus: true, - showCursor: true - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[9] = cursorOffset; - $2[10] = handleSubmit; - $2[11] = whenToUse; - $2[12] = t6; - } else { - t6 = $2[12]; - } - let t7; - if ($2[13] !== error46) { - t7 = error46 && /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[13] = error46; - $2[14] = t7; - } else { - t7 = $2[14]; - } - let t8; - if ($2[15] !== t6 || $2[16] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(WizardDialogLayout, { - subtitle: "Description (tell Claude when to use this agent)", - footerText: t4, - children: /* @__PURE__ */ jsx_dev_runtime326.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t5, - t6, - t7 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[15] = t6; - $2[16] = t7; - $2[17] = t8; - } else { - t8 = $2[17]; - } - return t8; -} -var import_compiler_runtime256, import_react182, jsx_dev_runtime326; -var init_DescriptionStep = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_promptEditor(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_TextInput(); - init_wizard(); - init_WizardDialogLayout(); - import_compiler_runtime256 = __toESM(require_compiler_runtime(), 1); - import_react182 = __toESM(require_react(), 1); - jsx_dev_runtime326 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/generateAgent.ts -async function generateAgent(userPrompt, model, existingIdentifiers, abortSignal) { - const existingList = existingIdentifiers.length > 0 ? ` - -IMPORTANT: The following identifiers already exist and must NOT be used: ${existingIdentifiers.join(", ")}` : ""; - const prompt = `Create an agent configuration based on this request: "${userPrompt}".${existingList} - Return ONLY the JSON object, no other text.`; - const userMessage = createUserMessage({ content: prompt }); - const userContext = await getUserContext(); - const messagesWithContext = prependUserContext([userMessage], userContext); - const systemPrompt = isAutoMemoryEnabled() ? AGENT_CREATION_SYSTEM_PROMPT + AGENT_MEMORY_INSTRUCTIONS : AGENT_CREATION_SYSTEM_PROMPT; - const response7 = await queryModelWithoutStreaming({ - messages: normalizeMessagesForAPI(messagesWithContext), - systemPrompt: asSystemPrompt([systemPrompt]), - thinkingConfig: { type: "disabled" }, - tools: [], - signal: abortSignal, - options: { - getToolPermissionContext: async () => getEmptyToolPermissionContext(), - model, - toolChoice: undefined, - agents: [], - isNonInteractiveSession: false, - hasAppendSystemPrompt: false, - querySource: "agent_creation", - mcpTools: [] - } - }); - const textBlocks = response7.message.content.filter((block2) => block2.type === "text"); - const responseText = textBlocks.map((block2) => block2.text).join(` -`); - let parsed; - try { - parsed = jsonParse(responseText.trim()); - } catch { - const jsonMatch = responseText.match(/\{[\s\S]*\}/); - if (!jsonMatch) { - throw new Error("No JSON object found in response"); - } - parsed = jsonParse(jsonMatch[0]); - } - if (!parsed.identifier || !parsed.whenToUse || !parsed.systemPrompt) { - throw new Error("Invalid agent configuration generated"); - } - logEvent("tengu_agent_definition_generated", { - agent_identifier: parsed.identifier - }); - return { - identifier: parsed.identifier, - whenToUse: parsed.whenToUse, - systemPrompt: parsed.systemPrompt - }; -} -var AGENT_CREATION_SYSTEM_PROMPT, AGENT_MEMORY_INSTRUCTIONS = ` - -7. **Agent Memory Instructions**: If the user mentions "memory", "remember", "learn", "persist", or similar concepts, OR if the agent would benefit from building up knowledge across conversations (e.g., code reviewers learning patterns, architects learning codebase structure, etc.), include domain-specific memory update instructions in the systemPrompt. - - Add a section like this to the systemPrompt, tailored to the agent's specific domain: - - "**Update your agent memory** as you discover [domain-specific items]. This builds up institutional knowledge across conversations. Write concise notes about what you found and where. - - Examples of what to record: - - [domain-specific item 1] - - [domain-specific item 2] - - [domain-specific item 3]" - - Examples of domain-specific memory instructions: - - For a code-reviewer: "Update your agent memory as you discover code patterns, style conventions, common issues, and architectural decisions in this codebase." - - For a test-runner: "Update your agent memory as you discover test patterns, common failure modes, flaky tests, and testing best practices." - - For an architect: "Update your agent memory as you discover codepaths, library locations, key architectural decisions, and component relationships." - - For a documentation writer: "Update your agent memory as you discover documentation patterns, API structures, and terminology conventions." - - The memory instructions should be specific to what the agent would naturally learn while performing its core tasks. -`; -var init_generateAgent = __esm(() => { - init_context4(); - init_claude(); - init_Tool(); - init_constants3(); - init_api3(); - init_messages9(); - init_paths(); - init_analytics(); - init_slowOperations(); - AGENT_CREATION_SYSTEM_PROMPT = `You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability. - -**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices. - -When a user describes what they want an agent to do, you will: - -1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise. - -2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach. - -3. **Architect Comprehensive Instructions**: Develop a system prompt that: - - Establishes clear behavioral boundaries and operational parameters - - Provides specific methodologies and best practices for task execution - - Anticipates edge cases and provides guidance for handling them - - Incorporates any specific requirements or preferences mentioned by the user - - Defines output format expectations when relevant - - Aligns with project-specific coding standards and patterns from CLAUDE.md - -4. **Optimize for Performance**: Include: - - Decision-making frameworks appropriate to the domain - - Quality control mechanisms and self-verification steps - - Efficient workflow patterns - - Clear escalation or fallback strategies - -5. **Create Identifier**: Design a concise, descriptive identifier that: - - Uses lowercase letters, numbers, and hyphens only - - Is typically 2-4 words joined by hyphens - - Clearly indicates the agent's primary function - - Is memorable and easy to type - - Avoids generic terms like "helper" or "assistant" - -6 **Example agent descriptions**: - - in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used. - - examples should be of the form: - - - Context: The user is creating a test-runner agent that should be called after a logical chunk of code is written. - user: "Please write a function that checks if a number is prime" - assistant: "Here is the relevant function: " - - - Since a significant piece of code was written, use the ${AGENT_TOOL_NAME} tool to launch the test-runner agent to run the tests. - - assistant: "Now let me use the test-runner agent to run the tests" - - - - Context: User is creating an agent to respond to the word "hello" with a friendly jok. - user: "Hello" - assistant: "I'm going to use the ${AGENT_TOOL_NAME} tool to launch the greeting-responder agent to respond with a friendly joke" - - Since the user is greeting, use the greeting-responder agent to respond with a friendly joke. - - - - If the user mentioned or implied that the agent should be used proactively, you should include examples of this. -- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task. - -Your output must be a valid JSON object with exactly these fields: -{ - "identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'test-runner', 'api-docs-writer', 'code-formatter')", - "whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.", - "systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness" -} - -Key principles for your system prompts: -- Be specific rather than generic - avoid vague instructions -- Include concrete examples when they would clarify behavior -- Balance comprehensiveness with clarity - every instruction should add value -- Ensure the agent has enough context to handle variations of the core task -- Make the agent proactive in seeking clarification when needed -- Build in quality assurance and self-correction mechanisms - -Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual. -`; -}); - -// src/components/agents/new-agent-creation/wizard-steps/GenerateStep.tsx -function GenerateStep() { - const { - updateWizardData, - goBack, - goToStep, - wizardData - } = useWizard(); - const [prompt, setPrompt] = import_react183.useState(wizardData.generationPrompt || ""); - const [isGenerating, setIsGenerating] = import_react183.useState(false); - const [error46, setError] = import_react183.useState(null); - const [cursorOffset, setCursorOffset] = import_react183.useState(prompt.length); - const model = useMainLoopModel(); - const abortControllerRef = import_react183.useRef(null); - const handleCancelGeneration = import_react183.useCallback(() => { - if (abortControllerRef.current) { - abortControllerRef.current.abort(); - abortControllerRef.current = null; - setIsGenerating(false); - setError("Generation cancelled"); - } - }, []); - useKeybinding("confirm:no", handleCancelGeneration, { - context: "Settings", - isActive: isGenerating - }); - const handleExternalEditor = import_react183.useCallback(async () => { - const result = await editPromptInEditor(prompt); - if (result.content !== null) { - setPrompt(result.content); - setCursorOffset(result.content.length); - } - }, [prompt]); - useKeybinding("chat:externalEditor", handleExternalEditor, { - context: "Chat", - isActive: !isGenerating - }); - const handleGoBack = import_react183.useCallback(() => { - updateWizardData({ - generationPrompt: "", - agentType: "", - systemPrompt: "", - whenToUse: "", - generatedAgent: undefined, - wasGenerated: false - }); - setPrompt(""); - setError(null); - goBack(); - }, [updateWizardData, goBack]); - useKeybinding("confirm:no", handleGoBack, { - context: "Settings", - isActive: !isGenerating - }); - const handleGenerate = async () => { - const trimmedPrompt = prompt.trim(); - if (!trimmedPrompt) { - setError("Please describe what the agent should do"); - return; - } - setError(null); - setIsGenerating(true); - updateWizardData({ - generationPrompt: trimmedPrompt, - isGenerating: true - }); - const controller = createAbortController(); - abortControllerRef.current = controller; - try { - const generated = await generateAgent(trimmedPrompt, model, [], controller.signal); - updateWizardData({ - agentType: generated.identifier, - whenToUse: generated.whenToUse, - systemPrompt: generated.systemPrompt, - generatedAgent: generated, - isGenerating: false, - wasGenerated: true - }); - goToStep(6); - } catch (err2) { - if (err2 instanceof APIUserAbortError) {} else if (err2 instanceof Error && !err2.message.includes("No assistant message found")) { - setError(err2.message || "Failed to generate agent"); - } - updateWizardData({ - isGenerating: false - }); - } finally { - setIsGenerating(false); - abortControllerRef.current = null; - } - }; - const subtitle = "Describe what this agent should do and when it should be used (be comprehensive for best results)"; - if (isGenerating) { - return /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(WizardDialogLayout, { - subtitle, - footerText: /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Settings", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ThemedBox_default, { - flexDirection: "row", - alignItems: "center", - children: [ - /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ThemedText, { - color: "suggestion", - children: " Generating agent from description..." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(WizardDialogLayout, { - subtitle, - footerText: /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:yes", - context: "Confirmation", - fallback: "Enter", - description: "submit" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ConfigurableShortcutHint, { - action: "chat:externalEditor", - context: "Chat", - fallback: "ctrl+g", - description: "open in editor" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Settings", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - error46 && /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime327.jsxDEV(TextInput, { - value: prompt, - onChange: setPrompt, - onSubmit: handleGenerate, - placeholder: "e.g., Help me write unit tests for my code...", - columns: 80, - cursorOffset, - onChangeCursorOffset: setCursorOffset, - focus: true, - showCursor: true - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var import_react183, jsx_dev_runtime327; -var init_GenerateStep = __esm(() => { - init_sdk(); - init_useMainLoopModel(); - init_ink2(); - init_useKeybinding(); - init_abortController(); - init_promptEditor(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_Spinner2(); - init_TextInput(); - init_wizard(); - init_WizardDialogLayout(); - init_generateAgent(); - import_react183 = __toESM(require_react(), 1); - jsx_dev_runtime327 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/LocationStep.tsx -function LocationStep() { - const $2 = import_compiler_runtime257.c(11); - const { - goNext, - updateWizardData, - cancel - } = useWizard(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - label: "Project (.claude/agents/)", - value: "projectSettings" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - let t1; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = [t0, { - label: "Personal (~/.claude/agents/)", - value: "userSettings" - }]; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const locationOptions = t1; - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== goNext || $2[4] !== updateWizardData) { - t32 = (value) => { - updateWizardData({ - location: value - }); - goNext(); - }; - $2[3] = goNext; - $2[4] = updateWizardData; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== cancel) { - t4 = () => cancel(); - $2[6] = cancel; - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] !== t32 || $2[9] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(WizardDialogLayout, { - subtitle: "Choose location", - footerText: t22, - children: /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime328.jsxDEV(Select, { - options: locationOptions, - onChange: t32, - onCancel: t4 - }, "location-select", false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[8] = t32; - $2[9] = t4; - $2[10] = t5; - } else { - t5 = $2[10]; - } - return t5; -} -var import_compiler_runtime257, jsx_dev_runtime328; -var init_LocationStep = __esm(() => { - init_ink2(); - init_ConfigurableShortcutHint(); - init_select(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - import_compiler_runtime257 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime328 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/MemoryStep.tsx -function MemoryStep() { - const $2 = import_compiler_runtime258.c(13); - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - context: "Confirmation" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - useKeybinding("confirm:no", goBack, t0); - const isUserScope = wizardData.location === "userSettings"; - let t1; - if ($2[1] !== isUserScope) { - t1 = isUserScope ? [{ - label: "User scope (~/.claude/agent-memory/) (Recommended)", - value: "user" - }, { - label: "None (no persistent memory)", - value: "none" - }, { - label: "Project scope (.claude/agent-memory/)", - value: "project" - }, { - label: "Local scope (.claude/agent-memory-local/)", - value: "local" - }] : [{ - label: "Project scope (.claude/agent-memory/) (Recommended)", - value: "project" - }, { - label: "None (no persistent memory)", - value: "none" - }, { - label: "User scope (~/.claude/agent-memory/)", - value: "user" - }, { - label: "Local scope (.claude/agent-memory-local/)", - value: "local" - }]; - $2[1] = isUserScope; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const memoryOptions = t1; - let t22; - if ($2[3] !== goNext || $2[4] !== updateWizardData || $2[5] !== wizardData.finalAgent || $2[6] !== wizardData.systemPrompt) { - t22 = (value) => { - const memory2 = value === "none" ? undefined : value; - const agentType = wizardData.finalAgent?.agentType; - updateWizardData({ - selectedMemory: memory2, - finalAgent: wizardData.finalAgent ? { - ...wizardData.finalAgent, - memory: memory2, - getSystemPrompt: isAutoMemoryEnabled() && memory2 && agentType ? () => wizardData.systemPrompt + ` - -` + loadAgentMemoryPrompt(agentType, memory2) : () => wizardData.systemPrompt - } : undefined - }); - goNext(); - }; - $2[3] = goNext; - $2[4] = updateWizardData; - $2[5] = wizardData.finalAgent; - $2[6] = wizardData.systemPrompt; - $2[7] = t22; - } else { - t22 = $2[7]; - } - const handleSelect = t22; - let t32; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[8] = t32; - } else { - t32 = $2[8]; - } - let t4; - if ($2[9] !== goBack || $2[10] !== handleSelect || $2[11] !== memoryOptions) { - t4 = /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(WizardDialogLayout, { - subtitle: "Configure agent memory", - footerText: t32, - children: /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime329.jsxDEV(Select, { - options: memoryOptions, - onChange: handleSelect, - onCancel: goBack - }, "memory-select", false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[9] = goBack; - $2[10] = handleSelect; - $2[11] = memoryOptions; - $2[12] = t4; - } else { - t4 = $2[12]; - } - return t4; -} -var import_compiler_runtime258, jsx_dev_runtime329; -var init_MemoryStep = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_paths(); - init_agentMemory(); - init_ConfigurableShortcutHint(); - init_select(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - import_compiler_runtime258 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime329 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/MethodStep.tsx -function MethodStep() { - const $2 = import_compiler_runtime259.c(11); - const { - goNext, - goBack, - updateWizardData, - goToStep - } = useWizard(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = [{ - label: "Generate with Claude (recommended)", - value: "generate" - }, { - label: "Manual configuration", - value: "manual" - }]; - $2[0] = t0; - } else { - t0 = $2[0]; - } - const methodOptions = t0; - let t1; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== goNext || $2[3] !== goToStep || $2[4] !== updateWizardData) { - t22 = (value) => { - const method = value; - updateWizardData({ - method, - wasGenerated: method === "generate" - }); - if (method === "generate") { - goNext(); - } else { - goToStep(3); - } - }; - $2[2] = goNext; - $2[3] = goToStep; - $2[4] = updateWizardData; - $2[5] = t22; - } else { - t22 = $2[5]; - } - let t32; - if ($2[6] !== goBack) { - t32 = () => goBack(); - $2[6] = goBack; - $2[7] = t32; - } else { - t32 = $2[7]; - } - let t4; - if ($2[8] !== t22 || $2[9] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(WizardDialogLayout, { - subtitle: "Creation method", - footerText: t1, - children: /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime330.jsxDEV(Select, { - options: methodOptions, - onChange: t22, - onCancel: t32 - }, "method-select", false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[8] = t22; - $2[9] = t32; - $2[10] = t4; - } else { - t4 = $2[10]; - } - return t4; -} -var import_compiler_runtime259, jsx_dev_runtime330; -var init_MethodStep = __esm(() => { - init_ink2(); - init_ConfigurableShortcutHint(); - init_select(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - import_compiler_runtime259 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime330 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/ModelStep.tsx -function ModelStep() { - const $2 = import_compiler_runtime260.c(8); - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - let t0; - if ($2[0] !== goNext || $2[1] !== updateWizardData) { - t0 = (model) => { - updateWizardData({ - selectedModel: model - }); - goNext(); - }; - $2[0] = goNext; - $2[1] = updateWizardData; - $2[2] = t0; - } else { - t0 = $2[2]; - } - const handleComplete = t0; - let t1; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime331.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime331.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime331.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime331.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[3] = t1; - } else { - t1 = $2[3]; - } - let t22; - if ($2[4] !== goBack || $2[5] !== handleComplete || $2[6] !== wizardData.selectedModel) { - t22 = /* @__PURE__ */ jsx_dev_runtime331.jsxDEV(WizardDialogLayout, { - subtitle: "Select model", - footerText: t1, - children: /* @__PURE__ */ jsx_dev_runtime331.jsxDEV(ModelSelector, { - initialModel: wizardData.selectedModel, - onComplete: handleComplete, - onCancel: goBack - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[4] = goBack; - $2[5] = handleComplete; - $2[6] = wizardData.selectedModel; - $2[7] = t22; - } else { - t22 = $2[7]; - } - return t22; -} -var import_compiler_runtime260, jsx_dev_runtime331; -var init_ModelStep = __esm(() => { - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - init_ModelSelector(); - import_compiler_runtime260 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime331 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/PromptStep.tsx -function PromptStep() { - const $2 = import_compiler_runtime261.c(20); - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - const [systemPrompt, setSystemPrompt] = import_react184.useState(wizardData.systemPrompt || ""); - const [cursorOffset, setCursorOffset] = import_react184.useState(systemPrompt.length); - const [error46, setError] = import_react184.useState(null); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - context: "Settings" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - useKeybinding("confirm:no", goBack, t0); - let t1; - if ($2[1] !== systemPrompt) { - t1 = async () => { - const result = await editPromptInEditor(systemPrompt); - if (result.content !== null) { - setSystemPrompt(result.content); - setCursorOffset(result.content.length); - } - }; - $2[1] = systemPrompt; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const handleExternalEditor = t1; - let t22; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t22 = { - context: "Chat" - }; - $2[3] = t22; - } else { - t22 = $2[3]; - } - useKeybinding("chat:externalEditor", handleExternalEditor, t22); - let t32; - if ($2[4] !== goNext || $2[5] !== systemPrompt || $2[6] !== updateWizardData) { - t32 = () => { - const trimmedPrompt = systemPrompt.trim(); - if (!trimmedPrompt) { - setError("System prompt is required"); - return; - } - setError(null); - updateWizardData({ - systemPrompt: trimmedPrompt - }); - goNext(); - }; - $2[4] = goNext; - $2[5] = systemPrompt; - $2[6] = updateWizardData; - $2[7] = t32; - } else { - t32 = $2[7]; - } - const handleSubmit = t32; - let t4; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(KeyboardShortcutHint, { - shortcut: "Type", - action: "enter text" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "continue" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ConfigurableShortcutHint, { - action: "chat:externalEditor", - context: "Chat", - fallback: "ctrl+g", - description: "open in editor" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Settings", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - let t6; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ThemedText, { - children: "Enter the system prompt for your agent:" - }, undefined, false, undefined, this); - t6 = /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ThemedText, { - dimColor: true, - children: "Be comprehensive for best results" - }, undefined, false, undefined, this); - $2[9] = t5; - $2[10] = t6; - } else { - t5 = $2[9]; - t6 = $2[10]; - } - let t7; - if ($2[11] !== cursorOffset || $2[12] !== handleSubmit || $2[13] !== systemPrompt) { - t7 = /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(TextInput, { - value: systemPrompt, - onChange: setSystemPrompt, - onSubmit: handleSubmit, - placeholder: "You are a helpful code reviewer who...", - columns: 80, - cursorOffset, - onChangeCursorOffset: setCursorOffset, - focus: true, - showCursor: true - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[11] = cursorOffset; - $2[12] = handleSubmit; - $2[13] = systemPrompt; - $2[14] = t7; - } else { - t7 = $2[14]; - } - let t8; - if ($2[15] !== error46) { - t8 = error46 && /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[15] = error46; - $2[16] = t8; - } else { - t8 = $2[16]; - } - let t9; - if ($2[17] !== t7 || $2[18] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(WizardDialogLayout, { - subtitle: "System prompt", - footerText: t4, - children: /* @__PURE__ */ jsx_dev_runtime332.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t5, - t6, - t7, - t8 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[17] = t7; - $2[18] = t8; - $2[19] = t9; - } else { - t9 = $2[19]; - } - return t9; -} -var import_compiler_runtime261, import_react184, jsx_dev_runtime332; -var init_PromptStep = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_promptEditor(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_TextInput(); - init_wizard(); - init_WizardDialogLayout(); - import_compiler_runtime261 = __toESM(require_compiler_runtime(), 1); - import_react184 = __toESM(require_react(), 1); - jsx_dev_runtime332 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/ToolsStep.tsx -function ToolsStep(t0) { - const $2 = import_compiler_runtime262.c(9); - const { - tools - } = t0; - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - let t1; - if ($2[0] !== goNext || $2[1] !== updateWizardData) { - t1 = (selectedTools) => { - updateWizardData({ - selectedTools - }); - goNext(); - }; - $2[0] = goNext; - $2[1] = updateWizardData; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const handleComplete = t1; - const initialTools = wizardData.selectedTools; - let t22; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime333.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime333.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "toggle selection" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime333.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime333.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== goBack || $2[5] !== handleComplete || $2[6] !== initialTools || $2[7] !== tools) { - t32 = /* @__PURE__ */ jsx_dev_runtime333.jsxDEV(WizardDialogLayout, { - subtitle: "Select tools", - footerText: t22, - children: /* @__PURE__ */ jsx_dev_runtime333.jsxDEV(ToolSelector, { - tools, - initialTools, - onComplete: handleComplete, - onCancel: goBack - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[4] = goBack; - $2[5] = handleComplete; - $2[6] = initialTools; - $2[7] = tools; - $2[8] = t32; - } else { - t32 = $2[8]; - } - return t32; -} -var import_compiler_runtime262, jsx_dev_runtime333; -var init_ToolsStep = __esm(() => { - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_wizard(); - init_WizardDialogLayout(); - init_ToolSelector(); - import_compiler_runtime262 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime333 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/wizard-steps/TypeStep.tsx -function TypeStep(_props) { - const $2 = import_compiler_runtime263.c(15); - const { - goNext, - goBack, - updateWizardData, - wizardData - } = useWizard(); - const [agentType, setAgentType] = import_react185.useState(wizardData.agentType || ""); - const [error46, setError] = import_react185.useState(null); - const [cursorOffset, setCursorOffset] = import_react185.useState(agentType.length); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - context: "Settings" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - useKeybinding("confirm:no", goBack, t0); - let t1; - if ($2[1] !== goNext || $2[2] !== updateWizardData) { - t1 = (value) => { - const trimmedValue = value.trim(); - const validationError = validateAgentType(trimmedValue); - if (validationError) { - setError(validationError); - return; - } - setError(null); - updateWizardData({ - agentType: trimmedValue - }); - goNext(); - }; - $2[1] = goNext; - $2[2] = updateWizardData; - $2[3] = t1; - } else { - t1 = $2[3]; - } - const handleSubmit = t1; - let t22; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(KeyboardShortcutHint, { - shortcut: "Type", - action: "enter text" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "continue" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Settings", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(ThemedText, { - children: "Enter a unique identifier for your agent:" - }, undefined, false, undefined, this); - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== agentType || $2[7] !== cursorOffset || $2[8] !== handleSubmit) { - t4 = /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(TextInput, { - value: agentType, - onChange: setAgentType, - onSubmit: handleSubmit, - placeholder: "e.g., test-runner, tech-lead, etc", - columns: 60, - cursorOffset, - onChangeCursorOffset: setCursorOffset, - focus: true, - showCursor: true - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[6] = agentType; - $2[7] = cursorOffset; - $2[8] = handleSubmit; - $2[9] = t4; - } else { - t4 = $2[9]; - } - let t5; - if ($2[10] !== error46) { - t5 = error46 && /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[10] = error46; - $2[11] = t5; - } else { - t5 = $2[11]; - } - let t6; - if ($2[12] !== t4 || $2[13] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(WizardDialogLayout, { - subtitle: "Agent type (identifier)", - footerText: t22, - children: /* @__PURE__ */ jsx_dev_runtime334.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t32, - t4, - t5 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[12] = t4; - $2[13] = t5; - $2[14] = t6; - } else { - t6 = $2[14]; - } - return t6; -} -var import_compiler_runtime263, import_react185, jsx_dev_runtime334; -var init_TypeStep = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_KeyboardShortcutHint(); - init_TextInput(); - init_wizard(); - init_WizardDialogLayout(); - init_validateAgent(); - import_compiler_runtime263 = __toESM(require_compiler_runtime(), 1); - import_react185 = __toESM(require_react(), 1); - jsx_dev_runtime334 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/new-agent-creation/CreateAgentWizard.tsx -function CreateAgentWizard(t0) { - const $2 = import_compiler_runtime264.c(17); - const { - tools, - existingAgents, - onComplete, - onCancel - } = t0; - let t1; - if ($2[0] !== existingAgents) { - t1 = () => /* @__PURE__ */ jsx_dev_runtime335.jsxDEV(TypeStep, { - existingAgents - }, undefined, false, undefined, this); - $2[0] = existingAgents; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== tools) { - t22 = () => /* @__PURE__ */ jsx_dev_runtime335.jsxDEV(ToolsStep, { - tools - }, undefined, false, undefined, this); - $2[2] = tools; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = isAutoMemoryEnabled() ? [MemoryStep] : []; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== existingAgents || $2[6] !== onComplete || $2[7] !== tools) { - t4 = () => /* @__PURE__ */ jsx_dev_runtime335.jsxDEV(ConfirmStepWrapper, { - tools, - existingAgents, - onComplete - }, undefined, false, undefined, this); - $2[5] = existingAgents; - $2[6] = onComplete; - $2[7] = tools; - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] !== t1 || $2[10] !== t22 || $2[11] !== t4) { - t5 = [LocationStep, MethodStep, GenerateStep, t1, PromptStep, DescriptionStep, t22, ModelStep, ColorStep, ...t32, t4]; - $2[9] = t1; - $2[10] = t22; - $2[11] = t4; - $2[12] = t5; - } else { - t5 = $2[12]; - } - const steps = t5; - let t6; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t6 = {}; - $2[13] = t6; - } else { - t6 = $2[13]; - } - let t7; - if ($2[14] !== onCancel || $2[15] !== steps) { - t7 = /* @__PURE__ */ jsx_dev_runtime335.jsxDEV(WizardProvider, { - steps, - initialData: t6, - onComplete: _temp157, - onCancel, - title: "Create new agent", - showStepCounter: false - }, undefined, false, undefined, this); - $2[14] = onCancel; - $2[15] = steps; - $2[16] = t7; - } else { - t7 = $2[16]; - } - return t7; -} -function _temp157() {} -var import_compiler_runtime264, jsx_dev_runtime335; -var init_CreateAgentWizard = __esm(() => { - init_paths(); - init_wizard(); - init_ColorStep(); - init_ConfirmStepWrapper(); - init_DescriptionStep(); - init_GenerateStep(); - init_LocationStep(); - init_MemoryStep(); - init_MethodStep(); - init_ModelStep(); - init_PromptStep(); - init_ToolsStep(); - init_TypeStep(); - import_compiler_runtime264 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime335 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/agents/AgentsMenu.tsx -function AgentsMenu(t0) { - const $2 = import_compiler_runtime265.c(157); - const { - tools, - onExit: onExit2 - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - mode: "list-agents", - source: "all" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const [modeState, setModeState] = import_react186.useState(t1); - const agentDefinitions = useAppState(_temp158); - const mcpTools = useAppState(_temp269); - const toolPermissionContext = useAppState(_temp343); - const setAppState = useSetAppState(); - const { - allAgents, - activeAgents: agents - } = agentDefinitions; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = []; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const [changes, setChanges] = import_react186.useState(t22); - const mergedTools = useMergedTools(tools, mcpTools, toolPermissionContext); - useExitOnCtrlCDWithKeybindings(); - let t32; - if ($2[2] !== allAgents) { - t32 = allAgents.filter(_temp431); - $2[2] = allAgents; - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] !== allAgents) { - t4 = allAgents.filter(_temp523); - $2[4] = allAgents; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== allAgents) { - t5 = allAgents.filter(_temp620); - $2[6] = allAgents; - $2[7] = t5; - } else { - t5 = $2[7]; - } - let t6; - if ($2[8] !== allAgents) { - t6 = allAgents.filter(_temp716); - $2[8] = allAgents; - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] !== allAgents) { - t7 = allAgents.filter(_temp812); - $2[10] = allAgents; - $2[11] = t7; - } else { - t7 = $2[11]; - } - let t8; - if ($2[12] !== allAgents) { - t8 = allAgents.filter(_temp912); - $2[12] = allAgents; - $2[13] = t8; - } else { - t8 = $2[13]; - } - let t9; - if ($2[14] !== allAgents) { - t9 = allAgents.filter(_temp05); - $2[14] = allAgents; - $2[15] = t9; - } else { - t9 = $2[15]; - } - let t10; - if ($2[16] !== allAgents || $2[17] !== t32 || $2[18] !== t4 || $2[19] !== t5 || $2[20] !== t6 || $2[21] !== t7 || $2[22] !== t8 || $2[23] !== t9) { - t10 = { - "built-in": t32, - userSettings: t4, - projectSettings: t5, - policySettings: t6, - localSettings: t7, - flagSettings: t8, - plugin: t9, - all: allAgents - }; - $2[16] = allAgents; - $2[17] = t32; - $2[18] = t4; - $2[19] = t5; - $2[20] = t6; - $2[21] = t7; - $2[22] = t8; - $2[23] = t9; - $2[24] = t10; - } else { - t10 = $2[24]; - } - const agentsBySource = t10; - let t11; - if ($2[25] === Symbol.for("react.memo_cache_sentinel")) { - t11 = (message) => { - setChanges((prev) => [...prev, message]); - setModeState({ - mode: "list-agents", - source: "all" - }); - }; - $2[25] = t11; - } else { - t11 = $2[25]; - } - const handleAgentCreated = t11; - let t12; - if ($2[26] !== setAppState) { - t12 = async (agent) => { - try { - await deleteAgentFromFile(agent); - setAppState((state3) => { - const allAgents_0 = state3.agentDefinitions.allAgents.filter((a_6) => !(a_6.agentType === agent.agentType && a_6.source === agent.source)); - return { - ...state3, - agentDefinitions: { - ...state3.agentDefinitions, - allAgents: allAgents_0, - activeAgents: getActiveAgentsFromList(allAgents_0) - } - }; - }); - setChanges((prev_0) => [...prev_0, `Deleted agent: ${source_default.bold(agent.agentType)}`]); - setModeState({ - mode: "list-agents", - source: "all" - }); - } catch (t13) { - const error46 = t13; - logError2(toError(error46)); - } - }; - $2[26] = setAppState; - $2[27] = t12; - } else { - t12 = $2[27]; - } - const handleAgentDeleted = t12; - switch (modeState.mode) { - case "list-agents": { - let t13; - if ($2[28] !== agentsBySource || $2[29] !== modeState.source) { - t13 = modeState.source === "all" ? [...agentsBySource["built-in"], ...agentsBySource.userSettings, ...agentsBySource.projectSettings, ...agentsBySource.localSettings, ...agentsBySource.policySettings, ...agentsBySource.flagSettings, ...agentsBySource.plugin] : agentsBySource[modeState.source]; - $2[28] = agentsBySource; - $2[29] = modeState.source; - $2[30] = t13; - } else { - t13 = $2[30]; - } - const agentsToShow = t13; - let t14; - if ($2[31] !== agents || $2[32] !== agentsToShow) { - t14 = resolveAgentOverrides(agentsToShow, agents); - $2[31] = agents; - $2[32] = agentsToShow; - $2[33] = t14; - } else { - t14 = $2[33]; - } - const allResolved = t14; - const resolvedAgents = allResolved; - let t15; - if ($2[34] !== changes || $2[35] !== onExit2) { - t15 = () => { - const exitMessage = changes.length > 0 ? `Agent changes: -${changes.join(` -`)}` : undefined; - onExit2(exitMessage ?? "Agents dialog dismissed", { - display: changes.length === 0 ? "system" : undefined - }); - }; - $2[34] = changes; - $2[35] = onExit2; - $2[36] = t15; - } else { - t15 = $2[36]; - } - let t16; - if ($2[37] !== modeState) { - t16 = (agent_0) => setModeState({ - mode: "agent-menu", - agent: agent_0, - previousMode: modeState - }); - $2[37] = modeState; - $2[38] = t16; - } else { - t16 = $2[38]; - } - let t17; - if ($2[39] === Symbol.for("react.memo_cache_sentinel")) { - t17 = () => setModeState({ - mode: "create-agent" - }); - $2[39] = t17; - } else { - t17 = $2[39]; - } - let t18; - if ($2[40] !== changes || $2[41] !== modeState.source || $2[42] !== resolvedAgents || $2[43] !== t15 || $2[44] !== t16) { - t18 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentsList, { - source: modeState.source, - agents: resolvedAgents, - onBack: t15, - onSelect: t16, - onCreateNew: t17, - changes - }, undefined, false, undefined, this); - $2[40] = changes; - $2[41] = modeState.source; - $2[42] = resolvedAgents; - $2[43] = t15; - $2[44] = t16; - $2[45] = t18; - } else { - t18 = $2[45]; - } - let t19; - if ($2[46] === Symbol.for("react.memo_cache_sentinel")) { - t19 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentNavigationFooter, {}, undefined, false, undefined, this); - $2[46] = t19; - } else { - t19 = $2[46]; - } - let t20; - if ($2[47] !== t18) { - t20 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(jsx_dev_runtime336.Fragment, { - children: [ - t18, - t19 - ] - }, undefined, true, undefined, this); - $2[47] = t18; - $2[48] = t20; - } else { - t20 = $2[48]; - } - return t20; - } - case "create-agent": { - let t13; - if ($2[49] === Symbol.for("react.memo_cache_sentinel")) { - t13 = () => setModeState({ - mode: "list-agents", - source: "all" - }); - $2[49] = t13; - } else { - t13 = $2[49]; - } - let t14; - if ($2[50] !== agents || $2[51] !== mergedTools) { - t14 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(CreateAgentWizard, { - tools: mergedTools, - existingAgents: agents, - onComplete: handleAgentCreated, - onCancel: t13 - }, undefined, false, undefined, this); - $2[50] = agents; - $2[51] = mergedTools; - $2[52] = t14; - } else { - t14 = $2[52]; - } - return t14; - } - case "agent-menu": { - let t13; - if ($2[53] !== allAgents || $2[54] !== modeState.agent.agentType || $2[55] !== modeState.agent.source) { - let t142; - if ($2[57] !== modeState.agent.agentType || $2[58] !== modeState.agent.source) { - t142 = (a_9) => a_9.agentType === modeState.agent.agentType && a_9.source === modeState.agent.source; - $2[57] = modeState.agent.agentType; - $2[58] = modeState.agent.source; - $2[59] = t142; - } else { - t142 = $2[59]; - } - t13 = allAgents.find(t142); - $2[53] = allAgents; - $2[54] = modeState.agent.agentType; - $2[55] = modeState.agent.source; - $2[56] = t13; - } else { - t13 = $2[56]; - } - const freshAgent_1 = t13; - const agentToUse = freshAgent_1 || modeState.agent; - const isEditable = agentToUse.source !== "built-in" && agentToUse.source !== "plugin" && agentToUse.source !== "flagSettings"; - let t14; - if ($2[60] === Symbol.for("react.memo_cache_sentinel")) { - t14 = { - label: "View agent", - value: "view" - }; - $2[60] = t14; - } else { - t14 = $2[60]; - } - let t15; - if ($2[61] !== isEditable) { - t15 = isEditable ? [{ - label: "Edit agent", - value: "edit" - }, { - label: "Delete agent", - value: "delete" - }] : []; - $2[61] = isEditable; - $2[62] = t15; - } else { - t15 = $2[62]; - } - let t16; - if ($2[63] === Symbol.for("react.memo_cache_sentinel")) { - t16 = { - label: "Back", - value: "back" - }; - $2[63] = t16; - } else { - t16 = $2[63]; - } - let t17; - if ($2[64] !== t15) { - t17 = [t14, ...t15, t16]; - $2[64] = t15; - $2[65] = t17; - } else { - t17 = $2[65]; - } - const menuItems = t17; - let t18; - if ($2[66] !== agentToUse || $2[67] !== modeState) { - t18 = (value_0) => { - bb129: - switch (value_0) { - case "view": { - setModeState({ - mode: "view-agent", - agent: agentToUse, - previousMode: modeState.previousMode - }); - break bb129; - } - case "edit": { - setModeState({ - mode: "edit-agent", - agent: agentToUse, - previousMode: modeState - }); - break bb129; - } - case "delete": { - setModeState({ - mode: "delete-confirm", - agent: agentToUse, - previousMode: modeState - }); - break bb129; - } - case "back": { - setModeState(modeState.previousMode); - } - } - }; - $2[66] = agentToUse; - $2[67] = modeState; - $2[68] = t18; - } else { - t18 = $2[68]; - } - const handleMenuSelect = t18; - let t19; - if ($2[69] !== modeState.previousMode) { - t19 = () => setModeState(modeState.previousMode); - $2[69] = modeState.previousMode; - $2[70] = t19; - } else { - t19 = $2[70]; - } - let t20; - if ($2[71] !== modeState.previousMode) { - t20 = () => setModeState(modeState.previousMode); - $2[71] = modeState.previousMode; - $2[72] = t20; - } else { - t20 = $2[72]; - } - let t21; - if ($2[73] !== handleMenuSelect || $2[74] !== menuItems || $2[75] !== t20) { - t21 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(Select, { - options: menuItems, - onChange: handleMenuSelect, - onCancel: t20 - }, undefined, false, undefined, this); - $2[73] = handleMenuSelect; - $2[74] = menuItems; - $2[75] = t20; - $2[76] = t21; - } else { - t21 = $2[76]; - } - let t222; - if ($2[77] !== changes) { - t222 = changes.length > 0 && /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedText, { - dimColor: true, - children: changes[changes.length - 1] - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[77] = changes; - $2[78] = t222; - } else { - t222 = $2[78]; - } - let t23; - if ($2[79] !== t21 || $2[80] !== t222) { - t23 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t21, - t222 - ] - }, undefined, true, undefined, this); - $2[79] = t21; - $2[80] = t222; - $2[81] = t23; - } else { - t23 = $2[81]; - } - let t24; - if ($2[82] !== modeState.agent.agentType || $2[83] !== t19 || $2[84] !== t23) { - t24 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(Dialog, { - title: modeState.agent.agentType, - onCancel: t19, - hideInputGuide: true, - children: t23 - }, undefined, false, undefined, this); - $2[82] = modeState.agent.agentType; - $2[83] = t19; - $2[84] = t23; - $2[85] = t24; - } else { - t24 = $2[85]; - } - let t25; - if ($2[86] === Symbol.for("react.memo_cache_sentinel")) { - t25 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentNavigationFooter, {}, undefined, false, undefined, this); - $2[86] = t25; - } else { - t25 = $2[86]; - } - let t26; - if ($2[87] !== t24) { - t26 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(jsx_dev_runtime336.Fragment, { - children: [ - t24, - t25 - ] - }, undefined, true, undefined, this); - $2[87] = t24; - $2[88] = t26; - } else { - t26 = $2[88]; - } - return t26; - } - case "view-agent": { - let t13; - if ($2[89] !== allAgents || $2[90] !== modeState.agent) { - let t142; - if ($2[92] !== modeState.agent) { - t142 = (a_8) => a_8.agentType === modeState.agent.agentType && a_8.source === modeState.agent.source; - $2[92] = modeState.agent; - $2[93] = t142; - } else { - t142 = $2[93]; - } - t13 = allAgents.find(t142); - $2[89] = allAgents; - $2[90] = modeState.agent; - $2[91] = t13; - } else { - t13 = $2[91]; - } - const freshAgent_0 = t13; - const agentToDisplay = freshAgent_0 || modeState.agent; - let t14; - if ($2[94] !== agentToDisplay || $2[95] !== modeState.previousMode) { - t14 = () => setModeState({ - mode: "agent-menu", - agent: agentToDisplay, - previousMode: modeState.previousMode - }); - $2[94] = agentToDisplay; - $2[95] = modeState.previousMode; - $2[96] = t14; - } else { - t14 = $2[96]; - } - let t15; - if ($2[97] !== agentToDisplay || $2[98] !== modeState.previousMode) { - t15 = () => setModeState({ - mode: "agent-menu", - agent: agentToDisplay, - previousMode: modeState.previousMode - }); - $2[97] = agentToDisplay; - $2[98] = modeState.previousMode; - $2[99] = t15; - } else { - t15 = $2[99]; - } - let t16; - if ($2[100] !== agentToDisplay || $2[101] !== allAgents || $2[102] !== mergedTools || $2[103] !== t15) { - t16 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentDetail, { - agent: agentToDisplay, - tools: mergedTools, - allAgents, - onBack: t15 - }, undefined, false, undefined, this); - $2[100] = agentToDisplay; - $2[101] = allAgents; - $2[102] = mergedTools; - $2[103] = t15; - $2[104] = t16; - } else { - t16 = $2[104]; - } - let t17; - if ($2[105] !== agentToDisplay.agentType || $2[106] !== t14 || $2[107] !== t16) { - t17 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(Dialog, { - title: agentToDisplay.agentType, - onCancel: t14, - hideInputGuide: true, - children: t16 - }, undefined, false, undefined, this); - $2[105] = agentToDisplay.agentType; - $2[106] = t14; - $2[107] = t16; - $2[108] = t17; - } else { - t17 = $2[108]; - } - let t18; - if ($2[109] === Symbol.for("react.memo_cache_sentinel")) { - t18 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentNavigationFooter, { - instructions: "Press Enter or Esc to go back" - }, undefined, false, undefined, this); - $2[109] = t18; - } else { - t18 = $2[109]; - } - let t19; - if ($2[110] !== t17) { - t19 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(jsx_dev_runtime336.Fragment, { - children: [ - t17, - t18 - ] - }, undefined, true, undefined, this); - $2[110] = t17; - $2[111] = t19; - } else { - t19 = $2[111]; - } - return t19; - } - case "delete-confirm": { - let t13; - if ($2[112] === Symbol.for("react.memo_cache_sentinel")) { - t13 = [{ - label: "Yes, delete", - value: "yes" - }, { - label: "No, cancel", - value: "no" - }]; - $2[112] = t13; - } else { - t13 = $2[112]; - } - const deleteOptions = t13; - let t14; - if ($2[113] !== modeState) { - t14 = () => { - if ("previousMode" in modeState) { - setModeState(modeState.previousMode); - } - }; - $2[113] = modeState; - $2[114] = t14; - } else { - t14 = $2[114]; - } - let t15; - if ($2[115] !== modeState.agent.agentType) { - t15 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedText, { - children: [ - "Are you sure you want to delete the agent", - " ", - /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedText, { - bold: true, - children: modeState.agent.agentType - }, undefined, false, undefined, this), - "?" - ] - }, undefined, true, undefined, this); - $2[115] = modeState.agent.agentType; - $2[116] = t15; - } else { - t15 = $2[116]; - } - let t16; - if ($2[117] !== modeState.agent.source) { - t16 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Source: ", - modeState.agent.source - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[117] = modeState.agent.source; - $2[118] = t16; - } else { - t16 = $2[118]; - } - let t17; - if ($2[119] !== handleAgentDeleted || $2[120] !== modeState) { - t17 = (value) => { - if (value === "yes") { - handleAgentDeleted(modeState.agent); - } else { - if ("previousMode" in modeState) { - setModeState(modeState.previousMode); - } - } - }; - $2[119] = handleAgentDeleted; - $2[120] = modeState; - $2[121] = t17; - } else { - t17 = $2[121]; - } - let t18; - if ($2[122] !== modeState) { - t18 = () => { - if ("previousMode" in modeState) { - setModeState(modeState.previousMode); - } - }; - $2[122] = modeState; - $2[123] = t18; - } else { - t18 = $2[123]; - } - let t19; - if ($2[124] !== t17 || $2[125] !== t18) { - t19 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(Select, { - options: deleteOptions, - onChange: t17, - onCancel: t18 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[124] = t17; - $2[125] = t18; - $2[126] = t19; - } else { - t19 = $2[126]; - } - let t20; - if ($2[127] !== t14 || $2[128] !== t15 || $2[129] !== t16 || $2[130] !== t19) { - t20 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(Dialog, { - title: "Delete agent", - onCancel: t14, - color: "error", - children: [ - t15, - t16, - t19 - ] - }, undefined, true, undefined, this); - $2[127] = t14; - $2[128] = t15; - $2[129] = t16; - $2[130] = t19; - $2[131] = t20; - } else { - t20 = $2[131]; - } - let t21; - if ($2[132] === Symbol.for("react.memo_cache_sentinel")) { - t21 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentNavigationFooter, { - instructions: "Press \u2191\u2193 to navigate, Enter to select, Esc to cancel" - }, undefined, false, undefined, this); - $2[132] = t21; - } else { - t21 = $2[132]; - } - let t222; - if ($2[133] !== t20) { - t222 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(jsx_dev_runtime336.Fragment, { - children: [ - t20, - t21 - ] - }, undefined, true, undefined, this); - $2[133] = t20; - $2[134] = t222; - } else { - t222 = $2[134]; - } - return t222; - } - case "edit-agent": { - let t13; - if ($2[135] !== allAgents || $2[136] !== modeState.agent) { - let t142; - if ($2[138] !== modeState.agent) { - t142 = (a_7) => a_7.agentType === modeState.agent.agentType && a_7.source === modeState.agent.source; - $2[138] = modeState.agent; - $2[139] = t142; - } else { - t142 = $2[139]; - } - t13 = allAgents.find(t142); - $2[135] = allAgents; - $2[136] = modeState.agent; - $2[137] = t13; - } else { - t13 = $2[137]; - } - const freshAgent = t13; - const agentToEdit = freshAgent || modeState.agent; - const t14 = `Edit agent: ${agentToEdit.agentType}`; - let t15; - if ($2[140] !== modeState.previousMode) { - t15 = () => setModeState(modeState.previousMode); - $2[140] = modeState.previousMode; - $2[141] = t15; - } else { - t15 = $2[141]; - } - let t16; - let t17; - if ($2[142] !== modeState.previousMode) { - t16 = (message_0) => { - handleAgentCreated(message_0); - setModeState(modeState.previousMode); - }; - t17 = () => setModeState(modeState.previousMode); - $2[142] = modeState.previousMode; - $2[143] = t16; - $2[144] = t17; - } else { - t16 = $2[143]; - t17 = $2[144]; - } - let t18; - if ($2[145] !== agentToEdit || $2[146] !== mergedTools || $2[147] !== t16 || $2[148] !== t17) { - t18 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentEditor, { - agent: agentToEdit, - tools: mergedTools, - onSaved: t16, - onBack: t17 - }, undefined, false, undefined, this); - $2[145] = agentToEdit; - $2[146] = mergedTools; - $2[147] = t16; - $2[148] = t17; - $2[149] = t18; - } else { - t18 = $2[149]; - } - let t19; - if ($2[150] !== t14 || $2[151] !== t15 || $2[152] !== t18) { - t19 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(Dialog, { - title: t14, - onCancel: t15, - hideInputGuide: true, - children: t18 - }, undefined, false, undefined, this); - $2[150] = t14; - $2[151] = t15; - $2[152] = t18; - $2[153] = t19; - } else { - t19 = $2[153]; - } - let t20; - if ($2[154] === Symbol.for("react.memo_cache_sentinel")) { - t20 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(AgentNavigationFooter, {}, undefined, false, undefined, this); - $2[154] = t20; - } else { - t20 = $2[154]; - } - let t21; - if ($2[155] !== t19) { - t21 = /* @__PURE__ */ jsx_dev_runtime336.jsxDEV(jsx_dev_runtime336.Fragment, { - children: [ - t19, - t20 - ] - }, undefined, true, undefined, this); - $2[155] = t19; - $2[156] = t21; - } else { - t21 = $2[156]; - } - return t21; - } - default: { - return null; - } - } -} -function _temp05(a_5) { - return a_5.source === "plugin"; -} -function _temp912(a_4) { - return a_4.source === "flagSettings"; -} -function _temp812(a_3) { - return a_3.source === "localSettings"; -} -function _temp716(a_2) { - return a_2.source === "policySettings"; -} -function _temp620(a_1) { - return a_1.source === "projectSettings"; -} -function _temp523(a_0) { - return a_0.source === "userSettings"; -} -function _temp431(a5) { - return a5.source === "built-in"; -} -function _temp343(s_1) { - return s_1.toolPermissionContext; -} -function _temp269(s_0) { - return s_0.mcp.tools; -} -function _temp158(s4) { - return s4.agentDefinitions; -} -var import_compiler_runtime265, import_react186, jsx_dev_runtime336; -var init_AgentsMenu = __esm(() => { - init_source(); - init_useExitOnCtrlCDWithKeybindings(); - init_useMergedTools(); - init_ink2(); - init_AppState(); - init_agentDisplay(); - init_loadAgentsDir(); - init_errors(); - init_log2(); - init_select(); - init_Dialog(); - init_AgentDetail(); - init_AgentEditor(); - init_AgentNavigationFooter(); - init_AgentsList(); - init_agentFileUtils(); - init_CreateAgentWizard(); - import_compiler_runtime265 = __toESM(require_compiler_runtime(), 1); - import_react186 = __toESM(require_react(), 1); - jsx_dev_runtime336 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/agents/agents.tsx -var exports_agents = {}; -__export(exports_agents, { - call: () => call50 -}); -async function call50(onDone, context7) { - const appState = context7.getAppState(); - const permissionContext = appState.toolPermissionContext; - const tools = getTools(permissionContext); - return /* @__PURE__ */ jsx_dev_runtime337.jsxDEV(AgentsMenu, { - tools, - onExit: onDone - }, undefined, false, undefined, this); -} -var jsx_dev_runtime337; -var init_agents = __esm(() => { - init_AgentsMenu(); - init_tools2(); - jsx_dev_runtime337 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/agents/index.ts -var agents, agents_default; -var init_agents2 = __esm(() => { - agents = { - type: "local-jsx", - name: "agents", - description: "Manage agent configurations", - load: () => Promise.resolve().then(() => (init_agents(), exports_agents)) - }; - agents_default = agents; -}); - -// src/commands/plugin/plugin.tsx -var exports_plugin = {}; -__export(exports_plugin, { - call: () => call51 -}); -async function call51(onDone, _context, args) { - return /* @__PURE__ */ jsx_dev_runtime338.jsxDEV(PluginSettings, { - onComplete: onDone, - args - }, undefined, false, undefined, this); -} -var jsx_dev_runtime338; -var init_plugin = __esm(() => { - init_PluginSettings(); - jsx_dev_runtime338 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/plugin/index.tsx -var plugin, plugin_default; -var init_plugin2 = __esm(() => { - plugin = { - type: "local-jsx", - name: "plugin", - aliases: ["plugins", "marketplace"], - description: "Manage Claude Code plugins", - immediate: true, - load: () => Promise.resolve().then(() => (init_plugin(), exports_plugin)) - }; - plugin_default = plugin; -}); - -// src/services/settingsSync/types.ts -var UserSyncContentSchema, UserSyncDataSchema; -var init_types25 = __esm(() => { - init_v4(); - UserSyncContentSchema = lazySchema(() => exports_external.object({ - entries: exports_external.record(exports_external.string(), exports_external.string()) - })); - UserSyncDataSchema = lazySchema(() => exports_external.object({ - userId: exports_external.string(), - version: exports_external.number(), - lastModified: exports_external.string(), - checksum: exports_external.string(), - content: UserSyncContentSchema() - })); -}); - -// src/services/settingsSync/index.ts -var MAX_FILE_SIZE_BYTES3; -var init_settingsSync = __esm(() => { - init_state(); - init_oauth(); - init_auth14(); - init_claudemd(); - init_config(); - init_diagLogs(); - init_errors(); - init_git(); - init_providers(); - init_internalWrites(); - init_settings2(); - init_settingsCache(); - init_growthbook(); - init_analytics(); - init_withRetry(); - init_types25(); - MAX_FILE_SIZE_BYTES3 = 500 * 1024; -}); - -// src/utils/plugins/refresh.ts -async function refreshActivePlugins(setAppState) { - logForDebugging("refreshActivePlugins: clearing all plugin caches"); - clearAllCaches(); - clearPluginCacheExclusions(); - const pluginResult = await loadAllPlugins(); - const [pluginCommands, agentDefinitions] = await Promise.all([ - getPluginCommands(), - getAgentDefinitionsWithOverrides(getOriginalCwd()) - ]); - const { enabled: enabled2, disabled, errors: errors8 } = pluginResult; - const [mcpCounts, lspCounts] = await Promise.all([ - Promise.all(enabled2.map(async (p4) => { - if (p4.mcpServers) - return Object.keys(p4.mcpServers).length; - const servers = await loadPluginMcpServers(p4, errors8); - if (servers) - p4.mcpServers = servers; - return servers ? Object.keys(servers).length : 0; - })), - Promise.all(enabled2.map(async (p4) => { - if (p4.lspServers) - return Object.keys(p4.lspServers).length; - const servers = await loadPluginLspServers(p4, errors8); - if (servers) - p4.lspServers = servers; - return servers ? Object.keys(servers).length : 0; - })) - ]); - const mcp_count = mcpCounts.reduce((sum, n5) => sum + n5, 0); - const lsp_count = lspCounts.reduce((sum, n5) => sum + n5, 0); - setAppState((prev) => ({ - ...prev, - plugins: { - ...prev.plugins, - enabled: enabled2, - disabled, - commands: pluginCommands, - errors: mergePluginErrors(prev.plugins.errors, errors8), - needsRefresh: false - }, - agentDefinitions, - mcp: { - ...prev.mcp, - pluginReconnectKey: prev.mcp.pluginReconnectKey + 1 - } - })); - reinitializeLspServerManager(); - let hook_load_failed = false; - try { - await loadPluginHooks2(); - } catch (e4) { - hook_load_failed = true; - logError2(e4); - logForDebugging(`refreshActivePlugins: loadPluginHooks failed: ${errorMessage(e4)}`); - } - const hook_count = enabled2.reduce((sum, p4) => { - if (!p4.hooksConfig) - return sum; - return sum + Object.values(p4.hooksConfig).reduce((s4, matchers) => s4 + (matchers?.reduce((h5, m4) => h5 + m4.hooks.length, 0) ?? 0), 0); - }, 0); - logForDebugging(`refreshActivePlugins: ${enabled2.length} enabled, ${pluginCommands.length} commands, ${agentDefinitions.allAgents.length} agents, ${hook_count} hooks, ${mcp_count} MCP, ${lsp_count} LSP`); - return { - enabled_count: enabled2.length, - disabled_count: disabled.length, - command_count: pluginCommands.length, - agent_count: agentDefinitions.allAgents.length, - hook_count, - mcp_count, - lsp_count, - error_count: errors8.length + (hook_load_failed ? 1 : 0), - agentDefinitions, - pluginCommands - }; -} -function mergePluginErrors(existing, fresh) { - const preserved = existing.filter((e4) => e4.source === "lsp-manager" || e4.source.startsWith("plugin:")); - const freshKeys = new Set(fresh.map(errorKey)); - const deduped = preserved.filter((e4) => !freshKeys.has(errorKey(e4))); - return [...deduped, ...fresh]; -} -function errorKey(e4) { - return e4.type === "generic-error" ? `generic-error:${e4.source}:${e4.error}` : `${e4.type}:${e4.source}`; -} -var init_refresh = __esm(() => { - init_state(); - init_manager7(); - init_loadAgentsDir(); - init_debug(); - init_errors(); - init_log2(); - init_cacheUtils(); - init_loadPluginCommands(); - init_loadPluginHooks(); - init_lspPluginIntegration(); - init_mcpPluginIntegration(); - init_orphanedPluginFilter(); - init_pluginLoader(); -}); - -// src/commands/reload-plugins/reload-plugins.ts -var exports_reload_plugins = {}; -__export(exports_reload_plugins, { - call: () => call52 -}); -function n5(count4, noun) { - return `${count4} ${plural(count4, noun)}`; -} -var call52 = async (_args, context7) => { - if (false) {} - const r4 = await refreshActivePlugins(context7.setAppState); - const parts = [ - n5(r4.enabled_count, "plugin"), - n5(r4.command_count, "skill"), - n5(r4.agent_count, "agent"), - n5(r4.hook_count, "hook"), - n5(r4.mcp_count, "plugin MCP server"), - n5(r4.lsp_count, "plugin LSP server") - ]; - let msg = `Reloaded: ${parts.join(" \xB7 ")}`; - if (r4.error_count > 0) { - msg += ` -${n5(r4.error_count, "error")} during load. Run /doctor for details.`; - } - return { type: "text", value: msg }; -}; -var init_reload_plugins = __esm(() => { - init_state(); - init_settingsSync(); - init_envUtils(); - init_refresh(); - init_changeDetector(); - init_stringUtils(); -}); - -// src/commands/reload-plugins/index.ts -var reloadPlugins, reload_plugins_default; -var init_reload_plugins2 = __esm(() => { - reloadPlugins = { - type: "local", - name: "reload-plugins", - description: "Activate pending plugin changes in the current session", - supportsNonInteractive: false, - load: () => Promise.resolve().then(() => (init_reload_plugins(), exports_reload_plugins)) - }; - reload_plugins_default = reloadPlugins; -}); - -// src/commands/rewind/rewind.ts -var exports_rewind = {}; -__export(exports_rewind, { - call: () => call53 -}); -async function call53(_args, context7) { - if (context7.openMessageSelector) { - context7.openMessageSelector(); - } - return { type: "skip" }; -} - -// src/commands/rewind/index.ts -var rewind, rewind_default; -var init_rewind = __esm(() => { - rewind = { - description: `Restore the code and/or conversation to a previous point`, - name: "rewind", - aliases: ["checkpoint"], - argumentHint: "", - type: "local", - supportsNonInteractive: false, - load: () => Promise.resolve().then(() => exports_rewind) - }; - rewind_default = rewind; -}); - -// src/utils/heapDumpService.ts -import { createWriteStream as createWriteStream3, writeFileSync as writeFileSync8 } from "fs"; -import { readdir as readdir26, readFile as readFile50, writeFile as writeFile40 } from "fs/promises"; -import { join as join130 } from "path"; -import { pipeline as pipeline3 } from "stream/promises"; -import { - getHeapSnapshot, - getHeapSpaceStatistics, - getHeapStatistics -} from "v8"; -async function captureMemoryDiagnostics(trigger, dumpNumber = 0) { - const usage = process.memoryUsage(); - const heapStats = getHeapStatistics(); - const resourceUsage = process.resourceUsage(); - const uptimeSeconds = process.uptime(); - let heapSpaceStats; - try { - heapSpaceStats = getHeapSpaceStatistics(); - } catch {} - const activeHandles = process._getActiveHandles().length; - const activeRequests = process._getActiveRequests().length; - let openFileDescriptors; - try { - openFileDescriptors = (await readdir26("/proc/self/fd")).length; - } catch {} - let smapsRollup; - try { - smapsRollup = await readFile50("/proc/self/smaps_rollup", "utf8"); - } catch {} - const nativeMemory = usage.rss - usage.heapUsed; - const bytesPerSecond = uptimeSeconds > 0 ? usage.rss / uptimeSeconds : 0; - const mbPerHour = bytesPerSecond * 3600 / (1024 * 1024); - const potentialLeaks = []; - if (heapStats.number_of_detached_contexts > 0) { - potentialLeaks.push(`${heapStats.number_of_detached_contexts} detached context(s) - possible iframe/context leak`); - } - if (activeHandles > 100) { - potentialLeaks.push(`${activeHandles} active handles - possible timer/socket leak`); - } - if (nativeMemory > usage.heapUsed) { - potentialLeaks.push("Native memory > heap - leak may be in native addons (node-pty, sharp, etc.)"); - } - if (mbPerHour > 100) { - potentialLeaks.push(`High memory growth rate: ${mbPerHour.toFixed(1)} MB/hour`); - } - if (openFileDescriptors && openFileDescriptors > 500) { - potentialLeaks.push(`${openFileDescriptors} open file descriptors - possible file/socket leak`); - } - return { - timestamp: new Date().toISOString(), - sessionId: getSessionId(), - trigger, - dumpNumber, - uptimeSeconds, - memoryUsage: { - heapUsed: usage.heapUsed, - heapTotal: usage.heapTotal, - external: usage.external, - arrayBuffers: usage.arrayBuffers, - rss: usage.rss - }, - memoryGrowthRate: { - bytesPerSecond, - mbPerHour - }, - v8HeapStats: { - heapSizeLimit: heapStats.heap_size_limit, - mallocedMemory: heapStats.malloced_memory, - peakMallocedMemory: heapStats.peak_malloced_memory, - detachedContexts: heapStats.number_of_detached_contexts, - nativeContexts: heapStats.number_of_native_contexts - }, - v8HeapSpaces: heapSpaceStats?.map((space) => ({ - name: space.space_name, - size: space.space_size, - used: space.space_used_size, - available: space.space_available_size - })), - resourceUsage: { - maxRSS: resourceUsage.maxRSS * 1024, - userCPUTime: resourceUsage.userCPUTime, - systemCPUTime: resourceUsage.systemCPUTime - }, - activeHandles, - activeRequests, - openFileDescriptors, - analysis: { - potentialLeaks, - recommendation: potentialLeaks.length > 0 ? `WARNING: ${potentialLeaks.length} potential leak indicator(s) found. See potentialLeaks array.` : "No obvious leak indicators. Check heap snapshot for retained objects." - }, - smapsRollup, - platform: process.platform, - nodeVersion: process.version, - ccVersion: MACRO.VERSION - }; -} -async function performHeapDump(trigger = "manual", dumpNumber = 0) { - try { - const sessionId = getSessionId(); - const diagnostics = await captureMemoryDiagnostics(trigger, dumpNumber); - const toGB = (bytes) => (bytes / 1024 / 1024 / 1024).toFixed(3); - logForDebugging(`[HeapDump] Memory state: - heapUsed: ${toGB(diagnostics.memoryUsage.heapUsed)} GB (in snapshot) - external: ${toGB(diagnostics.memoryUsage.external)} GB (NOT in snapshot) - rss: ${toGB(diagnostics.memoryUsage.rss)} GB (total process) - ${diagnostics.analysis.recommendation}`); - const dumpDir = getDesktopPath(); - await getFsImplementation().mkdir(dumpDir); - const suffix = dumpNumber > 0 ? `-dump${dumpNumber}` : ""; - const heapFilename = `${sessionId}${suffix}.heapsnapshot`; - const diagFilename = `${sessionId}${suffix}-diagnostics.json`; - const heapPath = join130(dumpDir, heapFilename); - const diagPath = join130(dumpDir, diagFilename); - await writeFile40(diagPath, jsonStringify(diagnostics, null, 2), { - mode: 384 - }); - logForDebugging(`[HeapDump] Diagnostics written to ${diagPath}`); - await writeHeapSnapshot(heapPath); - logForDebugging(`[HeapDump] Heap dump written to ${heapPath}`); - logEvent("tengu_heap_dump", { - triggerManual: trigger === "manual", - triggerAuto15GB: trigger === "auto-1.5GB", - dumpNumber, - success: true - }); - return { success: true, heapPath, diagPath }; - } catch (err2) { - const error46 = toError(err2); - logError2(error46); - logEvent("tengu_heap_dump", { - triggerManual: trigger === "manual", - triggerAuto15GB: trigger === "auto-1.5GB", - dumpNumber, - success: false - }); - return { success: false, error: error46.message }; - } -} -async function writeHeapSnapshot(filepath) { - if (typeof Bun !== "undefined") { - writeFileSync8(filepath, Bun.generateHeapSnapshot("v8", "arraybuffer"), { - mode: 384 - }); - Bun.gc(true); - return; - } - const writeStream = createWriteStream3(filepath, { mode: 384 }); - const heapSnapshotStream = getHeapSnapshot(); - await pipeline3(heapSnapshotStream, writeStream); -} -var init_heapDumpService = __esm(() => { - init_state(); - init_analytics(); - init_debug(); - init_errors(); - init_file(); - init_fsOperations(); - init_log2(); - init_slowOperations(); -}); - -// src/commands/heapdump/heapdump.ts -var exports_heapdump = {}; -__export(exports_heapdump, { - call: () => call54 -}); -async function call54() { - const result = await performHeapDump(); - if (!result.success) { - return { - type: "text", - value: `Failed to create heap dump: ${result.error}` - }; - } - return { - type: "text", - value: `${result.heapPath} -${result.diagPath}` - }; -} -var init_heapdump = __esm(() => { - init_heapDumpService(); -}); - -// src/commands/heapdump/index.ts -var heapDump, heapdump_default; -var init_heapdump2 = __esm(() => { - heapDump = { - type: "local", - name: "heapdump", - description: "Dump the JS heap to ~/Desktop", - isHidden: true, - supportsNonInteractive: true, - load: () => Promise.resolve().then(() => (init_heapdump(), exports_heapdump)) - }; - heapdump_default = heapDump; -}); - -// src/commands/mock-limits/index.js -var mock_limits_default; -var init_mock_limits = __esm(() => { - mock_limits_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/bridge/bridgeApi.ts -function validateBridgeId(id, label) { - if (!id || !SAFE_ID_PATTERN.test(id)) { - throw new Error(`Invalid ${label}: contains unsafe characters`); - } - return id; -} -function createBridgeApiClient(deps) { - function debug2(msg) { - deps.onDebug?.(msg); - } - let consecutiveEmptyPolls = 0; - const EMPTY_POLL_LOG_INTERVAL = 100; - function getHeaders(accessToken) { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "anthropic-version": "2023-06-01", - "anthropic-beta": BETA_HEADER, - "x-environment-runner-version": deps.runnerVersion - }; - const deviceToken = deps.getTrustedDeviceToken?.(); - if (deviceToken) { - headers["X-Trusted-Device-Token"] = deviceToken; - } - return headers; - } - function resolveAuth() { - const accessToken = deps.getAccessToken(); - if (!accessToken) { - throw new Error(BRIDGE_LOGIN_INSTRUCTION); - } - return accessToken; - } - async function withOAuthRetry(fn, context7) { - const accessToken = resolveAuth(); - const response7 = await fn(accessToken); - if (response7.status !== 401) { - return response7; - } - if (!deps.onAuth401) { - debug2(`[bridge:api] ${context7}: 401 received, no refresh handler`); - return response7; - } - debug2(`[bridge:api] ${context7}: 401 received, attempting token refresh`); - const refreshed2 = await deps.onAuth401(accessToken); - if (refreshed2) { - debug2(`[bridge:api] ${context7}: Token refreshed, retrying request`); - const newToken = resolveAuth(); - const retryResponse = await fn(newToken); - if (retryResponse.status !== 401) { - return retryResponse; - } - debug2(`[bridge:api] ${context7}: Retry after refresh also got 401`); - } else { - debug2(`[bridge:api] ${context7}: Token refresh failed`); - } - return response7; - } - return { - async registerBridgeEnvironment(config10) { - debug2(`[bridge:api] POST /v1/environments/bridge bridgeId=${config10.bridgeId}`); - const response7 = await withOAuthRetry((token) => axios_default.post(`${deps.baseUrl}/v1/environments/bridge`, { - machine_name: config10.machineName, - directory: config10.dir, - branch: config10.branch, - git_repo_url: config10.gitRepoUrl, - max_sessions: config10.maxSessions, - metadata: { worker_type: config10.workerType }, - ...config10.reuseEnvironmentId && { - environment_id: config10.reuseEnvironmentId - } - }, { - headers: getHeaders(token), - timeout: 15000, - validateStatus: (status2) => status2 < 500 - }), "Registration"); - handleErrorStatus(response7.status, response7.data, "Registration"); - debug2(`[bridge:api] POST /v1/environments/bridge -> ${response7.status} environment_id=${response7.data.environment_id}`); - debug2(`[bridge:api] >>> ${debugBody({ machine_name: config10.machineName, directory: config10.dir, branch: config10.branch, git_repo_url: config10.gitRepoUrl, max_sessions: config10.maxSessions, metadata: { worker_type: config10.workerType } })}`); - debug2(`[bridge:api] <<< ${debugBody(response7.data)}`); - return response7.data; - }, - async pollForWork(environmentId, environmentSecret, signal, reclaimOlderThanMs) { - validateBridgeId(environmentId, "environmentId"); - const prevEmptyPolls = consecutiveEmptyPolls; - consecutiveEmptyPolls = 0; - const response7 = await axios_default.get(`${deps.baseUrl}/v1/environments/${environmentId}/work/poll`, { - headers: getHeaders(environmentSecret), - params: reclaimOlderThanMs !== undefined ? { reclaim_older_than_ms: reclaimOlderThanMs } : undefined, - timeout: 1e4, - signal, - validateStatus: (status2) => status2 < 500 - }); - handleErrorStatus(response7.status, response7.data, "Poll"); - if (!response7.data) { - consecutiveEmptyPolls = prevEmptyPolls + 1; - if (consecutiveEmptyPolls === 1 || consecutiveEmptyPolls % EMPTY_POLL_LOG_INTERVAL === 0) { - debug2(`[bridge:api] GET .../work/poll -> ${response7.status} (no work, ${consecutiveEmptyPolls} consecutive empty polls)`); - } - return null; - } - debug2(`[bridge:api] GET .../work/poll -> ${response7.status} workId=${response7.data.id} type=${response7.data.data?.type}${response7.data.data?.id ? ` sessionId=${response7.data.data.id}` : ""}`); - debug2(`[bridge:api] <<< ${debugBody(response7.data)}`); - return response7.data; - }, - async acknowledgeWork(environmentId, workId, sessionToken) { - validateBridgeId(environmentId, "environmentId"); - validateBridgeId(workId, "workId"); - debug2(`[bridge:api] POST .../work/${workId}/ack`); - const response7 = await axios_default.post(`${deps.baseUrl}/v1/environments/${environmentId}/work/${workId}/ack`, {}, { - headers: getHeaders(sessionToken), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }); - handleErrorStatus(response7.status, response7.data, "Acknowledge"); - debug2(`[bridge:api] POST .../work/${workId}/ack -> ${response7.status}`); - }, - async stopWork(environmentId, workId, force) { - validateBridgeId(environmentId, "environmentId"); - validateBridgeId(workId, "workId"); - debug2(`[bridge:api] POST .../work/${workId}/stop force=${force}`); - const response7 = await withOAuthRetry((token) => axios_default.post(`${deps.baseUrl}/v1/environments/${environmentId}/work/${workId}/stop`, { force }, { - headers: getHeaders(token), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }), "StopWork"); - handleErrorStatus(response7.status, response7.data, "StopWork"); - debug2(`[bridge:api] POST .../work/${workId}/stop -> ${response7.status}`); - }, - async deregisterEnvironment(environmentId) { - validateBridgeId(environmentId, "environmentId"); - debug2(`[bridge:api] DELETE /v1/environments/bridge/${environmentId}`); - const response7 = await withOAuthRetry((token) => axios_default.delete(`${deps.baseUrl}/v1/environments/bridge/${environmentId}`, { - headers: getHeaders(token), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }), "Deregister"); - handleErrorStatus(response7.status, response7.data, "Deregister"); - debug2(`[bridge:api] DELETE /v1/environments/bridge/${environmentId} -> ${response7.status}`); - }, - async archiveSession(sessionId) { - validateBridgeId(sessionId, "sessionId"); - debug2(`[bridge:api] POST /v1/sessions/${sessionId}/archive`); - const response7 = await withOAuthRetry((token) => axios_default.post(`${deps.baseUrl}/v1/sessions/${sessionId}/archive`, {}, { - headers: getHeaders(token), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }), "ArchiveSession"); - if (response7.status === 409) { - debug2(`[bridge:api] POST /v1/sessions/${sessionId}/archive -> 409 (already archived)`); - return; - } - handleErrorStatus(response7.status, response7.data, "ArchiveSession"); - debug2(`[bridge:api] POST /v1/sessions/${sessionId}/archive -> ${response7.status}`); - }, - async reconnectSession(environmentId, sessionId) { - validateBridgeId(environmentId, "environmentId"); - validateBridgeId(sessionId, "sessionId"); - debug2(`[bridge:api] POST /v1/environments/${environmentId}/bridge/reconnect session_id=${sessionId}`); - const response7 = await withOAuthRetry((token) => axios_default.post(`${deps.baseUrl}/v1/environments/${environmentId}/bridge/reconnect`, { session_id: sessionId }, { - headers: getHeaders(token), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }), "ReconnectSession"); - handleErrorStatus(response7.status, response7.data, "ReconnectSession"); - debug2(`[bridge:api] POST .../bridge/reconnect -> ${response7.status}`); - }, - async heartbeatWork(environmentId, workId, sessionToken) { - validateBridgeId(environmentId, "environmentId"); - validateBridgeId(workId, "workId"); - debug2(`[bridge:api] POST .../work/${workId}/heartbeat`); - const response7 = await axios_default.post(`${deps.baseUrl}/v1/environments/${environmentId}/work/${workId}/heartbeat`, {}, { - headers: getHeaders(sessionToken), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }); - handleErrorStatus(response7.status, response7.data, "Heartbeat"); - debug2(`[bridge:api] POST .../work/${workId}/heartbeat -> ${response7.status} lease_extended=${response7.data.lease_extended} state=${response7.data.state}`); - return response7.data; - }, - async sendPermissionResponseEvent(sessionId, event, sessionToken) { - validateBridgeId(sessionId, "sessionId"); - debug2(`[bridge:api] POST /v1/sessions/${sessionId}/events type=${event.type}`); - const response7 = await axios_default.post(`${deps.baseUrl}/v1/sessions/${sessionId}/events`, { events: [event] }, { - headers: getHeaders(sessionToken), - timeout: 1e4, - validateStatus: (s4) => s4 < 500 - }); - handleErrorStatus(response7.status, response7.data, "SendPermissionResponseEvent"); - debug2(`[bridge:api] POST /v1/sessions/${sessionId}/events -> ${response7.status}`); - debug2(`[bridge:api] >>> ${debugBody({ events: [event] })}`); - debug2(`[bridge:api] <<< ${debugBody(response7.data)}`); - } - }; -} -function handleErrorStatus(status2, data, context7) { - if (status2 === 200 || status2 === 204) { - return; - } - const detail = extractErrorDetail(data); - const errorType = extractErrorTypeFromData(data); - switch (status2) { - case 401: - throw new BridgeFatalError(`${context7}: Authentication failed (401)${detail ? `: ${detail}` : ""}. ${BRIDGE_LOGIN_INSTRUCTION}`, 401, errorType); - case 403: - throw new BridgeFatalError(isExpiredErrorType(errorType) ? "Remote Control session has expired. Please restart with `claude remote-control` or /remote-control." : `${context7}: Access denied (403)${detail ? `: ${detail}` : ""}. Check your organization permissions.`, 403, errorType); - case 404: - throw new BridgeFatalError(detail ?? `${context7}: Not found (404). Remote Control may not be available for this organization.`, 404, errorType); - case 410: - throw new BridgeFatalError(detail ?? "Remote Control session has expired. Please restart with `claude remote-control` or /remote-control.", 410, errorType ?? "environment_expired"); - case 429: - throw new Error(`${context7}: Rate limited (429). Polling too frequently.`); - default: - throw new Error(`${context7}: Failed with status ${status2}${detail ? `: ${detail}` : ""}`); - } -} -function isExpiredErrorType(errorType) { - if (!errorType) { - return false; - } - return errorType.includes("expired") || errorType.includes("lifetime"); -} -function isSuppressible403(err2) { - if (err2.status !== 403) { - return false; - } - return err2.message.includes("external_poll_sessions") || err2.message.includes("environments:manage"); -} -function extractErrorTypeFromData(data) { - if (data && typeof data === "object") { - if ("error" in data && data.error && typeof data.error === "object" && "type" in data.error && typeof data.error.type === "string") { - return data.error.type; - } - } - return; -} -var BETA_HEADER = "environments-2025-11-01", SAFE_ID_PATTERN, BridgeFatalError; -var init_bridgeApi = __esm(() => { - init_axios2(); - init_debugUtils(); - init_types23(); - SAFE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/; - BridgeFatalError = class BridgeFatalError extends Error { - status; - errorType; - constructor(message, status2, errorType) { - super(message); - this.name = "BridgeFatalError"; - this.status = status2; - this.errorType = errorType; - } - }; -}); - -// src/bridge/bridgeDebug.ts -function registerBridgeDebugHandle(h5) { - debugHandle = h5; -} -function clearBridgeDebugHandle() { - debugHandle = null; - faultQueue.length = 0; -} -function getBridgeDebugHandle() { - return debugHandle; -} -function injectBridgeFault(fault) { - faultQueue.push(fault); - logForDebugging(`[bridge:debug] Queued fault: ${fault.method} ${fault.kind}/${fault.status}${fault.errorType ? `/${fault.errorType}` : ""} \xD7${fault.count}`); -} -function wrapApiForFaultInjection(api4) { - function consume(method) { - const idx = faultQueue.findIndex((f4) => f4.method === method); - if (idx === -1) - return null; - const fault = faultQueue[idx]; - fault.count--; - if (fault.count <= 0) - faultQueue.splice(idx, 1); - return fault; - } - function throwFault(fault, context7) { - logForDebugging(`[bridge:debug] Injecting ${fault.kind} fault into ${context7}: status=${fault.status} errorType=${fault.errorType ?? "none"}`); - if (fault.kind === "fatal") { - throw new BridgeFatalError(`[injected] ${context7} ${fault.status}`, fault.status, fault.errorType); - } - throw new Error(`[injected transient] ${context7} ${fault.status}`); - } - return { - ...api4, - async pollForWork(envId, secret, signal, reclaimMs) { - const f4 = consume("pollForWork"); - if (f4) - throwFault(f4, "Poll"); - return api4.pollForWork(envId, secret, signal, reclaimMs); - }, - async registerBridgeEnvironment(config10) { - const f4 = consume("registerBridgeEnvironment"); - if (f4) - throwFault(f4, "Registration"); - return api4.registerBridgeEnvironment(config10); - }, - async reconnectSession(envId, sessionId) { - const f4 = consume("reconnectSession"); - if (f4) - throwFault(f4, "ReconnectSession"); - return api4.reconnectSession(envId, sessionId); - }, - async heartbeatWork(envId, workId, token) { - const f4 = consume("heartbeatWork"); - if (f4) - throwFault(f4, "Heartbeat"); - return api4.heartbeatWork(envId, workId, token); - } - }; -} -var debugHandle = null, faultQueue; -var init_bridgeDebug = __esm(() => { - init_debug(); - init_bridgeApi(); - faultQueue = []; -}); - -// src/commands/bridge-kick.ts -var USAGE = `/bridge-kick - close fire ws_closed with the given code (e.g. 1002) - poll [type] next poll throws BridgeFatalError(status, type) - poll transient next poll throws axios-style rejection (5xx/net) - register fail [N] next N registers transient-fail (default 1) - register fatal next register 403s (terminal) - reconnect-session fail next POST /bridge/reconnect fails - heartbeat next heartbeat throws BridgeFatalError(status) - reconnect call reconnectEnvironmentWithSession directly - status print bridge state`, call55 = async (args) => { - const h5 = getBridgeDebugHandle(); - if (!h5) { - return { - type: "text", - value: "No bridge debug handle registered. Remote Control must be connected (USER_TYPE=ant)." - }; - } - const [sub, a5, b5] = args.trim().split(/\s+/); - switch (sub) { - case "close": { - const code = Number(a5); - if (!Number.isFinite(code)) { - return { type: "text", value: `close: need a numeric code -${USAGE}` }; - } - h5.fireClose(code); - return { - type: "text", - value: `Fired transport close(${code}). Watch debug.log for [bridge:repl] recovery.` - }; - } - case "poll": { - if (a5 === "transient") { - h5.injectFault({ - method: "pollForWork", - kind: "transient", - status: 503, - count: 1 - }); - h5.wakePollLoop(); - return { - type: "text", - value: "Next poll will throw a transient (axios rejection). Poll loop woken." - }; - } - const status2 = Number(a5); - if (!Number.isFinite(status2)) { - return { - type: "text", - value: `poll: need 'transient' or a status code -${USAGE}` - }; - } - const errorType = b5 ?? (status2 === 404 ? "not_found_error" : "authentication_error"); - h5.injectFault({ - method: "pollForWork", - kind: "fatal", - status: status2, - errorType, - count: 1 - }); - h5.wakePollLoop(); - return { - type: "text", - value: `Next poll will throw BridgeFatalError(${status2}, ${errorType}). Poll loop woken.` - }; - } - case "register": { - if (a5 === "fatal") { - h5.injectFault({ - method: "registerBridgeEnvironment", - kind: "fatal", - status: 403, - errorType: "permission_error", - count: 1 - }); - return { - type: "text", - value: "Next registerBridgeEnvironment will 403. Trigger with close/reconnect." - }; - } - const n6 = Number(b5) || 1; - h5.injectFault({ - method: "registerBridgeEnvironment", - kind: "transient", - status: 503, - count: n6 - }); - return { - type: "text", - value: `Next ${n6} registerBridgeEnvironment call(s) will transient-fail. Trigger with close/reconnect.` - }; - } - case "reconnect-session": { - h5.injectFault({ - method: "reconnectSession", - kind: "fatal", - status: 404, - errorType: "not_found_error", - count: 2 - }); - return { - type: "text", - value: "Next 2 POST /bridge/reconnect calls will 404. doReconnect Strategy 1 falls through to Strategy 2." - }; - } - case "heartbeat": { - const status2 = Number(a5) || 401; - h5.injectFault({ - method: "heartbeatWork", - kind: "fatal", - status: status2, - errorType: status2 === 401 ? "authentication_error" : "not_found_error", - count: 1 - }); - return { - type: "text", - value: `Next heartbeat will ${status2}. Watch for onHeartbeatFatal \u2192 work-state teardown.` - }; - } - case "reconnect": { - h5.forceReconnect(); - return { - type: "text", - value: "Called reconnectEnvironmentWithSession(). Watch debug.log." - }; - } - case "status": { - return { type: "text", value: h5.describe() }; - } - default: - return { type: "text", value: USAGE }; - } -}, bridgeKick, bridge_kick_default; -var init_bridge_kick = __esm(() => { - init_bridgeDebug(); - bridgeKick = { - type: "local", - name: "bridge-kick", - description: "Inject bridge failure states for manual recovery testing", - isEnabled: () => process.env.USER_TYPE === "ant", - supportsNonInteractive: false, - load: () => Promise.resolve({ call: call55 }) - }; - bridge_kick_default = bridgeKick; -}); - -// src/commands/version.ts -var call56 = async () => { - return { - type: "text", - value: MACRO.BUILD_TIME ? `${MACRO.VERSION} (built ${MACRO.BUILD_TIME})` : MACRO.VERSION - }; -}, version6, version_default; -var init_version = __esm(() => { - version6 = { - type: "local", - name: "version", - description: "Print the version this session is running (not what autoupdate downloaded)", - isEnabled: () => process.env.USER_TYPE === "ant", - supportsNonInteractive: true, - load: () => Promise.resolve({ call: call56 }) - }; - version_default = version6; -}); - -// src/commands/summary/index.js -var summary_default; -var init_summary = __esm(() => { - summary_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/commands/reset-limits/index.js -var stub, resetLimits, resetLimitsNonInteractive; -var init_reset_limits = __esm(() => { - stub = { isEnabled: () => false, isHidden: true, name: "stub" }; - resetLimits = stub; - resetLimitsNonInteractive = stub; -}); - -// src/commands/ant-trace/index.js -var ant_trace_default; -var init_ant_trace = __esm(() => { - ant_trace_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/commands/perf-issue/index.js -var perf_issue_default; -var init_perf_issue = __esm(() => { - perf_issue_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/components/sandbox/SandboxConfigTab.tsx -function SandboxConfigTab() { - const $2 = import_compiler_runtime266.c(3); - const isEnabled2 = SandboxManager.isSandboxingEnabled(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - const depCheck = SandboxManager.checkDependencies(); - t0 = depCheck.warnings.length > 0 ? /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: depCheck.warnings.map(_temp159) - }, undefined, false, undefined, this) : null; - $2[0] = t0; - } else { - t0 = $2[0]; - } - const warningsNote = t0; - if (!isEnabled2) { - let t12; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - color: "subtle", - children: "Sandbox is not enabled" - }, undefined, false, undefined, this), - warningsNote - ] - }, undefined, true, undefined, this); - $2[1] = t12; - } else { - t12 = $2[1]; - } - return t12; - } - let t1; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - const fsReadConfig = SandboxManager.getFsReadConfig(); - const fsWriteConfig = SandboxManager.getFsWriteConfig(); - const networkConfig = SandboxManager.getNetworkRestrictionConfig(); - const allowUnixSockets = SandboxManager.getAllowUnixSockets(); - const excludedCommands = SandboxManager.getExcludedCommands(); - const globPatternWarnings = SandboxManager.getLinuxGlobPatternWarnings(); - t1 = /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: "Excluded Commands:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: excludedCommands.length > 0 ? excludedCommands.join(", ") : "None" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - fsReadConfig.denyOnly.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: "Filesystem Read Restrictions:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Denied: ", - fsReadConfig.denyOnly.join(", ") - ] - }, undefined, true, undefined, this), - fsReadConfig.allowWithinDeny && fsReadConfig.allowWithinDeny.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Allowed within denied: ", - fsReadConfig.allowWithinDeny.join(", ") - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - fsWriteConfig.allowOnly.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: "Filesystem Write Restrictions:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Allowed: ", - fsWriteConfig.allowOnly.join(", ") - ] - }, undefined, true, undefined, this), - fsWriteConfig.denyWithinAllow.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Denied within allowed: ", - fsWriteConfig.denyWithinAllow.join(", ") - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - (networkConfig.allowedHosts && networkConfig.allowedHosts.length > 0 || networkConfig.deniedHosts && networkConfig.deniedHosts.length > 0) && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: [ - "Network Restrictions", - shouldAllowManagedSandboxDomainsOnly() ? " (Managed)" : "", - ":" - ] - }, undefined, true, undefined, this), - networkConfig.allowedHosts && networkConfig.allowedHosts.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Allowed: ", - networkConfig.allowedHosts.join(", ") - ] - }, undefined, true, undefined, this), - networkConfig.deniedHosts && networkConfig.deniedHosts.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Denied: ", - networkConfig.deniedHosts.join(", ") - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - allowUnixSockets && allowUnixSockets.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: "Allowed Unix Sockets:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: allowUnixSockets.join(", ") - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - globPatternWarnings.length > 0 && /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - bold: true, - color: "warning", - children: "\u26A0 Warning: Glob patterns not fully supported on Linux" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "The following patterns will be ignored:", - " ", - globPatternWarnings.slice(0, 3).join(", "), - globPatternWarnings.length > 3 && ` (${globPatternWarnings.length - 3} more)` - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - warningsNote - ] - }, undefined, true, undefined, this); - $2[2] = t1; - } else { - t1 = $2[2]; - } - return t1; -} -function _temp159(w2, i6) { - return /* @__PURE__ */ jsx_dev_runtime339.jsxDEV(ThemedText, { - dimColor: true, - children: w2 - }, i6, false, undefined, this); -} -var import_compiler_runtime266, jsx_dev_runtime339; -var init_SandboxConfigTab = __esm(() => { - init_ink2(); - init_sandbox_adapter(); - import_compiler_runtime266 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime339 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/sandbox/SandboxDependenciesTab.tsx -function SandboxDependenciesTab(t0) { - const $2 = import_compiler_runtime267.c(24); - const { - depCheck - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getPlatform(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const platform6 = t1; - const isMac = platform6 === "macos"; - let t22; - if ($2[1] !== depCheck.errors) { - t22 = depCheck.errors.some(_temp160); - $2[1] = depCheck.errors; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const rgMissing = t22; - let t32; - if ($2[3] !== depCheck.errors) { - t32 = depCheck.errors.some(_temp270); - $2[3] = depCheck.errors; - $2[4] = t32; - } else { - t32 = $2[4]; - } - const bwrapMissing = t32; - let t4; - if ($2[5] !== depCheck.errors) { - t4 = depCheck.errors.some(_temp344); - $2[5] = depCheck.errors; - $2[6] = t4; - } else { - t4 = $2[6]; - } - const socatMissing = t4; - const seccompMissing = depCheck.warnings.length > 0; - let t5; - if ($2[7] !== bwrapMissing || $2[8] !== depCheck.errors || $2[9] !== rgMissing || $2[10] !== seccompMissing || $2[11] !== socatMissing) { - const otherErrors = depCheck.errors.filter(_temp432); - const rgInstallHint = isMac ? "brew install ripgrep" : "apt install ripgrep"; - let t6; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t6 = isMac && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - children: [ - "seatbelt: ", - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "success", - children: "built-in (macOS)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[13] = t6; - } else { - t6 = $2[13]; - } - let t7; - let t8; - if ($2[14] !== rgMissing) { - t7 = /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - children: [ - "ripgrep (rg):", - " ", - rgMissing ? /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "error", - children: "not found" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "success", - children: "found" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - t8 = rgMissing && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\xB7 ", - rgInstallHint - ] - }, undefined, true, undefined, this); - $2[14] = rgMissing; - $2[15] = t7; - $2[16] = t8; - } else { - t7 = $2[15]; - t8 = $2[16]; - } - let t9; - if ($2[17] !== t7 || $2[18] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t7, - t8 - ] - }, undefined, true, undefined, this); - $2[17] = t7; - $2[18] = t8; - $2[19] = t9; - } else { - t9 = $2[19]; - } - let t10; - if ($2[20] !== bwrapMissing || $2[21] !== seccompMissing || $2[22] !== socatMissing) { - t10 = !isMac && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(jsx_dev_runtime340.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - children: [ - "bubblewrap (bwrap):", - " ", - bwrapMissing ? /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "error", - children: "not installed" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "success", - children: "installed" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - bwrapMissing && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\xB7 apt install bubblewrap" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - children: [ - "socat:", - " ", - socatMissing ? /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "error", - children: "not installed" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "success", - children: "installed" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - socatMissing && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\xB7 apt install socat" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - children: [ - "seccomp filter:", - " ", - seccompMissing ? /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "warning", - children: "not installed" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "success", - children: "installed" - }, undefined, false, undefined, this), - seccompMissing && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: " (required to block unix domain sockets)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - seccompMissing && /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\xB7 npm install -g @anthropic-ai/sandbox-runtime" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\xB7 or copy vendor/seccomp/* from sandbox-runtime and set" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "sandbox.seccomp.bpfPath and applyPath in settings.json" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[20] = bwrapMissing; - $2[21] = seccompMissing; - $2[22] = socatMissing; - $2[23] = t10; - } else { - t10 = $2[23]; - } - t5 = /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - gap: 1, - children: [ - t6, - t9, - t10, - otherErrors.map(_temp524) - ] - }, undefined, true, undefined, this); - $2[7] = bwrapMissing; - $2[8] = depCheck.errors; - $2[9] = rgMissing; - $2[10] = seccompMissing; - $2[11] = socatMissing; - $2[12] = t5; - } else { - t5 = $2[12]; - } - return t5; -} -function _temp524(err2) { - return /* @__PURE__ */ jsx_dev_runtime340.jsxDEV(ThemedText, { - color: "error", - children: err2 - }, err2, false, undefined, this); -} -function _temp432(e_2) { - return !e_2.includes("ripgrep") && !e_2.includes("bwrap") && !e_2.includes("socat"); -} -function _temp344(e_1) { - return e_1.includes("socat"); -} -function _temp270(e_0) { - return e_0.includes("bwrap"); -} -function _temp160(e4) { - return e4.includes("ripgrep"); -} -var import_compiler_runtime267, jsx_dev_runtime340; -var init_SandboxDependenciesTab = __esm(() => { - init_ink2(); - init_platform2(); - import_compiler_runtime267 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime340 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/sandbox/SandboxOverridesTab.tsx -function SandboxOverridesTab(t0) { - const $2 = import_compiler_runtime268.c(5); - const { - onComplete - } = t0; - const isEnabled2 = SandboxManager.isSandboxingEnabled(); - const isLocked = SandboxManager.areSandboxSettingsLockedByPolicy(); - const currentAllowUnsandboxed = SandboxManager.areUnsandboxedCommandsAllowed(); - if (!isEnabled2) { - let t12; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - color: "subtle", - children: "Sandbox is not enabled. Enable sandbox to configure override settings." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = t12; - } else { - t12 = $2[0]; - } - return t12; - } - if (isLocked) { - let t12; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - color: "subtle", - children: "Override settings are managed by a higher-priority configuration and cannot be changed locally." - }, undefined, false, undefined, this); - $2[1] = t12; - } else { - t12 = $2[1]; - } - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: [ - t12, - /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Current setting:", - " ", - currentAllowUnsandboxed ? "Allow unsandboxed fallback" : "Strict sandbox mode" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[2] = t22; - } else { - t22 = $2[2]; - } - return t22; - } - let t1; - if ($2[3] !== onComplete) { - t1 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(OverridesSelect, { - onComplete, - currentMode: currentAllowUnsandboxed ? "open" : "closed" - }, undefined, false, undefined, this); - $2[3] = onComplete; - $2[4] = t1; - } else { - t1 = $2[4]; - } - return t1; -} -function OverridesSelect(t0) { - const $2 = import_compiler_runtime268.c(25); - const { - onComplete, - currentMode - } = t0; - const [theme2] = useTheme(); - const { - headerFocused, - focusHeader - } = useTabHeaderFocus(); - let t1; - if ($2[0] !== theme2) { - t1 = color("success", theme2)("(current)"); - $2[0] = theme2; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const currentIndicator = t1; - const t22 = currentMode === "open" ? `Allow unsandboxed fallback ${currentIndicator}` : "Allow unsandboxed fallback"; - let t32; - if ($2[2] !== t22) { - t32 = { - label: t22, - value: "open" - }; - $2[2] = t22; - $2[3] = t32; - } else { - t32 = $2[3]; - } - const t4 = currentMode === "closed" ? `Strict sandbox mode ${currentIndicator}` : "Strict sandbox mode"; - let t5; - if ($2[4] !== t4) { - t5 = { - label: t4, - value: "closed" - }; - $2[4] = t4; - $2[5] = t5; - } else { - t5 = $2[5]; - } - let t6; - if ($2[6] !== t32 || $2[7] !== t5) { - t6 = [t32, t5]; - $2[6] = t32; - $2[7] = t5; - $2[8] = t6; - } else { - t6 = $2[8]; - } - const options2 = t6; - let t7; - if ($2[9] !== onComplete) { - t7 = async function handleSelect2(value) { - const mode = value; - await SandboxManager.setSandboxSettings({ - allowUnsandboxedCommands: mode === "open" - }); - const message = mode === "open" ? "\u2713 Unsandboxed fallback allowed - commands can run outside sandbox when necessary" : "\u2713 Strict sandbox mode - all commands must run in sandbox or be excluded via the `excludedCommands` option"; - onComplete(message); - }; - $2[9] = onComplete; - $2[10] = t7; - } else { - t7 = $2[10]; - } - const handleSelect = t7; - let t8; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - bold: true, - children: "Configure Overrides:" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[11] = t8; - } else { - t8 = $2[11]; - } - let t9; - if ($2[12] !== onComplete) { - t9 = () => onComplete(undefined, { - display: "skip" - }); - $2[12] = onComplete; - $2[13] = t9; - } else { - t9 = $2[13]; - } - let t10; - if ($2[14] !== focusHeader || $2[15] !== handleSelect || $2[16] !== headerFocused || $2[17] !== options2 || $2[18] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - onCancel: t9, - onUpFromFirstItem: focusHeader, - isDisabled: headerFocused - }, undefined, false, undefined, this); - $2[14] = focusHeader; - $2[15] = handleSelect; - $2[16] = headerFocused; - $2[17] = options2; - $2[18] = t9; - $2[19] = t10; - } else { - t10 = $2[19]; - } - let t11; - if ($2[20] === Symbol.for("react.memo_cache_sentinel")) { - t11 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - dimColor: true, - children: [ - /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: "Allow unsandboxed fallback:" - }, undefined, false, undefined, this), - " ", - "When a command fails due to sandbox restrictions, Claude can retry with dangerouslyDisableSandbox to run outside the sandbox (falling back to default permissions)." - ] - }, undefined, true, undefined, this); - $2[20] = t11; - } else { - t11 = $2[20]; - } - let t12; - if ($2[21] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - dimColor: true, - children: [ - /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: "Strict sandbox mode:" - }, undefined, false, undefined, this), - " ", - "All bash commands invoked by the model must run in the sandbox unless they are explicitly listed in excludedCommands." - ] - }, undefined, true, undefined, this); - $2[21] = t12; - } else { - t12 = $2[21]; - } - let t13; - if ($2[22] === Symbol.for("react.memo_cache_sentinel")) { - t13 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - gap: 1, - children: [ - t11, - t12, - /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Learn more:", - " ", - /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/sandboxing#configure-sandboxing", - children: "code.claude.com/docs/en/sandboxing#configure-sandboxing" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[22] = t13; - } else { - t13 = $2[22]; - } - let t14; - if ($2[23] !== t10) { - t14 = /* @__PURE__ */ jsx_dev_runtime341.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: [ - t8, - t10, - t13 - ] - }, undefined, true, undefined, this); - $2[23] = t10; - $2[24] = t14; - } else { - t14 = $2[24]; - } - return t14; -} -var import_compiler_runtime268, jsx_dev_runtime341; -var init_SandboxOverridesTab = __esm(() => { - init_ink2(); - init_sandbox_adapter(); - init_select(); - init_Tabs(); - import_compiler_runtime268 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime341 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/sandbox/SandboxSettings.tsx -function SandboxSettings(t0) { - const $2 = import_compiler_runtime269.c(34); - const { - onComplete, - depCheck - } = t0; - const [theme2] = useTheme(); - const currentEnabled = SandboxManager.isSandboxingEnabled(); - const currentAutoAllow = SandboxManager.isAutoAllowBashIfSandboxedEnabled(); - const hasWarnings = depCheck.warnings.length > 0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getSettings_DEPRECATED(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const settings = t1; - const allowAllUnixSockets = settings.sandbox?.network?.allowAllUnixSockets; - const showSocketWarning = hasWarnings && !allowAllUnixSockets; - const getCurrentMode = () => { - if (!currentEnabled) { - return "disabled"; - } - if (currentAutoAllow) { - return "auto-allow"; - } - return "regular"; - }; - const currentMode = getCurrentMode(); - let t22; - if ($2[1] !== theme2) { - t22 = color("success", theme2)("(current)"); - $2[1] = theme2; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const currentIndicator = t22; - const t32 = currentMode === "auto-allow" ? `Sandbox BashTool, with auto-allow ${currentIndicator}` : "Sandbox BashTool, with auto-allow"; - let t4; - if ($2[3] !== t32) { - t4 = { - label: t32, - value: "auto-allow" - }; - $2[3] = t32; - $2[4] = t4; - } else { - t4 = $2[4]; - } - const t5 = currentMode === "regular" ? `Sandbox BashTool, with regular permissions ${currentIndicator}` : "Sandbox BashTool, with regular permissions"; - let t6; - if ($2[5] !== t5) { - t6 = { - label: t5, - value: "regular" - }; - $2[5] = t5; - $2[6] = t6; - } else { - t6 = $2[6]; - } - const t7 = currentMode === "disabled" ? `No Sandbox ${currentIndicator}` : "No Sandbox"; - let t8; - if ($2[7] !== t7) { - t8 = { - label: t7, - value: "disabled" - }; - $2[7] = t7; - $2[8] = t8; - } else { - t8 = $2[8]; - } - let t9; - if ($2[9] !== t4 || $2[10] !== t6 || $2[11] !== t8) { - t9 = [t4, t6, t8]; - $2[9] = t4; - $2[10] = t6; - $2[11] = t8; - $2[12] = t9; - } else { - t9 = $2[12]; - } - const options2 = t9; - let t10; - if ($2[13] !== onComplete) { - t10 = async function handleSelect2(value) { - const mode = value; - bb33: - switch (mode) { - case "auto-allow": { - await SandboxManager.setSandboxSettings({ - enabled: true, - autoAllowBashIfSandboxed: true - }); - onComplete("\u2713 Sandbox enabled with auto-allow for bash commands"); - break bb33; - } - case "regular": { - await SandboxManager.setSandboxSettings({ - enabled: true, - autoAllowBashIfSandboxed: false - }); - onComplete("\u2713 Sandbox enabled with regular bash permissions"); - break bb33; - } - case "disabled": { - await SandboxManager.setSandboxSettings({ - enabled: false, - autoAllowBashIfSandboxed: false - }); - onComplete("\u25CB Sandbox disabled"); - } - } - }; - $2[13] = onComplete; - $2[14] = t10; - } else { - t10 = $2[14]; - } - const handleSelect = t10; - let t11; - if ($2[15] !== onComplete) { - t11 = { - "confirm:no": () => onComplete(undefined, { - display: "skip" - }) - }; - $2[15] = onComplete; - $2[16] = t11; - } else { - t11 = $2[16]; - } - let t12; - if ($2[17] === Symbol.for("react.memo_cache_sentinel")) { - t12 = { - context: "Settings" - }; - $2[17] = t12; - } else { - t12 = $2[17]; - } - useKeybindings(t11, t12); - let t13; - if ($2[18] !== handleSelect || $2[19] !== onComplete || $2[20] !== options2 || $2[21] !== showSocketWarning) { - t13 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Tab, { - title: "Mode", - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(SandboxModeTab, { - showSocketWarning, - options: options2, - onSelect: handleSelect, - onComplete - }, undefined, false, undefined, this) - }, "mode", false, undefined, this); - $2[18] = handleSelect; - $2[19] = onComplete; - $2[20] = options2; - $2[21] = showSocketWarning; - $2[22] = t13; - } else { - t13 = $2[22]; - } - const modeTab = t13; - let t14; - if ($2[23] !== onComplete) { - t14 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Tab, { - title: "Overrides", - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(SandboxOverridesTab, { - onComplete - }, undefined, false, undefined, this) - }, "overrides", false, undefined, this); - $2[23] = onComplete; - $2[24] = t14; - } else { - t14 = $2[24]; - } - const overridesTab = t14; - let t15; - if ($2[25] === Symbol.for("react.memo_cache_sentinel")) { - t15 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Tab, { - title: "Config", - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(SandboxConfigTab, {}, undefined, false, undefined, this) - }, "config", false, undefined, this); - $2[25] = t15; - } else { - t15 = $2[25]; - } - const configTab = t15; - const hasErrors = depCheck.errors.length > 0; - let t16; - if ($2[26] !== depCheck || $2[27] !== hasErrors || $2[28] !== hasWarnings || $2[29] !== modeTab || $2[30] !== overridesTab) { - t16 = hasErrors ? [/* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Tab, { - title: "Dependencies", - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(SandboxDependenciesTab, { - depCheck - }, undefined, false, undefined, this) - }, "dependencies", false, undefined, this)] : [modeTab, ...hasWarnings ? [/* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Tab, { - title: "Dependencies", - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(SandboxDependenciesTab, { - depCheck - }, undefined, false, undefined, this) - }, "dependencies", false, undefined, this)] : [], overridesTab, configTab]; - $2[26] = depCheck; - $2[27] = hasErrors; - $2[28] = hasWarnings; - $2[29] = modeTab; - $2[30] = overridesTab; - $2[31] = t16; - } else { - t16 = $2[31]; - } - const tabs = t16; - let t17; - if ($2[32] !== tabs) { - t17 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Pane, { - color: "permission", - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Tabs, { - title: "Sandbox:", - color: "permission", - defaultTab: "Mode", - children: tabs - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[32] = tabs; - $2[33] = t17; - } else { - t17 = $2[33]; - } - return t17; -} -function SandboxModeTab(t0) { - const $2 = import_compiler_runtime269.c(16); - const { - showSocketWarning, - options: options2, - onSelect, - onComplete - } = t0; - const { - headerFocused, - focusHeader - } = useTabHeaderFocus(); - let t1; - if ($2[0] !== showSocketWarning) { - t1 = showSocketWarning && /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedText, { - color: "warning", - children: "Cannot block unix domain sockets (see Dependencies tab)" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = showSocketWarning; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedText, { - bold: true, - children: "Configure Mode:" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== onComplete) { - t32 = () => onComplete(undefined, { - display: "skip" - }); - $2[3] = onComplete; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== focusHeader || $2[6] !== headerFocused || $2[7] !== onSelect || $2[8] !== options2 || $2[9] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Select, { - options: options2, - onChange: onSelect, - onCancel: t32, - onUpFromFirstItem: focusHeader, - isDisabled: headerFocused - }, undefined, false, undefined, this); - $2[5] = focusHeader; - $2[6] = headerFocused; - $2[7] = onSelect; - $2[8] = options2; - $2[9] = t32; - $2[10] = t4; - } else { - t4 = $2[10]; - } - let t5; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedText, { - dimColor: true, - children: [ - /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: "Auto-allow mode:" - }, undefined, false, undefined, this), - " ", - "Commands will try to run in the sandbox automatically, and attempts to run outside of the sandbox fallback to regular permissions. Explicit ask/deny rules are always respected." - ] - }, undefined, true, undefined, this); - $2[11] = t5; - } else { - t5 = $2[11]; - } - let t6; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - gap: 1, - children: [ - t5, - /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Learn more:", - " ", - /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/sandboxing", - children: "code.claude.com/docs/en/sandboxing" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[12] = t6; - } else { - t6 = $2[12]; - } - let t7; - if ($2[13] !== t1 || $2[14] !== t4) { - t7 = /* @__PURE__ */ jsx_dev_runtime342.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: [ - t1, - t22, - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[13] = t1; - $2[14] = t4; - $2[15] = t7; - } else { - t7 = $2[15]; - } - return t7; -} -var import_compiler_runtime269, jsx_dev_runtime342; -var init_SandboxSettings = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_sandbox_adapter(); - init_settings2(); - init_select(); - init_Pane(); - init_Tabs(); - init_SandboxConfigTab(); - init_SandboxDependenciesTab(); - init_SandboxOverridesTab(); - import_compiler_runtime269 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime342 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/sandbox-toggle/sandbox-toggle.tsx -var exports_sandbox_toggle = {}; -__export(exports_sandbox_toggle, { - call: () => call57 -}); -import { relative as relative27 } from "path"; -async function call57(onDone, _context, args) { - const settings = getSettings_DEPRECATED(); - const themeName = settings.theme || "light"; - const platform6 = getPlatform(); - if (!SandboxManager.isSupportedPlatform()) { - const errorMessage2 = platform6 === "wsl" ? "Error: Sandboxing requires WSL2. WSL1 is not supported." : "Error: Sandboxing is currently only supported on macOS, Linux, and WSL2."; - const message = color("error", themeName)(errorMessage2); - onDone(message); - return null; - } - const depCheck = SandboxManager.checkDependencies(); - if (!SandboxManager.isPlatformInEnabledList()) { - const message = color("error", themeName)(`Error: Sandboxing is disabled for this platform (${platform6}) via the enabledPlatforms setting.`); - onDone(message); - return null; - } - if (SandboxManager.areSandboxSettingsLockedByPolicy()) { - const message = color("error", themeName)("Error: Sandbox settings are overridden by a higher-priority configuration and cannot be changed locally."); - onDone(message); - return null; - } - const trimmedArgs = args?.trim() || ""; - if (!trimmedArgs) { - return /* @__PURE__ */ jsx_dev_runtime343.jsxDEV(SandboxSettings, { - onComplete: onDone, - depCheck - }, undefined, false, undefined, this); - } - if (trimmedArgs) { - const parts = trimmedArgs.split(" "); - const subcommand = parts[0]; - if (subcommand === "exclude") { - const commandPattern = trimmedArgs.slice("exclude ".length).trim(); - if (!commandPattern) { - const message2 = color("error", themeName)('Error: Please provide a command pattern to exclude (e.g., /sandbox exclude "npm run test:*")'); - onDone(message2); - return null; - } - const cleanPattern = commandPattern.replace(/^["']|["']$/g, ""); - addToExcludedCommands(cleanPattern); - const localSettingsPath = getSettingsFilePathForSource("localSettings"); - const relativePath2 = localSettingsPath ? relative27(getCwdState(), localSettingsPath) : ".claude/settings.local.json"; - const message = color("success", themeName)(`Added "${cleanPattern}" to excluded commands in ${relativePath2}`); - onDone(message); - return null; - } else { - const message = color("error", themeName)(`Error: Unknown subcommand "${subcommand}". Available subcommand: exclude`); - onDone(message); - return null; - } - } - return null; -} -var jsx_dev_runtime343; -var init_sandbox_toggle = __esm(() => { - init_state(); - init_SandboxSettings(); - init_ink2(); - init_platform2(); - init_sandbox_adapter(); - init_settings2(); - jsx_dev_runtime343 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/sandbox-toggle/index.ts -var command17, sandbox_toggle_default; -var init_sandbox_toggle2 = __esm(() => { - init_figures(); - init_sandbox_adapter(); - command17 = { - name: "sandbox", - get description() { - const currentlyEnabled = SandboxManager.isSandboxingEnabled(); - const autoAllow = SandboxManager.isAutoAllowBashIfSandboxedEnabled(); - const allowUnsandboxed = SandboxManager.areUnsandboxedCommandsAllowed(); - const isLocked = SandboxManager.areSandboxSettingsLockedByPolicy(); - const hasDeps = SandboxManager.checkDependencies().errors.length === 0; - let icon; - if (!hasDeps) { - icon = figures_default.warning; - } else { - icon = currentlyEnabled ? figures_default.tick : figures_default.circle; - } - let statusText = "sandbox disabled"; - if (currentlyEnabled) { - statusText = autoAllow ? "sandbox enabled (auto-allow)" : "sandbox enabled"; - statusText += allowUnsandboxed ? ", fallback allowed" : ""; - } - if (isLocked) { - statusText += " (managed)"; - } - return `${icon} ${statusText} (\u23CE to configure)`; - }, - argumentHint: 'exclude "command pattern"', - get isHidden() { - return !SandboxManager.isSupportedPlatform() || !SandboxManager.isPlatformInEnabledList(); - }, - immediate: true, - type: "local-jsx", - load: () => Promise.resolve().then(() => (init_sandbox_toggle(), exports_sandbox_toggle)) - }; - sandbox_toggle_default = command17; -}); - -// src/utils/claudeInChrome/setupPortable.ts -import { readdir as readdir27 } from "fs/promises"; -import { join as join131 } from "path"; -function getExtensionIds() { - return process.env.USER_TYPE === "ant" ? [PROD_EXTENSION_ID, DEV_EXTENSION_ID, ANT_EXTENSION_ID] : [PROD_EXTENSION_ID]; -} -async function detectExtensionInstallationPortable(browserPaths, log3) { - if (browserPaths.length === 0) { - log3?.(`[Claude in Chrome] No browser paths to check`); - return { isInstalled: false, browser: null }; - } - const extensionIds = getExtensionIds(); - for (const { browser, path: browserBasePath } of browserPaths) { - let browserProfileEntries = []; - try { - browserProfileEntries = await readdir27(browserBasePath, { - withFileTypes: true - }); - } catch (e4) { - if (isFsInaccessible(e4)) - continue; - throw e4; - } - const profileDirs = browserProfileEntries.filter((entry) => entry.isDirectory()).filter((entry) => entry.name === "Default" || entry.name.startsWith("Profile ")).map((entry) => entry.name); - if (profileDirs.length > 0) { - log3?.(`[Claude in Chrome] Found ${browser} profiles: ${profileDirs.join(", ")}`); - } - for (const profile7 of profileDirs) { - for (const extensionId of extensionIds) { - const extensionPath = join131(browserBasePath, profile7, "Extensions", extensionId); - try { - await readdir27(extensionPath); - log3?.(`[Claude in Chrome] Extension ${extensionId} found in ${browser} ${profile7}`); - return { isInstalled: true, browser }; - } catch {} - } - } - } - log3?.(`[Claude in Chrome] Extension not found in any browser`); - return { isInstalled: false, browser: null }; -} -async function isChromeExtensionInstalledPortable(browserPaths, log3) { - const result = await detectExtensionInstallationPortable(browserPaths, log3); - return result.isInstalled; -} -var PROD_EXTENSION_ID = "fcoeoabgfenejglbffodgkkbkcdhcgfn", DEV_EXTENSION_ID = "dihbgbndebgnbjfmelmegjepbnkhlgni", ANT_EXTENSION_ID = "dngcpimnedloihjnnfngkgjoidhnaolf"; -var init_setupPortable = __esm(() => { - init_errors(); -}); - -// src/utils/claudeInChrome/setup.ts -import { chmod as chmod10, mkdir as mkdir36, readFile as readFile51, writeFile as writeFile41 } from "fs/promises"; -import { homedir as homedir32 } from "os"; -import { join as join132 } from "path"; -import { fileURLToPath as fileURLToPath7 } from "url"; -function shouldEnableClaudeInChrome(chromeFlag) { - if (getIsNonInteractiveSession() && chromeFlag !== true) { - return false; - } - if (chromeFlag === true) { - return true; - } - if (chromeFlag === false) { - return false; - } - if (isEnvTruthy(process.env.CLAUDE_CODE_ENABLE_CFC)) { - return true; - } - if (isEnvDefinedFalsy(process.env.CLAUDE_CODE_ENABLE_CFC)) { - return false; - } - const config10 = getGlobalConfig(); - if (config10.claudeInChromeDefaultEnabled !== undefined) { - return config10.claudeInChromeDefaultEnabled; - } - return false; -} -function shouldAutoEnableClaudeInChrome() { - if (shouldAutoEnable !== undefined) { - return shouldAutoEnable; - } - shouldAutoEnable = getIsInteractive() && isChromeExtensionInstalled_CACHED_MAY_BE_STALE() && (process.env.USER_TYPE === "ant" || getFeatureValue_CACHED_MAY_BE_STALE("tengu_chrome_auto_enable", false)); - return shouldAutoEnable; -} -function setupClaudeInChrome() { - const isNativeBuild = isInBundledMode(); - const allowedTools = import_claude_for_chrome_mcp2.BROWSER_TOOLS.map((tool) => `mcp__claude-in-chrome__${tool.name}`); - const env5 = {}; - if (getSessionBypassPermissionsMode()) { - env5.CLAUDE_CHROME_PERMISSION_MODE = "skip_all_permission_checks"; - } - const hasEnv = Object.keys(env5).length > 0; - if (isNativeBuild) { - const execCommand = `"${process.execPath}" --chrome-native-host`; - createWrapperScript(execCommand).then((manifestBinaryPath) => installChromeNativeHostManifest(manifestBinaryPath)).catch((e4) => logForDebugging(`[Claude in Chrome] Failed to install native host: ${e4}`, { level: "error" })); - return { - mcpConfig: { - [CLAUDE_IN_CHROME_MCP_SERVER_NAME]: { - type: "stdio", - command: process.execPath, - args: ["--claude-in-chrome-mcp"], - scope: "dynamic", - ...hasEnv && { env: env5 } - } - }, - allowedTools, - systemPrompt: getChromeSystemPrompt() - }; - } else { - const __filename3 = fileURLToPath7(import.meta.url); - const __dirname4 = join132(__filename3, ".."); - const cliPath = join132(__dirname4, "cli.js"); - createWrapperScript(`"${process.execPath}" "${cliPath}" --chrome-native-host`).then((manifestBinaryPath) => installChromeNativeHostManifest(manifestBinaryPath)).catch((e4) => logForDebugging(`[Claude in Chrome] Failed to install native host: ${e4}`, { level: "error" })); - const mcpConfig = { - [CLAUDE_IN_CHROME_MCP_SERVER_NAME]: { - type: "stdio", - command: process.execPath, - args: [`${cliPath}`, "--claude-in-chrome-mcp"], - scope: "dynamic", - ...hasEnv && { env: env5 } - } - }; - return { - mcpConfig, - allowedTools, - systemPrompt: getChromeSystemPrompt() - }; - } -} -function getNativeMessagingHostsDirs() { - const platform6 = getPlatform(); - if (platform6 === "windows") { - const home = homedir32(); - const appData = process.env.APPDATA || join132(home, "AppData", "Local"); - return [join132(appData, "Claude Code", "ChromeNativeHost")]; - } - return getAllNativeMessagingHostsDirs().map(({ path: path25 }) => path25); -} -async function installChromeNativeHostManifest(manifestBinaryPath) { - const manifestDirs = getNativeMessagingHostsDirs(); - if (manifestDirs.length === 0) { - throw Error("Claude in Chrome Native Host not supported on this platform"); - } - const manifest = { - name: NATIVE_HOST_IDENTIFIER, - description: "Claude Code Browser Extension Native Host", - path: manifestBinaryPath, - type: "stdio", - allowed_origins: [ - `chrome-extension://fcoeoabgfenejglbffodgkkbkcdhcgfn/`, - ...process.env.USER_TYPE === "ant" ? [ - "chrome-extension://dihbgbndebgnbjfmelmegjepbnkhlgni/", - "chrome-extension://dngcpimnedloihjnnfngkgjoidhnaolf/" - ] : [] - ] - }; - const manifestContent = jsonStringify(manifest, null, 2); - let anyManifestUpdated = false; - for (const manifestDir of manifestDirs) { - const manifestPath = join132(manifestDir, NATIVE_HOST_MANIFEST_NAME); - const existingContent = await readFile51(manifestPath, "utf-8").catch(() => null); - if (existingContent === manifestContent) { - continue; - } - try { - await mkdir36(manifestDir, { recursive: true }); - await writeFile41(manifestPath, manifestContent); - logForDebugging(`[Claude in Chrome] Installed native host manifest at: ${manifestPath}`); - anyManifestUpdated = true; - } catch (error46) { - logForDebugging(`[Claude in Chrome] Failed to install manifest at ${manifestPath}: ${error46}`); - } - } - if (getPlatform() === "windows") { - const manifestPath = join132(manifestDirs[0], NATIVE_HOST_MANIFEST_NAME); - registerWindowsNativeHosts(manifestPath); - } - if (anyManifestUpdated) { - isChromeExtensionInstalled().then((isInstalled) => { - if (isInstalled) { - logForDebugging(`[Claude in Chrome] First-time install detected, opening reconnect page in browser`); - openInChrome(CHROME_EXTENSION_RECONNECT_URL); - } else { - logForDebugging(`[Claude in Chrome] First-time install detected, but extension not installed, skipping reconnect`); - } - }); - } -} -function registerWindowsNativeHosts(manifestPath) { - const registryKeys = getAllWindowsRegistryKeys(); - for (const { browser, key: key2 } of registryKeys) { - const fullKey = `${key2}\\${NATIVE_HOST_IDENTIFIER}`; - execFileNoThrowWithCwd("reg", [ - "add", - fullKey, - "/ve", - "/t", - "REG_SZ", - "/d", - manifestPath, - "/f" - ]).then((result) => { - if (result.code === 0) { - logForDebugging(`[Claude in Chrome] Registered native host for ${browser} in Windows registry: ${fullKey}`); - } else { - logForDebugging(`[Claude in Chrome] Failed to register native host for ${browser} in Windows registry: ${result.stderr}`); - } - }); - } -} -async function createWrapperScript(command18) { - const platform6 = getPlatform(); - const chromeDir = join132(getClaudeConfigHomeDir(), "chrome"); - const wrapperPath = platform6 === "windows" ? join132(chromeDir, "chrome-native-host.bat") : join132(chromeDir, "chrome-native-host"); - const scriptContent = platform6 === "windows" ? `@echo off -REM Chrome native host wrapper script -REM Generated by Claude Code - do not edit manually -${command18} -` : `#!/bin/sh -# Chrome native host wrapper script -# Generated by Claude Code - do not edit manually -exec ${command18} -`; - const existingContent = await readFile51(wrapperPath, "utf-8").catch(() => null); - if (existingContent === scriptContent) { - return wrapperPath; - } - await mkdir36(chromeDir, { recursive: true }); - await writeFile41(wrapperPath, scriptContent); - if (platform6 !== "windows") { - await chmod10(wrapperPath, 493); - } - logForDebugging(`[Claude in Chrome] Created Chrome native host wrapper script: ${wrapperPath}`); - return wrapperPath; -} -function isChromeExtensionInstalled_CACHED_MAY_BE_STALE() { - isChromeExtensionInstalled().then((isInstalled) => { - if (!isInstalled) { - return; - } - const config10 = getGlobalConfig(); - if (config10.cachedChromeExtensionInstalled !== isInstalled) { - saveGlobalConfig((prev) => ({ - ...prev, - cachedChromeExtensionInstalled: isInstalled - })); - } - }); - const cached3 = getGlobalConfig().cachedChromeExtensionInstalled; - return cached3 ?? false; -} -async function isChromeExtensionInstalled() { - const browserPaths = getAllBrowserDataPaths(); - if (browserPaths.length === 0) { - logForDebugging(`[Claude in Chrome] Unsupported platform for extension detection: ${getPlatform()}`); - return false; - } - return isChromeExtensionInstalledPortable(browserPaths, logForDebugging); -} -var import_claude_for_chrome_mcp2, CHROME_EXTENSION_RECONNECT_URL = "https://clau.de/chrome/reconnect", NATIVE_HOST_IDENTIFIER = "com.anthropic.claude_code_browser_extension", NATIVE_HOST_MANIFEST_NAME, shouldAutoEnable = undefined; -var init_setup2 = __esm(() => { - init_state(); - init_growthbook(); - init_config(); - init_debug(); - init_envUtils(); - init_execFileNoThrow(); - init_platform2(); - init_slowOperations(); - init_common3(); - init_setupPortable(); - import_claude_for_chrome_mcp2 = __toESM(require_claude_for_chrome_mcp(), 1); - NATIVE_HOST_MANIFEST_NAME = `${NATIVE_HOST_IDENTIFIER}.json`; -}); - -// src/commands/chrome/chrome.tsx -var exports_chrome = {}; -__export(exports_chrome, { - call: () => call58 -}); -function ClaudeInChromeMenu(t0) { - const $2 = import_compiler_runtime270.c(41); - const { - onDone, - isExtensionInstalled: installed, - configEnabled, - isClaudeAISubscriber: isClaudeAISubscriber2, - isWSL - } = t0; - const mcpClients = useAppState(_temp161); - const [selectKey, setSelectKey] = import_react187.useState(0); - const [enabledByDefault, setEnabledByDefault] = import_react187.useState(configEnabled ?? false); - const [showInstallHint, setShowInstallHint] = import_react187.useState(false); - const [isExtensionInstalled, setIsExtensionInstalled] = import_react187.useState(installed); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = false; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const isHomespace = t1; - let t22; - if ($2[1] !== mcpClients) { - t22 = mcpClients.find(_temp271); - $2[1] = mcpClients; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const chromeClient = t22; - const isConnected2 = chromeClient?.type === "connected"; - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = function openUrl2(url3) { - if (isHomespace) { - openBrowser(url3); - } else { - openInChrome(url3); - } - }; - $2[3] = t32; - } else { - t32 = $2[3]; - } - const openUrl = t32; - let t4; - if ($2[4] !== enabledByDefault) { - t4 = function handleAction2(action2) { - bb22: - switch (action2) { - case "install-extension": { - setSelectKey(_temp345); - setShowInstallHint(true); - openUrl(CHROME_EXTENSION_URL); - break bb22; - } - case "reconnect": { - setSelectKey(_temp433); - isChromeExtensionInstalled().then((installed_0) => { - setIsExtensionInstalled(installed_0); - if (installed_0) { - setShowInstallHint(false); - } - }); - openUrl(CHROME_RECONNECT_URL); - break bb22; - } - case "manage-permissions": { - setSelectKey(_temp525); - openUrl(CHROME_PERMISSIONS_URL); - break bb22; - } - case "toggle-default": { - const newValue = !enabledByDefault; - saveGlobalConfig((current) => ({ - ...current, - claudeInChromeDefaultEnabled: newValue - })); - setEnabledByDefault(newValue); - } - } - }; - $2[4] = enabledByDefault; - $2[5] = t4; - } else { - t4 = $2[5]; - } - const handleAction = t4; - let options2; - if ($2[6] !== enabledByDefault || $2[7] !== isExtensionInstalled) { - options2 = []; - const requiresExtensionSuffix = isExtensionInstalled ? "" : " (requires extension)"; - if (!isExtensionInstalled && !isHomespace) { - let t53; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t53 = { - label: "Install Chrome extension", - value: "install-extension" - }; - $2[9] = t53; - } else { - t53 = $2[9]; - } - options2.push(t53); - } - let t52; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t52 = /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: "Manage permissions" - }, undefined, false, undefined, this); - $2[10] = t52; - } else { - t52 = $2[10]; - } - let t62; - if ($2[11] !== requiresExtensionSuffix) { - t62 = { - label: /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(jsx_dev_runtime344.Fragment, { - children: [ - t52, - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - dimColor: true, - children: requiresExtensionSuffix - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "manage-permissions" - }; - $2[11] = requiresExtensionSuffix; - $2[12] = t62; - } else { - t62 = $2[12]; - } - let t72; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t72 = /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: "Reconnect extension" - }, undefined, false, undefined, this); - $2[13] = t72; - } else { - t72 = $2[13]; - } - let t82; - if ($2[14] !== requiresExtensionSuffix) { - t82 = { - label: /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(jsx_dev_runtime344.Fragment, { - children: [ - t72, - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - dimColor: true, - children: requiresExtensionSuffix - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "reconnect" - }; - $2[14] = requiresExtensionSuffix; - $2[15] = t82; - } else { - t82 = $2[15]; - } - const t92 = `Enabled by default: ${enabledByDefault ? "Yes" : "No"}`; - let t102; - if ($2[16] !== t92) { - t102 = { - label: t92, - value: "toggle-default" - }; - $2[16] = t92; - $2[17] = t102; - } else { - t102 = $2[17]; - } - options2.push(t62, t82, t102); - $2[6] = enabledByDefault; - $2[7] = isExtensionInstalled; - $2[8] = options2; - } else { - options2 = $2[8]; - } - const isDisabled = isWSL || !isClaudeAISubscriber2; - let t5; - if ($2[18] !== onDone) { - t5 = () => onDone(); - $2[18] = onDone; - $2[19] = t5; - } else { - t5 = $2[19]; - } - let t6; - if ($2[20] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: "Claude in Chrome works with the Chrome extension to let you control your browser directly from Claude Code. Navigate websites, fill forms, capture screenshots, record GIFs, and debug with console logs and network requests." - }, undefined, false, undefined, this); - $2[20] = t6; - } else { - t6 = $2[20]; - } - let t7; - if ($2[21] !== isWSL) { - t7 = isWSL && /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "error", - children: "Claude in Chrome is not supported in WSL at this time." - }, undefined, false, undefined, this); - $2[21] = isWSL; - $2[22] = t7; - } else { - t7 = $2[22]; - } - let t8; - if ($2[23] !== isClaudeAISubscriber2) { - t8 = !isClaudeAISubscriber2 && /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "error", - children: "Claude in Chrome requires a claude.ai subscription." - }, undefined, false, undefined, this); - $2[23] = isClaudeAISubscriber2; - $2[24] = t8; - } else { - t8 = $2[24]; - } - let t9; - if ($2[25] !== handleAction || $2[26] !== isConnected2 || $2[27] !== isDisabled || $2[28] !== isExtensionInstalled || $2[29] !== options2 || $2[30] !== selectKey || $2[31] !== showInstallHint) { - t9 = !isDisabled && /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(jsx_dev_runtime344.Fragment, { - children: [ - !isHomespace && /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: [ - "Status:", - " ", - isConnected2 ? /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "success", - children: "Enabled" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "inactive", - children: "Disabled" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: [ - "Extension:", - " ", - isExtensionInstalled ? /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "success", - children: "Installed" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "warning", - children: "Not detected" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(Select, { - options: options2, - onChange: handleAction, - hideIndexes: true - }, selectKey, false, undefined, this), - showInstallHint && /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - color: "warning", - children: [ - "Once installed, select ", - '"Reconnect extension"', - " to connect." - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - dimColor: true, - children: "Usage: " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: "claude --chrome" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - dimColor: true, - children: " or " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - children: "claude --no-chrome" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - dimColor: true, - children: "Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[25] = handleAction; - $2[26] = isConnected2; - $2[27] = isDisabled; - $2[28] = isExtensionInstalled; - $2[29] = options2; - $2[30] = selectKey; - $2[31] = showInstallHint; - $2[32] = t9; - } else { - t9 = $2[32]; - } - let t10; - if ($2[33] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedText, { - dimColor: true, - children: "Learn more: https://code.claude.com/docs/en/chrome" - }, undefined, false, undefined, this); - $2[33] = t10; - } else { - t10 = $2[33]; - } - let t11; - if ($2[34] !== t7 || $2[35] !== t8 || $2[36] !== t9) { - t11 = /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t6, - t7, - t8, - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[34] = t7; - $2[35] = t8; - $2[36] = t9; - $2[37] = t11; - } else { - t11 = $2[37]; - } - let t12; - if ($2[38] !== t11 || $2[39] !== t5) { - t12 = /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(Dialog, { - title: "Claude in Chrome (Beta)", - onCancel: t5, - color: "chromeYellow", - children: t11 - }, undefined, false, undefined, this); - $2[38] = t11; - $2[39] = t5; - $2[40] = t12; - } else { - t12 = $2[40]; - } - return t12; -} -function _temp525(k4) { - return k4 + 1; -} -function _temp433(k_0) { - return k_0 + 1; -} -function _temp345(k_1) { - return k_1 + 1; -} -function _temp271(c9) { - return c9.name === CLAUDE_IN_CHROME_MCP_SERVER_NAME; -} -function _temp161(s4) { - return s4.mcp.clients; -} -var import_compiler_runtime270, import_react187, jsx_dev_runtime344, CHROME_EXTENSION_URL = "https://claude.ai/chrome", CHROME_PERMISSIONS_URL = "https://clau.de/chrome/permissions", CHROME_RECONNECT_URL = "https://clau.de/chrome/reconnect", call58 = async function(onDone) { - const isExtensionInstalled = await isChromeExtensionInstalled(); - const config10 = getGlobalConfig(); - const isSubscriber = isClaudeAISubscriber(); - const isWSL = env2.isWslEnvironment(); - return /* @__PURE__ */ jsx_dev_runtime344.jsxDEV(ClaudeInChromeMenu, { - onDone, - isExtensionInstalled, - configEnabled: config10.claudeInChromeDefaultEnabled, - isClaudeAISubscriber: isSubscriber, - isWSL - }, undefined, false, undefined, this); -}; -var init_chrome = __esm(() => { - init_select(); - init_Dialog(); - init_ink2(); - init_AppState(); - init_auth14(); - init_browser(); - init_common3(); - init_setup2(); - init_config(); - init_env(); - init_envUtils(); - import_compiler_runtime270 = __toESM(require_compiler_runtime(), 1); - import_react187 = __toESM(require_react(), 1); - jsx_dev_runtime344 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/chrome/index.ts -var command18, chrome_default; -var init_chrome2 = __esm(() => { - init_state(); - command18 = { - name: "chrome", - description: "Claude in Chrome (Beta) settings", - availability: ["claude-ai"], - isEnabled: () => !getIsNonInteractiveSession(), - type: "local-jsx", - load: () => Promise.resolve().then(() => (init_chrome(), exports_chrome)) - }; - chrome_default = command18; -}); - -// src/commands/stickers/stickers.ts -var exports_stickers = {}; -__export(exports_stickers, { - call: () => call59 -}); -async function call59() { - const url3 = "https://www.stickermule.com/claudecode"; - const success2 = await openBrowser(url3); - if (success2) { - return { type: "text", value: "Opening sticker page in browser\u2026" }; - } else { - return { - type: "text", - value: `Failed to open browser. Visit: ${url3}` - }; - } -} -var init_stickers = __esm(() => { - init_browser(); -}); - -// src/commands/stickers/index.ts -var stickers, stickers_default; -var init_stickers2 = __esm(() => { - stickers = { - type: "local", - name: "stickers", - description: "Order Claude Code stickers", - supportsNonInteractive: false, - load: () => Promise.resolve().then(() => (init_stickers(), exports_stickers)) - }; - stickers_default = stickers; -}); - -// src/commands/advisor.ts -var call60 = async (args, context7) => { - const arg = args.trim().toLowerCase(); - const baseModel = parseUserSpecifiedModel(context7.getAppState().mainLoopModel ?? getDefaultMainLoopModelSetting()); - if (!arg) { - const current = context7.getAppState().advisorModel; - if (!current) { - return { - type: "text", - value: `Advisor: not set -Use "/advisor " to enable (e.g. "/advisor opus").` - }; - } - if (!modelSupportsAdvisor(baseModel)) { - return { - type: "text", - value: `Advisor: ${current} (inactive) -The current model (${baseModel}) does not support advisors.` - }; - } - return { - type: "text", - value: `Advisor: ${current} -Use "/advisor unset" to disable or "/advisor " to change.` - }; - } - if (arg === "unset" || arg === "off") { - const prev = context7.getAppState().advisorModel; - context7.setAppState((s4) => { - if (s4.advisorModel === undefined) - return s4; - return { ...s4, advisorModel: undefined }; - }); - updateSettingsForSource("userSettings", { advisorModel: undefined }); - return { - type: "text", - value: prev ? `Advisor disabled (was ${prev}).` : "Advisor already unset." - }; - } - const normalizedModel = normalizeModelStringForAPI(arg); - const resolvedModel = parseUserSpecifiedModel(arg); - const { valid, error: error46 } = await validateModel(resolvedModel); - if (!valid) { - return { - type: "text", - value: error46 ? `Invalid advisor model: ${error46}` : `Unknown model: ${arg} (${resolvedModel})` - }; - } - if (!isValidAdvisorModel(resolvedModel)) { - return { - type: "text", - value: `The model ${arg} (${resolvedModel}) cannot be used as an advisor` - }; - } - context7.setAppState((s4) => { - if (s4.advisorModel === normalizedModel) - return s4; - return { ...s4, advisorModel: normalizedModel }; - }); - updateSettingsForSource("userSettings", { advisorModel: normalizedModel }); - if (!modelSupportsAdvisor(baseModel)) { - return { - type: "text", - value: `Advisor set to ${normalizedModel}. -Note: Your current model (${baseModel}) does not support advisors. Switch to a supported model to use the advisor.` - }; - } - return { - type: "text", - value: `Advisor set to ${normalizedModel}.` - }; -}, advisor, advisor_default; -var init_advisor2 = __esm(() => { - init_advisor(); - init_model(); - init_validateModel(); - init_settings2(); - advisor = { - type: "local", - name: "advisor", - description: "Configure the advisor model", - argumentHint: "[|off]", - isEnabled: () => canUserConfigureAdvisor(), - get isHidden() { - return !canUserConfigureAdvisor(); - }, - supportsNonInteractive: true, - load: () => Promise.resolve({ call: call60 }) - }; - advisor_default = advisor; -}); - -// src/skills/bundledSkills.ts -import { constants as fsConstants8 } from "fs"; -import { mkdir as mkdir37, open as open15 } from "fs/promises"; -import { dirname as dirname53, isAbsolute as isAbsolute24, join as join133, normalize as normalize14, sep as pathSep2 } from "path"; -function registerBundledSkill(definition) { - const { files: files3 } = definition; - let skillRoot; - let getPromptForCommand = definition.getPromptForCommand; - if (files3 && Object.keys(files3).length > 0) { - skillRoot = getBundledSkillExtractDir(definition.name); - let extractionPromise; - const inner = definition.getPromptForCommand; - getPromptForCommand = async (args, ctx) => { - extractionPromise ??= extractBundledSkillFiles(definition.name, files3); - const extractedDir = await extractionPromise; - const blocks = await inner(args, ctx); - if (extractedDir === null) - return blocks; - return prependBaseDir(blocks, extractedDir); - }; - } - const command19 = { - type: "prompt", - name: definition.name, - description: definition.description, - aliases: definition.aliases, - hasUserSpecifiedDescription: true, - allowedTools: definition.allowedTools ?? [], - argumentHint: definition.argumentHint, - whenToUse: definition.whenToUse, - model: definition.model, - disableModelInvocation: definition.disableModelInvocation ?? false, - userInvocable: definition.userInvocable ?? true, - contentLength: 0, - source: "bundled", - loadedFrom: "bundled", - hooks: definition.hooks, - skillRoot, - context: definition.context, - agent: definition.agent, - isEnabled: definition.isEnabled, - isHidden: !(definition.userInvocable ?? true), - progressMessage: "running", - getPromptForCommand - }; - bundledSkills.push(command19); -} -function getBundledSkills() { - return [...bundledSkills]; -} -function getBundledSkillExtractDir(skillName) { - return join133(getBundledSkillsRoot(), skillName); -} -async function extractBundledSkillFiles(skillName, files3) { - const dir = getBundledSkillExtractDir(skillName); - try { - await writeSkillFiles(dir, files3); - return dir; - } catch (e4) { - logForDebugging(`Failed to extract bundled skill '${skillName}' to ${dir}: ${e4 instanceof Error ? e4.message : String(e4)}`); - return null; - } -} -async function writeSkillFiles(dir, files3) { - const byParent = new Map; - for (const [relPath, content] of Object.entries(files3)) { - const target = resolveSkillFilePath(dir, relPath); - const parent2 = dirname53(target); - const entry = [target, content]; - const group = byParent.get(parent2); - if (group) - group.push(entry); - else - byParent.set(parent2, [entry]); - } - await Promise.all([...byParent].map(async ([parent2, entries]) => { - await mkdir37(parent2, { recursive: true, mode: 448 }); - await Promise.all(entries.map(([p4, c9]) => safeWriteFile(p4, c9))); - })); -} -async function safeWriteFile(p4, content) { - const fh = await open15(p4, SAFE_WRITE_FLAGS, 384); - try { - await fh.writeFile(content, "utf8"); - } finally { - await fh.close(); - } -} -function resolveSkillFilePath(baseDir, relPath) { - const normalized = normalize14(relPath); - if (isAbsolute24(normalized) || normalized.split(pathSep2).includes("..") || normalized.split("/").includes("..")) { - throw new Error(`bundled skill file path escapes skill dir: ${relPath}`); - } - return join133(baseDir, normalized); -} -function prependBaseDir(blocks, baseDir) { - const prefix = `Base directory for this skill: ${baseDir} - -`; - if (blocks.length > 0 && blocks[0].type === "text") { - return [ - { type: "text", text: prefix + blocks[0].text }, - ...blocks.slice(1) - ]; - } - return [{ type: "text", text: prefix }, ...blocks]; -} -var bundledSkills, O_NOFOLLOW2, SAFE_WRITE_FLAGS; -var init_bundledSkills = __esm(() => { - init_debug(); - init_filesystem(); - bundledSkills = []; - O_NOFOLLOW2 = fsConstants8.O_NOFOLLOW ?? 0; - SAFE_WRITE_FLAGS = process.platform === "win32" ? "wx" : fsConstants8.O_WRONLY | fsConstants8.O_CREAT | fsConstants8.O_EXCL | O_NOFOLLOW2; -}); - -// src/commands/env/index.js -var env_default; -var init_env2 = __esm(() => { - env_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/components/WorktreeExitDialog.tsx -function recordWorktreeExit() { - (init_sessionStorage(), __toCommonJS(exports_sessionStorage)).saveWorktreeState(null); -} -function WorktreeExitDialog({ - onDone, - onCancel -}) { - const [status2, setStatus] = import_react188.useState("loading"); - const [changes, setChanges] = import_react188.useState([]); - const [commitCount, setCommitCount] = import_react188.useState(0); - const [resultMessage, setResultMessage] = import_react188.useState(); - const worktreeSession = getCurrentWorktreeSession(); - import_react188.useEffect(() => { - async function loadChanges() { - let changeLines = []; - const gitStatus = await execFileNoThrow("git", ["status", "--porcelain"]); - if (gitStatus.stdout) { - changeLines = gitStatus.stdout.split(` -`).filter((_) => _.trim() !== ""); - setChanges(changeLines); - } - if (worktreeSession) { - const { - stdout: commitsStr - } = await execFileNoThrow("git", ["rev-list", "--count", `${worktreeSession.originalHeadCommit}..HEAD`]); - const count4 = parseInt(commitsStr.trim()) || 0; - setCommitCount(count4); - if (changeLines.length === 0 && count4 === 0) { - setStatus("removing"); - cleanupWorktree().then(() => { - process.chdir(worktreeSession.originalCwd); - setCwd(worktreeSession.originalCwd); - recordWorktreeExit(); - getPlansDirectory.cache.clear?.(); - setResultMessage("Worktree removed (no changes)"); - }).catch((error46) => { - logForDebugging(`Failed to clean up worktree: ${error46}`, { - level: "error" - }); - setResultMessage("Worktree cleanup failed, exiting anyway"); - }).then(() => { - setStatus("done"); - }); - return; - } else { - setStatus("asking"); - } - } - } - loadChanges(); - }, [worktreeSession]); - import_react188.useEffect(() => { - if (status2 === "done") { - onDone(resultMessage); - } - }, [status2, onDone, resultMessage]); - if (!worktreeSession) { - onDone("No active worktree session found", { - display: "system" - }); - return null; - } - if (status2 === "loading" || status2 === "done") { - return null; - } - async function handleSelect(value) { - if (!worktreeSession) - return; - const hasTmux = Boolean(worktreeSession.tmuxSessionName); - if (value === "keep" || value === "keep-with-tmux") { - setStatus("keeping"); - logEvent("tengu_worktree_kept", { - commits: commitCount, - changed_files: changes.length - }); - await keepWorktree(); - process.chdir(worktreeSession.originalCwd); - setCwd(worktreeSession.originalCwd); - recordWorktreeExit(); - getPlansDirectory.cache.clear?.(); - if (hasTmux) { - setResultMessage(`Worktree kept. Your work is saved at ${worktreeSession.worktreePath} on branch ${worktreeSession.worktreeBranch}. Reattach to tmux session with: tmux attach -t ${worktreeSession.tmuxSessionName}`); - } else { - setResultMessage(`Worktree kept. Your work is saved at ${worktreeSession.worktreePath} on branch ${worktreeSession.worktreeBranch}`); - } - setStatus("done"); - } else if (value === "keep-kill-tmux") { - setStatus("keeping"); - logEvent("tengu_worktree_kept", { - commits: commitCount, - changed_files: changes.length - }); - if (worktreeSession.tmuxSessionName) { - await killTmuxSession(worktreeSession.tmuxSessionName); - } - await keepWorktree(); - process.chdir(worktreeSession.originalCwd); - setCwd(worktreeSession.originalCwd); - recordWorktreeExit(); - getPlansDirectory.cache.clear?.(); - setResultMessage(`Worktree kept at ${worktreeSession.worktreePath} on branch ${worktreeSession.worktreeBranch}. Tmux session terminated.`); - setStatus("done"); - } else if (value === "remove" || value === "remove-with-tmux") { - setStatus("removing"); - logEvent("tengu_worktree_removed", { - commits: commitCount, - changed_files: changes.length - }); - if (worktreeSession.tmuxSessionName) { - await killTmuxSession(worktreeSession.tmuxSessionName); - } - try { - await cleanupWorktree(); - process.chdir(worktreeSession.originalCwd); - setCwd(worktreeSession.originalCwd); - recordWorktreeExit(); - getPlansDirectory.cache.clear?.(); - } catch (error46) { - logForDebugging(`Failed to clean up worktree: ${error46}`, { - level: "error" - }); - setResultMessage("Worktree cleanup failed, exiting anyway"); - setStatus("done"); - return; - } - const tmuxNote = hasTmux ? " Tmux session terminated." : ""; - if (commitCount > 0 && changes.length > 0) { - setResultMessage(`Worktree removed. ${commitCount} ${commitCount === 1 ? "commit" : "commits"} and uncommitted changes were discarded.${tmuxNote}`); - } else if (commitCount > 0) { - setResultMessage(`Worktree removed. ${commitCount} ${commitCount === 1 ? "commit" : "commits"} on ${worktreeSession.worktreeBranch} ${commitCount === 1 ? "was" : "were"} discarded.${tmuxNote}`); - } else if (changes.length > 0) { - setResultMessage(`Worktree removed. Uncommitted changes were discarded.${tmuxNote}`); - } else { - setResultMessage(`Worktree removed.${tmuxNote}`); - } - setStatus("done"); - } - } - if (status2 === "keeping") { - return /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(ThemedBox_default, { - flexDirection: "row", - marginY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(ThemedText, { - children: "Keeping worktree\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - if (status2 === "removing") { - return /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(ThemedBox_default, { - flexDirection: "row", - marginY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(ThemedText, { - children: "Removing worktree\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - const branchName = worktreeSession.worktreeBranch; - const hasUncommitted = changes.length > 0; - const hasCommits = commitCount > 0; - let subtitle = ""; - if (hasUncommitted && hasCommits) { - subtitle = `You have ${changes.length} uncommitted ${changes.length === 1 ? "file" : "files"} and ${commitCount} ${commitCount === 1 ? "commit" : "commits"} on ${branchName}. All will be lost if you remove.`; - } else if (hasUncommitted) { - subtitle = `You have ${changes.length} uncommitted ${changes.length === 1 ? "file" : "files"}. These will be lost if you remove the worktree.`; - } else if (hasCommits) { - subtitle = `You have ${commitCount} ${commitCount === 1 ? "commit" : "commits"} on ${branchName}. The branch will be deleted if you remove the worktree.`; - } else { - subtitle = "You are working in a worktree. Keep it to continue working there, or remove it to clean up."; - } - function handleCancel() { - if (onCancel) { - onCancel(); - return; - } - handleSelect("keep"); - } - const removeDescription = hasUncommitted || hasCommits ? "All changes and commits will be lost." : "Clean up the worktree directory."; - const hasTmuxSession = Boolean(worktreeSession.tmuxSessionName); - const options2 = hasTmuxSession ? [{ - label: "Keep worktree and tmux session", - value: "keep-with-tmux", - description: `Stays at ${worktreeSession.worktreePath}. Reattach with: tmux attach -t ${worktreeSession.tmuxSessionName}` - }, { - label: "Keep worktree, kill tmux session", - value: "keep-kill-tmux", - description: `Keeps worktree at ${worktreeSession.worktreePath}, terminates tmux session.` - }, { - label: "Remove worktree and tmux session", - value: "remove-with-tmux", - description: removeDescription - }] : [{ - label: "Keep worktree", - value: "keep", - description: `Stays at ${worktreeSession.worktreePath}` - }, { - label: "Remove worktree", - value: "remove", - description: removeDescription - }]; - const defaultValue = hasTmuxSession ? "keep-with-tmux" : "keep"; - return /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(Dialog, { - title: "Exiting worktree session", - subtitle, - onCancel: handleCancel, - children: /* @__PURE__ */ jsx_dev_runtime345.jsxDEV(Select, { - defaultFocusValue: defaultValue, - options: options2, - onChange: handleSelect - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); -} -var import_react188, jsx_dev_runtime345; -var init_WorktreeExitDialog = __esm(() => { - init_analytics(); - init_debug(); - init_ink2(); - init_execFileNoThrow(); - init_plans(); - init_Shell(); - init_worktree(); - init_select(); - init_Dialog(); - init_Spinner2(); - import_react188 = __toESM(require_react(), 1); - jsx_dev_runtime345 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/ExitFlow.tsx -function getRandomGoodbyeMessage() { - return sample_default(GOODBYE_MESSAGES) ?? "Goodbye!"; -} -function ExitFlow(t0) { - const $2 = import_compiler_runtime271.c(5); - const { - showWorktree, - onDone, - onCancel - } = t0; - let t1; - if ($2[0] !== onDone) { - t1 = async function onExit3(resultMessage) { - onDone(resultMessage ?? getRandomGoodbyeMessage()); - await gracefulShutdown(0, "prompt_input_exit"); - }; - $2[0] = onDone; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const onExit2 = t1; - if (showWorktree) { - let t22; - if ($2[2] !== onCancel || $2[3] !== onExit2) { - t22 = /* @__PURE__ */ jsx_dev_runtime346.jsxDEV(WorktreeExitDialog, { - onDone: onExit2, - onCancel - }, undefined, false, undefined, this); - $2[2] = onCancel; - $2[3] = onExit2; - $2[4] = t22; - } else { - t22 = $2[4]; - } - return t22; - } - return null; -} -var import_compiler_runtime271, jsx_dev_runtime346, GOODBYE_MESSAGES; -var init_ExitFlow = __esm(() => { - init_sample(); - init_gracefulShutdown(); - init_WorktreeExitDialog(); - import_compiler_runtime271 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime346 = __toESM(require_jsx_dev_runtime(), 1); - GOODBYE_MESSAGES = ["Goodbye!", "See ya!", "Bye!", "Catch you later!"]; -}); - -// src/commands/exit/exit.tsx -var exports_exit = {}; -__export(exports_exit, { - call: () => call61 -}); -function getRandomGoodbyeMessage2() { - return sample_default(GOODBYE_MESSAGES2) ?? "Goodbye!"; -} -async function call61(onDone) { - if (false) {} - const showWorktree = getCurrentWorktreeSession() !== null; - if (showWorktree) { - return /* @__PURE__ */ jsx_dev_runtime347.jsxDEV(ExitFlow, { - showWorktree, - onDone, - onCancel: () => onDone() - }, undefined, false, undefined, this); - } - onDone(getRandomGoodbyeMessage2()); - await gracefulShutdown(0, "prompt_input_exit"); - return null; -} -var jsx_dev_runtime347, GOODBYE_MESSAGES2; -var init_exit = __esm(() => { - init_sample(); - init_ExitFlow(); - init_concurrentSessions(); - init_gracefulShutdown(); - init_worktree(); - jsx_dev_runtime347 = __toESM(require_jsx_dev_runtime(), 1); - GOODBYE_MESSAGES2 = ["Goodbye!", "See ya!", "Bye!", "Catch you later!"]; -}); - -// src/commands/exit/index.ts -var exit, exit_default; -var init_exit2 = __esm(() => { - exit = { - type: "local-jsx", - name: "exit", - aliases: ["quit"], - description: "Exit the REPL", - immediate: true, - load: () => Promise.resolve().then(() => (init_exit(), exports_exit)) - }; - exit_default = exit; -}); - -// src/components/ExportDialog.tsx -import { join as join134 } from "path"; -function ExportDialog({ - content, - defaultFilename, - onDone -}) { - const [, setSelectedOption] = import_react189.useState(null); - const [filename, setFilename] = import_react189.useState(defaultFilename); - const [cursorOffset, setCursorOffset] = import_react189.useState(defaultFilename.length); - const [showFilenameInput, setShowFilenameInput] = import_react189.useState(false); - const { - columns - } = useTerminalSize(); - const handleGoBack = import_react189.useCallback(() => { - setShowFilenameInput(false); - setSelectedOption(null); - }, []); - const handleSelectOption = async (value) => { - if (value === "clipboard") { - const raw = await setClipboard(content); - if (raw) - process.stdout.write(raw); - onDone({ - success: true, - message: "Conversation copied to clipboard" - }); - } else if (value === "file") { - setSelectedOption("file"); - setShowFilenameInput(true); - } - }; - const handleFilenameSubmit = () => { - const finalFilename = filename.endsWith(".txt") ? filename : filename.replace(/\.[^.]+$/, "") + ".txt"; - const filepath = join134(getCwd(), finalFilename); - try { - writeFileSync_DEPRECATED(filepath, content, { - encoding: "utf-8", - flush: true - }); - onDone({ - success: true, - message: `Conversation exported to: ${filepath}` - }); - } catch (error46) { - onDone({ - success: false, - message: `Failed to export conversation: ${error46 instanceof Error ? error46.message : "Unknown error"}` - }); - } - }; - const handleCancel = import_react189.useCallback(() => { - if (showFilenameInput) { - handleGoBack(); - } else { - onDone({ - success: false, - message: "Export cancelled" - }); - } - }, [showFilenameInput, handleGoBack, onDone]); - const options2 = [{ - label: "Copy to clipboard", - value: "clipboard", - description: "Copy the conversation to your system clipboard" - }, { - label: "Save to file", - value: "file", - description: "Save the conversation to a file in the current directory" - }]; - function renderInputGuide2(exitState) { - if (showFilenameInput) { - return /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "save" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "go back" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - if (exitState.pending) { - return /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this); - } - useKeybinding("confirm:no", handleCancel, { - context: "Settings", - isActive: showFilenameInput - }); - return /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(Dialog, { - title: "Export Conversation", - subtitle: "Select export method:", - color: "permission", - onCancel: handleCancel, - inputGuide: renderInputGuide2, - isCancelActive: !showFilenameInput, - children: !showFilenameInput ? /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(Select, { - options: options2, - onChange: handleSelectOption, - onCancel: handleCancel - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ThemedText, { - children: "Enter filename:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(ThemedText, { - children: ">" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime348.jsxDEV(TextInput, { - value: filename, - onChange: setFilename, - onSubmit: handleFilenameSubmit, - focus: true, - showCursor: true, - columns, - cursorOffset, - onChangeCursorOffset: setCursorOffset - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var import_react189, jsx_dev_runtime348; -var init_ExportDialog = __esm(() => { - init_useTerminalSize(); - init_osc(); - init_ink2(); - init_useKeybinding(); - init_cwd(); - init_slowOperations(); - init_ConfigurableShortcutHint(); - init_select(); - init_Byline(); - init_Dialog(); - init_KeyboardShortcutHint(); - init_TextInput(); - import_react189 = __toESM(require_react(), 1); - jsx_dev_runtime348 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/exportRenderer.tsx -function StaticKeybindingProvider({ - children -}) { - const { - bindings - } = loadKeybindingsSyncWithWarnings(); - const pendingChordRef = import_react190.useRef(null); - const handlerRegistryRef = import_react190.useRef(new Map); - const activeContexts = import_react190.useRef(new Set).current; - return /* @__PURE__ */ jsx_dev_runtime349.jsxDEV(KeybindingProvider, { - bindings, - pendingChordRef, - pendingChord: null, - setPendingChord: () => {}, - activeContexts, - registerActiveContext: () => {}, - unregisterActiveContext: () => {}, - handlerRegistryRef, - children - }, undefined, false, undefined, this); -} -function normalizedUpperBound(m4) { - if (!("message" in m4)) - return 1; - const c9 = m4.message.content; - return Array.isArray(c9) ? c9.length : 1; -} -async function streamRenderedMessages(messages, tools, sink2, { - columns, - verbose = false, - chunkSize = 40, - onProgress -} = {}) { - const renderChunk = (range) => renderToAnsiString(/* @__PURE__ */ jsx_dev_runtime349.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime349.jsxDEV(StaticKeybindingProvider, { - children: /* @__PURE__ */ jsx_dev_runtime349.jsxDEV(Messages10, { - messages, - tools, - commands: [], - verbose, - toolJSX: null, - toolUseConfirmQueue: [], - inProgressToolUseIDs: new Set, - isMessageSelectorVisible: false, - conversationId: "export", - screen: "prompt", - streamingToolUses: [], - showAllInTranscript: true, - isLoading: false, - renderRange: range - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), columns); - let ceiling = chunkSize; - for (const m4 of messages) - ceiling += normalizedUpperBound(m4); - for (let offset = 0;offset < ceiling; offset += chunkSize) { - const ansi = await renderChunk([offset, offset + chunkSize]); - if (stripAnsi(ansi).trim() === "") - break; - await sink2(ansi); - onProgress?.(offset + chunkSize); - } -} -async function renderMessagesToPlainText(messages, tools = [], columns) { - const parts = []; - await streamRenderedMessages(messages, tools, (chunk) => void parts.push(stripAnsi(chunk)), { - columns - }); - return parts.join(""); -} -var import_react190, jsx_dev_runtime349; -var init_exportRenderer = __esm(() => { - init_strip_ansi(); - init_Messages(); - init_KeybindingContext(); - init_loadUserBindings(); - init_AppState(); - init_staticRender(); - import_react190 = __toESM(require_react(), 1); - jsx_dev_runtime349 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/export/export.tsx -var exports_export = {}; -__export(exports_export, { - sanitizeFilename: () => sanitizeFilename, - extractFirstPrompt: () => extractFirstPrompt, - call: () => call62 -}); -import { join as join135 } from "path"; -function formatTimestamp(date6) { - const year = date6.getFullYear(); - const month = String(date6.getMonth() + 1).padStart(2, "0"); - const day = String(date6.getDate()).padStart(2, "0"); - const hours = String(date6.getHours()).padStart(2, "0"); - const minutes = String(date6.getMinutes()).padStart(2, "0"); - const seconds = String(date6.getSeconds()).padStart(2, "0"); - return `${year}-${month}-${day}-${hours}${minutes}${seconds}`; -} -function extractFirstPrompt(messages) { - const firstUserMessage = messages.find((msg) => msg.type === "user"); - if (!firstUserMessage || firstUserMessage.type !== "user") { - return ""; - } - const content = firstUserMessage.message?.content; - let result = ""; - if (typeof content === "string") { - result = content.trim(); - } else if (Array.isArray(content)) { - const textContent = content.find((item) => item.type === "text"); - if (textContent && "text" in textContent) { - result = textContent.text.trim(); - } - } - result = result.split(` -`)[0] || ""; - if (result.length > 50) { - result = result.substring(0, 49) + "\u2026"; - } - return result; -} -function sanitizeFilename(text) { - return text.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, ""); -} -async function exportWithReactRenderer(context7) { - const tools = context7.options.tools || []; - return renderMessagesToPlainText(context7.messages, tools); -} -async function call62(onDone, context7, args) { - const content = await exportWithReactRenderer(context7); - const filename = args.trim(); - if (filename) { - const finalFilename = filename.endsWith(".txt") ? filename : filename.replace(/\.[^.]+$/, "") + ".txt"; - const filepath = join135(getCwd(), finalFilename); - try { - writeFileSync_DEPRECATED(filepath, content, { - encoding: "utf-8", - flush: true - }); - onDone(`Conversation exported to: ${filepath}`); - return null; - } catch (error46) { - onDone(`Failed to export conversation: ${error46 instanceof Error ? error46.message : "Unknown error"}`); - return null; - } - } - const firstPrompt = extractFirstPrompt(context7.messages); - const timestamp = formatTimestamp(new Date); - let defaultFilename; - if (firstPrompt) { - const sanitized = sanitizeFilename(firstPrompt); - defaultFilename = sanitized ? `${timestamp}-${sanitized}.txt` : `conversation-${timestamp}.txt`; - } else { - defaultFilename = `conversation-${timestamp}.txt`; - } - return /* @__PURE__ */ jsx_dev_runtime350.jsxDEV(ExportDialog, { - content, - defaultFilename, - onDone: (result) => { - onDone(result.message); - } - }, undefined, false, undefined, this); -} -var jsx_dev_runtime350; -var init_export = __esm(() => { - init_ExportDialog(); - init_cwd(); - init_exportRenderer(); - init_slowOperations(); - jsx_dev_runtime350 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/export/index.ts -var exportCommand, export_default; -var init_export2 = __esm(() => { - exportCommand = { - type: "local-jsx", - name: "export", - description: "Export the current conversation to a file or clipboard", - argumentHint: "[filename]", - load: () => Promise.resolve().then(() => (init_export(), exports_export)) - }; - export_default = exportCommand; -}); - -// src/commands/model/model.tsx -var exports_model2 = {}; -__export(exports_model2, { - call: () => call63 -}); -function ModelPickerWrapper(t0) { - const $2 = import_compiler_runtime272.c(17); - const { - onDone - } = t0; - const mainLoopModel = useAppState(_temp163); - const mainLoopModelForSession = useAppState(_temp272); - const isFastMode = useAppState(_temp346); - const setAppState = useSetAppState(); - let t1; - if ($2[0] !== mainLoopModel || $2[1] !== onDone) { - t1 = function handleCancel2() { - logEvent("tengu_model_command_menu", { - action: "cancel" - }); - const displayModel = renderModelLabel(mainLoopModel); - onDone(`Kept model as ${source_default.bold(displayModel)}`, { - display: "system" - }); - }; - $2[0] = mainLoopModel; - $2[1] = onDone; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const handleCancel = t1; - let t22; - if ($2[3] !== isFastMode || $2[4] !== mainLoopModel || $2[5] !== onDone || $2[6] !== setAppState) { - t22 = function handleSelect2(model, effort) { - logEvent("tengu_model_command_menu", { - action: model, - from_model: mainLoopModel, - to_model: model - }); - setAppState((prev) => ({ - ...prev, - mainLoopModel: model, - mainLoopModelForSession: null - })); - let message = `Set model to ${source_default.bold(renderModelLabel(model))}`; - if (effort !== undefined) { - message = message + ` with ${source_default.bold(effort)} effort`; - } - let wasFastModeToggledOn = undefined; - if (isFastModeEnabled()) { - clearFastModeCooldown(); - if (!isFastModeSupportedByModel(model) && isFastMode) { - setAppState(_temp434); - wasFastModeToggledOn = false; - } else { - if (isFastModeSupportedByModel(model) && isFastModeAvailable() && isFastMode) { - message = message + " \xB7 Fast mode ON"; - wasFastModeToggledOn = true; - } - } - } - if (isBilledAsExtraUsage(model, wasFastModeToggledOn === true, isOpus1mMergeEnabled())) { - message = message + " \xB7 Billed as extra usage"; - } - if (wasFastModeToggledOn === false) { - message = message + " \xB7 Fast mode OFF"; - } - onDone(message); - }; - $2[3] = isFastMode; - $2[4] = mainLoopModel; - $2[5] = onDone; - $2[6] = setAppState; - $2[7] = t22; - } else { - t22 = $2[7]; - } - const handleSelect = t22; - let t32; - if ($2[8] !== isFastMode || $2[9] !== mainLoopModel) { - t32 = isFastModeEnabled() && isFastMode && isFastModeSupportedByModel(mainLoopModel) && isFastModeAvailable(); - $2[8] = isFastMode; - $2[9] = mainLoopModel; - $2[10] = t32; - } else { - t32 = $2[10]; - } - let t4; - if ($2[11] !== handleCancel || $2[12] !== handleSelect || $2[13] !== mainLoopModel || $2[14] !== mainLoopModelForSession || $2[15] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime351.jsxDEV(ModelPicker, { - initial: mainLoopModel, - sessionModel: mainLoopModelForSession, - onSelect: handleSelect, - onCancel: handleCancel, - isStandaloneCommand: true, - showFastModeNotice: t32 - }, undefined, false, undefined, this); - $2[11] = handleCancel; - $2[12] = handleSelect; - $2[13] = mainLoopModel; - $2[14] = mainLoopModelForSession; - $2[15] = t32; - $2[16] = t4; - } else { - t4 = $2[16]; - } - return t4; -} -function _temp434(prev_0) { - return { - ...prev_0, - fastMode: false - }; -} -function _temp346(s_1) { - return s_1.fastMode; -} -function _temp272(s_0) { - return s_0.mainLoopModelForSession; -} -function _temp163(s4) { - return s4.mainLoopModel; -} -function SetModelAndClose({ - args, - onDone -}) { - const isFastMode = useAppState((s4) => s4.fastMode); - const setAppState = useSetAppState(); - const model = args === "default" ? null : args; - React107.useEffect(() => { - async function handleModelChange() { - if (model && !isModelAllowed(model)) { - onDone(`Model '${model}' is not available. Your organization restricts model selection.`, { - display: "system" - }); - return; - } - if (model && isOpus1mUnavailable(model)) { - onDone(`Opus 4.6 with 1M context is not available for your account. Learn more: https://code.claude.com/docs/en/model-config#extended-context-with-1m`, { - display: "system" - }); - return; - } - if (model && isSonnet1mUnavailable(model)) { - onDone(`Sonnet 4.6 with 1M context is not available for your account. Learn more: https://code.claude.com/docs/en/model-config#extended-context-with-1m`, { - display: "system" - }); - return; - } - if (!model) { - setModel(null); - return; - } - if (isKnownAlias(model)) { - setModel(model); - return; - } - try { - const { - valid, - error: error_0 - } = await validateModel(model); - if (valid) { - setModel(model); - } else { - onDone(error_0 || `Model '${model}' not found`, { - display: "system" - }); - } - } catch (error46) { - onDone(`Failed to validate model: ${error46.message}`, { - display: "system" - }); - } - } - function setModel(modelValue) { - setAppState((prev) => ({ - ...prev, - mainLoopModel: modelValue, - mainLoopModelForSession: null - })); - let message = `Set model to ${source_default.bold(renderModelLabel(modelValue))}`; - let wasFastModeToggledOn = undefined; - if (isFastModeEnabled()) { - clearFastModeCooldown(); - if (!isFastModeSupportedByModel(modelValue) && isFastMode) { - setAppState((prev_0) => ({ - ...prev_0, - fastMode: false - })); - wasFastModeToggledOn = false; - } else if (isFastModeSupportedByModel(modelValue) && isFastMode) { - message += ` \xB7 Fast mode ON`; - wasFastModeToggledOn = true; - } - } - if (isBilledAsExtraUsage(modelValue, wasFastModeToggledOn === true, isOpus1mMergeEnabled())) { - message += ` \xB7 Billed as extra usage`; - } - if (wasFastModeToggledOn === false) { - message += ` \xB7 Fast mode OFF`; - } - onDone(message); - } - handleModelChange(); - }, [model, onDone, setAppState]); - return null; -} -function isKnownAlias(model) { - return MODEL_ALIASES.includes(model.toLowerCase().trim()); -} -function isOpus1mUnavailable(model) { - const m4 = model.toLowerCase(); - return !checkOpus1mAccess() && !isOpus1mMergeEnabled() && m4.includes("opus") && m4.includes("[1m]"); -} -function isSonnet1mUnavailable(model) { - const m4 = model.toLowerCase(); - return !checkSonnet1mAccess() && (m4.includes("sonnet[1m]") || m4.includes("sonnet-4-6[1m]")); -} -function ShowModelAndClose(t0) { - const { - onDone - } = t0; - const mainLoopModel = useAppState(_temp717); - const mainLoopModelForSession = useAppState(_temp813); - const effortValue = useAppState(_temp913); - const displayModel = renderModelLabel(mainLoopModel); - const effortInfo = effortValue !== undefined ? ` (effort: ${effortValue})` : ""; - if (mainLoopModelForSession) { - onDone(`Current model: ${source_default.bold(renderModelLabel(mainLoopModelForSession))} (session override from plan mode) -Base model: ${displayModel}${effortInfo}`); - } else { - onDone(`Current model: ${displayModel}${effortInfo}`); - } - return null; -} -function _temp913(s_1) { - return s_1.effortValue; -} -function _temp813(s_0) { - return s_0.mainLoopModelForSession; -} -function _temp717(s4) { - return s4.mainLoopModel; -} -function renderModelLabel(model) { - const rendered = renderDefaultModelSetting(model ?? getDefaultMainLoopModelSetting()); - return model === null ? `${rendered} (default)` : rendered; -} -var import_compiler_runtime272, React107, jsx_dev_runtime351, call63 = async (onDone, _context, args) => { - args = args?.trim() || ""; - if (COMMON_INFO_ARGS.includes(args)) { - logEvent("tengu_model_command_inline_help", { - args - }); - return /* @__PURE__ */ jsx_dev_runtime351.jsxDEV(ShowModelAndClose, { - onDone - }, undefined, false, undefined, this); - } - if (COMMON_HELP_ARGS.includes(args)) { - onDone("Run /model to open the model selection menu, or /model [modelName] to set the model.", { - display: "system" - }); - return; - } - if (args) { - logEvent("tengu_model_command_inline", { - args - }); - return /* @__PURE__ */ jsx_dev_runtime351.jsxDEV(SetModelAndClose, { - args, - onDone - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime351.jsxDEV(ModelPickerWrapper, { - onDone - }, undefined, false, undefined, this); -}; -var init_model2 = __esm(() => { - init_source(); - init_ModelPicker(); - init_xml(); - init_analytics(); - init_AppState(); - init_extraUsage(); - init_fastMode(); - init_aliases(); - init_check1mAccess(); - init_model(); - init_modelAllowlist(); - init_validateModel(); - import_compiler_runtime272 = __toESM(require_compiler_runtime(), 1); - React107 = __toESM(require_react(), 1); - jsx_dev_runtime351 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/model/index.ts -var model_default; -var init_model3 = __esm(() => { - init_immediateCommand(); - init_model(); - model_default = { - type: "local-jsx", - name: "model", - get description() { - return `Set the AI model for Claude Code (currently ${renderModelName(getMainLoopModel())})`; - }, - argumentHint: "[model]", - get immediate() { - return shouldInferenceConfigCommandBeImmediate(); - }, - load: () => Promise.resolve().then(() => (init_model2(), exports_model2)) - }; -}); - -// src/commands/tag/tag.tsx -var exports_tag = {}; -__export(exports_tag, { - call: () => call64 -}); -function ConfirmRemoveTag(t0) { - const $2 = import_compiler_runtime273.c(11); - const { - tagName, - onConfirm, - onCancel - } = t0; - const t1 = `Current tag: #${tagName}`; - let t22; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(ThemedText, { - children: "This will remove the tag from the current session." - }, undefined, false, undefined, this); - $2[0] = t22; - } else { - t22 = $2[0]; - } - let t32; - if ($2[1] !== onCancel || $2[2] !== onConfirm) { - t32 = (value) => value === "yes" ? onConfirm() : onCancel(); - $2[1] = onCancel; - $2[2] = onConfirm; - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = [{ - label: "Yes, remove tag", - value: "yes" - }, { - label: "No, keep tag", - value: "no" - }]; - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] !== t32) { - t5 = /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t22, - /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(Select, { - onChange: t32, - options: t4 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[5] = t32; - $2[6] = t5; - } else { - t5 = $2[6]; - } - let t6; - if ($2[7] !== onCancel || $2[8] !== t1 || $2[9] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(Dialog, { - title: "Remove tag?", - subtitle: t1, - onCancel, - color: "warning", - children: t5 - }, undefined, false, undefined, this); - $2[7] = onCancel; - $2[8] = t1; - $2[9] = t5; - $2[10] = t6; - } else { - t6 = $2[10]; - } - return t6; -} -function ToggleTagAndClose(t0) { - const $2 = import_compiler_runtime273.c(17); - const { - tagName, - onDone - } = t0; - const [showConfirm, setShowConfirm] = React108.useState(false); - const [sessionId, setSessionId] = React108.useState(null); - let t1; - if ($2[0] !== tagName) { - t1 = recursivelySanitizeUnicode(tagName).trim(); - $2[0] = tagName; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const normalizedTag = t1; - let t22; - let t32; - if ($2[2] !== normalizedTag || $2[3] !== onDone) { - t22 = () => { - const id = getSessionId(); - if (!id) { - onDone("No active session to tag", { - display: "system" - }); - return; - } - if (!normalizedTag) { - onDone("Tag name cannot be empty", { - display: "system" - }); - return; - } - setSessionId(id); - const currentTag = getCurrentSessionTag(id); - if (currentTag === normalizedTag) { - logEvent("tengu_tag_command_remove_prompt", {}); - setShowConfirm(true); - } else { - const isReplacing = !!currentTag; - logEvent("tengu_tag_command_add", { - is_replacing: isReplacing - }); - (async () => { - const fullPath = getTranscriptPath(); - await saveTag(id, normalizedTag, fullPath); - onDone(`Tagged session with ${source_default.cyan(`#${normalizedTag}`)}`, { - display: "system" - }); - })(); - } - }; - t32 = [normalizedTag, onDone]; - $2[2] = normalizedTag; - $2[3] = onDone; - $2[4] = t22; - $2[5] = t32; - } else { - t22 = $2[4]; - t32 = $2[5]; - } - React108.useEffect(t22, t32); - if (showConfirm && sessionId) { - let t4; - if ($2[6] !== normalizedTag || $2[7] !== onDone || $2[8] !== sessionId) { - t4 = async () => { - logEvent("tengu_tag_command_remove_confirmed", {}); - const fullPath_0 = getTranscriptPath(); - await saveTag(sessionId, "", fullPath_0); - onDone(`Removed tag ${source_default.cyan(`#${normalizedTag}`)}`, { - display: "system" - }); - }; - $2[6] = normalizedTag; - $2[7] = onDone; - $2[8] = sessionId; - $2[9] = t4; - } else { - t4 = $2[9]; - } - let t5; - if ($2[10] !== normalizedTag || $2[11] !== onDone) { - t5 = () => { - logEvent("tengu_tag_command_remove_cancelled", {}); - onDone(`Kept tag ${source_default.cyan(`#${normalizedTag}`)}`, { - display: "system" - }); - }; - $2[10] = normalizedTag; - $2[11] = onDone; - $2[12] = t5; - } else { - t5 = $2[12]; - } - let t6; - if ($2[13] !== normalizedTag || $2[14] !== t4 || $2[15] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(ConfirmRemoveTag, { - tagName: normalizedTag, - onConfirm: t4, - onCancel: t5 - }, undefined, false, undefined, this); - $2[13] = normalizedTag; - $2[14] = t4; - $2[15] = t5; - $2[16] = t6; - } else { - t6 = $2[16]; - } - return t6; - } - return null; -} -function ShowHelp(t0) { - const $2 = import_compiler_runtime273.c(3); - const { - onDone - } = t0; - let t1; - let t22; - if ($2[0] !== onDone) { - t1 = () => { - onDone(`Usage: /tag - -Toggle a searchable tag on the current session. -Run the same command again to remove the tag. -Tags are displayed after the branch name in /resume and can be searched with /. - -Examples: - /tag bugfix # Add tag - /tag bugfix # Remove tag (toggle) - /tag feature-auth - /tag wip`, { - display: "system" - }); - }; - t22 = [onDone]; - $2[0] = onDone; - $2[1] = t1; - $2[2] = t22; - } else { - t1 = $2[1]; - t22 = $2[2]; - } - React108.useEffect(t1, t22); - return null; -} -async function call64(onDone, _context, args) { - args = args?.trim() || ""; - if (COMMON_INFO_ARGS.includes(args) || COMMON_HELP_ARGS.includes(args)) { - return /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(ShowHelp, { - onDone - }, undefined, false, undefined, this); - } - if (!args) { - return /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(ShowHelp, { - onDone - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime352.jsxDEV(ToggleTagAndClose, { - tagName: args, - onDone - }, undefined, false, undefined, this); -} -var import_compiler_runtime273, React108, jsx_dev_runtime352; -var init_tag = __esm(() => { - init_source(); - init_state(); - init_select(); - init_Dialog(); - init_xml(); - init_ink2(); - init_analytics(); - init_sessionStorage(); - import_compiler_runtime273 = __toESM(require_compiler_runtime(), 1); - React108 = __toESM(require_react(), 1); - jsx_dev_runtime352 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/tag/index.ts -var tag2, tag_default; -var init_tag2 = __esm(() => { - tag2 = { - type: "local-jsx", - name: "tag", - description: "Toggle a searchable tag on the current session", - isEnabled: () => process.env.USER_TYPE === "ant", - argumentHint: "", - load: () => Promise.resolve().then(() => (init_tag(), exports_tag)) - }; - tag_default = tag2; -}); - -// src/commands/output-style/output-style.tsx -var exports_output_style = {}; -__export(exports_output_style, { - call: () => call65 -}); -async function call65(onDone) { - onDone("/output-style has been deprecated. Use /config to change your output style, or set it in your settings file. Changes take effect on the next session.", { - display: "system" - }); -} - -// src/commands/output-style/index.ts -var outputStyle, output_style_default; -var init_output_style = __esm(() => { - outputStyle = { - type: "local-jsx", - name: "output-style", - description: "Deprecated: use /config to change output style", - isHidden: true, - load: () => Promise.resolve().then(() => exports_output_style) - }; - output_style_default = outputStyle; -}); - -// src/utils/teleport/environmentSelection.ts -async function getEnvironmentSelectionInfo() { - const environments = await fetchEnvironments(); - if (environments.length === 0) { - return { - availableEnvironments: [], - selectedEnvironment: null, - selectedEnvironmentSource: null - }; - } - const mergedSettings = getSettings_DEPRECATED(); - const defaultEnvironmentId = mergedSettings?.remote?.defaultEnvironmentId; - let selectedEnvironment = environments.find((env5) => env5.kind !== "bridge") ?? environments[0]; - let selectedEnvironmentSource = null; - if (defaultEnvironmentId) { - const matchingEnvironment = environments.find((env5) => env5.environment_id === defaultEnvironmentId); - if (matchingEnvironment) { - selectedEnvironment = matchingEnvironment; - for (let i6 = SETTING_SOURCES.length - 1;i6 >= 0; i6--) { - const source = SETTING_SOURCES[i6]; - if (!source || source === "flagSettings") { - continue; - } - const sourceSettings = getSettingsForSource(source); - if (sourceSettings?.remote?.defaultEnvironmentId === defaultEnvironmentId) { - selectedEnvironmentSource = source; - break; - } - } - } - } - return { - availableEnvironments: environments, - selectedEnvironment, - selectedEnvironmentSource - }; -} -var init_environmentSelection = __esm(() => { - init_constants2(); - init_settings2(); - init_environments(); -}); - -// src/components/RemoteEnvironmentDialog.tsx -function RemoteEnvironmentDialog(t0) { - const $2 = import_compiler_runtime274.c(27); - const { - onDone - } = t0; - const [loadingState, setLoadingState] = import_react191.useState("loading"); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = []; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const [environments, setEnvironments] = import_react191.useState(t1); - const [selectedEnvironment, setSelectedEnvironment] = import_react191.useState(null); - const [selectedEnvironmentSource, setSelectedEnvironmentSource] = import_react191.useState(null); - const [error46, setError] = import_react191.useState(null); - let t22; - let t32; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = () => { - let cancelled = false; - const fetchInfo = async function fetchInfo2() { - try { - const result = await getEnvironmentSelectionInfo(); - if (cancelled) { - return; - } - setEnvironments(result.availableEnvironments); - setSelectedEnvironment(result.selectedEnvironment); - setSelectedEnvironmentSource(result.selectedEnvironmentSource); - setLoadingState(null); - } catch (t42) { - const err2 = t42; - if (cancelled) { - return; - } - const fetchError = toError(err2); - logError2(fetchError); - setError(fetchError.message); - setLoadingState(null); - } - }; - fetchInfo(); - return () => { - cancelled = true; - }; - }; - t32 = []; - $2[1] = t22; - $2[2] = t32; - } else { - t22 = $2[1]; - t32 = $2[2]; - } - import_react191.useEffect(t22, t32); - let t4; - if ($2[3] !== environments || $2[4] !== onDone) { - t4 = function handleSelect2(value) { - if (value === "cancel") { - onDone(); - return; - } - setLoadingState("updating"); - const selectedEnv = environments.find((env5) => env5.environment_id === value); - if (!selectedEnv) { - onDone("Error: Selected environment not found"); - return; - } - updateSettingsForSource("localSettings", { - remote: { - defaultEnvironmentId: selectedEnv.environment_id - } - }); - onDone(`Set default remote environment to ${source_default.bold(selectedEnv.name)} (${selectedEnv.environment_id})`); - }; - $2[3] = environments; - $2[4] = onDone; - $2[5] = t4; - } else { - t4 = $2[5]; - } - const handleSelect = t4; - if (loadingState === "loading") { - let t52; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t52 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(LoadingState, { - message: "Loading environments\u2026" - }, undefined, false, undefined, this); - $2[6] = t52; - } else { - t52 = $2[6]; - } - let t6; - if ($2[7] !== onDone) { - t6 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Dialog, { - title: DIALOG_TITLE, - onCancel: onDone, - hideInputGuide: true, - children: t52 - }, undefined, false, undefined, this); - $2[7] = onDone; - $2[8] = t6; - } else { - t6 = $2[8]; - } - return t6; - } - if (error46) { - let t52; - if ($2[9] !== error46) { - t52 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - color: "error", - children: [ - "Error: ", - error46 - ] - }, undefined, true, undefined, this); - $2[9] = error46; - $2[10] = t52; - } else { - t52 = $2[10]; - } - let t6; - if ($2[11] !== onDone || $2[12] !== t52) { - t6 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Dialog, { - title: DIALOG_TITLE, - onCancel: onDone, - children: t52 - }, undefined, false, undefined, this); - $2[11] = onDone; - $2[12] = t52; - $2[13] = t6; - } else { - t6 = $2[13]; - } - return t6; - } - if (!selectedEnvironment) { - let t52; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t52 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - children: "No remote environments available." - }, undefined, false, undefined, this); - $2[14] = t52; - } else { - t52 = $2[14]; - } - let t6; - if ($2[15] !== onDone) { - t6 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Dialog, { - title: DIALOG_TITLE, - subtitle: SETUP_HINT, - onCancel: onDone, - children: t52 - }, undefined, false, undefined, this); - $2[15] = onDone; - $2[16] = t6; - } else { - t6 = $2[16]; - } - return t6; - } - if (environments.length === 1) { - let t52; - if ($2[17] !== onDone || $2[18] !== selectedEnvironment) { - t52 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(SingleEnvironmentContent, { - environment: selectedEnvironment, - onDone - }, undefined, false, undefined, this); - $2[17] = onDone; - $2[18] = selectedEnvironment; - $2[19] = t52; - } else { - t52 = $2[19]; - } - return t52; - } - let t5; - if ($2[20] !== environments || $2[21] !== handleSelect || $2[22] !== loadingState || $2[23] !== onDone || $2[24] !== selectedEnvironment || $2[25] !== selectedEnvironmentSource) { - t5 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(MultipleEnvironmentsContent, { - environments, - selectedEnvironment, - selectedEnvironmentSource, - loadingState, - onSelect: handleSelect, - onCancel: onDone - }, undefined, false, undefined, this); - $2[20] = environments; - $2[21] = handleSelect; - $2[22] = loadingState; - $2[23] = onDone; - $2[24] = selectedEnvironment; - $2[25] = selectedEnvironmentSource; - $2[26] = t5; - } else { - t5 = $2[26]; - } - return t5; -} -function EnvironmentLabel(t0) { - const $2 = import_compiler_runtime274.c(7); - const { - environment - } = t0; - let t1; - if ($2[0] !== environment.name) { - t1 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - bold: true, - children: environment.name - }, undefined, false, undefined, this); - $2[0] = environment.name; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== environment.environment_id) { - t22 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "(", - environment.environment_id, - ")" - ] - }, undefined, true, undefined, this); - $2[2] = environment.environment_id; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== t1 || $2[5] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - children: [ - figures_default.tick, - " Using ", - t1, - " ", - t22 - ] - }, undefined, true, undefined, this); - $2[4] = t1; - $2[5] = t22; - $2[6] = t32; - } else { - t32 = $2[6]; - } - return t32; -} -function SingleEnvironmentContent(t0) { - const $2 = import_compiler_runtime274.c(6); - const { - environment, - onDone - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - context: "Confirmation" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - useKeybinding("confirm:yes", onDone, t1); - let t22; - if ($2[1] !== environment) { - t22 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(EnvironmentLabel, { - environment - }, undefined, false, undefined, this); - $2[1] = environment; - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== onDone || $2[4] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Dialog, { - title: DIALOG_TITLE, - subtitle: SETUP_HINT, - onCancel: onDone, - children: t22 - }, undefined, false, undefined, this); - $2[3] = onDone; - $2[4] = t22; - $2[5] = t32; - } else { - t32 = $2[5]; - } - return t32; -} -function MultipleEnvironmentsContent(t0) { - const $2 = import_compiler_runtime274.c(18); - const { - environments, - selectedEnvironment, - selectedEnvironmentSource, - loadingState, - onSelect, - onCancel - } = t0; - let t1; - if ($2[0] !== selectedEnvironmentSource) { - t1 = selectedEnvironmentSource && selectedEnvironmentSource !== "localSettings" ? ` (from ${getSettingSourceName(selectedEnvironmentSource)} settings)` : ""; - $2[0] = selectedEnvironmentSource; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const sourceSuffix = t1; - let t22; - if ($2[2] !== selectedEnvironment.name) { - t22 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - bold: true, - children: selectedEnvironment.name - }, undefined, false, undefined, this); - $2[2] = selectedEnvironment.name; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== sourceSuffix || $2[5] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - children: [ - "Currently using: ", - t22, - sourceSuffix - ] - }, undefined, true, undefined, this); - $2[4] = sourceSuffix; - $2[5] = t22; - $2[6] = t32; - } else { - t32 = $2[6]; - } - const subtitle = t32; - let t4; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - dimColor: true, - children: SETUP_HINT - }, undefined, false, undefined, this); - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] !== environments || $2[9] !== loadingState || $2[10] !== onSelect || $2[11] !== selectedEnvironment.environment_id) { - t5 = loadingState === "updating" ? /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(LoadingState, { - message: "Updating\u2026" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Select, { - options: environments.map(_temp165), - defaultValue: selectedEnvironment.environment_id, - onChange: onSelect, - onCancel: () => onSelect("cancel"), - layout: "compact-vertical" - }, undefined, false, undefined, this); - $2[8] = environments; - $2[9] = loadingState; - $2[10] = onSelect; - $2[11] = selectedEnvironment.environment_id; - $2[12] = t5; - } else { - t5 = $2[12]; - } - let t6; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[13] = t6; - } else { - t6 = $2[13]; - } - let t7; - if ($2[14] !== onCancel || $2[15] !== subtitle || $2[16] !== t5) { - t7 = /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(Dialog, { - title: DIALOG_TITLE, - subtitle, - onCancel, - hideInputGuide: true, - children: [ - t4, - t5, - t6 - ] - }, undefined, true, undefined, this); - $2[14] = onCancel; - $2[15] = subtitle; - $2[16] = t5; - $2[17] = t7; - } else { - t7 = $2[17]; - } - return t7; -} -function _temp165(env5) { - return { - label: /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - children: [ - env5.name, - " ", - /* @__PURE__ */ jsx_dev_runtime353.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "(", - env5.environment_id, - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - value: env5.environment_id - }; -} -var import_compiler_runtime274, import_react191, jsx_dev_runtime353, DIALOG_TITLE = "Select Remote Environment", SETUP_HINT = `Configure environments at: https://claude.ai/code`; -var init_RemoteEnvironmentDialog = __esm(() => { - init_source(); - init_figures(); - init_ink2(); - init_useKeybinding(); - init_errors(); - init_log2(); - init_constants2(); - init_settings2(); - init_environmentSelection(); - init_ConfigurableShortcutHint(); - init_select(); - init_Byline(); - init_Dialog(); - init_KeyboardShortcutHint(); - init_LoadingState(); - import_compiler_runtime274 = __toESM(require_compiler_runtime(), 1); - import_react191 = __toESM(require_react(), 1); - jsx_dev_runtime353 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/remote-env/remote-env.tsx -var exports_remote_env = {}; -__export(exports_remote_env, { - call: () => call66 -}); -async function call66(onDone) { - return /* @__PURE__ */ jsx_dev_runtime354.jsxDEV(RemoteEnvironmentDialog, { - onDone - }, undefined, false, undefined, this); -} -var jsx_dev_runtime354; -var init_remote_env = __esm(() => { - init_RemoteEnvironmentDialog(); - jsx_dev_runtime354 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/remote-env/index.ts -var remote_env_default; -var init_remote_env2 = __esm(() => { - init_policyLimits(); - init_auth14(); - remote_env_default = { - type: "local-jsx", - name: "remote-env", - description: "Configure the default remote environment for teleport sessions", - isEnabled: () => isClaudeAISubscriber() && isPolicyAllowed("allow_remote_sessions"), - get isHidden() { - return !isClaudeAISubscriber() || !isPolicyAllowed("allow_remote_sessions"); - }, - load: () => Promise.resolve().then(() => (init_remote_env(), exports_remote_env)) - }; -}); - -// src/commands/upgrade/upgrade.tsx -var exports_upgrade = {}; -__export(exports_upgrade, { - call: () => call67 -}); -async function call67(onDone, context7) { - try { - if (isClaudeAISubscriber()) { - const tokens = getClaudeAIOAuthTokens(); - let isMax20x = false; - if (tokens?.subscriptionType && tokens?.rateLimitTier) { - isMax20x = tokens.subscriptionType === "max" && tokens.rateLimitTier === "default_claude_max_20x"; - } else if (tokens?.accessToken) { - const profile7 = await getOauthProfileFromOauthToken(tokens.accessToken); - isMax20x = profile7?.organization?.organization_type === "claude_max" && profile7?.organization?.rate_limit_tier === "default_claude_max_20x"; - } - if (isMax20x) { - setTimeout(onDone, 0, "You are already on the highest Max subscription plan. For additional usage, run /login to switch to an API usage-billed account."); - return null; - } - } - const url3 = "https://claude.ai/upgrade/max"; - await openBrowser(url3); - return /* @__PURE__ */ jsx_dev_runtime355.jsxDEV(Login, { - startingMessage: "Starting new login following /upgrade. Exit with Ctrl-C to use existing account.", - onDone: (success2) => { - context7.onChangeAPIKey(); - onDone(success2 ? "Login successful" : "Login interrupted"); - } - }, undefined, false, undefined, this); - } catch (error46) { - logError2(error46); - setTimeout(onDone, 0, "Failed to open browser. Please visit https://claude.ai/upgrade/max to upgrade."); - } - return null; -} -var jsx_dev_runtime355; -var init_upgrade = __esm(() => { - init_getOauthProfile(); - init_auth14(); - init_browser(); - init_log2(); - init_login(); - jsx_dev_runtime355 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/upgrade/index.ts -var upgrade, upgrade_default; -var init_upgrade2 = __esm(() => { - init_auth14(); - init_envUtils(); - upgrade = { - type: "local-jsx", - name: "upgrade", - description: "Upgrade to Max for higher rate limits and more Opus", - availability: ["claude-ai"], - isEnabled: () => !isEnvTruthy(process.env.DISABLE_UPGRADE_COMMAND) && getSubscriptionType() !== "enterprise", - load: () => Promise.resolve().then(() => (init_upgrade(), exports_upgrade)) - }; - upgrade_default = upgrade; -}); - -// src/commands/rate-limit-options/rate-limit-options.tsx -var exports_rate_limit_options = {}; -__export(exports_rate_limit_options, { - call: () => call68 -}); -function RateLimitOptionsMenu(t0) { - const $2 = import_compiler_runtime275.c(25); - const { - onDone, - context: context7 - } = t0; - const [subCommandJSX, setSubCommandJSX] = import_react192.useState(null); - const claudeAiLimits = useClaudeAiLimits(); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getSubscriptionType(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const subscriptionType = t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = getRateLimitTier(); - $2[1] = t22; - } else { - t22 = $2[1]; - } - const rateLimitTier = t22; - const hasExtraUsageEnabled = getOauthAccountInfo()?.hasExtraUsageEnabled === true; - const isMax = subscriptionType === "max"; - const isMax20x = isMax && rateLimitTier === "default_claude_max_20x"; - const isTeamOrEnterprise = subscriptionType === "team" || subscriptionType === "enterprise"; - const buyFirst = getFeatureValue_CACHED_MAY_BE_STALE("tengu_jade_anvil_4", false); - let t32; - bb0: { - let actionOptions; - if ($2[2] !== claudeAiLimits.overageDisabledReason || $2[3] !== claudeAiLimits.overageStatus) { - actionOptions = []; - if (extraUsage.isEnabled()) { - const hasBillingAccess = hasClaudeAiBillingAccess(); - const needsToRequestFromAdmin = isTeamOrEnterprise && !hasBillingAccess; - const isOrgSpendCapDepleted = claudeAiLimits.overageDisabledReason === "out_of_credits" || claudeAiLimits.overageDisabledReason === "org_level_disabled_until" || claudeAiLimits.overageDisabledReason === "org_service_zero_credit_limit"; - if (needsToRequestFromAdmin && isOrgSpendCapDepleted) {} else { - const isOverageState = claudeAiLimits.overageStatus === "rejected" || claudeAiLimits.overageStatus === "allowed_warning"; - let label; - if (needsToRequestFromAdmin) { - label = isOverageState ? "Request more" : "Request extra usage"; - } else { - label = hasExtraUsageEnabled ? "Add funds to continue with extra usage" : "Switch to extra usage"; - } - let t43; - if ($2[5] !== label) { - t43 = { - label, - value: "extra-usage" - }; - $2[5] = label; - $2[6] = t43; - } else { - t43 = $2[6]; - } - actionOptions.push(t43); - } - } - if (!isMax20x && !isTeamOrEnterprise && upgrade_default.isEnabled()) { - let t43; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t43 = { - label: "Upgrade your plan", - value: "upgrade" - }; - $2[7] = t43; - } else { - t43 = $2[7]; - } - actionOptions.push(t43); - } - $2[2] = claudeAiLimits.overageDisabledReason; - $2[3] = claudeAiLimits.overageStatus; - $2[4] = actionOptions; - } else { - actionOptions = $2[4]; - } - let t42; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t42 = { - label: "Stop and wait for limit to reset", - value: "cancel" - }; - $2[8] = t42; - } else { - t42 = $2[8]; - } - const cancelOption = t42; - if (buyFirst) { - let t53; - if ($2[9] !== actionOptions) { - t53 = [...actionOptions, cancelOption]; - $2[9] = actionOptions; - $2[10] = t53; - } else { - t53 = $2[10]; - } - t32 = t53; - break bb0; - } - let t52; - if ($2[11] !== actionOptions) { - t52 = [cancelOption, ...actionOptions]; - $2[11] = actionOptions; - $2[12] = t52; - } else { - t52 = $2[12]; - } - t32 = t52; - } - const options2 = t32; - let t4; - if ($2[13] !== onDone) { - t4 = function handleCancel2() { - logEvent("tengu_rate_limit_options_menu_cancel", {}); - onDone(undefined, { - display: "skip" - }); - }; - $2[13] = onDone; - $2[14] = t4; - } else { - t4 = $2[14]; - } - const handleCancel = t4; - let t5; - if ($2[15] !== context7 || $2[16] !== handleCancel || $2[17] !== onDone) { - t5 = function handleSelect2(value) { - if (value === "upgrade") { - logEvent("tengu_rate_limit_options_menu_select_upgrade", {}); - call67(onDone, context7).then((jsx) => { - if (jsx) { - setSubCommandJSX(jsx); - } - }); - } else { - if (value === "extra-usage") { - logEvent("tengu_rate_limit_options_menu_select_extra_usage", {}); - call4(onDone, context7).then((jsx_0) => { - if (jsx_0) { - setSubCommandJSX(jsx_0); - } - }); - } else { - if (value === "cancel") { - handleCancel(); - } - } - } - }; - $2[15] = context7; - $2[16] = handleCancel; - $2[17] = onDone; - $2[18] = t5; - } else { - t5 = $2[18]; - } - const handleSelect = t5; - if (subCommandJSX) { - return subCommandJSX; - } - let t6; - if ($2[19] !== handleSelect || $2[20] !== options2) { - t6 = /* @__PURE__ */ jsx_dev_runtime356.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - visibleOptionCount: options2.length - }, undefined, false, undefined, this); - $2[19] = handleSelect; - $2[20] = options2; - $2[21] = t6; - } else { - t6 = $2[21]; - } - let t7; - if ($2[22] !== handleCancel || $2[23] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime356.jsxDEV(Dialog, { - title: "What do you want to do?", - onCancel: handleCancel, - color: "suggestion", - children: t6 - }, undefined, false, undefined, this); - $2[22] = handleCancel; - $2[23] = t6; - $2[24] = t7; - } else { - t7 = $2[24]; - } - return t7; -} -async function call68(onDone, context7) { - return /* @__PURE__ */ jsx_dev_runtime356.jsxDEV(RateLimitOptionsMenu, { - onDone, - context: context7 - }, undefined, false, undefined, this); -} -var import_compiler_runtime275, import_react192, jsx_dev_runtime356; -var init_rate_limit_options = __esm(() => { - init_select(); - init_Dialog(); - init_growthbook(); - init_analytics(); - init_claudeAiLimitsHook(); - init_auth14(); - init_billing(); - init_extra_usage(); - init_extra_usage2(); - init_upgrade2(); - init_upgrade(); - import_compiler_runtime275 = __toESM(require_compiler_runtime(), 1); - import_react192 = __toESM(require_react(), 1); - jsx_dev_runtime356 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/rate-limit-options/index.ts -var rateLimitOptions, rate_limit_options_default; -var init_rate_limit_options2 = __esm(() => { - init_auth14(); - rateLimitOptions = { - type: "local-jsx", - name: "rate-limit-options", - description: "Show options when rate limit is reached", - isEnabled: () => { - if (!isClaudeAISubscriber()) { - return false; - } - return true; - }, - isHidden: true, - load: () => Promise.resolve().then(() => (init_rate_limit_options(), exports_rate_limit_options)) - }; - rate_limit_options_default = rateLimitOptions; -}); - -// src/commands/statusline.tsx -var statusline, statusline_default; -var init_statusline = __esm(() => { - init_constants3(); - statusline = { - type: "prompt", - description: "Set up Claude Code's status line UI", - contentLength: 0, - aliases: [], - name: "statusline", - progressMessage: "setting up statusLine", - allowedTools: [AGENT_TOOL_NAME, "Read(~/**)", "Edit(~/.claude/settings.json)"], - source: "builtin", - disableNonInteractive: true, - async getPromptForCommand(args) { - const prompt = args.trim() || "Configure my statusLine from my shell PS1 configuration"; - return [{ - type: "text", - text: `Create an ${AGENT_TOOL_NAME} with subagent_type "statusline-setup" and the prompt "${prompt}"` - }]; - } - }; - statusline_default = statusline; -}); - -// src/commands/effort/effort.tsx -var exports_effort = {}; -__export(exports_effort, { - showCurrentEffort: () => showCurrentEffort, - executeEffort: () => executeEffort, - call: () => call69 -}); -function setEffortValue(effortValue) { - const persistable = toPersistableEffort(effortValue); - if (persistable !== undefined) { - const result = updateSettingsForSource("userSettings", { - effortLevel: persistable - }); - if (result.error) { - return { - message: `Failed to set effort level: ${result.error.message}` - }; - } - } - logEvent("tengu_effort_command", { - effort: effortValue - }); - const envOverride = getEffortEnvOverride(); - if (envOverride !== undefined && envOverride !== effortValue) { - const envRaw = process.env.CLAUDE_CODE_EFFORT_LEVEL; - if (persistable === undefined) { - return { - message: `Not applied: CLAUDE_CODE_EFFORT_LEVEL=${envRaw} overrides effort this session, and ${effortValue} is session-only (nothing saved)`, - effortUpdate: { - value: effortValue - } - }; - } - return { - message: `CLAUDE_CODE_EFFORT_LEVEL=${envRaw} overrides this session \u2014 clear it and ${effortValue} takes over`, - effortUpdate: { - value: effortValue - } - }; - } - const description = getEffortValueDescription(effortValue); - const suffix = persistable !== undefined ? "" : " (this session only)"; - return { - message: `Set effort level to ${effortValue}${suffix}: ${description}`, - effortUpdate: { - value: effortValue - } - }; -} -function showCurrentEffort(appStateEffort, model) { - const envOverride = getEffortEnvOverride(); - const effectiveValue = envOverride === null ? undefined : envOverride ?? appStateEffort; - if (effectiveValue === undefined) { - const level = getDisplayedEffortLevel(model, appStateEffort); - return { - message: `Effort level: auto (currently ${level})` - }; - } - const description = getEffortValueDescription(effectiveValue); - return { - message: `Current effort level: ${effectiveValue} (${description})` - }; -} -function unsetEffortLevel() { - const result = updateSettingsForSource("userSettings", { - effortLevel: undefined - }); - if (result.error) { - return { - message: `Failed to set effort level: ${result.error.message}` - }; - } - logEvent("tengu_effort_command", { - effort: "auto" - }); - const envOverride = getEffortEnvOverride(); - if (envOverride !== undefined && envOverride !== null) { - const envRaw = process.env.CLAUDE_CODE_EFFORT_LEVEL; - return { - message: `Cleared effort from settings, but CLAUDE_CODE_EFFORT_LEVEL=${envRaw} still controls this session`, - effortUpdate: { - value: undefined - } - }; - } - return { - message: "Effort level set to auto", - effortUpdate: { - value: undefined - } - }; -} -function executeEffort(args) { - const normalized = args.toLowerCase(); - if (normalized === "auto" || normalized === "unset") { - return unsetEffortLevel(); - } - if (!isEffortLevel(normalized)) { - return { - message: `Invalid argument: ${args}. Valid options are: low, medium, high, max, auto` - }; - } - return setEffortValue(normalized); -} -function ShowCurrentEffort(t0) { - const { - onDone - } = t0; - const effortValue = useAppState(_temp166); - const model = useMainLoopModel(); - const { - message - } = showCurrentEffort(effortValue, model); - onDone(message); - return null; -} -function _temp166(s4) { - return s4.effortValue; -} -function ApplyEffortAndClose(t0) { - const $2 = import_compiler_runtime276.c(6); - const { - result, - onDone - } = t0; - const setAppState = useSetAppState(); - const { - effortUpdate, - message - } = result; - let t1; - let t22; - if ($2[0] !== effortUpdate || $2[1] !== message || $2[2] !== onDone || $2[3] !== setAppState) { - t1 = () => { - if (effortUpdate) { - setAppState((prev) => ({ - ...prev, - effortValue: effortUpdate.value - })); - } - onDone(message); - }; - t22 = [setAppState, effortUpdate, message, onDone]; - $2[0] = effortUpdate; - $2[1] = message; - $2[2] = onDone; - $2[3] = setAppState; - $2[4] = t1; - $2[5] = t22; - } else { - t1 = $2[4]; - t22 = $2[5]; - } - React110.useEffect(t1, t22); - return null; -} -async function call69(onDone, _context, args) { - args = args?.trim() || ""; - if (COMMON_HELP_ARGS2.includes(args)) { - onDone(`Usage: /effort [low|medium|high|max|auto] - -Effort levels: -- low: Quick, straightforward implementation -- medium: Balanced approach with standard testing -- high: Comprehensive implementation with extensive testing -- max: Maximum capability with deepest reasoning (Opus 4.6 only) -- auto: Use the default effort level for your model`); - return; - } - if (!args || args === "current" || args === "status") { - return /* @__PURE__ */ jsx_dev_runtime357.jsxDEV(ShowCurrentEffort, { - onDone - }, undefined, false, undefined, this); - } - const result = executeEffort(args); - return /* @__PURE__ */ jsx_dev_runtime357.jsxDEV(ApplyEffortAndClose, { - result, - onDone - }, undefined, false, undefined, this); -} -var import_compiler_runtime276, React110, jsx_dev_runtime357, COMMON_HELP_ARGS2; -var init_effort2 = __esm(() => { - init_useMainLoopModel(); - init_analytics(); - init_AppState(); - init_effort(); - init_settings2(); - import_compiler_runtime276 = __toESM(require_compiler_runtime(), 1); - React110 = __toESM(require_react(), 1); - jsx_dev_runtime357 = __toESM(require_jsx_dev_runtime(), 1); - COMMON_HELP_ARGS2 = ["help", "-h", "--help"]; -}); - -// src/commands/effort/index.ts -var effort_default; -var init_effort3 = __esm(() => { - init_immediateCommand(); - effort_default = { - type: "local-jsx", - name: "effort", - description: "Set effort level for model usage", - argumentHint: "[low|medium|high|max|auto]", - get immediate() { - return shouldInferenceConfigCommandBeImmediate(); - }, - load: () => Promise.resolve().then(() => (init_effort2(), exports_effort)) - }; -}); - -// node_modules/asciichart/asciichart.js -var require_asciichart = __commonJS((exports) => { - (function(exports2) { - exports2.black = "\x1B[30m"; - exports2.red = "\x1B[31m"; - exports2.green = "\x1B[32m"; - exports2.yellow = "\x1B[33m"; - exports2.blue = "\x1B[34m"; - exports2.magenta = "\x1B[35m"; - exports2.cyan = "\x1B[36m"; - exports2.lightgray = "\x1B[37m"; - exports2.default = "\x1B[39m"; - exports2.darkgray = "\x1B[90m"; - exports2.lightred = "\x1B[91m"; - exports2.lightgreen = "\x1B[92m"; - exports2.lightyellow = "\x1B[93m"; - exports2.lightblue = "\x1B[94m"; - exports2.lightmagenta = "\x1B[95m"; - exports2.lightcyan = "\x1B[96m"; - exports2.white = "\x1B[97m"; - exports2.reset = "\x1B[0m"; - function colored(char, color3) { - return color3 === undefined ? char : color3 + char + exports2.reset; - } - exports2.colored = colored; - exports2.plot = function(series, cfg = undefined) { - if (typeof series[0] == "number") { - series = [series]; - } - cfg = typeof cfg !== "undefined" ? cfg : {}; - let min = typeof cfg.min !== "undefined" ? cfg.min : series[0][0]; - let max2 = typeof cfg.max !== "undefined" ? cfg.max : series[0][0]; - for (let j4 = 0;j4 < series.length; j4++) { - for (let i6 = 0;i6 < series[j4].length; i6++) { - min = Math.min(min, series[j4][i6]); - max2 = Math.max(max2, series[j4][i6]); - } - } - let defaultSymbols = ["\u253C", "\u2524", "\u2576", "\u2574", "\u2500", "\u2570", "\u256D", "\u256E", "\u256F", "\u2502"]; - let range = Math.abs(max2 - min); - let offset = typeof cfg.offset !== "undefined" ? cfg.offset : 3; - let padding = typeof cfg.padding !== "undefined" ? cfg.padding : " "; - let height2 = typeof cfg.height !== "undefined" ? cfg.height : range; - let colors4 = typeof cfg.colors !== "undefined" ? cfg.colors : []; - let ratio = range !== 0 ? height2 / range : 1; - let min2 = Math.round(min * ratio); - let max22 = Math.round(max2 * ratio); - let rows = Math.abs(max22 - min2); - let width = 0; - for (let i6 = 0;i6 < series.length; i6++) { - width = Math.max(width, series[i6].length); - } - width = width + offset; - let symbols = typeof cfg.symbols !== "undefined" ? cfg.symbols : defaultSymbols; - let format5 = typeof cfg.format !== "undefined" ? cfg.format : function(x4) { - return (padding + x4.toFixed(2)).slice(-padding.length); - }; - let result = new Array(rows + 1); - for (let i6 = 0;i6 <= rows; i6++) { - result[i6] = new Array(width); - for (let j4 = 0;j4 < width; j4++) { - result[i6][j4] = " "; - } - } - for (let y3 = min2;y3 <= max22; ++y3) { - let label = format5(rows > 0 ? max2 - (y3 - min2) * range / rows : y3, y3 - min2); - result[y3 - min2][Math.max(offset - label.length, 0)] = label; - result[y3 - min2][offset - 1] = y3 == 0 ? symbols[0] : symbols[1]; - } - for (let j4 = 0;j4 < series.length; j4++) { - let currentColor = colors4[j4 % colors4.length]; - let y0 = Math.round(series[j4][0] * ratio) - min2; - result[rows - y0][offset - 1] = colored(symbols[0], currentColor); - for (let x4 = 0;x4 < series[j4].length - 1; x4++) { - let y02 = Math.round(series[j4][x4 + 0] * ratio) - min2; - let y1 = Math.round(series[j4][x4 + 1] * ratio) - min2; - if (y02 == y1) { - result[rows - y02][x4 + offset] = colored(symbols[4], currentColor); - } else { - result[rows - y1][x4 + offset] = colored(y02 > y1 ? symbols[5] : symbols[6], currentColor); - result[rows - y02][x4 + offset] = colored(y02 > y1 ? symbols[7] : symbols[8], currentColor); - let from = Math.min(y02, y1); - let to = Math.max(y02, y1); - for (let y3 = from + 1;y3 < to; y3++) { - result[rows - y3][x4 + offset] = colored(symbols[9], currentColor); - } - } - } - } - return result.map(function(x4) { - return x4.join(""); - }).join(` -`); - }; - })(typeof exports === "undefined" ? exports["asciichart"] = {} : exports); -}); - -// src/utils/statsCache.ts -import { randomBytes as randomBytes19 } from "crypto"; -import { open as open16 } from "fs/promises"; -import { join as join136 } from "path"; -async function withStatsCacheLock(fn) { - while (statsCacheLockPromise) { - await statsCacheLockPromise; - } - let releaseLock2; - statsCacheLockPromise = new Promise((resolve42) => { - releaseLock2 = resolve42; - }); - try { - return await fn(); - } finally { - statsCacheLockPromise = null; - releaseLock2?.(); - } -} -function getStatsCachePath() { - return join136(getClaudeConfigHomeDir(), STATS_CACHE_FILENAME); -} -function getEmptyCache() { - return { - version: STATS_CACHE_VERSION, - lastComputedDate: null, - dailyActivity: [], - dailyModelTokens: [], - modelUsage: {}, - totalSessions: 0, - totalMessages: 0, - longestSession: null, - firstSessionDate: null, - hourCounts: {}, - totalSpeculationTimeSavedMs: 0, - shotDistribution: {} - }; -} -function migrateStatsCache(parsed) { - if (typeof parsed.version !== "number" || parsed.version < MIN_MIGRATABLE_VERSION || parsed.version > STATS_CACHE_VERSION) { - return null; - } - if (!Array.isArray(parsed.dailyActivity) || !Array.isArray(parsed.dailyModelTokens) || typeof parsed.totalSessions !== "number" || typeof parsed.totalMessages !== "number") { - return null; - } - return { - version: STATS_CACHE_VERSION, - lastComputedDate: parsed.lastComputedDate ?? null, - dailyActivity: parsed.dailyActivity, - dailyModelTokens: parsed.dailyModelTokens, - modelUsage: parsed.modelUsage ?? {}, - totalSessions: parsed.totalSessions, - totalMessages: parsed.totalMessages, - longestSession: parsed.longestSession ?? null, - firstSessionDate: parsed.firstSessionDate ?? null, - hourCounts: parsed.hourCounts ?? {}, - totalSpeculationTimeSavedMs: parsed.totalSpeculationTimeSavedMs ?? 0, - shotDistribution: parsed.shotDistribution - }; -} -async function loadStatsCache() { - const fs13 = getFsImplementation(); - const cachePath = getStatsCachePath(); - try { - const content = await fs13.readFile(cachePath, { encoding: "utf-8" }); - const parsed = jsonParse(content); - if (parsed.version !== STATS_CACHE_VERSION) { - const migrated = migrateStatsCache(parsed); - if (!migrated) { - logForDebugging(`Stats cache version ${parsed.version} not migratable (expected ${STATS_CACHE_VERSION}), returning empty cache`); - return getEmptyCache(); - } - logForDebugging(`Migrated stats cache from v${parsed.version} to v${STATS_CACHE_VERSION}`); - await saveStatsCache(migrated); - if (false) {} - return migrated; - } - if (!Array.isArray(parsed.dailyActivity) || !Array.isArray(parsed.dailyModelTokens) || typeof parsed.totalSessions !== "number" || typeof parsed.totalMessages !== "number") { - logForDebugging("Stats cache has invalid structure, returning empty cache"); - return getEmptyCache(); - } - if (false) {} - return parsed; - } catch (error46) { - logForDebugging(`Failed to load stats cache: ${errorMessage(error46)}`); - return getEmptyCache(); - } -} -async function saveStatsCache(cache8) { - const fs13 = getFsImplementation(); - const cachePath = getStatsCachePath(); - const tempPath = `${cachePath}.${randomBytes19(8).toString("hex")}.tmp`; - try { - const configDir = getClaudeConfigHomeDir(); - try { - await fs13.mkdir(configDir); - } catch {} - const content = jsonStringify(cache8, null, 2); - const handle = await open16(tempPath, "w", 384); - try { - await handle.writeFile(content, { encoding: "utf-8" }); - await handle.sync(); - } finally { - await handle.close(); - } - await fs13.rename(tempPath, cachePath); - logForDebugging(`Stats cache saved successfully (lastComputedDate: ${cache8.lastComputedDate})`); - } catch (error46) { - logError2(error46); - try { - await fs13.unlink(tempPath); - } catch {} - } -} -function mergeCacheWithNewStats(existingCache, newStats, newLastComputedDate) { - const dailyActivityMap = new Map; - for (const day of existingCache.dailyActivity) { - dailyActivityMap.set(day.date, { ...day }); - } - for (const day of newStats.dailyActivity) { - const existing = dailyActivityMap.get(day.date); - if (existing) { - existing.messageCount += day.messageCount; - existing.sessionCount += day.sessionCount; - existing.toolCallCount += day.toolCallCount; - } else { - dailyActivityMap.set(day.date, { ...day }); - } - } - const dailyModelTokensMap = new Map; - for (const day of existingCache.dailyModelTokens) { - dailyModelTokensMap.set(day.date, { ...day.tokensByModel }); - } - for (const day of newStats.dailyModelTokens) { - const existing = dailyModelTokensMap.get(day.date); - if (existing) { - for (const [model, tokens] of Object.entries(day.tokensByModel)) { - existing[model] = (existing[model] || 0) + tokens; - } - } else { - dailyModelTokensMap.set(day.date, { ...day.tokensByModel }); - } - } - const modelUsage = { ...existingCache.modelUsage }; - for (const [model, usage] of Object.entries(newStats.modelUsage)) { - if (modelUsage[model]) { - modelUsage[model] = { - inputTokens: modelUsage[model].inputTokens + usage.inputTokens, - outputTokens: modelUsage[model].outputTokens + usage.outputTokens, - cacheReadInputTokens: modelUsage[model].cacheReadInputTokens + usage.cacheReadInputTokens, - cacheCreationInputTokens: modelUsage[model].cacheCreationInputTokens + usage.cacheCreationInputTokens, - webSearchRequests: modelUsage[model].webSearchRequests + usage.webSearchRequests, - costUSD: modelUsage[model].costUSD + usage.costUSD, - contextWindow: Math.max(modelUsage[model].contextWindow, usage.contextWindow), - maxOutputTokens: Math.max(modelUsage[model].maxOutputTokens, usage.maxOutputTokens) - }; - } else { - modelUsage[model] = { ...usage }; - } - } - const hourCounts = { ...existingCache.hourCounts }; - for (const [hour, count4] of Object.entries(newStats.hourCounts)) { - const hourNum = parseInt(hour, 10); - hourCounts[hourNum] = (hourCounts[hourNum] || 0) + count4; - } - const totalSessions = existingCache.totalSessions + newStats.sessionStats.length; - const totalMessages = existingCache.totalMessages + newStats.sessionStats.reduce((sum, s4) => sum + s4.messageCount, 0); - let longestSession = existingCache.longestSession; - for (const session2 of newStats.sessionStats) { - if (!longestSession || session2.duration > longestSession.duration) { - longestSession = session2; - } - } - let firstSessionDate = existingCache.firstSessionDate; - for (const session2 of newStats.sessionStats) { - if (!firstSessionDate || session2.timestamp < firstSessionDate) { - firstSessionDate = session2.timestamp; - } - } - const result = { - version: STATS_CACHE_VERSION, - lastComputedDate: newLastComputedDate, - dailyActivity: Array.from(dailyActivityMap.values()).sort((a5, b5) => a5.date.localeCompare(b5.date)), - dailyModelTokens: Array.from(dailyModelTokensMap.entries()).map(([date6, tokensByModel]) => ({ date: date6, tokensByModel })).sort((a5, b5) => a5.date.localeCompare(b5.date)), - modelUsage, - totalSessions, - totalMessages, - longestSession, - firstSessionDate, - hourCounts, - totalSpeculationTimeSavedMs: existingCache.totalSpeculationTimeSavedMs + newStats.totalSpeculationTimeSavedMs - }; - if (false) {} - return result; -} -function toDateString(date6) { - const parts = date6.toISOString().split("T"); - const dateStr = parts[0]; - if (!dateStr) { - throw new Error("Invalid ISO date string"); - } - return dateStr; -} -function getTodayDateString() { - return toDateString(new Date); -} -function getYesterdayDateString() { - const yesterday = new Date; - yesterday.setDate(yesterday.getDate() - 1); - return toDateString(yesterday); -} -function isDateBefore(date1, date22) { - return date1 < date22; -} -var STATS_CACHE_VERSION = 3, MIN_MIGRATABLE_VERSION = 1, STATS_CACHE_FILENAME = "stats-cache.json", statsCacheLockPromise = null; -var init_statsCache = __esm(() => { - init_debug(); - init_envUtils(); - init_errors(); - init_fsOperations(); - init_log2(); - init_slowOperations(); -}); - -// src/utils/heatmap.ts -function calculatePercentiles(dailyActivity) { - const counts = dailyActivity.map((a5) => a5.messageCount).filter((c9) => c9 > 0).sort((a5, b5) => a5 - b5); - if (counts.length === 0) - return null; - return { - p25: counts[Math.floor(counts.length * 0.25)], - p50: counts[Math.floor(counts.length * 0.5)], - p75: counts[Math.floor(counts.length * 0.75)] - }; -} -function generateHeatmap(dailyActivity, options2 = {}) { - const { terminalWidth = 80, showMonthLabels = true } = options2; - const dayLabelWidth = 4; - const availableWidth = terminalWidth - dayLabelWidth; - const width = Math.min(52, Math.max(10, availableWidth)); - const activityMap = new Map; - for (const activity of dailyActivity) { - activityMap.set(activity.date, activity); - } - const percentiles = calculatePercentiles(dailyActivity); - const today = new Date; - today.setHours(0, 0, 0, 0); - const currentWeekStart = new Date(today); - currentWeekStart.setDate(today.getDate() - today.getDay()); - const startDate = new Date(currentWeekStart); - startDate.setDate(startDate.getDate() - (width - 1) * 7); - const grid = Array.from({ length: 7 }, () => Array(width).fill("")); - const monthStarts = []; - let lastMonth = -1; - const currentDate = new Date(startDate); - for (let week = 0;week < width; week++) { - for (let day = 0;day < 7; day++) { - if (currentDate > today) { - grid[day][week] = " "; - currentDate.setDate(currentDate.getDate() + 1); - continue; - } - const dateStr = toDateString(currentDate); - const activity = activityMap.get(dateStr); - if (day === 0) { - const month = currentDate.getMonth(); - if (month !== lastMonth) { - monthStarts.push({ month, week }); - lastMonth = month; - } - } - const intensity = getIntensity(activity?.messageCount || 0, percentiles); - grid[day][week] = getHeatmapChar(intensity); - currentDate.setDate(currentDate.getDate() + 1); - } - } - const lines2 = []; - if (showMonthLabels) { - const monthNames = [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec" - ]; - const uniqueMonths = monthStarts.map((m4) => m4.month); - const labelWidth = Math.floor(width / Math.max(uniqueMonths.length, 1)); - const monthLabels = uniqueMonths.map((month) => monthNames[month].padEnd(labelWidth)).join(""); - lines2.push(" " + monthLabels); - } - const dayLabels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - for (let day = 0;day < 7; day++) { - const label = [1, 3, 5].includes(day) ? dayLabels[day].padEnd(3) : " "; - const row = label + " " + grid[day].join(""); - lines2.push(row); - } - lines2.push(""); - lines2.push(" Less " + [ - claudeOrange("\u2591"), - claudeOrange("\u2592"), - claudeOrange("\u2593"), - claudeOrange("\u2588") - ].join(" ") + " More"); - return lines2.join(` -`); -} -function getIntensity(messageCount, percentiles) { - if (messageCount === 0 || !percentiles) - return 0; - if (messageCount >= percentiles.p75) - return 4; - if (messageCount >= percentiles.p50) - return 3; - if (messageCount >= percentiles.p25) - return 2; - return 1; -} -function getHeatmapChar(intensity) { - switch (intensity) { - case 0: - return source_default.gray("\xB7"); - case 1: - return claudeOrange("\u2591"); - case 2: - return claudeOrange("\u2592"); - case 3: - return claudeOrange("\u2593"); - case 4: - return claudeOrange("\u2588"); - default: - return source_default.gray("\xB7"); - } -} -var claudeOrange; -var init_heatmap = __esm(() => { - init_source(); - init_statsCache(); - claudeOrange = source_default.hex("#da7756"); -}); - -// src/utils/ansiToSvg.ts -function parseAnsi(text) { - const lines2 = []; - const rawLines = text.split(` -`); - for (const line of rawLines) { - const spans = []; - let currentColor = DEFAULT_FG; - let bold2 = false; - let i6 = 0; - while (i6 < line.length) { - if (line[i6] === "\x1B" && line[i6 + 1] === "[") { - let j4 = i6 + 2; - while (j4 < line.length && !/[A-Za-z]/.test(line[j4])) { - j4++; - } - if (line[j4] === "m") { - const codes = line.slice(i6 + 2, j4).split(";").map(Number); - let k4 = 0; - while (k4 < codes.length) { - const code = codes[k4]; - if (code === 0) { - currentColor = DEFAULT_FG; - bold2 = false; - } else if (code === 1) { - bold2 = true; - } else if (code >= 30 && code <= 37) { - currentColor = ANSI_COLORS[code] || DEFAULT_FG; - } else if (code >= 90 && code <= 97) { - currentColor = ANSI_COLORS[code] || DEFAULT_FG; - } else if (code === 39) { - currentColor = DEFAULT_FG; - } else if (code === 38) { - if (codes[k4 + 1] === 5 && codes[k4 + 2] !== undefined) { - const colorIndex2 = codes[k4 + 2]; - currentColor = get256Color(colorIndex2); - k4 += 2; - } else if (codes[k4 + 1] === 2 && codes[k4 + 2] !== undefined && codes[k4 + 3] !== undefined && codes[k4 + 4] !== undefined) { - currentColor = { - r: codes[k4 + 2], - g: codes[k4 + 3], - b: codes[k4 + 4] - }; - k4 += 4; - } - } - k4++; - } - } - i6 = j4 + 1; - continue; - } - const textStart = i6; - while (i6 < line.length && line[i6] !== "\x1B") { - i6++; - } - const spanText = line.slice(textStart, i6); - if (spanText) { - spans.push({ text: spanText, color: currentColor, bold: bold2 }); - } - } - if (spans.length === 0) { - spans.push({ text: "", color: DEFAULT_FG, bold: false }); - } - lines2.push(spans); - } - return lines2; -} -function get256Color(index2) { - if (index2 < 16) { - const standardColors = [ - { r: 0, g: 0, b: 0 }, - { r: 128, g: 0, b: 0 }, - { r: 0, g: 128, b: 0 }, - { r: 128, g: 128, b: 0 }, - { r: 0, g: 0, b: 128 }, - { r: 128, g: 0, b: 128 }, - { r: 0, g: 128, b: 128 }, - { r: 192, g: 192, b: 192 }, - { r: 128, g: 128, b: 128 }, - { r: 255, g: 0, b: 0 }, - { r: 0, g: 255, b: 0 }, - { r: 255, g: 255, b: 0 }, - { r: 0, g: 0, b: 255 }, - { r: 255, g: 0, b: 255 }, - { r: 0, g: 255, b: 255 }, - { r: 255, g: 255, b: 255 } - ]; - return standardColors[index2] || DEFAULT_FG; - } - if (index2 < 232) { - const i6 = index2 - 16; - const r4 = Math.floor(i6 / 36); - const g4 = Math.floor(i6 % 36 / 6); - const b5 = i6 % 6; - return { - r: r4 === 0 ? 0 : 55 + r4 * 40, - g: g4 === 0 ? 0 : 55 + g4 * 40, - b: b5 === 0 ? 0 : 55 + b5 * 40 - }; - } - const gray2 = (index2 - 232) * 10 + 8; - return { r: gray2, g: gray2, b: gray2 }; -} -var ANSI_COLORS, DEFAULT_FG, DEFAULT_BG; -var init_ansiToSvg = __esm(() => { - ANSI_COLORS = { - 30: { r: 0, g: 0, b: 0 }, - 31: { r: 205, g: 49, b: 49 }, - 32: { r: 13, g: 188, b: 121 }, - 33: { r: 229, g: 229, b: 16 }, - 34: { r: 36, g: 114, b: 200 }, - 35: { r: 188, g: 63, b: 188 }, - 36: { r: 17, g: 168, b: 205 }, - 37: { r: 229, g: 229, b: 229 }, - 90: { r: 102, g: 102, b: 102 }, - 91: { r: 241, g: 76, b: 76 }, - 92: { r: 35, g: 209, b: 139 }, - 93: { r: 245, g: 245, b: 67 }, - 94: { r: 59, g: 142, b: 234 }, - 95: { r: 214, g: 112, b: 214 }, - 96: { r: 41, g: 184, b: 219 }, - 97: { r: 255, g: 255, b: 255 } - }; - DEFAULT_FG = { r: 229, g: 229, b: 229 }; - DEFAULT_BG = { r: 30, g: 30, b: 30 }; -}); - -// src/utils/ansiToPng.ts -import { deflateSync as deflateSync2 } from "zlib"; -function makeFallbackGlyph() { - const g4 = new Uint8Array(GLYPH_BYTES); - for (let y3 = 2;y3 < GLYPH_H - 4; y3++) { - for (let x4 = 1;x4 < GLYPH_W - 1; x4++) { - const onBorder = y3 === 2 || y3 === GLYPH_H - 5 || x4 === 1 || x4 === GLYPH_W - 2; - if (onBorder && (x4 + y3) % 2 === 0) - g4[y3 * GLYPH_W + x4] = 255; - } - } - return g4; -} -function decodeFont() { - const buf = Buffer.from(FONT_B64, "base64"); - const count4 = buf.readUInt16LE(0); - const map8 = new Map; - let off = 2; - for (let i6 = 0;i6 < count4; i6++) { - const cp = buf.readUInt32LE(off); - off += 4; - map8.set(cp, buf.subarray(off, off + GLYPH_BYTES)); - off += GLYPH_BYTES; - } - return map8; -} -function ansiToPng(ansiText, options2 = {}) { - const { - scale = 1, - paddingX = 48, - paddingY = 48, - borderRadius = 16, - background = DEFAULT_BG - } = options2; - const lines2 = parseAnsi(ansiText); - while (lines2.length > 0 && lines2[lines2.length - 1].every((span) => span.text.trim() === "")) { - lines2.pop(); - } - if (lines2.length === 0) { - lines2.push([{ text: "", color: background, bold: false }]); - } - const cols = Math.max(1, ...lines2.map(lineWidthCells)); - const rows = lines2.length; - const width = (cols * GLYPH_W + paddingX * 2) * scale; - const height2 = (rows * GLYPH_H + paddingY * 2) * scale; - const px = new Uint8Array(width * height2 * 4); - fillBackground(px, background); - if (borderRadius > 0) { - roundCorners(px, width, height2, borderRadius * scale); - } - const padX = paddingX * scale; - const padY = paddingY * scale; - for (let row = 0;row < rows; row++) { - let col = 0; - for (const span of lines2[row]) { - for (const ch2 of span.text) { - const cp = ch2.codePointAt(0); - const cellW = stringWidth(ch2); - if (cellW === 0) - continue; - const x4 = padX + col * GLYPH_W * scale; - const y3 = padY + row * GLYPH_H * scale; - const shade = SHADE_ALPHA[cp]; - if (shade !== undefined) { - blitShade(px, width, x4, y3, span.color, background, shade, scale); - } else { - const glyph = FONT.get(cp) ?? FALLBACK_GLYPH; - blitGlyph(px, width, x4, y3, glyph, span.color, span.bold, scale); - } - col += cellW; - } - } - } - return encodePng(px, width, height2); -} -function lineWidthCells(line) { - let w2 = 0; - for (const span of line) - w2 += stringWidth(span.text); - return w2; -} -function fillBackground(px, bg) { - for (let i6 = 0;i6 < px.length; i6 += 4) { - px[i6] = bg.r; - px[i6 + 1] = bg.g; - px[i6 + 2] = bg.b; - px[i6 + 3] = 255; - } -} -function blitShade(px, width, x4, y3, fg, bg, alpha, scale) { - const r4 = Math.round(fg.r * alpha + bg.r * (1 - alpha)); - const g4 = Math.round(fg.g * alpha + bg.g * (1 - alpha)); - const b5 = Math.round(fg.b * alpha + bg.b * (1 - alpha)); - const cellW = GLYPH_W * scale; - const cellH = GLYPH_H * scale; - for (let dy = 0;dy < cellH; dy++) { - const rowBase = ((y3 + dy) * width + x4) * 4; - for (let dx = 0;dx < cellW; dx++) { - const i6 = rowBase + dx * 4; - px[i6] = r4; - px[i6 + 1] = g4; - px[i6 + 2] = b5; - } - } -} -function blitGlyph(px, width, x4, y3, glyph, color3, bold2, scale) { - for (let gy = 0;gy < GLYPH_H; gy++) { - for (let gx = 0;gx < GLYPH_W; gx++) { - let a5 = glyph[gy * GLYPH_W + gx]; - if (a5 === 0) - continue; - if (bold2) - a5 = Math.min(255, a5 * 1.4); - const inv = 255 - a5; - for (let sy = 0;sy < scale; sy++) { - const rowBase = ((y3 + gy * scale + sy) * width + x4 + gx * scale) * 4; - for (let sx = 0;sx < scale; sx++) { - const i6 = rowBase + sx * 4; - px[i6] = color3.r * a5 + px[i6] * inv >> 8; - px[i6 + 1] = color3.g * a5 + px[i6 + 1] * inv >> 8; - px[i6 + 2] = color3.b * a5 + px[i6 + 2] * inv >> 8; - } - } - } - } -} -function roundCorners(px, width, height2, r4) { - const r22 = r4 * r4; - for (let dy = 0;dy < r4; dy++) { - for (let dx = 0;dx < r4; dx++) { - const ox = r4 - dx - 0.5; - const oy = r4 - dy - 0.5; - if (ox * ox + oy * oy <= r22) - continue; - px[(dy * width + dx) * 4 + 3] = 0; - px[(dy * width + (width - 1 - dx)) * 4 + 3] = 0; - px[((height2 - 1 - dy) * width + dx) * 4 + 3] = 0; - px[((height2 - 1 - dy) * width + (width - 1 - dx)) * 4 + 3] = 0; - } - } -} -function makeCrcTable() { - const t4 = new Uint32Array(256); - for (let n6 = 0;n6 < 256; n6++) { - let c9 = n6; - for (let k4 = 0;k4 < 8; k4++) { - c9 = c9 & 1 ? 3988292384 ^ c9 >>> 1 : c9 >>> 1; - } - t4[n6] = c9 >>> 0; - } - return t4; -} -function crc32(data) { - let c9 = 4294967295; - for (let i6 = 0;i6 < data.length; i6++) { - c9 = CRC_TABLE[(c9 ^ data[i6]) & 255] ^ c9 >>> 8; - } - return (c9 ^ 4294967295) >>> 0; -} -function chunk(type, data) { - const body = Buffer.alloc(4 + data.length); - body.write(type, 0, "ascii"); - body.set(data, 4); - const out = Buffer.alloc(12 + data.length); - out.writeUInt32BE(data.length, 0); - body.copy(out, 4); - out.writeUInt32BE(crc32(body), 8 + data.length); - return out; -} -function encodePng(px, width, height2) { - const ihdr = Buffer.alloc(13); - ihdr.writeUInt32BE(width, 0); - ihdr.writeUInt32BE(height2, 4); - ihdr[8] = 8; - ihdr[9] = 6; - ihdr[10] = 0; - ihdr[11] = 0; - ihdr[12] = 0; - const stride = width * 4; - const raw = Buffer.alloc(height2 * (stride + 1)); - for (let y3 = 0;y3 < height2; y3++) { - const dst = y3 * (stride + 1); - raw[dst] = 0; - raw.set(px.subarray(y3 * stride, (y3 + 1) * stride), dst + 1); - } - const idat = deflateSync2(raw); - return Buffer.concat([ - PNG_SIG, - chunk("IHDR", ihdr), - chunk("IDAT", idat), - chunk("IEND", new Uint8Array(0)) - ]); -} -var GLYPH_W = 24, GLYPH_H = 48, GLYPH_BYTES, FONT_B64 = "hQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwQEBAEAAAAAAAAAAAAAAAAAAAAAAAAAC/////EAAAAAAAAAAAAAAAAAAAAAAAAAC/////AAAAAAAAAAAAAAAAAAAAAAAAAAC/////AAAAAAAAAAAAAAAAAAAAAAAAAAC/////AAAAAAAAAAAAAAAAAAAAAAAAAACP////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA///vAAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAABw//+/AAAAAAAAAAAAAAAAAAAAAAAAAABA//+/AAAAAAAAAAAAAAAAAAAAAAAAAABA//+/AAAAAAAAAAAAAAAAAAAAAAAAAAAwv7+PAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABg7/+/EAAAAAAAAAAAAAAAAAAAAAAAADD/////vwAAAAAAAAAAAAAAAAAAAAAAAID//////wAAAAAAAAAAAAAAAAAAAAAAAGD/////7wAAAAAAAAAAAAAAAAAAAAAAAADP////YAAAAAAAAAAAAAAAAAAAAAAAAAAAYIAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQQEBAQAAAIEBAQEAAAAAAAAAAAAAAAABA/////wAAUP///88AAAAAAAAAAAAAAABA/////wAAQP///78AAAAAAAAAAAAAAAAg////3wAAQP///78AAAAAAAAAAAAAAAAA////vwAAQP///78AAAAAAAAAAAAAAAAA////vwAAIP///48AAAAAAAAAAAAAAAAA////vwAAAP///4AAAAAAAAAAAAAAAAAA3///nwAAAP///4AAAAAAAAAAAAAAAAAAv///gAAAAP///4AAAAAAAAAAAAAAAAAAv///gAAAAO///1AAAAAAAAAAAAAAAAAAv///gAAAAL///0AAAAAAAAAAAAAAAAAAMEBAIAAAADBAQBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwQEAQAAAAAAAwQEAAAAAAAAAAAAAAAADP//8gAAAAAAD///8AAAAAAAAAAAAAAAD///8AAAAAAAD//98AAAAAAAAAAAAAABD//88AAAAAAED//78AAAAAAAAAAAAAAED//78AAAAAAED//48AAAAAAAAAAAAAAGD//4AAAAAAAID//4AAAAAAAAAAAAAAAID//3AAAAAAAI///0AAAAAAAAAAIICAgL///5+AgICAgN///5+AgEAAAAAAQP///////////////////////4AAAAAAQP///////////////////////4AAAAAAEEBAQP//30BAQEBAYP//z0BAQCAAAAAAAAAAMP//vwAAAAAAQP//rwAAAAAAAAAAAAAAQP//nwAAAAAAYP//gAAAAAAAAAAAAAAAcP//gAAAAAAAgP//YAAAAAAAAAAAAAAAgP//UAAAAAAAr///QAAAAAAAAAAAAAAAv///QAAAAAAAv///IAAAAAAAAAAAAAAAz///EAAAAAAA////AAAAAAAAAAAAAAAA////AAAAAAAQ///PAAAAAAAAAAAAAAAg//+/AAAAAABA//+/AAAAAAAAAABggICf///fgICAgICf///PgICAAAAAAAC/////////////////////////AAAAAAC/////////////////////////AAAAAAAAAACv//9AAAAAAAC///8wAAAAAAAAAAAAAAC///8wAAAAAADf//8AAAAAAAAAAAAAAADv//8AAAAAAAD//+8AAAAAAAAAAAAAAAD//+8AAAAAACD//78AAAAAAAAAAAAAAED//78AAAAAAED//68AAAAAAAAAAAAAAED//58AAAAAAHD//4AAAAAAAAAAAAAAAID//4AAAAAAAID//3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYL+/MAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAFCAz///n3AwAAAAAAAAAAAAAAAAABCA7///////////34AQAAAAAAAAAAAAEM/////////////////fUAAAAAAAAAAAz////++Pn///cIDf/////3AAAAAAAABg////rxAAgP//QAAAQN//zxAAAAAAAADP///vEAAAgP//QAAAABCfEAAAAAAAAAD///+fAAAAgP//QAAAAAAAAAAAAAAAAAD///+AAAAAgP//QAAAAAAAAAAAAAAAAAD///+/AAAAgP//QAAAAAAAAAAAAAAAAADP////MAAAgP//QAAAAAAAAAAAAAAAAABg////70AAgP//QAAAAAAAAAAAAAAAAAAAn/////+/r///QAAAAAAAAAAAAAAAAAAAAJ//////////cAAAAAAAAAAAAAAAAAAAAABQ3////////++AEAAAAAAAAAAAAAAAAAAAEGDf////////73AAAAAAAAAAAAAAAAAAAAAAj/////////+fAAAAAAAAAAAAAAAAAAAAgP//gL//////jwAAAAAAAAAAAAAAAAAAgP//QABw/////0AAAAAAAAAAAAAAAAAAgP//QAAAcP///58AAAAAAAAAAAAAAAAAgP//QAAAAO///+8AAAAAAAAAAAAAAAAAgP//QAAAAL////8AAAAAAAAAAAAAAAAAgP//QAAAAL////8AAAAAAAAAAAAAAAAAgP//QAAAAL////8AAAAAAABgMAAAAAAAgP//QAAAEP///68AAAAAADDv71AAAAAAgP//QAAAn////2AAAAAAAN////+vIAAAgP//QCCv////zwAAAAAAADDf/////8+Pv///z//////vIAAAAAAAAAAQj////////////////88gAAAAAAAAAAAAACCf7//////////PYAAAAAAAAAAAAAAAAAAAADBQv///cBAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//QAAAAAAAAAAAAAAAAAAAAAAAAAAAIEBAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQI+/r4AgAAAAAAAAAAAAAK+AAAAAABC/////////cAAAAAAAAAAAUP//nwAAAM////+/3////3AAAAAAAAAQ7///MAAAgP//7zAAAGD//+8QAAAAAACv//+AAAAA3///YAAAAACv//9wAAAAAGD//88AAAAg////AAAAAACA//+/AAAAIO//7zAAAABA////AAAAAABA//+/AAAAv///cAAAAABA////AAAAAABQ//+/AABw//+/AAAAAAAQ////EAAAAACA//+vACDv/+8gAAAAAAAAz///gAAAAADP//9gAL///3AAAAAAAAAAUP//71AAEJ///98AgP//rwAAAAAAAAAAAJ///////////0Aw///vEAAAAAAAAAAAAACA///////fQADP//9QAAAAAAAAAAAAAAAAEGCAgEAAAID//68AAAAAAAAAAAAAAAAAAAAAAAAAMP//7xAAAAAAAAAAAAAAAAAAAAAAAAAQz///QAAAAAAAAAAAAAAAAAAAAAAAAACP//+PABCAz///v2AAAAAAAAAAAAAAAED//98QMO/////////PEAAAAAAAAAAAEN///0AQ3///34+P7///rwAAAAAAAAAAj///jwCA///PEAAAMO///0AAAAAAAABA///PAADf//9QAAAAAI///58AAAAAABDv//8wABD///8AAAAAAFD//78AAAAAAK///4AAAED///8AAAAAAED///8AAAAAUP//zwAAACD///8AAAAAAED//88AAAAQ7//vMAAAAADv//9AAAAAAID//68AAACv//9wAAAAAACf//+vAAAAAN///2AAAHD//78AAAAAAAAg7///r0BAv///zwAAIO//7yAAAAAAAAAAYP/////////vMAAAYP//cAAAAAAAAAAAAEC//////68gAAAAADCAAAAAAAAAAAAAAAAAIEBAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwgI+/j3AwAAAAAAAAAAAAAAAAAAAAQM//////////z0AAAAAAAAAAAAAAAABg//////////////9gAAAAAAAAAAAAADD////PQAAAAFC////vEAAAAAAAAAAAAL///88QAAAAAAAAn+8wAAAAAAAAAAAAIP///1AAAAAAAAAAACAAAAAAAAAAAAAAQP///xAAAAAAAAAAAAAAAAAAAAAAAAAAQP///xAAAAAAAAAAAAAAAAAAAAAAAAAAIP///1AAAAAAAAAAAAAAAAAAAAAAAAAAAN///88AAAAAAAAAAAAAAAAAAAAAAAAAAFD///+fEAAAAAAAAAAAAAAAAAAAAAAAAACP////33BAQEBAQEBAQEBAQEAgAAAAAAAAQK////////////////////+AAAAAAAAAII/P//////////////////+AAAAAABCf////z4+AgICAgJ///9+AgIBAAAAAEM///+9AAAAAAAAAAED//78AAAAAAAAAn///7zAAAAAAAAAAAED//78AAAAAAAAg////cAAAAAAAAAAAAED//78AAAAAAACA////EAAAAAAAAAAAAED//78AAAAAAAC///+/AAAAAAAAAAAAAED//78AAAAAAAC///+AAAAAAAAAAAAAAED//78AAAAAAAC///+PAAAAAAAAAAAAAED//78AAAAAAACv//+/AAAAAAAAAAAAAED//78AAAAAAABw////IAAAAAAAAAAAAED//78AAAAAAAAg////rwAAAAAAAAAAAGD//78AAAAAAAAAn////58AAAAAAAAAcO///78AAAAAAAAAEM/////fj2BAYI/f////7zAAAAAAAAAAABDP///////////////PIAAAAAAAAAAAAAAAgN//////////z2AAAAAAAAAAAAAAAAAAAAAwUICAgEAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwQEBAIAAAAAAAAAAAAAAAAAAAAAAAAAC/////gAAAAAAAAAAAAAAAAAAAAAAAAAC/////UAAAAAAAAAAAAAAAAAAAAAAAAAC/////QAAAAAAAAAAAAAAAAAAAAAAAAACf////QAAAAAAAAAAAAAAAAAAAAAAAAACA////QAAAAAAAAAAAAAAAAAAAAAAAAACA////EAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAABg////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA///fAAAAAAAAAAAAAAAAAAAAAAAAAAAQQEAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABCv/2AAAAAAAAAAAAAAAAAAAAAAAAAAEM///+8QAAAAAAAAAAAAAAAAAAAAAAAQz///7zAAAAAAAAAAAAAAAAAAAAAAABDP///vIAAAAAAAAAAAAAAAAAAAAAAAAM///+8wAAAAAAAAAAAAAAAAAAAAAAAAn///7zAAAAAAAAAAAAAAAAAAAAAAAABQ////YAAAAAAAAAAAAAAAAAAAAAAAABDv//+vAAAAAAAAAAAAAAAAAAAAAAAAAJ///+8QAAAAAAAAAAAAAAAAAAAAAAAAIP///4AAAAAAAAAAAAAAAAAAAAAAAAAAj///7xAAAAAAAAAAAAAAAAAAAAAAAAAA7///nwAAAAAAAAAAAAAAAAAAAAAAAABA////UAAAAAAAAAAAAAAAAAAAAAAAAACA////EAAAAAAAAAAAAAAAAAAAAAAAAAC////PAAAAAAAAAAAAAAAAAAAAAAAAAADv//+/AAAAAAAAAAAAAAAAAAAAAAAAAAD///+AAAAAAAAAAAAAAAAAAAAAAAAAACD///+AAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAADD///+AAAAAAAAAAAAAAAAAAAAAAAAAAAD///+AAAAAAAAAAAAAAAAAAAAAAAAAAAD///+vAAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAACP////AAAAAAAAAAAAAAAAAAAAAAAAAABg////QAAAAAAAAAAAAAAAAAAAAAAAAAAQ////jwAAAAAAAAAAAAAAAAAAAAAAAAAAr///3wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///2AAAAAAAAAAAAAAAAAAAAAAAAAAAL///98AAAAAAAAAAAAAAAAAAAAAAAAAADD///+AAAAAAAAAAAAAAAAAAAAAAAAAAACP////MAAAAAAAAAAAAAAAAAAAAAAAAAAAz///3xAAAAAAAAAAAAAAAAAAAAAAAAAAIO///88QAAAAAAAAAAAAAAAAAAAAAAAAADDv//+fAAAAAAAAAAAAAAAAAAAAAAAAAAAw7///nwAAAAAAAAAAAAAAAAAAAAAAAAAAMO///88QAAAAAAAAAAAAAAAAAAAAAAAAADDv/58AAAAAAAAAAAAAAAAAAAAAAAAAAAAQgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwEAAAAAAAAAAAAAAAAAAAAAAAAAAAABDv7zAAAAAAAAAAAAAAAAAAAAAAAAAAAJ///+8wAAAAAAAAAAAAAAAAAAAAAAAAAACf///vMAAAAAAAAAAAAAAAAAAAAAAAAAAAn///7zAAAAAAAAAAAAAAAAAAAAAAAAAAAK///+8wAAAAAAAAAAAAAAAAAAAAAAAAABDP///fEAAAAAAAAAAAAAAAAAAAAAAAAAAg7///rwAAAAAAAAAAAAAAAAAAAAAAAAAAUP///1AAAAAAAAAAAAAAAAAAAAAAAAAAAL///98AAAAAAAAAAAAAAAAAAAAAAAAAACD///9gAAAAAAAAAAAAAAAAAAAAAAAAAACv///fAAAAAAAAAAAAAAAAAAAAAAAAAABQ////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////jwAAAAAAAAAAAAAAAAAAAAAAAAAAv///zwAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAYP///0AAAAAAAAAAAAAAAAAAAAAAAAAAQP///1AAAAAAAAAAAAAAAAAAAAAAAAAAQP///4AAAAAAAAAAAAAAAAAAAAAAAAAAIP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAEP///4AAAAAAAAAAAAAAAAAAAAAAAAAAQP///4AAAAAAAAAAAAAAAAAAAAAAAAAAQP///2AAAAAAAAAAAAAAAAAAAAAAAAAAUP///0AAAAAAAAAAAAAAAAAAAAAAAAAAgP///yAAAAAAAAAAAAAAAAAAAAAAAAAAr///7wAAAAAAAAAAAAAAAAAAAAAAAAAA7///rwAAAAAAAAAAAAAAAAAAAAAAAAAw////YAAAAAAAAAAAAAAAAAAAAAAAAACf///vEAAAAAAAAAAAAAAAAAAAAAAAABDv//+PAAAAAAAAAAAAAAAAAAAAAAAAAI///+8gAAAAAAAAAAAAAAAAAAAAAAAAMP///4AAAAAAAAAAAAAAAAAAAAAAAAAQz///zwAAAAAAAAAAAAAAAAAAAAAAAACf///vMAAAAAAAAAAAAAAAAAAAAAAAAHD///9gAAAAAAAAAAAAAAAAAAAAAAAAYP///2AAAAAAAAAAAAAAAAAAAAAAAABg////jwAAAAAAAAAAAAAAAAAAAAAAAGD///9wAAAAAAAAAAAAAAAAAAAAAAAAAGD//2AAAAAAAAAAAAAAAAAAAAAAAAAAAABgQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgv7+/AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAABQ////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAABAAAAAAAABA///vAAAAAAAAAAAAAAAAMP+vUAAAAABA//+/AAAAACBwz88AAAAAj////++fQABA//+/ABBgv/////8gAAAAz////////9+v///fr/////////9wAAAAMIDP///////////////////vr2AQAAAAAAAAEGCv7//////////fj0AAAAAAAAAAAAAAAAAAAHD/////3yAAAAAAAAAAAAAAAAAAAAAAEN///////48AAAAAAAAAAAAAAAAAAAAAr///74D///9QAAAAAAAAAAAAAAAAAACA////UAC////vMAAAAAAAAAAAAAAAAED///+vAAAg7///zxAAAAAAAAAAAAAAEO///+8QAAAAUP///58AAAAAAAAAAAAAz////1AAAAAAAK////9gAAAAAAAAAAAAcO//jwAAAAAAABDv/88wAAAAAAAAAAAAADCvEAAAAAAAAABQjxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIICAYAAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAABBAQEBAQEBAcP//z0BAQEBAQEBAAAAAAED/////////////////////////AAAAAED/////////////////////////AAAAADC/v7+/v7+/z///77+/v7+/v7+/AAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAML+/jwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAECvv48QAAAAAAAAAAAAAAAAAAAAAAAAQP/////PEAAAAAAAAAAAAAAAAAAAAAAAz///////cAAAAAAAAAAAAAAAAAAAAAAA////////jwAAAAAAAAAAAAAAAAAAAAAA3///////gAAAAAAAAAAAAAAAAAAAAAAAYP//////UAAAAAAAAAAAAAAAAAAAAAAAAL/////vAAAAAAAAAAAAAAAAAAAAAAAAAO////+AAAAAAAAAAAAAAAAAAAAAAAAAMP////8QAAAAAAAAAAAAAAAAAAAAAAAAcP///58AAAAAAAAAAAAAAAAAAAAAAAAAr////zAAAAAAAAAAAAAAAAAAAAAAAAAA7///vwAAAAAAAAAAAAAAAAAAAAAAAAAw////YAAAAAAAAAAAAAAAAAAAAAAAAABg///fAAAAAAAAAAAAAAAAAAAAAAAAAAAgQEAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAIAAAAAAAAAD/////////////////////gAAAAAAAAAD/////////////////////gAAAAAAAAAC/v7+/v7+/v7+/v7+/v7+/YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUK+/jxAAAAAAAAAAAAAAAAAAAAAAAABg/////+8gAAAAAAAAAAAAAAAAAAAAABD///////+fAAAAAAAAAAAAAAAAAAAAAED////////fAAAAAAAAAAAAAAAAAAAAAED////////PAAAAAAAAAAAAAAAAAAAAAADv//////+AAAAAAAAAAAAAAAAAAAAAAAAw7////78AAAAAAAAAAAAAAAAAAAAAAAAAEGCAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/fYAAAAAAAAAAAAAAAAAAAAAAAAAAAIP///0AAAAAAAAAAAAAAAAAAAAAAAAAAn///vwAAAAAAAAAAAAAAAAAAAAAAAAAg////YAAAAAAAAAAAAAAAAAAAAAAAAACf///fAAAAAAAAAAAAAAAAAAAAAAAAABDv//9gAAAAAAAAAAAAAAAAAAAAAAAAAID//98AAAAAAAAAAAAAAAAAAAAAAAAAEO///2AAAAAAAAAAAAAAAAAAAAAAAAAAgP//3wAAAAAAAAAAAAAAAAAAAAAAAAAQ7///YAAAAAAAAAAAAAAAAAAAAAAAAACA///fAAAAAAAAAAAAAAAAAAAAAAAAABDv//9gAAAAAAAAAAAAAAAAAAAAAAAAAID//+8QAAAAAAAAAAAAAAAAAAAAAAAAAO///4AAAAAAAAAAAAAAAAAAAAAAAAAAYP//7xAAAAAAAAAAAAAAAAAAAAAAAAAA3///gAAAAAAAAAAAAAAAAAAAAAAAAABg///vEAAAAAAAAAAAAAAAAAAAAAAAAADf//+AAAAAAAAAAAAAAAAAAAAAAAAAAGD//+8QAAAAAAAAAAAAAAAAAAAAAAAAAN///4AAAAAAAAAAAAAAAAAAAAAAAAAAYP///xAAAAAAAAAAAAAAAAAAAAAAAAAA3///nwAAAAAAAAAAAAAAAAAAAAAAAABA////IAAAAAAAAAAAAAAAAAAAAAAAAAC///+fAAAAAAAAAAAAAAAAAAAAAAAAAED///8gAAAAAAAAAAAAAAAAAAAAAAAAAL///58AAAAAAAAAAAAAAAAAAAAAAAAAQP///yAAAAAAAAAAAAAAAAAAAAAAAAAAv///nwAAAAAAAAAAAAAAAAAAAAAAAABA////IAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAACD///9AAAAAAAAAAAAAAAAAAAAAAAAAAJ///78AAAAAAAAAAAAAAAAAAAAAAAAAIP///0AAAAAAAAAAAAAAAAAAAAAAAAAAn///vwAAAAAAAAAAAAAAAAAAAAAAAAAg////QAAAAAAAAAAAAAAAAAAAAAAAAACf//+/AAAAAAAAAAAAAAAAAAAAAAAAAAAgn+9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAECAv7+fcCAAAAAAAAAAAAAAAAAAAABA3/////////+fEAAAAAAAAAAAAAAAAGD/////////////zxAAAAAAAAAAAAAAMP///++AMABAj////88AAAAAAAAAAAAAz///7zAAAAAAAGD///+AAAAAAAAAAABg////cAAAAAAAAED////vAAAAAAAAAACv///fAAAAAAAAAL//////YAAAAAAAABD///+PAAAAAAAAQP//3///rwAAAAAAAFD///9AAAAAAAAAv/+fj///7wAAAAAAAID///8QAAAAAABA//8gcP///yAAAAAAAK////8AAAAAAAC//78AQP///0AAAAAAAL///88AAAAAAED//0AAQP///3AAAAAAAM///78AAAAAAL//vwAAIP///4AAAAAAAP///78AAAAAQP//QAAAAP///4AAAAAAAP///78AAAAAv/+/AAAAAP///4AAAAAAAP///78AAABA//9AAAAAAP///4AAAAAAAP///78AAAC//78AAAAAAP///4AAAAAAAL///78AAED//0AAAAAAQP///4AAAAAAAL///78AAL//vwAAAAAAQP///2AAAAAAAJ////8AQP//QAAAAAAAUP///0AAAAAAAID///8Qv/+/AAAAAAAAgP///xAAAAAAAED///+A//9AAAAAAAAAr///3wAAAAAAAADv/////78AAAAAAAAA7///nwAAAAAAAACf/////0AAAAAAAABg////QAAAAAAAAABA////vwAAAAAAABDf///fAAAAAAAAAAAAv///7zAAAAAAEM////9QAAAAAAAAAAAAEO////+fYECA3////58AAAAAAAAAAAAAADDv////////////nwAAAAAAAAAAAAAAAAAQn////////99gAAAAAAAAAAAAAAAAAAAAABBAgIBwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEAQAAAAAAAAAAAAAAAAAAAAAAAAIL////9AAAAAAAAAAAAAAAAAAAAAAACA//////9AAAAAAAAAAAAAAAAAAAAAQN////////9AAAAAAAAAAAAAAAAAABCv/////7////9AAAAAAAAAAAAAAAAAcO/////fUAD///9AAAAAAAAAAAAAAAAAv////4AQAAD///9AAAAAAAAAAAAAAAAAMP+/IAAAAAD///9AAAAAAAAAAAAAAAAAAEAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAL+/v7+/v7/////Pv7+/v78wAAAAAAAAAP////////////////////9AAAAAAAAAAP////////////////////9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBQgK+/v4BgEAAAAAAAAAAAAAAAAAAQgO///////////4AQAAAAAAAAAAAAADDf///////////////PEAAAAAAAAAAAMO////+/YEBAQHDf////zwAAAAAAAAAAj///71AAAAAAAAAQz////2AAAAAAAAAAAHDvMAAAAAAAAAAAEO///88AAAAAAAAAAAAAAAAAAAAAAAAAAJ////8QAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///8wAAAAAAAAAAAAAAAAAAAAAAAAAJ////8AAAAAAAAAAAAAAAAAAAAAAAAAAN///68AAAAAAAAAAAAAAAAAAAAAAAAAQP///2AAAAAAAAAAAAAAAAAAAAAAAAAAv///3wAAAAAAAAAAAAAAAAAAAAAAAABw////UAAAAAAAAAAAAAAAAAAAAAAAADDv//+vAAAAAAAAAAAAAAAAAAAAAAAAEM///98QAAAAAAAAAAAAAAAAAAAAAAAAz///7zAAAAAAAAAAAAAAAAAAAAAAAACf////UAAAAAAAAAAAAAAAAAAAAAAAAJ////9gAAAAAAAAAAAAAAAAAAAAAAAAn////2AAAAAAAAAAAAAAAAAAAAAAAACf////YAAAAAAAAAAAAAAAAAAAAAAAAJ////9gAAAAAAAAAAAAAAAAAAAAAAAAn////2AAAAAAAAAAAAAAAAAAAAAAAACf////YAAAAAAAAAAAAAAAAAAAAAAAAJ///+8wAAAAAAAAAAAAAAAAAAAAAAAAQP/////////////////////PAAAAAAAAQP////////////////////+/AAAAAAAAQP////////////////////+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQICfv7+AYBAAAAAAAAAAAAAAAAAAEIDv//////////+fEAAAAAAAAAAAAAAw3///////////////7zAAAAAAAAAAACD/////n1AQACBQv////+8gAAAAAAAAAACA/88wAAAAAAAAAHD///+fAAAAAAAAAAAAYBAAAAAAAAAAAACv////EAAAAAAAAAAAAAAAAAAAAAAAAABQ////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABg///vAAAAAAAAAAAAAAAAAAAAAAAAAADP//+PAAAAAAAAAAAAAAAAAAAAAAAAEJ///88QAAAAAAAAAAAAAAAAABBAQECP7///zxAAAAAAAAAAAAAAAAAAAED//////89gAAAAAAAAAAAAAAAAAAAAAID///////+vYAAAAAAAAAAAAAAAAAAAAECAgICv7////78QAAAAAAAAAAAAAAAAAAAAAAAAAGDv///PEAAAAAAAAAAAAAAAAAAAAAAAAABA////gAAAAAAAAAAAAAAAAAAAAAAAAAAAr///3wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///yAAAAAAAAAAAAAAAAAAAAAAAAAAcP///0AAAAAAAAAAAAAAAAAAAAAAAAAAgP///0AAAAAAAAAAAAAAAAAAAAAAAAAAj////xAAAAAAAAAAEAAAAAAAAAAAAAAA3///zwAAAAAAABCvrxAAAAAAAAAAAACA////YAAAAAAAEM///99AAAAAAAAAEI/////PAAAAAAAAAHD/////34+AgICf7////+8wAAAAAAAAAABQ7///////////////zyAAAAAAAAAAAAAAEIDf/////////89gAAAAAAAAAAAAAAAAAAAAIECAgIBAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI8gAAAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAr///rwAAAAAAAAAAAAAAAAAAAAAAAAAg////QAAAAAAAAAAAAAAAAAAAAAAAAACP///fAAAAAAAAAAAAAAAAAAAAAAAAABDv//9wAAAAAAAAAAAAAAAAAAAAAAAAAGD//+8QAAAAAAAAAAAAAAAAAAAAAAAAAN///58AAAAAAAAAAAAAAAAAAAAAAAAAQP///yAAAAAAAAAAAAAAAAAAAAAAAAAAr///vwAAAAAAAAAAAAAAAAAAAAAAAAAg////YAAAAAAAAAAAAAAAAAAAAAAAAACP///fAAAAAACPv78AAAAAAAAAAAAAABDv//+AAAAAAAD///8AAAAAAAAAAAAAAGD///8gAAAAAAD///8AAAAAAAAAAAAAAN///58AAAAAAAD///8AAAAAAAAAAAAAQP///0AAAAAAAAD///8AAAAAAAAAAAAAr///zwAAAAAAACD///8AAAAAAAAAAAAg////YAAAAAAAAED///8AAAAAAAAAAACP///vEAAAAAAAAED///8AAAAAAAAAAADv///PgICAgICAgJ////+AgIBgAAAAAAD///////////////////////+/AAAAAAD///////////////////////+/AAAAAABAQEBAQEBAQEBAQHD///9AQEAwAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAD//////////////////88AAAAAAAAAAAD//////////////////68AAAAAAAAAAAD///+fgICAgICAgICAgEAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AIHCvv7+/gCAAAAAAAAAAAAAAAAD////P//////////+PAAAAAAAAAAAAAAD/////////////////rwAAAAAAAAAAAAC/v7+fUBAAABBg3////4AAAAAAAAAAAAAAAAAAAAAAAAAAEN///+8QAAAAAAAAAAAAAAAAAAAAAAAAAGD///9wAAAAAAAAAAAAAAAAAAAAAAAAAAD///+vAAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC////vAAAAAAAAAAAAAAAAAAAAAAAAAAC////vAAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAD///+fAAAAAAAAAAAAAAAAAAAAAAAAAGD///9gAAAAAAAAADC/EAAAAAAAAAAAEN///+8QAAAAAAAAUO//32AAAAAAAAAgz////3AAAAAAAAAAYP/////fj4CAgK//////nwAAAAAAAAAAADDf//////////////+PAAAAAAAAAAAAAAAAYN//////////r0AAAAAAAAAAAAAAAAAAAAAgUICAgEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgcJ+/v4BgEAAAAAAAAAAAAAAAAAAAIL//////////748QAAAAAAAAAAAAAABQ7////////////+8QAAAAAAAAAAAAAED////vj0AQIFCP73AAAAAAAAAAAAAAEO///88gAAAAAAAAEAAAAAAAAAAAAAAAn///7zAAAAAAAAAAAAAAAAAAAAAAAAAg////gAAAAAAAAAAAAAAAAAAAAAAAAABw///vEAAAAAAAAAAAAAAAAAAAAAAAAADP//+fAAAAAAAAAAAAAAAAAAAAAAAAABD///9QAAAAAAAAAAAAAAAAAAAAAAAAAED///8gAAAAMECAUDAAAAAAAAAAAAAAAID///8AAFDf///////fYAAAAAAAAAAAAID//78An////////////88QAAAAAAAAAL///7+f///fn4CAn+////+/AAAAAAAAAL///+///4AAAAAAABCf////YAAAAAAAAL//////QAAAAAAAAAAA3///3wAAAAAAAL////9gAAAAAAAAAAAAYP///zAAAAAAAL///88AAAAAAAAAAAAAMP///2AAAAAAAJ///78AAAAAAAAAAAAAAP///4AAAAAAAID//98AAAAAAAAAAAAAAP///4AAAAAAAGD///8AAAAAAAAAAAAAAP///4AAAAAAADD///8wAAAAAAAAAAAAMP///2AAAAAAAADv//9gAAAAAAAAAAAAUP///zAAAAAAAACf//+/AAAAAAAAAAAAn///3wAAAAAAAABA////QAAAAAAAAAAw////gAAAAAAAAAAAv///7zAAAAAAACDf///fEAAAAAAAAAAAIO////+fcEBgn////+8wAAAAAAAAAAAAADDv////////////7zAAAAAAAAAAAAAAAAAQn////////++fEAAAAAAAAAAAAAAAAAAAABBAgICAQBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQDAAAAAAAAAA/////////////////////78AAAAAAAAA/////////////////////78AAAAAAAAAv7+/v7+/v7+/v7+/v+///58AAAAAAAAAAAAAAAAAAAAAAAAAIP///0AAAAAAAAAAAAAAAAAAAAAAAAAAn///zwAAAAAAAAAAAAAAAAAAAAAAAAAQ7///YAAAAAAAAAAAAAAAAAAAAAAAAACA///vAAAAAAAAAAAAAAAAAAAAAAAAAADf//+AAAAAAAAAAAAAAAAAAAAAAAAAAGD///8gAAAAAAAAAAAAAAAAAAAAAAAAAM///58AAAAAAAAAAAAAAAAAAAAAAAAAQP///zAAAAAAAAAAAAAAAAAAAAAAAAAAr///vwAAAAAAAAAAAAAAAAAAAAAAAAAg////YAAAAAAAAAAAAAAAAAAAAAAAAACf///fAAAAAAAAAAAAAAAAAAAAAAAAABDv//+AAAAAAAAAAAAAAAAAAAAAAAAAAID///8QAAAAAAAAAAAAAAAAAAAAAAAAAN///58AAAAAAAAAAAAAAAAAAAAAAAAAYP///yAAAAAAAAAAAAAAAAAAAAAAAAAAz///vwAAAAAAAAAAAAAAAAAAAAAAAABA////UAAAAAAAAAAAAAAAAAAAAAAAAACv///fAAAAAAAAAAAAAAAAAAAAAAAAACD///9wAAAAAAAAAAAAAAAAAAAAAAAAAJ///+8QAAAAAAAAAAAAAAAAAAAAAAAAEO///58AAAAAAAAAAAAAAAAAAAAAAAAAgP///yAAAAAAAAAAAAAAAAAAAAAAAAAA3///rwAAAAAAAAAAAAAAAAAAAAAAAABg////QAAAAAAAAAAAAAAAAAAAAAAAAABgz//fAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUICvv5+AMAAAAAAAAAAAAAAAAAAAAIDv/////////99gAAAAAAAAAAAAAAAQz///////////////nwAAAAAAAAAAAADP////nzAAABBQz////48AAAAAAAAAAID///9gAAAAAAAAAK////8wAAAAAAAAAN///58AAAAAAAAAABD///+PAAAAAAAAEP///2AAAAAAAAAAAAC///+/AAAAAAAAQP///0AAAAAAAAAAAAC///+/AAAAAAAAIP///0AAAAAAAAAAAAC///+vAAAAAAAAAO///48AAAAAAAAAAADv//9gAAAAAAAAAJ////8wAAAAAAAAAHD//98QAAAAAAAAACDv////gBAAAAAAYP//7zAAAAAAAAAAAAAw7/////+vUCCv///PIAAAAAAAAAAAAAAAEK///////////4AAAAAAAAAAAAAAAAAAAHDv/////////99gAAAAAAAAAAAAAAAwz///z1Bgv///////rxAAAAAAAAAAADDv//+fAAAAACCP7////88QAAAAAAAAIO///58AAAAAAAAAEK////+/AAAAAAAAn///3wAAAAAAAAAAAACf////QAAAAAAQ////jwAAAAAAAAAAAAAQ////rwAAAABA////YAAAAAAAAAAAAAAAv///3wAAAABA////QAAAAAAAAAAAAAAAv////wAAAABA////cAAAAAAAAAAAAAAAz///zwAAAAAQ////nwAAAAAAAAAAAAAg////rwAAAAAAv////zAAAAAAAAAAAACv////UAAAAAAAQP///+8wAAAAAAAAEJ////+/AAAAAAAAAGD/////r4BQQHCf7////+8QAAAAAAAAAABg7///////////////vxAAAAAAAAAAAAAAIJ/v/////////89gAAAAAAAAAAAAAAAAAAAAQGCAgIBAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIGCAr6+AYBAAAAAAAAAAAAAAAAAAACCf//////////+fEAAAAAAAAAAAAAAAYO//////////////3zAAAAAAAAAAAABA/////59QQEBQv////88QAAAAAAAAABDf///vMAAAAAAAAGD///+AAAAAAAAAAHD///9QAAAAAAAAAACv///vEAAAAAAAAM///98AAAAAAAAAAAAw////YAAAAAAAAP///58AAAAAAAAAAAAA7///rwAAAAAAIP///4AAAAAAAAAAAAAAv///7wAAAAAAQP///4AAAAAAAAAAAAAAgP///wAAAAAAMP///4AAAAAAAAAAAAAAgP///yAAAAAAAP///4AAAAAAAAAAAAAAgP///0AAAAAAAN///78AAAAAAAAAAAAAr////0AAAAAAAI////8gAAAAAAAAAABw/////0AAAAAAACD////PEAAAAAAAAI///////wAAAAAAAACA////33BAAEBg3///z////wAAAAAAAAAAn/////////////9gn///3wAAAAAAAAAAAHDv////////vzAAv///rwAAAAAAAAAAAAAAUICvn4AwAAAQ////gAAAAAAAAAAAAAAAAAAAAAAAAABg////MAAAAAAAAAAAAAAAAAAAAAAAAADf///fAAAAAAAAAAAAAAAAAAAAAAAAAID///9gAAAAAAAAAAAAAAAAAAAAAAAAYP///88AAAAAAAAAAAAAAAAAAAAAAABw////7zAAAAAAAAAAAAAAAAAAAAAAIL/////vMAAAAAAAAAAAAAAAAAAAADCf/////98wAAAAAAAAAAAAAAAAACBwz///////jxAAAAAAAAAAAAAAAAAAgP///////58gAAAAAAAAAAAAAAAAAAAAUP///89wEAAAAAAAAAAAAAAAAAAAAAAAAL9wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgN//rzAAAAAAAAAAAAAAAAAAAAAAAACA/////+8gAAAAAAAAAAAAAAAAAAAAAADv//////+AAAAAAAAAAAAAAAAAAAAAAAD///////+AAAAAAAAAAAAAAAAAAAAAAADf//////9gAAAAAAAAAAAAAAAAAAAAAABA/////88AAAAAAAAAAAAAAAAAAAAAAAAAMI+/cBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAwAAAAAAAAAAAAAAAAAAAAAAAAAAAQr///72AAAAAAAAAAAAAAAAAAAAAAAACP//////8gAAAAAAAAAAAAAAAAAAAAAAD///////+AAAAAAAAAAAAAAAAAAAAAAAD///////+AAAAAAAAAAAAAAAAAAAAAAAC///////9gAAAAAAAAAAAAAAAAAAAAAAAw7////58AAAAAAAAAAAAAAAAAAAAAAAAAEGCAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHDf/68wAAAAAAAAAAAAAAAAAAAAAAAAgP/////vIAAAAAAAAAAAAAAAAAAAAAAA7///////gAAAAAAAAAAAAAAAAAAAAAAA////////jwAAAAAAAAAAAAAAAAAAAAAAz///////cAAAAAAAAAAAAAAAAAAAAAAAQO/////PEAAAAAAAAAAAAAAAAAAAAAAAACCPv3AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAECvv58QAAAAAAAAAAAAAAAAAAAAAAAAUP/////PEAAAAAAAAAAAAAAAAAAAAAAA3///////cAAAAAAAAAAAAAAAAAAAAAAA////////nwAAAAAAAAAAAAAAAAAAAAAA3///////gAAAAAAAAAAAAAAAAAAAAAAAYP//////UAAAAAAAAAAAAAAAAAAAAAAAAL/////fAAAAAAAAAAAAAAAAAAAAAAAAAP////+AAAAAAAAAAAAAAAAAAAAAAAAAMP////8QAAAAAAAAAAAAAAAAAAAAAAAAcP///58AAAAAAAAAAAAAAAAAAAAAAAAAr////yAAAAAAAAAAAAAAAAAAAAAAAAAA7///vwAAAAAAAAAAAAAAAAAAAAAAAAAw////UAAAAAAAAAAAAAAAAAAAAAAAAABw///fAAAAAAAAAAAAAAAAAAAAAAAAAABQgIBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAQM/fEAAAAAAAAAAAAAAAAAAAAAAAABCP////jwAAAAAAAAAAAAAAAAAAAAAAUO//////nwAAAAAAAAAAAAAAAAAAACC//////89AAAAAAAAAAAAAAAAAAAAAgP/////vgAAAAAAAAAAAAAAAAAAAAEDf/////68gAAAAAAAAAAAAAAAAAAAQr//////fQAAAAAAAAAAAAAAAAAAAAHDv/////4AQAAAAAAAAAAAAAAAAAAAwv/////+/IAAAAAAAAAAAAAAAAAAAAGD/////72AAAAAAAAAAAAAAAAAAAAAAAID///+PEAAAAAAAAAAAAAAAAAAAAAAAAID//99AAAAAAAAAAAAAAAAAAAAAAAAAAID/////nxAAAAAAAAAAAAAAAAAAAAAAAACA7////+9wAAAAAAAAAAAAAAAAAAAAAAAAIL//////vzAAAAAAAAAAAAAAAAAAAAAAAABQ7/////+PEAAAAAAAAAAAAAAAAAAAAAAAEI//////31AAAAAAAAAAAAAAAAAAAAAAAABAz/////+vIAAAAAAAAAAAAAAAAAAAAAAAAIDv////74AAAAAAAAAAAAAAAAAAAAAAAAAgv//////PQAAAAAAAAAAAAAAAAAAAAAAAAFDv////vwAAAAAAAAAAAAAAAAAAAAAAAAAQj//vIAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQBAAAAAAAAAAv////////////////////0AAAAAAAAAAv////////////////////0AAAAAAAAAAj7+/v7+/v7+/v7+/v7+/vzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQBAAAAAAAAAAv////////////////////0AAAAAAAAAAv////////////////////0AAAAAAAAAAj7+/v7+/v7+/v7+/v7+/vzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAED/nxAAAAAAAAAAAAAAAAAAAAAAAAAAEN///+9gAAAAAAAAAAAAAAAAAAAAAAAAIL//////vyAAAAAAAAAAAAAAAAAAAAAAAABw7/////+AEAAAAAAAAAAAAAAAAAAAAAAAEJ//////30AAAAAAAAAAAAAAAAAAAAAAAABA3/////+vIAAAAAAAAAAAAAAAAAAAAAAAAIDv////73AAAAAAAAAAAAAAAAAAAAAAAAAgv//////PMAAAAAAAAAAAAAAAAAAAAAAAAFDf/////48QAAAAAAAAAAAAAAAAAAAAAAAQj//////vAAAAAAAAAAAAAAAAAAAAAAAAADC/////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAQN//////AAAAAAAAAAAAAAAAAAAAABCf/////99AAAAAAAAAAAAAAAAAAAAAYO//////gAAAAAAAAAAAAAAAAAAAADC//////78gAAAAAAAAAAAAAAAAAAAQgP/////vYAAAAAAAAAAAAAAAAAAAAFDf/////58QAAAAAAAAAAAAAAAAAAAgr//////fQAAAAAAAAAAAAAAAAAAAAHDv/////4AAAAAAAAAAAAAAAAAAAAAAIO////+/IAAAAAAAAAAAAAAAAAAAAAAAAGD/72AAAAAAAAAAAAAAAAAAAAAAAAAAAABwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEGCAv7+vgDAAAAAAAAAAAAAAAAAAACCf///////////fQAAAAAAAAAAAAAAAYP///////////////4AAAAAAAAAAAACf/////59QQEBQn/////9QAAAAAAAAABDv///PIAAAAAAAADDv///fAAAAAAAAAAAQr68AAAAAAAAAAACA////QAAAAAAAAAAAABAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAACP////MAAAAAAAAAAAAAAAAAAAAAAAAGD///+/AAAAAAAAAAAAAAAAAAAAAAAAYP////8wAAAAAAAAAAAAAAAAAAAAABCf////72AAAAAAAAAAAAAAAAAAAAAAEM/////fMAAAAAAAAAAAAAAAAAAAAAAQz////68QAAAAAAAAAAAAAAAAAAAAAACP////nwAAAAAAAAAAAAAAAAAAAAAAACD///+/AAAAAAAAAAAAAAAAAAAAAAAAAFD///9QAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAGC/v78AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFDf/78wAAAAAAAAAAAAAAAAAAAAAAAAIO/////fAAAAAAAAAAAAAAAAAAAAAAAAQP//////IAAAAAAAAAAAAAAAAAAAAAAAMP//////AAAAAAAAAAAAAAAAAAAAAAAAAJ////9gAAAAAAAAAAAAAAAAAAAAAAAAAABggDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIGCAr7+/j4BAAAAAAAAAAAAAAAAAEHDP////////////74AQAAAAAAAAAACA7//////////////////fMAAAAAAAMM//////76+AUEBAgJ/v////7zAAAABQ7////99gAAAAAAAAAAAQj////+8gAAAQ7//vcAAAAAAAAAAAAAAAAGD///+vAAAAMM8wAAAAAAAAAAAAAAAAAACP////QAAAAAAAAAAAAAAAAAAAAAAAAAAQ7///nwAAAAAAAAAAAAAAAAAAAAAAAAAAn///7wAAAAAAAAAAAAAAAAAAAAAAAAAAUP///0AAAAAAAAAAAAAAAAAAAAAAAAAAEP///3AAAAAAAECv7////++vUAAAAAAAAN///58AAAAAn////////////98AAAAAAL///78AAACf////z4CAgM////8AAAAAAL///88AAFD///9gAAAAAAD///8AAAAAAID///8AAM///58AAAAAAAD///8AAAAAAID///8AMP///zAAAAAAAAD///8AAAAAAID///8AcP//7wAAAAAAAAD///8AAAAAAID///8Aj///vwAAAAAAAAD///8AAAAAAID///8Av///nwAAAAAAAAD///8AAAAAAID///8Av///gAAAAAAAAAD///8AAAAAAID///8Av///gAAAAAAAAAD///8AAAAAAID///8Av///gAAAAAAAAAD///8AAAAAAID//98Av///rwAAAAAAAAD///8AAAAAAID//78AgP//vwAAAAAAAAD///8AAAAAAL///78AYP///wAAAAAAAGD///8AAAAAAL///48AIP///1AAAAAAEN////8gAAAAAM///4AAAL///88QAAAQv/+/v/9QAAAAEP///0AAADD////vv7///+8gn/+fAAAAYP//7wAAAABg////////70AAQP//gBAg3///nwAAAAAAIJ+/v7+PIAAAAL/////////vIAAAAAAAAAAAAAAAAAAAABDP//////9gAAAAAAAAAAAAAAAAAAAAAAAQcL+/gCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEAgAAAAAAAAAAAAAAAAAAAAAAAAMP/////PAAAAAAAAAAAAAAAAAAAAAAAAj///////IAAAAAAAAAAAAAAAAAAAAAAA3///////cAAAAAAAAAAAAAAAAAAAAAAw////j///zwAAAAAAAAAAAAAAAAAAAACP//+vMP///yAAAAAAAAAAAAAAAAAAAADf//9gAO///3AAAAAAAAAAAAAAAAAAACD///8QAJ///88AAAAAAAAAAAAAAAAAAHD//78AAFD///8gAAAAAAAAAAAAAAAAAM///3AAAAD///9wAAAAAAAAAAAAAAAAIP///yAAAACv///PAAAAAAAAAAAAAAAAcP//zwAAAABg////EAAAAAAAAAAAAAAAz///gAAAAAAg////YAAAAAAAAAAAAAAg////MAAAAAAAz///rwAAAAAAAAAAAABw///fAAAAAAAAcP///xAAAAAAAAAAAADP//+PAAAAAAAAMP///2AAAAAAAAAAACD///9AAAAAAAAAAN///68AAAAAAAAAAHD//+8AAAAAAAAAAI////8QAAAAAAAAAK///79AQEBAQEBAQHD///9gAAAAAAAAEP////////////////////+vAAAAAAAAYP//////////////////////EAAAAAAAr///37+/v7+/v7+/v7/P////UAAAAAAQ////YAAAAAAAAAAAAAAA////nwAAAABg////EAAAAAAAAAAAAAAAr///7wAAAACv///PAAAAAAAAAAAAAAAAYP///1AAABD///9wAAAAAAAAAAAAAAAAEP///58AAGD///8gAAAAAAAAAAAAAAAAAK///+8AAK///88AAAAAAAAAAAAAAAAAAHD///9QAO///4AAAAAAAAAAAAAAAAAAACD///+fAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEAAAAAAAAAAAAAAAAAAAAD/////////////769gAAAAAAAAAAAAAAD/////////////////30AAAAAAAAAAAAD////fv7+/v7+///////9gAAAAAAAAAAD///+AAAAAAAAAEID////vIAAAAAAAAAD///+AAAAAAAAAAABw////jwAAAAAAAAD///+AAAAAAAAAAAAA7///vwAAAAAAAAD///+AAAAAAAAAAAAAv///7wAAAAAAAAD///+AAAAAAAAAAAAAv///3wAAAAAAAAD///+AAAAAAAAAAAAA3///vwAAAAAAAAD///+AAAAAAAAAAABA////YAAAAAAAAAD///+AAAAAAAAAACDP///PAAAAAAAAAAD///+fQEBAQEBQj+///78QAAAAAAAAAAD////////////////PYAAAAAAAAAAAAAD///////////////+/cCAAAAAAAAAAAAD////fv7+/v7+/7/////+AAAAAAAAAAAD///+AAAAAAAAAADC/////nwAAAAAAAAD///+AAAAAAAAAAAAAr////2AAAAAAAAD///+AAAAAAAAAAAAAEP///88AAAAAAAD///+AAAAAAAAAAAAAAL////8AAAAAAAD///+AAAAAAAAAAAAAAL////8gAAAAAAD///+AAAAAAAAAAAAAAK////8QAAAAAAD///+AAAAAAAAAAAAAAL////8AAAAAAAD///+AAAAAAAAAAAAAIP///88AAAAAAAD///+AAAAAAAAAAAAQz////2AAAAAAAAD///+AAAAAAAAAMIDv////vwAAAAAAAAD///////////////////+/EAAAAAAAAAD/////////////////73AAAAAAAAAAAAD////////////vv49QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAECAn7+/j4BAAAAAAAAAAAAAAAAAABCA7///////////74AQAAAAAAAAAAAAQN/////////////////fQAAAAAAAAABg/////++fcEBAcJ/f////gAAAAAAAAED/////gBAAAAAAAAAAYO+fAAAAAAAAEO///+8wAAAAAAAAAAAAACAAAAAAAAAAgP///2AAAAAAAAAAAAAAAAAAAAAAAAAQ7///vwAAAAAAAAAAAAAAAAAAAAAAAABw////UAAAAAAAAAAAAAAAAAAAAAAAAAC////vAAAAAAAAAAAAAAAAAAAAAAAAAAD///+vAAAAAAAAAAAAAAAAAAAAAAAAADD///+AAAAAAAAAAAAAAAAAAAAAAAAAAED///9wAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAHD///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAACD///+AAAAAAAAAAAAAAAAAAAAAAAAAAADv//+/AAAAAAAAAAAAAAAAAAAAAAAAAACv////EAAAAAAAAAAAAAAAAAAAAAAAAABg////YAAAAAAAAAAAAAAAAAAAAAAAAAAA7///3wAAAAAAAAAAAAAAAAAAAAAAAAAAcP///48AAAAAAAAAAAAAAAAAAAAAAAAAAM////9wAAAAAAAAAAAAAEC/AAAAAAAAACDv////v0AAAAAAAAAwn///jwAAAAAAAAAw7//////fv4CAv9//////7xAAAAAAAAAAEL////////////////+/IAAAAAAAAAAAAABAr///////////r0AAAAAAAAAAAAAAAAAAABBAcICAcEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIEBAQEBAQEAwAAAAAAAAAAAAAAAAAAAAgP///////////9+fYAAAAAAAAAAAAAAAgP///////////////99gAAAAAAAAAAAAgP///7+/v7+/3///////nxAAAAAAAAAAgP///wAAAAAAACCA7////68AAAAAAAAAgP///wAAAAAAAAAAMM////+AAAAAAAAAgP///wAAAAAAAAAAACDv///vEAAAAAAAgP///wAAAAAAAAAAAACA////gAAAAAAAgP///wAAAAAAAAAAAAAQ////3wAAAAAAgP///wAAAAAAAAAAAAAAr////yAAAAAAgP///wAAAAAAAAAAAAAAgP///1AAAAAAgP///wAAAAAAAAAAAAAAQP///4AAAAAAgP///wAAAAAAAAAAAAAAQP///4AAAAAAgP///wAAAAAAAAAAAAAAQP///68AAAAAgP///wAAAAAAAAAAAAAAQP///78AAAAAgP///wAAAAAAAAAAAAAAQP///78AAAAAgP///wAAAAAAAAAAAAAAQP///48AAAAAgP///wAAAAAAAAAAAAAAQP///4AAAAAAgP///wAAAAAAAAAAAAAAcP///3AAAAAAgP///wAAAAAAAAAAAAAAn////0AAAAAAgP///wAAAAAAAAAAAAAA3////wAAAAAAgP///wAAAAAAAAAAAABA////rwAAAAAAgP///wAAAAAAAAAAAAC/////QAAAAAAAgP///wAAAAAAAAAAAHD///+/AAAAAAAAgP///wAAAAAAAAAAgP///+8wAAAAAAAAgP///wAAAAAAEGDf/////2AAAAAAAAAAgP///7+/v7/////////vUAAAAAAAAAAAgP///////////////58QAAAAAAAAAAAAgP//////////v59gEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQBAAAAAAAAAAv////////////////////xAAAAAAAAAAv////////////////////wAAAAAAAAAAv///77+/v7+/v7+/v7+/jwAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///77+/v7+/v7+/v78wAAAAAAAAAAAAv/////////////////9AAAAAAAAAAAAAv/////////////////9AAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///77+/v7+/v7+/v7+/v2AAAAAAAAAAv////////////////////4AAAAAAAAAAv////////////////////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBAQEBAQEBAQEBAQEBAQEBAEAAAAAAAAED/////////////////////QAAAAAAAAED/////////////////////AAAAAAAAAED////Pv7+/v7+/v7+/v7+/AAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///+fgICAgICAgICAgCAAAAAAAAAAAED//////////////////0AAAAAAAAAAAED//////////////////0AAAAAAAAAAAED///+fgICAgICAgICAgCAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADCAn7+/j3AwAAAAAAAAAAAAAAAAAABg3///////////z0AAAAAAAAAAAAAAEM////////////////+fEAAAAAAAAAAw7////++fYEBAgK//////gAAAAAAAABDf////jxAAAAAAAAAgv/+fAAAAAAAAAK////9gAAAAAAAAAAAAAIAAAAAAAAAAQP///68AAAAAAAAAAAAAAAAAAAAAAAAAv////yAAAAAAAAAAAAAAAAAAAAAAAAAg////nwAAAAAAAAAAAAAAAAAAAAAAAABw////UAAAAAAAAAAAAAAAAAAAAAAAAACv////EAAAAAAAAAAAAAAAAAAAAAAAAADf///vAAAAAAAAAAAAAAAAAAAAAAAAAAD///+/AAAAAAAAAAAAAAAAAAAAAAAAAAD///+/AAAAAAAAMICAgICAgICAgAAAAAD///+/AAAAAAAAQP///////////wAAAAD///+/AAAAAAAAIP///////////wAAAAD///+/AAAAAAAAAICAgICAv////wAAAAD///+/AAAAAAAAAAAAAAAAgP///wAAAADv///vAAAAAAAAAAAAAAAAgP///wAAAAC/////EAAAAAAAAAAAAAAAgP///wAAAACP////QAAAAAAAAAAAAAAAgP///wAAAABQ////jwAAAAAAAAAAAAAAgP///wAAAAAA7///3wAAAAAAAAAAAAAAgP///wAAAAAAj////4AAAAAAAAAAAAAAgP///wAAAAAAEO////8wAAAAAAAAAAAAgP///wAAAAAAAGD/////gBAAAAAAABBg3////wAAAAAAAACP/////++/gICPv////////wAAAAAAAAAAYO/////////////////PYAAAAAAAAAAAACCf7//////////vn0AAAAAAAAAAAAAAAAAAAEBggICAQDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBAQEAAAAAAAAAAAAAAEEBAQBAAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///9AQEBAQEBAQEBAcP///0AAAAAAAID//////////////////////0AAAAAAAID//////////////////////0AAAAAAAID///+AgICAgICAgICAn////0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAID///8AAAAAAAAAAAAAQP///0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQCAAAAAAAAAAv////////////////////4AAAAAAAAAAv////////////////////4AAAAAAAAAAYICAgICAv////4CAgICAgEAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAj7+/v7+/3////7+/v7+/v2AAAAAAAAAAv////////////////////4AAAAAAAAAAv////////////////////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQQEBAQEBAQEBAQEAwAAAAAAAAAAAAAABA//////////////+/AAAAAAAAAAAAAABA//////////////+/AAAAAAAAAAAAAAAwv7+/v7+/v7/v//+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAADv//+/AAAAAAAAAAAAAAAAAAAAAAAAAAD///+AAAAAAAAAAAAAAAAAAAAAAAAAAFD///9gAAAAAAAAAAAAAAAAAAAAAAAAAL////8gAAAAAAAAACAgAAAAAAAAAAAAYP///78AAAAAAAAAAL/vgCAAAAAAAACA/////0AAAAAAAAAAcP/////Pn4CAn+//////gAAAAAAAAAAAIL////////////////+AAAAAAAAAAAAAAABAn///////////r0AAAAAAAAAAAAAAAAAAAABAYICAcEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwQEAwAAAAAAAAAAAAAABAQEBAEAAAAAC///+/AAAAAAAAAAAAAHD///+fAAAAAAC///+/AAAAAAAAAAAAUP///88AAAAAAAC///+/AAAAAAAAAAAw7///zxAAAAAAAAC///+/AAAAAAAAABDv///vMAAAAAAAAAC///+/AAAAAAAAEM////9AAAAAAAAAAAC///+/AAAAAAAAn////2AAAAAAAAAAAAC///+/AAAAAACA////jwAAAAAAAAAAAAC///+/AAAAAGD///+fAAAAAAAAAAAAAAC///+/AAAAMP///88QAAAAAAAAAAAAAAC///+/AAAg7///3xAAAAAAAAAAAAAAAAC///+/ABDP///vMAAAAAAAAAAAAAAAAAC///+/AL////9AAAAAAAAAAAAAAAAAAAC///+/n////4AAAAAAAAAAAAAAAAAAAAC///+/gP///88QAAAAAAAAAAAAAAAAAAC///+/AL////+fAAAAAAAAAAAAAAAAAAC///+/ABDf////YAAAAAAAAAAAAAAAAAC///+/AAAw/////zAAAAAAAAAAAAAAAAC///+/AAAAcP///98QAAAAAAAAAAAAAAC///+/AAAAAJ////+/AAAAAAAAAAAAAAC///+/AAAAABDP////gAAAAAAAAAAAAAC///+/AAAAAAAw7////0AAAAAAAAAAAAC///+/AAAAAAAAYP///+8gAAAAAAAAAAC///+/AAAAAAAAAJ/////PAAAAAAAAAAC///+/AAAAAAAAAADP////nwAAAAAAAAC///+/AAAAAAAAAAAg7////2AAAAAAAAC///+/AAAAAAAAAAAAUP///+8wAAAAAAC///+/AAAAAAAAAAAAAID////PEAAAAAC///+/AAAAAAAAAAAAAAC/////rwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBAQEAQAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9AAAAAAAAAAAAAAAAAAAAAAAAAAID///9wQEBAQEBAQEBAQEBAAAAAAAAAAID////////////////////vAAAAAAAAAID///////////////////+/AAAAAAAAAID///////////////////+vAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQQEBAQDAAAAAAAAAAABBAQEBAMAAAAABA//////8AAAAAAAAAAHD/////vwAAAABA//////9AAAAAAAAAAJ//////zwAAAABA//////+AAAAAAAAAAN///////wAAAABQ//////+vAAAAAAAAEP///////wAAAACA//+////vAAAAAAAAUP//v////wAAAACA//+A7///MAAAAAAAgP//gP///wAAAACA//+Ar///cAAAAAAAv///QP///zAAAACA//+AcP//nwAAAAAA//+/QP///0AAAACv//+AMP//3wAAAABA//+AAP///0AAAAC///+AAO///yAAAABw//9AAP///0AAAAC///+AAK///2AAAACv//8QAP///2AAAAC///+AAHD//48AAADf/88AAP///4AAAADf//9wADD//88AACD//48AAP///4AAAAD///9AAADv//8QAFD//1AAAP///4AAAAD///9AAACv//9QAI///xAAAN///4AAAAD///9AAABg//+PAM//3wAAAL///78AAAD///9AAAAg//+/AP//nwAAAL///78AAED///8wAAAA3///QP//YAAAAL///78AAED///8AAAAAn///v///IAAAAJ///78AAED///8AAAAAYP/////fAAAAAID//+8AAED///8AAAAAIP////+fAAAAAID///8AAGD///8AAAAAAN////9wAAAAAID///8AAID//98AAAAAAJ////8wAAAAAHD///8AAID//78AAAAAAAAAAAAAAAAAAED///8QAID//78AAAAAAAAAAAAAAAAAAED///9AAI///78AAAAAAAAAAAAAAAAAAED///9AAL///78AAAAAAAAAAAAAAAAAAED///9AAL///58AAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBAQEBAEAAAAAAAAAAAAEBAQBAAAAAAAID/////jwAAAAAAAAAAAP///0AAAAAAAID/////7wAAAAAAAAAAAP///0AAAAAAAID//////2AAAAAAAAAAAP///0AAAAAAAID//9///78AAAAAAAAAAP///0AAAAAAAID//3D///8gAAAAAAAAAP///0AAAAAAAID//3DP//+fAAAAAAAAAP///0AAAAAAAID//4Bg///vEAAAAAAAAP///0AAAAAAAID//4AQ7///YAAAAAAAAP///0AAAAAAAID//4AAn///zwAAAAAAAP///0AAAAAAAID//58AMP///zAAAAAAAP///0AAAAAAAID//78AAM///58AAAAAAP///0AAAAAAAID//78AAGD//+8QAAAAAP///0AAAAAAAID//78AABDv//9gAAAAAP///0AAAAAAAID//78AAACf///PAAAAAP///0AAAAAAAID//78AAAAw////QAAAAP///0AAAAAAAID//78AAAAAz///nwAAAP///0AAAAAAAID//78AAAAAYP///xAAAP///0AAAAAAAID//78AAAAAEO///3AAAP///0AAAAAAAID//78AAAAAAJ///98AAP///0AAAAAAAID//78AAAAAADD///9AAP///0AAAAAAAID//78AAAAAAADP//+fAP///0AAAAAAAID//78AAAAAAABg////EM///0AAAAAAAID//78AAAAAAAAQ7///cL///0AAAAAAAID//78AAAAAAAAAn///37///0AAAAAAAID//78AAAAAAAAAMP///////0AAAAAAAID//78AAAAAAAAAAM///////0AAAAAAAID//78AAAAAAAAAAGD//////0AAAAAAAID//78AAAAAAAAAABDv/////0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBQgL+/n4AwAAAAAAAAAAAAAAAAAAAAgO//////////30AAAAAAAAAAAAAAABC///////////////+AAAAAAAAAAAAAAM/////fj1BAYJ//////cAAAAAAAAAAAgP///58AAAAAAAAgz////zAAAAAAAAAg////rwAAAAAAAAAAIO///78AAAAAAACf////IAAAAAAAAAAAAID///9AAAAAAADv//+vAAAAAAAAAAAAABD///+fAAAAAFD///9gAAAAAAAAAAAAAAC////vAAAAAID///8gAAAAAAAAAAAAAACA////MAAAAL////8AAAAAAAAAAAAAAABQ////YAAAAN///78AAAAAAAAAAAAAAABA////gAAAAP///78AAAAAAAAAAAAAAAAQ////jwAAAP///78AAAAAAAAAAAAAAAAA////vwAAAP///78AAAAAAAAAAAAAAAAA////vwAAAP///78AAAAAAAAAAAAAAAAA////vwAAAP///78AAAAAAAAAAAAAAAAA////vwAAAP///78AAAAAAAAAAAAAAAAg////gAAAAN///88AAAAAAAAAAAAAAABA////gAAAAL////8AAAAAAAAAAAAAAABQ////UAAAAID///8wAAAAAAAAAAAAAACA////IAAAAED///9wAAAAAAAAAAAAAADP///fAAAAAADv///PAAAAAAAAAAAAACD///+PAAAAAACP////QAAAAAAAAAAAAJ////8gAAAAAAAg7///zxAAAAAAAAAAQP///58AAAAAAAAAcP///88wAAAAAABg7///7xAAAAAAAAAAAJ//////z4+An9/////vMAAAAAAAAAAAAACf/////////////+8wAAAAAAAAAAAAAAAAQL/////////vnxAAAAAAAAAAAAAAAAAAAAAgUICAcEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBAQEBAQEBAQEAQAAAAAAAAAAAAAAAAAED/////////////769gEAAAAAAAAAAAAED/////////////////73AAAAAAAAAAAED///+fgICAgK+///////+fAAAAAAAAAED///9AAAAAAAAAEID/////gAAAAAAAAED///9AAAAAAAAAAAAw/////yAAAAAAAED///9AAAAAAAAAAAAAj////3AAAAAAAED///9AAAAAAAAAAAAAMP///68AAAAAAED///9AAAAAAAAAAAAAAP///78AAAAAAED///9AAAAAAAAAAAAAAP///78AAAAAAED///9AAAAAAAAAAAAAAP///78AAAAAAED///9AAAAAAAAAAAAAMP///68AAAAAAED///9AAAAAAAAAAAAAgP///3AAAAAAAED///9AAAAAAAAAAAAQ7////yAAAAAAAED///9AAAAAAAAAAEDP////jwAAAAAAAED///9wQEBAQICPz//////PEAAAAAAAAED//////////////////48QAAAAAAAAAED//////////////++fQAAAAAAAAAAAAED///+fgICAgIBQMAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAED///9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEFCAv7+fgDAAAAAAAAAAAAAAAAAAAACA7//////////fQAAAAAAAAAAAAAAAEM///////////////4AAAAAAAAAAAAAAz////9+AUEBgn/////9wAAAAAAAAAACA////nwAAAAAAADDP////MAAAAAAAACD///+vAAAAAAAAAAAg7///vwAAAAAAAJ///+8QAAAAAAAAAAAAgP///0AAAAAAAO///58AAAAAAAAAAAAAEP///58AAAAAUP///1AAAAAAAAAAAAAAAK///+8AAAAAj////xAAAAAAAAAAAAAAAID///8wAAAAv///3wAAAAAAAAAAAAAAAED///9gAAAA7///vwAAAAAAAAAAAAAAADD///+AAAAA////rwAAAAAAAAAAAAAAAAD///+PAAAA////gAAAAAAAAAAAAAAAAAD///+/AAAg////gAAAAAAAAAAAAAAAAAD///+/AAAg////gAAAAAAAAAAAAAAAAAD///+/AAAA////gAAAAAAAAAAAAAAAAAD///+/AAAA////vwAAAAAAAAAAAAAAAAD///+AAAAA7///vwAAAAAAAAAAAAAAAED///+AAAAAv///7wAAAAAAAAAAAAAAAFD///9QAAAAj////xAAAAAAAAAAAAAAAID///8gAAAAUP///2AAAAAAAAAAAAAAAM///88AAAAAAO///68AAAAAAAAAAAAAIP///4AAAAAAAJ////8wAAAAAAAAAAAAn////yAAAAAAACD////PEAAAAAAAAABA////gAAAAAAAAACA////zyAAAAAAAGDv///PAAAAAAAAAAAAn//////Pj4Cf3////88QAAAAAAAAAAAAAJ//////////////gAAAAAAAAAAAAAAAAABQz///////////759AAAAAAAAAAAAAAAAAACBAYICAr+//////vyAAAAAAAAAAAAAAAAAAAAAAABCA/////+8wAAAAAAAAAAAAAAAAAAAAAAAAMO/////PAAAAAAAAAAAAAAAAAAAAAAAAAFD/////YAAAAAAAAAAAAAAAAAAAAAAAAACv////3wAAAAAAAAAAAAAAAAAAAAAAAAAg////7wAAAAAAAAAAAAAAAAAAAAAAAAAAr69gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAMAAAAAAAAAAAAAAAAAAAv//////////////fn0AAAAAAAAAAAAAAv/////////////////+/MAAAAAAAAAAAv///34CAgICAv8//////7zAAAAAAAAAAv///vwAAAAAAAAAgr////+8QAAAAAAAAv///vwAAAAAAAAAAAK////9wAAAAAAAAv///vwAAAAAAAAAAACD////PAAAAAAAAv///vwAAAAAAAAAAAADP////AAAAAAAAv///vwAAAAAAAAAAAAC/////AAAAAAAAv///vwAAAAAAAAAAAAC/////AAAAAAAAv///vwAAAAAAAAAAAAD////fAAAAAAAAv///vwAAAAAAAAAAAGD///+PAAAAAAAAv///vwAAAAAAAAAAMO///+8gAAAAAAAAv///vwAAAAAAAECP7////2AAAAAAAAAAv//////////////////vUAAAAAAAAAAAv////////////////58gAAAAAAAAAAAAv/////////////+PEAAAAAAAAAAAAAAAv///vwAAACDv///PAAAAAAAAAAAAAAAAv///vwAAAABw////gAAAAAAAAAAAAAAAv///vwAAAAAAv////zAAAAAAAAAAAAAAv///vwAAAAAAMP///88AAAAAAAAAAAAAv///vwAAAAAAAID///+AAAAAAAAAAAAAv///vwAAAAAAAADf////MAAAAAAAAAAAv///vwAAAAAAAABA////zwAAAAAAAAAAv///vwAAAAAAAAAAj////4AAAAAAAAAAv///vwAAAAAAAAAAEO////8wAAAAAAAAv///vwAAAAAAAAAAAFD////PAAAAAAAAv///vwAAAAAAAAAAAACv////gAAAAAAAv///vwAAAAAAAAAAAAAg7////zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgcI+/v7+AYCAAAAAAAAAAAAAAAAAAQL/////////////PYAAAAAAAAAAAAACA/////////////////88wAAAAAAAAAHD/////z4BAQFCAv//////vEAAAAAAAIP///+9AAAAAAAAAACCf//9gAAAAAAAAj////0AAAAAAAAAAAAAAQHAAAAAAAAAAv///3wAAAAAAAAAAAAAAAAAAAAAAAAAA3///vwAAAAAAAAAAAAAAAAAAAAAAAAAAv///3wAAAAAAAAAAAAAAAAAAAAAAAAAAn////3AAAAAAAAAAAAAAAAAAAAAAAAAAQP////+AAAAAAAAAAAAAAAAAAAAAAAAAAJ//////33AgAAAAAAAAAAAAAAAAAAAAAACf////////v3AgAAAAAAAAAAAAAAAAAAAAUN//////////z2AQAAAAAAAAAAAAAAAAAABgz//////////vcAAAAAAAAAAAAAAAAAAAADCAz////////68QAAAAAAAAAAAAAAAAAAAAACCA7/////+vAAAAAAAAAAAAAAAAAAAAAAAAEID/////YAAAAAAAAAAAAAAAAAAAAAAAAABw////vwAAAAAAAAAAAAAAAAAAAAAAAAAA3////wAAAAAAAAAAAAAAAAAAAAAAAAAAn////wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAv////wAAAAAAIDAAAAAAAAAAAAAAAAAg////zwAAAAAQz+9QAAAAAAAAAAAAABDP////cAAAAADP////v1AAAAAAAAAAQM/////fAAAAAABg///////vv4+AgK/f/////+8wAAAAAAAAML//////////////////zzAAAAAAAAAAAABAn+///////////89gAAAAAAAAAAAAAAAAAAAwQICAgHBAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQQEBAQEBAQEBAQEBAQEBAQEBAQEBAAABA///////////////////////////fAABA//////////////////////////+/AAAwv7+/v7+/v7/f////v7+/v7+/v7+AAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAACA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEAgAAAAAAAAAAAAAABAQEAwAAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+/AAAAAAD///+AAAAAAAAAAAAAAAD///+fAAAAAADv//+PAAAAAAAAAAAAAAD///+AAAAAAAC////PAAAAAAAAAAAAAED///9gAAAAAABw////IAAAAAAAAAAAAJ////8QAAAAAAAg////vwAAAAAAAAAAMP///58AAAAAAAAAj////78gAAAAAABw7////yAAAAAAAAAAEM//////z6+Pv+//////YAAAAAAAAAAAABC//////////////+9gAAAAAAAAAAAAAAAAYN//////////nyAAAAAAAAAAAAAAAAAAAAAgUICAcEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABWAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEAAAAAAAAAAAAAAAAAAAABAQEAgAK////8QAAAAAAAAAAAAAAAAADD///9gAGD///9gAAAAAAAAAAAAAAAAAI////8QABD///+vAAAAAAAAAAAAAAAAAN///68AAACv////EAAAAAAAAAAAAAAAIP///2AAAABg////UAAAAAAAAAAAAAAAcP///xAAAAAQ////nwAAAAAAAAAAAAAAz///rwAAAAAAr///7wAAAAAAAAAAAAAg////YAAAAAAAYP///0AAAAAAAAAAAABw////EAAAAAAAEP///48AAAAAAAAAAACv//+vAAAAAAAAAK///98AAAAAAAAAABD///9gAAAAAAAAAGD///8wAAAAAAAAAGD///8QAAAAAAAAABD///+AAAAAAAAAAK///68AAAAAAAAAAACv///PAAAAAAAAAP///2AAAAAAAAAAAABg////IAAAAAAAUP///xAAAAAAAAAAAAAQ////cAAAAAAAn///rwAAAAAAAAAAAAAAr///vwAAAAAA7///YAAAAAAAAAAAAAAAYP///xAAAABQ////EAAAAAAAAAAAAAAAEP///2AAAACP//+vAAAAAAAAAAAAAAAAAK///68AAADf//9gAAAAAAAAAAAAAAAAAGD///8AADD//+8QAAAAAAAAAAAAAAAAABD///9QAI///58AAAAAAAAAAAAAAAAAAACv//+fAM///1AAAAAAAAAAAAAAAAAAAABg///vIP//7wAAAAAAAAAAAAAAAAAAAAAQ////r///nwAAAAAAAAAAAAAAAAAAAAAAr///////UAAAAAAAAAAAAAAAAAAAAAAAYP/////vAAAAAAAAAAAAAAAAAAAAAAAAEP////+fAAAAAAAAAAAAAAAAAAAAAAAAAK////9QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBAQDAAAAAAAAAAAAAAAAAAAAAAAEBAQL///88AAAAAAAAAAAAAAAAAAAAAAP///4D///8AAAAAAAAAAAAAAAAAAAAAIP///4D///8QAAAAAAAAAAAAAAAAAAAAQP///0D///9AAAAAAADv////jwAAAAAAcP//3zD///9QAAAAABD/////vwAAAAAAgP//vwD///+AAAAAAED/////7wAAAAAAr///gADf//+PAAAAAHD//////wAAAAAAv///cAC///+/AAAAAID//7///0AAAAAA////QACP///PAAAAAL//74D//2AAAAAQ////EACA////AAAAAN//v2D//4AAAABA////AABA////EAAAAP//n0D//68AAABg//+/AAAw////QAAAQP//gAD//88AAACA//+fAAAA////UAAAYP//QADv//8AAACv//+AAAAA3///gAAAgP//MAC///8gAAC///9QAAAAv///jwAAv///AACf//9AAADv//8wAAAAj///vwAAz//fAACA//9wAAD///8AAAAAgP//zwAA//+/AABA//+PAED//98AAAAAQP///wAw//+AAAAw//+/AFD//78AAAAAMP///wBQ//9wAAAA///fAID//48AAAAAAP///0CA//9AAAAAz///AJ///3AAAAAAAN///0Cv//8QAAAAv///QL///0AAAAAAAL///4DP//8AAAAAgP//UO///yAAAAAAAJ///4D//78AAAAAYP//gP///wAAAAAAAID//9///58AAAAAQP//3///vwAAAAAAAFD//////4AAAAAAEP//////rwAAAAAAAED//////1AAAAAAAP//////gAAAAAAAAAD//////zAAAAAAAL//////UAAAAAAAAADv/////wAAAAAAAJ//////QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEAQAAAAAAAAAAAAAAAgQEBAEAAAAID///+AAAAAAAAAAAAAAADf///fEAAAABDf////IAAAAAAAAAAAAID///9QAAAAAABA////rwAAAAAAAAAAEO///68AAAAAAAAAr////0AAAAAAAAAAn///7yAAAAAAAAAAIO///88AAAAAAAAw////gAAAAAAAAAAAAHD///9gAAAAAAC////PAAAAAAAAAAAAAADP///vEAAAAGD///9AAAAAAAAAAAAAAABA////gAAAEN///48AAAAAAAAAAAAAAAAAj////yAAgP//7xAAAAAAAAAAAAAAAAAAEO///68g7///YAAAAAAAAAAAAAAAAAAAAGD////P//+/AAAAAAAAAAAAAAAAAAAAAAC///////8gAAAAAAAAAAAAAAAAAAAAAAAg/////48AAAAAAAAAAAAAAAAAAAAAAAAw/////78AAAAAAAAAAAAAAAAAAAAAAAC///////9gAAAAAAAAAAAAAAAAAAAAAGD//++////vEAAAAAAAAAAAAAAAAAAAEO///4Ag7///jwAAAAAAAAAAAAAAAAAAgP//7xAAgP///yAAAAAAAAAAAAAAAAAg////YAAAEO///78AAAAAAAAAAAAAAAC////fAAAAAHD///9QAAAAAAAAAAAAAFD///9AAAAAAADf///fEAAAAAAAAAAAAN///78AAAAAAABQ////gAAAAAAAAAAAgP///zAAAAAAAAAAv////yAAAAAAAAAg7///nwAAAAAAAAAAQP///68AAAAAAACv///vIAAAAAAAAAAAAK////9AAAAAAED///+AAAAAAAAAAAAAACD////fAAAAAM///98QAAAAAAAAAAAAAACP////gAAAcP///2AAAAAAAAAAAAAAAAAQ7///7xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEAAAAAAAAAAAAAAAAAAAABAQEAgAJ////9AAAAAAAAAAAAAAAAAAHD///9AACDv///fAAAAAAAAAAAAAAAAEO///68AAACA////YAAAAAAAAAAAAAAAgP///yAAAAAQ7///3wAAAAAAAAAAAAAQ7///nwAAAAAAcP///2AAAAAAAAAAAACf///vEAAAAAAAAN///+8QAAAAAAAAACD///+AAAAAAAAAAGD///+AAAAAAAAAAJ///98QAAAAAAAAAAC////vEAAAAAAAMP///2AAAAAAAAAAAABA////gAAAAAAAv///3wAAAAAAAAAAAAAAr///7xAAAABA////QAAAAAAAAAAAAAAAIP///58AAAC///+/AAAAAAAAAAAAAAAAAJ////8gAFD///9AAAAAAAAAAAAAAAAAABDv//+fAN///58AAAAAAAAAAAAAAAAAAACA////gP///yAAAAAAAAAAAAAAAAAAAAAQ7///////gAAAAAAAAAAAAAAAAAAAAAAAYP/////vEAAAAAAAAAAAAAAAAAAAAAAAAN////+AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgQEBAQEBAQEBAQEBAQEBAQDAAAAAAAACA/////////////////////78AAAAAAACA/////////////////////78AAAAAAABgv7+/v7+/v7+/v7+/z////68AAAAAAAAAAAAAAAAAAAAAAAAAj////zAAAAAAAAAAAAAAAAAAAAAAAABA////gAAAAAAAAAAAAAAAAAAAAAAAABDf///PAAAAAAAAAAAAAAAAAAAAAAAAAI////8wAAAAAAAAAAAAAAAAAAAAAAAAQP///4AAAAAAAAAAAAAAAAAAAAAAAAAQ3///zwAAAAAAAAAAAAAAAAAAAAAAAACP////MAAAAAAAAAAAAAAAAAAAAAAAAFD///+AAAAAAAAAAAAAAAAAAAAAAAAAEO///88AAAAAAAAAAAAAAAAAAAAAAAAAr////zAAAAAAAAAAAAAAAAAAAAAAAABQ////gAAAAAAAAAAAAAAAAAAAAAAAABDv///PAAAAAAAAAAAAAAAAAAAAAAAAAK////8wAAAAAAAAAAAAAAAAAAAAAAAAUP///4AAAAAAAAAAAAAAAAAAAAAAAAAQ7///zwAAAAAAAAAAAAAAAAAAAAAAAACv////MAAAAAAAAAAAAAAAAAAAAAAAAFD///+AAAAAAAAAAAAAAAAAAAAAAAAAEO///88AAAAAAAAAAAAAAAAAAAAAAAAAr////zAAAAAAAAAAAAAAAAAAAAAAAABQ////gAAAAAAAAAAAAAAAAAAAAAAAABDv///PAAAAAAAAAAAAAAAAAAAAAAAAAK////8wAAAAAAAAAAAAAAAAAAAAAAAAAP///////////////////////4AAAAAAAP///////////////////////3AAAAAAAP///////////////////////0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQICAgICAgICAgGAAAAAAAAAAAAAAAAAAgP///////////78AAAAAAAAAAAAAAAAAgP///////////78AAAAAAAAAAAAAAAAAgP//34CAgICAgGAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//z0BAQEBAQDAAAAAAAAAAAAAAAAAAgP///////////78AAAAAAAAAAAAAAAAAgP///////////78AAAAAAAAAAAAAAAAAYL+/v7+/v7+/v48AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgO9AAAAAAAAAAAAAAAAAAAAAAAAAAACf//+/AAAAAAAAAAAAAAAAAAAAAAAAAAAw////QAAAAAAAAAAAAAAAAAAAAAAAAAAAv///vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP///zAAAAAAAAAAAAAAAAAAAAAAAAAAAL///58AAAAAAAAAAAAAAAAAAAAAAAAAAED///8gAAAAAAAAAAAAAAAAAAAAAAAAAAC///+fAAAAAAAAAAAAAAAAAAAAAAAAAABA////IAAAAAAAAAAAAAAAAAAAAAAAAAAAv///nwAAAAAAAAAAAAAAAAAAAAAAAAAAQP///yAAAAAAAAAAAAAAAAAAAAAAAAAAAN///58AAAAAAAAAAAAAAAAAAAAAAAAAAGD///8gAAAAAAAAAAAAAAAAAAAAAAAAAADf//+AAAAAAAAAAAAAAAAAAAAAAAAAAABg///vEAAAAAAAAAAAAAAAAAAAAAAAAAAA3///gAAAAAAAAAAAAAAAAAAAAAAAAAAAYP//7xAAAAAAAAAAAAAAAAAAAAAAAAAAAN///4AAAAAAAAAAAAAAAAAAAAAAAAAAAGD//+8QAAAAAAAAAAAAAAAAAAAAAAAAAADf//+AAAAAAAAAAAAAAAAAAAAAAAAAAACA///vEAAAAAAAAAAAAAAAAAAAAAAAAAAQ7///YAAAAAAAAAAAAAAAAAAAAAAAAAAAgP//3wAAAAAAAAAAAAAAAAAAAAAAAAAAEO///2AAAAAAAAAAAAAAAAAAAAAAAAAAAID//98AAAAAAAAAAAAAAAAAAAAAAAAAABDv//9gAAAAAAAAAAAAAAAAAAAAAAAAAACA///fAAAAAAAAAAAAAAAAAAAAAAAAAAAQ7///YAAAAAAAAAAAAAAAAAAAAAAAAAAAn///3wAAAAAAAAAAAAAAAAAAAAAAAAAAIP///1AAAAAAAAAAAAAAAAAAAAAAAAAAAJ///78AAAAAAAAAAAAAAAAAAAAAAAAAACD///9AAAAAAAAAAAAAAAAAAAAAAAAAAACf//+/AAAAAAAAAAAAAAAAAAAAAAAAAAAg////QAAAAAAAAAAAAAAAAAAAAAAAAAAAn///vwAAAAAAAAAAAAAAAAAAAAAAAAAAIP///0AAAAAAAAAAAAAAAAAAAAAAAAAAAJ/fYBAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACCAgICAgICAgICAIAAAAAAAAAAAAAAAAED/////////////QAAAAAAAAAAAAAAAAED/////////////QAAAAAAAAAAAAAAAACCAgICAgICA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAABBAQEBAQEBA////QAAAAAAAAAAAAAAAAED/////////////QAAAAAAAAAAAAAAAAED/////////////QAAAAAAAAAAAAAAAADC/v7+/v7+/v7+/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMICAgAAAAAAAAAAAAAAAAAAAAAAAAAAAz////3AAAAAAAAAAAAAAAAAAAAAAAABw/////+8QAAAAAAAAAAAAAAAAAAAAABDv///v//+fAAAAAAAAAAAAAAAAAAAAAJ///79A////QAAAAAAAAAAAAAAAAAAAQP///0AAr///zwAAAAAAAAAAAAAAAAAAz///nwAAIP///3AAAAAAAAAAAAAAAABw///vIAAAAID//+8QAAAAAAAAAAAAABDv//+AAAAAABDv//+vAAAAAAAAAAAAAJ///98QAAAAAABg////QAAAAAAAAAAAQP///2AAAAAAAAAAz///3wAAAAAAAAAAz///vwAAAAAAAAAAQP///4AAAAAAAACA////QAAAAAAAAAAAAJ///+8gAAAAAABwgIBgAAAAAAAAAAAAACCAgIBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABfAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgICAgICAgICAgICAgICAgICAgEAAAAD//////////////////////////4AAAAD//////////////////////////4AAAACAgICAgICAgICAgICAgICAgICAgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIO+PEAAAAAAAAAAAAAAAAAAAAAAAAAAAr///30AAAAAAAAAAAAAAAAAAAAAAAAAw//////+vEAAAAAAAAAAAAAAAAAAAAAAAII/v////72AAAAAAAAAAAAAAAAAAAAAAAAAQgO////+vAAAAAAAAAAAAAAAAAAAAAAAAAABg3/9wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBgn7//////769gEAAAAAAAAAAAAAAAUP//////////////3zAAAAAAAAAAAAAAIP/////vv7/v/////+8wAAAAAAAAAAAAAK+PQAAAAAAAIJ/////PAAAAAAAAAAAAAAAAAAAAAAAAAACP////MAAAAAAAAAAAAAAAAAAAAAAAAAAQ////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAYJ/P////////////gAAAAAAAAAAAAFDf////////////////gAAAAAAAAAAAn/////+vcEBAQEBA////gAAAAAAAAABQ////zyAAAAAAAAAA////gAAAAAAAAADP////IAAAAAAAAAAA////gAAAAAAAABD///+vAAAAAAAAAAAA////gAAAAAAAAED///+AAAAAAAAAAAAA////gAAAAAAAADD///+AAAAAAAAAAAAA////gAAAAAAAAAD////PAAAAAAAAAABg////gAAAAAAAAACv////UAAAAAAAAID/////vwAAAAAAAABA/////49AQEBw3///3////3AAAAAAAAAAYP////////////+PEN////8wAAAAAAAAAFDf////////v0AAADDP/98AAAAAAAAAAAAAMGCAgFAgAAAAAAAAMFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCAj2AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAECv////359AAAAAAAAAAAAAAP///4AQr///////////jwAAAAAAAAAAAP///4/P///vv7/v/////48AAAAAAAAAAP///+//72AAAAAAcP////9AAAAAAAAAAP/////PIAAAAAAAAHD///+vAAAAAAAAAP///+8wAAAAAAAAAADf////EAAAAAAAAP///4AAAAAAAAAAAACA////UAAAAAAAAP///4AAAAAAAAAAAABA////gAAAAAAAAP///4AAAAAAAAAAAAAQ////vwAAAAAAAP///4AAAAAAAAAAAAAA////vwAAAAAAAP///4AAAAAAAAAAAAAA////vwAAAAAAAP///4AAAAAAAAAAAAAA////vwAAAAAAAP///4AAAAAAAAAAAAAA////vwAAAAAAAP///4AAAAAAAAAAAAAA////vwAAAAAAAP///4AAAAAAAAAAAABA////gAAAAAAAAP///4AAAAAAAAAAAABw////UAAAAAAAAP///4AAAAAAAAAAAADP////EAAAAAAAAP///+8QAAAAAAAAAFD///+fAAAAAAAAAP/////fMAAAAAAAQO////8gAAAAAAAAAP///+///69wQHCv/////4AAAAAAAAAAAP///1DP////////////nwAAAAAAAAAAAP///0AQj+///////99QAAAAAAAAAAAAAAAAAAAAABBAgIBwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACCPz/////+/jyAAAAAAAAAAAAAAAAAQj/////////////+fEAAAAAAAAAAAABDP//////+/z///////3wAAAAAAAAAAAM/////PUAAAAABQn///YAAAAAAAAAAAgP///58AAAAAAAAAACCAAAAAAAAAAAAQ7///3xAAAAAAAAAAAAAAAAAAAAAAAABw////YAAAAAAAAAAAAAAAAAAAAAAAAAC////vAAAAAAAAAAAAAAAAAAAAAAAAAAD///+/AAAAAAAAAAAAAAAAAAAAAAAAADD///+PAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAAED///+AAAAAAAAAAAAAAAAAAAAAAAAAABD///+fAAAAAAAAAAAAAAAAAAAAAAAAAADv///PAAAAAAAAAAAAAAAAAAAAAAAAAACv////IAAAAAAAAAAAAAAAAAAAAAAAAABg////gAAAAAAAAAAAAAAAAAAAAAAAAAAA3////0AAAAAAAAAAAAAwAAAAAAAAAAAAUP////9wAAAAAAAAQL//MAAAAAAAAAAAAI//////75+AgJ/f////3xAAAAAAAAAAAABw///////////////vYAAAAAAAAAAAAAAAIJ//////////34AQAAAAAAAAAAAAAAAAAAAAQHCAgFAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCPgEAAAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAHC/////348gAID//78AAAAAAAAAAAAw3//////////vYID//78AAAAAAAAAADDv/////8+/z////8///78AAAAAAAAAAM////+vIAAAACCP/////78AAAAAAAAAYP///58AAAAAAAAAYP///78AAAAAAAAA3///7xAAAAAAAAAAAJ///78AAAAAAAAw////jwAAAAAAAAAAAID//78AAAAAAACA////QAAAAAAAAAAAAID//78AAAAAAACv////EAAAAAAAAAAAAID//78AAAAAAAC/////AAAAAAAAAAAAAID//78AAAAAAAC/////AAAAAAAAAAAAAID//78AAAAAAAC/////AAAAAAAAAAAAAID//78AAAAAAAC/////AAAAAAAAAAAAAID//78AAAAAAAC/////AAAAAAAAAAAAAID//78AAAAAAACf////MAAAAAAAAAAAAID//78AAAAAAABw////YAAAAAAAAAAAAID//78AAAAAAAAg////rwAAAAAAAAAAAL///78AAAAAAAAAz////zAAAAAAAAAAn////78AAAAAAAAAYP///98gAAAAAACf/////78AAAAAAAAAAL/////vn2BAgN///7///78AAAAAAAAAABDP////////////YFD//78AAAAAAAAAAAAQj+///////78wAED//78AAAAAAAAAAAAAABBAgIBgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgj8/////fn0AAAAAAAAAAAAAAAAAAAID///////////+vEAAAAAAAAAAAAAAAn//////fv8//////zxAAAAAAAAAAAACA////v0AAAAAQj////48AAAAAAAAAACD///+fAAAAAAAAAHD///8wAAAAAAAAAJ///98QAAAAAAAAAAC///+fAAAAAAAAEP///3AAAAAAAAAAAABg///vAAAAAAAAUP///zAAAAAAAAAAAAAg////MAAAAAAAgP///wAAAAAAAAAAAAAA////QAAAAAAAv///70BAQEBAQEBAQEBA////gAAAAAAAv///////////////////////gAAAAAAAv///////////////////////gAAAAAAAv///34CAgICAgICAgICAgICAIAAAAAAAn////wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///xAAAAAAAAAAAAAAAAAAAAAAAAAAMP///2AAAAAAAAAAAAAAAAAAAAAAAAAAAN///78AAAAAAAAAAAAAAAAAAAAAAAAAAGD///9wAAAAAAAAAAAAIAAAAAAAAAAAAADP////jxAAAAAAABCA74AAAAAAAAAAAAAw7////++fgICAr/////9AAAAAAAAAAAAAMM///////////////58QAAAAAAAAAAAAABCA3////////++fQAAAAAAAAAAAAAAAAAAAADBggIBwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwgK+/v6+AUBAAAAAAAAAAAAAAAAAAML////////////9wAAAAAAAAAAAAAABQ7/////////////9AAAAAAAAAAAAAACDv///vgEAgEEBgn88AAAAAAAAAAAAAAJ////8wAAAAAAAAAAAAAAAAAAAAAAAAAN///58AAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAED///////////////////+/AAAAAAAAAED///////////////////+PAAAAAAAAADC/v7+/v////9+/v7+/v79gAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEGCfAAAAAAAAAAAAAAAAAAAAADBAUIC/////IAAAAAAAAAAAII/P////////////////cAAAAAAAABCP////////////////77+vYAAAAAAAEM/////fj4CAr+//73AAAAAAAAAAAAAAr////3AAAAAAABDP//+fAAAAAAAAAAAw////gAAAAAAAAAAQ7///cAAAAAAAAACP////EAAAAAAAAAAAn///3wAAAAAAAAC////PAAAAAAAAAAAAgP///yAAAAAAAAC///+/AAAAAAAAAAAAgP///0AAAAAAAAC////PAAAAAAAAAAAAgP///yAAAAAAAABw////IAAAAAAAAAAAr///7wAAAAAAAAAg////jwAAAAAAAAAw////nwAAAAAAAAAAgP///4AAAAAAADDP///vEAAAAAAAAAAAAID////vr4CAv////+8wAAAAAAAAAAAAAACA////////////vzAAAAAAAAAAAAAAAGD//5+Av7+/v4AwAAAAAAAAAAAAAAAAIP//3wAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//7zAAAAAAAAAAAAAAAAAAAAAAAAAAQP/////Pv7+/v7+/j1AAAAAAAAAAAAAAAJ/////////////////fUAAAAAAAAAAAAACA7////////////////58AAAAAAAAAAAAAADBAQEBAQEBwr/////9gAAAAAAAAAAAAAAAAAAAAAAAAADDv///fAAAAAAAAAAAAAAAAAAAAAAAAAACP////AAAAADC/v48AAAAAAAAAAAAAAABQ////EAAAAED///8AAAAAAAAAAAAAAACf////AAAAAAD///9wAAAAAAAAAAAAAGD///+fAAAAAACf////v3BAQAAgQECAz////+8gAAAAAAAQz///////////////////3zAAAAAAAAAAEJ///////////////9+AEAAAAAAAAAAAAAAQUICPv7+/r4BwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBwgEAAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAAAAAAAAAAAAAAAAAAAAAAAAAAP///4AAACCPz////8+AEAAAAAAAAAAAAP///4AAgP//////////zxAAAAAAAAAAAP///4Cf///vv7+//////58AAAAAAAAAAP///+///4AQAAAAIM////8gAAAAAAAAAP/////vMAAAAAAAAED///9gAAAAAAAAAP///+8wAAAAAAAAAAD///+AAAAAAAAAAP///48AAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQn79wAAAAAAAAAAAAAAAAAAAAAAAAAADP////gAAAAAAAAAAAAAAAAAAAAAAAADD/////vwAAAAAAAAAAAAAAAAAAAAAAABD/////rwAAAAAAAAAAAAAAAAAAAAAAAABg///fMAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYICAgICAgICAgAAAAAAAAAAAAAAAAAAAv////////////wAAAAAAAAAAAAAAAAAAv////////////wAAAAAAAAAAAAAAAAAAMEBAQEBAn////wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAv7+/v7+/3////7+/v7+/vzAAAAAAAAAA/////////////////////0AAAAAAAAAA/////////////////////0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCvr0AAAAAAAAAAAAAAAAAAAAAAAAAAQP////8gAAAAAAAAAAAAAAAAAAAAAAAAgP////+AAAAAAAAAAAAAAAAAAAAAAAAAYP////9gAAAAAAAAAAAAAAAAAAAAAAAAAL///58AAAAAAAAAAAAAAAAAAAAAAAAAAAAgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAggICAgICAgICAgICAIAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAAAQQEBAQEBAQEBw////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////MAAAAAAAAAAAAAAAAAAAAAAAAABw////AAAAAAAAAAAAAAAAAAAAAAAAAACf///PAAAAAAAAAAAAAAAAAAAAAAAAABD///+PAAAAAAAAAAAAAAAAAAAAAAAAAK////8gAAAAAAAAAAAAAAAAAAAAAAAAn////48AAAAAAAAAAAAAAAAAAAAAACCv////zxAAAAAAAAAAAAAAAAAAAAAwn+/////PEAAAAAAAAAAAAAAAABBQj8///////48AAAAAAAAAAAAAAAAAEP////////+fIAAAAAAAAAAAAAAAAAAAAN////+/cBAAAAAAAAAAAAAAAAAAAAAAAHCAQBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABrAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADCAgI8AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAAAAAAAAAAAAAAAAAL///78AAAAAAAAAAABQgICAcAAAAAAAAL///78AAAAAAAAAAGD////vMAAAAAAAAL///78AAAAAAAAAYP///+8wAAAAAAAAAL///78AAAAAAABg////7zAAAAAAAAAAAL///78AAAAAAFD////vMAAAAAAAAAAAAL///78AAAAAMO///+8wAAAAAAAAAAAAAL///78AAAAw7///7zAAAAAAAAAAAAAAAL///78AADDv///vMAAAAAAAAAAAAAAAAL///78AMO///+8wAAAAAAAAAAAAAAAAAL///78w7///7zAAAAAAAAAAAAAAAAAAAL///7+P////zxAAAAAAAAAAAAAAAAAAAL///78An////78AAAAAAAAAAAAAAAAAAL///78AAL////+fAAAAAAAAAAAAAAAAAL///78AABDP////nwAAAAAAAAAAAAAAAL///78AAAAQz////4AAAAAAAAAAAAAAAL///78AAAAAMO////9gAAAAAAAAAAAAAL///78AAAAAADDv////YAAAAAAAAAAAAL///78AAAAAAABA/////zAAAAAAAAAAAL///78AAAAAAAAAYP///+8wAAAAAAAAAL///78AAAAAAAAAAGD////vMAAAAAAAAL///78AAAAAAAAAAACf////3xAAAAAAAL///78AAAAAAAAAAAAAn////88QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEAAAAAAAAAAAAAAAAAAAP////////////8AAAAAAAAAAAAAAAAAAP////////////8AAAAAAAAAAAAAAAAAAICAgICAgL////8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8AAAAAAAAAAAAAAAAAAAAAAAAAAHD///8QAAAAAAAAAAAAAAAAAAAAAAAAADD///+PAAAAAAAAEAAAAAAAAAAAAAAAAAC/////z4CAgJ/fYAAAAAAAAAAAAAAAAAAw7///////////zwAAAAAAAAAAAAAAAAAAIL/////////vnwAAAAAAAAAAAAAAAAAAAAAgYICAYEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAYAAQgO///68wAAAwr///34AAAAAAAP//3xDP///////vEGD///////+PAAAAAP///6//77+/////n///37/P////EAAAAP////+vEAAAj/////9wAAAA7///UAAAAP///78AAAAAcP///3AAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAP///0AAAAAAQP///wAAAAAAv///gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABuAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgAAAACCPz////8+AEAAAAAAAAAAAAP///zAQj///////////zxAAAAAAAAAAAP///1DP///vv7+//////58AAAAAAAAAAP///+///4AQAAAAIN////8gAAAAAAAAAP/////vMAAAAAAAAGD///9gAAAAAAAAAP///+8wAAAAAAAAACD///+AAAAAAAAAAP///48AAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAP///4AAAAAAAAAAAAD///+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUK/v////359AAAAAAAAAAAAAAAAAACC/////////////rxAAAAAAAAAAAAAAMO//////z7/f/////88QAAAAAAAAAAAQ3////4AQAAAAIL////+PAAAAAAAAAACA////YAAAAAAAAAC/////QAAAAAAAAADv//+/AAAAAAAAAAAg////nwAAAAAAAFD///9gAAAAAAAAAAAAr///7wAAAAAAAI////8QAAAAAAAAAAAAcP///0AAAAAAAL///98AAAAAAAAAAAAAQP///3AAAAAAAO///78AAAAAAAAAAAAAQP///4AAAAAAAP///78AAAAAAAAAAAAAAP///4AAAAAAAP///78AAAAAAAAAAAAAAP///4AAAAAAAP///78AAAAAAAAAAAAAIP///4AAAAAAAM///78AAAAAAAAAAAAAQP///4AAAAAAAL////8AAAAAAAAAAAAAYP///0AAAAAAAHD///8wAAAAAAAAAAAAj////xAAAAAAACD///+PAAAAAAAAAAAA7///rwAAAAAAAAC////vIAAAAAAAAACA////YAAAAAAAAABA////zyAAAAAAAGD///+/AAAAAAAAAAAAj////++fgFCAz////+8gAAAAAAAAAAAAAI//////////////3zAAAAAAAAAAAAAAAABAv////////++AEAAAAAAAAAAAAAAAAAAAACBQgIBwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgICAAAAAUK/v///vn0AAAAAAAAAAAAAA////QBC///////////+PAAAAAAAAAAAA////UM///++/v+//////gAAAAAAAAAAA////7//vYAAAABCP/////yAAAAAAAAAA/////88gAAAAAAAAj////48AAAAAAAAA////7zAAAAAAAAAAEO///98AAAAAAAAA////gAAAAAAAAAAAAK////8gAAAAAAAA////gAAAAAAAAAAAAHD///9QAAAAAAAA////gAAAAAAAAAAAAED///+AAAAAAAAA////gAAAAAAAAAAAAED///+AAAAAAAAA////gAAAAAAAAAAAABD///+AAAAAAAAA////gAAAAAAAAAAAAAD///+AAAAAAAAA////gAAAAAAAAAAAACD///+AAAAAAAAA////gAAAAAAAAAAAAED///+AAAAAAAAA////gAAAAAAAAAAAAGD///9QAAAAAAAA////gAAAAAAAAAAAAI////8gAAAAAAAA////gAAAAAAAAAAAAN///98AAAAAAAAA////7zAAAAAAAAAAcP///4AAAAAAAAAA/////+9AAAAAAABg////7xAAAAAAAAAA////////z4CAgM//////YAAAAAAAAAAA////j8////////////+AAAAAAAAAAAAA////gBCA7///////31AAAAAAAAAAAAAA////gAAAEECAgHAwAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAA////gAAAAAAAAAAAAAAAAAAAAAAAAAAAr4BwIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCAz////8+AEAAggIBgAAAAAAAAAAAAMN//////////71BA//+/AAAAAAAAAAAw7/////+/v8/////P//+/AAAAAAAAAADP////jxAAAAAgr/////+/AAAAAAAAAGD///+fAAAAAAAAAID///+/AAAAAAAAAM///+8QAAAAAAAAAADP//+/AAAAAAAAIP///48AAAAAAAAAAAC///+/AAAAAAAAYP///1AAAAAAAAAAAAC///+/AAAAAAAAgP///zAAAAAAAAAAAAC///+/AAAAAAAAv////wAAAAAAAAAAAAC///+/AAAAAAAAv////wAAAAAAAAAAAAC///+/AAAAAAAAv////wAAAAAAAAAAAAC///+/AAAAAAAAv////wAAAAAAAAAAAAC///+/AAAAAAAAr////xAAAAAAAAAAAAC///+/AAAAAAAAgP///0AAAAAAAAAAAAC///+/AAAAAAAAYP///3AAAAAAAAAAAAC///+/AAAAAAAAIP///78AAAAAAAAAABDf//+/AAAAAAAAAN////9AAAAAAAAAAJ////+/AAAAAAAAAGD////fMAAAAAAQv/////+/AAAAAAAAAADP/////5+AgJ/v/+/f//+/AAAAAAAAAAAw7///////////7zC///+/AAAAAAAAAAAAEJ////////+/IAC///+/AAAAAAAAAAAAAAAgUICAYCAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAAwcICAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABggICAgIAwAAAAEIDP////748AAAAAAAC///////+AAAAw7////////78AAAAAAAC///////+PADDv/////////58AAAAAAAAAAABA//+/EN///79gQID//4AAAAAAAAAAAABA///PgP//cAAAAID//4AAAAAAAAAAAABA////7/9wAAAAAID//4AAAAAAAAAAAABA/////78AAAAAAID//1AAAAAAAAAAAABA/////0AAAAAAAGC/vzAAAAAAAAAAAABA////vwAAAAAAAAAAAAAAAAAAAAAAAABA////YAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAAAAAABA////QAAAAAAAAAAAAAAAAAAAAACPv7/P////z7+/v2AAAAAAAAAAAAAAAAC//////////////4AAAAAAAAAAAAAAAAC//////////////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCv3/////+/j0AAAAAAAAAAAAAAAABQ3//////////////fUAAAAAAAAAAAAGD/////77+/v8///////1AAAAAAAAAAEO///+9QAAAAAAAQYM//vwAAAAAAAAAAYP///0AAAAAAAAAAAABgIAAAAAAAAAAAgP///wAAAAAAAAAAAAAAAAAAAAAAAAAAgP///zAAAAAAAAAAAAAAAAAAAAAAAAAAUP///88gAAAAAAAAAAAAAAAAAAAAAAAAAN//////n1AAAAAAAAAAAAAAAAAAAAAAADDf////////r3AgAAAAAAAAAAAAAAAAAAAQj+//////////r0AAAAAAAAAAAAAAAAAAABBgr+////////+fEAAAAAAAAAAAAAAAAAAAAABAj9//////rwAAAAAAAAAAAAAAAAAAAAAAAABg7////1AAAAAAAAAAAAAAAAAAAAAAAAAAYP///58AAAAAAAAAAAAAAAAAAAAAAAAAAP///78AAAAAAAAAAAAAAAAAAAAAAAAAAP///78AAAAAAAAAEIAAAAAAAAAAAAAAQP///58AAAAAAAAQz//PQAAAAAAAAABA7////0AAAAAAAACP/////9+fgICAgM//////nwAAAAAAAAAAgO////////////////+fAAAAAAAAAAAAACCP3///////////r0AAAAAAAAAAAAAAAAAAADBQgICAYEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgr7+vAAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAYICAgIDf///fgICAgICAgAAAAAAAAAAAv////////////////////wAAAAAAAAAAv///////////////////vwAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAAC///+/AAAAAAAAAAAAAAAAAAAAAAAAAACf///fAAAAAAAAAAAAAAAAAAAAAAAAAABQ////jwAAAAAAAEAAAAAAAAAAAAAAAAAAz////8+AgICPz/+AAAAAAAAAAAAAAAAAIN/////////////vEAAAAAAAAAAAAAAAABCf/////////89gAAAAAAAAAAAAAAAAAAAAEECAgIBAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAdQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgIBAAAAAAAAAAAAAgICAQAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAAD///+AAAAAAAAAAAAA////gAAAAAAAAADP//+PAAAAAAAAAAAg////gAAAAAAAAAC////PAAAAAAAAABDP////gAAAAAAAAACP////QAAAAAAAQN//////gAAAAAAAAAAw////749AQHC////Pz///gAAAAAAAAAAAj////////////88Qj///gAAAAAAAAAAAAIDv///////fYAAAgP//gAAAAAAAAAAAAAAQQICAYDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADCAgIAgAAAAAAAAAAAAAABAgICAAAAAACD///+PAAAAAAAAAAAAAADP//+vAAAAAAC////fAAAAAAAAAAAAACD///9gAAAAAABg////MAAAAAAAAAAAAHD//+8QAAAAAAAQ////jwAAAAAAAAAAAM///58AAAAAAAAAr///3wAAAAAAAAAAIP///1AAAAAAAAAAUP///zAAAAAAAAAAcP//3wAAAAAAAAAAAO///48AAAAAAAAAz///jwAAAAAAAAAAAJ///98AAAAAAAAg////MAAAAAAAAAAAADD///8wAAAAAABw///PAAAAAAAAAAAAAADf//+PAAAAAADP//9wAAAAAAAAAAAAAACP///fAAAAACD///8gAAAAAAAAAAAAAAAg////MAAAAHD//68AAAAAAAAAAAAAAAAAz///jwAAAM///2AAAAAAAAAAAAAAAAAAcP//3wAAIP//7xAAAAAAAAAAAAAAAAAAEP///0AAcP//nwAAAAAAAAAAAAAAAAAAAK///58Az///UAAAAAAAAAAAAAAAAAAAAGD//+8g///fAAAAAAAAAAAAAAAAAAAAAADv//+///+PAAAAAAAAAAAAAAAAAAAAAACf//////8wAAAAAAAAAAAAAAAAAAAAAABQ/////88AAAAAAAAAAAAAAAAAAAAAAAAA3////3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIICAgCAAAAAAAAAAAAAAAAAAAABAgIBgEP///3AAAAAAAAAAAAAAAAAAAACf//+/AO///4AAAAAAAAAAAAAAAAAAAAC///+AAL///78AAAAAAIC/v79wAAAAAADv//9gAID//88AAAAAAM////+/AAAAAAD///8wAFD///8AAAAAAP//////AAAAAED///8AADD///8gAAAAQP//3///MAAAAFD//88AAAD///9AAAAAgP//gP//YAAAAID//68AAAC///9gAAAAr///IP//jwAAAJ///4AAAACf//+AAAAA3//PAP//vwAAAL///0AAAABw//+vAAAQ//+fAL///wAAAO///yAAAABA//+/AABA//9wAJ///zAAAP///wAAAAAQ////AACA//9AAHD//1AAMP//vwAAAAAA3///EACv//8AAED//4AAQP//nwAAAAAAv///QADf/98AABD//78AgP//cAAAAAAAgP//YCD//68AAADv/+8Aj///QAAAAAAAUP//gFD//4AAAAC///8gv///EAAAAAAAMP//r4D//0AAAACA//9Q3//vAAAAAAAAAP//v7///xAAAABg//+A//+/AAAAAAAAAL///+//3wAAAABA///v//+PAAAAAAAAAJ//////vwAAAAAA//////9gAAAAAAAAAHD/////gAAAAAAAz/////9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAECAgIBQAAAAAAAAAAAAcICAgBAAAAAAABDv///vEAAAAAAAAABA////jwAAAAAAAABQ////rwAAAAAAABDf///fEAAAAAAAAAAAj////0AAAAAAAID///8wAAAAAAAAAAAAEN///98QAAAAMP///4AAAAAAAAAAAAAAAED///+AAAAAz///zwAAAAAAAAAAAAAAAACP////IABw///vMAAAAAAAAAAAAAAAAAAAz///vyDv//9wAAAAAAAAAAAAAAAAAAAAMP///9///78AAAAAAAAAAAAAAAAAAAAAAID/////7yAAAAAAAAAAAAAAAAAAAAAAAADv////jwAAAAAAAAAAAAAAAAAAAAAAAGD/////7yAAAAAAAAAAAAAAAAAAAAAAIO///+///88AAAAAAAAAAAAAAAAAAAAAv///v1D///+AAAAAAAAAAAAAAAAAAACA///vIACv////MAAAAAAAAAAAAAAAADD///9wAAAQ7///zwAAAAAAAAAAAAAAEM///78AAAAAcP///48AAAAAAAAAAAAAj////yAAAAAAAL////9AAAAAAAAAAABA////gAAAAAAAACD////fEAAAAAAAABDv///PAAAAAAAAAACA////jwAAAAAAAK////8wAAAAAAAAAAAAz////1AAAAAAYP///4AAAAAAAAAAAAAAQP///+8QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADCAgIAgAAAAAAAAAAAAAABQgICAAAAAACD///+PAAAAAAAAAAAAAADP//+vAAAAAACv///fAAAAAAAAAAAAACD///9gAAAAAABg////MAAAAAAAAAAAAHD///8QAAAAAAAQ////jwAAAAAAAAAAAM///58AAAAAAAAAr///3wAAAAAAAAAAIP///1AAAAAAAAAAYP///zAAAAAAAAAAcP//7wAAAAAAAAAAEO///48AAAAAAAAAz///nwAAAAAAAAAAAJ///98AAAAAAAAg////UAAAAAAAAAAAAFD///8wAAAAAABg///fAAAAAAAAAAAAAADv//+PAAAAAACv//+PAAAAAAAAAAAAAACf///fAAAAABD///8wAAAAAAAAAAAAAABA////MAAAAGD//98AAAAAAAAAAAAAAAAA3///cAAAAK///48AAAAAAAAAAAAAAAAAj///zwAAEP///zAAAAAAAAAAAAAAAAAAMP///yAAYP//zwAAAAAAAAAAAAAAAAAAAN///3AAn///cAAAAAAAAAAAAAAAAAAAAID//88A7///IAAAAAAAAAAAAAAAAAAAACD///9w///PAAAAAAAAAAAAAAAAAAAAAADP///v//9wAAAAAAAAAAAAAAAAAAAAAABw//////8QAAAAAAAAAAAAAAAAAAAAAAAg/////68AAAAAAAAAAAAAAAAAAAAAAAAAAO///2AAAAAAAAAAAAAAAAAAAAAAAAAAYP//7xAAAAAAAAAAAAAAAAAAAAAAAAAA3///gAAAAAAAAAAAAAAAAAAAAAAAAACf///vEAAAAAAAAAAAAAAAAAAAAAAAEJ////9QAAAAAAAAAAAAAAAAAAAAIFCf7////58AAAAAAAAAAAAAAAAAAAAAj///////gAAAAAAAAAAAAAAAAAAAAAAAYP///79AAAAAAAAAAAAAAAAAAAAAAAAAMI9wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABggICAgICAgICAgICAgIAgAAAAAAAAAAC///////////////////9AAAAAAAAAAAC///////////////////9AAAAAAAAAAABggICAgICAgICAj////+8QAAAAAAAAAAAAAAAAAAAAAAAAn////0AAAAAAAAAAAAAAAAAAAAAAAABg////gAAAAAAAAAAAAAAAAAAAAAAAADDv//+/AAAAAAAAAAAAAAAAAAAAAAAAEM///+8QAAAAAAAAAAAAAAAAAAAAAAAAn////1AAAAAAAAAAAAAAAAAAAAAAAABg////jwAAAAAAAAAAAAAAAAAAAAAAADDv///PAAAAAAAAAAAAAAAAAAAAAAAAEM///+8gAAAAAAAAAAAAAAAAAAAAAAAAn////1AAAAAAAAAAAAAAAAAAAAAAAABg////jwAAAAAAAAAAAAAAAAAAAAAAADDv///PAAAAAAAAAAAAAAAAAAAAAAAAEM///+8gAAAAAAAAAAAAAAAAAAAAAAAAn////1AAAAAAAAAAAAAAAAAAAAAAAABg////jwAAAAAAAAAAAAAAAAAAAAAAADDv///PEAAAAAAAAAAAAAAAAAAAAAAAAK////////////////////9gAAAAAAAAAL////////////////////9AAAAAAAAAAL////////////////////8QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAewAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgQDAAAAAAAAAAAAAAAAAAAAAAAABgr+///78AAAAAAAAAAAAAAAAAAAAAEM///////78AAAAAAAAAAAAAAAAAAAAAz////++fgGAAAAAAAAAAAAAAAAAAAABQ////jwAAAAAAAAAAAAAAAAAAAAAAAACA///PAAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAABA///fAAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAAAg////AAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAA7///QAAAAAAAAAAAAAAAAAAAAAAAAAAAv///YAAAAAAAAAAAAAAAAAAAAAAAAAAAv///gAAAAAAAAAAAAAAAAAAAAAAAAAAAj///gAAAAAAAAAAAAAAAAAAAAAAAAAAAv///gAAAAAAAAAAAAAAAAAAAAAAAAAAQ7///cAAAAAAAAAAAAAAAAAAAAAAAAFDf////IAAAAAAAAAAAAAAAAAAAj7/P/////+9gAAAAAAAAAAAAAAAAAAAAv//////vnxAAAAAAAAAAAAAAAAAAAAAAv////////78wAAAAAAAAAAAAAAAAAAAAAAAgUJ/////vEAAAAAAAAAAAAAAAAAAAAAAAAAAw////cAAAAAAAAAAAAAAAAAAAAAAAAAAAv///gAAAAAAAAAAAAAAAAAAAAAAAAAAAj///gAAAAAAAAAAAAAAAAAAAAAAAAAAAv///gAAAAAAAAAAAAAAAAAAAAAAAAAAAv///cAAAAAAAAAAAAAAAAAAAAAAAAAAA3///QAAAAAAAAAAAAAAAAAAAAAAAAAAA////QAAAAAAAAAAAAAAAAAAAAAAAAAAQ////EAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA///vAAAAAAAAAAAAAAAAAAAAAAAAAABw//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAABg////MAAAAAAAAAAAAAAAAAAAAAAAAAAQ7////59gQDAAAAAAAAAAAAAAAAAAAAAAMO///////78AAAAAAAAAAAAAAAAAAAAAACCf/////78AAAAAAAAAAAAAAAAAAAAAAAAAAEBwgGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAQP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAEEBAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAgAAAAAAAAAAAAAAAAAAAAAAAAAAAA////769gAAAAAAAAAAAAAAAAAAAAAAAA////////vxAAAAAAAAAAAAAAAAAAAAAAgICv7////78AAAAAAAAAAAAAAAAAAAAAAAAAAJ////8wAAAAAAAAAAAAAAAAAAAAAAAAAADf//+AAAAAAAAAAAAAAAAAAAAAAAAAAAC///+AAAAAAAAAAAAAAAAAAAAAAAAAAAC///9gAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAACD///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED//88AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//68AAAAAAAAAAAAAAAAAAAAAAAAAAJ///4AAAAAAAAAAAAAAAAAAAAAAAAAAAK///68AAAAAAAAAAAAAAAAAAAAAAAAAAID///8wAAAAAAAAAAAAAAAAAAAAAAAAACD////vYBAAAAAAAAAAAAAAAAAAAAAAAABQ7//////fv48AAAAAAAAAAAAAAAAAAAAAEHDf/////78AAAAAAAAAAAAAAAAAAAAwr////////78AAAAAAAAAAAAAAAAAABDv////n1AwAAAAAAAAAAAAAAAAAAAAAHD///9gAAAAAAAAAAAAAAAAAAAAAAAAAK///88AAAAAAAAAAAAAAAAAAAAAAAAAAK///4AAAAAAAAAAAAAAAAAAAAAAAAAAAID//58AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAFD//78AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAADD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAD///8wAAAAAAAAAAAAAAAAAAAAAAAAAAD///9AAAAAAAAAAAAAAAAAAAAAAAAAAADP//9QAAAAAAAAAAAAAAAAAAAAAAAAAAC///+AAAAAAAAAAAAAAAAAAAAAAAAAAAC///+AAAAAAAAAAAAAAAAAAAAAAAAAAFD///9QAAAAAAAAAAAAAAAAAAAAQEBgn////98AAAAAAAAAAAAAAAAAAAAA////////7zAAAAAAAAAAAAAAAAAAAAAA/////++fEAAAAAAAAAAAAAAAAAAAAAAAgIBwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBggFAQAAAAAAAAAAAAAAAAAAAAAAAQv///////gAAAAAAAAAAAn0AAAAAAACDv/////////88QAAAAAABw//+PAAAAAM////+fgM/////PEAAAAGD///9AAAAAgP//7zAAAACA////73BQn////48AAAAA7///MAAAAAAAYP//////////zxAAAAAAIJ+AAAAAAAAAAEDf//////+vEAAAAAAAAAAAAAAAAAAAAAAQYI+vgDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIICAcBAAAAAAAAAAAAAAAAAAAAAAAABg/////88QAAAAAAAAAAAAAAAAAAAAABDv//////+fAAAAAAAAAAAAAAAAAAAAAED////////fAAAAAAAAAAAAAAAAAAAAAED////////fAAAAAAAAAAAAAAAAAAAAABDv//////+fAAAAAAAAAAAAAAAAAAAAAABg/////88QAAAAAAAAAAAAAAAAAAAAAAAAIICAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADXAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMI8AAAAAAAAAABCPAAAAAAAAAAAAAAAw7/+fAAAAAAAAEM//nwAAAAAAAAAAAACf////nwAAAAAQz////0AAAAAAAAAAAAAQz////58AABDP////YAAAAAAAAAAAAAAAEM////+fEM////9gAAAAAAAAAAAAAAAAABDP////7////2AAAAAAAAAAAAAAAAAAAAAQz///////YAAAAAAAAAAAAAAAAAAAAAAAIP////+/AAAAAAAAAAAAAAAAAAAAAAAQz///////nwAAAAAAAAAAAAAAAAAAABDP////3////58AAAAAAAAAAAAAAAAAEM////9gEM////+fAAAAAAAAAAAAAAAQz////2AAABDP////nwAAAAAAAAAAAACf////YAAAAAAQz////0AAAAAAAAAAAAAQz/9gAAAAAAAAEM//YAAAAAAAAAAAAAAAEFAAAAAAAAAAABBQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBAAAAAAAAAAAAAAAAAAAAAAAAAAAAwv//PAAAAAAAAAAAAAAAAAAAAAAAAEJ//////YAAAAAAAAAAAAAAAAAAAAACA7/////+/UAAAAAAAAAAAAAAAAAAAUN/////vnzAAAAAAAAAAAAAAAAAAAAAAgP//z2AQAAAAAAAAAAAAAAAAAAAAAAAAEJ8wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAII/P////359AAAAAAAAAAAAAAAAAAACA////////////rxAAAAAAAAAAAAAAAJ//////37/P/////88QAAAAAAAAAAAAgP///79AAAAAEI////+PAAAAAAAAAAAg////nwAAAAAAAABw////MAAAAAAAAACf///fEAAAAAAAAAAAv///nwAAAAAAABD///9wAAAAAAAAAAAAYP//7wAAAAAAAFD///8wAAAAAAAAAAAAIP///zAAAAAAAID///8AAAAAAAAAAAAAAP///0AAAAAAAL///+9AQEBAQEBAQEBAQP///4AAAAAAAL///////////////////////4AAAAAAAL///////////////////////4AAAAAAAL///9+AgICAgICAgICAgICAgCAAAAAAAJ////8AAAAAAAAAAAAAAAAAAAAAAAAAAID///8QAAAAAAAAAAAAAAAAAAAAAAAAADD///9gAAAAAAAAAAAAAAAAAAAAAAAAAADf//+/AAAAAAAAAAAAAAAAAAAAAAAAAABg////cAAAAAAAAAAAACAAAAAAAAAAAAAAz////48QAAAAAAAQgO+AAAAAAAAAAAAAMO/////vn4CAgK//////QAAAAAAAAAAAADDP//////////////+fEAAAAAAAAAAAAAAQgN/////////vn0AAAAAAAAAAAAAAAAAAAAAwYICAcEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQEBAQEBAQBAAv////////////////////////////0AAv////////////////////////////0AAj7+/v7+/v7+/v7+/v7+/v7+/v7+/vzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA////////////////////////////////////////////////////////////////v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQDAAAAAAAAAAAAAAAAAAAAAAAAAAAGD//4AAAAAAAAAAAAAAAAAAAAAAAAAAAN///0AAAAAAAAAAAAAAAAAAAAAAAAAAYP///xAAAAAAAAAAAAAAAAAAAAAAAAAA3///zwAAAAAAAAAAAAAAAAAAAAAAAABA////nwAAAAAAAAAAAAAAAAAAAAAAAAC/////YAAAAAAAAAAAAAAAAAAAAAAAAED/////MAAAAAAAAAAAAAAAAAAAAAAAAK//////YAAAAAAAAAAAAAAAAAAAAAAAAP//////7wAAAAAAAAAAAAAAAAAAAAAAAP///////wAAAAAAAAAAAAAAAAAAAAAAAN//////3wAAAAAAAAAAAAAAAAAAAAAAADDv///vMAAAAAAAAAAAAAAAAAAAAAAAAAAQYGAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABkgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBAMAAAAAAAAAAAAAAAAAAAAAAAAAAAn////78AAAAAAAAAAAAAAAAAAAAAAABA//////9wAAAAAAAAAAAAAAAAAAAAAACA//////+/AAAAAAAAAAAAAAAAAAAAAABw//////+fAAAAAAAAAAAAAAAAAAAAAAAQz/////9QAAAAAAAAAAAAAAAAAAAAAAAAj////98AAAAAAAAAAAAAAAAAAAAAAAAAz////2AAAAAAAAAAAAAAAAAAAAAAAAAA////3wAAAAAAAAAAAAAAAAAAAAAAAABA////YAAAAAAAAAAAAAAAAAAAAAAAAACA///vAAAAAAAAAAAAAAAAAAAAAAAAAACv//+AAAAAAAAAAAAAAAAAAAAAAAAAAADv/+8QAAAAAAAAAAAAAAAAAAAAAAAAAACAgFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgQEAQAAAAAAAwQEAAAAAAAAAAAAAAAADf//8QAAAAABDv/+8AAAAAAAAAAAAAAGD//88AAAAAAHD//78AAAAAAAAAAAAAAM///58AAAAAAN///4AAAAAAAAAAAAAAQP///2AAAAAAYP///0AAAAAAAAAAAAAAv////zAAAAAA3////xAAAAAAAAAAAABA////7wAAAABg////zwAAAAAAAAAAAACv////vwAAAADf////nwAAAAAAAAAAACD/////zxAAAED/////zxAAAAAAAAAAAHD//////48AAID//////3AAAAAAAAAAAID//////78AAK///////4AAAAAAAAAAAFD//////3AAAHD//////2AAAAAAAAAAAACf////vxAAAAC/////nwAAAAAAAAAAAAAAMIBAAAAAAAAAQIAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQBAAAAAAAABAQBAAAAAAAAAAAAAAIM///+9gAAAAMO///+8wAAAAAAAAAAAAr//////vEAAA3//////fAAAAAAAAAAAA////////QAAA////////AAAAAAAAAAAA3///////MAAA////////AAAAAAAAAAAAYP/////fAAAAYP////+/AAAAAAAAAAAAEP////9gAAAAMP////9QAAAAAAAAAAAAQP///98AAAAAYP///98AAAAAAAAAAAAAgP///3AAAAAAj////2AAAAAAAAAAAAAAr///7xAAAAAAz///3wAAAAAAAAAAAAAA7///gAAAAAAA////YAAAAAAAAAAAAAAg///vEAAAAABA///fAAAAAAAAAAAAAABQ//+PAAAAAACA//+AAAAAAAAAAAAAAABAgIAgAAAAAABQgIAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwr+//z4AQAAAAAAAAAAAAAAAAAAAAAGD////////PEAAAAAAAAAAAAAAAAAAAIO//////////nwAAAAAAAAAAAAAAAAAAcP///////////xAAAAAAAAAAAAAAAAAAr////////////0AAAAAAAAAAAAAAAAAAr////////////0AAAAAAAAAAAAAAAAAAcP///////////xAAAAAAAAAAAAAAAAAAEO//////////nwAAAAAAAAAAAAAAAAAAAFD////////PEAAAAAAAAAAAAAAAAAAAAAAwn+//z4AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACP//+/EAAAAGDv/88wAAAAMN//71AAAHD/////nwAAMP////+/AAAQ7////+8QAL//////vwAAgP//////AABA//////9AAI//////rwAAYP/////vAAAg//////8wACDv///vMAAAAM////9gAAAAj////58AAAAQYHAgAAAAAABQgDAAAAAAAECAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////////////////////////////////////////////////////////////0BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIlAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAMJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAED/////////////////AAAAAAAAAAAAAED/////////////////AAAAAAAAAAAAAED/////////////////AAAAAAAAAAAAAED///9AQEBAQEBAQEBAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAECUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////8AAAAAAAAAAAAA//////////////////8AAAAAAAAAAAAA//////////////////8AAAAAAAAAAAAAQEBAQEBAQEBAQHD///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAABQlAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP////////////////8AAAAAAAAAAAAAQP////////////////8AAAAAAAAAAAAAQP////////////////8AAAAAAAAAAAAAEEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYJQAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHCUAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA/////////////////wAAAAAAAAAAAABA/////////////////wAAAAAAAAAAAABA/////////////////wAAAAAAAAAAAABA////QEBAQEBAQEBAQAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAACQlAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAP//////////////////AAAAAAAAAAAAAP//////////////////AAAAAAAAAAAAAP//////////////////AAAAAAAAAAAAAEBAQEBAQEBAQEBw////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAsJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////////////////////////////////////////////////////////////////////////////////////////QEBAQEBAQEBAQHD///9AQEBAQEBAQEBAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAAAAAAAAAAAAAAAED///8AAAAAAAAAAAAANCUAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAAAAAAAAAAAAAABA////AAAAAAAAAAAAAP///////////////////////////////////////////////////////////////////////////////////////////////0BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwlAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////9AQEBAQEBAQEBAcP///0BAQEBAQEBAQEAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAAAAAAAAAAAAAAAAQP///wAAAAAAAAAAAABQJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/////////////////////////////////////////////////////////////////gICAgICAgICAgICAgICAgICAgICAgICAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUSUAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAFQlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAgP////////////////////8AAAAAAAAAgP////////////////////8AAAAAAAAAgP////////////////////8AAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAAAAAAAAAAAAAAAAAAAAAAAAgP//vwAAAL+/v7+/v7+/v78AAAAAAAAAgP//vwAAAP////////////8AAAAAAAAAgP//vwAAAP////////////8AAAAAAAAAgP//vwAAAP///5+AgICAgIAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAAAAAAAAAAAAgP//vwAAAP///0AAAAAAAABXJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQEAwAAAAAAAAv/////////////////////+/AAAAAAAAv/////////////////////+/AAAAAAAAv/////////////////////+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAj7+/v7+/v7+/v78wAACA//+/AAAAAAAAv/////////////9AAACA//+/AAAAAAAAv/////////////9AAACA//+/AAAAAAAAYICAgICAgJ////9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAAAAAAAAAAAAAAED///9AAACA//+/AAAAWiUAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////QAAAAAAAAAAAAAAAAACA//+/AAAA////cEBAQEBAQAAAAAAAAACA//+/AAAA/////////////wAAAAAAAACA//+/AAAA/////////////wAAAAAAAACA//+/AAAA/////////////wAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA//+/AAAAAAAAAAAAAAAAAAAAAAAAAACA///vv7+/v7+/v7+/v7+/vwAAAAAAAACA/////////////////////wAAAAAAAACA/////////////////////wAAAAAAAABAgICAgICAgICAgICAgICAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0lAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAAAAAAAAAAQP///0AAAID//78AAAAAAAAwQEBAQEBAcP///0AAAID//78AAAAAAAC//////////////0AAAID//78AAAAAAAC//////////////0AAAID//78AAAAAAAC//////////////0AAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAAAAAAAAAAAAAAAAAAAAAID//78AAAAAAACPv7+/v7+/v7+/v7+/v9///78AAAAAAAC//////////////////////78AAAAAAAC//////////////////////78AAAAAAABggICAgICAgICAgICAgICAgGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAJQAA////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhCUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQP///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////4glAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+MJQAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAAAAAAABA////////////////QAAAAAAAkCUAAAAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////wAAAAAAAAAAAAAAAL///////////////5ElAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL+/AACPvzAAj78wAI+/YABgv2AAYL8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAEBAAAAwQBAAMEAQADBAIAAgQCAAIEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL+/AACPvzAAj78wAI+/YABgv2AAYL8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAICAAABggCAAYIAgAGCAQABAgEAAQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAAABggCAAYIAgAGCAQABAgEAAQIAAAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAICAAABggCAAYIAgAGCAQABAgEAAQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAAABggCAAYIAgAGCAQABAgEAAQIAAAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAL+/AACPvzAAj78wAI+/YABgv2AAYL8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAwQBAAMEAQADBAIAAgQCAAIEAAAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAL+/AACPvzAAj78wAI+/YABgv2AAYL8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAEBAAAAwQBAAMEAQADBAIAAgQCAAIEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL+/AACPvzAAj78wAI+/YABgv2AAYL8AAP//AAC//0AAv/9AAL//gACA/4AAgP8AAP//AAC//0AAv/9AAL//gACA/4AAgP+SJQAA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAQEC/v0BAn79gQJ+/YECfv4BAgL+AQIC/AAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/v79AQL+/YECfv2BAn79gQIC/gECAv4BA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAQEC/v0BAn79gQJ+/YECfv4BAgL+AQIC/AAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/gICAgICAgICAgICAgICAgICAgICAgICA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAgICAgICAgICAgICAgICAgICAgICAgICAAAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/gICAgICAgICAgICAgICAgICAgICAgICA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAgICAgICAgICAgICAgICAgICAgICAgICAAAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/QEC/v0BAn79gQJ+/YECfv4BAgL+AQIC///8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAv79AQL+/YECfv2BAn79gQIC/gECAv4BAAAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/QEC/v0BAn79gQJ+/YECfv4BAgL+AQIC///8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAAAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID///8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAAAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/v79AQL+/YECfv2BAn79gQIC/gECAv4BA//8AAP//QAC//0AAv/9AAID/gACA/4AA//8AAP//QAC//0AAv/9AAID/gACA/4AAQEC/v0BAn79gQJ+/YECfv4BAgL+AQIC/AAD//wAAv/9AAL//QAC//4AAgP+AAID/AAD//wAAv/9AAL//QAC//4AAgP+AAID/kyUAAP//////////////////////////////////////////////////////////////////QED//3BAz/9wQM//cECf/59An/+fQP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//v7///8+/7//Pv+//z7/f/9+/3//fv///////////////////////////////////////////////////////////////////QED//3BAz/9wQM//cECf/59An/+fQP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//gID//5+A3/+fgN//n4C//7+Av/+/gP//////////////////////////////////////////////////////////////////gID//5+A3/+fgN//n4C//7+Av/+/gP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//gID//5+A3/+fgN//n4C//7+Av/+/gP//////////////////////////////////////////////////////////////////gID//5+A3/+fgN//n4C//7+Av/+/gP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//QED//3BAz/9wQM//cECf/59An/+fQP//////////////////////////////////////////////////////////////////v7///8+/7//Pv+//z7/f/9+/3//fv///AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//QED//3BAz/9wQM//cECf/59An/+fQP//////////////////////////////////////////////////////////////////////////////////////////////////AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//////////////////////////////////////////////////////////////////////////////////////////////////AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//v7///8+/7//Pv+//z7/f/9+/3//fv///////////////////////////////////////////////////////////////////QED//3BAz/9wQM//cECf/59An/+fQP//AAD//0AAv/9AAL//QACA/4AAgP+AAP//AAD//0AAv/9AAL//QACA/4AAgP+AAKAlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEBAQEBAQEBAQEBAQEBAQEBAQEBAQCAAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAv////////////////////////////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADPJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgQAAAAAAAAAAAAAAAAAAAAAAAABBwz//////vr2AAAAAAAAAAAAAAAAAAgO/////////////fQAAAAAAAAAAAABDP/////////////////4AAAAAAAAAAEM////////////////////+AAAAAAAAAv///////////////////////UAAAAABg////////////////////////7xAAAADf/////////////////////////3AAADD//////////////////////////98AAID///////////////////////////8gAL////////////////////////////9AAL////////////////////////////9gAL////////////////////////////9QAK////////////////////////////9AAID///////////////////////////8QADD//////////////////////////88AAAC//////////////////////////2AAAABA////////////////////////3wAAAAAAn///////////////////////QAAAAAAAEM////////////////////9gAAAAAAAAABCv////////////////72AAAAAAAAAAAAAAYN////////////+/IAAAAAAAAAAAAAAAAABgn9////+/jzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", FALLBACK_GLYPH, FONT, SHADE_ALPHA, PNG_SIG, CRC_TABLE; -var init_ansiToPng = __esm(() => { - init_stringWidth(); - init_ansiToSvg(); - GLYPH_BYTES = GLYPH_W * GLYPH_H; - FALLBACK_GLYPH = makeFallbackGlyph(); - FONT = decodeFont(); - SHADE_ALPHA = { - 9617: 0.25, - 9618: 0.5, - 9619: 0.75, - 9608: 1 - }; - PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); - CRC_TABLE = makeCrcTable(); -}); - -// src/utils/screenshotClipboard.ts -import { mkdir as mkdir38, unlink as unlink20, writeFile as writeFile42 } from "fs/promises"; -import { tmpdir as tmpdir11 } from "os"; -import { join as join137 } from "path"; -async function copyAnsiToClipboard(ansiText, options2) { - try { - const tempDir = join137(tmpdir11(), "claude-code-screenshots"); - await mkdir38(tempDir, { recursive: true }); - const pngPath = join137(tempDir, `screenshot-${Date.now()}.png`); - const pngBuffer = ansiToPng(ansiText, options2); - await writeFile42(pngPath, pngBuffer); - const result = await copyPngToClipboard(pngPath); - try { - await unlink20(pngPath); - } catch {} - return result; - } catch (error46) { - logError2(error46); - return { - success: false, - message: `Failed to copy screenshot: ${error46 instanceof Error ? error46.message : "Unknown error"}` - }; - } -} -async function copyPngToClipboard(pngPath) { - const platform6 = getPlatform(); - if (platform6 === "macos") { - const escapedPath = pngPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\""); - const script = `set the clipboard to (read (POSIX file "${escapedPath}") as \xABclass PNGf\xBB)`; - const result = await execFileNoThrowWithCwd("osascript", ["-e", script], { - timeout: 5000 - }); - if (result.code === 0) { - return { success: true, message: "Screenshot copied to clipboard" }; - } - return { - success: false, - message: `Failed to copy to clipboard: ${result.stderr}` - }; - } - if (platform6 === "linux") { - const xclipResult = await execFileNoThrowWithCwd("xclip", ["-selection", "clipboard", "-t", "image/png", "-i", pngPath], { timeout: 5000 }); - if (xclipResult.code === 0) { - return { success: true, message: "Screenshot copied to clipboard" }; - } - const xselResult = await execFileNoThrowWithCwd("xsel", ["--clipboard", "--input", "--type", "image/png"], { timeout: 5000 }); - if (xselResult.code === 0) { - return { success: true, message: "Screenshot copied to clipboard" }; - } - return { - success: false, - message: "Failed to copy to clipboard. Please install xclip or xsel: sudo apt install xclip" - }; - } - if (platform6 === "windows") { - const psScript = `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::SetImage([System.Drawing.Image]::FromFile('${pngPath.replace(/'/g, "''")}'))`; - const result = await execFileNoThrowWithCwd("powershell", ["-NoProfile", "-Command", psScript], { timeout: 5000 }); - if (result.code === 0) { - return { success: true, message: "Screenshot copied to clipboard" }; - } - return { - success: false, - message: `Failed to copy to clipboard: ${result.stderr}` - }; - } - return { - success: false, - message: `Screenshot to clipboard is not supported on ${platform6}` - }; -} -var init_screenshotClipboard = __esm(() => { - init_ansiToPng(); - init_execFileNoThrow(); - init_log2(); - init_platform2(); -}); - -// src/utils/stats.ts -import { open as open17 } from "fs/promises"; -import { basename as basename41, join as join138, sep as sep34 } from "path"; -async function processSessionFiles(sessionFiles, options2 = {}) { - const { fromDate, toDate: toDate2 } = options2; - const fs13 = getFsImplementation(); - const dailyActivityMap = new Map; - const dailyModelTokensMap = new Map; - const sessions = []; - const hourCounts = new Map; - let totalMessages = 0; - let totalSpeculationTimeSavedMs = 0; - const modelUsageAgg = {}; - const shotDistributionMap = undefined; - const sessionsWithShotCount = new Set; - const BATCH_SIZE = 20; - for (let i6 = 0;i6 < sessionFiles.length; i6 += BATCH_SIZE) { - const batch = sessionFiles.slice(i6, i6 + BATCH_SIZE); - const results = await Promise.all(batch.map(async (sessionFile) => { - try { - if (fromDate) { - let fileSize = 0; - try { - const fileStat = await fs13.stat(sessionFile); - const fileModifiedDate = toDateString(fileStat.mtime); - if (isDateBefore(fileModifiedDate, fromDate)) { - return { - sessionFile, - entries: null, - error: null, - skipped: true - }; - } - fileSize = fileStat.size; - } catch {} - if (fileSize > 65536) { - const startDate = await readSessionStartDate(sessionFile); - if (startDate && isDateBefore(startDate, fromDate)) { - return { - sessionFile, - entries: null, - error: null, - skipped: true - }; - } - } - } - const entries = await readJSONLFile(sessionFile); - return { sessionFile, entries, error: null, skipped: false }; - } catch (error46) { - return { sessionFile, entries: null, error: error46, skipped: false }; - } - })); - for (const { sessionFile, entries, error: error46, skipped } of results) { - if (skipped) - continue; - if (error46 || !entries) { - logForDebugging(`Failed to read session file ${sessionFile}: ${errorMessage(error46)}`); - continue; - } - const sessionId = basename41(sessionFile, ".jsonl"); - const messages = []; - for (const entry of entries) { - if (isTranscriptMessage(entry)) { - messages.push(entry); - } else if (entry.type === "speculation-accept") { - totalSpeculationTimeSavedMs += entry.timeSavedMs; - } - } - if (messages.length === 0) - continue; - const isSubagentFile = sessionFile.includes(`${sep34}subagents${sep34}`); - if (false) {} - const mainMessages = isSubagentFile ? messages : messages.filter((m4) => !m4.isSidechain); - if (mainMessages.length === 0) - continue; - const firstMessage = mainMessages[0]; - const lastMessage = mainMessages.at(-1); - const firstTimestamp = new Date(firstMessage.timestamp); - const lastTimestamp = new Date(lastMessage.timestamp); - if (isNaN(firstTimestamp.getTime()) || isNaN(lastTimestamp.getTime())) { - logForDebugging(`Skipping session with invalid timestamp: ${sessionFile}`); - continue; - } - const dateKey = toDateString(firstTimestamp); - if (fromDate && isDateBefore(dateKey, fromDate)) - continue; - if (toDate2 && isDateBefore(toDate2, dateKey)) - continue; - const existing = dailyActivityMap.get(dateKey) || { - date: dateKey, - messageCount: 0, - sessionCount: 0, - toolCallCount: 0 - }; - if (!isSubagentFile) { - const duration3 = lastTimestamp.getTime() - firstTimestamp.getTime(); - sessions.push({ - sessionId, - duration: duration3, - messageCount: mainMessages.length, - timestamp: firstMessage.timestamp - }); - totalMessages += mainMessages.length; - existing.sessionCount++; - existing.messageCount += mainMessages.length; - const hour = firstTimestamp.getHours(); - hourCounts.set(hour, (hourCounts.get(hour) || 0) + 1); - } - if (!isSubagentFile || dailyActivityMap.has(dateKey)) { - dailyActivityMap.set(dateKey, existing); - } - for (const message of mainMessages) { - if (message.type === "assistant") { - const content = message.message?.content; - if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "tool_use") { - const activity = dailyActivityMap.get(dateKey); - if (activity) { - activity.toolCallCount++; - } - } - } - } - if (message.message?.usage) { - const usage = message.message.usage; - const model = message.message.model || "unknown"; - if (model === SYNTHETIC_MODEL) { - continue; - } - if (!modelUsageAgg[model]) { - modelUsageAgg[model] = { - inputTokens: 0, - outputTokens: 0, - cacheReadInputTokens: 0, - cacheCreationInputTokens: 0, - webSearchRequests: 0, - costUSD: 0, - contextWindow: 0, - maxOutputTokens: 0 - }; - } - modelUsageAgg[model].inputTokens += usage.input_tokens || 0; - modelUsageAgg[model].outputTokens += usage.output_tokens || 0; - modelUsageAgg[model].cacheReadInputTokens += usage.cache_read_input_tokens || 0; - modelUsageAgg[model].cacheCreationInputTokens += usage.cache_creation_input_tokens || 0; - const totalTokens = (usage.input_tokens || 0) + (usage.output_tokens || 0); - if (totalTokens > 0) { - const dayTokens = dailyModelTokensMap.get(dateKey) || {}; - dayTokens[model] = (dayTokens[model] || 0) + totalTokens; - dailyModelTokensMap.set(dateKey, dayTokens); - } - } - } - } - } - } - return { - dailyActivity: Array.from(dailyActivityMap.values()).sort((a5, b5) => a5.date.localeCompare(b5.date)), - dailyModelTokens: Array.from(dailyModelTokensMap.entries()).map(([date6, tokensByModel]) => ({ date: date6, tokensByModel })).sort((a5, b5) => a5.date.localeCompare(b5.date)), - modelUsage: modelUsageAgg, - sessionStats: sessions, - hourCounts: Object.fromEntries(hourCounts), - totalMessages, - totalSpeculationTimeSavedMs, - ...{} - }; -} -async function getAllSessionFiles() { - const projectsDir = getProjectsDir2(); - const fs13 = getFsImplementation(); - let allEntries; - try { - allEntries = await fs13.readdir(projectsDir); - } catch (e4) { - if (isENOENT(e4)) - return []; - throw e4; - } - const projectDirs = allEntries.filter((dirent) => dirent.isDirectory()).map((dirent) => join138(projectsDir, dirent.name)); - const projectResults = await Promise.all(projectDirs.map(async (projectDir) => { - try { - const entries = await fs13.readdir(projectDir); - const mainFiles = entries.filter((dirent) => dirent.isFile() && dirent.name.endsWith(".jsonl")).map((dirent) => join138(projectDir, dirent.name)); - const sessionDirs = entries.filter((dirent) => dirent.isDirectory()); - const subagentResults = await Promise.all(sessionDirs.map(async (sessionDir) => { - const subagentsDir = join138(projectDir, sessionDir.name, "subagents"); - try { - const subagentEntries = await fs13.readdir(subagentsDir); - return subagentEntries.filter((dirent) => dirent.isFile() && dirent.name.endsWith(".jsonl") && dirent.name.startsWith("agent-")).map((dirent) => join138(subagentsDir, dirent.name)); - } catch { - return []; - } - })); - return [...mainFiles, ...subagentResults.flat()]; - } catch (error46) { - logForDebugging(`Failed to read project directory ${projectDir}: ${errorMessage(error46)}`); - return []; - } - })); - return projectResults.flat(); -} -function cacheToStats(cache8, todayStats) { - const dailyActivityMap = new Map; - for (const day of cache8.dailyActivity) { - dailyActivityMap.set(day.date, { ...day }); - } - if (todayStats) { - for (const day of todayStats.dailyActivity) { - const existing = dailyActivityMap.get(day.date); - if (existing) { - existing.messageCount += day.messageCount; - existing.sessionCount += day.sessionCount; - existing.toolCallCount += day.toolCallCount; - } else { - dailyActivityMap.set(day.date, { ...day }); - } - } - } - const dailyModelTokensMap = new Map; - for (const day of cache8.dailyModelTokens) { - dailyModelTokensMap.set(day.date, { ...day.tokensByModel }); - } - if (todayStats) { - for (const day of todayStats.dailyModelTokens) { - const existing = dailyModelTokensMap.get(day.date); - if (existing) { - for (const [model, tokens] of Object.entries(day.tokensByModel)) { - existing[model] = (existing[model] || 0) + tokens; - } - } else { - dailyModelTokensMap.set(day.date, { ...day.tokensByModel }); - } - } - } - const modelUsage = { ...cache8.modelUsage }; - if (todayStats) { - for (const [model, usage] of Object.entries(todayStats.modelUsage)) { - if (modelUsage[model]) { - modelUsage[model] = { - inputTokens: modelUsage[model].inputTokens + usage.inputTokens, - outputTokens: modelUsage[model].outputTokens + usage.outputTokens, - cacheReadInputTokens: modelUsage[model].cacheReadInputTokens + usage.cacheReadInputTokens, - cacheCreationInputTokens: modelUsage[model].cacheCreationInputTokens + usage.cacheCreationInputTokens, - webSearchRequests: modelUsage[model].webSearchRequests + usage.webSearchRequests, - costUSD: modelUsage[model].costUSD + usage.costUSD, - contextWindow: Math.max(modelUsage[model].contextWindow, usage.contextWindow), - maxOutputTokens: Math.max(modelUsage[model].maxOutputTokens, usage.maxOutputTokens) - }; - } else { - modelUsage[model] = { ...usage }; - } - } - } - const hourCountsMap = new Map; - for (const [hour, count4] of Object.entries(cache8.hourCounts)) { - hourCountsMap.set(parseInt(hour, 10), count4); - } - if (todayStats) { - for (const [hour, count4] of Object.entries(todayStats.hourCounts)) { - const hourNum = parseInt(hour, 10); - hourCountsMap.set(hourNum, (hourCountsMap.get(hourNum) || 0) + count4); - } - } - const dailyActivityArray = Array.from(dailyActivityMap.values()).sort((a5, b5) => a5.date.localeCompare(b5.date)); - const streaks = calculateStreaks(dailyActivityArray); - const dailyModelTokens = Array.from(dailyModelTokensMap.entries()).map(([date6, tokensByModel]) => ({ date: date6, tokensByModel })).sort((a5, b5) => a5.date.localeCompare(b5.date)); - const totalSessions = cache8.totalSessions + (todayStats?.sessionStats.length || 0); - const totalMessages = cache8.totalMessages + (todayStats?.totalMessages || 0); - let longestSession = cache8.longestSession; - if (todayStats) { - for (const session2 of todayStats.sessionStats) { - if (!longestSession || session2.duration > longestSession.duration) { - longestSession = session2; - } - } - } - let firstSessionDate = cache8.firstSessionDate; - let lastSessionDate = null; - if (todayStats) { - for (const session2 of todayStats.sessionStats) { - if (!firstSessionDate || session2.timestamp < firstSessionDate) { - firstSessionDate = session2.timestamp; - } - if (!lastSessionDate || session2.timestamp > lastSessionDate) { - lastSessionDate = session2.timestamp; - } - } - } - if (!lastSessionDate && dailyActivityArray.length > 0) { - lastSessionDate = dailyActivityArray.at(-1).date; - } - const peakActivityDay = dailyActivityArray.length > 0 ? dailyActivityArray.reduce((max2, d4) => d4.messageCount > max2.messageCount ? d4 : max2).date : null; - const peakActivityHour = hourCountsMap.size > 0 ? Array.from(hourCountsMap.entries()).reduce((max2, [hour, count4]) => count4 > max2[1] ? [hour, count4] : max2)[0] : null; - const totalDays = firstSessionDate && lastSessionDate ? Math.ceil((new Date(lastSessionDate).getTime() - new Date(firstSessionDate).getTime()) / (1000 * 60 * 60 * 24)) + 1 : 0; - const totalSpeculationTimeSavedMs = cache8.totalSpeculationTimeSavedMs + (todayStats?.totalSpeculationTimeSavedMs || 0); - const result = { - totalSessions, - totalMessages, - totalDays, - activeDays: dailyActivityMap.size, - streaks, - dailyActivity: dailyActivityArray, - dailyModelTokens, - longestSession, - modelUsage, - firstSessionDate, - lastSessionDate, - peakActivityDay, - peakActivityHour, - totalSpeculationTimeSavedMs - }; - if (false) {} - return result; -} -async function aggregateClaudeCodeStats() { - const allSessionFiles = await getAllSessionFiles(); - if (allSessionFiles.length === 0) { - return getEmptyStats(); - } - const updatedCache = await withStatsCacheLock(async () => { - const cache8 = await loadStatsCache(); - const yesterday = getYesterdayDateString(); - let result = cache8; - if (!cache8.lastComputedDate) { - logForDebugging("Stats cache empty, processing all historical data"); - const historicalStats = await processSessionFiles(allSessionFiles, { - toDate: yesterday - }); - if (historicalStats.sessionStats.length > 0 || historicalStats.dailyActivity.length > 0) { - result = mergeCacheWithNewStats(cache8, historicalStats, yesterday); - await saveStatsCache(result); - } - } else if (isDateBefore(cache8.lastComputedDate, yesterday)) { - const nextDay = getNextDay(cache8.lastComputedDate); - logForDebugging(`Stats cache stale (${cache8.lastComputedDate}), processing ${nextDay} to ${yesterday}`); - const newStats = await processSessionFiles(allSessionFiles, { - fromDate: nextDay, - toDate: yesterday - }); - if (newStats.sessionStats.length > 0 || newStats.dailyActivity.length > 0) { - result = mergeCacheWithNewStats(cache8, newStats, yesterday); - await saveStatsCache(result); - } else { - result = { ...cache8, lastComputedDate: yesterday }; - await saveStatsCache(result); - } - } - return result; - }); - const today = getTodayDateString(); - const todayStats = await processSessionFiles(allSessionFiles, { - fromDate: today, - toDate: today - }); - return cacheToStats(updatedCache, todayStats); -} -async function aggregateClaudeCodeStatsForRange(range) { - if (range === "all") { - return aggregateClaudeCodeStats(); - } - const allSessionFiles = await getAllSessionFiles(); - if (allSessionFiles.length === 0) { - return getEmptyStats(); - } - const today = new Date; - const daysBack = range === "7d" ? 7 : 30; - const fromDate = new Date(today); - fromDate.setDate(today.getDate() - daysBack + 1); - const fromDateStr = toDateString(fromDate); - const stats = await processSessionFiles(allSessionFiles, { - fromDate: fromDateStr - }); - return processedStatsToClaudeCodeStats(stats); -} -function processedStatsToClaudeCodeStats(stats) { - const dailyActivitySorted = stats.dailyActivity.slice().sort((a5, b5) => a5.date.localeCompare(b5.date)); - const dailyModelTokensSorted = stats.dailyModelTokens.slice().sort((a5, b5) => a5.date.localeCompare(b5.date)); - const streaks = calculateStreaks(dailyActivitySorted); - let longestSession = null; - for (const session2 of stats.sessionStats) { - if (!longestSession || session2.duration > longestSession.duration) { - longestSession = session2; - } - } - let firstSessionDate = null; - let lastSessionDate = null; - for (const session2 of stats.sessionStats) { - if (!firstSessionDate || session2.timestamp < firstSessionDate) { - firstSessionDate = session2.timestamp; - } - if (!lastSessionDate || session2.timestamp > lastSessionDate) { - lastSessionDate = session2.timestamp; - } - } - const peakActivityDay = dailyActivitySorted.length > 0 ? dailyActivitySorted.reduce((max2, d4) => d4.messageCount > max2.messageCount ? d4 : max2).date : null; - const hourEntries = Object.entries(stats.hourCounts); - const peakActivityHour = hourEntries.length > 0 ? parseInt(hourEntries.reduce((max2, [hour, count4]) => count4 > parseInt(max2[1].toString()) ? [hour, count4] : max2)[0], 10) : null; - const totalDays = firstSessionDate && lastSessionDate ? Math.ceil((new Date(lastSessionDate).getTime() - new Date(firstSessionDate).getTime()) / (1000 * 60 * 60 * 24)) + 1 : 0; - const result = { - totalSessions: stats.sessionStats.length, - totalMessages: stats.totalMessages, - totalDays, - activeDays: stats.dailyActivity.length, - streaks, - dailyActivity: dailyActivitySorted, - dailyModelTokens: dailyModelTokensSorted, - longestSession, - modelUsage: stats.modelUsage, - firstSessionDate, - lastSessionDate, - peakActivityDay, - peakActivityHour, - totalSpeculationTimeSavedMs: stats.totalSpeculationTimeSavedMs - }; - if (false) {} - return result; -} -function getNextDay(dateStr) { - const date6 = new Date(dateStr); - date6.setDate(date6.getDate() + 1); - return toDateString(date6); -} -function calculateStreaks(dailyActivity) { - if (dailyActivity.length === 0) { - return { - currentStreak: 0, - longestStreak: 0, - currentStreakStart: null, - longestStreakStart: null, - longestStreakEnd: null - }; - } - const today = new Date; - today.setHours(0, 0, 0, 0); - let currentStreak = 0; - let currentStreakStart = null; - const checkDate = new Date(today); - const activeDates = new Set(dailyActivity.map((d4) => d4.date)); - while (true) { - const dateStr = toDateString(checkDate); - if (!activeDates.has(dateStr)) { - break; - } - currentStreak++; - currentStreakStart = dateStr; - checkDate.setDate(checkDate.getDate() - 1); - } - let longestStreak = 0; - let longestStreakStart = null; - let longestStreakEnd = null; - if (dailyActivity.length > 0) { - const sortedDates = Array.from(activeDates).sort(); - let tempStreak = 1; - let tempStart = sortedDates[0]; - for (let i6 = 1;i6 < sortedDates.length; i6++) { - const prevDate = new Date(sortedDates[i6 - 1]); - const currDate = new Date(sortedDates[i6]); - const dayDiff = Math.round((currDate.getTime() - prevDate.getTime()) / (1000 * 60 * 60 * 24)); - if (dayDiff === 1) { - tempStreak++; - } else { - if (tempStreak > longestStreak) { - longestStreak = tempStreak; - longestStreakStart = tempStart; - longestStreakEnd = sortedDates[i6 - 1]; - } - tempStreak = 1; - tempStart = sortedDates[i6]; - } - } - if (tempStreak > longestStreak) { - longestStreak = tempStreak; - longestStreakStart = tempStart; - longestStreakEnd = sortedDates.at(-1); - } - } - return { - currentStreak, - longestStreak, - currentStreakStart, - longestStreakStart, - longestStreakEnd - }; -} -async function readSessionStartDate(filePath) { - try { - const fd2 = await open17(filePath, "r"); - try { - const buf = Buffer.allocUnsafe(4096); - const { bytesRead } = await fd2.read(buf, 0, buf.length, 0); - if (bytesRead === 0) - return null; - const head = buf.toString("utf8", 0, bytesRead); - const lastNewline = head.lastIndexOf(` -`); - if (lastNewline < 0) - return null; - for (const line of head.slice(0, lastNewline).split(` -`)) { - if (!line) - continue; - let entry; - try { - entry = jsonParse(line); - } catch { - continue; - } - if (typeof entry.type !== "string") - continue; - if (!TRANSCRIPT_MESSAGE_TYPES.has(entry.type)) - continue; - if (entry.isSidechain === true) - continue; - if (typeof entry.timestamp !== "string") - return null; - const date6 = new Date(entry.timestamp); - if (Number.isNaN(date6.getTime())) - return null; - return toDateString(date6); - } - return null; - } finally { - await fd2.close(); - } - } catch { - return null; - } -} -function getEmptyStats() { - return { - totalSessions: 0, - totalMessages: 0, - totalDays: 0, - activeDays: 0, - streaks: { - currentStreak: 0, - longestStreak: 0, - currentStreakStart: null, - longestStreakStart: null, - longestStreakEnd: null - }, - dailyActivity: [], - dailyModelTokens: [], - longestSession: null, - modelUsage: {}, - firstSessionDate: null, - lastSessionDate: null, - peakActivityDay: null, - peakActivityHour: null, - totalSpeculationTimeSavedMs: 0 - }; -} -var TRANSCRIPT_MESSAGE_TYPES; -var init_stats = __esm(() => { - init_debug(); - init_errors(); - init_fsOperations(); - init_json(); - init_messages9(); - init_sessionStorage(); - init_shellToolUtils(); - init_slowOperations(); - init_statsCache(); - TRANSCRIPT_MESSAGE_TYPES = new Set([ - "user", - "assistant", - "attachment", - "system", - "progress" - ]); -}); - -// src/components/Stats.tsx -function formatPeakDay(dateStr) { - const date6 = new Date(dateStr); - return date6.toLocaleDateString("en-US", { - month: "short", - day: "numeric" - }); -} -function getNextDateRange(current) { - const currentIndex = DATE_RANGE_ORDER.indexOf(current); - return DATE_RANGE_ORDER[(currentIndex + 1) % DATE_RANGE_ORDER.length]; -} -function createAllTimeStatsPromise() { - return aggregateClaudeCodeStatsForRange("all").then((data) => { - if (!data || data.totalSessions === 0) { - return { - type: "empty" - }; - } - return { - type: "success", - data - }; - }).catch((err2) => { - const message = err2 instanceof Error ? err2.message : "Failed to load stats"; - return { - type: "error", - message - }; - }); -} -function Stats(t0) { - const $2 = import_compiler_runtime277.c(4); - const { - onClose - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = createAllTimeStatsPromise(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const allTimePromise = t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - children: " Loading your Claude Code stats\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[1] = t22; - } else { - t22 = $2[1]; - } - let t32; - if ($2[2] !== onClose) { - t32 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(import_react193.Suspense, { - fallback: t22, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(StatsContent, { - allTimePromise, - onClose - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = onClose; - $2[3] = t32; - } else { - t32 = $2[3]; - } - return t32; -} -function StatsContent(t0) { - const $2 = import_compiler_runtime277.c(34); - const { - allTimePromise, - onClose - } = t0; - const allTimeResult = import_react193.use(allTimePromise); - const [dateRange, setDateRange] = import_react193.useState("all"); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = {}; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const [statsCache, setStatsCache] = import_react193.useState(t1); - const [isLoadingFiltered, setIsLoadingFiltered] = import_react193.useState(false); - const [activeTab, setActiveTab] = import_react193.useState("Overview"); - const [copyStatus, setCopyStatus] = import_react193.useState(null); - let t22; - let t32; - if ($2[1] !== dateRange || $2[2] !== statsCache) { - t22 = () => { - if (dateRange === "all") { - return; - } - if (statsCache[dateRange]) { - return; - } - let cancelled = false; - setIsLoadingFiltered(true); - aggregateClaudeCodeStatsForRange(dateRange).then((data) => { - if (!cancelled) { - setStatsCache((prev) => ({ - ...prev, - [dateRange]: data - })); - setIsLoadingFiltered(false); - } - }).catch(() => { - if (!cancelled) { - setIsLoadingFiltered(false); - } - }); - return () => { - cancelled = true; - }; - }; - t32 = [dateRange, statsCache]; - $2[1] = dateRange; - $2[2] = statsCache; - $2[3] = t22; - $2[4] = t32; - } else { - t22 = $2[3]; - t32 = $2[4]; - } - import_react193.useEffect(t22, t32); - const displayStats = dateRange === "all" ? allTimeResult.type === "success" ? allTimeResult.data : null : statsCache[dateRange] ?? (allTimeResult.type === "success" ? allTimeResult.data : null); - const allTimeStats = allTimeResult.type === "success" ? allTimeResult.data : null; - let t4; - if ($2[5] !== onClose) { - t4 = () => { - onClose("Stats dialog dismissed", { - display: "system" - }); - }; - $2[5] = onClose; - $2[6] = t4; - } else { - t4 = $2[6]; - } - const handleClose = t4; - let t5; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t5 = { - context: "Confirmation" - }; - $2[7] = t5; - } else { - t5 = $2[7]; - } - useKeybinding("confirm:no", handleClose, t5); - let t6; - if ($2[8] !== activeTab || $2[9] !== dateRange || $2[10] !== displayStats || $2[11] !== onClose) { - t6 = (input, key2) => { - if (key2.ctrl && (input === "c" || input === "d")) { - onClose("Stats dialog dismissed", { - display: "system" - }); - } - if (key2.tab) { - setActiveTab(_temp167); - } - if (input === "r" && !key2.ctrl && !key2.meta) { - setDateRange(getNextDateRange(dateRange)); - } - if (key2.ctrl && input === "s" && displayStats) { - handleScreenshot(displayStats, activeTab, setCopyStatus); - } - }; - $2[8] = activeTab; - $2[9] = dateRange; - $2[10] = displayStats; - $2[11] = onClose; - $2[12] = t6; - } else { - t6 = $2[12]; - } - use_input_default(t6); - if (allTimeResult.type === "error") { - let t72; - if ($2[13] !== allTimeResult.message) { - t72 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "error", - children: [ - "Failed to load stats: ", - allTimeResult.message - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[13] = allTimeResult.message; - $2[14] = t72; - } else { - t72 = $2[14]; - } - return t72; - } - if (allTimeResult.type === "empty") { - let t72; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t72 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "warning", - children: "No stats available yet. Start using Claude Code!" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[15] = t72; - } else { - t72 = $2[15]; - } - return t72; - } - if (!displayStats || !allTimeStats) { - let t72; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t72 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - children: " Loading stats\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[16] = t72; - } else { - t72 = $2[16]; - } - return t72; - } - let t7; - if ($2[17] !== allTimeStats || $2[18] !== dateRange || $2[19] !== displayStats || $2[20] !== isLoadingFiltered) { - t7 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Tab, { - title: "Overview", - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(OverviewTab, { - stats: displayStats, - allTimeStats, - dateRange, - isLoading: isLoadingFiltered - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[17] = allTimeStats; - $2[18] = dateRange; - $2[19] = displayStats; - $2[20] = isLoadingFiltered; - $2[21] = t7; - } else { - t7 = $2[21]; - } - let t8; - if ($2[22] !== dateRange || $2[23] !== displayStats || $2[24] !== isLoadingFiltered) { - t8 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Tab, { - title: "Models", - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ModelsTab, { - stats: displayStats, - dateRange, - isLoading: isLoadingFiltered - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[22] = dateRange; - $2[23] = displayStats; - $2[24] = isLoadingFiltered; - $2[25] = t8; - } else { - t8 = $2[25]; - } - let t9; - if ($2[26] !== t7 || $2[27] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Tabs, { - title: "", - color: "claude", - defaultTab: "Overview", - children: [ - t7, - t8 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[26] = t7; - $2[27] = t8; - $2[28] = t9; - } else { - t9 = $2[28]; - } - const t10 = copyStatus ? ` \xB7 ${copyStatus}` : ""; - let t11; - if ($2[29] !== t10) { - t11 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Esc to cancel \xB7 r to cycle dates \xB7 ctrl+s to copy", - t10 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[29] = t10; - $2[30] = t11; - } else { - t11 = $2[30]; - } - let t12; - if ($2[31] !== t11 || $2[32] !== t9) { - t12 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Pane, { - color: "claude", - children: [ - t9, - t11 - ] - }, undefined, true, undefined, this); - $2[31] = t11; - $2[32] = t9; - $2[33] = t12; - } else { - t12 = $2[33]; - } - return t12; -} -function _temp167(prev_0) { - return prev_0 === "Overview" ? "Models" : "Overview"; -} -function DateRangeSelector(t0) { - const $2 = import_compiler_runtime277.c(9); - const { - dateRange, - isLoading - } = t0; - let t1; - if ($2[0] !== dateRange) { - t1 = DATE_RANGE_ORDER.map((range, i6) => /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - children: [ - i6 > 0 && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 " - }, undefined, false, undefined, this), - range === dateRange ? /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - bold: true, - color: "claude", - children: DATE_RANGE_LABELS[range] - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - dimColor: true, - children: DATE_RANGE_LABELS[range] - }, undefined, false, undefined, this) - ] - }, range, true, undefined, this)); - $2[0] = dateRange; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - children: t1 - }, undefined, false, undefined, this); - $2[2] = t1; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== isLoading) { - t32 = isLoading && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Spinner, {}, undefined, false, undefined, this); - $2[4] = isLoading; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== t22 || $2[7] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginBottom: 1, - gap: 1, - children: [ - t22, - t32 - ] - }, undefined, true, undefined, this); - $2[6] = t22; - $2[7] = t32; - $2[8] = t4; - } else { - t4 = $2[8]; - } - return t4; -} -function OverviewTab({ - stats, - allTimeStats, - dateRange, - isLoading -}) { - const { - columns: terminalWidth - } = useTerminalSize(); - const modelEntries = Object.entries(stats.modelUsage).sort(([, a5], [, b5]) => b5.inputTokens + b5.outputTokens - (a5.inputTokens + a5.outputTokens)); - const favoriteModel = modelEntries[0]; - const totalTokens = modelEntries.reduce((sum, [, usage]) => sum + usage.inputTokens + usage.outputTokens, 0); - const factoid = import_react193.useMemo(() => generateFunFactoid(stats, totalTokens), [stats, totalTokens]); - const rangeDays = dateRange === "7d" ? 7 : dateRange === "30d" ? 30 : stats.totalDays; - let shotStatsData = null; - if (false) {} - return /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - allTimeStats.dailyActivity.length > 0 && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Ansi, { - children: generateHeatmap(allTimeStats.dailyActivity, { - terminalWidth - }) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(DateRangeSelector, { - dateRange, - isLoading - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - marginBottom: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: favoriteModel && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Favorite model:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - bold: true, - children: renderModelName(favoriteModel[0]) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Total tokens:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: formatNumber(totalTokens) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Sessions:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: formatNumber(stats.totalSessions) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: stats.longestSession && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Longest session:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: formatDuration(stats.longestSession.duration) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Active days: ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: stats.activeDays - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - "/", - rangeDays - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Longest streak:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - bold: true, - children: stats.streaks.longestStreak - }, undefined, false, undefined, this), - " ", - stats.streaks.longestStreak === 1 ? "day" : "days" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: stats.peakActivityDay && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Most active day:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: formatPeakDay(stats.peakActivityDay) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Current streak:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - bold: true, - children: allTimeStats.streaks.currentStreak - }, undefined, false, undefined, this), - " ", - allTimeStats.streaks.currentStreak === 1 ? "day" : "days" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - false, - shotStatsData && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(jsx_dev_runtime358.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - children: "Shot distribution" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - shotStatsData.buckets[0].label, - ":", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: shotStatsData.buckets[0].count - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - " (", - shotStatsData.buckets[0].pct, - "%)" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - shotStatsData.buckets[1].label, - ":", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: shotStatsData.buckets[1].count - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - " (", - shotStatsData.buckets[1].pct, - "%)" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - shotStatsData.buckets[2].label, - ":", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: shotStatsData.buckets[2].count - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - " (", - shotStatsData.buckets[2].pct, - "%)" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - shotStatsData.buckets[3].label, - ":", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: shotStatsData.buckets[3].count - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - " (", - shotStatsData.buckets[3].pct, - "%)" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 28, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - wrap: "truncate", - children: [ - "Avg/session:", - " ", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "claude", - children: shotStatsData.avgShots - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - factoid && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "suggestion", - children: factoid - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -function generateFunFactoid(stats, totalTokens) { - const factoids = []; - if (totalTokens > 0) { - const matchingBooks = BOOK_COMPARISONS.filter((book) => totalTokens >= book.tokens); - for (const book of matchingBooks) { - const times = totalTokens / book.tokens; - if (times >= 2) { - factoids.push(`You've used ~${Math.floor(times)}x more tokens than ${book.name}`); - } else { - factoids.push(`You've used the same number of tokens as ${book.name}`); - } - } - } - if (stats.longestSession) { - const sessionMinutes = stats.longestSession.duration / (1000 * 60); - for (const comparison of TIME_COMPARISONS) { - const ratio = sessionMinutes / comparison.minutes; - if (ratio >= 2) { - factoids.push(`Your longest session is ~${Math.floor(ratio)}x longer than ${comparison.name}`); - } - } - } - if (factoids.length === 0) { - return ""; - } - const randomIndex = Math.floor(Math.random() * factoids.length); - return factoids[randomIndex]; -} -function ModelsTab(t0) { - const $2 = import_compiler_runtime277.c(15); - const { - stats, - dateRange, - isLoading - } = t0; - const { - headerFocused, - focusHeader - } = useTabHeaderFocus(); - const [scrollOffset, setScrollOffset] = import_react193.useState(0); - const { - columns: terminalWidth - } = useTerminalSize(); - const modelEntries = Object.entries(stats.modelUsage).sort(_temp718); - const t1 = !headerFocused; - let t22; - if ($2[0] !== t1) { - t22 = { - isActive: t1 - }; - $2[0] = t1; - $2[1] = t22; - } else { - t22 = $2[1]; - } - use_input_default((_input, key2) => { - if (key2.downArrow && scrollOffset < modelEntries.length - 4) { - setScrollOffset((prev) => Math.min(prev + 2, modelEntries.length - 4)); - } - if (key2.upArrow) { - if (scrollOffset > 0) { - setScrollOffset(_temp814); - } else { - focusHeader(); - } - } - }, t22); - if (modelEntries.length === 0) { - let t33; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t33 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: "No model usage data available" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = t33; - } else { - t33 = $2[2]; - } - return t33; - } - const totalTokens = modelEntries.reduce(_temp914, 0); - const chartOutput = generateTokenChart(stats.dailyModelTokens, modelEntries.map(_temp06), terminalWidth); - const visibleModels = modelEntries.slice(scrollOffset, scrollOffset + 4); - const midpoint = Math.ceil(visibleModels.length / 2); - const leftModels = visibleModels.slice(0, midpoint); - const rightModels = visibleModels.slice(midpoint); - const canScrollUp = scrollOffset > 0; - const canScrollDown = scrollOffset < modelEntries.length - 4; - const showScrollHint = modelEntries.length > 4; - let t32; - if ($2[3] !== dateRange || $2[4] !== isLoading) { - t32 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(DateRangeSelector, { - dateRange, - isLoading - }, undefined, false, undefined, this); - $2[3] = dateRange; - $2[4] = isLoading; - $2[5] = t32; - } else { - t32 = $2[5]; - } - const T0 = ThemedBox_default; - const t5 = "column"; - const t6 = 36; - const t8 = rightModels.map((t7) => { - const [model_1, usage_1] = t7; - return /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ModelEntry, { - model: model_1, - usage: usage_1, - totalTokens - }, model_1, false, undefined, this); - }); - let t9; - if ($2[6] !== T0 || $2[7] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(T0, { - flexDirection: t5, - width: t6, - children: t8 - }, undefined, false, undefined, this); - $2[6] = T0; - $2[7] = t8; - $2[8] = t9; - } else { - t9 = $2[8]; - } - let t10; - if ($2[9] !== canScrollDown || $2[10] !== canScrollUp || $2[11] !== modelEntries || $2[12] !== scrollOffset || $2[13] !== showScrollHint) { - t10 = showScrollHint && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - canScrollUp ? figures_default.arrowUp : " ", - " ", - canScrollDown ? figures_default.arrowDown : " ", - " ", - scrollOffset + 1, - "-", - Math.min(scrollOffset + 4, modelEntries.length), - " of", - " ", - modelEntries.length, - " models (\u2191\u2193 to scroll)" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[9] = canScrollDown; - $2[10] = canScrollUp; - $2[11] = modelEntries; - $2[12] = scrollOffset; - $2[13] = showScrollHint; - $2[14] = t10; - } else { - t10 = $2[14]; - } - return /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - chartOutput && /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - bold: true, - children: "Tokens per Day" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Ansi, { - children: chartOutput.chart - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: chartOutput.xAxisLabels - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - children: chartOutput.legend.map(_temp125) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - t32, - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 36, - children: leftModels.map((t4) => { - const [model_0, usage_0] = t4; - return /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ModelEntry, { - model: model_0, - usage: usage_0, - totalTokens - }, model_0, false, undefined, this); - }) - }, undefined, false, undefined, this), - t9 - ] - }, undefined, true, undefined, this), - t10 - ] - }, undefined, true, undefined, this); -} -function _temp125(item, i6) { - return /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - children: [ - i6 > 0 ? " \xB7 " : "", - /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(Ansi, { - children: item.coloredBullet - }, undefined, false, undefined, this), - " ", - item.model - ] - }, item.model, true, undefined, this); -} -function _temp06(t0) { - const [model] = t0; - return model; -} -function _temp914(sum, t0) { - const [, usage] = t0; - return sum + usage.inputTokens + usage.outputTokens; -} -function _temp814(prev_0) { - return Math.max(prev_0 - 2, 0); -} -function _temp718(t0, t1) { - const [, a5] = t0; - const [, b5] = t1; - return b5.inputTokens + b5.outputTokens - (a5.inputTokens + a5.outputTokens); -} -function ModelEntry(t0) { - const $2 = import_compiler_runtime277.c(21); - const { - model, - usage, - totalTokens - } = t0; - const modelTokens = usage.inputTokens + usage.outputTokens; - const t1 = modelTokens / totalTokens * 100; - let t22; - if ($2[0] !== t1) { - t22 = t1.toFixed(1); - $2[0] = t1; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const percentage = t22; - let t32; - if ($2[2] !== model) { - t32 = renderModelName(model); - $2[2] = model; - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - bold: true, - children: t32 - }, undefined, false, undefined, this); - $2[4] = t32; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== percentage) { - t5 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - "(", - percentage, - "%)" - ] - }, undefined, true, undefined, this); - $2[6] = percentage; - $2[7] = t5; - } else { - t5 = $2[7]; - } - let t6; - if ($2[8] !== t4 || $2[9] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - children: [ - figures_default.bullet, - " ", - t4, - " ", - t5 - ] - }, undefined, true, undefined, this); - $2[8] = t4; - $2[9] = t5; - $2[10] = t6; - } else { - t6 = $2[10]; - } - let t7; - if ($2[11] !== usage.inputTokens) { - t7 = formatNumber(usage.inputTokens); - $2[11] = usage.inputTokens; - $2[12] = t7; - } else { - t7 = $2[12]; - } - let t8; - if ($2[13] !== usage.outputTokens) { - t8 = formatNumber(usage.outputTokens); - $2[13] = usage.outputTokens; - $2[14] = t8; - } else { - t8 = $2[14]; - } - let t9; - if ($2[15] !== t7 || $2[16] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedText, { - color: "subtle", - children: [ - " ", - "In: ", - t7, - " \xB7 Out:", - " ", - t8 - ] - }, undefined, true, undefined, this); - $2[15] = t7; - $2[16] = t8; - $2[17] = t9; - } else { - t9 = $2[17]; - } - let t10; - if ($2[18] !== t6 || $2[19] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime358.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t6, - t9 - ] - }, undefined, true, undefined, this); - $2[18] = t6; - $2[19] = t9; - $2[20] = t10; - } else { - t10 = $2[20]; - } - return t10; -} -function generateTokenChart(dailyTokens, models, terminalWidth) { - if (dailyTokens.length < 2 || models.length === 0) { - return null; - } - const yAxisWidth = 7; - const availableWidth = terminalWidth - yAxisWidth; - const chartWidth = Math.min(52, Math.max(20, availableWidth)); - let recentData; - if (dailyTokens.length >= chartWidth) { - recentData = dailyTokens.slice(-chartWidth); - } else { - const repeatCount = Math.floor(chartWidth / dailyTokens.length); - recentData = []; - for (const day of dailyTokens) { - for (let i6 = 0;i6 < repeatCount; i6++) { - recentData.push(day); - } - } - } - const theme2 = getTheme(resolveThemeSetting(getGlobalConfig().theme)); - const colors4 = [themeColorToAnsi(theme2.suggestion), themeColorToAnsi(theme2.success), themeColorToAnsi(theme2.warning)]; - const series = []; - const legend = []; - const topModels = models.slice(0, 3); - for (let i6 = 0;i6 < topModels.length; i6++) { - const model = topModels[i6]; - const data = recentData.map((day) => day.tokensByModel[model] || 0); - if (data.some((v6) => v6 > 0)) { - series.push(data); - const bulletColors = [theme2.suggestion, theme2.success, theme2.warning]; - legend.push({ - model: renderModelName(model), - coloredBullet: applyColor(figures_default.bullet, bulletColors[i6 % bulletColors.length]) - }); - } - } - if (series.length === 0) { - return null; - } - const chart = import_asciichart.plot(series, { - height: 8, - colors: colors4.slice(0, series.length), - format: (x4) => { - let label; - if (x4 >= 1e6) { - label = (x4 / 1e6).toFixed(1) + "M"; - } else if (x4 >= 1000) { - label = (x4 / 1000).toFixed(0) + "k"; - } else { - label = x4.toFixed(0); - } - return label.padStart(6); - } - }); - const xAxisLabels = generateXAxisLabels(recentData, recentData.length, yAxisWidth); - return { - chart, - legend, - xAxisLabels - }; -} -function generateXAxisLabels(data, _chartWidth, yAxisOffset) { - if (data.length === 0) - return ""; - const numLabels = Math.min(4, Math.max(2, Math.floor(data.length / 8))); - const usableLength = data.length - 6; - const step = Math.floor(usableLength / (numLabels - 1)) || 1; - const labelPositions = []; - for (let i6 = 0;i6 < numLabels; i6++) { - const idx = Math.min(i6 * step, data.length - 1); - const date6 = new Date(data[idx].date); - const label = date6.toLocaleDateString("en-US", { - month: "short", - day: "numeric" - }); - labelPositions.push({ - pos: idx, - label - }); - } - let result = " ".repeat(yAxisOffset); - let currentPos = 0; - for (const { - pos, - label - } of labelPositions) { - const spaces = Math.max(1, pos - currentPos); - result += " ".repeat(spaces) + label; - currentPos = pos + label.length; - } - return result; -} -async function handleScreenshot(stats, activeTab, setStatus) { - setStatus("copying\u2026"); - const ansiText = renderStatsToAnsi(stats, activeTab); - const result = await copyAnsiToClipboard(ansiText); - setStatus(result.success ? "copied!" : "copy failed"); - setTimeout(setStatus, 2000, null); -} -function renderStatsToAnsi(stats, activeTab) { - const lines2 = []; - if (activeTab === "Overview") { - lines2.push(...renderOverviewToAnsi(stats)); - } else { - lines2.push(...renderModelsToAnsi(stats)); - } - while (lines2.length > 0 && stripAnsi(lines2[lines2.length - 1]).trim() === "") { - lines2.pop(); - } - if (lines2.length > 0) { - const lastLine2 = lines2[lines2.length - 1]; - const lastLineLen = stringWidth(lastLine2); - const contentWidth = activeTab === "Overview" ? 70 : 80; - const statsLabel = "/stats"; - const padding = Math.max(2, contentWidth - lastLineLen - statsLabel.length); - lines2[lines2.length - 1] = lastLine2 + " ".repeat(padding) + source_default.gray(statsLabel); - } - return lines2.join(` -`); -} -function renderOverviewToAnsi(stats) { - const lines2 = []; - const theme2 = getTheme(resolveThemeSetting(getGlobalConfig().theme)); - const h5 = (text) => applyColor(text, theme2.claude); - const COL1_LABEL_WIDTH = 18; - const COL2_START = 40; - const COL2_LABEL_WIDTH = 18; - const row = (l1, v12, l22, v22) => { - const label1 = (l1 + ":").padEnd(COL1_LABEL_WIDTH); - const col1PlainLen = label1.length + v12.length; - const spaceBetween = Math.max(2, COL2_START - col1PlainLen); - const label2 = (l22 + ":").padEnd(COL2_LABEL_WIDTH); - return label1 + h5(v12) + " ".repeat(spaceBetween) + label2 + h5(v22); - }; - if (stats.dailyActivity.length > 0) { - lines2.push(generateHeatmap(stats.dailyActivity, { - terminalWidth: 56 - })); - lines2.push(""); - } - const modelEntries = Object.entries(stats.modelUsage).sort(([, a5], [, b5]) => b5.inputTokens + b5.outputTokens - (a5.inputTokens + a5.outputTokens)); - const favoriteModel = modelEntries[0]; - const totalTokens = modelEntries.reduce((sum, [, usage]) => sum + usage.inputTokens + usage.outputTokens, 0); - if (favoriteModel) { - lines2.push(row("Favorite model", renderModelName(favoriteModel[0]), "Total tokens", formatNumber(totalTokens))); - } - lines2.push(""); - lines2.push(row("Sessions", formatNumber(stats.totalSessions), "Longest session", stats.longestSession ? formatDuration(stats.longestSession.duration) : "N/A")); - const currentStreakVal = `${stats.streaks.currentStreak} ${stats.streaks.currentStreak === 1 ? "day" : "days"}`; - const longestStreakVal = `${stats.streaks.longestStreak} ${stats.streaks.longestStreak === 1 ? "day" : "days"}`; - lines2.push(row("Current streak", currentStreakVal, "Longest streak", longestStreakVal)); - const activeDaysVal = `${stats.activeDays}/${stats.totalDays}`; - const peakHourVal = stats.peakActivityHour !== null ? `${stats.peakActivityHour}:00-${stats.peakActivityHour + 1}:00` : "N/A"; - lines2.push(row("Active days", activeDaysVal, "Peak hour", peakHourVal)); - if (false) {} - if (false) {} - lines2.push(""); - const factoid = generateFunFactoid(stats, totalTokens); - lines2.push(h5(factoid)); - lines2.push(source_default.gray(`Stats from the last ${stats.totalDays} days`)); - return lines2; -} -function renderModelsToAnsi(stats) { - const lines2 = []; - const modelEntries = Object.entries(stats.modelUsage).sort(([, a5], [, b5]) => b5.inputTokens + b5.outputTokens - (a5.inputTokens + a5.outputTokens)); - if (modelEntries.length === 0) { - lines2.push(source_default.gray("No model usage data available")); - return lines2; - } - const favoriteModel = modelEntries[0]; - const totalTokens = modelEntries.reduce((sum, [, usage]) => sum + usage.inputTokens + usage.outputTokens, 0); - const chartOutput = generateTokenChart(stats.dailyModelTokens, modelEntries.map(([model]) => model), 80); - if (chartOutput) { - lines2.push(source_default.bold("Tokens per Day")); - lines2.push(chartOutput.chart); - lines2.push(source_default.gray(chartOutput.xAxisLabels)); - const legendLine = chartOutput.legend.map((item) => `${item.coloredBullet} ${item.model}`).join(" \xB7 "); - lines2.push(legendLine); - lines2.push(""); - } - lines2.push(`${figures_default.star} Favorite: ${source_default.magenta.bold(renderModelName(favoriteModel?.[0] || ""))} \xB7 ${figures_default.circle} Total: ${source_default.magenta(formatNumber(totalTokens))} tokens`); - lines2.push(""); - const topModels = modelEntries.slice(0, 3); - for (const [model, usage] of topModels) { - const modelTokens = usage.inputTokens + usage.outputTokens; - const percentage = (modelTokens / totalTokens * 100).toFixed(1); - lines2.push(`${figures_default.bullet} ${source_default.bold(renderModelName(model))} ${source_default.gray(`(${percentage}%)`)}`); - lines2.push(source_default.dim(` In: ${formatNumber(usage.inputTokens)} \xB7 Out: ${formatNumber(usage.outputTokens)}`)); - } - return lines2; -} -var import_compiler_runtime277, import_asciichart, import_react193, jsx_dev_runtime358, DATE_RANGE_LABELS, DATE_RANGE_ORDER, BOOK_COMPARISONS, TIME_COMPARISONS; -var init_Stats = __esm(() => { - init_source(); - init_figures(); - init_strip_ansi(); - init_useTerminalSize(); - init_colorize(); - init_stringWidth(); - init_ink2(); - init_useKeybinding(); - init_config(); - init_format(); - init_heatmap(); - init_model(); - init_screenshotClipboard(); - init_stats(); - init_theme(); - init_Pane(); - init_Tabs(); - init_Spinner2(); - import_compiler_runtime277 = __toESM(require_compiler_runtime(), 1); - import_asciichart = __toESM(require_asciichart(), 1); - import_react193 = __toESM(require_react(), 1); - jsx_dev_runtime358 = __toESM(require_jsx_dev_runtime(), 1); - DATE_RANGE_LABELS = { - "7d": "Last 7 days", - "30d": "Last 30 days", - all: "All time" - }; - DATE_RANGE_ORDER = ["all", "7d", "30d"]; - BOOK_COMPARISONS = [{ - name: "The Little Prince", - tokens: 22000 - }, { - name: "The Old Man and the Sea", - tokens: 35000 - }, { - name: "A Christmas Carol", - tokens: 37000 - }, { - name: "Animal Farm", - tokens: 39000 - }, { - name: "Fahrenheit 451", - tokens: 60000 - }, { - name: "The Great Gatsby", - tokens: 62000 - }, { - name: "Slaughterhouse-Five", - tokens: 64000 - }, { - name: "Brave New World", - tokens: 83000 - }, { - name: "The Catcher in the Rye", - tokens: 95000 - }, { - name: "Harry Potter and the Philosopher's Stone", - tokens: 103000 - }, { - name: "The Hobbit", - tokens: 123000 - }, { - name: "1984", - tokens: 123000 - }, { - name: "To Kill a Mockingbird", - tokens: 130000 - }, { - name: "Pride and Prejudice", - tokens: 156000 - }, { - name: "Dune", - tokens: 244000 - }, { - name: "Moby-Dick", - tokens: 268000 - }, { - name: "Crime and Punishment", - tokens: 274000 - }, { - name: "A Game of Thrones", - tokens: 381000 - }, { - name: "Anna Karenina", - tokens: 468000 - }, { - name: "Don Quixote", - tokens: 520000 - }, { - name: "The Lord of the Rings", - tokens: 576000 - }, { - name: "The Count of Monte Cristo", - tokens: 603000 - }, { - name: "Les Mis\xE9rables", - tokens: 689000 - }, { - name: "War and Peace", - tokens: 730000 - }]; - TIME_COMPARISONS = [{ - name: "a TED talk", - minutes: 18 - }, { - name: "an episode of The Office", - minutes: 22 - }, { - name: "listening to Abbey Road", - minutes: 47 - }, { - name: "a yoga class", - minutes: 60 - }, { - name: "a World Cup soccer match", - minutes: 90 - }, { - name: "a half marathon (average time)", - minutes: 120 - }, { - name: "the movie Inception", - minutes: 148 - }, { - name: "watching Titanic", - minutes: 195 - }, { - name: "a transatlantic flight", - minutes: 420 - }, { - name: "a full night of sleep", - minutes: 480 - }]; -}); - -// src/commands/stats/stats.tsx -var exports_stats = {}; -__export(exports_stats, { - call: () => call70 -}); -var jsx_dev_runtime359, call70 = async (onDone) => { - return /* @__PURE__ */ jsx_dev_runtime359.jsxDEV(Stats, { - onClose: onDone - }, undefined, false, undefined, this); -}; -var init_stats2 = __esm(() => { - init_Stats(); - jsx_dev_runtime359 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/commands/stats/index.ts -var stats, stats_default; -var init_stats3 = __esm(() => { - stats = { - type: "local-jsx", - name: "stats", - description: "Show your Claude Code usage statistics and activity", - load: () => Promise.resolve().then(() => (init_stats2(), exports_stats)) - }; - stats_default = stats; -}); - -// src/commands/oauth-refresh/index.js -var oauth_refresh_default; -var init_oauth_refresh = __esm(() => { - oauth_refresh_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/commands/debug-tool-call/index.js -var debug_tool_call_default; -var init_debug_tool_call = __esm(() => { - debug_tool_call_default = { isEnabled: () => false, isHidden: true, name: "stub" }; -}); - -// src/types/command.ts -function getCommandName(cmd) { - return cmd.userFacingName?.() ?? cmd.name; -} -function isCommandEnabled(cmd) { - return cmd.isEnabled?.() ?? true; -} - -// src/commands/agents-platform/index.ts -var exports_agents_platform = {}; -__export(exports_agents_platform, { - default: () => agents_platform_default -}); -var agents_platform_default = null; - -// src/commands/insights.ts -var exports_insights = {}; -__export(exports_insights, { - generateUsageReport: () => generateUsageReport, - detectMultiClauding: () => detectMultiClauding, - default: () => insights_default, - deduplicateSessionBranches: () => deduplicateSessionBranches, - buildExportData: () => buildExportData -}); -import { execFileSync as execFileSync4 } from "child_process"; -import { constants as fsConstants9 } from "fs"; -import { - copyFile as copyFile11, - mkdir as mkdir39, - mkdtemp as mkdtemp3, - readdir as readdir28, - readFile as readFile52, - rm as rm12, - unlink as unlink21, - writeFile as writeFile43 -} from "fs/promises"; -import { tmpdir as tmpdir12 } from "os"; -import { extname as extname12, join as join139 } from "path"; -function getAnalysisModel() { - return getDefaultOpusModel(); -} -function getInsightsModel() { - return getDefaultOpusModel(); -} -function getDataDir() { - return join139(getClaudeConfigHomeDir(), "usage-data"); -} -function getFacetsDir() { - return join139(getDataDir(), "facets"); -} -function getSessionMetaDir() { - return join139(getDataDir(), "session-meta"); -} -function getLanguageFromPath(filePath) { - const ext = extname12(filePath).toLowerCase(); - return EXTENSION_TO_LANGUAGE[ext] || null; -} -function extractToolStats(log3) { - const toolCounts = {}; - const languages = {}; - let gitCommits = 0; - let gitPushes = 0; - let inputTokens = 0; - let outputTokens = 0; - let userInterruptions = 0; - const userResponseTimes = []; - let toolErrors = 0; - const toolErrorCategories = {}; - let usesTaskAgent = false; - let linesAdded = 0; - let linesRemoved = 0; - const filesModified = new Set; - const messageHours = []; - const userMessageTimestamps = []; - let usesMcp = false; - let usesWebSearch = false; - let usesWebFetch = false; - let lastAssistantTimestamp = null; - for (const msg of log3.messages) { - const msgTimestamp = msg.timestamp; - if (msg.type === "assistant" && msg.message) { - if (msgTimestamp) { - lastAssistantTimestamp = msgTimestamp; - } - const usage = msg.message.usage; - if (usage) { - inputTokens += usage.input_tokens || 0; - outputTokens += usage.output_tokens || 0; - } - const content = msg.message.content; - if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "tool_use" && "name" in block2) { - const toolName = block2.name; - toolCounts[toolName] = (toolCounts[toolName] || 0) + 1; - if (toolName === AGENT_TOOL_NAME || toolName === LEGACY_AGENT_TOOL_NAME) - usesTaskAgent = true; - if (toolName.startsWith("mcp__")) - usesMcp = true; - if (toolName === "WebSearch") - usesWebSearch = true; - if (toolName === "WebFetch") - usesWebFetch = true; - const input = block2.input; - if (input) { - const filePath = input.file_path || ""; - if (filePath) { - const lang = getLanguageFromPath(filePath); - if (lang) { - languages[lang] = (languages[lang] || 0) + 1; - } - if (toolName === "Edit" || toolName === "Write") { - filesModified.add(filePath); - } - } - if (toolName === "Edit") { - const oldString = input.old_string || ""; - const newString = input.new_string || ""; - for (const change of diffLines(oldString, newString)) { - if (change.added) - linesAdded += change.count || 0; - if (change.removed) - linesRemoved += change.count || 0; - } - } - if (toolName === "Write") { - const writeContent = input.content || ""; - if (writeContent) { - linesAdded += countCharInString(writeContent, ` -`) + 1; - } - } - const command19 = input.command || ""; - if (command19.includes("git commit")) - gitCommits++; - if (command19.includes("git push")) - gitPushes++; - } - } - } - } - } - if (msg.type === "user" && msg.message) { - const content = msg.message.content; - let isHumanMessage = false; - if (typeof content === "string" && content.trim()) { - isHumanMessage = true; - } else if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "text" && "text" in block2) { - isHumanMessage = true; - break; - } - } - } - if (isHumanMessage) { - if (msgTimestamp) { - try { - const msgDate = new Date(msgTimestamp); - const hour = msgDate.getHours(); - messageHours.push(hour); - userMessageTimestamps.push(msgTimestamp); - } catch {} - } - if (lastAssistantTimestamp && msgTimestamp) { - const assistantTime = new Date(lastAssistantTimestamp).getTime(); - const userTime = new Date(msgTimestamp).getTime(); - const responseTimeSec = (userTime - assistantTime) / 1000; - if (responseTimeSec > 2 && responseTimeSec < 3600) { - userResponseTimes.push(responseTimeSec); - } - } - } - if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "tool_result" && "content" in block2) { - const isError3 = block2.is_error; - if (isError3) { - toolErrors++; - const resultContent = block2.content; - let category = "Other"; - if (typeof resultContent === "string") { - const lowerContent = resultContent.toLowerCase(); - if (lowerContent.includes("exit code")) { - category = "Command Failed"; - } else if (lowerContent.includes("rejected") || lowerContent.includes("doesn't want")) { - category = "User Rejected"; - } else if (lowerContent.includes("string to replace not found") || lowerContent.includes("no changes")) { - category = "Edit Failed"; - } else if (lowerContent.includes("modified since read")) { - category = "File Changed"; - } else if (lowerContent.includes("exceeds maximum") || lowerContent.includes("too large")) { - category = "File Too Large"; - } else if (lowerContent.includes("file not found") || lowerContent.includes("does not exist")) { - category = "File Not Found"; - } - } - toolErrorCategories[category] = (toolErrorCategories[category] || 0) + 1; - } - } - } - } - if (typeof content === "string") { - if (content.includes("[Request interrupted by user")) { - userInterruptions++; - } - } else if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "text" && "text" in block2 && block2.text.includes("[Request interrupted by user")) { - userInterruptions++; - break; - } - } - } - } - } - return { - toolCounts, - languages, - gitCommits, - gitPushes, - inputTokens, - outputTokens, - userInterruptions, - userResponseTimes, - toolErrors, - toolErrorCategories, - usesTaskAgent, - usesMcp, - usesWebSearch, - usesWebFetch, - linesAdded, - linesRemoved, - filesModified, - messageHours, - userMessageTimestamps - }; -} -function hasValidDates(log3) { - return !Number.isNaN(log3.created.getTime()) && !Number.isNaN(log3.modified.getTime()); -} -function logToSessionMeta(log3) { - const stats2 = extractToolStats(log3); - const sessionId = getSessionIdFromLog(log3) || "unknown"; - const startTime = log3.created.toISOString(); - const durationMinutes = Math.round((log3.modified.getTime() - log3.created.getTime()) / 1000 / 60); - let userMessageCount = 0; - let assistantMessageCount = 0; - for (const msg of log3.messages) { - if (msg.type === "assistant") - assistantMessageCount++; - if (msg.type === "user" && msg.message) { - const content = msg.message.content; - let isHumanMessage = false; - if (typeof content === "string" && content.trim()) { - isHumanMessage = true; - } else if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "text" && "text" in block2) { - isHumanMessage = true; - break; - } - } - } - if (isHumanMessage) { - userMessageCount++; - } - } - } - return { - session_id: sessionId, - project_path: log3.projectPath || "", - start_time: startTime, - duration_minutes: durationMinutes, - user_message_count: userMessageCount, - assistant_message_count: assistantMessageCount, - tool_counts: stats2.toolCounts, - languages: stats2.languages, - git_commits: stats2.gitCommits, - git_pushes: stats2.gitPushes, - input_tokens: stats2.inputTokens, - output_tokens: stats2.outputTokens, - first_prompt: log3.firstPrompt || "", - summary: log3.summary, - user_interruptions: stats2.userInterruptions, - user_response_times: stats2.userResponseTimes, - tool_errors: stats2.toolErrors, - tool_error_categories: stats2.toolErrorCategories, - uses_task_agent: stats2.usesTaskAgent, - uses_mcp: stats2.usesMcp, - uses_web_search: stats2.usesWebSearch, - uses_web_fetch: stats2.usesWebFetch, - lines_added: stats2.linesAdded, - lines_removed: stats2.linesRemoved, - files_modified: stats2.filesModified.size, - message_hours: stats2.messageHours, - user_message_timestamps: stats2.userMessageTimestamps - }; -} -function deduplicateSessionBranches(entries) { - const bestBySession = new Map; - for (const entry of entries) { - const id = entry.meta.session_id; - const existing = bestBySession.get(id); - if (!existing || entry.meta.user_message_count > existing.meta.user_message_count || entry.meta.user_message_count === existing.meta.user_message_count && entry.meta.duration_minutes > existing.meta.duration_minutes) { - bestBySession.set(id, entry); - } - } - return [...bestBySession.values()]; -} -function formatTranscriptForFacets(log3) { - const lines2 = []; - const meta = logToSessionMeta(log3); - lines2.push(`Session: ${meta.session_id.slice(0, 8)}`); - lines2.push(`Date: ${meta.start_time}`); - lines2.push(`Project: ${meta.project_path}`); - lines2.push(`Duration: ${meta.duration_minutes} min`); - lines2.push(""); - for (const msg of log3.messages) { - if (msg.type === "user" && msg.message) { - const content = msg.message.content; - if (typeof content === "string") { - lines2.push(`[User]: ${content.slice(0, 500)}`); - } else if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "text" && "text" in block2) { - lines2.push(`[User]: ${block2.text.slice(0, 500)}`); - } - } - } - } else if (msg.type === "assistant" && msg.message) { - const content = msg.message.content; - if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "text" && "text" in block2) { - lines2.push(`[Assistant]: ${block2.text.slice(0, 300)}`); - } else if (block2.type === "tool_use" && "name" in block2) { - lines2.push(`[Tool: ${block2.name}]`); - } - } - } - } - } - return lines2.join(` -`); -} -async function summarizeTranscriptChunk(chunk2) { - try { - const result = await queryWithModel({ - systemPrompt: asSystemPrompt([]), - userPrompt: SUMMARIZE_CHUNK_PROMPT + chunk2, - signal: new AbortController().signal, - options: { - model: getAnalysisModel(), - querySource: "insights", - agents: [], - isNonInteractiveSession: true, - hasAppendSystemPrompt: false, - mcpTools: [], - maxOutputTokensOverride: 500 - } - }); - const text = extractTextContent(result.message.content); - return text || chunk2.slice(0, 2000); - } catch { - return chunk2.slice(0, 2000); - } -} -async function formatTranscriptWithSummarization(log3) { - const fullTranscript = formatTranscriptForFacets(log3); - if (fullTranscript.length <= 30000) { - return fullTranscript; - } - const CHUNK_SIZE2 = 25000; - const chunks = []; - for (let i6 = 0;i6 < fullTranscript.length; i6 += CHUNK_SIZE2) { - chunks.push(fullTranscript.slice(i6, i6 + CHUNK_SIZE2)); - } - const summaries = await Promise.all(chunks.map(summarizeTranscriptChunk)); - const meta = logToSessionMeta(log3); - const header = [ - `Session: ${meta.session_id.slice(0, 8)}`, - `Date: ${meta.start_time}`, - `Project: ${meta.project_path}`, - `Duration: ${meta.duration_minutes} min`, - `[Long session - ${chunks.length} parts summarized]`, - "" - ].join(` -`); - return header + summaries.join(` - ---- - -`); -} -async function loadCachedFacets(sessionId) { - const facetPath = join139(getFacetsDir(), `${sessionId}.json`); - try { - const content = await readFile52(facetPath, { encoding: "utf-8" }); - const parsed = jsonParse(content); - if (!isValidSessionFacets(parsed)) { - try { - await unlink21(facetPath); - } catch {} - return null; - } - return parsed; - } catch { - return null; - } -} -async function saveFacets(facets) { - try { - await mkdir39(getFacetsDir(), { recursive: true }); - } catch {} - const facetPath = join139(getFacetsDir(), `${facets.session_id}.json`); - await writeFile43(facetPath, jsonStringify(facets, null, 2), { - encoding: "utf-8", - mode: 384 - }); -} -async function loadCachedSessionMeta(sessionId) { - const metaPath = join139(getSessionMetaDir(), `${sessionId}.json`); - try { - const content = await readFile52(metaPath, { encoding: "utf-8" }); - return jsonParse(content); - } catch { - return null; - } -} -async function saveSessionMeta(meta) { - try { - await mkdir39(getSessionMetaDir(), { recursive: true }); - } catch {} - const metaPath = join139(getSessionMetaDir(), `${meta.session_id}.json`); - await writeFile43(metaPath, jsonStringify(meta, null, 2), { - encoding: "utf-8", - mode: 384 - }); -} -async function extractFacetsFromAPI(log3, sessionId) { - try { - const transcript = await formatTranscriptWithSummarization(log3); - const jsonPrompt = `${FACET_EXTRACTION_PROMPT}${transcript} - -RESPOND WITH ONLY A VALID JSON OBJECT matching this schema: -{ - "underlying_goal": "What the user fundamentally wanted to achieve", - "goal_categories": {"category_name": count, ...}, - "outcome": "fully_achieved|mostly_achieved|partially_achieved|not_achieved|unclear_from_transcript", - "user_satisfaction_counts": {"level": count, ...}, - "claude_helpfulness": "unhelpful|slightly_helpful|moderately_helpful|very_helpful|essential", - "session_type": "single_task|multi_task|iterative_refinement|exploration|quick_question", - "friction_counts": {"friction_type": count, ...}, - "friction_detail": "One sentence describing friction or empty", - "primary_success": "none|fast_accurate_search|correct_code_edits|good_explanations|proactive_help|multi_file_changes|good_debugging", - "brief_summary": "One sentence: what user wanted and whether they got it" -}`; - const result = await queryWithModel({ - systemPrompt: asSystemPrompt([]), - userPrompt: jsonPrompt, - signal: new AbortController().signal, - options: { - model: getAnalysisModel(), - querySource: "insights", - agents: [], - isNonInteractiveSession: true, - hasAppendSystemPrompt: false, - mcpTools: [], - maxOutputTokensOverride: 4096 - } - }); - const text = extractTextContent(result.message.content); - const jsonMatch = text.match(/\{[\s\S]*\}/); - if (!jsonMatch) - return null; - const parsed = jsonParse(jsonMatch[0]); - if (!isValidSessionFacets(parsed)) - return null; - const facets = { ...parsed, session_id: sessionId }; - return facets; - } catch (err2) { - logError2(new Error(`Facet extraction failed: ${toError(err2).message}`)); - return null; - } -} -function detectMultiClauding(sessions) { - const OVERLAP_WINDOW_MS = 30 * 60000; - const allSessionMessages = []; - for (const session2 of sessions) { - for (const timestamp of session2.user_message_timestamps) { - try { - const ts = new Date(timestamp).getTime(); - allSessionMessages.push({ ts, sessionId: session2.session_id }); - } catch {} - } - } - allSessionMessages.sort((a5, b5) => a5.ts - b5.ts); - const multiClaudeSessionPairs = new Set; - const messagesDuringMulticlaude = new Set; - let windowStart = 0; - const sessionLastIndex = new Map; - for (let i6 = 0;i6 < allSessionMessages.length; i6++) { - const msg = allSessionMessages[i6]; - while (windowStart < i6 && msg.ts - allSessionMessages[windowStart].ts > OVERLAP_WINDOW_MS) { - const expiring = allSessionMessages[windowStart]; - if (sessionLastIndex.get(expiring.sessionId) === windowStart) { - sessionLastIndex.delete(expiring.sessionId); - } - windowStart++; - } - const prevIndex = sessionLastIndex.get(msg.sessionId); - if (prevIndex !== undefined) { - for (let j4 = prevIndex + 1;j4 < i6; j4++) { - const between = allSessionMessages[j4]; - if (between.sessionId !== msg.sessionId) { - const pair = [msg.sessionId, between.sessionId].sort().join(":"); - multiClaudeSessionPairs.add(pair); - messagesDuringMulticlaude.add(`${allSessionMessages[prevIndex].ts}:${msg.sessionId}`); - messagesDuringMulticlaude.add(`${between.ts}:${between.sessionId}`); - messagesDuringMulticlaude.add(`${msg.ts}:${msg.sessionId}`); - break; - } - } - } - sessionLastIndex.set(msg.sessionId, i6); - } - const sessionsWithOverlaps = new Set; - for (const pair of multiClaudeSessionPairs) { - const [s1, s22] = pair.split(":"); - if (s1) - sessionsWithOverlaps.add(s1); - if (s22) - sessionsWithOverlaps.add(s22); - } - return { - overlap_events: multiClaudeSessionPairs.size, - sessions_involved: sessionsWithOverlaps.size, - user_messages_during: messagesDuringMulticlaude.size - }; -} -function aggregateData(sessions, facets) { - const result = { - total_sessions: sessions.length, - sessions_with_facets: facets.size, - date_range: { start: "", end: "" }, - total_messages: 0, - total_duration_hours: 0, - total_input_tokens: 0, - total_output_tokens: 0, - tool_counts: {}, - languages: {}, - git_commits: 0, - git_pushes: 0, - projects: {}, - goal_categories: {}, - outcomes: {}, - satisfaction: {}, - helpfulness: {}, - session_types: {}, - friction: {}, - success: {}, - session_summaries: [], - total_interruptions: 0, - total_tool_errors: 0, - tool_error_categories: {}, - user_response_times: [], - median_response_time: 0, - avg_response_time: 0, - sessions_using_task_agent: 0, - sessions_using_mcp: 0, - sessions_using_web_search: 0, - sessions_using_web_fetch: 0, - total_lines_added: 0, - total_lines_removed: 0, - total_files_modified: 0, - days_active: 0, - messages_per_day: 0, - message_hours: [], - multi_clauding: { - overlap_events: 0, - sessions_involved: 0, - user_messages_during: 0 - } - }; - const dates = []; - const allResponseTimes = []; - const allMessageHours = []; - for (const session2 of sessions) { - dates.push(session2.start_time); - result.total_messages += session2.user_message_count; - result.total_duration_hours += session2.duration_minutes / 60; - result.total_input_tokens += session2.input_tokens; - result.total_output_tokens += session2.output_tokens; - result.git_commits += session2.git_commits; - result.git_pushes += session2.git_pushes; - result.total_interruptions += session2.user_interruptions; - result.total_tool_errors += session2.tool_errors; - for (const [cat2, count4] of Object.entries(session2.tool_error_categories)) { - result.tool_error_categories[cat2] = (result.tool_error_categories[cat2] || 0) + count4; - } - allResponseTimes.push(...session2.user_response_times); - if (session2.uses_task_agent) - result.sessions_using_task_agent++; - if (session2.uses_mcp) - result.sessions_using_mcp++; - if (session2.uses_web_search) - result.sessions_using_web_search++; - if (session2.uses_web_fetch) - result.sessions_using_web_fetch++; - result.total_lines_added += session2.lines_added; - result.total_lines_removed += session2.lines_removed; - result.total_files_modified += session2.files_modified; - allMessageHours.push(...session2.message_hours); - for (const [tool, count4] of Object.entries(session2.tool_counts)) { - result.tool_counts[tool] = (result.tool_counts[tool] || 0) + count4; - } - for (const [lang, count4] of Object.entries(session2.languages)) { - result.languages[lang] = (result.languages[lang] || 0) + count4; - } - if (session2.project_path) { - result.projects[session2.project_path] = (result.projects[session2.project_path] || 0) + 1; - } - const sessionFacets = facets.get(session2.session_id); - if (sessionFacets) { - for (const [cat2, count4] of safeEntries(sessionFacets.goal_categories)) { - if (count4 > 0) { - result.goal_categories[cat2] = (result.goal_categories[cat2] || 0) + count4; - } - } - result.outcomes[sessionFacets.outcome] = (result.outcomes[sessionFacets.outcome] || 0) + 1; - for (const [level, count4] of safeEntries(sessionFacets.user_satisfaction_counts)) { - if (count4 > 0) { - result.satisfaction[level] = (result.satisfaction[level] || 0) + count4; - } - } - result.helpfulness[sessionFacets.claude_helpfulness] = (result.helpfulness[sessionFacets.claude_helpfulness] || 0) + 1; - result.session_types[sessionFacets.session_type] = (result.session_types[sessionFacets.session_type] || 0) + 1; - for (const [type, count4] of safeEntries(sessionFacets.friction_counts)) { - if (count4 > 0) { - result.friction[type] = (result.friction[type] || 0) + count4; - } - } - if (sessionFacets.primary_success !== "none") { - result.success[sessionFacets.primary_success] = (result.success[sessionFacets.primary_success] || 0) + 1; - } - } - if (result.session_summaries.length < 50) { - result.session_summaries.push({ - id: session2.session_id.slice(0, 8), - date: session2.start_time.split("T")[0] || "", - summary: session2.summary || session2.first_prompt.slice(0, 100), - goal: sessionFacets?.underlying_goal - }); - } - } - dates.sort(); - result.date_range.start = dates[0]?.split("T")[0] || ""; - result.date_range.end = dates[dates.length - 1]?.split("T")[0] || ""; - result.user_response_times = allResponseTimes; - if (allResponseTimes.length > 0) { - const sorted = [...allResponseTimes].sort((a5, b5) => a5 - b5); - result.median_response_time = sorted[Math.floor(sorted.length / 2)] || 0; - result.avg_response_time = allResponseTimes.reduce((a5, b5) => a5 + b5, 0) / allResponseTimes.length; - } - const uniqueDays = new Set(dates.map((d4) => d4.split("T")[0])); - result.days_active = uniqueDays.size; - result.messages_per_day = result.days_active > 0 ? Math.round(result.total_messages / result.days_active * 10) / 10 : 0; - result.message_hours = allMessageHours; - result.multi_clauding = detectMultiClauding(sessions); - return result; -} -async function generateSectionInsight(section, dataContext) { - try { - const result = await queryWithModel({ - systemPrompt: asSystemPrompt([]), - userPrompt: section.prompt + ` - -DATA: -` + dataContext, - signal: new AbortController().signal, - options: { - model: getInsightsModel(), - querySource: "insights", - agents: [], - isNonInteractiveSession: true, - hasAppendSystemPrompt: false, - mcpTools: [], - maxOutputTokensOverride: section.maxTokens - } - }); - const text = extractTextContent(result.message.content); - if (text) { - const jsonMatch = text.match(/\{[\s\S]*\}/); - if (jsonMatch) { - try { - return { name: section.name, result: jsonParse(jsonMatch[0]) }; - } catch { - return { name: section.name, result: null }; - } - } - } - return { name: section.name, result: null }; - } catch (err2) { - logError2(new Error(`${section.name} failed: ${toError(err2).message}`)); - return { name: section.name, result: null }; - } -} -async function generateParallelInsights(data, facets) { - const facetSummaries = Array.from(facets.values()).slice(0, 50).map((f4) => `- ${f4.brief_summary} (${f4.outcome}, ${f4.claude_helpfulness})`).join(` -`); - const frictionDetails = Array.from(facets.values()).filter((f4) => f4.friction_detail).slice(0, 20).map((f4) => `- ${f4.friction_detail}`).join(` -`); - const userInstructions = Array.from(facets.values()).flatMap((f4) => f4.user_instructions_to_claude || []).slice(0, 15).map((i6) => `- ${i6}`).join(` -`); - const dataContext = jsonStringify({ - sessions: data.total_sessions, - analyzed: data.sessions_with_facets, - date_range: data.date_range, - messages: data.total_messages, - hours: Math.round(data.total_duration_hours), - commits: data.git_commits, - top_tools: Object.entries(data.tool_counts).sort((a5, b5) => b5[1] - a5[1]).slice(0, 8), - top_goals: Object.entries(data.goal_categories).sort((a5, b5) => b5[1] - a5[1]).slice(0, 8), - outcomes: data.outcomes, - satisfaction: data.satisfaction, - friction: data.friction, - success: data.success, - languages: data.languages - }, null, 2); - const fullContext = dataContext + ` - -SESSION SUMMARIES: -` + facetSummaries + ` - -FRICTION DETAILS: -` + frictionDetails + ` - -USER INSTRUCTIONS TO CLAUDE: -` + (userInstructions || "None captured"); - const results = await Promise.all(INSIGHT_SECTIONS.map((section) => generateSectionInsight(section, fullContext))); - const insights = {}; - for (const { name: name3, result } of results) { - if (result) { - insights[name3] = result; - } - } - const projectAreasText = insights.project_areas?.areas?.map((a5) => `- ${a5.name}: ${a5.description}`).join(` -`) || ""; - const bigWinsText = insights.what_works?.impressive_workflows?.map((w2) => `- ${w2.title}: ${w2.description}`).join(` -`) || ""; - const frictionText = insights.friction_analysis?.categories?.map((c9) => `- ${c9.category}: ${c9.description}`).join(` -`) || ""; - const featuresText = insights.suggestions?.features_to_try?.map((f4) => `- ${f4.feature}: ${f4.one_liner}`).join(` -`) || ""; - const patternsText = insights.suggestions?.usage_patterns?.map((p4) => `- ${p4.title}: ${p4.suggestion}`).join(` -`) || ""; - const horizonText = insights.on_the_horizon?.opportunities?.map((o5) => `- ${o5.title}: ${o5.whats_possible}`).join(` -`) || ""; - const atAGlancePrompt = `You're writing an "At a Glance" summary for a Claude Code usage insights report for Claude Code users. The goal is to help them understand their usage and improve how they can use Claude better, especially as models improve. - -Use this 4-part structure: - -1. **What's working** - What is the user's unique style of interacting with Claude and what are some impactful things they've done? You can include one or two details, but keep it high level since things might not be fresh in the user's memory. Don't be fluffy or overly complimentary. Also, don't focus on the tool calls they use. - -2. **What's hindering you** - Split into (a) Claude's fault (misunderstandings, wrong approaches, bugs) and (b) user-side friction (not providing enough context, environment issues -- ideally more general than just one project). Be honest but constructive. - -3. **Quick wins to try** - Specific Claude Code features they could try from the examples below, or a workflow technique if you think it's really compelling. (Avoid stuff like "Ask Claude to confirm before taking actions" or "Type out more context up front" which are less compelling.) - -4. **Ambitious workflows for better models** - As we move to much more capable models over the next 3-6 months, what should they prepare for? What workflows that seem impossible now will become possible? Draw from the appropriate section below. - -Keep each section to 2-3 not-too-long sentences. Don't overwhelm the user. Don't mention specific numerical stats or underlined_categories from the session data below. Use a coaching tone. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "whats_working": "(refer to instructions above)", - "whats_hindering": "(refer to instructions above)", - "quick_wins": "(refer to instructions above)", - "ambitious_workflows": "(refer to instructions above)" -} - -SESSION DATA: -${fullContext} - -## Project Areas (what user works on) -${projectAreasText} - -## Big Wins (impressive accomplishments) -${bigWinsText} - -## Friction Categories (where things go wrong) -${frictionText} - -## Features to Try -${featuresText} - -## Usage Patterns to Adopt -${patternsText} - -## On the Horizon (ambitious workflows for better models) -${horizonText}`; - const atAGlanceSection = { - name: "at_a_glance", - prompt: atAGlancePrompt, - maxTokens: 8192 - }; - const atAGlanceResult = await generateSectionInsight(atAGlanceSection, ""); - if (atAGlanceResult.result) { - insights.at_a_glance = atAGlanceResult.result; - } - return insights; -} -function escapeHtmlWithBold(text) { - const escaped = escapeXmlAttr(text); - return escaped.replace(/\*\*(.+?)\*\*/g, "$1"); -} -function generateBarChart(data, color3, maxItems = 6, fixedOrder) { - let entries; - if (fixedOrder) { - entries = fixedOrder.filter((key2) => (key2 in data) && (data[key2] ?? 0) > 0).map((key2) => [key2, data[key2] ?? 0]); - } else { - entries = Object.entries(data).sort((a5, b5) => b5[1] - a5[1]).slice(0, maxItems); - } - if (entries.length === 0) - return '

    No data

    '; - const maxVal = Math.max(...entries.map((e4) => e4[1])); - return entries.map(([label, count4]) => { - const pct = count4 / maxVal * 100; - const cleanLabel = LABEL_MAP[label] || label.replace(/_/g, " ").replace(/\b\w/g, (c9) => c9.toUpperCase()); - return `
    -
    ${escapeXmlAttr(cleanLabel)}
    -
    -
    ${count4}
    -
    `; - }).join(` -`); -} -function generateResponseTimeHistogram(times) { - if (times.length === 0) - return '

    No response time data

    '; - const buckets = { - "2-10s": 0, - "10-30s": 0, - "30s-1m": 0, - "1-2m": 0, - "2-5m": 0, - "5-15m": 0, - ">15m": 0 - }; - for (const t4 of times) { - if (t4 < 10) - buckets["2-10s"] = (buckets["2-10s"] ?? 0) + 1; - else if (t4 < 30) - buckets["10-30s"] = (buckets["10-30s"] ?? 0) + 1; - else if (t4 < 60) - buckets["30s-1m"] = (buckets["30s-1m"] ?? 0) + 1; - else if (t4 < 120) - buckets["1-2m"] = (buckets["1-2m"] ?? 0) + 1; - else if (t4 < 300) - buckets["2-5m"] = (buckets["2-5m"] ?? 0) + 1; - else if (t4 < 900) - buckets["5-15m"] = (buckets["5-15m"] ?? 0) + 1; - else - buckets[">15m"] = (buckets[">15m"] ?? 0) + 1; - } - const maxVal = Math.max(...Object.values(buckets)); - if (maxVal === 0) - return '

    No response time data

    '; - return Object.entries(buckets).map(([label, count4]) => { - const pct = count4 / maxVal * 100; - return `
    -
    ${label}
    -
    -
    ${count4}
    -
    `; - }).join(` -`); -} -function generateTimeOfDayChart(messageHours) { - if (messageHours.length === 0) - return '

    No time data

    '; - const periods = [ - { label: "Morning (6-12)", range: [6, 7, 8, 9, 10, 11] }, - { label: "Afternoon (12-18)", range: [12, 13, 14, 15, 16, 17] }, - { label: "Evening (18-24)", range: [18, 19, 20, 21, 22, 23] }, - { label: "Night (0-6)", range: [0, 1, 2, 3, 4, 5] } - ]; - const hourCounts = {}; - for (const h5 of messageHours) { - hourCounts[h5] = (hourCounts[h5] || 0) + 1; - } - const periodCounts = periods.map((p4) => ({ - label: p4.label, - count: p4.range.reduce((sum, h5) => sum + (hourCounts[h5] || 0), 0) - })); - const maxVal = Math.max(...periodCounts.map((p4) => p4.count)) || 1; - const barsHtml = periodCounts.map((p4) => ` -
    -
    ${p4.label}
    -
    -
    ${p4.count}
    -
    `).join(` -`); - return `
    ${barsHtml}
    `; -} -function getHourCountsJson(messageHours) { - const hourCounts = {}; - for (const h5 of messageHours) { - hourCounts[h5] = (hourCounts[h5] || 0) + 1; - } - return jsonStringify(hourCounts); -} -function generateHtmlReport(data, insights) { - const markdownToHtml = (md) => { - if (!md) - return ""; - return md.split(` - -`).map((p4) => { - let html3 = escapeXmlAttr(p4); - html3 = html3.replace(/\*\*(.+?)\*\*/g, "$1"); - html3 = html3.replace(/^- /gm, "\u2022 "); - html3 = html3.replace(/\n/g, "
    "); - return `

    ${html3}

    `; - }).join(` -`); - }; - const atAGlance = insights.at_a_glance; - const atAGlanceHtml = atAGlance ? ` -
    - ` : ""; - const projectAreas = insights.project_areas?.areas || []; - const projectAreasHtml = projectAreas.length > 0 ? ` -

    What You Work On

    -
    - ${projectAreas.map((area) => ` -
    -
    - ${escapeXmlAttr(area.name)} - ~${area.session_count} sessions -
    -
    ${escapeXmlAttr(area.description)}
    -
    - `).join("")} -
    - ` : ""; - const interactionStyle = insights.interaction_style; - const interactionHtml = interactionStyle?.narrative ? ` -

    How You Use Claude Code

    -
    - ${markdownToHtml(interactionStyle.narrative)} - ${interactionStyle.key_pattern ? `
    Key pattern: ${escapeXmlAttr(interactionStyle.key_pattern)}
    ` : ""} -
    - ` : ""; - const whatWorks = insights.what_works; - const whatWorksHtml = whatWorks?.impressive_workflows && whatWorks.impressive_workflows.length > 0 ? ` -

    Impressive Things You Did

    - ${whatWorks.intro ? `

    ${escapeXmlAttr(whatWorks.intro)}

    ` : ""} -
    - ${whatWorks.impressive_workflows.map((wf) => ` -
    -
    ${escapeXmlAttr(wf.title || "")}
    -
    ${escapeXmlAttr(wf.description || "")}
    -
    - `).join("")} -
    - ` : ""; - const frictionAnalysis = insights.friction_analysis; - const frictionHtml = frictionAnalysis?.categories && frictionAnalysis.categories.length > 0 ? ` -

    Where Things Go Wrong

    - ${frictionAnalysis.intro ? `

    ${escapeXmlAttr(frictionAnalysis.intro)}

    ` : ""} -
    - ${frictionAnalysis.categories.map((cat2) => ` -
    -
    ${escapeXmlAttr(cat2.category || "")}
    -
    ${escapeXmlAttr(cat2.description || "")}
    - ${cat2.examples ? `
      ${cat2.examples.map((ex) => `
    • ${escapeXmlAttr(ex)}
    • `).join("")}
    ` : ""} -
    - `).join("")} -
    - ` : ""; - const suggestions = insights.suggestions; - const suggestionsHtml = suggestions ? ` - ${suggestions.claude_md_additions && suggestions.claude_md_additions.length > 0 ? ` -

    Existing CC Features to Try

    -
    -

    Suggested CLAUDE.md Additions

    -

    Just copy this into Claude Code to add it to your CLAUDE.md.

    -
    - -
    - ${suggestions.claude_md_additions.map((add, i6) => ` -
    - - -
    ${escapeXmlAttr(add.why)}
    -
    - `).join("")} -
    - ` : ""} - ${suggestions.features_to_try && suggestions.features_to_try.length > 0 ? ` -

    Just copy this into Claude Code and it'll set it up for you.

    -
    - ${suggestions.features_to_try.map((feat) => ` -
    -
    ${escapeXmlAttr(feat.feature || "")}
    -
    ${escapeXmlAttr(feat.one_liner || "")}
    -
    Why for you: ${escapeXmlAttr(feat.why_for_you || "")}
    - ${feat.example_code ? ` -
    -
    -
    - ${escapeXmlAttr(feat.example_code)} - -
    -
    -
    - ` : ""} -
    - `).join("")} -
    - ` : ""} - ${suggestions.usage_patterns && suggestions.usage_patterns.length > 0 ? ` -

    New Ways to Use Claude Code

    -

    Just copy this into Claude Code and it'll walk you through it.

    -
    - ${suggestions.usage_patterns.map((pat) => ` -
    -
    ${escapeXmlAttr(pat.title || "")}
    -
    ${escapeXmlAttr(pat.suggestion || "")}
    - ${pat.detail ? `
    ${escapeXmlAttr(pat.detail)}
    ` : ""} - ${pat.copyable_prompt ? ` -
    -
    Paste into Claude Code:
    -
    - ${escapeXmlAttr(pat.copyable_prompt)} - -
    -
    - ` : ""} -
    - `).join("")} -
    - ` : ""} - ` : ""; - const horizonData = insights.on_the_horizon; - const horizonHtml = horizonData?.opportunities && horizonData.opportunities.length > 0 ? ` -

    On the Horizon

    - ${horizonData.intro ? `

    ${escapeXmlAttr(horizonData.intro)}

    ` : ""} -
    - ${horizonData.opportunities.map((opp) => ` -
    -
    ${escapeXmlAttr(opp.title || "")}
    -
    ${escapeXmlAttr(opp.whats_possible || "")}
    - ${opp.how_to_try ? `
    Getting started: ${escapeXmlAttr(opp.how_to_try)}
    ` : ""} - ${opp.copyable_prompt ? `
    Paste into Claude Code:
    ${escapeXmlAttr(opp.copyable_prompt)}
    ` : ""} -
    - `).join("")} -
    - ` : ""; - const ccImprovements = process.env.USER_TYPE === "ant" ? insights.cc_team_improvements?.improvements || [] : []; - const modelImprovements = process.env.USER_TYPE === "ant" ? insights.model_behavior_improvements?.improvements || [] : []; - const teamFeedbackHtml = ccImprovements.length > 0 || modelImprovements.length > 0 ? ` - - - ${ccImprovements.length > 0 ? ` -
    -
    - \u25B6 -

    Product Improvements for CC Team

    -
    -
    -
    - ${ccImprovements.map((imp) => ` - - `).join("")} -
    -
    -
    - ` : ""} - ${modelImprovements.length > 0 ? ` -
    -
    - \u25B6 -

    Model Behavior Improvements

    -
    -
    -
    - ${modelImprovements.map((imp) => ` - - `).join("")} -
    -
    -
    - ` : ""} - ` : ""; - const funEnding = insights.fun_ending; - const funEndingHtml = funEnding?.headline ? ` -
    -
    "${escapeXmlAttr(funEnding.headline)}"
    - ${funEnding.detail ? `
    ${escapeXmlAttr(funEnding.detail)}
    ` : ""} -
    - ` : ""; - const css = ` - * { box-sizing: border-box; margin: 0; padding: 0; } - body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; background: #f8fafc; color: #334155; line-height: 1.65; padding: 48px 24px; } - .container { max-width: 800px; margin: 0 auto; } - h1 { font-size: 32px; font-weight: 700; color: #0f172a; margin-bottom: 8px; } - h2 { font-size: 20px; font-weight: 600; color: #0f172a; margin-top: 48px; margin-bottom: 16px; } - .subtitle { color: #64748b; font-size: 15px; margin-bottom: 32px; } - .nav-toc { display: flex; flex-wrap: wrap; gap: 8px; margin: 24px 0 32px 0; padding: 16px; background: white; border-radius: 8px; border: 1px solid #e2e8f0; } - .nav-toc a { font-size: 12px; color: #64748b; text-decoration: none; padding: 6px 12px; border-radius: 6px; background: #f1f5f9; transition: all 0.15s; } - .nav-toc a:hover { background: #e2e8f0; color: #334155; } - .stats-row { display: flex; gap: 24px; margin-bottom: 40px; padding: 20px 0; border-top: 1px solid #e2e8f0; border-bottom: 1px solid #e2e8f0; flex-wrap: wrap; } - .stat { text-align: center; } - .stat-value { font-size: 24px; font-weight: 700; color: #0f172a; } - .stat-label { font-size: 11px; color: #64748b; text-transform: uppercase; } - .at-a-glance { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #f59e0b; border-radius: 12px; padding: 20px 24px; margin-bottom: 32px; } - .glance-title { font-size: 16px; font-weight: 700; color: #92400e; margin-bottom: 16px; } - .glance-sections { display: flex; flex-direction: column; gap: 12px; } - .glance-section { font-size: 14px; color: #78350f; line-height: 1.6; } - .glance-section strong { color: #92400e; } - .see-more { color: #b45309; text-decoration: none; font-size: 13px; white-space: nowrap; } - .see-more:hover { text-decoration: underline; } - .project-areas { display: flex; flex-direction: column; gap: 12px; margin-bottom: 32px; } - .project-area { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; } - .area-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; } - .area-name { font-weight: 600; font-size: 15px; color: #0f172a; } - .area-count { font-size: 12px; color: #64748b; background: #f1f5f9; padding: 2px 8px; border-radius: 4px; } - .area-desc { font-size: 14px; color: #475569; line-height: 1.5; } - .narrative { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 24px; } - .narrative p { margin-bottom: 12px; font-size: 14px; color: #475569; line-height: 1.7; } - .key-insight { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 8px; padding: 12px 16px; margin-top: 12px; font-size: 14px; color: #166534; } - .section-intro { font-size: 14px; color: #64748b; margin-bottom: 16px; } - .big-wins { display: flex; flex-direction: column; gap: 12px; margin-bottom: 24px; } - .big-win { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 8px; padding: 16px; } - .big-win-title { font-weight: 600; font-size: 15px; color: #166534; margin-bottom: 8px; } - .big-win-desc { font-size: 14px; color: #15803d; line-height: 1.5; } - .friction-categories { display: flex; flex-direction: column; gap: 16px; margin-bottom: 24px; } - .friction-category { background: #fef2f2; border: 1px solid #fca5a5; border-radius: 8px; padding: 16px; } - .friction-title { font-weight: 600; font-size: 15px; color: #991b1b; margin-bottom: 6px; } - .friction-desc { font-size: 13px; color: #7f1d1d; margin-bottom: 10px; } - .friction-examples { margin: 0 0 0 20px; font-size: 13px; color: #334155; } - .friction-examples li { margin-bottom: 4px; } - .claude-md-section { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px; padding: 16px; margin-bottom: 20px; } - .claude-md-section h3 { font-size: 14px; font-weight: 600; color: #1e40af; margin: 0 0 12px 0; } - .claude-md-actions { margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #dbeafe; } - .copy-all-btn { background: #2563eb; color: white; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; cursor: pointer; font-weight: 500; transition: all 0.2s; } - .copy-all-btn:hover { background: #1d4ed8; } - .copy-all-btn.copied { background: #16a34a; } - .claude-md-item { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 8px; padding: 10px 0; border-bottom: 1px solid #dbeafe; } - .claude-md-item:last-child { border-bottom: none; } - .cmd-checkbox { margin-top: 2px; } - .cmd-code { background: white; padding: 8px 12px; border-radius: 4px; font-size: 12px; color: #1e40af; border: 1px solid #bfdbfe; font-family: monospace; display: block; white-space: pre-wrap; word-break: break-word; flex: 1; } - .cmd-why { font-size: 12px; color: #64748b; width: 100%; padding-left: 24px; margin-top: 4px; } - .features-section, .patterns-section { display: flex; flex-direction: column; gap: 12px; margin: 16px 0; } - .feature-card { background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; padding: 16px; } - .pattern-card { background: #f0f9ff; border: 1px solid #7dd3fc; border-radius: 8px; padding: 16px; } - .feature-title, .pattern-title { font-weight: 600; font-size: 15px; color: #0f172a; margin-bottom: 6px; } - .feature-oneliner { font-size: 14px; color: #475569; margin-bottom: 8px; } - .pattern-summary { font-size: 14px; color: #475569; margin-bottom: 8px; } - .feature-why, .pattern-detail { font-size: 13px; color: #334155; line-height: 1.5; } - .feature-examples { margin-top: 12px; } - .feature-example { padding: 8px 0; border-top: 1px solid #d1fae5; } - .feature-example:first-child { border-top: none; } - .example-desc { font-size: 13px; color: #334155; margin-bottom: 6px; } - .example-code-row { display: flex; align-items: flex-start; gap: 8px; } - .example-code { flex: 1; background: #f1f5f9; padding: 8px 12px; border-radius: 4px; font-family: monospace; font-size: 12px; color: #334155; overflow-x: auto; white-space: pre-wrap; } - .copyable-prompt-section { margin-top: 12px; padding-top: 12px; border-top: 1px solid #e2e8f0; } - .copyable-prompt-row { display: flex; align-items: flex-start; gap: 8px; } - .copyable-prompt { flex: 1; background: #f8fafc; padding: 10px 12px; border-radius: 4px; font-family: monospace; font-size: 12px; color: #334155; border: 1px solid #e2e8f0; white-space: pre-wrap; line-height: 1.5; } - .feature-code { background: #f8fafc; padding: 12px; border-radius: 6px; margin-top: 12px; border: 1px solid #e2e8f0; display: flex; align-items: flex-start; gap: 8px; } - .feature-code code { flex: 1; font-family: monospace; font-size: 12px; color: #334155; white-space: pre-wrap; } - .pattern-prompt { background: #f8fafc; padding: 12px; border-radius: 6px; margin-top: 12px; border: 1px solid #e2e8f0; } - .pattern-prompt code { font-family: monospace; font-size: 12px; color: #334155; display: block; white-space: pre-wrap; margin-bottom: 8px; } - .prompt-label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: #64748b; margin-bottom: 6px; } - .copy-btn { background: #e2e8f0; border: none; border-radius: 4px; padding: 4px 8px; font-size: 11px; cursor: pointer; color: #475569; flex-shrink: 0; } - .copy-btn:hover { background: #cbd5e1; } - .charts-row { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin: 24px 0; } - .chart-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; } - .chart-title { font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; margin-bottom: 12px; } - .bar-row { display: flex; align-items: center; margin-bottom: 6px; } - .bar-label { width: 100px; font-size: 11px; color: #475569; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } - .bar-track { flex: 1; height: 6px; background: #f1f5f9; border-radius: 3px; margin: 0 8px; } - .bar-fill { height: 100%; border-radius: 3px; } - .bar-value { width: 28px; font-size: 11px; font-weight: 500; color: #64748b; text-align: right; } - .empty { color: #94a3b8; font-size: 13px; } - .horizon-section { display: flex; flex-direction: column; gap: 16px; } - .horizon-card { background: linear-gradient(135deg, #faf5ff 0%, #f5f3ff 100%); border: 1px solid #c4b5fd; border-radius: 8px; padding: 16px; } - .horizon-title { font-weight: 600; font-size: 15px; color: #5b21b6; margin-bottom: 8px; } - .horizon-possible { font-size: 14px; color: #334155; margin-bottom: 10px; line-height: 1.5; } - .horizon-tip { font-size: 13px; color: #6b21a8; background: rgba(255,255,255,0.6); padding: 8px 12px; border-radius: 4px; } - .feedback-header { margin-top: 48px; color: #64748b; font-size: 16px; } - .feedback-intro { font-size: 13px; color: #94a3b8; margin-bottom: 16px; } - .feedback-section { margin-top: 16px; } - .feedback-section h3 { font-size: 14px; font-weight: 600; color: #475569; margin-bottom: 12px; } - .feedback-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; margin-bottom: 12px; } - .feedback-card.team-card { background: #eff6ff; border-color: #bfdbfe; } - .feedback-card.model-card { background: #faf5ff; border-color: #e9d5ff; } - .feedback-title { font-weight: 600; font-size: 14px; color: #0f172a; margin-bottom: 6px; } - .feedback-detail { font-size: 13px; color: #475569; line-height: 1.5; } - .feedback-evidence { font-size: 12px; color: #64748b; margin-top: 8px; } - .fun-ending { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #fbbf24; border-radius: 12px; padding: 24px; margin-top: 40px; text-align: center; } - .fun-headline { font-size: 18px; font-weight: 600; color: #78350f; margin-bottom: 8px; } - .fun-detail { font-size: 14px; color: #92400e; } - .collapsible-section { margin-top: 16px; } - .collapsible-header { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 12px 0; border-bottom: 1px solid #e2e8f0; } - .collapsible-header h3 { margin: 0; font-size: 14px; font-weight: 600; color: #475569; } - .collapsible-arrow { font-size: 12px; color: #94a3b8; transition: transform 0.2s; } - .collapsible-content { display: none; padding-top: 16px; } - .collapsible-content.open { display: block; } - .collapsible-header.open .collapsible-arrow { transform: rotate(90deg); } - @media (max-width: 640px) { .charts-row { grid-template-columns: 1fr; } .stats-row { justify-content: center; } } - `; - const hourCountsJson = getHourCountsJson(data.message_hours); - const js = ` - function toggleCollapsible(header) { - header.classList.toggle('open'); - const content = header.nextElementSibling; - content.classList.toggle('open'); - } - function copyText(btn) { - const code = btn.previousElementSibling; - navigator.clipboard.writeText(code.textContent).then(() => { - btn.textContent = 'Copied!'; - setTimeout(() => { btn.textContent = 'Copy'; }, 2000); - }); - } - function copyCmdItem(idx) { - const checkbox = document.getElementById('cmd-' + idx); - if (checkbox) { - const text = checkbox.dataset.text; - navigator.clipboard.writeText(text).then(() => { - const btn = checkbox.nextElementSibling.querySelector('.copy-btn'); - if (btn) { btn.textContent = 'Copied!'; setTimeout(() => { btn.textContent = 'Copy'; }, 2000); } - }); - } - } - function copyAllCheckedClaudeMd() { - const checkboxes = document.querySelectorAll('.cmd-checkbox:checked'); - const texts = []; - checkboxes.forEach(cb => { - if (cb.dataset.text) { texts.push(cb.dataset.text); } - }); - const combined = texts.join('\\n'); - const btn = document.querySelector('.copy-all-btn'); - if (btn) { - navigator.clipboard.writeText(combined).then(() => { - btn.textContent = 'Copied ' + texts.length + ' items!'; - btn.classList.add('copied'); - setTimeout(() => { btn.textContent = 'Copy All Checked'; btn.classList.remove('copied'); }, 2000); - }); - } - } - // Timezone selector for time of day chart (data is from our own analytics, not user input) - const rawHourCounts = ${hourCountsJson}; - function updateHourHistogram(offsetFromPT) { - const periods = [ - { label: "Morning (6-12)", range: [6,7,8,9,10,11] }, - { label: "Afternoon (12-18)", range: [12,13,14,15,16,17] }, - { label: "Evening (18-24)", range: [18,19,20,21,22,23] }, - { label: "Night (0-6)", range: [0,1,2,3,4,5] } - ]; - const adjustedCounts = {}; - for (const [hour, count] of Object.entries(rawHourCounts)) { - const newHour = (parseInt(hour) + offsetFromPT + 24) % 24; - adjustedCounts[newHour] = (adjustedCounts[newHour] || 0) + count; - } - const periodCounts = periods.map(p => ({ - label: p.label, - count: p.range.reduce((sum, h) => sum + (adjustedCounts[h] || 0), 0) - })); - const maxCount = Math.max(...periodCounts.map(p => p.count)) || 1; - const container = document.getElementById('hour-histogram'); - container.textContent = ''; - periodCounts.forEach(p => { - const row = document.createElement('div'); - row.className = 'bar-row'; - const label = document.createElement('div'); - label.className = 'bar-label'; - label.textContent = p.label; - const track = document.createElement('div'); - track.className = 'bar-track'; - const fill = document.createElement('div'); - fill.className = 'bar-fill'; - fill.style.width = (p.count / maxCount) * 100 + '%'; - fill.style.background = '#8b5cf6'; - track.appendChild(fill); - const value = document.createElement('div'); - value.className = 'bar-value'; - value.textContent = p.count; - row.appendChild(label); - row.appendChild(track); - row.appendChild(value); - container.appendChild(row); - }); - } - document.getElementById('timezone-select').addEventListener('change', function() { - const customInput = document.getElementById('custom-offset'); - if (this.value === 'custom') { - customInput.style.display = 'inline-block'; - customInput.focus(); - } else { - customInput.style.display = 'none'; - updateHourHistogram(parseInt(this.value)); - } - }); - document.getElementById('custom-offset').addEventListener('change', function() { - const offset = parseInt(this.value) + 8; - updateHourHistogram(offset); - }); - `; - return ` - - - - Claude Code Insights - - - - -
    -

    Claude Code Insights

    -

    ${data.total_messages.toLocaleString()} messages across ${data.total_sessions} sessions${data.total_sessions_scanned && data.total_sessions_scanned > data.total_sessions ? ` (${data.total_sessions_scanned.toLocaleString()} total)` : ""} | ${data.date_range.start} to ${data.date_range.end}

    - - ${atAGlanceHtml} - - - -
    -
    ${data.total_messages.toLocaleString()}
    Messages
    -
    +${data.total_lines_added.toLocaleString()}/-${data.total_lines_removed.toLocaleString()}
    Lines
    -
    ${data.total_files_modified}
    Files
    -
    ${data.days_active}
    Days
    -
    ${data.messages_per_day}
    Msgs/Day
    -
    - - ${projectAreasHtml} - -
    -
    -
    What You Wanted
    - ${generateBarChart(data.goal_categories, "#2563eb")} -
    -
    -
    Top Tools Used
    - ${generateBarChart(data.tool_counts, "#0891b2")} -
    -
    - -
    -
    -
    Languages
    - ${generateBarChart(data.languages, "#10b981")} -
    -
    -
    Session Types
    - ${generateBarChart(data.session_types || {}, "#8b5cf6")} -
    -
    - - ${interactionHtml} - - -
    -
    User Response Time Distribution
    - ${generateResponseTimeHistogram(data.user_response_times)} -
    - Median: ${data.median_response_time.toFixed(1)}s • Average: ${data.avg_response_time.toFixed(1)}s -
    -
    - - -
    -
    Multi-Clauding (Parallel Sessions)
    - ${data.multi_clauding.overlap_events === 0 ? ` -

    - No parallel session usage detected. You typically work with one Claude Code session at a time. -

    - ` : ` -
    -
    -
    ${data.multi_clauding.overlap_events}
    -
    Overlap Events
    -
    -
    -
    ${data.multi_clauding.sessions_involved}
    -
    Sessions Involved
    -
    -
    -
    ${data.total_messages > 0 ? Math.round(100 * data.multi_clauding.user_messages_during / data.total_messages) : 0}%
    -
    Of Messages
    -
    -
    -

    - You run multiple Claude Code sessions simultaneously. Multi-clauding is detected when sessions - overlap in time, suggesting parallel workflows. -

    - `} -
    - - -
    -
    -
    - User Messages by Time of Day - - -
    - ${generateTimeOfDayChart(data.message_hours)} -
    -
    -
    Tool Errors Encountered
    - ${Object.keys(data.tool_error_categories).length > 0 ? generateBarChart(data.tool_error_categories, "#dc2626") : '

    No tool errors

    '} -
    -
    - - ${whatWorksHtml} - -
    -
    -
    What Helped Most (Claude's Capabilities)
    - ${generateBarChart(data.success, "#16a34a")} -
    -
    -
    Outcomes
    - ${generateBarChart(data.outcomes, "#8b5cf6", 6, OUTCOME_ORDER)} -
    -
    - - ${frictionHtml} - -
    -
    -
    Primary Friction Types
    - ${generateBarChart(data.friction, "#dc2626")} -
    -
    -
    Inferred Satisfaction (model-estimated)
    - ${generateBarChart(data.satisfaction, "#eab308", 6, SATISFACTION_ORDER)} -
    -
    - - ${suggestionsHtml} - - ${horizonHtml} - - ${funEndingHtml} - - ${teamFeedbackHtml} -
    - - -`; -} -function buildExportData(data, insights, facets, remoteStats) { - const version7 = typeof MACRO !== "undefined" ? MACRO.VERSION : "unknown"; - const remote_hosts_collected = remoteStats?.hosts.filter((h5) => h5.sessionCount > 0).map((h5) => h5.name); - const facets_summary = { - total: facets.size, - goal_categories: {}, - outcomes: {}, - satisfaction: {}, - friction: {} - }; - for (const f4 of facets.values()) { - for (const [cat2, count4] of safeEntries(f4.goal_categories)) { - if (count4 > 0) { - facets_summary.goal_categories[cat2] = (facets_summary.goal_categories[cat2] || 0) + count4; - } - } - facets_summary.outcomes[f4.outcome] = (facets_summary.outcomes[f4.outcome] || 0) + 1; - for (const [level, count4] of safeEntries(f4.user_satisfaction_counts)) { - if (count4 > 0) { - facets_summary.satisfaction[level] = (facets_summary.satisfaction[level] || 0) + count4; - } - } - for (const [type, count4] of safeEntries(f4.friction_counts)) { - if (count4 > 0) { - facets_summary.friction[type] = (facets_summary.friction[type] || 0) + count4; - } - } - } - return { - metadata: { - username: process.env.SAFEUSER || process.env.USER || "unknown", - generated_at: new Date().toISOString(), - claude_code_version: version7, - date_range: data.date_range, - session_count: data.total_sessions, - ...remote_hosts_collected && remote_hosts_collected.length > 0 && { - remote_hosts_collected - } - }, - aggregated_data: data, - insights, - facets_summary - }; -} -async function scanAllSessions() { - const projectsDir = getProjectsDir2(); - let dirents; - try { - dirents = await readdir28(projectsDir, { withFileTypes: true }); - } catch { - return []; - } - const projectDirs = dirents.filter((dirent) => dirent.isDirectory()).map((dirent) => join139(projectsDir, dirent.name)); - const allSessions = []; - for (let i6 = 0;i6 < projectDirs.length; i6++) { - const sessionFiles = await getSessionFilesWithMtime(projectDirs[i6]); - for (const [sessionId, fileInfo] of sessionFiles) { - allSessions.push({ - sessionId, - path: fileInfo.path, - mtime: fileInfo.mtime, - size: fileInfo.size - }); - } - if (i6 % 10 === 9) { - await new Promise((resolve42) => setImmediate(resolve42)); - } - } - allSessions.sort((a5, b5) => b5.mtime - a5.mtime); - return allSessions; -} -async function generateUsageReport(options2) { - let remoteStats; - if (process.env.USER_TYPE === "ant" && options2?.collectRemote) { - const destDir = join139(getClaudeConfigHomeDir(), "projects"); - const { hosts, totalCopied } = await collectAllRemoteHostData(destDir); - remoteStats = { hosts, totalCopied }; - } - const allScannedSessions = await scanAllSessions(); - const totalSessionsScanned = allScannedSessions.length; - const META_BATCH_SIZE = 50; - const MAX_SESSIONS_TO_LOAD = 200; - let allMetas = []; - const uncachedSessions = []; - for (let i6 = 0;i6 < allScannedSessions.length; i6 += META_BATCH_SIZE) { - const batch = allScannedSessions.slice(i6, i6 + META_BATCH_SIZE); - const results = await Promise.all(batch.map(async (sessionInfo) => ({ - sessionInfo, - cached: await loadCachedSessionMeta(sessionInfo.sessionId) - }))); - for (const { sessionInfo, cached: cached3 } of results) { - if (cached3) { - allMetas.push(cached3); - } else if (uncachedSessions.length < MAX_SESSIONS_TO_LOAD) { - uncachedSessions.push(sessionInfo); - } - } - } - const logsForFacets = new Map; - const isMetaSession = (log3) => { - for (const msg of log3.messages.slice(0, 5)) { - if (msg.type === "user" && msg.message) { - const content = msg.message.content; - if (typeof content === "string") { - if (content.includes("RESPOND WITH ONLY A VALID JSON OBJECT") || content.includes("record_facets")) { - return true; - } - } - } - } - return false; - }; - const LOAD_BATCH_SIZE = 10; - for (let i6 = 0;i6 < uncachedSessions.length; i6 += LOAD_BATCH_SIZE) { - const batch = uncachedSessions.slice(i6, i6 + LOAD_BATCH_SIZE); - const batchResults = await Promise.all(batch.map(async (sessionInfo) => { - try { - return await loadAllLogsFromSessionFile(sessionInfo.path); - } catch { - return []; - } - })); - const metasToSave = []; - for (const logs2 of batchResults) { - for (const log3 of logs2) { - if (isMetaSession(log3) || !hasValidDates(log3)) - continue; - const meta = logToSessionMeta(log3); - allMetas.push(meta); - metasToSave.push(meta); - logsForFacets.set(meta.session_id, log3); - } - } - await Promise.all(metasToSave.map((meta) => saveSessionMeta(meta))); - } - const bestBySession = new Map; - for (const meta of allMetas) { - const existing = bestBySession.get(meta.session_id); - if (!existing || meta.user_message_count > existing.user_message_count || meta.user_message_count === existing.user_message_count && meta.duration_minutes > existing.duration_minutes) { - bestBySession.set(meta.session_id, meta); - } - } - const keptSessionIds = new Set(bestBySession.keys()); - allMetas = [...bestBySession.values()]; - for (const sessionId of logsForFacets.keys()) { - if (!keptSessionIds.has(sessionId)) { - logsForFacets.delete(sessionId); - } - } - allMetas.sort((a5, b5) => b5.start_time.localeCompare(a5.start_time)); - const isSubstantiveSession = (meta) => { - if (meta.user_message_count < 2) - return false; - if (meta.duration_minutes < 1) - return false; - return true; - }; - const substantiveMetas = allMetas.filter(isSubstantiveSession); - const facets = new Map; - const toExtract = []; - const MAX_FACET_EXTRACTIONS = 50; - const cachedFacetResults = await Promise.all(substantiveMetas.map(async (meta) => ({ - sessionId: meta.session_id, - cached: await loadCachedFacets(meta.session_id) - }))); - for (const { sessionId, cached: cached3 } of cachedFacetResults) { - if (cached3) { - facets.set(sessionId, cached3); - } else { - const log3 = logsForFacets.get(sessionId); - if (log3 && toExtract.length < MAX_FACET_EXTRACTIONS) { - toExtract.push({ log: log3, sessionId }); - } - } - } - const CONCURRENCY = 50; - for (let i6 = 0;i6 < toExtract.length; i6 += CONCURRENCY) { - const batch = toExtract.slice(i6, i6 + CONCURRENCY); - const results = await Promise.all(batch.map(async ({ log: log3, sessionId }) => { - const newFacets = await extractFacetsFromAPI(log3, sessionId); - return { sessionId, newFacets }; - })); - const facetsToSave = []; - for (const { sessionId, newFacets } of results) { - if (newFacets) { - facets.set(sessionId, newFacets); - facetsToSave.push(newFacets); - } - } - await Promise.all(facetsToSave.map((f4) => saveFacets(f4))); - } - const isMinimalSession = (sessionId) => { - const sessionFacets = facets.get(sessionId); - if (!sessionFacets) - return false; - const cats = sessionFacets.goal_categories; - const catKeys = safeKeys(cats).filter((k4) => (cats[k4] ?? 0) > 0); - return catKeys.length === 1 && catKeys[0] === "warmup_minimal"; - }; - const substantiveSessions = substantiveMetas.filter((s4) => !isMinimalSession(s4.session_id)); - const substantiveFacets = new Map; - for (const [sessionId, f4] of facets) { - if (!isMinimalSession(sessionId)) { - substantiveFacets.set(sessionId, f4); - } - } - const aggregated = aggregateData(substantiveSessions, substantiveFacets); - aggregated.total_sessions_scanned = totalSessionsScanned; - const insights = await generateParallelInsights(aggregated, facets); - const htmlReport = generateHtmlReport(aggregated, insights); - try { - await mkdir39(getDataDir(), { recursive: true }); - } catch {} - const htmlPath = join139(getDataDir(), "report.html"); - await writeFile43(htmlPath, htmlReport, { - encoding: "utf-8", - mode: 384 - }); - return { - insights, - htmlPath, - data: aggregated, - remoteStats, - facets: substantiveFacets - }; -} -function safeEntries(obj) { - return obj ? Object.entries(obj) : []; -} -function safeKeys(obj) { - return obj ? Object.keys(obj) : []; -} -function isValidSessionFacets(obj) { - if (!obj || typeof obj !== "object") - return false; - const o5 = obj; - return typeof o5.underlying_goal === "string" && typeof o5.outcome === "string" && typeof o5.brief_summary === "string" && o5.goal_categories !== null && typeof o5.goal_categories === "object" && o5.user_satisfaction_counts !== null && typeof o5.user_satisfaction_counts === "object" && o5.friction_counts !== null && typeof o5.friction_counts === "object"; -} -var getRunningRemoteHosts, getRemoteHostSessionCount, collectFromRemoteHost, collectAllRemoteHostData, EXTENSION_TO_LANGUAGE, LABEL_MAP, FACET_EXTRACTION_PROMPT = `Analyze this Claude Code session and extract structured facets. - -CRITICAL GUIDELINES: - -1. **goal_categories**: Count ONLY what the USER explicitly asked for. - - DO NOT count Claude's autonomous codebase exploration - - DO NOT count work Claude decided to do on its own - - ONLY count when user says "can you...", "please...", "I need...", "let's..." - -2. **user_satisfaction_counts**: Base ONLY on explicit user signals. - - "Yay!", "great!", "perfect!" \u2192 happy - - "thanks", "looks good", "that works" \u2192 satisfied - - "ok, now let's..." (continuing without complaint) \u2192 likely_satisfied - - "that's not right", "try again" \u2192 dissatisfied - - "this is broken", "I give up" \u2192 frustrated - -3. **friction_counts**: Be specific about what went wrong. - - misunderstood_request: Claude interpreted incorrectly - - wrong_approach: Right goal, wrong solution method - - buggy_code: Code didn't work correctly - - user_rejected_action: User said no/stop to a tool call - - excessive_changes: Over-engineered or changed too much - -4. If very short or just warmup, use warmup_minimal for goal_category - -SESSION: -`, SUMMARIZE_CHUNK_PROMPT = `Summarize this portion of a Claude Code session transcript. Focus on: -1. What the user asked for -2. What Claude did (tools used, files modified) -3. Any friction or issues -4. The outcome - -Keep it concise - 3-5 sentences. Preserve specific details like file names, error messages, and user feedback. - -TRANSCRIPT CHUNK: -`, INSIGHT_SECTIONS, SATISFACTION_ORDER, OUTCOME_ORDER, usageReport, insights_default; -var init_insights = __esm(() => { - init_lib(); - init_claude(); - init_constants3(); - init_envUtils(); - init_errors(); - init_execFileNoThrow(); - init_log2(); - init_messages9(); - init_model(); - init_sessionStorage(); - init_slowOperations(); - init_stringUtils(); - getRunningRemoteHosts = process.env.USER_TYPE === "ant" ? async () => { - const { stdout, code } = await execFileNoThrow("coder", ["list", "-o", "json"], { timeout: 30000 }); - if (code !== 0) - return []; - try { - const workspaces = jsonParse(stdout); - return workspaces.filter((w2) => w2.latest_build?.status === "running").map((w2) => w2.name); - } catch { - return []; - } - } : async () => []; - getRemoteHostSessionCount = process.env.USER_TYPE === "ant" ? async (homespace) => { - const { stdout, code } = await execFileNoThrow("ssh", [ - `${homespace}.coder`, - 'find /root/.claude/projects -name "*.jsonl" 2>/dev/null | wc -l' - ], { timeout: 30000 }); - if (code !== 0) - return 0; - return parseInt(stdout.trim(), 10) || 0; - } : async () => 0; - collectFromRemoteHost = process.env.USER_TYPE === "ant" ? async (homespace, destDir) => { - const result = { copied: 0, skipped: 0 }; - const tempDir = await mkdtemp3(join139(tmpdir12(), "claude-hs-")); - try { - const scpResult = await execFileNoThrow("scp", ["-rq", `${homespace}.coder:/root/.claude/projects/`, tempDir], { timeout: 300000 }); - if (scpResult.code !== 0) { - return result; - } - const projectsDir = join139(tempDir, "projects"); - let projectDirents; - try { - projectDirents = await readdir28(projectsDir, { withFileTypes: true }); - } catch { - return result; - } - await Promise.all(projectDirents.map(async (dirent) => { - const projectName = dirent.name; - const projectPath = join139(projectsDir, projectName); - if (!dirent.isDirectory()) - return; - const destProjectName = `${projectName}__${homespace}`; - const destProjectPath = join139(destDir, destProjectName); - try { - await mkdir39(destProjectPath, { recursive: true }); - } catch {} - let files3; - try { - files3 = await readdir28(projectPath, { withFileTypes: true }); - } catch { - return; - } - await Promise.all(files3.map(async (fileDirent) => { - const fileName = fileDirent.name; - if (!fileName.endsWith(".jsonl")) - return; - const srcFile = join139(projectPath, fileName); - const destFile = join139(destProjectPath, fileName); - try { - await copyFile11(srcFile, destFile, fsConstants9.COPYFILE_EXCL); - result.copied++; - } catch { - result.skipped++; - } - })); - })); - } finally { - try { - await rm12(tempDir, { recursive: true, force: true }); - } catch {} - } - return result; - } : async () => ({ copied: 0, skipped: 0 }); - collectAllRemoteHostData = process.env.USER_TYPE === "ant" ? async (destDir) => { - const rHosts = await getRunningRemoteHosts(); - const result = []; - let totalCopied = 0; - let totalSkipped = 0; - const hostResults = await Promise.all(rHosts.map(async (hs) => { - const sessionCount = await getRemoteHostSessionCount(hs); - if (sessionCount > 0) { - const { copied, skipped } = await collectFromRemoteHost(hs, destDir); - return { name: hs, sessionCount, copied, skipped }; - } - return { name: hs, sessionCount, copied: 0, skipped: 0 }; - })); - for (const hr2 of hostResults) { - result.push({ name: hr2.name, sessionCount: hr2.sessionCount }); - totalCopied += hr2.copied; - totalSkipped += hr2.skipped; - } - return { hosts: result, totalCopied, totalSkipped }; - } : async () => ({ hosts: [], totalCopied: 0, totalSkipped: 0 }); - EXTENSION_TO_LANGUAGE = { - ".ts": "TypeScript", - ".tsx": "TypeScript", - ".js": "JavaScript", - ".jsx": "JavaScript", - ".py": "Python", - ".rb": "Ruby", - ".go": "Go", - ".rs": "Rust", - ".java": "Java", - ".md": "Markdown", - ".json": "JSON", - ".yaml": "YAML", - ".yml": "YAML", - ".sh": "Shell", - ".css": "CSS", - ".html": "HTML" - }; - LABEL_MAP = { - debug_investigate: "Debug/Investigate", - implement_feature: "Implement Feature", - fix_bug: "Fix Bug", - write_script_tool: "Write Script/Tool", - refactor_code: "Refactor Code", - configure_system: "Configure System", - create_pr_commit: "Create PR/Commit", - analyze_data: "Analyze Data", - understand_codebase: "Understand Codebase", - write_tests: "Write Tests", - write_docs: "Write Docs", - deploy_infra: "Deploy/Infra", - warmup_minimal: "Cache Warmup", - fast_accurate_search: "Fast/Accurate Search", - correct_code_edits: "Correct Code Edits", - good_explanations: "Good Explanations", - proactive_help: "Proactive Help", - multi_file_changes: "Multi-file Changes", - handled_complexity: "Multi-file Changes", - good_debugging: "Good Debugging", - misunderstood_request: "Misunderstood Request", - wrong_approach: "Wrong Approach", - buggy_code: "Buggy Code", - user_rejected_action: "User Rejected Action", - claude_got_blocked: "Claude Got Blocked", - user_stopped_early: "User Stopped Early", - wrong_file_or_location: "Wrong File/Location", - excessive_changes: "Excessive Changes", - slow_or_verbose: "Slow/Verbose", - tool_failed: "Tool Failed", - user_unclear: "User Unclear", - external_issue: "External Issue", - frustrated: "Frustrated", - dissatisfied: "Dissatisfied", - likely_satisfied: "Likely Satisfied", - satisfied: "Satisfied", - happy: "Happy", - unsure: "Unsure", - neutral: "Neutral", - delighted: "Delighted", - single_task: "Single Task", - multi_task: "Multi Task", - iterative_refinement: "Iterative Refinement", - exploration: "Exploration", - quick_question: "Quick Question", - fully_achieved: "Fully Achieved", - mostly_achieved: "Mostly Achieved", - partially_achieved: "Partially Achieved", - not_achieved: "Not Achieved", - unclear_from_transcript: "Unclear", - unhelpful: "Unhelpful", - slightly_helpful: "Slightly Helpful", - moderately_helpful: "Moderately Helpful", - very_helpful: "Very Helpful", - essential: "Essential" - }; - INSIGHT_SECTIONS = [ - { - name: "project_areas", - prompt: `Analyze this Claude Code usage data and identify project areas. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "areas": [ - {"name": "Area name", "session_count": N, "description": "2-3 sentences about what was worked on and how Claude Code was used."} - ] -} - -Include 4-5 areas. Skip internal CC operations.`, - maxTokens: 8192 - }, - { - name: "interaction_style", - prompt: `Analyze this Claude Code usage data and describe the user's interaction style. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "narrative": "2-3 paragraphs analyzing HOW the user interacts with Claude Code. Use second person 'you'. Describe patterns: iterate quickly vs detailed upfront specs? Interrupt often or let Claude run? Include specific examples. Use **bold** for key insights.", - "key_pattern": "One sentence summary of most distinctive interaction style" -}`, - maxTokens: 8192 - }, - { - name: "what_works", - prompt: `Analyze this Claude Code usage data and identify what's working well for this user. Use second person ("you"). - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "intro": "1 sentence of context", - "impressive_workflows": [ - {"title": "Short title (3-6 words)", "description": "2-3 sentences describing the impressive workflow or approach. Use 'you' not 'the user'."} - ] -} - -Include 3 impressive workflows.`, - maxTokens: 8192 - }, - { - name: "friction_analysis", - prompt: `Analyze this Claude Code usage data and identify friction points for this user. Use second person ("you"). - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "intro": "1 sentence summarizing friction patterns", - "categories": [ - {"category": "Concrete category name", "description": "1-2 sentences explaining this category and what could be done differently. Use 'you' not 'the user'.", "examples": ["Specific example with consequence", "Another example"]} - ] -} - -Include 3 friction categories with 2 examples each.`, - maxTokens: 8192 - }, - { - name: "suggestions", - prompt: `Analyze this Claude Code usage data and suggest improvements. - -## CC FEATURES REFERENCE (pick from these for features_to_try): -1. **MCP Servers**: Connect Claude to external tools, databases, and APIs via Model Context Protocol. - - How to use: Run \`claude mcp add -- \` - - Good for: database queries, Slack integration, GitHub issue lookup, connecting to internal APIs - -2. **Custom Skills**: Reusable prompts you define as markdown files that run with a single /command. - - How to use: Create \`.claude/skills/commit/SKILL.md\` with instructions. Then type \`/commit\` to run it. - - Good for: repetitive workflows - /commit, /review, /test, /deploy, /pr, or complex multi-step workflows - -3. **Hooks**: Shell commands that auto-run at specific lifecycle events. - - How to use: Add to \`.claude/settings.json\` under "hooks" key. - - Good for: auto-formatting code, running type checks, enforcing conventions - -4. **Headless Mode**: Run Claude non-interactively from scripts and CI/CD. - - How to use: \`claude -p "fix lint errors" --allowedTools "Edit,Read,Bash"\` - - Good for: CI/CD integration, batch code fixes, automated reviews - -5. **Task Agents**: Claude spawns focused sub-agents for complex exploration or parallel work. - - How to use: Claude auto-invokes when helpful, or ask "use an agent to explore X" - - Good for: codebase exploration, understanding complex systems - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "claude_md_additions": [ - {"addition": "A specific line or block to add to CLAUDE.md based on workflow patterns. E.g., 'Always run tests after modifying auth-related files'", "why": "1 sentence explaining why this would help based on actual sessions", "prompt_scaffold": "Instructions for where to add this in CLAUDE.md. E.g., 'Add under ## Testing section'"} - ], - "features_to_try": [ - {"feature": "Feature name from CC FEATURES REFERENCE above", "one_liner": "What it does", "why_for_you": "Why this would help YOU based on your sessions", "example_code": "Actual command or config to copy"} - ], - "usage_patterns": [ - {"title": "Short title", "suggestion": "1-2 sentence summary", "detail": "3-4 sentences explaining how this applies to YOUR work", "copyable_prompt": "A specific prompt to copy and try"} - ] -} - -IMPORTANT for claude_md_additions: PRIORITIZE instructions that appear MULTIPLE TIMES in the user data. If user told Claude the same thing in 2+ sessions (e.g., 'always run tests', 'use TypeScript'), that's a PRIME candidate - they shouldn't have to repeat themselves. - -IMPORTANT for features_to_try: Pick 2-3 from the CC FEATURES REFERENCE above. Include 2-3 items for each category.`, - maxTokens: 8192 - }, - { - name: "on_the_horizon", - prompt: `Analyze this Claude Code usage data and identify future opportunities. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "intro": "1 sentence about evolving AI-assisted development", - "opportunities": [ - {"title": "Short title (4-8 words)", "whats_possible": "2-3 ambitious sentences about autonomous workflows", "how_to_try": "1-2 sentences mentioning relevant tooling", "copyable_prompt": "Detailed prompt to try"} - ] -} - -Include 3 opportunities. Think BIG - autonomous workflows, parallel agents, iterating against tests.`, - maxTokens: 8192 - }, - ...process.env.USER_TYPE === "ant" ? [ - { - name: "cc_team_improvements", - prompt: `Analyze this Claude Code usage data and suggest product improvements for the CC team. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "improvements": [ - {"title": "Product/tooling improvement", "detail": "3-4 sentences describing the improvement", "evidence": "3-4 sentences with specific session examples"} - ] -} - -Include 2-3 improvements based on friction patterns observed.`, - maxTokens: 8192 - }, - { - name: "model_behavior_improvements", - prompt: `Analyze this Claude Code usage data and suggest model behavior improvements. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "improvements": [ - {"title": "Model behavior change", "detail": "3-4 sentences describing what the model should do differently", "evidence": "3-4 sentences with specific examples"} - ] -} - -Include 2-3 improvements based on friction patterns observed.`, - maxTokens: 8192 - } - ] : [], - { - name: "fun_ending", - prompt: `Analyze this Claude Code usage data and find a memorable moment. - -RESPOND WITH ONLY A VALID JSON OBJECT: -{ - "headline": "A memorable QUALITATIVE moment from the transcripts - not a statistic. Something human, funny, or surprising.", - "detail": "Brief context about when/where this happened" -} - -Find something genuinely interesting or amusing from the session summaries.`, - maxTokens: 8192 - } - ]; - SATISFACTION_ORDER = [ - "frustrated", - "dissatisfied", - "likely_satisfied", - "satisfied", - "happy", - "unsure" - ]; - OUTCOME_ORDER = [ - "not_achieved", - "partially_achieved", - "mostly_achieved", - "fully_achieved", - "unclear_from_transcript" - ]; - usageReport = { - type: "prompt", - name: "insights", - description: "Generate a report analyzing your Claude Code sessions", - contentLength: 0, - progressMessage: "analyzing your sessions", - source: "builtin", - async getPromptForCommand(args) { - let collectRemote = false; - let remoteHosts = []; - let hasRemoteHosts = false; - if (process.env.USER_TYPE === "ant") { - collectRemote = args?.includes("--homespaces") ?? false; - remoteHosts = await getRunningRemoteHosts(); - hasRemoteHosts = remoteHosts.length > 0; - if (collectRemote && hasRemoteHosts) { - console.error(`Collecting sessions from ${remoteHosts.length} homespace(s): ${remoteHosts.join(", ")}...`); - } - } - const { insights, htmlPath, data, remoteStats } = await generateUsageReport({ collectRemote }); - let reportUrl = `file://${htmlPath}`; - let uploadHint = ""; - if (process.env.USER_TYPE === "ant") { - const timestamp = new Date().toISOString().replace(/[-:]/g, "").replace("T", "_").slice(0, 15); - const username = process.env.SAFEUSER || process.env.USER || "unknown"; - const filename = `${username}_insights_${timestamp}.html`; - const s3Path = `s3://anthropic-serve/atamkin/cc-user-reports/${filename}`; - const s3Url = `https://s3-frontend.infra.ant.dev/anthropic-serve/atamkin/cc-user-reports/${filename}`; - reportUrl = s3Url; - try { - execFileSync4("ff", ["cp", htmlPath, s3Path], { - timeout: 60000, - stdio: "pipe" - }); - } catch { - reportUrl = `file://${htmlPath}`; - uploadHint = ` -Automatic upload failed. Are you on the boron namespace? Try \`use-bo\` and ensure you've run \`sso\`. -To share, run: ff cp ${htmlPath} ${s3Path} -Then access at: ${s3Url}`; - } - } - const sessionLabel = data.total_sessions_scanned && data.total_sessions_scanned > data.total_sessions ? `${data.total_sessions_scanned.toLocaleString()} sessions total \xB7 ${data.total_sessions} analyzed` : `${data.total_sessions} sessions`; - const stats2 = [ - sessionLabel, - `${data.total_messages.toLocaleString()} messages`, - `${Math.round(data.total_duration_hours)}h`, - `${data.git_commits} commits` - ].join(" \xB7 "); - let remoteInfo = ""; - if (process.env.USER_TYPE === "ant") { - if (remoteStats && remoteStats.totalCopied > 0) { - const hsNames = remoteStats.hosts.filter((h5) => h5.sessionCount > 0).map((h5) => h5.name).join(", "); - remoteInfo = ` -_Collected ${remoteStats.totalCopied} new sessions from: ${hsNames}_ -`; - } else if (!collectRemote && hasRemoteHosts) { - remoteInfo = ` -_Tip: Run \`/insights --homespaces\` to include sessions from your ${remoteHosts.length} running homespace(s)_ -`; - } - } - const atAGlance = insights.at_a_glance; - const summaryText = atAGlance ? `## At a Glance - -${atAGlance.whats_working ? `**What's working:** ${atAGlance.whats_working} See _Impressive Things You Did_.` : ""} - -${atAGlance.whats_hindering ? `**What's hindering you:** ${atAGlance.whats_hindering} See _Where Things Go Wrong_.` : ""} - -${atAGlance.quick_wins ? `**Quick wins to try:** ${atAGlance.quick_wins} See _Features to Try_.` : ""} - -${atAGlance.ambitious_workflows ? `**Ambitious workflows:** ${atAGlance.ambitious_workflows} See _On the Horizon_.` : ""}` : "_No insights generated_"; - const header = `# Claude Code Insights - -${stats2} -${data.date_range.start} to ${data.date_range.end} -${remoteInfo} -`; - const userSummary = `${header}${summaryText} - -Your full shareable insights report is ready: ${reportUrl}${uploadHint}`; - return [ - { - type: "text", - text: `The user just ran /insights to generate a usage report analyzing their Claude Code sessions. - -Here is the full insights data: -${jsonStringify(insights, null, 2)} - -Report URL: ${reportUrl} -HTML file: ${htmlPath} -Facets directory: ${getFacetsDir()} - -Here is what the user sees: -${userSummary} - -Now output the following message exactly: - - -Your shareable insights report is ready: -${reportUrl}${uploadHint} - -Want to dig into any section or try one of the suggestions? -` - } - ]; - } - }; - insights_default = usageReport; -}); - -// src/commands.ts -async function getSkills(cwd2) { - try { - const [skillDirCommands, pluginSkills] = await Promise.all([ - getSkillDirCommands(cwd2).catch((err2) => { - logError2(toError(err2)); - logForDebugging("Skill directory commands failed to load, continuing without them"); - return []; - }), - getPluginSkills().catch((err2) => { - logError2(toError(err2)); - logForDebugging("Plugin skills failed to load, continuing without them"); - return []; - }) - ]); - const bundledSkills2 = getBundledSkills(); - const builtinPluginSkills = getBuiltinPluginSkillCommands(); - logForDebugging(`getSkills returning: ${skillDirCommands.length} skill dir commands, ${pluginSkills.length} plugin skills, ${bundledSkills2.length} bundled skills, ${builtinPluginSkills.length} builtin plugin skills`); - return { - skillDirCommands, - pluginSkills, - bundledSkills: bundledSkills2, - builtinPluginSkills - }; - } catch (err2) { - logError2(toError(err2)); - logForDebugging("Unexpected error in getSkills, returning empty"); - return { - skillDirCommands: [], - pluginSkills: [], - bundledSkills: [], - builtinPluginSkills: [] - }; - } -} -function meetsAvailabilityRequirement(cmd) { - if (!cmd.availability) - return true; - for (const a5 of cmd.availability) { - switch (a5) { - case "claude-ai": - if (isClaudeAISubscriber()) - return true; - break; - case "console": - if (!isClaudeAISubscriber() && !isUsing3PServices() && isFirstPartyAnthropicBaseUrl()) - return true; - break; - default: { - const _exhaustive = a5; - break; - } - } - } - return false; -} -async function getCommands(cwd2) { - const allCommands = await loadAllCommands(cwd2); - const dynamicSkills2 = getDynamicSkills(); - const baseCommands = allCommands.filter((_) => meetsAvailabilityRequirement(_) && isCommandEnabled(_)); - if (dynamicSkills2.length === 0) { - return baseCommands; - } - const baseCommandNames = new Set(baseCommands.map((c9) => c9.name)); - const uniqueDynamicSkills = dynamicSkills2.filter((s4) => !baseCommandNames.has(s4.name) && meetsAvailabilityRequirement(s4) && isCommandEnabled(s4)); - if (uniqueDynamicSkills.length === 0) { - return baseCommands; - } - const builtInNames = new Set(COMMANDS().map((c9) => c9.name)); - const insertIndex = baseCommands.findIndex((c9) => builtInNames.has(c9.name)); - if (insertIndex === -1) { - return [...baseCommands, ...uniqueDynamicSkills]; - } - return [ - ...baseCommands.slice(0, insertIndex), - ...uniqueDynamicSkills, - ...baseCommands.slice(insertIndex) - ]; -} -function clearCommandMemoizationCaches() { - loadAllCommands.cache?.clear?.(); - getSkillToolCommands.cache?.clear?.(); - getSlashCommandToolSkills.cache?.clear?.(); - clearSkillIndexCache2?.(); -} -function clearCommandsCache() { - clearCommandMemoizationCaches(); - clearPluginCommandCache(); - clearPluginSkillsCache(); - clearSkillCaches(); -} -function getMcpSkillCommands(mcpCommands) { - if (false) {} - return []; -} -function isBridgeSafeCommand(cmd) { - if (cmd.type === "local-jsx") - return false; - if (cmd.type === "prompt") - return true; - return BRIDGE_SAFE_COMMANDS.has(cmd); -} -function filterCommandsForRemoteMode(commands7) { - return commands7.filter((cmd) => REMOTE_SAFE_COMMANDS.has(cmd)); -} -function findCommand(commandName, commands7) { - return commands7.find((_) => _.name === commandName || getCommandName(_) === commandName || _.aliases?.includes(commandName)); -} -function hasCommand(commandName, commands7) { - return findCommand(commandName, commands7) !== undefined; -} -function getCommand(commandName, commands7) { - const command19 = findCommand(commandName, commands7); - if (!command19) { - throw ReferenceError(`Command ${commandName} not found. Available commands: ${commands7.map((_) => { - const name3 = getCommandName(_); - return _.aliases ? `${name3} (aliases: ${_.aliases.join(", ")})` : name3; - }).sort((a5, b5) => a5.localeCompare(b5)).join(", ")}`); - } - return command19; -} -function formatDescriptionWithSource(cmd) { - if (cmd.type !== "prompt") { - return cmd.description; - } - if (cmd.kind === "workflow") { - return `${cmd.description} (workflow)`; - } - if (cmd.source === "plugin") { - const pluginName = cmd.pluginInfo?.pluginManifest.name; - if (pluginName) { - return `(${pluginName}) ${cmd.description}`; - } - return `${cmd.description} (plugin)`; - } - if (cmd.source === "builtin" || cmd.source === "mcp") { - return cmd.description; - } - if (cmd.source === "bundled") { - return `${cmd.description} (bundled)`; - } - return `${cmd.description} (${getSettingSourceName(cmd.source)})`; -} -var agentsPlatform, proactive = null, briefCommand = null, assistantCommand = null, bridge = null, remoteControlServerCommand = null, voiceCommand = null, forceSnip = null, workflowsCmd = null, webCmd = null, clearSkillIndexCache2 = null, subscribePr = null, ultraplan = null, torch = null, peersCmd = null, forkCmd = null, buddy = null, usageReport2, INTERNAL_ONLY_COMMANDS2, COMMANDS, builtInCommandNames, getWorkflowCommands = null, loadAllCommands, getSkillToolCommands, getSlashCommandToolSkills, REMOTE_SAFE_COMMANDS, BRIDGE_SAFE_COMMANDS; -var init_commands5 = __esm(() => { - init_add_dir2(); - init_autofix_pr(); - init_backfill_sessions(); - init_btw2(); - init_good_claude(); - init_issue(); - init_feedback2(); - init_clear2(); - init_color3(); - init_commit(); - init_copy2(); - init_desktop2(); - init_commit_push_pr(); - init_compact3(); - init_config15(); - init_context3(); - init_cost2(); - init_diff4(); - init_ctx_viz(); - init_doctor2(); - init_memory2(); - init_help2(); - init_ide3(); - init_init2(); - init_init_verifiers(); - init_keybindings2(); - init_login2(); - init_logout2(); - init_install_github_app2(); - init_install_slack_app2(); - init_break_cache(); - init_mcp3(); - init_mobile2(); - init_onboarding(); - init_pr_comments(); - init_release_notes2(); - init_rename2(); - init_resume2(); - init_review(); - init_session2(); - init_share(); - init_skills5(); - init_status3(); - init_tasks4(); - init_teleport2(); - init_security_review(); - init_bughunter(); - init_terminalSetup2(); - init_usage3(); - init_theme4(); - init_vim2(); - init_thinkback2(); - init_thinkback_play2(); - init_permissions4(); - init_plan2(); - init_fast2(); - init_passes2(); - init_privacy_settings2(); - init_hooks5(); - init_files7(); - init_branch2(); - init_agents2(); - init_plugin2(); - init_reload_plugins2(); - init_rewind(); - init_heapdump2(); - init_mock_limits(); - init_bridge_kick(); - init_version(); - init_summary(); - init_reset_limits(); - init_ant_trace(); - init_perf_issue(); - init_sandbox_toggle2(); - init_chrome2(); - init_stickers2(); - init_advisor2(); - init_log2(); - init_errors(); - init_debug(); - init_loadSkillsDir(); - init_bundledSkills(); - init_builtinPlugins(); - init_loadPluginCommands(); - init_memoize(); - init_auth14(); - init_providers(); - init_env2(); - init_exit2(); - init_export2(); - init_model3(); - init_tag2(); - init_output_style(); - init_remote_env2(); - init_upgrade2(); - init_extra_usage2(); - init_rate_limit_options2(); - init_statusline(); - init_effort3(); - init_stats3(); - init_oauth_refresh(); - init_debug_tool_call(); - init_constants2(); - agentsPlatform = process.env.USER_TYPE === "ant" ? __toCommonJS(exports_agents_platform).default : null; - usageReport2 = { - type: "prompt", - name: "insights", - description: "Generate a report analyzing your Claude Code sessions", - contentLength: 0, - progressMessage: "analyzing your sessions", - source: "builtin", - async getPromptForCommand(args, context7) { - const real = (await Promise.resolve().then(() => (init_insights(), exports_insights))).default; - if (real.type !== "prompt") - throw new Error("unreachable"); - return real.getPromptForCommand(args, context7); - } - }; - INTERNAL_ONLY_COMMANDS2 = [ - backfill_sessions_default, - break_cache_default, - bughunter_default, - commit_default, - commit_push_pr_default, - ctx_viz_default, - good_claude_default, - issue_default, - init_verifiers_default, - ...forceSnip ? [forceSnip] : [], - mock_limits_default, - bridge_kick_default, - version_default, - ...ultraplan ? [ultraplan] : [], - ...subscribePr ? [subscribePr] : [], - resetLimits, - resetLimitsNonInteractive, - onboarding_default, - share_default, - summary_default, - teleport_default, - ant_trace_default, - perf_issue_default, - env_default, - oauth_refresh_default, - debug_tool_call_default, - agentsPlatform, - autofix_pr_default - ].filter(Boolean); - COMMANDS = memoize_default(() => [ - add_dir_default, - advisor_default, - agents_default, - branch_default, - btw_default, - chrome_default, - clear_default, - color_default, - compact_default, - config_default, - copy_default, - desktop_default, - context6, - contextNonInteractive, - cost_default, - diff_default, - doctor_default, - effort_default, - exit_default, - fast_default, - files_default, - heapdump_default, - help_default, - ide_default, - init_default3, - keybindings_default, - install_github_app_default, - install_slack_app_default, - mcp_default, - memory_default, - mobile_default, - model_default, - output_style_default, - remote_env_default, - plugin_default, - pr_comments_default, - release_notes_default, - reload_plugins_default, - rename_default, - resume_default, - session_default, - skills_default, - stats_default, - status_default, - statusline_default, - stickers_default, - tag_default, - theme_default, - feedback_default, - review_default, - ultrareview, - rewind_default, - security_review_default, - terminalSetup_default, - upgrade_default, - extraUsage, - extraUsageNonInteractive, - rate_limit_options_default, - usage_default, - usageReport2, - vim_default, - ...webCmd ? [webCmd] : [], - ...forkCmd ? [forkCmd] : [], - ...buddy ? [buddy] : [], - ...proactive ? [proactive] : [], - ...briefCommand ? [briefCommand] : [], - ...assistantCommand ? [assistantCommand] : [], - ...bridge ? [bridge] : [], - ...remoteControlServerCommand ? [remoteControlServerCommand] : [], - ...voiceCommand ? [voiceCommand] : [], - thinkback_default, - thinkback_play_default, - permissions_default, - plan_default, - privacy_settings_default, - hooks_default, - export_default, - sandbox_toggle_default, - ...!isUsing3PServices() ? [logout_default, login_default()] : [], - passes_default, - ...peersCmd ? [peersCmd] : [], - tasks_default, - ...workflowsCmd ? [workflowsCmd] : [], - ...torch ? [torch] : [], - ...process.env.USER_TYPE === "ant" && !process.env.IS_DEMO ? INTERNAL_ONLY_COMMANDS2 : [] - ]); - builtInCommandNames = memoize_default(() => new Set(COMMANDS().flatMap((_) => [_.name, ..._.aliases ?? []]))); - loadAllCommands = memoize_default(async (cwd2) => { - const [ - { skillDirCommands, pluginSkills, bundledSkills: bundledSkills2, builtinPluginSkills }, - pluginCommands, - workflowCommands - ] = await Promise.all([ - getSkills(cwd2), - getPluginCommands(), - getWorkflowCommands ? getWorkflowCommands(cwd2) : Promise.resolve([]) - ]); - return [ - ...bundledSkills2, - ...builtinPluginSkills, - ...skillDirCommands, - ...workflowCommands, - ...pluginCommands, - ...pluginSkills, - ...COMMANDS() - ]; - }); - getSkillToolCommands = memoize_default(async (cwd2) => { - const allCommands = await getCommands(cwd2); - return allCommands.filter((cmd) => cmd.type === "prompt" && !cmd.disableModelInvocation && cmd.source !== "builtin" && (cmd.loadedFrom === "bundled" || cmd.loadedFrom === "skills" || cmd.loadedFrom === "commands_DEPRECATED" || cmd.hasUserSpecifiedDescription || cmd.whenToUse)); - }); - getSlashCommandToolSkills = memoize_default(async (cwd2) => { - try { - const allCommands = await getCommands(cwd2); - return allCommands.filter((cmd) => cmd.type === "prompt" && cmd.source !== "builtin" && (cmd.hasUserSpecifiedDescription || cmd.whenToUse) && (cmd.loadedFrom === "skills" || cmd.loadedFrom === "plugin" || cmd.loadedFrom === "bundled" || cmd.disableModelInvocation)); - } catch (error46) { - logError2(toError(error46)); - logForDebugging("Returning empty skills array due to load failure"); - return []; - } - }); - REMOTE_SAFE_COMMANDS = new Set([ - session_default, - exit_default, - clear_default, - help_default, - theme_default, - color_default, - vim_default, - cost_default, - usage_default, - copy_default, - btw_default, - feedback_default, - plan_default, - keybindings_default, - statusline_default, - stickers_default, - mobile_default - ]); - BRIDGE_SAFE_COMMANDS = new Set([ - compact_default, - clear_default, - cost_default, - summary_default, - release_notes_default, - files_default - ].filter((c9) => c9 !== null)); -}); - -// src/utils/sessionStorage.ts -var exports_sessionStorage = {}; -__export(exports_sessionStorage, { - writeRemoteAgentMetadata: () => writeRemoteAgentMetadata, - writeAgentMetadata: () => writeAgentMetadata, - setSessionFileForTesting: () => setSessionFileForTesting, - setRemoteIngressUrlForTesting: () => setRemoteIngressUrlForTesting, - setInternalEventWriter: () => setInternalEventWriter, - setInternalEventReader: () => setInternalEventReader, - setAgentTranscriptSubdir: () => setAgentTranscriptSubdir, - sessionIdExists: () => sessionIdExists, - searchSessionsByCustomTitle: () => searchSessionsByCustomTitle, - saveWorktreeState: () => saveWorktreeState, - saveTaskSummary: () => saveTaskSummary, - saveTag: () => saveTag, - saveMode: () => saveMode, - saveCustomTitle: () => saveCustomTitle, - saveAiGeneratedTitle: () => saveAiGeneratedTitle, - saveAgentSetting: () => saveAgentSetting, - saveAgentName: () => saveAgentName, - saveAgentColor: () => saveAgentColor, - restoreSessionMetadata: () => restoreSessionMetadata, - resetSessionFilePointer: () => resetSessionFilePointer, - resetProjectForTesting: () => resetProjectForTesting, - resetProjectFlushStateForTesting: () => resetProjectFlushStateForTesting, - removeTranscriptMessage: () => removeTranscriptMessage, - removeExtraFields: () => removeExtraFields, - recordTranscript: () => recordTranscript, - recordSidechainTranscript: () => recordSidechainTranscript, - recordQueueOperation: () => recordQueueOperation, - recordFileHistorySnapshot: () => recordFileHistorySnapshot, - recordContextCollapseSnapshot: () => recordContextCollapseSnapshot, - recordContextCollapseCommit: () => recordContextCollapseCommit, - recordContentReplacement: () => recordContentReplacement, - recordAttributionSnapshot: () => recordAttributionSnapshot, - readRemoteAgentMetadata: () => readRemoteAgentMetadata, - readAgentMetadata: () => readAgentMetadata, - reAppendSessionMetadata: () => reAppendSessionMetadata, - loadTranscriptFromFile: () => loadTranscriptFromFile, - loadTranscriptFile: () => loadTranscriptFile, - loadSubagentTranscripts: () => loadSubagentTranscripts, - loadSameRepoMessageLogsProgressive: () => loadSameRepoMessageLogsProgressive, - loadSameRepoMessageLogs: () => loadSameRepoMessageLogs, - loadMessageLogs: () => loadMessageLogs, - loadFullLog: () => loadFullLog, - loadAllSubagentTranscriptsFromDisk: () => loadAllSubagentTranscriptsFromDisk, - loadAllProjectsMessageLogsProgressive: () => loadAllProjectsMessageLogsProgressive, - loadAllProjectsMessageLogs: () => loadAllProjectsMessageLogs, - loadAllLogsFromSessionFile: () => loadAllLogsFromSessionFile, - listRemoteAgentMetadata: () => listRemoteAgentMetadata, - linkSessionToPR: () => linkSessionToPR, - isTranscriptMessage: () => isTranscriptMessage, - isLoggableMessage: () => isLoggableMessage, - isLiteLog: () => isLiteLog, - isEphemeralToolProgress: () => isEphemeralToolProgress, - isCustomTitleEnabled: () => isCustomTitleEnabled, - isChainParticipant: () => isChainParticipant, - hydrateRemoteSession: () => hydrateRemoteSession, - hydrateFromCCRv2InternalEvents: () => hydrateFromCCRv2InternalEvents, - getUserType: () => getUserType, - getTranscriptPathForSession: () => getTranscriptPathForSession, - getTranscriptPath: () => getTranscriptPath, - getSessionIdFromLog: () => getSessionIdFromLog, - getSessionFilesWithMtime: () => getSessionFilesWithMtime, - getSessionFilesLite: () => getSessionFilesLite, - getProjectsDir: () => getProjectsDir2, - getProjectDir: () => getProjectDir2, - getNodeEnv: () => getNodeEnv, - getLogByIndex: () => getLogByIndex, - getLastSessionLog: () => getLastSessionLog, - getFirstMeaningfulUserMessageTextContent: () => getFirstMeaningfulUserMessageTextContent, - getCurrentSessionTitle: () => getCurrentSessionTitle, - getCurrentSessionTag: () => getCurrentSessionTag, - getCurrentSessionAgentColor: () => getCurrentSessionAgentColor, - getAgentTranscriptPath: () => getAgentTranscriptPath, - getAgentTranscript: () => getAgentTranscript, - flushSessionStorage: () => flushSessionStorage, - findUnresolvedToolUse: () => findUnresolvedToolUse, - fetchLogs: () => fetchLogs, - extractTeammateTranscriptsFromTasks: () => extractTeammateTranscriptsFromTasks, - extractAgentIdsFromMessages: () => extractAgentIdsFromMessages, - enrichLogs: () => enrichLogs, - doesMessageExistInSession: () => doesMessageExistInSession, - deleteRemoteAgentMetadata: () => deleteRemoteAgentMetadata, - clearSessionMetadata: () => clearSessionMetadata, - clearSessionMessagesCache: () => clearSessionMessagesCache, - clearAgentTranscriptSubdir: () => clearAgentTranscriptSubdir, - cleanMessagesForLogging: () => cleanMessagesForLogging, - checkResumeConsistency: () => checkResumeConsistency, - cacheSessionTitle: () => cacheSessionTitle, - buildConversationChain: () => buildConversationChain, - adoptResumedSessionFile: () => adoptResumedSessionFile, - MAX_TRANSCRIPT_READ_BYTES: () => MAX_TRANSCRIPT_READ_BYTES -}); -import { closeSync as closeSync4, fstatSync, openSync as openSync5, readSync as readSync3 } from "fs"; -import { - appendFile as fsAppendFile, - open as fsOpen2, - mkdir as mkdir40, - readdir as readdir29, - readFile as readFile53, - stat as stat44, - unlink as unlink22, - writeFile as writeFile44 -} from "fs/promises"; -import { basename as basename42, dirname as dirname55, join as join140 } from "path"; -function isTranscriptMessage(entry) { - return entry.type === "user" || entry.type === "assistant" || entry.type === "attachment" || entry.type === "system"; -} -function isChainParticipant(m4) { - return m4.type !== "progress"; -} -function isLegacyProgressEntry(entry) { - return typeof entry === "object" && entry !== null && "type" in entry && entry.type === "progress" && "uuid" in entry && typeof entry.uuid === "string"; -} -function isEphemeralToolProgress(dataType) { - return typeof dataType === "string" && EPHEMERAL_PROGRESS_TYPES.has(dataType); -} -function getProjectsDir2() { - return join140(getClaudeConfigHomeDir(), "projects"); -} -function getTranscriptPath() { - const projectDir = getSessionProjectDir() ?? getProjectDir2(getOriginalCwd()); - return join140(projectDir, `${getSessionId()}.jsonl`); -} -function getTranscriptPathForSession(sessionId) { - if (sessionId === getSessionId()) { - return getTranscriptPath(); - } - const projectDir = getProjectDir2(getOriginalCwd()); - return join140(projectDir, `${sessionId}.jsonl`); -} -function setAgentTranscriptSubdir(agentId, subdir) { - agentTranscriptSubdirs.set(agentId, subdir); -} -function clearAgentTranscriptSubdir(agentId) { - agentTranscriptSubdirs.delete(agentId); -} -function getAgentTranscriptPath(agentId) { - const projectDir = getSessionProjectDir() ?? getProjectDir2(getOriginalCwd()); - const sessionId = getSessionId(); - const subdir = agentTranscriptSubdirs.get(agentId); - const base2 = subdir ? join140(projectDir, sessionId, "subagents", subdir) : join140(projectDir, sessionId, "subagents"); - return join140(base2, `agent-${agentId}.jsonl`); -} -function getAgentMetadataPath(agentId) { - return getAgentTranscriptPath(agentId).replace(/\.jsonl$/, ".meta.json"); -} -async function writeAgentMetadata(agentId, metadata) { - const path25 = getAgentMetadataPath(agentId); - await mkdir40(dirname55(path25), { recursive: true }); - await writeFile44(path25, JSON.stringify(metadata)); -} -async function readAgentMetadata(agentId) { - const path25 = getAgentMetadataPath(agentId); - try { - const raw = await readFile53(path25, "utf-8"); - return JSON.parse(raw); - } catch (e4) { - if (isFsInaccessible(e4)) - return null; - throw e4; - } -} -function getRemoteAgentsDir() { - const projectDir = getSessionProjectDir() ?? getProjectDir2(getOriginalCwd()); - return join140(projectDir, getSessionId(), "remote-agents"); -} -function getRemoteAgentMetadataPath(taskId) { - return join140(getRemoteAgentsDir(), `remote-agent-${taskId}.meta.json`); -} -async function writeRemoteAgentMetadata(taskId, metadata) { - const path25 = getRemoteAgentMetadataPath(taskId); - await mkdir40(dirname55(path25), { recursive: true }); - await writeFile44(path25, JSON.stringify(metadata)); -} -async function readRemoteAgentMetadata(taskId) { - const path25 = getRemoteAgentMetadataPath(taskId); - try { - const raw = await readFile53(path25, "utf-8"); - return JSON.parse(raw); - } catch (e4) { - if (isFsInaccessible(e4)) - return null; - throw e4; - } -} -async function deleteRemoteAgentMetadata(taskId) { - const path25 = getRemoteAgentMetadataPath(taskId); - try { - await unlink22(path25); - } catch (e4) { - if (isFsInaccessible(e4)) - return; - throw e4; - } -} -async function listRemoteAgentMetadata() { - const dir = getRemoteAgentsDir(); - let entries; - try { - entries = await readdir29(dir, { withFileTypes: true }); - } catch (e4) { - if (isFsInaccessible(e4)) - return []; - throw e4; - } - const results = []; - for (const entry of entries) { - if (!entry.isFile() || !entry.name.endsWith(".meta.json")) - continue; - try { - const raw = await readFile53(join140(dir, entry.name), "utf-8"); - results.push(JSON.parse(raw)); - } catch (e4) { - logForDebugging(`listRemoteAgentMetadata: skipping ${entry.name}: ${String(e4)}`); - } - } - return results; -} -function sessionIdExists(sessionId) { - const projectDir = getProjectDir2(getOriginalCwd()); - const sessionFile = join140(projectDir, `${sessionId}.jsonl`); - const fs13 = getFsImplementation(); - try { - fs13.statSync(sessionFile); - return true; - } catch { - return false; - } -} -function getNodeEnv() { - return "development"; -} -function getUserType() { - return process.env.USER_TYPE || "external"; -} -function getEntrypoint() { - return process.env.CLAUDE_CODE_ENTRYPOINT; -} -function isCustomTitleEnabled() { - return true; -} -function getProject() { - if (!project) { - project = new Project; - if (!cleanupRegistered4) { - registerCleanup(async () => { - await project?.flush(); - try { - project?.reAppendSessionMetadata(); - } catch {} - }); - cleanupRegistered4 = true; - } - } - return project; -} -function resetProjectFlushStateForTesting() { - project?._resetFlushState(); -} -function resetProjectForTesting() { - project = null; -} -function setSessionFileForTesting(path25) { - getProject().sessionFile = path25; -} -function setInternalEventWriter(writer) { - getProject().setInternalEventWriter(writer); -} -function setInternalEventReader(reader, subagentReader) { - getProject().setInternalEventReader(reader); - getProject().setInternalSubagentEventReader(subagentReader); -} -function setRemoteIngressUrlForTesting(url3) { - getProject().setRemoteIngressUrl(url3); -} - -class Project { - currentSessionTag; - currentSessionTitle; - currentSessionAgentName; - currentSessionAgentColor; - currentSessionLastPrompt; - currentSessionAgentSetting; - currentSessionMode; - currentSessionWorktree; - currentSessionPrNumber; - currentSessionPrUrl; - currentSessionPrRepository; - sessionFile = null; - pendingEntries = []; - remoteIngressUrl = null; - internalEventWriter = null; - internalEventReader = null; - internalSubagentEventReader = null; - pendingWriteCount = 0; - flushResolvers = []; - writeQueues = new Map; - flushTimer = null; - activeDrain = null; - FLUSH_INTERVAL_MS = 100; - MAX_CHUNK_BYTES = 100 * 1024 * 1024; - constructor() {} - _resetFlushState() { - this.pendingWriteCount = 0; - this.flushResolvers = []; - if (this.flushTimer) - clearTimeout(this.flushTimer); - this.flushTimer = null; - this.activeDrain = null; - this.writeQueues = new Map; - } - incrementPendingWrites() { - this.pendingWriteCount++; - } - decrementPendingWrites() { - this.pendingWriteCount--; - if (this.pendingWriteCount === 0) { - for (const resolve42 of this.flushResolvers) { - resolve42(); - } - this.flushResolvers = []; - } - } - async trackWrite(fn) { - this.incrementPendingWrites(); - try { - return await fn(); - } finally { - this.decrementPendingWrites(); - } - } - enqueueWrite(filePath, entry) { - return new Promise((resolve42) => { - let queue2 = this.writeQueues.get(filePath); - if (!queue2) { - queue2 = []; - this.writeQueues.set(filePath, queue2); - } - queue2.push({ entry, resolve: resolve42 }); - this.scheduleDrain(); - }); - } - scheduleDrain() { - if (this.flushTimer) { - return; - } - this.flushTimer = setTimeout(async () => { - this.flushTimer = null; - this.activeDrain = this.drainWriteQueue(); - await this.activeDrain; - this.activeDrain = null; - if (this.writeQueues.size > 0) { - this.scheduleDrain(); - } - }, this.FLUSH_INTERVAL_MS); - } - async appendToFile(filePath, data) { - try { - await fsAppendFile(filePath, data, { mode: 384 }); - } catch { - await mkdir40(dirname55(filePath), { recursive: true, mode: 448 }); - await fsAppendFile(filePath, data, { mode: 384 }); - } - } - async drainWriteQueue() { - for (const [filePath, queue2] of this.writeQueues) { - if (queue2.length === 0) { - continue; - } - const batch = queue2.splice(0); - let content = ""; - const resolvers2 = []; - for (const { entry, resolve: resolve42 } of batch) { - const line = jsonStringify(entry) + ` -`; - if (content.length + line.length >= this.MAX_CHUNK_BYTES) { - await this.appendToFile(filePath, content); - for (const r4 of resolvers2) { - r4(); - } - resolvers2.length = 0; - content = ""; - } - content += line; - resolvers2.push(resolve42); - } - if (content.length > 0) { - await this.appendToFile(filePath, content); - for (const r4 of resolvers2) { - r4(); - } - } - } - for (const [filePath, queue2] of this.writeQueues) { - if (queue2.length === 0) { - this.writeQueues.delete(filePath); - } - } - } - resetSessionFile() { - this.sessionFile = null; - this.pendingEntries = []; - } - reAppendSessionMetadata(skipTitleRefresh = false) { - if (!this.sessionFile) - return; - const sessionId = getSessionId(); - if (!sessionId) - return; - const tail = readFileTailSync(this.sessionFile); - const tailLines = tail.split(` -`); - if (!skipTitleRefresh) { - const titleLine = tailLines.findLast((l4) => l4.startsWith('{"type":"custom-title"')); - if (titleLine) { - const tailTitle = extractLastJsonStringField(titleLine, "customTitle"); - if (tailTitle !== undefined) { - this.currentSessionTitle = tailTitle || undefined; - } - } - } - const tagLine = tailLines.findLast((l4) => l4.startsWith('{"type":"tag"')); - if (tagLine) { - const tailTag = extractLastJsonStringField(tagLine, "tag"); - if (tailTag !== undefined) { - this.currentSessionTag = tailTag || undefined; - } - } - if (this.currentSessionLastPrompt) { - appendEntryToFile(this.sessionFile, { - type: "last-prompt", - lastPrompt: this.currentSessionLastPrompt, - sessionId - }); - } - if (this.currentSessionTitle) { - appendEntryToFile(this.sessionFile, { - type: "custom-title", - customTitle: this.currentSessionTitle, - sessionId - }); - } - if (this.currentSessionTag) { - appendEntryToFile(this.sessionFile, { - type: "tag", - tag: this.currentSessionTag, - sessionId - }); - } - if (this.currentSessionAgentName) { - appendEntryToFile(this.sessionFile, { - type: "agent-name", - agentName: this.currentSessionAgentName, - sessionId - }); - } - if (this.currentSessionAgentColor) { - appendEntryToFile(this.sessionFile, { - type: "agent-color", - agentColor: this.currentSessionAgentColor, - sessionId - }); - } - if (this.currentSessionAgentSetting) { - appendEntryToFile(this.sessionFile, { - type: "agent-setting", - agentSetting: this.currentSessionAgentSetting, - sessionId - }); - } - if (this.currentSessionMode) { - appendEntryToFile(this.sessionFile, { - type: "mode", - mode: this.currentSessionMode, - sessionId - }); - } - if (this.currentSessionWorktree !== undefined) { - appendEntryToFile(this.sessionFile, { - type: "worktree-state", - worktreeSession: this.currentSessionWorktree, - sessionId - }); - } - if (this.currentSessionPrNumber !== undefined && this.currentSessionPrUrl && this.currentSessionPrRepository) { - appendEntryToFile(this.sessionFile, { - type: "pr-link", - sessionId, - prNumber: this.currentSessionPrNumber, - prUrl: this.currentSessionPrUrl, - prRepository: this.currentSessionPrRepository, - timestamp: new Date().toISOString() - }); - } - } - async flush() { - if (this.flushTimer) { - clearTimeout(this.flushTimer); - this.flushTimer = null; - } - if (this.activeDrain) { - await this.activeDrain; - } - await this.drainWriteQueue(); - if (this.pendingWriteCount === 0) { - return; - } - return new Promise((resolve42) => { - this.flushResolvers.push(resolve42); - }); - } - async removeMessageByUuid(targetUuid) { - return this.trackWrite(async () => { - if (this.sessionFile === null) - return; - try { - let fileSize = 0; - const fh = await fsOpen2(this.sessionFile, "r+"); - try { - const { size } = await fh.stat(); - fileSize = size; - if (size === 0) - return; - const chunkLen = Math.min(size, LITE_READ_BUF_SIZE); - const tailStart = size - chunkLen; - const buf = Buffer.allocUnsafe(chunkLen); - const { bytesRead } = await fh.read(buf, 0, chunkLen, tailStart); - const tail = buf.subarray(0, bytesRead); - const needle = `"uuid":"${targetUuid}"`; - const matchIdx = tail.lastIndexOf(needle); - if (matchIdx >= 0) { - const prevNl = tail.lastIndexOf(10, matchIdx); - if (prevNl >= 0 || tailStart === 0) { - const lineStart = prevNl + 1; - const nextNl = tail.indexOf(10, matchIdx + needle.length); - const lineEnd = nextNl >= 0 ? nextNl + 1 : bytesRead; - const absLineStart = tailStart + lineStart; - const afterLen = bytesRead - lineEnd; - await fh.truncate(absLineStart); - if (afterLen > 0) { - await fh.write(tail, lineEnd, afterLen, absLineStart); - } - return; - } - } - } finally { - await fh.close(); - } - if (fileSize > MAX_TOMBSTONE_REWRITE_BYTES) { - logForDebugging(`Skipping tombstone removal: session file too large (${formatFileSize(fileSize)})`, { level: "warn" }); - return; - } - const content = await readFile53(this.sessionFile, { encoding: "utf-8" }); - const lines2 = content.split(` -`).filter((line) => { - if (!line.trim()) - return true; - try { - const entry = jsonParse(line); - return entry.uuid !== targetUuid; - } catch { - return true; - } - }); - await writeFile44(this.sessionFile, lines2.join(` -`), { - encoding: "utf8" - }); - } catch {} - }); - } - shouldSkipPersistence() { - const allowTestPersistence = isEnvTruthy(process.env.TEST_ENABLE_SESSION_PERSISTENCE); - return getNodeEnv() === "test" && !allowTestPersistence || getSettings_DEPRECATED()?.cleanupPeriodDays === 0 || isSessionPersistenceDisabled() || isEnvTruthy(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY); - } - async materializeSessionFile() { - if (this.shouldSkipPersistence()) - return; - this.ensureCurrentSessionFile(); - this.reAppendSessionMetadata(); - if (this.pendingEntries.length > 0) { - const buffered = this.pendingEntries; - this.pendingEntries = []; - for (const entry of buffered) { - await this.appendEntry(entry); - } - } - } - async insertMessageChain(messages, isSidechain = false, agentId, startingParentUuid, teamInfo) { - return this.trackWrite(async () => { - let parentUuid = startingParentUuid ?? null; - if (this.sessionFile === null && messages.some((m4) => m4.type === "user" || m4.type === "assistant")) { - await this.materializeSessionFile(); - } - let gitBranch; - try { - gitBranch = await getBranch(); - } catch { - gitBranch = undefined; - } - const sessionId = getSessionId(); - const slug = getPlanSlugCache().get(sessionId); - for (const message of messages) { - const isCompactBoundary = isCompactBoundaryMessage(message); - let effectiveParentUuid = parentUuid; - if (message.type === "user" && "sourceToolAssistantUUID" in message && message.sourceToolAssistantUUID) { - effectiveParentUuid = message.sourceToolAssistantUUID; - } - const transcriptMessage = { - parentUuid: isCompactBoundary ? null : effectiveParentUuid, - logicalParentUuid: isCompactBoundary ? parentUuid : undefined, - isSidechain, - teamName: teamInfo?.teamName, - agentName: teamInfo?.agentName, - promptId: message.type === "user" ? getPromptId() ?? undefined : undefined, - agentId, - ...message, - userType: getUserType(), - entrypoint: getEntrypoint(), - cwd: getCwd(), - sessionId, - version: VERSION9, - gitBranch, - slug - }; - await this.appendEntry(transcriptMessage); - if (isChainParticipant(message)) { - parentUuid = message.uuid; - } - } - if (!isSidechain) { - const text = getFirstMeaningfulUserMessageTextContent(messages); - if (text) { - const flat = text.replace(/\n/g, " ").trim(); - this.currentSessionLastPrompt = flat.length > 200 ? flat.slice(0, 200).trim() + "\u2026" : flat; - } - } - }); - } - async insertFileHistorySnapshot(messageId, snapshot2, isSnapshotUpdate) { - return this.trackWrite(async () => { - const fileHistoryMessage = { - type: "file-history-snapshot", - messageId, - snapshot: snapshot2, - isSnapshotUpdate - }; - await this.appendEntry(fileHistoryMessage); - }); - } - async insertQueueOperation(queueOp) { - return this.trackWrite(async () => { - await this.appendEntry(queueOp); - }); - } - async insertAttributionSnapshot(snapshot2) { - return this.trackWrite(async () => { - await this.appendEntry(snapshot2); - }); - } - async insertContentReplacement(replacements3, agentId) { - return this.trackWrite(async () => { - const entry = { - type: "content-replacement", - sessionId: getSessionId(), - agentId, - replacements: replacements3 - }; - await this.appendEntry(entry); - }); - } - async appendEntry(entry, sessionId = getSessionId()) { - if (this.shouldSkipPersistence()) { - return; - } - const currentSessionId = getSessionId(); - const isCurrentSession = sessionId === currentSessionId; - let sessionFile; - if (isCurrentSession) { - if (this.sessionFile === null) { - this.pendingEntries.push(entry); - return; - } - sessionFile = this.sessionFile; - } else { - const existing = await this.getExistingSessionFile(sessionId); - if (!existing) { - logError2(new Error(`appendEntry: session file not found for other session ${sessionId}`)); - return; - } - sessionFile = existing; - } - if (entry.type === "summary") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "custom-title") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "ai-title") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "last-prompt") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "task-summary") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "tag") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "agent-name") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "agent-color") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "agent-setting") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "pr-link") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "file-history-snapshot") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "attribution-snapshot") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "speculation-accept") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "mode") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "worktree-state") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "content-replacement") { - const targetFile = entry.agentId ? getAgentTranscriptPath(entry.agentId) : sessionFile; - this.enqueueWrite(targetFile, entry); - } else if (entry.type === "marble-origami-commit") { - this.enqueueWrite(sessionFile, entry); - } else if (entry.type === "marble-origami-snapshot") { - this.enqueueWrite(sessionFile, entry); - } else { - const messageSet = await getSessionMessages(sessionId); - if (entry.type === "queue-operation") { - this.enqueueWrite(sessionFile, entry); - } else { - const isAgentSidechain = entry.isSidechain && entry.agentId !== undefined; - const targetFile = isAgentSidechain ? getAgentTranscriptPath(asAgentId(entry.agentId)) : sessionFile; - const isNewUuid = !messageSet.has(entry.uuid); - if (isAgentSidechain || isNewUuid) { - this.enqueueWrite(targetFile, entry); - if (!isAgentSidechain) { - messageSet.add(entry.uuid); - if (isTranscriptMessage(entry)) { - await this.persistToRemote(sessionId, entry); - } - } - } - } - } - } - ensureCurrentSessionFile() { - if (this.sessionFile === null) { - this.sessionFile = getTranscriptPath(); - } - return this.sessionFile; - } - existingSessionFiles = new Map; - async getExistingSessionFile(sessionId) { - const cached3 = this.existingSessionFiles.get(sessionId); - if (cached3) - return cached3; - const targetFile = getTranscriptPathForSession(sessionId); - try { - await stat44(targetFile); - this.existingSessionFiles.set(sessionId, targetFile); - return targetFile; - } catch (e4) { - if (isFsInaccessible(e4)) - return null; - throw e4; - } - } - async persistToRemote(sessionId, entry) { - if (isShuttingDown()) { - return; - } - if (this.internalEventWriter) { - try { - await this.internalEventWriter("transcript", entry, { - ...isCompactBoundaryMessage(entry) && { isCompaction: true }, - ...entry.agentId && { agentId: entry.agentId } - }); - } catch { - logEvent("tengu_session_persistence_failed", {}); - logForDebugging("Failed to write transcript as internal event"); - } - return; - } - if (!isEnvTruthy(process.env.ENABLE_SESSION_PERSISTENCE) || !this.remoteIngressUrl) { - return; - } - const success2 = await appendSessionLog(sessionId, entry, this.remoteIngressUrl); - if (!success2) { - logEvent("tengu_session_persistence_failed", {}); - gracefulShutdownSync(1, "other"); - } - } - setRemoteIngressUrl(url3) { - this.remoteIngressUrl = url3; - logForDebugging(`Remote persistence enabled with URL: ${url3}`); - if (url3) { - this.FLUSH_INTERVAL_MS = REMOTE_FLUSH_INTERVAL_MS; - } - } - setInternalEventWriter(writer) { - this.internalEventWriter = writer; - logForDebugging("CCR v2 internal event writer registered for transcript persistence"); - this.FLUSH_INTERVAL_MS = REMOTE_FLUSH_INTERVAL_MS; - } - setInternalEventReader(reader) { - this.internalEventReader = reader; - logForDebugging("CCR v2 internal event reader registered for session resume"); - } - setInternalSubagentEventReader(reader) { - this.internalSubagentEventReader = reader; - logForDebugging("CCR v2 subagent event reader registered for session resume"); - } - getInternalEventReader() { - return this.internalEventReader; - } - getInternalSubagentEventReader() { - return this.internalSubagentEventReader; - } -} -async function recordTranscript(messages, teamInfo, startingParentUuidHint, allMessages) { - const cleanedMessages = cleanMessagesForLogging(messages, allMessages); - const sessionId = getSessionId(); - const messageSet = await getSessionMessages(sessionId); - const newMessages = []; - let startingParentUuid = startingParentUuidHint; - let seenNewMessage = false; - for (const m4 of cleanedMessages) { - if (messageSet.has(m4.uuid)) { - if (!seenNewMessage && isChainParticipant(m4)) { - startingParentUuid = m4.uuid; - } - } else { - newMessages.push(m4); - seenNewMessage = true; - } - } - if (newMessages.length > 0) { - await getProject().insertMessageChain(newMessages, false, undefined, startingParentUuid, teamInfo); - } - const lastRecorded = newMessages.findLast(isChainParticipant); - return lastRecorded?.uuid ?? startingParentUuid ?? null; -} -async function recordSidechainTranscript(messages, agentId, startingParentUuid) { - await getProject().insertMessageChain(cleanMessagesForLogging(messages), true, agentId, startingParentUuid); -} -async function recordQueueOperation(queueOp) { - await getProject().insertQueueOperation(queueOp); -} -async function removeTranscriptMessage(targetUuid) { - await getProject().removeMessageByUuid(targetUuid); -} -async function recordFileHistorySnapshot(messageId, snapshot2, isSnapshotUpdate) { - await getProject().insertFileHistorySnapshot(messageId, snapshot2, isSnapshotUpdate); -} -async function recordAttributionSnapshot(snapshot2) { - await getProject().insertAttributionSnapshot(snapshot2); -} -async function recordContentReplacement(replacements3, agentId) { - await getProject().insertContentReplacement(replacements3, agentId); -} -async function resetSessionFilePointer() { - getProject().resetSessionFile(); -} -function adoptResumedSessionFile() { - const project2 = getProject(); - project2.sessionFile = getTranscriptPath(); - project2.reAppendSessionMetadata(true); -} -async function recordContextCollapseCommit(commit) { - const sessionId = getSessionId(); - if (!sessionId) - return; - await getProject().appendEntry({ - type: "marble-origami-commit", - sessionId, - ...commit - }); -} -async function recordContextCollapseSnapshot(snapshot2) { - const sessionId = getSessionId(); - if (!sessionId) - return; - await getProject().appendEntry({ - type: "marble-origami-snapshot", - sessionId, - ...snapshot2 - }); -} -async function flushSessionStorage() { - await getProject().flush(); -} -async function hydrateRemoteSession(sessionId, ingressUrl) { - switchSession(asSessionId(sessionId)); - const project2 = getProject(); - try { - const remoteLogs = await getSessionLogs(sessionId, ingressUrl) || []; - const projectDir = getProjectDir2(getOriginalCwd()); - await mkdir40(projectDir, { recursive: true, mode: 448 }); - const sessionFile = getTranscriptPathForSession(sessionId); - const content = remoteLogs.map((e4) => jsonStringify(e4) + ` -`).join(""); - await writeFile44(sessionFile, content, { encoding: "utf8", mode: 384 }); - logForDebugging(`Hydrated ${remoteLogs.length} entries from remote`); - return remoteLogs.length > 0; - } catch (error46) { - logForDebugging(`Error hydrating session from remote: ${error46}`); - logForDiagnosticsNoPII("error", "hydrate_remote_session_fail"); - return false; - } finally { - project2.setRemoteIngressUrl(ingressUrl); - } -} -async function hydrateFromCCRv2InternalEvents(sessionId) { - const startMs = Date.now(); - switchSession(asSessionId(sessionId)); - const project2 = getProject(); - const reader = project2.getInternalEventReader(); - if (!reader) { - logForDebugging("No internal event reader registered for CCR v2 resume"); - return false; - } - try { - const events2 = await reader(); - if (!events2) { - logForDebugging("Failed to read internal events for resume"); - logForDiagnosticsNoPII("error", "hydrate_ccr_v2_read_fail"); - return false; - } - const projectDir = getProjectDir2(getOriginalCwd()); - await mkdir40(projectDir, { recursive: true, mode: 448 }); - const sessionFile = getTranscriptPathForSession(sessionId); - const fgContent = events2.map((e4) => jsonStringify(e4.payload) + ` -`).join(""); - await writeFile44(sessionFile, fgContent, { encoding: "utf8", mode: 384 }); - logForDebugging(`Hydrated ${events2.length} foreground entries from CCR v2 internal events`); - let subagentEventCount = 0; - const subagentReader = project2.getInternalSubagentEventReader(); - if (subagentReader) { - const subagentEvents = await subagentReader(); - if (subagentEvents && subagentEvents.length > 0) { - subagentEventCount = subagentEvents.length; - const byAgent = new Map; - for (const e4 of subagentEvents) { - const agentId = e4.agent_id || ""; - if (!agentId) - continue; - let list2 = byAgent.get(agentId); - if (!list2) { - list2 = []; - byAgent.set(agentId, list2); - } - list2.push(e4.payload); - } - for (const [agentId, entries] of byAgent) { - const agentFile = getAgentTranscriptPath(asAgentId(agentId)); - await mkdir40(dirname55(agentFile), { recursive: true, mode: 448 }); - const agentContent = entries.map((p4) => jsonStringify(p4) + ` -`).join(""); - await writeFile44(agentFile, agentContent, { - encoding: "utf8", - mode: 384 - }); - } - logForDebugging(`Hydrated ${subagentEvents.length} subagent entries across ${byAgent.size} agents`); - } - } - logForDiagnosticsNoPII("info", "hydrate_ccr_v2_completed", { - duration_ms: Date.now() - startMs, - event_count: events2.length, - subagent_event_count: subagentEventCount - }); - return events2.length > 0; - } catch (error46) { - if (error46 instanceof Error && error46.message === "CCRClient: Epoch mismatch (409)") { - throw error46; - } - logForDebugging(`Error hydrating session from CCR v2: ${error46}`); - logForDiagnosticsNoPII("error", "hydrate_ccr_v2_fail"); - return false; - } -} -function extractFirstPrompt2(transcript) { - const textContent = getFirstMeaningfulUserMessageTextContent(transcript); - if (textContent) { - let result = textContent.replace(/\n/g, " ").trim(); - if (result.length > 200) { - result = result.slice(0, 200).trim() + "\u2026"; - } - return result; - } - return "No prompt"; -} -function getFirstMeaningfulUserMessageTextContent(transcript) { - for (const msg of transcript) { - if (msg.type !== "user" || msg.isMeta) - continue; - if ("isCompactSummary" in msg && msg.isCompactSummary) - continue; - const content = msg.message?.content; - if (!content) - continue; - const texts = []; - if (typeof content === "string") { - texts.push(content); - } else if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "text" && block2.text) { - texts.push(block2.text); - } - } - } - for (const textContent of texts) { - if (!textContent) - continue; - const commandNameTag = extractTag(textContent, COMMAND_NAME_TAG); - if (commandNameTag) { - const commandName = commandNameTag.replace(/^\//, ""); - if (builtInCommandNames().has(commandName)) { - continue; - } else { - const commandArgs = extractTag(textContent, "command-args")?.trim(); - if (!commandArgs) { - continue; - } - return `${commandNameTag} ${commandArgs}`; - } - } - const bashInput = extractTag(textContent, "bash-input"); - if (bashInput) { - return `! ${bashInput}`; - } - if (SKIP_FIRST_PROMPT_PATTERN.test(textContent)) { - continue; - } - return textContent; - } - } - return; -} -function removeExtraFields(transcript) { - return transcript.map((m4) => { - const { isSidechain, parentUuid, ...serializedMessage } = m4; - return serializedMessage; - }); -} -function applyPreservedSegmentRelinks(messages) { - let lastSeg; - let lastSegBoundaryIdx = -1; - let absoluteLastBoundaryIdx = -1; - const entryIndex = new Map; - let i6 = 0; - for (const entry of messages.values()) { - entryIndex.set(entry.uuid, i6); - if (isCompactBoundaryMessage(entry)) { - absoluteLastBoundaryIdx = i6; - const seg = entry.compactMetadata?.preservedSegment; - if (seg) { - lastSeg = seg; - lastSegBoundaryIdx = i6; - } - } - i6++; - } - if (!lastSeg) - return; - const segIsLive = lastSegBoundaryIdx === absoluteLastBoundaryIdx; - const preservedUuids = new Set; - if (segIsLive) { - const walkSeen = new Set; - let cur = messages.get(lastSeg.tailUuid); - let reachedHead = false; - while (cur && !walkSeen.has(cur.uuid)) { - walkSeen.add(cur.uuid); - preservedUuids.add(cur.uuid); - if (cur.uuid === lastSeg.headUuid) { - reachedHead = true; - break; - } - cur = cur.parentUuid ? messages.get(cur.parentUuid) : undefined; - } - if (!reachedHead) { - logEvent("tengu_relink_walk_broken", { - tailInTranscript: messages.has(lastSeg.tailUuid), - headInTranscript: messages.has(lastSeg.headUuid), - anchorInTranscript: messages.has(lastSeg.anchorUuid), - walkSteps: walkSeen.size, - transcriptSize: messages.size - }); - return; - } - } - if (segIsLive) { - const head = messages.get(lastSeg.headUuid); - if (head) { - messages.set(lastSeg.headUuid, { - ...head, - parentUuid: lastSeg.anchorUuid - }); - } - for (const [uuid8, msg] of messages) { - if (msg.parentUuid === lastSeg.anchorUuid && uuid8 !== lastSeg.headUuid) { - messages.set(uuid8, { ...msg, parentUuid: lastSeg.tailUuid }); - } - } - for (const uuid8 of preservedUuids) { - const msg = messages.get(uuid8); - if (msg?.type !== "assistant") - continue; - messages.set(uuid8, { - ...msg, - message: { - ...msg.message, - usage: { - ...msg.message.usage, - input_tokens: 0, - output_tokens: 0, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0 - } - } - }); - } - } - const toDelete = []; - for (const [uuid8] of messages) { - const idx = entryIndex.get(uuid8); - if (idx !== undefined && idx < absoluteLastBoundaryIdx && !preservedUuids.has(uuid8)) { - toDelete.push(uuid8); - } - } - for (const uuid8 of toDelete) - messages.delete(uuid8); -} -function applySnipRemovals(messages) { - const toDelete = new Set; - for (const entry of messages.values()) { - const removedUuids = entry.snipMetadata?.removedUuids; - if (!removedUuids) - continue; - for (const uuid8 of removedUuids) - toDelete.add(uuid8); - } - if (toDelete.size === 0) - return; - const deletedParent = new Map; - let removedCount = 0; - for (const uuid8 of toDelete) { - const entry = messages.get(uuid8); - if (!entry) - continue; - deletedParent.set(uuid8, entry.parentUuid); - messages.delete(uuid8); - removedCount++; - } - const resolve42 = (start) => { - const path25 = []; - let cur = start; - while (cur && toDelete.has(cur)) { - path25.push(cur); - cur = deletedParent.get(cur); - if (cur === undefined) { - cur = null; - break; - } - } - for (const p4 of path25) - deletedParent.set(p4, cur); - return cur; - }; - let relinkedCount = 0; - for (const [uuid8, msg] of messages) { - if (!msg.parentUuid || !toDelete.has(msg.parentUuid)) - continue; - messages.set(uuid8, { ...msg, parentUuid: resolve42(msg.parentUuid) }); - relinkedCount++; - } - logEvent("tengu_snip_resume_filtered", { - removed_count: removedCount, - relinked_count: relinkedCount - }); -} -function findLatestMessage(messages, predicate) { - let latest; - let maxTime = -Infinity; - for (const m4 of messages) { - if (!predicate(m4)) - continue; - const t4 = Date.parse(m4.timestamp); - if (t4 > maxTime) { - maxTime = t4; - latest = m4; - } - } - return latest; -} -function buildConversationChain(messages, leafMessage) { - const transcript = []; - const seen = new Set; - let currentMsg = leafMessage; - while (currentMsg) { - if (seen.has(currentMsg.uuid)) { - logError2(new Error(`Cycle detected in parentUuid chain at message ${currentMsg.uuid}. Returning partial transcript.`)); - logEvent("tengu_chain_parent_cycle", {}); - break; - } - seen.add(currentMsg.uuid); - transcript.push(currentMsg); - currentMsg = currentMsg.parentUuid ? messages.get(currentMsg.parentUuid) : undefined; - } - transcript.reverse(); - return recoverOrphanedParallelToolResults(messages, transcript, seen); -} -function recoverOrphanedParallelToolResults(messages, chain4, seen) { - const chainAssistants = chain4.filter((m4) => m4.type === "assistant"); - if (chainAssistants.length === 0) - return chain4; - const anchorByMsgId = new Map; - for (const a5 of chainAssistants) { - if (a5.message.id) - anchorByMsgId.set(a5.message.id, a5); - } - const siblingsByMsgId = new Map; - const toolResultsByAsst = new Map; - for (const m4 of messages.values()) { - if (m4.type === "assistant" && m4.message.id) { - const group = siblingsByMsgId.get(m4.message.id); - if (group) - group.push(m4); - else - siblingsByMsgId.set(m4.message.id, [m4]); - } else if (m4.type === "user" && m4.parentUuid && Array.isArray(m4.message.content) && m4.message.content.some((b5) => b5.type === "tool_result")) { - const group = toolResultsByAsst.get(m4.parentUuid); - if (group) - group.push(m4); - else - toolResultsByAsst.set(m4.parentUuid, [m4]); - } - } - const processedGroups = new Set; - const inserts = new Map; - let recoveredCount = 0; - for (const asst of chainAssistants) { - const msgId = asst.message.id; - if (!msgId || processedGroups.has(msgId)) - continue; - processedGroups.add(msgId); - const group = siblingsByMsgId.get(msgId) ?? [asst]; - const orphanedSiblings = group.filter((s4) => !seen.has(s4.uuid)); - const orphanedTRs = []; - for (const member of group) { - const trs = toolResultsByAsst.get(member.uuid); - if (!trs) - continue; - for (const tr of trs) { - if (!seen.has(tr.uuid)) - orphanedTRs.push(tr); - } - } - if (orphanedSiblings.length === 0 && orphanedTRs.length === 0) - continue; - orphanedSiblings.sort((a5, b5) => a5.timestamp.localeCompare(b5.timestamp)); - orphanedTRs.sort((a5, b5) => a5.timestamp.localeCompare(b5.timestamp)); - const anchor = anchorByMsgId.get(msgId); - const recovered = [...orphanedSiblings, ...orphanedTRs]; - for (const r4 of recovered) - seen.add(r4.uuid); - recoveredCount += recovered.length; - inserts.set(anchor.uuid, recovered); - } - if (recoveredCount === 0) - return chain4; - logEvent("tengu_chain_parallel_tr_recovered", { - recovered_count: recoveredCount - }); - const result = []; - for (const m4 of chain4) { - result.push(m4); - const toInsert = inserts.get(m4.uuid); - if (toInsert) - result.push(...toInsert); - } - return result; -} -function checkResumeConsistency(chain4) { - for (let i6 = chain4.length - 1;i6 >= 0; i6--) { - const m4 = chain4[i6]; - if (m4.type !== "system" || m4.subtype !== "turn_duration") - continue; - const expected = m4.messageCount; - if (expected === undefined) - return; - const actual = i6; - logEvent("tengu_resume_consistency_delta", { - expected, - actual, - delta: actual - expected, - chain_length: chain4.length, - checkpoint_age_entries: chain4.length - 1 - i6 - }); - return; - } -} -function buildFileHistorySnapshotChain(fileHistorySnapshots, conversation) { - const snapshots = []; - const indexByMessageId = new Map; - for (const message of conversation) { - const snapshotMessage = fileHistorySnapshots.get(message.uuid); - if (!snapshotMessage) { - continue; - } - const { snapshot: snapshot2, isSnapshotUpdate } = snapshotMessage; - const existingIndex = isSnapshotUpdate ? indexByMessageId.get(snapshot2.messageId) : undefined; - if (existingIndex === undefined) { - indexByMessageId.set(snapshot2.messageId, snapshots.length); - snapshots.push(snapshot2); - } else { - snapshots[existingIndex] = snapshot2; - } - } - return snapshots; -} -function buildAttributionSnapshotChain(attributionSnapshots, _conversation) { - return Array.from(attributionSnapshots.values()); -} -async function loadTranscriptFromFile(filePath) { - if (filePath.endsWith(".jsonl")) { - const { - messages: messages2, - summaries, - customTitles, - tags, - fileHistorySnapshots, - attributionSnapshots, - contextCollapseCommits, - contextCollapseSnapshot, - leafUuids, - contentReplacements, - worktreeStates - } = await loadTranscriptFile(filePath); - if (messages2.size === 0) { - throw new Error("No messages found in JSONL file"); - } - const leafMessage = findLatestMessage(messages2.values(), (msg) => leafUuids.has(msg.uuid)); - if (!leafMessage) { - throw new Error("No valid conversation chain found in JSONL file"); - } - const transcript = buildConversationChain(messages2, leafMessage); - const summary = summaries.get(leafMessage.uuid); - const customTitle = customTitles.get(leafMessage.sessionId); - const tag3 = tags.get(leafMessage.sessionId); - const sessionId = leafMessage.sessionId; - return { - ...convertToLogOption(transcript, 0, summary, customTitle, buildFileHistorySnapshotChain(fileHistorySnapshots, transcript), tag3, filePath, buildAttributionSnapshotChain(attributionSnapshots, transcript), undefined, contentReplacements.get(sessionId) ?? []), - contextCollapseCommits: contextCollapseCommits.filter((e4) => e4.sessionId === sessionId), - contextCollapseSnapshot: contextCollapseSnapshot?.sessionId === sessionId ? contextCollapseSnapshot : undefined, - worktreeSession: worktreeStates.has(sessionId) ? worktreeStates.get(sessionId) : undefined - }; - } - const content = await readFile53(filePath, { encoding: "utf-8" }); - let parsed; - try { - parsed = jsonParse(content); - } catch (error46) { - throw new Error(`Invalid JSON in transcript file: ${error46}`); - } - let messages; - if (Array.isArray(parsed)) { - messages = parsed; - } else if (parsed && typeof parsed === "object" && "messages" in parsed) { - if (!Array.isArray(parsed.messages)) { - throw new Error("Transcript messages must be an array"); - } - messages = parsed.messages; - } else { - throw new Error("Transcript must be an array of messages or an object with a messages array"); - } - return convertToLogOption(messages, 0, undefined, undefined, undefined, undefined, filePath); -} -function hasVisibleUserContent(message) { - if (message.type !== "user") - return false; - if (message.isMeta) - return false; - const content = message.message?.content; - if (!content) - return false; - if (typeof content === "string") { - return content.trim().length > 0; - } - if (Array.isArray(content)) { - return content.some((block2) => block2.type === "text" || block2.type === "image" || block2.type === "document"); - } - return false; -} -function hasVisibleAssistantContent(message) { - if (message.type !== "assistant") - return false; - const content = message.message?.content; - if (!content || !Array.isArray(content)) - return false; - return content.some((block2) => block2.type === "text" && typeof block2.text === "string" && block2.text.trim().length > 0); -} -function countVisibleMessages(transcript) { - let count4 = 0; - for (const message of transcript) { - switch (message.type) { - case "user": - if (hasVisibleUserContent(message)) { - count4++; - } - break; - case "assistant": - if (hasVisibleAssistantContent(message)) { - count4++; - } - break; - case "attachment": - case "system": - case "progress": - break; - } - } - return count4; -} -function convertToLogOption(transcript, value = 0, summary, customTitle, fileHistorySnapshots, tag3, fullPath, attributionSnapshots, agentSetting, contentReplacements) { - const lastMessage = transcript.at(-1); - const firstMessage = transcript[0]; - const firstPrompt = extractFirstPrompt2(transcript); - const created = new Date(firstMessage.timestamp); - const modified = new Date(lastMessage.timestamp); - return { - date: lastMessage.timestamp, - messages: removeExtraFields(transcript), - fullPath, - value, - created, - modified, - firstPrompt, - messageCount: countVisibleMessages(transcript), - isSidechain: firstMessage.isSidechain, - teamName: firstMessage.teamName, - agentName: firstMessage.agentName, - agentSetting, - leafUuid: lastMessage.uuid, - summary, - customTitle, - tag: tag3, - fileHistorySnapshots, - attributionSnapshots, - contentReplacements, - gitBranch: lastMessage.gitBranch, - projectPath: firstMessage.cwd - }; -} -async function trackSessionBranchingAnalytics(logs2) { - const sessionIdCounts = new Map; - let maxCount = 0; - for (const log3 of logs2) { - const sessionId = getSessionIdFromLog(log3); - if (sessionId) { - const newCount = (sessionIdCounts.get(sessionId) || 0) + 1; - sessionIdCounts.set(sessionId, newCount); - maxCount = Math.max(newCount, maxCount); - } - } - if (maxCount <= 1) { - return; - } - const branchCounts = Array.from(sessionIdCounts.values()).filter((c9) => c9 > 1); - const sessionsWithBranches = branchCounts.length; - const totalBranches = branchCounts.reduce((sum, count4) => sum + count4, 0); - logEvent("tengu_session_forked_branches_fetched", { - total_sessions: sessionIdCounts.size, - sessions_with_branches: sessionsWithBranches, - max_branches_per_session: Math.max(...branchCounts), - avg_branches_per_session: Math.round(totalBranches / sessionsWithBranches), - total_transcript_count: logs2.length - }); -} -async function fetchLogs(limit) { - const projectDir = getProjectDir2(getOriginalCwd()); - const logs2 = await getSessionFilesLite(projectDir, limit, getOriginalCwd()); - await trackSessionBranchingAnalytics(logs2); - return logs2; -} -function appendEntryToFile(fullPath, entry) { - const fs13 = getFsImplementation(); - const line = jsonStringify(entry) + ` -`; - try { - fs13.appendFileSync(fullPath, line, { mode: 384 }); - } catch { - fs13.mkdirSync(dirname55(fullPath), { mode: 448 }); - fs13.appendFileSync(fullPath, line, { mode: 384 }); - } -} -function readFileTailSync(fullPath) { - let fd2; - try { - fd2 = openSync5(fullPath, "r"); - const st = fstatSync(fd2); - const tailOffset = Math.max(0, st.size - LITE_READ_BUF_SIZE); - const buf = Buffer.allocUnsafe(Math.min(LITE_READ_BUF_SIZE, st.size - tailOffset)); - const bytesRead = readSync3(fd2, buf, 0, buf.length, tailOffset); - return buf.toString("utf8", 0, bytesRead); - } catch { - return ""; - } finally { - if (fd2 !== undefined) { - try { - closeSync4(fd2); - } catch {} - } - } -} -async function saveCustomTitle(sessionId, customTitle, fullPath, source = "user") { - const resolvedPath5 = fullPath ?? getTranscriptPathForSession(sessionId); - appendEntryToFile(resolvedPath5, { - type: "custom-title", - customTitle, - sessionId - }); - if (sessionId === getSessionId()) { - getProject().currentSessionTitle = customTitle; - } - logEvent("tengu_session_renamed", { - source - }); -} -function saveAiGeneratedTitle(sessionId, aiTitle) { - appendEntryToFile(getTranscriptPathForSession(sessionId), { - type: "ai-title", - aiTitle, - sessionId - }); -} -function saveTaskSummary(sessionId, summary) { - appendEntryToFile(getTranscriptPathForSession(sessionId), { - type: "task-summary", - summary, - sessionId, - timestamp: new Date().toISOString() - }); -} -async function saveTag(sessionId, tag3, fullPath) { - const resolvedPath5 = fullPath ?? getTranscriptPathForSession(sessionId); - appendEntryToFile(resolvedPath5, { type: "tag", tag: tag3, sessionId }); - if (sessionId === getSessionId()) { - getProject().currentSessionTag = tag3; - } - logEvent("tengu_session_tagged", {}); -} -async function linkSessionToPR(sessionId, prNumber, prUrl, prRepository, fullPath) { - const resolvedPath5 = fullPath ?? getTranscriptPathForSession(sessionId); - appendEntryToFile(resolvedPath5, { - type: "pr-link", - sessionId, - prNumber, - prUrl, - prRepository, - timestamp: new Date().toISOString() - }); - if (sessionId === getSessionId()) { - const project2 = getProject(); - project2.currentSessionPrNumber = prNumber; - project2.currentSessionPrUrl = prUrl; - project2.currentSessionPrRepository = prRepository; - } - logEvent("tengu_session_linked_to_pr", { prNumber }); -} -function getCurrentSessionTag(sessionId) { - if (sessionId === getSessionId()) { - return getProject().currentSessionTag; - } - return; -} -function getCurrentSessionTitle(sessionId) { - if (sessionId === getSessionId()) { - return getProject().currentSessionTitle; - } - return; -} -function getCurrentSessionAgentColor() { - return getProject().currentSessionAgentColor; -} -function restoreSessionMetadata(meta) { - const project2 = getProject(); - if (meta.customTitle) - project2.currentSessionTitle ??= meta.customTitle; - if (meta.tag !== undefined) - project2.currentSessionTag = meta.tag || undefined; - if (meta.agentName) - project2.currentSessionAgentName = meta.agentName; - if (meta.agentColor) - project2.currentSessionAgentColor = meta.agentColor; - if (meta.agentSetting) - project2.currentSessionAgentSetting = meta.agentSetting; - if (meta.mode) - project2.currentSessionMode = meta.mode; - if (meta.worktreeSession !== undefined) - project2.currentSessionWorktree = meta.worktreeSession; - if (meta.prNumber !== undefined) - project2.currentSessionPrNumber = meta.prNumber; - if (meta.prUrl) - project2.currentSessionPrUrl = meta.prUrl; - if (meta.prRepository) - project2.currentSessionPrRepository = meta.prRepository; -} -function clearSessionMetadata() { - const project2 = getProject(); - project2.currentSessionTitle = undefined; - project2.currentSessionTag = undefined; - project2.currentSessionAgentName = undefined; - project2.currentSessionAgentColor = undefined; - project2.currentSessionLastPrompt = undefined; - project2.currentSessionAgentSetting = undefined; - project2.currentSessionMode = undefined; - project2.currentSessionWorktree = undefined; - project2.currentSessionPrNumber = undefined; - project2.currentSessionPrUrl = undefined; - project2.currentSessionPrRepository = undefined; -} -function reAppendSessionMetadata() { - getProject().reAppendSessionMetadata(); -} -async function saveAgentName(sessionId, agentName, fullPath, source = "user") { - const resolvedPath5 = fullPath ?? getTranscriptPathForSession(sessionId); - appendEntryToFile(resolvedPath5, { type: "agent-name", agentName, sessionId }); - if (sessionId === getSessionId()) { - getProject().currentSessionAgentName = agentName; - updateSessionName(agentName); - } - logEvent("tengu_agent_name_set", { - source - }); -} -async function saveAgentColor(sessionId, agentColor, fullPath) { - const resolvedPath5 = fullPath ?? getTranscriptPathForSession(sessionId); - appendEntryToFile(resolvedPath5, { - type: "agent-color", - agentColor, - sessionId - }); - if (sessionId === getSessionId()) { - getProject().currentSessionAgentColor = agentColor; - } - logEvent("tengu_agent_color_set", {}); -} -function saveAgentSetting(agentSetting) { - getProject().currentSessionAgentSetting = agentSetting; -} -function cacheSessionTitle(customTitle) { - getProject().currentSessionTitle = customTitle; -} -function saveMode(mode) { - getProject().currentSessionMode = mode; -} -function saveWorktreeState(worktreeSession) { - const stripped = worktreeSession ? { - originalCwd: worktreeSession.originalCwd, - worktreePath: worktreeSession.worktreePath, - worktreeName: worktreeSession.worktreeName, - worktreeBranch: worktreeSession.worktreeBranch, - originalBranch: worktreeSession.originalBranch, - originalHeadCommit: worktreeSession.originalHeadCommit, - sessionId: worktreeSession.sessionId, - tmuxSessionName: worktreeSession.tmuxSessionName, - hookBased: worktreeSession.hookBased - } : null; - const project2 = getProject(); - project2.currentSessionWorktree = stripped; - if (project2.sessionFile) { - appendEntryToFile(project2.sessionFile, { - type: "worktree-state", - worktreeSession: stripped, - sessionId: getSessionId() - }); - } -} -function getSessionIdFromLog(log3) { - if (log3.sessionId) { - return log3.sessionId; - } - return log3.messages[0]?.sessionId; -} -function isLiteLog(log3) { - return log3.messages.length === 0 && log3.sessionId !== undefined; -} -async function loadFullLog(log3) { - if (!isLiteLog(log3)) { - return log3; - } - const sessionFile = log3.fullPath; - if (!sessionFile) { - return log3; - } - try { - const { - messages, - summaries, - customTitles, - tags, - agentNames, - agentColors, - agentSettings, - prNumbers, - prUrls, - prRepositories, - modes, - worktreeStates, - fileHistorySnapshots, - attributionSnapshots, - contentReplacements, - contextCollapseCommits, - contextCollapseSnapshot, - leafUuids - } = await loadTranscriptFile(sessionFile); - if (messages.size === 0) { - return log3; - } - const mostRecentLeaf = findLatestMessage(messages.values(), (msg) => leafUuids.has(msg.uuid) && (msg.type === "user" || msg.type === "assistant")); - if (!mostRecentLeaf) { - return log3; - } - const transcript = buildConversationChain(messages, mostRecentLeaf); - const sessionId = mostRecentLeaf.sessionId; - return { - ...log3, - messages: removeExtraFields(transcript), - firstPrompt: extractFirstPrompt2(transcript), - messageCount: countVisibleMessages(transcript), - summary: mostRecentLeaf ? summaries.get(mostRecentLeaf.uuid) : log3.summary, - customTitle: sessionId ? customTitles.get(sessionId) : log3.customTitle, - tag: sessionId ? tags.get(sessionId) : log3.tag, - agentName: sessionId ? agentNames.get(sessionId) : log3.agentName, - agentColor: sessionId ? agentColors.get(sessionId) : log3.agentColor, - agentSetting: sessionId ? agentSettings.get(sessionId) : log3.agentSetting, - mode: sessionId ? modes.get(sessionId) : log3.mode, - worktreeSession: sessionId && worktreeStates.has(sessionId) ? worktreeStates.get(sessionId) : log3.worktreeSession, - prNumber: sessionId ? prNumbers.get(sessionId) : log3.prNumber, - prUrl: sessionId ? prUrls.get(sessionId) : log3.prUrl, - prRepository: sessionId ? prRepositories.get(sessionId) : log3.prRepository, - gitBranch: mostRecentLeaf?.gitBranch ?? log3.gitBranch, - isSidechain: transcript[0]?.isSidechain ?? log3.isSidechain, - teamName: transcript[0]?.teamName ?? log3.teamName, - leafUuid: mostRecentLeaf?.uuid ?? log3.leafUuid, - fileHistorySnapshots: buildFileHistorySnapshotChain(fileHistorySnapshots, transcript), - attributionSnapshots: buildAttributionSnapshotChain(attributionSnapshots, transcript), - contentReplacements: sessionId ? contentReplacements.get(sessionId) ?? [] : log3.contentReplacements, - contextCollapseCommits: sessionId ? contextCollapseCommits.filter((e4) => e4.sessionId === sessionId) : undefined, - contextCollapseSnapshot: sessionId && contextCollapseSnapshot?.sessionId === sessionId ? contextCollapseSnapshot : undefined - }; - } catch { - return log3; - } -} -async function searchSessionsByCustomTitle(query2, options2) { - const { limit, exact } = options2 || {}; - const worktreePaths = await getWorktreePaths(getOriginalCwd()); - const allStatLogs = await getStatOnlyLogsForWorktrees(worktreePaths); - const { logs: logs2 } = await enrichLogs(allStatLogs, 0, allStatLogs.length); - const normalizedQuery = query2.toLowerCase().trim(); - const matchingLogs = logs2.filter((log3) => { - const title = log3.customTitle?.toLowerCase().trim(); - if (!title) - return false; - return exact ? title === normalizedQuery : title.includes(normalizedQuery); - }); - const sessionIdToLog = new Map; - for (const log3 of matchingLogs) { - const sessionId = getSessionIdFromLog(log3); - if (sessionId) { - const existing = sessionIdToLog.get(sessionId); - if (!existing || log3.modified > existing.modified) { - sessionIdToLog.set(sessionId, log3); - } - } - } - const deduplicated = Array.from(sessionIdToLog.values()); - deduplicated.sort((a5, b5) => b5.modified.getTime() - a5.modified.getTime()); - if (limit) { - return deduplicated.slice(0, limit); - } - return deduplicated; -} -function resolveMetadataBuf(carry, chunkBuf) { - if (carry === null || carry.length === 0) - return chunkBuf; - if (carry.length < METADATA_PREFIX_BOUND) { - return Buffer.concat([carry, chunkBuf]); - } - if (carry[0] === 123) { - for (const m4 of METADATA_MARKER_BUFS) { - if (carry.compare(m4, 0, m4.length, 1, 1 + m4.length) === 0) { - return Buffer.concat([carry, chunkBuf]); - } - } - } - const firstNl = chunkBuf.indexOf(10); - return firstNl === -1 ? null : chunkBuf.subarray(firstNl + 1); -} -async function scanPreBoundaryMetadata(filePath, endOffset) { - const { createReadStream: createReadStream3 } = await import("fs"); - const NEWLINE2 = 10; - const stream10 = createReadStream3(filePath, { end: endOffset - 1 }); - const metadataLines = []; - let carry = null; - for await (const chunk2 of stream10) { - const chunkBuf = chunk2; - const buf = resolveMetadataBuf(carry, chunkBuf); - if (buf === null) { - carry = null; - continue; - } - let hasAnyMarker = false; - for (const m4 of METADATA_MARKER_BUFS) { - if (buf.includes(m4)) { - hasAnyMarker = true; - break; - } - } - if (hasAnyMarker) { - let lineStart = 0; - let nl = buf.indexOf(NEWLINE2); - while (nl !== -1) { - for (const m4 of METADATA_MARKER_BUFS) { - const mIdx = buf.indexOf(m4, lineStart); - if (mIdx !== -1 && mIdx < nl) { - metadataLines.push(buf.toString("utf-8", lineStart, nl)); - break; - } - } - lineStart = nl + 1; - nl = buf.indexOf(NEWLINE2, lineStart); - } - carry = buf.subarray(lineStart); - } else { - const lastNl = buf.lastIndexOf(NEWLINE2); - carry = lastNl >= 0 ? buf.subarray(lastNl + 1) : buf; - } - if (carry.length > 65536) - carry = null; - } - if (carry !== null && carry.length > 0) { - for (const m4 of METADATA_MARKER_BUFS) { - if (carry.includes(m4)) { - metadataLines.push(carry.toString("utf-8")); - break; - } - } - } - return metadataLines; -} -function pickDepthOneUuidCandidate(buf, lineStart, candidates) { - const QUOTE = 34; - const BACKSLASH = 92; - const OPEN_BRACE = 123; - const CLOSE_BRACE = 125; - let depth = 0; - let inString = false; - let escapeNext = false; - let ci = 0; - for (let i6 = lineStart;ci < candidates.length; i6++) { - if (i6 === candidates[ci]) { - if (depth === 1 && !inString) - return candidates[ci]; - ci++; - } - const b5 = buf[i6]; - if (escapeNext) { - escapeNext = false; - } else if (inString) { - if (b5 === BACKSLASH) - escapeNext = true; - else if (b5 === QUOTE) - inString = false; - } else if (b5 === QUOTE) - inString = true; - else if (b5 === OPEN_BRACE) - depth++; - else if (b5 === CLOSE_BRACE) - depth--; - } - return candidates.at(-1); -} -function walkChainBeforeParse(buf) { - const NEWLINE2 = 10; - const OPEN_BRACE = 123; - const QUOTE = 34; - const PARENT_PREFIX = Buffer.from('{"parentUuid":'); - const UUID_KEY = Buffer.from('"uuid":"'); - const SIDECHAIN_TRUE = Buffer.from('"isSidechain":true'); - const UUID_LEN = 36; - const TS_SUFFIX = Buffer.from('","timestamp":"'); - const TS_SUFFIX_LEN = TS_SUFFIX.length; - const PREFIX_LEN = PARENT_PREFIX.length; - const KEY_LEN = UUID_KEY.length; - const msgIdx = []; - const metaRanges = []; - const uuidToSlot = new Map; - let pos = 0; - const len = buf.length; - while (pos < len) { - const nl = buf.indexOf(NEWLINE2, pos); - const lineEnd = nl === -1 ? len : nl + 1; - if (lineEnd - pos > PREFIX_LEN && buf[pos] === OPEN_BRACE && buf.compare(PARENT_PREFIX, 0, PREFIX_LEN, pos, pos + PREFIX_LEN) === 0) { - const parentStart = buf[pos + PREFIX_LEN] === QUOTE ? pos + PREFIX_LEN + 1 : -1; - let firstAny = -1; - let suffix0 = -1; - let suffixN; - let from = pos; - for (;; ) { - const next2 = buf.indexOf(UUID_KEY, from); - if (next2 < 0 || next2 >= lineEnd) - break; - if (firstAny < 0) - firstAny = next2; - const after = next2 + KEY_LEN + UUID_LEN; - if (after + TS_SUFFIX_LEN <= lineEnd && buf.compare(TS_SUFFIX, 0, TS_SUFFIX_LEN, after, after + TS_SUFFIX_LEN) === 0) { - if (suffix0 < 0) - suffix0 = next2; - else - (suffixN ??= [suffix0]).push(next2); - } - from = next2 + KEY_LEN; - } - const uk = suffixN ? pickDepthOneUuidCandidate(buf, pos, suffixN) : suffix0 >= 0 ? suffix0 : firstAny; - if (uk >= 0) { - const uuidStart = uk + KEY_LEN; - const uuid8 = buf.toString("latin1", uuidStart, uuidStart + UUID_LEN); - uuidToSlot.set(uuid8, msgIdx.length); - msgIdx.push(pos, lineEnd, parentStart); - } else { - metaRanges.push(pos, lineEnd); - } - } else { - metaRanges.push(pos, lineEnd); - } - pos = lineEnd; - } - let leafSlot = -1; - for (let i6 = msgIdx.length - 3;i6 >= 0; i6 -= 3) { - const sc = buf.indexOf(SIDECHAIN_TRUE, msgIdx[i6]); - if (sc === -1 || sc >= msgIdx[i6 + 1]) { - leafSlot = i6; - break; - } - } - if (leafSlot < 0) - return buf; - const seen = new Set; - const chain4 = new Set; - let chainBytes = 0; - let slot = leafSlot; - while (slot !== undefined) { - if (seen.has(slot)) - break; - seen.add(slot); - chain4.add(msgIdx[slot]); - chainBytes += msgIdx[slot + 1] - msgIdx[slot]; - const parentStart = msgIdx[slot + 2]; - if (parentStart < 0) - break; - const parent2 = buf.toString("latin1", parentStart, parentStart + UUID_LEN); - slot = uuidToSlot.get(parent2); - } - if (len - chainBytes < len >> 1) - return buf; - const parts = []; - let m4 = 0; - for (let i6 = 0;i6 < msgIdx.length; i6 += 3) { - const start = msgIdx[i6]; - while (m4 < metaRanges.length && metaRanges[m4] < start) { - parts.push(buf.subarray(metaRanges[m4], metaRanges[m4 + 1])); - m4 += 2; - } - if (chain4.has(start)) { - parts.push(buf.subarray(start, msgIdx[i6 + 1])); - } - } - while (m4 < metaRanges.length) { - parts.push(buf.subarray(metaRanges[m4], metaRanges[m4 + 1])); - m4 += 2; - } - return Buffer.concat(parts); -} -async function loadTranscriptFile(filePath, opts) { - const messages = new Map; - const summaries = new Map; - const customTitles = new Map; - const tags = new Map; - const agentNames = new Map; - const agentColors = new Map; - const agentSettings = new Map; - const prNumbers = new Map; - const prUrls = new Map; - const prRepositories = new Map; - const modes = new Map; - const worktreeStates = new Map; - const fileHistorySnapshots = new Map; - const attributionSnapshots = new Map; - const contentReplacements = new Map; - const agentContentReplacements = new Map; - const contextCollapseCommits = []; - let contextCollapseSnapshot; - try { - let buf = null; - let metadataLines = null; - let hasPreservedSegment = false; - if (!isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)) { - const { size } = await stat44(filePath); - if (size > SKIP_PRECOMPACT_THRESHOLD) { - const scan = await readTranscriptForLoad(filePath, size); - buf = scan.postBoundaryBuf; - hasPreservedSegment = scan.hasPreservedSegment; - if (scan.boundaryStartOffset > 0) { - metadataLines = await scanPreBoundaryMetadata(filePath, scan.boundaryStartOffset); - } - } - } - buf ??= await readFile53(filePath); - if (!opts?.keepAllLeaves && !hasPreservedSegment && !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP) && buf.length > SKIP_PRECOMPACT_THRESHOLD) { - buf = walkChainBeforeParse(buf); - } - if (metadataLines && metadataLines.length > 0) { - const metaEntries = parseJSONL(Buffer.from(metadataLines.join(` -`))); - for (const entry of metaEntries) { - if (entry.type === "summary" && entry.leafUuid) { - summaries.set(entry.leafUuid, entry.summary); - } else if (entry.type === "custom-title" && entry.sessionId) { - customTitles.set(entry.sessionId, entry.customTitle); - } else if (entry.type === "tag" && entry.sessionId) { - tags.set(entry.sessionId, entry.tag); - } else if (entry.type === "agent-name" && entry.sessionId) { - agentNames.set(entry.sessionId, entry.agentName); - } else if (entry.type === "agent-color" && entry.sessionId) { - agentColors.set(entry.sessionId, entry.agentColor); - } else if (entry.type === "agent-setting" && entry.sessionId) { - agentSettings.set(entry.sessionId, entry.agentSetting); - } else if (entry.type === "mode" && entry.sessionId) { - modes.set(entry.sessionId, entry.mode); - } else if (entry.type === "worktree-state" && entry.sessionId) { - worktreeStates.set(entry.sessionId, entry.worktreeSession); - } else if (entry.type === "pr-link" && entry.sessionId) { - prNumbers.set(entry.sessionId, entry.prNumber); - prUrls.set(entry.sessionId, entry.prUrl); - prRepositories.set(entry.sessionId, entry.prRepository); - } - } - } - const entries = parseJSONL(buf); - const progressBridge = new Map; - for (const entry of entries) { - if (isLegacyProgressEntry(entry)) { - const parent2 = entry.parentUuid; - progressBridge.set(entry.uuid, parent2 && progressBridge.has(parent2) ? progressBridge.get(parent2) ?? null : parent2); - continue; - } - if (isTranscriptMessage(entry)) { - if (entry.parentUuid && progressBridge.has(entry.parentUuid)) { - entry.parentUuid = progressBridge.get(entry.parentUuid) ?? null; - } - messages.set(entry.uuid, entry); - if (isCompactBoundaryMessage(entry)) { - contextCollapseCommits.length = 0; - contextCollapseSnapshot = undefined; - } - } else if (entry.type === "summary" && entry.leafUuid) { - summaries.set(entry.leafUuid, entry.summary); - } else if (entry.type === "custom-title" && entry.sessionId) { - customTitles.set(entry.sessionId, entry.customTitle); - } else if (entry.type === "tag" && entry.sessionId) { - tags.set(entry.sessionId, entry.tag); - } else if (entry.type === "agent-name" && entry.sessionId) { - agentNames.set(entry.sessionId, entry.agentName); - } else if (entry.type === "agent-color" && entry.sessionId) { - agentColors.set(entry.sessionId, entry.agentColor); - } else if (entry.type === "agent-setting" && entry.sessionId) { - agentSettings.set(entry.sessionId, entry.agentSetting); - } else if (entry.type === "mode" && entry.sessionId) { - modes.set(entry.sessionId, entry.mode); - } else if (entry.type === "worktree-state" && entry.sessionId) { - worktreeStates.set(entry.sessionId, entry.worktreeSession); - } else if (entry.type === "pr-link" && entry.sessionId) { - prNumbers.set(entry.sessionId, entry.prNumber); - prUrls.set(entry.sessionId, entry.prUrl); - prRepositories.set(entry.sessionId, entry.prRepository); - } else if (entry.type === "file-history-snapshot") { - fileHistorySnapshots.set(entry.messageId, entry); - } else if (entry.type === "attribution-snapshot") { - attributionSnapshots.set(entry.messageId, entry); - } else if (entry.type === "content-replacement") { - if (entry.agentId) { - const existing = agentContentReplacements.get(entry.agentId) ?? []; - agentContentReplacements.set(entry.agentId, existing); - existing.push(...entry.replacements); - } else { - const existing = contentReplacements.get(entry.sessionId) ?? []; - contentReplacements.set(entry.sessionId, existing); - existing.push(...entry.replacements); - } - } else if (entry.type === "marble-origami-commit") { - contextCollapseCommits.push(entry); - } else if (entry.type === "marble-origami-snapshot") { - contextCollapseSnapshot = entry; - } - } - } catch {} - applyPreservedSegmentRelinks(messages); - applySnipRemovals(messages); - const allMessages = [...messages.values()]; - const parentUuids = new Set(allMessages.map((msg) => msg.parentUuid).filter((uuid8) => uuid8 !== null)); - const terminalMessages = allMessages.filter((msg) => !parentUuids.has(msg.uuid)); - const leafUuids = new Set; - let hasCycle = false; - if (getFeatureValue_CACHED_MAY_BE_STALE("tengu_pebble_leaf_prune", false)) { - const hasUserAssistantChild = new Set; - for (const msg of allMessages) { - if (msg.parentUuid && (msg.type === "user" || msg.type === "assistant")) { - hasUserAssistantChild.add(msg.parentUuid); - } - } - for (const terminal of terminalMessages) { - const seen = new Set; - let current = terminal; - while (current) { - if (seen.has(current.uuid)) { - hasCycle = true; - break; - } - seen.add(current.uuid); - if (current.type === "user" || current.type === "assistant") { - if (!hasUserAssistantChild.has(current.uuid)) { - leafUuids.add(current.uuid); - } - break; - } - current = current.parentUuid ? messages.get(current.parentUuid) : undefined; - } - } - } else { - for (const terminal of terminalMessages) { - const seen = new Set; - let current = terminal; - while (current) { - if (seen.has(current.uuid)) { - hasCycle = true; - break; - } - seen.add(current.uuid); - if (current.type === "user" || current.type === "assistant") { - leafUuids.add(current.uuid); - break; - } - current = current.parentUuid ? messages.get(current.parentUuid) : undefined; - } - } - } - if (hasCycle) { - logEvent("tengu_transcript_parent_cycle", {}); - } - return { - messages, - summaries, - customTitles, - tags, - agentNames, - agentColors, - agentSettings, - prNumbers, - prUrls, - prRepositories, - modes, - worktreeStates, - fileHistorySnapshots, - attributionSnapshots, - contentReplacements, - agentContentReplacements, - contextCollapseCommits, - contextCollapseSnapshot, - leafUuids - }; -} -async function loadSessionFile(sessionId) { - const sessionFile = join140(getSessionProjectDir() ?? getProjectDir2(getOriginalCwd()), `${sessionId}.jsonl`); - return loadTranscriptFile(sessionFile); -} -function clearSessionMessagesCache() { - getSessionMessages.cache.clear?.(); -} -async function doesMessageExistInSession(sessionId, messageUuid) { - const messageSet = await getSessionMessages(sessionId); - return messageSet.has(messageUuid); -} -async function getLastSessionLog(sessionId) { - const { - messages, - summaries, - customTitles, - tags, - agentSettings, - worktreeStates, - fileHistorySnapshots, - attributionSnapshots, - contentReplacements, - contextCollapseCommits, - contextCollapseSnapshot - } = await loadSessionFile(sessionId); - if (messages.size === 0) - return null; - if (!getSessionMessages.cache.has(sessionId)) { - getSessionMessages.cache.set(sessionId, Promise.resolve(new Set(messages.keys()))); - } - const lastMessage = findLatestMessage(messages.values(), (m4) => !m4.isSidechain); - if (!lastMessage) - return null; - const transcript = buildConversationChain(messages, lastMessage); - const summary = summaries.get(lastMessage.uuid); - const customTitle = customTitles.get(lastMessage.sessionId); - const tag3 = tags.get(lastMessage.sessionId); - const agentSetting = agentSettings.get(sessionId); - return { - ...convertToLogOption(transcript, 0, summary, customTitle, buildFileHistorySnapshotChain(fileHistorySnapshots, transcript), tag3, getTranscriptPathForSession(sessionId), buildAttributionSnapshotChain(attributionSnapshots, transcript), agentSetting, contentReplacements.get(sessionId) ?? []), - worktreeSession: worktreeStates.get(sessionId), - contextCollapseCommits: contextCollapseCommits.filter((e4) => e4.sessionId === sessionId), - contextCollapseSnapshot: contextCollapseSnapshot?.sessionId === sessionId ? contextCollapseSnapshot : undefined - }; -} -async function loadMessageLogs(limit) { - const sessionLogs = await fetchLogs(limit); - const { logs: enriched } = await enrichLogs(sessionLogs, 0, sessionLogs.length); - const sorted = sortLogs(enriched); - sorted.forEach((log3, i6) => { - log3.value = i6; - }); - return sorted; -} -async function loadAllProjectsMessageLogs(limit, options2) { - if (options2?.skipIndex) { - return loadAllProjectsMessageLogsFull(limit); - } - const result = await loadAllProjectsMessageLogsProgressive(limit, options2?.initialEnrichCount ?? INITIAL_ENRICH_COUNT); - return result.logs; -} -async function loadAllProjectsMessageLogsFull(limit) { - const projectsDir = getProjectsDir2(); - let dirents; - try { - dirents = await readdir29(projectsDir, { withFileTypes: true }); - } catch { - return []; - } - const projectDirs = dirents.filter((dirent) => dirent.isDirectory()).map((dirent) => join140(projectsDir, dirent.name)); - const logsPerProject = await Promise.all(projectDirs.map((projectDir) => getLogsWithoutIndex(projectDir, limit))); - const allLogs = logsPerProject.flat(); - const deduped = new Map; - for (const log3 of allLogs) { - const key2 = `${log3.sessionId ?? ""}:${log3.leafUuid ?? ""}`; - const existing = deduped.get(key2); - if (!existing || log3.modified.getTime() > existing.modified.getTime()) { - deduped.set(key2, log3); - } - } - const sorted = sortLogs([...deduped.values()]); - sorted.forEach((log3, i6) => { - log3.value = i6; - }); - return sorted; -} -async function loadAllProjectsMessageLogsProgressive(limit, initialEnrichCount = INITIAL_ENRICH_COUNT) { - const projectsDir = getProjectsDir2(); - let dirents; - try { - dirents = await readdir29(projectsDir, { withFileTypes: true }); - } catch { - return { logs: [], allStatLogs: [], nextIndex: 0 }; - } - const projectDirs = dirents.filter((dirent) => dirent.isDirectory()).map((dirent) => join140(projectsDir, dirent.name)); - const rawLogs = []; - for (const projectDir of projectDirs) { - rawLogs.push(...await getSessionFilesLite(projectDir, limit)); - } - const sorted = deduplicateLogsBySessionId(rawLogs); - const { logs: logs2, nextIndex } = await enrichLogs(sorted, 0, initialEnrichCount); - logs2.forEach((log3, i6) => { - log3.value = i6; - }); - return { logs: logs2, allStatLogs: sorted, nextIndex }; -} -async function loadSameRepoMessageLogs(worktreePaths, limit, initialEnrichCount = INITIAL_ENRICH_COUNT) { - const result = await loadSameRepoMessageLogsProgressive(worktreePaths, limit, initialEnrichCount); - return result.logs; -} -async function loadSameRepoMessageLogsProgressive(worktreePaths, limit, initialEnrichCount = INITIAL_ENRICH_COUNT) { - logForDebugging(`/resume: loading sessions for cwd=${getOriginalCwd()}, worktrees=[${worktreePaths.join(", ")}]`); - const allStatLogs = await getStatOnlyLogsForWorktrees(worktreePaths, limit); - logForDebugging(`/resume: found ${allStatLogs.length} session files on disk`); - const { logs: logs2, nextIndex } = await enrichLogs(allStatLogs, 0, initialEnrichCount); - logs2.forEach((log3, i6) => { - log3.value = i6; - }); - return { logs: logs2, allStatLogs, nextIndex }; -} -async function getStatOnlyLogsForWorktrees(worktreePaths, limit) { - const projectsDir = getProjectsDir2(); - if (worktreePaths.length <= 1) { - const cwd2 = getOriginalCwd(); - const projectDir = getProjectDir2(cwd2); - return getSessionFilesLite(projectDir, undefined, cwd2); - } - const caseInsensitive = process.platform === "win32"; - const indexed = worktreePaths.map((wt) => { - const sanitized = sanitizePath2(wt); - return { - path: wt, - prefix: caseInsensitive ? sanitized.toLowerCase() : sanitized - }; - }); - indexed.sort((a5, b5) => b5.prefix.length - a5.prefix.length); - const allLogs = []; - const seenDirs = new Set; - let allDirents; - try { - allDirents = await readdir29(projectsDir, { withFileTypes: true }); - } catch (e4) { - logForDebugging(`Failed to read projects dir ${projectsDir}, falling back to current project: ${e4}`); - const projectDir = getProjectDir2(getOriginalCwd()); - return getSessionFilesLite(projectDir, limit, getOriginalCwd()); - } - for (const dirent of allDirents) { - if (!dirent.isDirectory()) - continue; - const dirName = caseInsensitive ? dirent.name.toLowerCase() : dirent.name; - if (seenDirs.has(dirName)) - continue; - for (const { path: wtPath, prefix } of indexed) { - if (dirName === prefix || dirName.startsWith(prefix + "-")) { - seenDirs.add(dirName); - allLogs.push(...await getSessionFilesLite(join140(projectsDir, dirent.name), undefined, wtPath)); - break; - } - } - } - return deduplicateLogsBySessionId(allLogs); -} -async function getAgentTranscript(agentId) { - const agentFile = getAgentTranscriptPath(agentId); - try { - const { messages, agentContentReplacements } = await loadTranscriptFile(agentFile); - const agentMessages = Array.from(messages.values()).filter((msg) => msg.agentId === agentId && msg.isSidechain); - if (agentMessages.length === 0) { - return null; - } - const parentUuids = new Set(agentMessages.map((msg) => msg.parentUuid)); - const leafMessage = findLatestMessage(agentMessages, (msg) => !parentUuids.has(msg.uuid)); - if (!leafMessage) { - return null; - } - const transcript = buildConversationChain(messages, leafMessage); - const agentTranscript = transcript.filter((msg) => msg.agentId === agentId); - return { - messages: agentTranscript.map(({ isSidechain, parentUuid, ...msg }) => msg), - contentReplacements: agentContentReplacements.get(agentId) ?? [] - }; - } catch { - return null; - } -} -function extractAgentIdsFromMessages(messages) { - const agentIds = []; - for (const message of messages) { - if (message.type === "progress" && message.data && typeof message.data === "object" && "type" in message.data && (message.data.type === "agent_progress" || message.data.type === "skill_progress") && "agentId" in message.data && typeof message.data.agentId === "string") { - agentIds.push(message.data.agentId); - } - } - return uniq(agentIds); -} -function extractTeammateTranscriptsFromTasks(tasks2) { - const transcripts = {}; - for (const task of Object.values(tasks2)) { - if (task.type === "in_process_teammate" && task.identity?.agentId && task.messages && task.messages.length > 0) { - transcripts[task.identity.agentId] = task.messages; - } - } - return transcripts; -} -async function loadSubagentTranscripts(agentIds) { - const results = await Promise.all(agentIds.map(async (agentId) => { - try { - const result = await getAgentTranscript(asAgentId(agentId)); - if (result && result.messages.length > 0) { - return { agentId, transcript: result.messages }; - } - return null; - } catch { - return null; - } - })); - const transcripts = {}; - for (const result of results) { - if (result) { - transcripts[result.agentId] = result.transcript; - } - } - return transcripts; -} -async function loadAllSubagentTranscriptsFromDisk() { - const subagentsDir = join140(getSessionProjectDir() ?? getProjectDir2(getOriginalCwd()), getSessionId(), "subagents"); - let entries; - try { - entries = await readdir29(subagentsDir, { withFileTypes: true }); - } catch { - return {}; - } - const agentIds = entries.filter((d4) => d4.isFile() && d4.name.startsWith("agent-") && d4.name.endsWith(".jsonl")).map((d4) => d4.name.slice("agent-".length, -".jsonl".length)); - return loadSubagentTranscripts(agentIds); -} -function isLoggableMessage(m4) { - if (m4.type === "progress") - return false; - if (m4.type === "attachment" && getUserType() !== "ant") { - if (m4.attachment.type === "hook_additional_context" && isEnvTruthy(process.env.CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT)) { - return true; - } - return false; - } - return true; -} -function collectReplIds(messages) { - const ids = new Set; - for (const m4 of messages) { - if (m4.type === "assistant" && Array.isArray(m4.message.content)) { - for (const b5 of m4.message.content) { - if (b5.type === "tool_use" && b5.name === REPL_TOOL_NAME) { - ids.add(b5.id); - } - } - } - } - return ids; -} -function transformMessagesForExternalTranscript(messages, replIds) { - return messages.flatMap((m4) => { - if (m4.type === "assistant" && Array.isArray(m4.message.content)) { - const content = m4.message.content; - const hasRepl = content.some((b5) => b5.type === "tool_use" && b5.name === REPL_TOOL_NAME); - const filtered = hasRepl ? content.filter((b5) => !(b5.type === "tool_use" && b5.name === REPL_TOOL_NAME)) : content; - if (filtered.length === 0) - return []; - if (m4.isVirtual) { - const { isVirtual: _omit, ...rest } = m4; - return [{ ...rest, message: { ...m4.message, content: filtered } }]; - } - if (filtered !== content) { - return [{ ...m4, message: { ...m4.message, content: filtered } }]; - } - return [m4]; - } - if (m4.type === "user" && Array.isArray(m4.message.content)) { - const content = m4.message.content; - const hasRepl = content.some((b5) => b5.type === "tool_result" && replIds.has(b5.tool_use_id)); - const filtered = hasRepl ? content.filter((b5) => !(b5.type === "tool_result" && replIds.has(b5.tool_use_id))) : content; - if (filtered.length === 0) - return []; - if (m4.isVirtual) { - const { isVirtual: _omit, ...rest } = m4; - return [{ ...rest, message: { ...m4.message, content: filtered } }]; - } - if (filtered !== content) { - return [{ ...m4, message: { ...m4.message, content: filtered } }]; - } - return [m4]; - } - if ("isVirtual" in m4 && m4.isVirtual) { - const { isVirtual: _omit, ...rest } = m4; - return [rest]; - } - return [m4]; - }); -} -function cleanMessagesForLogging(messages, allMessages = messages) { - const filtered = messages.filter(isLoggableMessage); - return getUserType() !== "ant" ? transformMessagesForExternalTranscript(filtered, collectReplIds(allMessages)) : filtered; -} -async function getLogByIndex(index2) { - const logs2 = await loadMessageLogs(); - return logs2[index2] || null; -} -async function findUnresolvedToolUse(toolUseId) { - try { - const transcriptPath = getTranscriptPath(); - const { messages } = await loadTranscriptFile(transcriptPath); - let toolUseMessage = null; - for (const message of messages.values()) { - if (message.type === "assistant") { - const content = message.message.content; - if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "tool_use" && block2.id === toolUseId) { - toolUseMessage = message; - break; - } - } - } - } else if (message.type === "user") { - const content = message.message.content; - if (Array.isArray(content)) { - for (const block2 of content) { - if (block2.type === "tool_result" && block2.tool_use_id === toolUseId) { - return null; - } - } - } - } - } - return toolUseMessage; - } catch { - return null; - } -} -async function getSessionFilesWithMtime(projectDir) { - const sessionFilesMap = new Map; - let dirents; - try { - dirents = await readdir29(projectDir, { withFileTypes: true }); - } catch { - return sessionFilesMap; - } - const candidates = []; - for (const dirent of dirents) { - if (!dirent.isFile() || !dirent.name.endsWith(".jsonl")) - continue; - const sessionId = validateUuid2(basename42(dirent.name, ".jsonl")); - if (!sessionId) - continue; - candidates.push({ sessionId, filePath: join140(projectDir, dirent.name) }); - } - await Promise.all(candidates.map(async ({ sessionId, filePath }) => { - try { - const st = await stat44(filePath); - sessionFilesMap.set(sessionId, { - path: filePath, - mtime: st.mtime.getTime(), - ctime: st.birthtime.getTime(), - size: st.size - }); - } catch { - logForDebugging(`Failed to stat session file: ${filePath}`); - } - })); - return sessionFilesMap; -} -async function loadAllLogsFromSessionFile(sessionFile, projectPathOverride) { - const { - messages, - summaries, - customTitles, - tags, - agentNames, - agentColors, - agentSettings, - prNumbers, - prUrls, - prRepositories, - modes, - fileHistorySnapshots, - attributionSnapshots, - contentReplacements, - leafUuids - } = await loadTranscriptFile(sessionFile, { keepAllLeaves: true }); - if (messages.size === 0) - return []; - const leafMessages = []; - const childrenByParent = new Map; - for (const msg of messages.values()) { - if (leafUuids.has(msg.uuid)) { - leafMessages.push(msg); - } else if (msg.parentUuid) { - const siblings = childrenByParent.get(msg.parentUuid); - if (siblings) { - siblings.push(msg); - } else { - childrenByParent.set(msg.parentUuid, [msg]); - } - } - } - const logs2 = []; - for (const leafMessage of leafMessages) { - const chain4 = buildConversationChain(messages, leafMessage); - if (chain4.length === 0) - continue; - const trailingMessages = childrenByParent.get(leafMessage.uuid); - if (trailingMessages) { - trailingMessages.sort((a5, b5) => a5.timestamp < b5.timestamp ? -1 : a5.timestamp > b5.timestamp ? 1 : 0); - chain4.push(...trailingMessages); - } - const firstMessage = chain4[0]; - const sessionId = leafMessage.sessionId; - logs2.push({ - date: leafMessage.timestamp, - messages: removeExtraFields(chain4), - fullPath: sessionFile, - value: 0, - created: new Date(firstMessage.timestamp), - modified: new Date(leafMessage.timestamp), - firstPrompt: extractFirstPrompt2(chain4), - messageCount: countVisibleMessages(chain4), - isSidechain: firstMessage.isSidechain ?? false, - sessionId, - leafUuid: leafMessage.uuid, - summary: summaries.get(leafMessage.uuid), - customTitle: customTitles.get(sessionId), - tag: tags.get(sessionId), - agentName: agentNames.get(sessionId), - agentColor: agentColors.get(sessionId), - agentSetting: agentSettings.get(sessionId), - mode: modes.get(sessionId), - prNumber: prNumbers.get(sessionId), - prUrl: prUrls.get(sessionId), - prRepository: prRepositories.get(sessionId), - gitBranch: leafMessage.gitBranch, - projectPath: projectPathOverride ?? firstMessage.cwd, - fileHistorySnapshots: buildFileHistorySnapshotChain(fileHistorySnapshots, chain4), - attributionSnapshots: buildAttributionSnapshotChain(attributionSnapshots, chain4), - contentReplacements: contentReplacements.get(sessionId) ?? [] - }); - } - return logs2; -} -async function getLogsWithoutIndex(projectDir, limit) { - const sessionFilesMap = await getSessionFilesWithMtime(projectDir); - if (sessionFilesMap.size === 0) - return []; - let filesToProcess; - if (limit && sessionFilesMap.size > limit) { - filesToProcess = [...sessionFilesMap.values()].sort((a5, b5) => b5.mtime - a5.mtime).slice(0, limit); - } else { - filesToProcess = [...sessionFilesMap.values()]; - } - const logs2 = []; - for (const fileInfo of filesToProcess) { - try { - const fileLogOptions = await loadAllLogsFromSessionFile(fileInfo.path); - logs2.push(...fileLogOptions); - } catch { - logForDebugging(`Failed to load session file: ${fileInfo.path}`); - } - } - return logs2; -} -async function readLiteMetadata(filePath, fileSize, buf) { - const { head, tail } = await readHeadAndTail(filePath, fileSize, buf); - if (!head) - return { firstPrompt: "", isSidechain: false }; - const isSidechain = head.includes('"isSidechain":true') || head.includes('"isSidechain": true'); - const projectPath = extractJsonStringField(head, "cwd"); - const teamName = extractJsonStringField(head, "teamName"); - const agentSetting = extractJsonStringField(head, "agentSetting"); - const firstPrompt = extractLastJsonStringField(tail, "lastPrompt") || extractFirstPromptFromChunk(head) || extractJsonStringFieldPrefix(head, "content", 200) || extractJsonStringFieldPrefix(head, "text", 200) || ""; - const customTitle = extractLastJsonStringField(tail, "customTitle") ?? extractLastJsonStringField(head, "customTitle") ?? extractLastJsonStringField(tail, "aiTitle") ?? extractLastJsonStringField(head, "aiTitle"); - const summary = extractLastJsonStringField(tail, "summary"); - const tag3 = extractLastJsonStringField(tail, "tag"); - const gitBranch = extractLastJsonStringField(tail, "gitBranch") ?? extractJsonStringField(head, "gitBranch"); - const prUrl = extractLastJsonStringField(tail, "prUrl"); - const prRepository = extractLastJsonStringField(tail, "prRepository"); - let prNumber; - const prNumStr = extractLastJsonStringField(tail, "prNumber"); - if (prNumStr) { - prNumber = parseInt(prNumStr, 10) || undefined; - } - if (!prNumber) { - const prNumMatch = tail.lastIndexOf('"prNumber":'); - if (prNumMatch >= 0) { - const afterColon = tail.slice(prNumMatch + 11, prNumMatch + 25); - const num = parseInt(afterColon.trim(), 10); - if (num > 0) - prNumber = num; - } - } - return { - firstPrompt, - gitBranch, - isSidechain, - projectPath, - teamName, - customTitle, - summary, - tag: tag3, - agentSetting, - prNumber, - prUrl, - prRepository - }; -} -function extractFirstPromptFromChunk(chunk2) { - let start = 0; - let hasTickMessages = false; - let firstCommandFallback = ""; - while (start < chunk2.length) { - const newlineIdx = chunk2.indexOf(` -`, start); - const line = newlineIdx >= 0 ? chunk2.slice(start, newlineIdx) : chunk2.slice(start); - start = newlineIdx >= 0 ? newlineIdx + 1 : chunk2.length; - if (!line.includes('"type":"user"') && !line.includes('"type": "user"')) { - continue; - } - if (line.includes('"tool_result"')) - continue; - if (line.includes('"isMeta":true') || line.includes('"isMeta": true')) - continue; - try { - const entry = jsonParse(line); - if (entry.type !== "user") - continue; - const message = entry.message; - if (!message) - continue; - const content = message.content; - const texts = []; - if (typeof content === "string") { - texts.push(content); - } else if (Array.isArray(content)) { - for (const block2 of content) { - const b5 = block2; - if (b5.type === "text" && typeof b5.text === "string") { - texts.push(b5.text); - } - } - } - for (const text of texts) { - if (!text) - continue; - let result = text.replace(/\n/g, " ").trim(); - const commandNameTag = extractTag(result, COMMAND_NAME_TAG); - if (commandNameTag) { - const name3 = commandNameTag.replace(/^\//, ""); - const commandArgs = extractTag(result, "command-args")?.trim() || ""; - if (builtInCommandNames().has(name3) || !commandArgs) { - if (!firstCommandFallback) { - firstCommandFallback = commandNameTag; - } - continue; - } - return commandArgs ? `${commandNameTag} ${commandArgs}` : commandNameTag; - } - const bashInput = extractTag(result, "bash-input"); - if (bashInput) - return `! ${bashInput}`; - if (SKIP_FIRST_PROMPT_PATTERN.test(result)) { - if (false) - ; - continue; - } - if (result.length > 200) { - result = result.slice(0, 200).trim() + "\u2026"; - } - return result; - } - } catch { - continue; - } - } - if (firstCommandFallback) - return firstCommandFallback; - if (false) - ; - return ""; -} -function extractJsonStringFieldPrefix(text, key2, maxLen) { - const patterns = [`"${key2}":"`, `"${key2}": "`]; - for (const pattern of patterns) { - const idx = text.indexOf(pattern); - if (idx < 0) - continue; - const valueStart = idx + pattern.length; - let i6 = valueStart; - let collected = 0; - while (i6 < text.length && collected < maxLen) { - if (text[i6] === "\\") { - i6 += 2; - collected++; - continue; - } - if (text[i6] === '"') - break; - i6++; - collected++; - } - const raw = text.slice(valueStart, i6); - return raw.replace(/\\n/g, " ").replace(/\\t/g, " ").trim(); - } - return ""; -} -function deduplicateLogsBySessionId(logs2) { - const deduped = new Map; - for (const log3 of logs2) { - if (!log3.sessionId) - continue; - const existing = deduped.get(log3.sessionId); - if (!existing || log3.modified.getTime() > existing.modified.getTime()) { - deduped.set(log3.sessionId, log3); - } - } - return sortLogs([...deduped.values()]).map((log3, i6) => ({ - ...log3, - value: i6 - })); -} -async function getSessionFilesLite(projectDir, limit, projectPath) { - const sessionFilesMap = await getSessionFilesWithMtime(projectDir); - let entries = [...sessionFilesMap.entries()].sort((a5, b5) => b5[1].mtime - a5[1].mtime); - if (limit && entries.length > limit) { - entries = entries.slice(0, limit); - } - const logs2 = []; - for (const [sessionId, fileInfo] of entries) { - logs2.push({ - date: new Date(fileInfo.mtime).toISOString(), - messages: [], - isLite: true, - fullPath: fileInfo.path, - value: 0, - created: new Date(fileInfo.ctime), - modified: new Date(fileInfo.mtime), - firstPrompt: "", - messageCount: 0, - fileSize: fileInfo.size, - isSidechain: false, - sessionId, - projectPath - }); - } - const sorted = sortLogs(logs2); - sorted.forEach((log3, i6) => { - log3.value = i6; - }); - return sorted; -} -async function enrichLog(log3, readBuf) { - if (!log3.isLite || !log3.fullPath) - return log3; - const meta = await readLiteMetadata(log3.fullPath, log3.fileSize ?? 0, readBuf); - const enriched = { - ...log3, - isLite: false, - firstPrompt: meta.firstPrompt, - gitBranch: meta.gitBranch, - isSidechain: meta.isSidechain, - teamName: meta.teamName, - customTitle: meta.customTitle, - summary: meta.summary, - tag: meta.tag, - agentSetting: meta.agentSetting, - prNumber: meta.prNumber, - prUrl: meta.prUrl, - prRepository: meta.prRepository, - projectPath: meta.projectPath ?? log3.projectPath - }; - if (!enriched.firstPrompt && !enriched.customTitle) { - enriched.firstPrompt = "(session)"; - } - if (enriched.isSidechain) { - logForDebugging(`Session ${log3.sessionId} filtered from /resume: isSidechain=true`); - return null; - } - if (enriched.teamName) { - logForDebugging(`Session ${log3.sessionId} filtered from /resume: teamName=${enriched.teamName}`); - return null; - } - return enriched; -} -async function enrichLogs(allLogs, startIndex, count4) { - const result = []; - const readBuf = Buffer.alloc(LITE_READ_BUF_SIZE); - let i6 = startIndex; - while (i6 < allLogs.length && result.length < count4) { - const log3 = allLogs[i6]; - i6++; - const enriched = await enrichLog(log3, readBuf); - if (enriched) { - result.push(enriched); - } - } - const scanned = i6 - startIndex; - const filtered = scanned - result.length; - if (filtered > 0) { - logForDebugging(`/resume: enriched ${scanned} sessions, ${filtered} filtered out, ${result.length} visible (${allLogs.length - i6} remaining on disk)`); - } - return { logs: result, nextIndex: i6 }; -} -var VERSION9, MAX_TOMBSTONE_REWRITE_BYTES, SKIP_FIRST_PROMPT_PATTERN, EPHEMERAL_PROGRESS_TYPES, MAX_TRANSCRIPT_READ_BYTES, agentTranscriptSubdirs, getProjectDir2, project = null, cleanupRegistered4 = false, REMOTE_FLUSH_INTERVAL_MS = 10, METADATA_TYPE_MARKERS, METADATA_MARKER_BUFS, METADATA_PREFIX_BOUND = 25, getSessionMessages, INITIAL_ENRICH_COUNT = 50; -var init_sessionStorage = __esm(() => { - init_memoize(); - init_analytics(); - init_state(); - init_commands5(); - init_xml(); - init_growthbook(); - init_sessionIngress(); - init_constants11(); - init_ids(); - init_cleanupRegistry(); - init_concurrentSessions(); - init_cwd(); - init_debug(); - init_diagLogs(); - init_envUtils(); - init_errors(); - init_format(); - init_fsOperations(); - init_getWorktreePaths(); - init_git(); - init_gracefulShutdown(); - init_json(); - init_log2(); - init_messages9(); - init_path(); - init_sessionStoragePortable(); - init_settings2(); - init_slowOperations(); - init_uuid(); - VERSION9 = typeof MACRO !== "undefined" ? MACRO.VERSION : "unknown"; - MAX_TOMBSTONE_REWRITE_BYTES = 50 * 1024 * 1024; - SKIP_FIRST_PROMPT_PATTERN = /^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/; - EPHEMERAL_PROGRESS_TYPES = new Set([ - "bash_progress", - "powershell_progress", - "mcp_progress", - ...[] - ]); - MAX_TRANSCRIPT_READ_BYTES = 50 * 1024 * 1024; - agentTranscriptSubdirs = new Map; - getProjectDir2 = memoize_default((projectDir) => { - return join140(getProjectsDir2(), sanitizePath2(projectDir)); - }); - METADATA_TYPE_MARKERS = [ - '"type":"summary"', - '"type":"custom-title"', - '"type":"tag"', - '"type":"agent-name"', - '"type":"agent-color"', - '"type":"agent-setting"', - '"type":"mode"', - '"type":"worktree-state"', - '"type":"pr-link"' - ]; - METADATA_MARKER_BUFS = METADATA_TYPE_MARKERS.map((m4) => Buffer.from(m4)); - getSessionMessages = memoize_default(async (sessionId) => { - const { messages } = await loadSessionFile(sessionId); - return new Set(messages.keys()); - }, (sessionId) => sessionId); -}); - -// src/memdir/memdir.ts -function truncateEntrypointContent(raw) { - const trimmed = raw.trim(); - const contentLines = trimmed.split(` -`); - const lineCount = contentLines.length; - const byteCount = trimmed.length; - const wasLineTruncated = lineCount > MAX_ENTRYPOINT_LINES; - const wasByteTruncated = byteCount > MAX_ENTRYPOINT_BYTES; - if (!wasLineTruncated && !wasByteTruncated) { - return { - content: trimmed, - lineCount, - byteCount, - wasLineTruncated, - wasByteTruncated - }; - } - let truncated = wasLineTruncated ? contentLines.slice(0, MAX_ENTRYPOINT_LINES).join(` -`) : trimmed; - if (truncated.length > MAX_ENTRYPOINT_BYTES) { - const cutAt = truncated.lastIndexOf(` -`, MAX_ENTRYPOINT_BYTES); - truncated = truncated.slice(0, cutAt > 0 ? cutAt : MAX_ENTRYPOINT_BYTES); - } - const reason = wasByteTruncated && !wasLineTruncated ? `${formatFileSize(byteCount)} (limit: ${formatFileSize(MAX_ENTRYPOINT_BYTES)}) \u2014 index entries are too long` : wasLineTruncated && !wasByteTruncated ? `${lineCount} lines (limit: ${MAX_ENTRYPOINT_LINES})` : `${lineCount} lines and ${formatFileSize(byteCount)}`; - return { - content: truncated + ` - -> WARNING: ${ENTRYPOINT_NAME} is ${reason}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`, - lineCount, - byteCount, - wasLineTruncated, - wasByteTruncated - }; -} -async function ensureMemoryDirExists(memoryDir) { - const fs13 = getFsImplementation(); - try { - await fs13.mkdir(memoryDir); - } catch (e4) { - const code = e4 instanceof Error && "code" in e4 && typeof e4.code === "string" ? e4.code : undefined; - logForDebugging(`ensureMemoryDirExists failed for ${memoryDir}: ${code ?? String(e4)}`, { level: "debug" }); - } -} -function logMemoryDirCounts(memoryDir, baseMetadata2) { - const fs13 = getFsImplementation(); - fs13.readdir(memoryDir).then((dirents) => { - let fileCount = 0; - let subdirCount = 0; - for (const d4 of dirents) { - if (d4.isFile()) { - fileCount++; - } else if (d4.isDirectory()) { - subdirCount++; - } - } - logEvent("tengu_memdir_loaded", { - ...baseMetadata2, - total_file_count: fileCount, - total_subdir_count: subdirCount - }); - }, () => { - logEvent("tengu_memdir_loaded", baseMetadata2); - }); -} -function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = false) { - const howToSave = skipIndex ? [ - "## How to save memories", - "", - "Write each memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:", - "", - ...MEMORY_FRONTMATTER_EXAMPLE, - "", - "- Keep the name, description, and type fields in memory files up-to-date with the content", - "- Organize memory semantically by topic, not chronologically", - "- Update or remove memories that turn out to be wrong or outdated", - "- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one." - ] : [ - "## How to save memories", - "", - "Saving a memory is a two-step process:", - "", - "**Step 1** \u2014 write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:", - "", - ...MEMORY_FRONTMATTER_EXAMPLE, - "", - `**Step 2** \u2014 add a pointer to that file in \`${ENTRYPOINT_NAME}\`. \`${ENTRYPOINT_NAME}\` is an index, not a memory \u2014 each entry should be one line, under ~150 characters: \`- [Title](file.md) \u2014 one-line hook\`. It has no frontmatter. Never write memory content directly into \`${ENTRYPOINT_NAME}\`.`, - "", - `- \`${ENTRYPOINT_NAME}\` is always loaded into your conversation context \u2014 lines after ${MAX_ENTRYPOINT_LINES} will be truncated, so keep the index concise`, - "- Keep the name, description, and type fields in memory files up-to-date with the content", - "- Organize memory semantically by topic, not chronologically", - "- Update or remove memories that turn out to be wrong or outdated", - "- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one." - ]; - const lines2 = [ - `# ${displayName}`, - "", - `You have a persistent, file-based memory system at \`${memoryDir}\`. ${DIR_EXISTS_GUIDANCE}`, - "", - "You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.", - "", - "If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.", - "", - ...TYPES_SECTION_INDIVIDUAL, - ...WHAT_NOT_TO_SAVE_SECTION, - "", - ...howToSave, - "", - ...WHEN_TO_ACCESS_SECTION, - "", - ...TRUSTING_RECALL_SECTION, - "", - "## Memory and other forms of persistence", - "Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.", - "- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.", - "- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.", - "", - ...extraGuidelines ?? [], - "" - ]; - lines2.push(...buildSearchingPastContextSection(memoryDir)); - return lines2; -} -function buildMemoryPrompt(params) { - const { displayName, memoryDir, extraGuidelines } = params; - const fs13 = getFsImplementation(); - const entrypoint = memoryDir + ENTRYPOINT_NAME; - let entrypointContent = ""; - try { - entrypointContent = fs13.readFileSync(entrypoint, { encoding: "utf-8" }); - } catch {} - const lines2 = buildMemoryLines(displayName, memoryDir, extraGuidelines); - if (entrypointContent.trim()) { - const t4 = truncateEntrypointContent(entrypointContent); - const memoryType = displayName === AUTO_MEM_DISPLAY_NAME ? "auto" : "agent"; - logMemoryDirCounts(memoryDir, { - content_length: t4.byteCount, - line_count: t4.lineCount, - was_truncated: t4.wasLineTruncated, - was_byte_truncated: t4.wasByteTruncated, - memory_type: memoryType - }); - lines2.push(`## ${ENTRYPOINT_NAME}`, "", t4.content); - } else { - lines2.push(`## ${ENTRYPOINT_NAME}`, "", `Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`); - } - return lines2.join(` -`); -} -function buildSearchingPastContextSection(autoMemDir) { - if (!getFeatureValue_CACHED_MAY_BE_STALE("tengu_coral_fern", false)) { - return []; - } - const projectDir = getProjectDir2(getOriginalCwd()); - const embedded = hasEmbeddedSearchTools() || isReplModeEnabled(); - const memSearch = embedded ? `grep -rn "" ${autoMemDir} --include="*.md"` : `${GREP_TOOL_NAME} with pattern="" path="${autoMemDir}" glob="*.md"`; - const transcriptSearch = embedded ? `grep -rn "" ${projectDir}/ --include="*.jsonl"` : `${GREP_TOOL_NAME} with pattern="" path="${projectDir}/" glob="*.jsonl"`; - return [ - "## Searching past context", - "", - "When looking for past context:", - "1. Search topic files in your memory directory:", - "```", - memSearch, - "```", - "2. Session transcript logs (last resort \u2014 large files, slow):", - "```", - transcriptSearch, - "```", - "Use narrow search terms (error messages, file paths, function names) rather than broad keywords.", - "" - ]; -} -async function loadMemoryPrompt() { - const autoEnabled = isAutoMemoryEnabled(); - const skipIndex = getFeatureValue_CACHED_MAY_BE_STALE("tengu_moth_copse", false); - if (false) {} - const coworkExtraGuidelines = process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES; - const extraGuidelines = coworkExtraGuidelines && coworkExtraGuidelines.trim().length > 0 ? [coworkExtraGuidelines] : undefined; - if (false) {} - if (autoEnabled) { - const autoDir = getAutoMemPath(); - await ensureMemoryDirExists(autoDir); - logMemoryDirCounts(autoDir, { - memory_type: "auto" - }); - return buildMemoryLines("auto memory", autoDir, extraGuidelines, skipIndex).join(` -`); - } - logEvent("tengu_memdir_disabled", { - disabled_by_env_var: isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY), - disabled_by_setting: !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY) && getInitialSettings().autoMemoryEnabled === false - }); - if (getFeatureValue_CACHED_MAY_BE_STALE("tengu_herring_clock", false)) { - logEvent("tengu_team_memdir_disabled", {}); - } - return null; -} -var ENTRYPOINT_NAME = "MEMORY.md", MAX_ENTRYPOINT_LINES = 200, MAX_ENTRYPOINT_BYTES = 25000, AUTO_MEM_DISPLAY_NAME = "auto memory", DIR_EXISTS_GUIDANCE = "This directory already exists \u2014 write to it directly with the Write tool (do not run mkdir or check for its existence)."; -var init_memdir = __esm(() => { - init_fsOperations(); - init_paths(); - init_state(); - init_growthbook(); - init_analytics(); - init_prompt(); - init_constants11(); - init_debug(); - init_embeddedTools(); - init_envUtils(); - init_format(); - init_sessionStorage(); - init_settings2(); - init_memoryTypes(); -}); - -// src/utils/claudemd.ts -import { - basename as basename43, - dirname as dirname56, - extname as extname13, - isAbsolute as isAbsolute25, - join as join141, - parse as parse15, - relative as relative28, - sep as sep35 -} from "path"; -function pathInOriginalCwd(path25) { - return pathInWorkingPath(path25, getOriginalCwd()); -} -function parseFrontmatterPaths(rawContent2) { - const { frontmatter, content } = parseFrontmatter(rawContent2); - if (!frontmatter.paths) { - return { content }; - } - const patterns = splitPathInFrontmatter(frontmatter.paths).map((pattern) => { - return pattern.endsWith("/**") ? pattern.slice(0, -3) : pattern; - }).filter((p4) => p4.length > 0); - if (patterns.length === 0 || patterns.every((p4) => p4 === "**")) { - return { content }; - } - return { content, paths: patterns }; -} -function stripHtmlCommentsFromTokens(tokens) { - let result = ""; - let stripped = false; - const commentSpan = //g; - for (const token of tokens) { - if (token.type === "html") { - const trimmed = token.raw.trimStart(); - if (trimmed.startsWith("")) { - const residue = token.raw.replace(commentSpan, ""); - stripped = true; - if (residue.trim().length > 0) { - result += residue; - } - continue; - } - } - result += token.raw; - } - return { content: result, stripped }; -} -function parseMemoryFileContent(rawContent2, filePath, type, includeBasePath) { - const ext = extname13(filePath).toLowerCase(); - if (ext && !TEXT_FILE_EXTENSIONS.has(ext)) { - logForDebugging(`Skipping non-text file in @include: ${filePath}`); - return { info: null, includePaths: [] }; - } - const { content: withoutFrontmatter, paths: paths2 } = parseFrontmatterPaths(rawContent2); - const hasComment = withoutFrontmatter.includes("")) { - const commentSpan = //g; - const residue = raw.replace(commentSpan, ""); - if (residue.trim().length > 0) { - extractPathsFromText(residue); - } - } - continue; - } - if (element.type === "text") { - extractPathsFromText(element.text || ""); - } - if (element.tokens) { - processElements(element.tokens); - } - if (element.items) { - processElements(element.items); - } - } - } - processElements(tokens); - return [...absolutePaths]; -} -function isClaudeMdExcluded(filePath, type) { - if (type !== "User" && type !== "Project" && type !== "Local") { - return false; - } - const patterns = getInitialSettings().claudeMdExcludes; - if (!patterns || patterns.length === 0) { - return false; - } - const matchOpts = { dot: true }; - const normalizedPath = filePath.replaceAll("\\", "/"); - const expandedPatterns = resolveExcludePatterns(patterns).filter((p4) => p4.length > 0); - if (expandedPatterns.length === 0) { - return false; - } - return import_picomatch.default.isMatch(normalizedPath, expandedPatterns, matchOpts); -} -function resolveExcludePatterns(patterns) { - const fs13 = getFsImplementation(); - const expanded = patterns.map((p4) => p4.replaceAll("\\", "/")); - for (const normalized of expanded) { - if (!normalized.startsWith("/")) { - continue; - } - const globStart = normalized.search(/[*?{[]/); - const staticPrefix = globStart === -1 ? normalized : normalized.slice(0, globStart); - const dirToResolve = dirname56(staticPrefix); - try { - const resolvedDir = fs13.realpathSync(dirToResolve).replaceAll("\\", "/"); - if (resolvedDir !== dirToResolve) { - const resolvedPattern = resolvedDir + normalized.slice(dirToResolve.length); - expanded.push(resolvedPattern); - } - } catch {} - } - return expanded; -} -async function processMemoryFile(filePath, type, processedPaths, includeExternal, depth = 0, parent2) { - const normalizedPath = normalizePathForComparison(filePath); - if (processedPaths.has(normalizedPath) || depth >= MAX_INCLUDE_DEPTH) { - return []; - } - if (isClaudeMdExcluded(filePath, type)) { - return []; - } - const { resolvedPath: resolvedPath5, isSymlink } = safeResolvePath(getFsImplementation(), filePath); - processedPaths.add(normalizedPath); - if (isSymlink) { - processedPaths.add(normalizePathForComparison(resolvedPath5)); - } - const { info: memoryFile, includePaths: resolvedIncludePaths } = await safelyReadMemoryFileAsync(filePath, type, resolvedPath5); - if (!memoryFile || !memoryFile.content.trim()) { - return []; - } - if (parent2) { - memoryFile.parent = parent2; - } - const result = []; - result.push(memoryFile); - for (const resolvedIncludePath of resolvedIncludePaths) { - const isExternal = !pathInOriginalCwd(resolvedIncludePath); - if (isExternal && !includeExternal) { - continue; - } - const includedFiles = await processMemoryFile(resolvedIncludePath, type, processedPaths, includeExternal, depth + 1, filePath); - result.push(...includedFiles); - } - return result; -} -async function processMdRules({ - rulesDir, - type, - processedPaths, - includeExternal, - conditionalRule, - visitedDirs = new Set -}) { - if (visitedDirs.has(rulesDir)) { - return []; - } - try { - const fs13 = getFsImplementation(); - const { resolvedPath: resolvedRulesDir, isSymlink } = safeResolvePath(fs13, rulesDir); - visitedDirs.add(rulesDir); - if (isSymlink) { - visitedDirs.add(resolvedRulesDir); - } - const result = []; - let entries; - try { - entries = await fs13.readdir(resolvedRulesDir); - } catch (e4) { - const code = getErrnoCode(e4); - if (code === "ENOENT" || code === "EACCES" || code === "ENOTDIR") { - return []; - } - throw e4; - } - for (const entry of entries) { - const entryPath = join141(rulesDir, entry.name); - const { resolvedPath: resolvedEntryPath, isSymlink: isSymlink2 } = safeResolvePath(fs13, entryPath); - const stats2 = isSymlink2 ? await fs13.stat(resolvedEntryPath) : null; - const isDirectory = stats2 ? stats2.isDirectory() : entry.isDirectory(); - const isFile2 = stats2 ? stats2.isFile() : entry.isFile(); - if (isDirectory) { - result.push(...await processMdRules({ - rulesDir: resolvedEntryPath, - type, - processedPaths, - includeExternal, - conditionalRule, - visitedDirs - })); - } else if (isFile2 && entry.name.endsWith(".md")) { - const files3 = await processMemoryFile(resolvedEntryPath, type, processedPaths, includeExternal); - result.push(...files3.filter((f4) => conditionalRule ? f4.globs : !f4.globs)); - } - } - return result; - } catch (error46) { - if (error46 instanceof Error && error46.message.includes("EACCES")) { - logEvent("tengu_claude_rules_md_permission_error", { - is_access_error: 1, - has_home_dir: rulesDir.includes(getClaudeConfigHomeDir()) ? 1 : 0 - }); - } - return []; - } -} -function isInstructionsMemoryType2(type) { - return type === "User" || type === "Project" || type === "Local" || type === "Managed"; -} -function consumeNextEagerLoadReason() { - if (!shouldFireHook) - return; - shouldFireHook = false; - const reason = nextEagerLoadReason; - nextEagerLoadReason = "session_start"; - return reason; -} -function clearMemoryFileCaches() { - getMemoryFiles.cache?.clear?.(); -} -function resetGetMemoryFilesCache(reason = "session_start") { - nextEagerLoadReason = reason; - shouldFireHook = true; - clearMemoryFileCaches(); -} -function getLargeMemoryFiles(files3) { - return files3.filter((f4) => f4.content.length > MAX_MEMORY_CHARACTER_COUNT); -} -function filterInjectedMemoryFiles2(files3) { - const skipMemoryIndex = getFeatureValue_CACHED_MAY_BE_STALE("tengu_moth_copse", false); - if (!skipMemoryIndex) - return files3; - return files3.filter((f4) => f4.type !== "AutoMem" && f4.type !== "TeamMem"); -} -async function getManagedAndUserConditionalRules(targetPath, processedPaths) { - const result = []; - const managedClaudeRulesDir = getManagedClaudeRulesDir(); - result.push(...await processConditionedMdRules(targetPath, managedClaudeRulesDir, "Managed", processedPaths, false)); - if (isSettingSourceEnabled("userSettings")) { - const userClaudeRulesDir = getUserClaudeRulesDir(); - result.push(...await processConditionedMdRules(targetPath, userClaudeRulesDir, "User", processedPaths, true)); - } - return result; -} -async function getMemoryFilesForNestedDirectory(dir, targetPath, processedPaths) { - const result = []; - if (isSettingSourceEnabled("projectSettings")) { - const projectPath = join141(dir, "CLAUDE.md"); - result.push(...await processMemoryFile(projectPath, "Project", processedPaths, false)); - const dotClaudePath = join141(dir, ".claude", "CLAUDE.md"); - result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, false)); - } - if (isSettingSourceEnabled("localSettings")) { - const localPath = join141(dir, "CLAUDE.local.md"); - result.push(...await processMemoryFile(localPath, "Local", processedPaths, false)); - } - const rulesDir = join141(dir, ".claude", "rules"); - const unconditionalProcessedPaths = new Set(processedPaths); - result.push(...await processMdRules({ - rulesDir, - type: "Project", - processedPaths: unconditionalProcessedPaths, - includeExternal: false, - conditionalRule: false - })); - result.push(...await processConditionedMdRules(targetPath, rulesDir, "Project", processedPaths, false)); - for (const path25 of unconditionalProcessedPaths) { - processedPaths.add(path25); - } - return result; -} -async function getConditionalRulesForCwdLevelDirectory(dir, targetPath, processedPaths) { - const rulesDir = join141(dir, ".claude", "rules"); - return processConditionedMdRules(targetPath, rulesDir, "Project", processedPaths, false); -} -async function processConditionedMdRules(targetPath, rulesDir, type, processedPaths, includeExternal) { - const conditionedRuleMdFiles = await processMdRules({ - rulesDir, - type, - processedPaths, - includeExternal, - conditionalRule: true - }); - return conditionedRuleMdFiles.filter((file2) => { - if (!file2.globs || file2.globs.length === 0) { - return false; - } - const baseDir = type === "Project" ? dirname56(dirname56(rulesDir)) : getOriginalCwd(); - const relativePath2 = isAbsolute25(targetPath) ? relative28(baseDir, targetPath) : targetPath; - if (!relativePath2 || relativePath2.startsWith("..") || isAbsolute25(relativePath2)) { - return false; - } - return import_ignore6.default().add(file2.globs).ignores(relativePath2); - }); -} -function getExternalClaudeMdIncludes(files3) { - const externals = []; - for (const file2 of files3) { - if (file2.type !== "User" && file2.parent && !pathInOriginalCwd(file2.path)) { - externals.push({ path: file2.path, parent: file2.parent }); - } - } - return externals; -} -function hasExternalClaudeMdIncludes(files3) { - return getExternalClaudeMdIncludes(files3).length > 0; -} -async function shouldShowClaudeMdExternalIncludesWarning() { - const config10 = getCurrentProjectConfig(); - if (config10.hasClaudeMdExternalIncludesApproved || config10.hasClaudeMdExternalIncludesWarningShown) { - return false; - } - return hasExternalClaudeMdIncludes(await getMemoryFiles(true)); -} -var import_ignore6, import_picomatch, hasLoggedInitialLoad = false, MEMORY_INSTRUCTION_PROMPT = "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.", MAX_MEMORY_CHARACTER_COUNT = 40000, TEXT_FILE_EXTENSIONS, MAX_INCLUDE_DEPTH = 5, getMemoryFiles, nextEagerLoadReason = "session_start", shouldFireHook = true, getClaudeMds = (memoryFiles, filter2) => { - const memories = []; - const skipProjectLevel = getFeatureValue_CACHED_MAY_BE_STALE("tengu_paper_halyard", false); - for (const file2 of memoryFiles) { - if (filter2 && !filter2(file2.type)) - continue; - if (skipProjectLevel && (file2.type === "Project" || file2.type === "Local")) - continue; - if (file2.content) { - const description = file2.type === "Project" ? " (project instructions, checked into the codebase)" : file2.type === "Local" ? " (user's private project instructions, not checked in)" : file2.type === "AutoMem" ? " (user's auto-memory, persists across conversations)" : " (user's private global instructions for all projects)"; - const content = file2.content.trim(); - if (false) {} else { - memories.push(`Contents of ${file2.path}${description}: - -${content}`); - } - } - } - if (memories.length === 0) { - return ""; - } - return `${MEMORY_INSTRUCTION_PROMPT} - -${memories.join(` - -`)}`; -}; -var init_claudemd = __esm(() => { - init_memoize(); - init_marked_esm(); - init_analytics(); - init_state(); - init_memdir(); - init_paths(); - init_growthbook(); - init_config(); - init_debug(); - init_diagLogs(); - init_envUtils(); - init_errors(); - init_file(); - init_fileStateCache(); - init_frontmatterParser(); - init_fsOperations(); - init_git(); - init_hooks3(); - init_path(); - init_filesystem(); - init_constants2(); - init_settings2(); - import_ignore6 = __toESM(require_ignore(), 1); - import_picomatch = __toESM(require_picomatch2(), 1); - TEXT_FILE_EXTENSIONS = new Set([ - ".md", - ".txt", - ".text", - ".json", - ".yaml", - ".yml", - ".toml", - ".xml", - ".csv", - ".html", - ".htm", - ".css", - ".scss", - ".sass", - ".less", - ".js", - ".ts", - ".tsx", - ".jsx", - ".mjs", - ".cjs", - ".mts", - ".cts", - ".py", - ".pyi", - ".pyw", - ".rb", - ".erb", - ".rake", - ".go", - ".rs", - ".java", - ".kt", - ".kts", - ".scala", - ".c", - ".cpp", - ".cc", - ".cxx", - ".h", - ".hpp", - ".hxx", - ".cs", - ".swift", - ".sh", - ".bash", - ".zsh", - ".fish", - ".ps1", - ".bat", - ".cmd", - ".env", - ".ini", - ".cfg", - ".conf", - ".config", - ".properties", - ".sql", - ".graphql", - ".gql", - ".proto", - ".vue", - ".svelte", - ".astro", - ".ejs", - ".hbs", - ".pug", - ".jade", - ".php", - ".pl", - ".pm", - ".lua", - ".r", - ".R", - ".dart", - ".ex", - ".exs", - ".erl", - ".hrl", - ".clj", - ".cljs", - ".cljc", - ".edn", - ".hs", - ".lhs", - ".elm", - ".ml", - ".mli", - ".f", - ".f90", - ".f95", - ".for", - ".cmake", - ".make", - ".makefile", - ".gradle", - ".sbt", - ".rst", - ".adoc", - ".asciidoc", - ".org", - ".tex", - ".latex", - ".lock", - ".log", - ".diff", - ".patch" - ]); - getMemoryFiles = memoize_default(async (forceIncludeExternal = false) => { - const startTime = Date.now(); - logForDiagnosticsNoPII("info", "memory_files_started"); - const result = []; - const processedPaths = new Set; - const config10 = getCurrentProjectConfig(); - const includeExternal = forceIncludeExternal || config10.hasClaudeMdExternalIncludesApproved || false; - const managedClaudeMd = getMemoryPath("Managed"); - result.push(...await processMemoryFile(managedClaudeMd, "Managed", processedPaths, includeExternal)); - const managedClaudeRulesDir = getManagedClaudeRulesDir(); - result.push(...await processMdRules({ - rulesDir: managedClaudeRulesDir, - type: "Managed", - processedPaths, - includeExternal, - conditionalRule: false - })); - if (isSettingSourceEnabled("userSettings")) { - const userClaudeMd = getMemoryPath("User"); - result.push(...await processMemoryFile(userClaudeMd, "User", processedPaths, true)); - const userClaudeRulesDir = getUserClaudeRulesDir(); - result.push(...await processMdRules({ - rulesDir: userClaudeRulesDir, - type: "User", - processedPaths, - includeExternal: true, - conditionalRule: false - })); - } - const dirs = []; - const originalCwd = getOriginalCwd(); - let currentDir = originalCwd; - while (currentDir !== parse15(currentDir).root) { - dirs.push(currentDir); - currentDir = dirname56(currentDir); - } - const gitRoot = findGitRoot(originalCwd); - const canonicalRoot = findCanonicalGitRoot(originalCwd); - const isNestedWorktree = gitRoot !== null && canonicalRoot !== null && normalizePathForComparison(gitRoot) !== normalizePathForComparison(canonicalRoot) && pathInWorkingPath(gitRoot, canonicalRoot); - for (const dir of dirs.reverse()) { - const skipProject = isNestedWorktree && pathInWorkingPath(dir, canonicalRoot) && !pathInWorkingPath(dir, gitRoot); - if (isSettingSourceEnabled("projectSettings") && !skipProject) { - const projectPath = join141(dir, "CLAUDE.md"); - result.push(...await processMemoryFile(projectPath, "Project", processedPaths, includeExternal)); - const dotClaudePath = join141(dir, ".claude", "CLAUDE.md"); - result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, includeExternal)); - const rulesDir = join141(dir, ".claude", "rules"); - result.push(...await processMdRules({ - rulesDir, - type: "Project", - processedPaths, - includeExternal, - conditionalRule: false - })); - } - if (isSettingSourceEnabled("localSettings")) { - const localPath = join141(dir, "CLAUDE.local.md"); - result.push(...await processMemoryFile(localPath, "Local", processedPaths, includeExternal)); - } - } - if (isEnvTruthy(process.env.CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD)) { - const additionalDirs = getAdditionalDirectoriesForClaudeMd(); - for (const dir of additionalDirs) { - const projectPath = join141(dir, "CLAUDE.md"); - result.push(...await processMemoryFile(projectPath, "Project", processedPaths, includeExternal)); - const dotClaudePath = join141(dir, ".claude", "CLAUDE.md"); - result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, includeExternal)); - const rulesDir = join141(dir, ".claude", "rules"); - result.push(...await processMdRules({ - rulesDir, - type: "Project", - processedPaths, - includeExternal, - conditionalRule: false - })); - } - } - if (isAutoMemoryEnabled()) { - const { info: memdirEntry } = await safelyReadMemoryFileAsync(getAutoMemEntrypoint(), "AutoMem"); - if (memdirEntry) { - const normalizedPath = normalizePathForComparison(memdirEntry.path); - if (!processedPaths.has(normalizedPath)) { - processedPaths.add(normalizedPath); - result.push(memdirEntry); - } - } - } - if (false) {} - const totalContentLength = result.reduce((sum, f4) => sum + f4.content.length, 0); - logForDiagnosticsNoPII("info", "memory_files_completed", { - duration_ms: Date.now() - startTime, - file_count: result.length, - total_content_length: totalContentLength - }); - const typeCounts = {}; - for (const f4 of result) { - typeCounts[f4.type] = (typeCounts[f4.type] ?? 0) + 1; - } - if (!hasLoggedInitialLoad) { - hasLoggedInitialLoad = true; - logEvent("tengu_claudemd__initial_load", { - file_count: result.length, - total_content_length: totalContentLength, - user_count: typeCounts["User"] ?? 0, - project_count: typeCounts["Project"] ?? 0, - local_count: typeCounts["Local"] ?? 0, - managed_count: typeCounts["Managed"] ?? 0, - automem_count: typeCounts["AutoMem"] ?? 0, - ...{}, - duration_ms: Date.now() - startTime - }); - } - if (!forceIncludeExternal) { - const eagerLoadReason = consumeNextEagerLoadReason(); - if (eagerLoadReason !== undefined && hasInstructionsLoadedHook()) { - for (const file2 of result) { - if (!isInstructionsMemoryType2(file2.type)) - continue; - const loadReason = file2.parent ? "include" : eagerLoadReason; - executeInstructionsLoadedHooks(file2.path, file2.type, loadReason, { - globs: file2.globs, - parentFilePath: file2.parent - }); - } - } - } - return result; - }); -}); - -// src/context.ts -function setSystemPromptInjection(value) { - systemPromptInjection = value; - getUserContext.cache.clear?.(); - getSystemContext.cache.clear?.(); -} -var MAX_STATUS_CHARS = 2000, systemPromptInjection = null, getGitStatus, getSystemContext, getUserContext; -var init_context4 = __esm(() => { - init_memoize(); - init_state(); - init_common(); - init_claudemd(); - init_diagLogs(); - init_envUtils(); - init_execFileNoThrow(); - init_git(); - init_gitSettings(); - init_log2(); - getGitStatus = memoize_default(async () => { - if (false) {} - const startTime = Date.now(); - logForDiagnosticsNoPII("info", "git_status_started"); - const isGitStart = Date.now(); - const isGit = await getIsGit(); - logForDiagnosticsNoPII("info", "git_is_git_check_completed", { - duration_ms: Date.now() - isGitStart, - is_git: isGit - }); - if (!isGit) { - logForDiagnosticsNoPII("info", "git_status_skipped_not_git", { - duration_ms: Date.now() - startTime - }); - return null; - } - try { - const gitCmdsStart = Date.now(); - const [branch2, mainBranch, status2, log3, userName] = await Promise.all([ - getBranch(), - getDefaultBranch(), - execFileNoThrow(gitExe(), ["--no-optional-locks", "status", "--short"], { - preserveOutputOnError: false - }).then(({ stdout }) => stdout.trim()), - execFileNoThrow(gitExe(), ["--no-optional-locks", "log", "--oneline", "-n", "5"], { - preserveOutputOnError: false - }).then(({ stdout }) => stdout.trim()), - execFileNoThrow(gitExe(), ["config", "user.name"], { - preserveOutputOnError: false - }).then(({ stdout }) => stdout.trim()) - ]); - logForDiagnosticsNoPII("info", "git_commands_completed", { - duration_ms: Date.now() - gitCmdsStart, - status_length: status2.length - }); - const truncatedStatus = status2.length > MAX_STATUS_CHARS ? status2.substring(0, MAX_STATUS_CHARS) + ` -... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)` : status2; - logForDiagnosticsNoPII("info", "git_status_completed", { - duration_ms: Date.now() - startTime, - truncated: status2.length > MAX_STATUS_CHARS - }); - return [ - `This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.`, - `Current branch: ${branch2}`, - `Main branch (you will usually use this for PRs): ${mainBranch}`, - ...userName ? [`Git user: ${userName}`] : [], - `Status: -${truncatedStatus || "(clean)"}`, - `Recent commits: -${log3}` - ].join(` - -`); - } catch (error46) { - logForDiagnosticsNoPII("error", "git_status_failed", { - duration_ms: Date.now() - startTime - }); - logError2(error46); - return null; - } - }); - getSystemContext = memoize_default(async () => { - const startTime = Date.now(); - logForDiagnosticsNoPII("info", "system_context_started"); - const gitStatus = isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) || !shouldIncludeGitInstructions() ? null : await getGitStatus(); - const injection = null; - logForDiagnosticsNoPII("info", "system_context_completed", { - duration_ms: Date.now() - startTime, - has_git_status: gitStatus !== null, - has_injection: injection !== null - }); - return { - ...gitStatus && { gitStatus }, - ...{} - }; - }); - getUserContext = memoize_default(async () => { - const startTime = Date.now(); - logForDiagnosticsNoPII("info", "user_context_started"); - const shouldDisableClaudeMd = isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS) || isBareMode() && getAdditionalDirectoriesForClaudeMd().length === 0; - const claudeMd = shouldDisableClaudeMd ? null : getClaudeMds(filterInjectedMemoryFiles2(await getMemoryFiles())); - setCachedClaudeMdContent(claudeMd || null); - logForDiagnosticsNoPII("info", "user_context_completed", { - duration_ms: Date.now() - startTime, - claudemd_length: claudeMd?.length ?? 0, - claudemd_disabled: Boolean(shouldDisableClaudeMd) - }); - return { - ...claudeMd && { claudeMd }, - currentDate: `Today's date is ${getLocalISODate()}.` - }; - }); -}); - -// src/utils/managedEnv.ts -function withoutSSHTunnelVars(env5) { - if (!env5 || !process.env.ANTHROPIC_UNIX_SOCKET) - return env5 || {}; - const { - ANTHROPIC_UNIX_SOCKET: _1, - ANTHROPIC_BASE_URL: _2, - ANTHROPIC_API_KEY: _3, - ANTHROPIC_AUTH_TOKEN: _4, - CLAUDE_CODE_OAUTH_TOKEN: _5, - ...rest - } = env5; - return rest; -} -function withoutHostManagedProviderVars(env5) { - if (!env5) - return {}; - if (!isEnvTruthy(process.env.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST)) { - return env5; - } - const out = {}; - for (const [key2, value] of Object.entries(env5)) { - if (!isProviderManagedEnvVar(key2)) { - out[key2] = value; - } - } - return out; -} -function withoutCcdSpawnEnvKeys(env5) { - if (!env5 || !ccdSpawnEnvKeys) - return env5 || {}; - const out = {}; - for (const [key2, value] of Object.entries(env5)) { - if (!ccdSpawnEnvKeys.has(key2)) - out[key2] = value; - } - return out; -} -function filterSettingsEnv(env5) { - return withoutCcdSpawnEnvKeys(withoutHostManagedProviderVars(withoutSSHTunnelVars(env5))); -} -function applySafeConfigEnvironmentVariables() { - if (ccdSpawnEnvKeys === undefined) { - ccdSpawnEnvKeys = process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" ? new Set(Object.keys(process.env)) : null; - } - Object.assign(process.env, filterSettingsEnv(getGlobalConfig().env)); - for (const source of TRUSTED_SETTING_SOURCES) { - if (source === "policySettings") - continue; - if (!isSettingSourceEnabled(source)) - continue; - Object.assign(process.env, filterSettingsEnv(getSettingsForSource(source)?.env)); - } - isRemoteManagedSettingsEligible(); - Object.assign(process.env, filterSettingsEnv(getSettingsForSource("policySettings")?.env)); - const settingsEnv = filterSettingsEnv(getSettings_DEPRECATED()?.env); - for (const [key2, value] of Object.entries(settingsEnv)) { - if (SAFE_ENV_VARS2.has(key2.toUpperCase())) { - process.env[key2] = value; - } - } -} -function applyConfigEnvironmentVariables() { - Object.assign(process.env, filterSettingsEnv(getGlobalConfig().env)); - Object.assign(process.env, filterSettingsEnv(getSettings_DEPRECATED()?.env)); - clearCACertsCache(); - clearMTLSCache(); - clearProxyCache(); - configureGlobalAgents(); -} -var ccdSpawnEnvKeys, TRUSTED_SETTING_SOURCES; -var init_managedEnv = __esm(() => { - init_syncCache(); - init_caCerts(); - init_config(); - init_envUtils(); - init_managedEnvConstants(); - init_mtls(); - init_proxy(); - init_constants2(); - init_settings2(); - TRUSTED_SETTING_SOURCES = [ - "userSettings", - "flagSettings", - "policySettings" - ]; -}); - -// src/upstreamproxy/relay.ts -import { createServer as createServer5 } from "net"; -function encodeChunk(data) { - const len = data.length; - const varint = []; - let n6 = len; - while (n6 > 127) { - varint.push(n6 & 127 | 128); - n6 >>>= 7; - } - varint.push(n6); - const out = new Uint8Array(1 + varint.length + len); - out[0] = 10; - out.set(varint, 1); - out.set(data, 1 + varint.length); - return out; -} -function decodeChunk(buf) { - if (buf.length === 0) - return new Uint8Array(0); - if (buf[0] !== 10) - return null; - let len = 0; - let shift = 0; - let i6 = 1; - while (i6 < buf.length) { - const b5 = buf[i6]; - len |= (b5 & 127) << shift; - i6++; - if ((b5 & 128) === 0) - break; - shift += 7; - if (shift > 28) - return null; - } - if (i6 + len > buf.length) - return null; - return buf.subarray(i6, i6 + len); -} -function newConnState() { - return { - connectBuf: Buffer.alloc(0), - pending: [], - wsOpen: false, - established: false, - closed: false - }; -} -async function startUpstreamProxyRelay(opts) { - const authHeader = "Basic " + Buffer.from(`${opts.sessionId}:${opts.token}`).toString("base64"); - const wsAuthHeader = `Bearer ${opts.token}`; - const relay = typeof Bun !== "undefined" ? startBunRelay(opts.wsUrl, authHeader, wsAuthHeader) : await startNodeRelay(opts.wsUrl, authHeader, wsAuthHeader); - logForDebugging(`[upstreamproxy] relay listening on 127.0.0.1:${relay.port}`); - return relay; -} -function startBunRelay(wsUrl, authHeader, wsAuthHeader) { - const server = Bun.listen({ - hostname: "127.0.0.1", - port: 0, - socket: { - open(sock) { - sock.data = { ...newConnState(), writeBuf: [] }; - }, - data(sock, data) { - const st = sock.data; - const adapter2 = { - write: (payload) => { - const bytes = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload; - if (st.writeBuf.length > 0) { - st.writeBuf.push(bytes); - return; - } - const n6 = sock.write(bytes); - if (n6 < bytes.length) - st.writeBuf.push(bytes.subarray(n6)); - }, - end: () => sock.end() - }; - handleData(adapter2, st, data, wsUrl, authHeader, wsAuthHeader); - }, - drain(sock) { - const st = sock.data; - while (st.writeBuf.length > 0) { - const chunk2 = st.writeBuf[0]; - const n6 = sock.write(chunk2); - if (n6 < chunk2.length) { - st.writeBuf[0] = chunk2.subarray(n6); - return; - } - st.writeBuf.shift(); - } - }, - close(sock) { - cleanupConn(sock.data); - }, - error(sock, err2) { - logForDebugging(`[upstreamproxy] client socket error: ${err2.message}`); - cleanupConn(sock.data); - } - } - }); - return { - port: server.port, - stop: () => server.stop(true) - }; -} -async function startNodeRelay(wsUrl, authHeader, wsAuthHeader) { - nodeWSCtor = (await import("ws")).default; - const states = new WeakMap; - const server = createServer5((sock) => { - const st = newConnState(); - states.set(sock, st); - const adapter2 = { - write: (payload) => { - sock.write(typeof payload === "string" ? payload : Buffer.from(payload)); - }, - end: () => sock.end() - }; - sock.on("data", (data) => handleData(adapter2, st, data, wsUrl, authHeader, wsAuthHeader)); - sock.on("close", () => cleanupConn(states.get(sock))); - sock.on("error", (err2) => { - logForDebugging(`[upstreamproxy] client socket error: ${err2.message}`); - cleanupConn(states.get(sock)); - }); - }); - return new Promise((resolve42, reject2) => { - server.once("error", reject2); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - if (addr === null || typeof addr === "string") { - reject2(new Error("upstreamproxy: server has no TCP address")); - return; - } - resolve42({ - port: addr.port, - stop: () => server.close() - }); - }); - }); -} -function handleData(sock, st, data, wsUrl, authHeader, wsAuthHeader) { - if (!st.ws) { - st.connectBuf = Buffer.concat([st.connectBuf, data]); - const headerEnd = st.connectBuf.indexOf(`\r -\r -`); - if (headerEnd === -1) { - if (st.connectBuf.length > 8192) { - sock.write(`HTTP/1.1 400 Bad Request\r -\r -`); - sock.end(); - } - return; - } - const reqHead = st.connectBuf.subarray(0, headerEnd).toString("utf8"); - const firstLine = reqHead.split(`\r -`)[0] ?? ""; - const m4 = firstLine.match(/^CONNECT\s+(\S+)\s+HTTP\/1\.[01]$/i); - if (!m4) { - sock.write(`HTTP/1.1 405 Method Not Allowed\r -\r -`); - sock.end(); - return; - } - const trailing = st.connectBuf.subarray(headerEnd + 4); - if (trailing.length > 0) { - st.pending.push(Buffer.from(trailing)); - } - st.connectBuf = Buffer.alloc(0); - openTunnel(sock, st, firstLine, wsUrl, authHeader, wsAuthHeader); - return; - } - if (!st.wsOpen) { - st.pending.push(Buffer.from(data)); - return; - } - forwardToWs(st.ws, data); -} -function openTunnel(sock, st, connectLine, wsUrl, authHeader, wsAuthHeader) { - const headers = { - "Content-Type": "application/proto", - Authorization: wsAuthHeader - }; - let ws; - if (nodeWSCtor) { - ws = new nodeWSCtor(wsUrl, { - headers, - agent: getWebSocketProxyAgent(wsUrl), - ...getWebSocketTLSOptions() - }); - } else { - ws = new globalThis.WebSocket(wsUrl, { - headers, - proxy: getWebSocketProxyUrl(wsUrl), - tls: getWebSocketTLSOptions() || undefined - }); - } - ws.binaryType = "arraybuffer"; - st.ws = ws; - ws.onopen = () => { - const head = `${connectLine}\r -Proxy-Authorization: ${authHeader}\r -\r -`; - ws.send(encodeChunk(Buffer.from(head, "utf8"))); - st.wsOpen = true; - for (const buf of st.pending) { - forwardToWs(ws, buf); - } - st.pending = []; - st.pinger = setInterval(sendKeepalive, PING_INTERVAL_MS, ws); - }; - ws.onmessage = (ev) => { - const raw = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : new Uint8Array(Buffer.from(ev.data)); - const payload = decodeChunk(raw); - if (payload && payload.length > 0) { - st.established = true; - sock.write(payload); - } - }; - ws.onerror = (ev) => { - const msg = "message" in ev ? String(ev.message) : "websocket error"; - logForDebugging(`[upstreamproxy] ws error: ${msg}`); - if (st.closed) - return; - st.closed = true; - if (!st.established) { - sock.write(`HTTP/1.1 502 Bad Gateway\r -\r -`); - } - sock.end(); - cleanupConn(st); - }; - ws.onclose = () => { - if (st.closed) - return; - st.closed = true; - sock.end(); - cleanupConn(st); - }; -} -function sendKeepalive(ws) { - if (ws.readyState === WebSocket.OPEN) { - ws.send(encodeChunk(new Uint8Array(0))); - } -} -function forwardToWs(ws, data) { - if (ws.readyState !== WebSocket.OPEN) - return; - for (let off = 0;off < data.length; off += MAX_CHUNK_BYTES) { - const slice = data.subarray(off, off + MAX_CHUNK_BYTES); - ws.send(encodeChunk(slice)); - } -} -function cleanupConn(st) { - if (!st) - return; - if (st.pinger) - clearInterval(st.pinger); - if (st.ws && st.ws.readyState <= WebSocket.OPEN) { - try { - st.ws.close(); - } catch {} - } - st.ws = undefined; -} -var nodeWSCtor, MAX_CHUNK_BYTES, PING_INTERVAL_MS = 30000; -var init_relay = __esm(() => { - init_debug(); - init_mtls(); - init_proxy(); - MAX_CHUNK_BYTES = 512 * 1024; -}); - -// src/upstreamproxy/upstreamproxy.ts -var exports_upstreamproxy = {}; -__export(exports_upstreamproxy, { - resetUpstreamProxyForTests: () => resetUpstreamProxyForTests, - initUpstreamProxy: () => initUpstreamProxy, - getUpstreamProxyEnv: () => getUpstreamProxyEnv, - SESSION_TOKEN_PATH: () => SESSION_TOKEN_PATH -}); -import { mkdir as mkdir41, readFile as readFile54, unlink as unlink23, writeFile as writeFile45 } from "fs/promises"; -import { homedir as homedir33 } from "os"; -import { join as join142 } from "path"; -async function initUpstreamProxy(opts) { - if (!isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) { - return state3; - } - if (!isEnvTruthy(process.env.CCR_UPSTREAM_PROXY_ENABLED)) { - return state3; - } - const sessionId = process.env.CLAUDE_CODE_REMOTE_SESSION_ID; - if (!sessionId) { - logForDebugging("[upstreamproxy] CLAUDE_CODE_REMOTE_SESSION_ID unset; proxy disabled", { level: "warn" }); - return state3; - } - const tokenPath = opts?.tokenPath ?? SESSION_TOKEN_PATH; - const token = await readToken(tokenPath); - if (!token) { - logForDebugging("[upstreamproxy] no session token file; proxy disabled"); - return state3; - } - setNonDumpable(); - const baseUrl = opts?.ccrBaseUrl ?? process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com"; - const caBundlePath = opts?.caBundlePath ?? join142(homedir33(), ".ccr", "ca-bundle.crt"); - const caOk = await downloadCaBundle(baseUrl, opts?.systemCaPath ?? SYSTEM_CA_BUNDLE, caBundlePath); - if (!caOk) - return state3; - try { - const wsUrl = baseUrl.replace(/^http/, "ws") + "/v1/code/upstreamproxy/ws"; - const relay = await startUpstreamProxyRelay({ wsUrl, sessionId, token }); - registerCleanup(async () => relay.stop()); - state3 = { enabled: true, port: relay.port, caBundlePath }; - logForDebugging(`[upstreamproxy] enabled on 127.0.0.1:${relay.port}`); - await unlink23(tokenPath).catch(() => { - logForDebugging("[upstreamproxy] token file unlink failed", { - level: "warn" - }); - }); - } catch (err2) { - logForDebugging(`[upstreamproxy] relay start failed: ${err2 instanceof Error ? err2.message : String(err2)}; proxy disabled`, { level: "warn" }); - } - return state3; -} -function getUpstreamProxyEnv() { - if (!state3.enabled || !state3.port || !state3.caBundlePath) { - if (process.env.HTTPS_PROXY && process.env.SSL_CERT_FILE) { - const inherited = {}; - for (const key2 of [ - "HTTPS_PROXY", - "https_proxy", - "NO_PROXY", - "no_proxy", - "SSL_CERT_FILE", - "NODE_EXTRA_CA_CERTS", - "REQUESTS_CA_BUNDLE", - "CURL_CA_BUNDLE" - ]) { - if (process.env[key2]) - inherited[key2] = process.env[key2]; - } - return inherited; - } - return {}; - } - const proxyUrl = `http://127.0.0.1:${state3.port}`; - return { - HTTPS_PROXY: proxyUrl, - https_proxy: proxyUrl, - NO_PROXY: NO_PROXY_LIST, - no_proxy: NO_PROXY_LIST, - SSL_CERT_FILE: state3.caBundlePath, - NODE_EXTRA_CA_CERTS: state3.caBundlePath, - REQUESTS_CA_BUNDLE: state3.caBundlePath, - CURL_CA_BUNDLE: state3.caBundlePath - }; -} -function resetUpstreamProxyForTests() { - state3 = { enabled: false }; -} -async function readToken(path25) { - try { - const raw = await readFile54(path25, "utf8"); - return raw.trim() || null; - } catch (err2) { - if (isENOENT(err2)) - return null; - logForDebugging(`[upstreamproxy] token read failed: ${err2 instanceof Error ? err2.message : String(err2)}`, { level: "warn" }); - return null; - } -} -function setNonDumpable() { - if (process.platform !== "linux" || typeof Bun === "undefined") - return; - try { - const ffi = __require("bun:ffi"); - const lib = ffi.dlopen("libc.so.6", { - prctl: { - args: ["int", "u64", "u64", "u64", "u64"], - returns: "int" - } - }); - const PR_SET_DUMPABLE = 4; - const rc = lib.symbols.prctl(PR_SET_DUMPABLE, 0n, 0n, 0n, 0n); - if (rc !== 0) { - logForDebugging("[upstreamproxy] prctl(PR_SET_DUMPABLE,0) returned nonzero", { - level: "warn" - }); - } - } catch (err2) { - logForDebugging(`[upstreamproxy] prctl unavailable: ${err2 instanceof Error ? err2.message : String(err2)}`, { level: "warn" }); - } -} -async function downloadCaBundle(baseUrl, systemCaPath, outPath) { - try { - const resp = await fetch(`${baseUrl}/v1/code/upstreamproxy/ca-cert`, { - signal: AbortSignal.timeout(5000) - }); - if (!resp.ok) { - logForDebugging(`[upstreamproxy] ca-cert fetch ${resp.status}; proxy disabled`, { level: "warn" }); - return false; - } - const ccrCa = await resp.text(); - const systemCa = await readFile54(systemCaPath, "utf8").catch(() => ""); - await mkdir41(join142(outPath, ".."), { recursive: true }); - await writeFile45(outPath, systemCa + ` -` + ccrCa, "utf8"); - return true; - } catch (err2) { - logForDebugging(`[upstreamproxy] ca-cert download failed: ${err2 instanceof Error ? err2.message : String(err2)}; proxy disabled`, { level: "warn" }); - return false; - } -} -var SESSION_TOKEN_PATH = "/run/ccr/session_token", SYSTEM_CA_BUNDLE = "/etc/ssl/certs/ca-certificates.crt", NO_PROXY_LIST, state3; -var init_upstreamproxy = __esm(() => { - init_cleanupRegistry(); - init_debug(); - init_envUtils(); - init_errors(); - init_relay(); - NO_PROXY_LIST = [ - "localhost", - "127.0.0.1", - "::1", - "169.254.0.0/16", - "10.0.0.0/8", - "172.16.0.0/12", - "192.168.0.0/16", - "anthropic.com", - ".anthropic.com", - "*.anthropic.com", - "github.com", - "api.github.com", - "*.github.com", - "*.githubusercontent.com", - "registry.npmjs.org", - "pypi.org", - "files.pythonhosted.org", - "index.crates.io", - "proxy.golang.org" - ].join(","); - state3 = { enabled: false }; -}); - -// src/components/InvalidConfigDialog.tsx -var exports_InvalidConfigDialog = {}; -__export(exports_InvalidConfigDialog, { - showInvalidConfigDialog: () => showInvalidConfigDialog -}); -function InvalidConfigDialog(t0) { - const $2 = import_compiler_runtime278.c(19); - const { - filePath, - errorDescription, - onExit: onExit2, - onReset - } = t0; - let t1; - if ($2[0] !== onExit2 || $2[1] !== onReset) { - t1 = (value) => { - if (value === "exit") { - onExit2(); - } else { - onReset(); - } - }; - $2[0] = onExit2; - $2[1] = onReset; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const handleSelect = t1; - let t22; - if ($2[3] !== filePath) { - t22 = /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(ThemedText, { - children: [ - "The configuration file at ", - /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(ThemedText, { - bold: true, - children: filePath - }, undefined, false, undefined, this), - " contains invalid JSON." - ] - }, undefined, true, undefined, this); - $2[3] = filePath; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] !== errorDescription) { - t32 = /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(ThemedText, { - children: errorDescription - }, undefined, false, undefined, this); - $2[5] = errorDescription; - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] !== t22 || $2[8] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t22, - t32 - ] - }, undefined, true, undefined, this); - $2[7] = t22; - $2[8] = t32; - $2[9] = t4; - } else { - t4 = $2[9]; - } - let t5; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(ThemedText, { - bold: true, - children: "Choose an option:" - }, undefined, false, undefined, this); - $2[10] = t5; - } else { - t5 = $2[10]; - } - let t6; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t6 = [{ - label: "Exit and fix manually", - value: "exit" - }, { - label: "Reset with default configuration", - value: "reset" - }]; - $2[11] = t6; - } else { - t6 = $2[11]; - } - let t7; - if ($2[12] !== handleSelect || $2[13] !== onExit2) { - t7 = /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t5, - /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(Select, { - options: t6, - onChange: handleSelect, - onCancel: onExit2 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[12] = handleSelect; - $2[13] = onExit2; - $2[14] = t7; - } else { - t7 = $2[14]; - } - let t8; - if ($2[15] !== onExit2 || $2[16] !== t4 || $2[17] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(Dialog, { - title: "Configuration Error", - color: "error", - onCancel: onExit2, - children: [ - t4, - t7 - ] - }, undefined, true, undefined, this); - $2[15] = onExit2; - $2[16] = t4; - $2[17] = t7; - $2[18] = t8; - } else { - t8 = $2[18]; - } - return t8; -} -async function showInvalidConfigDialog({ - error: error46 -}) { - const renderOptions = { - ...getBaseRenderOptions(false), - theme: SAFE_ERROR_THEME_NAME - }; - await new Promise(async (resolve42) => { - const { - unmount - } = await render(/* @__PURE__ */ jsx_dev_runtime360.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime360.jsxDEV(InvalidConfigDialog, { - filePath: error46.filePath, - errorDescription: error46.message, - onExit: () => { - unmount(); - resolve42(); - process.exit(1); - }, - onReset: () => { - writeFileSync_DEPRECATED(error46.filePath, jsonStringify(error46.defaultConfig, null, 2), { - flush: false, - encoding: "utf8" - }); - unmount(); - resolve42(); - process.exit(0); - } - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), renderOptions); - }); -} -var import_compiler_runtime278, jsx_dev_runtime360, SAFE_ERROR_THEME_NAME = "dark"; -var init_InvalidConfigDialog = __esm(() => { - init_ink2(); - init_KeybindingProviderSetup(); - init_AppState(); - init_renderOptions(); - init_slowOperations(); - init_CustomSelect(); - init_Dialog(); - import_compiler_runtime278 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime360 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/context/fpsMetrics.tsx -function FpsMetricsProvider(t0) { - const $2 = import_compiler_runtime279.c(3); - const { - getFpsMetrics, - children - } = t0; - let t1; - if ($2[0] !== children || $2[1] !== getFpsMetrics) { - t1 = /* @__PURE__ */ jsx_dev_runtime361.jsxDEV(FpsMetricsContext.Provider, { - value: getFpsMetrics, - children - }, undefined, false, undefined, this); - $2[0] = children; - $2[1] = getFpsMetrics; - $2[2] = t1; - } else { - t1 = $2[2]; - } - return t1; -} -function useFpsMetrics() { - return import_react194.useContext(FpsMetricsContext); -} -var import_compiler_runtime279, import_react194, jsx_dev_runtime361, FpsMetricsContext; -var init_fpsMetrics = __esm(() => { - import_compiler_runtime279 = __toESM(require_compiler_runtime(), 1); - import_react194 = __toESM(require_react(), 1); - jsx_dev_runtime361 = __toESM(require_jsx_dev_runtime(), 1); - FpsMetricsContext = import_react194.createContext(undefined); -}); - -// src/context/stats.tsx -function percentile(sorted, p4) { - const index2 = p4 / 100 * (sorted.length - 1); - const lower = Math.floor(index2); - const upper = Math.ceil(index2); - if (lower === upper) { - return sorted[lower]; - } - return sorted[lower] + (sorted[upper] - sorted[lower]) * (index2 - lower); -} -function createStatsStore() { - const metrics = new Map; - const histograms = new Map; - const sets = new Map; - return { - increment(name3, value = 1) { - metrics.set(name3, (metrics.get(name3) ?? 0) + value); - }, - set(name3, value) { - metrics.set(name3, value); - }, - observe(name3, value) { - let h5 = histograms.get(name3); - if (!h5) { - h5 = { - reservoir: [], - count: 0, - sum: 0, - min: value, - max: value - }; - histograms.set(name3, h5); - } - h5.count++; - h5.sum += value; - if (value < h5.min) { - h5.min = value; - } - if (value > h5.max) { - h5.max = value; - } - if (h5.reservoir.length < RESERVOIR_SIZE) { - h5.reservoir.push(value); - } else { - const j4 = Math.floor(Math.random() * h5.count); - if (j4 < RESERVOIR_SIZE) { - h5.reservoir[j4] = value; - } - } - }, - add(name3, value) { - let s4 = sets.get(name3); - if (!s4) { - s4 = new Set; - sets.set(name3, s4); - } - s4.add(value); - }, - getAll() { - const result = Object.fromEntries(metrics); - for (const [name3, h5] of histograms) { - if (h5.count === 0) { - continue; - } - result[`${name3}_count`] = h5.count; - result[`${name3}_min`] = h5.min; - result[`${name3}_max`] = h5.max; - result[`${name3}_avg`] = h5.sum / h5.count; - const sorted = [...h5.reservoir].sort((a5, b5) => a5 - b5); - result[`${name3}_p50`] = percentile(sorted, 50); - result[`${name3}_p95`] = percentile(sorted, 95); - result[`${name3}_p99`] = percentile(sorted, 99); - } - for (const [name3, s4] of sets) { - result[name3] = s4.size; - } - return result; - } - }; -} -function StatsProvider(t0) { - const $2 = import_compiler_runtime280.c(7); - const { - store: externalStore, - children - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = createStatsStore(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const internalStore = t1; - const store = externalStore ?? internalStore; - let t22; - let t32; - if ($2[1] !== store) { - t22 = () => { - const flush = () => { - const metrics = store.getAll(); - if (Object.keys(metrics).length > 0) { - saveCurrentProjectConfig((current) => ({ - ...current, - lastSessionMetrics: metrics - })); - } - }; - process.on("exit", flush); - return () => { - process.off("exit", flush); - }; - }; - t32 = [store]; - $2[1] = store; - $2[2] = t22; - $2[3] = t32; - } else { - t22 = $2[2]; - t32 = $2[3]; - } - import_react195.useEffect(t22, t32); - let t4; - if ($2[4] !== children || $2[5] !== store) { - t4 = /* @__PURE__ */ jsx_dev_runtime362.jsxDEV(StatsContext.Provider, { - value: store, - children - }, undefined, false, undefined, this); - $2[4] = children; - $2[5] = store; - $2[6] = t4; - } else { - t4 = $2[6]; - } - return t4; -} -var import_compiler_runtime280, import_react195, jsx_dev_runtime362, RESERVOIR_SIZE = 1024, StatsContext; -var init_stats4 = __esm(() => { - init_config(); - import_compiler_runtime280 = __toESM(require_compiler_runtime(), 1); - import_react195 = __toESM(require_react(), 1); - jsx_dev_runtime362 = __toESM(require_jsx_dev_runtime(), 1); - StatsContext = import_react195.createContext(null); -}); - -// src/utils/sessionState.ts -function setSessionStateChangedListener(cb) { - stateListener = cb; -} -function setSessionMetadataChangedListener(cb) { - metadataListener = cb; -} -function setPermissionModeChangedListener(cb) { - permissionModeListener = cb; -} -function getSessionState() { - return currentState; -} -function notifySessionStateChanged(state4, details) { - currentState = state4; - stateListener?.(state4, details); - if (state4 === "requires_action" && details) { - hasPendingAction = true; - metadataListener?.({ - pending_action: details - }); - } else if (hasPendingAction) { - hasPendingAction = false; - metadataListener?.({ pending_action: null }); - } - if (state4 === "idle") { - metadataListener?.({ task_summary: null }); - } - if (isEnvTruthy(process.env.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS)) { - enqueueSdkEvent({ - type: "system", - subtype: "session_state_changed", - state: state4 - }); - } -} -function notifySessionMetadataChanged(metadata) { - metadataListener?.(metadata); -} -function notifyPermissionModeChanged(mode) { - permissionModeListener?.(mode); -} -var stateListener = null, metadataListener = null, permissionModeListener = null, hasPendingAction = false, currentState = "idle"; -var init_sessionState = __esm(() => { - init_envUtils(); - init_sdkEventQueue(); -}); - -// src/state/onChangeAppState.ts -function externalMetadataToAppState(metadata) { - return (prev) => ({ - ...prev, - ...typeof metadata.permission_mode === "string" ? { - toolPermissionContext: { - ...prev.toolPermissionContext, - mode: permissionModeFromString(metadata.permission_mode) - } - } : {}, - ...typeof metadata.is_ultraplan_mode === "boolean" ? { isUltraplanMode: metadata.is_ultraplan_mode } : {} - }); -} -function onChangeAppState({ - newState, - oldState -}) { - const prevMode = oldState.toolPermissionContext.mode; - const newMode = newState.toolPermissionContext.mode; - if (prevMode !== newMode) { - const prevExternal = toExternalPermissionMode(prevMode); - const newExternal = toExternalPermissionMode(newMode); - if (prevExternal !== newExternal) { - const isUltraplan = newExternal === "plan" && newState.isUltraplanMode && !oldState.isUltraplanMode ? true : null; - notifySessionMetadataChanged({ - permission_mode: newExternal, - is_ultraplan_mode: isUltraplan - }); - } - notifyPermissionModeChanged(newMode); - } - if (newState.mainLoopModel !== oldState.mainLoopModel && newState.mainLoopModel === null) { - updateSettingsForSource("userSettings", { model: undefined }); - setMainLoopModelOverride(null); - } - if (newState.mainLoopModel !== oldState.mainLoopModel && newState.mainLoopModel !== null) { - updateSettingsForSource("userSettings", { model: newState.mainLoopModel }); - setMainLoopModelOverride(newState.mainLoopModel); - } - if (newState.expandedView !== oldState.expandedView) { - const showExpandedTodos = newState.expandedView === "tasks"; - const showSpinnerTree = newState.expandedView === "teammates"; - if (getGlobalConfig().showExpandedTodos !== showExpandedTodos || getGlobalConfig().showSpinnerTree !== showSpinnerTree) { - saveGlobalConfig((current) => ({ - ...current, - showExpandedTodos, - showSpinnerTree - })); - } - } - if (newState.verbose !== oldState.verbose && getGlobalConfig().verbose !== newState.verbose) { - const verbose = newState.verbose; - saveGlobalConfig((current) => ({ - ...current, - verbose - })); - } - if (process.env.USER_TYPE === "ant") { - if (newState.tungstenPanelVisible !== oldState.tungstenPanelVisible && newState.tungstenPanelVisible !== undefined && getGlobalConfig().tungstenPanelVisible !== newState.tungstenPanelVisible) { - const tungstenPanelVisible = newState.tungstenPanelVisible; - saveGlobalConfig((current) => ({ ...current, tungstenPanelVisible })); - } - } - if (newState.settings !== oldState.settings) { - try { - clearApiKeyHelperCache(); - clearAwsCredentialsCache(); - clearGcpCredentialsCache(); - if (newState.settings.env !== oldState.settings.env) { - applyConfigEnvironmentVariables(); - } - } catch (error46) { - logError2(toError(error46)); - } - } -} -var init_onChangeAppState = __esm(() => { - init_state(); - init_auth14(); - init_config(); - init_errors(); - init_log2(); - init_managedEnv(); - init_PermissionMode(); - init_sessionState(); - init_settings2(); -}); - -// src/components/App.tsx -var exports_App = {}; -__export(exports_App, { - App: () => App2 -}); -function App2(t0) { - const $2 = import_compiler_runtime281.c(9); - const { - getFpsMetrics, - stats: stats2, - initialState, - children - } = t0; - let t1; - if ($2[0] !== children || $2[1] !== initialState) { - t1 = /* @__PURE__ */ jsx_dev_runtime363.jsxDEV(AppStateProvider, { - initialState, - onChangeAppState, - children - }, undefined, false, undefined, this); - $2[0] = children; - $2[1] = initialState; - $2[2] = t1; - } else { - t1 = $2[2]; - } - let t22; - if ($2[3] !== stats2 || $2[4] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime363.jsxDEV(StatsProvider, { - store: stats2, - children: t1 - }, undefined, false, undefined, this); - $2[3] = stats2; - $2[4] = t1; - $2[5] = t22; - } else { - t22 = $2[5]; - } - let t32; - if ($2[6] !== getFpsMetrics || $2[7] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime363.jsxDEV(FpsMetricsProvider, { - getFpsMetrics, - children: t22 - }, undefined, false, undefined, this); - $2[6] = getFpsMetrics; - $2[7] = t22; - $2[8] = t32; - } else { - t32 = $2[8]; - } - return t32; -} -var import_compiler_runtime281, jsx_dev_runtime363; -var init_App2 = __esm(() => { - init_fpsMetrics(); - init_stats4(); - init_AppState(); - init_onChangeAppState(); - import_compiler_runtime281 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime363 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/ink/hooks/use-search-highlight.ts -function useSearchHighlight() { - import_react196.useContext(StdinContext_default); - const ink = instances_default.get(process.stdout); - return import_react196.useMemo(() => { - if (!ink) { - return { - setQuery: () => {}, - scanElement: () => [], - setPositions: () => {} - }; - } - return { - setQuery: (query2) => ink.setSearchHighlight(query2), - scanElement: (el) => ink.scanElementSubtree(el), - setPositions: (state4) => ink.setSearchPositions(state4) - }; - }, [ink]); -} -var import_react196; -var init_use_search_highlight = __esm(() => { - init_StdinContext(); - init_instances(); - import_react196 = __toESM(require_react(), 1); -}); - -// src/components/CostThresholdDialog.tsx -function CostThresholdDialog(t0) { - const $2 = import_compiler_runtime282.c(7); - const { - onDone - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime364.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime364.jsxDEV(ThemedText, { - children: "Learn more about how to monitor your spending:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime364.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/costs" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[0] = t1; - } else { - t1 = $2[0]; - } - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = [{ - value: "ok", - label: "Got it, thanks!" - }]; - $2[1] = t22; - } else { - t22 = $2[1]; - } - let t32; - if ($2[2] !== onDone) { - t32 = /* @__PURE__ */ jsx_dev_runtime364.jsxDEV(Select, { - options: t22, - onChange: onDone - }, undefined, false, undefined, this); - $2[2] = onDone; - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] !== onDone || $2[5] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime364.jsxDEV(Dialog, { - title: "You've spent $5 on the Anthropic API this session.", - onCancel: onDone, - children: [ - t1, - t32 - ] - }, undefined, true, undefined, this); - $2[4] = onDone; - $2[5] = t32; - $2[6] = t4; - } else { - t4 = $2[6]; - } - return t4; -} -var import_compiler_runtime282, jsx_dev_runtime364; -var init_CostThresholdDialog = __esm(() => { - init_ink2(); - init_CustomSelect(); - init_Dialog(); - import_compiler_runtime282 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime364 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/IdleReturnDialog.tsx -function IdleReturnDialog(t0) { - const $2 = import_compiler_runtime283.c(16); - const { - idleMinutes, - totalInputTokens, - onDone - } = t0; - let t1; - if ($2[0] !== idleMinutes) { - t1 = formatIdleDuration(idleMinutes); - $2[0] = idleMinutes; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const formattedIdle = t1; - let t22; - if ($2[2] !== totalInputTokens) { - t22 = formatTokens(totalInputTokens); - $2[2] = totalInputTokens; - $2[3] = t22; - } else { - t22 = $2[3]; - } - const formattedTokens = t22; - const t32 = `You've been away ${formattedIdle} and this conversation is ${formattedTokens} tokens.`; - let t4; - if ($2[4] !== onDone) { - t4 = () => onDone("dismiss"); - $2[4] = onDone; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime365.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime365.jsxDEV(ThemedText, { - children: "If this is a new task, clearing context will save usage and be faster." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[6] = t5; - } else { - t5 = $2[6]; - } - let t6; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t6 = { - value: "continue", - label: "Continue this conversation" - }; - $2[7] = t6; - } else { - t6 = $2[7]; - } - let t7; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t7 = { - value: "clear", - label: "Send message as a new conversation" - }; - $2[8] = t7; - } else { - t7 = $2[8]; - } - let t8; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t8 = [t6, t7, { - value: "never", - label: "Don't ask me again" - }]; - $2[9] = t8; - } else { - t8 = $2[9]; - } - let t9; - if ($2[10] !== onDone) { - t9 = /* @__PURE__ */ jsx_dev_runtime365.jsxDEV(Select, { - options: t8, - onChange: (value) => onDone(value) - }, undefined, false, undefined, this); - $2[10] = onDone; - $2[11] = t9; - } else { - t9 = $2[11]; - } - let t10; - if ($2[12] !== t32 || $2[13] !== t4 || $2[14] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime365.jsxDEV(Dialog, { - title: t32, - onCancel: t4, - children: [ - t5, - t9 - ] - }, undefined, true, undefined, this); - $2[12] = t32; - $2[13] = t4; - $2[14] = t9; - $2[15] = t10; - } else { - t10 = $2[15]; - } - return t10; -} -function formatIdleDuration(minutes) { - if (minutes < 1) { - return "< 1m"; - } - if (minutes < 60) { - return `${Math.floor(minutes)}m`; - } - const hours = Math.floor(minutes / 60); - const remainingMinutes = Math.floor(minutes % 60); - if (remainingMinutes === 0) { - return `${hours}h`; - } - return `${hours}h ${remainingMinutes}m`; -} -var import_compiler_runtime283, jsx_dev_runtime365; -var init_IdleReturnDialog = __esm(() => { - init_ink2(); - init_format(); - init_CustomSelect(); - init_Dialog(); - import_compiler_runtime283 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime365 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/services/preventSleep.ts -import { spawn as spawn8 } from "child_process"; -function startPreventSleep() { - refCount++; - if (refCount === 1) { - spawnCaffeinate(); - startRestartInterval(); - } -} -function stopPreventSleep() { - if (refCount > 0) { - refCount--; - } - if (refCount === 0) { - stopRestartInterval(); - killCaffeinate(); - } -} -function forceStopPreventSleep() { - refCount = 0; - stopRestartInterval(); - killCaffeinate(); -} -function startRestartInterval() { - if (process.platform !== "darwin") { - return; - } - if (restartInterval !== null) { - return; - } - restartInterval = setInterval(() => { - if (refCount > 0) { - logForDebugging("Restarting caffeinate to maintain sleep prevention"); - killCaffeinate(); - spawnCaffeinate(); - } - }, RESTART_INTERVAL_MS); - restartInterval.unref(); -} -function stopRestartInterval() { - if (restartInterval !== null) { - clearInterval(restartInterval); - restartInterval = null; - } -} -function spawnCaffeinate() { - if (process.platform !== "darwin") { - return; - } - if (caffeinateProcess !== null) { - return; - } - if (!cleanupRegistered5) { - cleanupRegistered5 = true; - registerCleanup(async () => { - forceStopPreventSleep(); - }); - } - try { - caffeinateProcess = spawn8("caffeinate", ["-i", "-t", String(CAFFEINATE_TIMEOUT_SECONDS)], { - stdio: "ignore" - }); - caffeinateProcess.unref(); - const thisProc = caffeinateProcess; - caffeinateProcess.on("error", (err2) => { - logForDebugging(`caffeinate spawn error: ${err2.message}`); - if (caffeinateProcess === thisProc) - caffeinateProcess = null; - }); - caffeinateProcess.on("exit", () => { - if (caffeinateProcess === thisProc) - caffeinateProcess = null; - }); - logForDebugging("Started caffeinate to prevent sleep"); - } catch { - caffeinateProcess = null; - } -} -function killCaffeinate() { - if (caffeinateProcess !== null) { - const proc = caffeinateProcess; - caffeinateProcess = null; - try { - proc.kill("SIGKILL"); - logForDebugging("Stopped caffeinate, allowing sleep"); - } catch {} - } -} -var CAFFEINATE_TIMEOUT_SECONDS = 300, RESTART_INTERVAL_MS, caffeinateProcess = null, restartInterval = null, refCount = 0, cleanupRegistered5 = false; -var init_preventSleep = __esm(() => { - init_cleanupRegistry(); - init_debug(); - RESTART_INTERVAL_MS = 4 * 60 * 1000; -}); - -// src/utils/QueryGuard.ts -class QueryGuard { - _status = "idle"; - _generation = 0; - _changed = createSignal(); - reserve() { - if (this._status !== "idle") - return false; - this._status = "dispatching"; - this._notify(); - return true; - } - cancelReservation() { - if (this._status !== "dispatching") - return; - this._status = "idle"; - this._notify(); - } - tryStart() { - if (this._status === "running") - return null; - this._status = "running"; - ++this._generation; - this._notify(); - return this._generation; - } - end(generation) { - if (this._generation !== generation) - return false; - if (this._status !== "running") - return false; - this._status = "idle"; - this._notify(); - return true; - } - forceEnd() { - if (this._status === "idle") - return; - this._status = "idle"; - ++this._generation; - this._notify(); - } - get isActive() { - return this._status !== "idle"; - } - get generation() { - return this._generation; - } - subscribe = this._changed.subscribe; - getSnapshot = () => { - return this._status !== "idle"; - }; - _notify() { - this._changed.emit(); - } -} -var init_QueryGuard = () => {}; - -// src/components/permissions/WorkerBadge.tsx -function WorkerBadge(t0) { - const $2 = import_compiler_runtime284.c(7); - const { - name: name3, - color: color3 - } = t0; - let t1; - if ($2[0] !== color3) { - t1 = toInkColor(color3); - $2[0] = color3; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const inkColor = t1; - let t22; - if ($2[2] !== name3) { - t22 = /* @__PURE__ */ jsx_dev_runtime366.jsxDEV(ThemedText, { - bold: true, - children: [ - "@", - name3 - ] - }, undefined, true, undefined, this); - $2[2] = name3; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== inkColor || $2[5] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime366.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: /* @__PURE__ */ jsx_dev_runtime366.jsxDEV(ThemedText, { - color: inkColor, - children: [ - BLACK_CIRCLE, - " ", - t22 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[4] = inkColor; - $2[5] = t22; - $2[6] = t32; - } else { - t32 = $2[6]; - } - return t32; -} -var import_compiler_runtime284, jsx_dev_runtime366; -var init_WorkerBadge = __esm(() => { - init_figures2(); - init_ink2(); - init_ink3(); - import_compiler_runtime284 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime366 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/WorkerPendingPermission.tsx -function WorkerPendingPermission(t0) { - const $2 = import_compiler_runtime285.c(15); - const { - toolName, - description - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getTeamName(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const teamName = t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = getAgentName(); - $2[1] = t22; - } else { - t22 = $2[1]; - } - const agentName = t22; - let t32; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t32 = getTeammateColor(); - $2[2] = t32; - } else { - t32 = $2[2]; - } - const agentColor = t32; - let t4; - let t5; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedText, { - color: "warning", - bold: true, - children: [ - " ", - "Waiting for team lead approval" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - t5 = agentName && agentColor && /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(WorkerBadge, { - name: agentName, - color: agentColor - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[3] = t4; - $2[4] = t5; - } else { - t4 = $2[3]; - t5 = $2[4]; - } - let t6; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedText, { - dimColor: true, - children: "Tool: " - }, undefined, false, undefined, this); - $2[5] = t6; - } else { - t6 = $2[5]; - } - let t7; - if ($2[6] !== toolName) { - t7 = /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedBox_default, { - children: [ - t6, - /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedText, { - children: toolName - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = toolName; - $2[7] = t7; - } else { - t7 = $2[7]; - } - let t8; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedText, { - dimColor: true, - children: "Action: " - }, undefined, false, undefined, this); - $2[8] = t8; - } else { - t8 = $2[8]; - } - let t9; - if ($2[9] !== description) { - t9 = /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedBox_default, { - children: [ - t8, - /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedText, { - children: description - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[9] = description; - $2[10] = t9; - } else { - t9 = $2[10]; - } - let t10; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t10 = teamName && /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Permission request sent to team ", - '"', - teamName, - '"', - " leader" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[11] = t10; - } else { - t10 = $2[11]; - } - let t11; - if ($2[12] !== t7 || $2[13] !== t9) { - t11 = /* @__PURE__ */ jsx_dev_runtime367.jsxDEV(ThemedBox_default, { - flexDirection: "column", - borderStyle: "round", - borderColor: "warning", - paddingX: 1, - children: [ - t4, - t5, - t7, - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[12] = t7; - $2[13] = t9; - $2[14] = t11; - } else { - t11 = $2[14]; - } - return t11; -} -var import_compiler_runtime285, jsx_dev_runtime367; -var init_WorkerPendingPermission = __esm(() => { - init_ink2(); - init_teammate(); - init_Spinner2(); - init_WorkerBadge(); - import_compiler_runtime285 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime367 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useLogMessages.ts -function useLogMessages(messages, ignore7 = false) { - const teamContext = useAppState((s4) => s4.teamContext); - const lastRecordedLengthRef = import_react197.useRef(0); - const lastParentUuidRef = import_react197.useRef(undefined); - const firstMessageUuidRef = import_react197.useRef(undefined); - const callSeqRef = import_react197.useRef(0); - import_react197.useEffect(() => { - if (ignore7) - return; - const currentFirstUuid = messages[0]?.uuid; - const prevLength = lastRecordedLengthRef.current; - const wasFirstRender = firstMessageUuidRef.current === undefined; - const isIncremental = currentFirstUuid !== undefined && !wasFirstRender && currentFirstUuid === firstMessageUuidRef.current && prevLength <= messages.length; - const isSameHeadShrink = currentFirstUuid !== undefined && !wasFirstRender && currentFirstUuid === firstMessageUuidRef.current && prevLength > messages.length; - const startIndex = isIncremental ? prevLength : 0; - if (startIndex === messages.length) - return; - const slice = startIndex === 0 ? messages : messages.slice(startIndex); - const parentHint = isIncremental ? lastParentUuidRef.current : undefined; - const seq = ++callSeqRef.current; - recordTranscript(slice, isAgentSwarmsEnabled() ? { - teamName: teamContext?.teamName, - agentName: teamContext?.selfAgentName - } : {}, parentHint, messages).then((lastRecordedUuid) => { - if (seq !== callSeqRef.current) - return; - if (lastRecordedUuid && !isIncremental) { - lastParentUuidRef.current = lastRecordedUuid; - } - }); - if (isIncremental || wasFirstRender || isSameHeadShrink) { - const last2 = cleanMessagesForLogging(slice, messages).findLast(isChainParticipant); - if (last2) - lastParentUuidRef.current = last2.uuid; - } - lastRecordedLengthRef.current = messages.length; - firstMessageUuidRef.current = currentFirstUuid; - }, [messages, ignore7, teamContext?.teamName, teamContext?.selfAgentName]); -} -var import_react197; -var init_useLogMessages = __esm(() => { - init_AppState(); - init_agentSwarmsEnabled(); - init_sessionStorage(); - import_react197 = __toESM(require_react(), 1); -}); - -// src/bridge/bridgePermissionCallbacks.ts -var init_bridgePermissionCallbacks = () => {}; - -// src/bridge/inboundMessages.ts -function extractInboundMessageFields(msg) { - if (msg.type !== "user") - return; - const content = msg.message?.content; - if (!content) - return; - if (Array.isArray(content) && content.length === 0) - return; - const uuid8 = "uuid" in msg && typeof msg.uuid === "string" ? msg.uuid : undefined; - return { - content: Array.isArray(content) ? normalizeImageBlocks(content) : content, - uuid: uuid8 - }; -} -function normalizeImageBlocks(blocks) { - if (!blocks.some(isMalformedBase64Image)) - return blocks; - return blocks.map((block2) => { - if (!isMalformedBase64Image(block2)) - return block2; - const src = block2.source; - const mediaType = typeof src.mediaType === "string" && src.mediaType ? src.mediaType : detectImageFormatFromBase64(block2.source.data); - return { - ...block2, - source: { - type: "base64", - media_type: mediaType, - data: block2.source.data - } - }; - }); -} -function isMalformedBase64Image(block2) { - if (block2.type !== "image" || block2.source?.type !== "base64") - return false; - return !block2.source.media_type; -} -var init_inboundMessages = __esm(() => { - init_imageResizer(); -}); - -// src/utils/messages/systemInit.ts -import { randomUUID as randomUUID34 } from "crypto"; -function sdkCompatToolName(name3) { - return name3 === AGENT_TOOL_NAME ? LEGACY_AGENT_TOOL_NAME : name3; -} -function buildSystemInitMessage(inputs) { - const settings = getSettings_DEPRECATED(); - const outputStyle2 = settings?.outputStyle ?? DEFAULT_OUTPUT_STYLE_NAME; - const initMessage = { - type: "system", - subtype: "init", - cwd: getCwd(), - session_id: getSessionId(), - tools: inputs.tools.map((tool) => sdkCompatToolName(tool.name)), - mcp_servers: inputs.mcpClients.map((client16) => ({ - name: client16.name, - status: client16.type - })), - model: inputs.model, - permissionMode: inputs.permissionMode, - slash_commands: inputs.commands.filter((c9) => c9.userInvocable !== false).map((c9) => c9.name), - apiKeySource: getAnthropicApiKeyWithSource().source, - betas: getSdkBetas(), - claude_code_version: MACRO.VERSION, - output_style: outputStyle2, - agents: inputs.agents.map((agent) => agent.agentType), - skills: inputs.skills.filter((s4) => s4.userInvocable !== false).map((skill) => skill.name), - plugins: inputs.plugins.map((plugin2) => ({ - name: plugin2.name, - path: plugin2.path, - source: plugin2.source - })), - uuid: randomUUID34() - }; - if (false) {} - initMessage.fast_mode_state = getFastModeState(inputs.model, inputs.fastMode); - return initMessage; -} -var init_systemInit = __esm(() => { - init_state(); - init_outputStyles(); - init_constants3(); - init_auth14(); - init_cwd(); - init_fastMode(); - init_settings2(); -}); - -// src/hooks/useReplBridge.tsx -function useReplBridge(messages, setMessages, abortControllerRef, commands7, mainLoopModel) { - const handleRef = import_react198.useRef(null); - const teardownPromiseRef = import_react198.useRef(undefined); - const lastWrittenIndexRef = import_react198.useRef(0); - const flushedUUIDsRef = import_react198.useRef(new Set); - const failureTimeoutRef = import_react198.useRef(undefined); - const consecutiveFailuresRef = import_react198.useRef(0); - const setAppState = useSetAppState(); - const commandsRef = import_react198.useRef(commands7); - commandsRef.current = commands7; - const mainLoopModelRef = import_react198.useRef(mainLoopModel); - mainLoopModelRef.current = mainLoopModel; - const messagesRef = import_react198.useRef(messages); - messagesRef.current = messages; - const store = useAppStateStore(); - const { - addNotification - } = useNotifications(); - const replBridgeEnabled = false; - const replBridgeConnected = false; - const replBridgeOutboundOnly = false; - const replBridgeInitialName = undefined; - import_react198.useEffect(() => { - if (false) { - let notifyBridgeFailed = function(detail) {}; - } - }, [replBridgeEnabled, replBridgeOutboundOnly, setAppState, setMessages, addNotification]); - import_react198.useEffect(() => { - if (false) {} - }, [messages, replBridgeConnected]); - const sendBridgeResult = import_react198.useCallback(() => { - if (false) {} - }, []); - return { - sendBridgeResult - }; -} -var import_react198, jsx_dev_runtime368; -var init_useReplBridge = __esm(() => { - init_state(); - init_bridgePermissionCallbacks(); - init_bridgeStatusUtil(); - init_inboundMessages(); - init_replBridgeHandle(); - init_commands5(); - init_notifications(); - init_ink2(); - init_growthbook(); - init_AppState(); - init_cwd(); - init_debug(); - init_errors(); - init_messageQueueManager(); - init_systemInit(); - init_messages9(); - init_permissionSetup(); - import_react198 = __toESM(require_react(), 1); - jsx_dev_runtime368 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/MessageSelector.tsx -var exports_MessageSelector = {}; -__export(exports_MessageSelector, { - selectableUserMessagesFilter: () => selectableUserMessagesFilter, - messagesAfterAreOnlySynthetic: () => messagesAfterAreOnlySynthetic, - MessageSelector: () => MessageSelector -}); -import { randomUUID as randomUUID35 } from "crypto"; -import * as path25 from "path"; -function isTextBlock2(block2) { - return block2.type === "text"; -} -function isSummarizeOption(option) { - return option === "summarize" || option === "summarize_up_to"; -} -function MessageSelector({ - messages, - onPreRestore, - onRestoreMessage, - onRestoreCode, - onSummarize, - onClose, - preselectedMessage -}) { - const fileHistory = useAppState((s4) => s4.fileHistory); - const [error46, setError] = import_react199.useState(undefined); - const isFileHistoryEnabled = fileHistoryEnabled(); - const currentUUID = import_react199.useMemo(randomUUID35, []); - const messageOptions = import_react199.useMemo(() => [...messages.filter(selectableUserMessagesFilter), { - ...createUserMessage({ - content: "" - }), - uuid: currentUUID - }], [messages, currentUUID]); - const [selectedIndex, setSelectedIndex] = import_react199.useState(messageOptions.length - 1); - const firstVisibleIndex = Math.max(0, Math.min(selectedIndex - Math.floor(MAX_VISIBLE_MESSAGES / 2), messageOptions.length - MAX_VISIBLE_MESSAGES)); - const hasMessagesToSelect = messageOptions.length > 1; - const [messageToRestore, setMessageToRestore] = import_react199.useState(preselectedMessage); - const [diffStatsForRestore, setDiffStatsForRestore] = import_react199.useState(undefined); - import_react199.useEffect(() => { - if (!preselectedMessage || !isFileHistoryEnabled) - return; - let cancelled = false; - fileHistoryGetDiffStats(fileHistory, preselectedMessage.uuid).then((stats2) => { - if (!cancelled) - setDiffStatsForRestore(stats2); - }); - return () => { - cancelled = true; - }; - }, [preselectedMessage, isFileHistoryEnabled, fileHistory]); - const [isRestoring, setIsRestoring] = import_react199.useState(false); - const [restoringOption, setRestoringOption] = import_react199.useState(null); - const [selectedRestoreOption, setSelectedRestoreOption] = import_react199.useState("both"); - const [summarizeFromFeedback, setSummarizeFromFeedback] = import_react199.useState(""); - const [summarizeUpToFeedback, setSummarizeUpToFeedback] = import_react199.useState(""); - function getRestoreOptions(canRestoreCode) { - const baseOptions = canRestoreCode ? [{ - value: "both", - label: "Restore code and conversation" - }, { - value: "conversation", - label: "Restore conversation" - }, { - value: "code", - label: "Restore code" - }] : [{ - value: "conversation", - label: "Restore conversation" - }]; - const summarizeInputProps = { - type: "input", - placeholder: "add context (optional)", - initialValue: "", - allowEmptySubmitToCancel: true, - showLabelWithValue: true, - labelValueSeparator: ": " - }; - baseOptions.push({ - value: "summarize", - label: "Summarize from here", - ...summarizeInputProps, - onChange: setSummarizeFromFeedback - }); - if (false) {} - baseOptions.push({ - value: "nevermind", - label: "Never mind" - }); - return baseOptions; - } - import_react199.useEffect(() => { - logEvent("tengu_message_selector_opened", {}); - }, []); - async function restoreConversationDirectly(message) { - onPreRestore(); - setIsRestoring(true); - try { - await onRestoreMessage(message); - setIsRestoring(false); - onClose(); - } catch (error_0) { - logError2(error_0); - setIsRestoring(false); - setError(`Failed to restore the conversation: -${error_0}`); - } - } - async function handleSelect(message_0) { - const index2 = messages.indexOf(message_0); - const indexFromEnd = messages.length - 1 - index2; - logEvent("tengu_message_selector_selected", { - index_from_end: indexFromEnd, - message_type: message_0.type, - is_current_prompt: false - }); - if (!messages.includes(message_0)) { - onClose(); - return; - } - if (!isFileHistoryEnabled) { - await restoreConversationDirectly(message_0); - return; - } - const diffStats = await fileHistoryGetDiffStats(fileHistory, message_0.uuid); - setMessageToRestore(message_0); - setDiffStatsForRestore(diffStats); - } - async function onSelectRestoreOption(option) { - logEvent("tengu_message_selector_restore_option_selected", { - option - }); - if (!messageToRestore) { - setError("Message not found."); - return; - } - if (option === "nevermind") { - if (preselectedMessage) - onClose(); - else - setMessageToRestore(undefined); - return; - } - if (isSummarizeOption(option)) { - onPreRestore(); - setIsRestoring(true); - setRestoringOption(option); - setError(undefined); - try { - const direction = option === "summarize_up_to" ? "up_to" : "from"; - const feedback2 = (direction === "up_to" ? summarizeUpToFeedback : summarizeFromFeedback).trim() || undefined; - await onSummarize(messageToRestore, feedback2, direction); - setIsRestoring(false); - setRestoringOption(null); - setMessageToRestore(undefined); - onClose(); - } catch (error_1) { - logError2(error_1); - setIsRestoring(false); - setRestoringOption(null); - setMessageToRestore(undefined); - setError(`Failed to summarize: -${error_1}`); - } - return; - } - onPreRestore(); - setIsRestoring(true); - setError(undefined); - let codeError = null; - let conversationError = null; - if (option === "code" || option === "both") { - try { - await onRestoreCode(messageToRestore); - } catch (error_2) { - codeError = error_2; - logError2(codeError); - } - } - if (option === "conversation" || option === "both") { - try { - await onRestoreMessage(messageToRestore); - } catch (error_3) { - conversationError = error_3; - logError2(conversationError); - } - } - setIsRestoring(false); - setMessageToRestore(undefined); - if (conversationError && codeError) { - setError(`Failed to restore the conversation and code: -${conversationError} -${codeError}`); - } else if (conversationError) { - setError(`Failed to restore the conversation: -${conversationError}`); - } else if (codeError) { - setError(`Failed to restore the code: -${codeError}`); - } else { - onClose(); - } - } - const exitState = useExitOnCtrlCDWithKeybindings(); - const handleEscape = import_react199.useCallback(() => { - if (messageToRestore && !preselectedMessage) { - setMessageToRestore(undefined); - return; - } - logEvent("tengu_message_selector_cancelled", {}); - onClose(); - }, [onClose, messageToRestore, preselectedMessage]); - const moveUp = import_react199.useCallback(() => setSelectedIndex((prev) => Math.max(0, prev - 1)), []); - const moveDown = import_react199.useCallback(() => setSelectedIndex((prev_0) => Math.min(messageOptions.length - 1, prev_0 + 1)), [messageOptions.length]); - const jumpToTop = import_react199.useCallback(() => setSelectedIndex(0), []); - const jumpToBottom = import_react199.useCallback(() => setSelectedIndex(messageOptions.length - 1), [messageOptions.length]); - const handleSelectCurrent = import_react199.useCallback(() => { - const selected = messageOptions[selectedIndex]; - if (selected) { - handleSelect(selected); - } - }, [messageOptions, selectedIndex, handleSelect]); - useKeybinding("confirm:no", handleEscape, { - context: "Confirmation", - isActive: !messageToRestore - }); - useKeybindings({ - "messageSelector:up": moveUp, - "messageSelector:down": moveDown, - "messageSelector:top": jumpToTop, - "messageSelector:bottom": jumpToBottom, - "messageSelector:select": handleSelectCurrent - }, { - context: "MessageSelector", - isActive: !isRestoring && !error46 && !messageToRestore && hasMessagesToSelect - }); - const [fileHistoryMetadata, setFileHistoryMetadata] = import_react199.useState({}); - import_react199.useEffect(() => { - async function loadFileHistoryMetadata() { - if (!isFileHistoryEnabled) { - return; - } - Promise.all(messageOptions.map(async (userMessage, itemIndex) => { - if (userMessage.uuid !== currentUUID) { - const canRestore = fileHistoryCanRestore(fileHistory, userMessage.uuid); - const nextUserMessage = messageOptions.at(itemIndex + 1); - const diffStats_0 = canRestore ? computeDiffStatsBetweenMessages(messages, userMessage.uuid, nextUserMessage?.uuid !== currentUUID ? nextUserMessage?.uuid : undefined) : undefined; - if (diffStats_0 !== undefined) { - setFileHistoryMetadata((prev_1) => ({ - ...prev_1, - [itemIndex]: diffStats_0 - })); - } else { - setFileHistoryMetadata((prev_2) => ({ - ...prev_2, - [itemIndex]: undefined - })); - } - } - })); - } - loadFileHistoryMetadata(); - }, [messageOptions, messages, currentUUID, fileHistory, isFileHistoryEnabled]); - const canRestoreCode_0 = isFileHistoryEnabled && diffStatsForRestore?.filesChanged && diffStatsForRestore.filesChanged.length > 0; - const showPickList = !error46 && !messageToRestore && !preselectedMessage && hasMessagesToSelect; - return /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: "100%", - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(Divider, { - color: "suggestion" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginX: 1, - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - bold: true, - color: "suggestion", - children: "Rewind" - }, undefined, false, undefined, this), - error46 && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: "error", - children: [ - "Error: ", - error46 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - !hasMessagesToSelect && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - children: "Nothing to rewind to yet." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - !error46 && messageToRestore && hasMessagesToSelect && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - children: [ - "Confirm you want to restore", - " ", - !diffStatsForRestore && "the conversation ", - "to the point before you sent this message:" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingLeft: 1, - borderStyle: "single", - borderRight: false, - borderTop: false, - borderBottom: false, - borderLeft: true, - borderLeftDimColor: true, - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(UserMessageOption, { - userMessage: messageToRestore, - color: "text", - isCurrent: false - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "(", - formatRelativeTimeAgo(new Date(messageToRestore.timestamp)), - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(RestoreOptionDescription, { - selectedRestoreOption, - canRestoreCode: !!canRestoreCode_0, - diffStatsForRestore - }, undefined, false, undefined, this), - isRestoring && isSummarizeOption(restoringOption) ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - children: "Summarizing\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(Select, { - isDisabled: isRestoring, - options: getRestoreOptions(!!canRestoreCode_0), - defaultFocusValue: canRestoreCode_0 ? "both" : "conversation", - onFocus: (value) => setSelectedRestoreOption(value), - onChange: (value_0) => onSelectRestoreOption(value_0), - onCancel: () => preselectedMessage ? onClose() : setMessageToRestore(undefined) - }, undefined, false, undefined, this), - canRestoreCode_0 && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.warning, - " Rewinding does not affect files edited manually or via bash." - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - showPickList && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: [ - isFileHistoryEnabled ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - children: "Restore the code and/or conversation to the point before\u2026" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - children: "Restore and fork the conversation to the point before\u2026" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - width: "100%", - flexDirection: "column", - children: messageOptions.slice(firstVisibleIndex, firstVisibleIndex + MAX_VISIBLE_MESSAGES).map((msg, visibleOptionIndex) => { - const optionIndex = firstVisibleIndex + visibleOptionIndex; - const isSelected = optionIndex === selectedIndex; - const isCurrent = msg.uuid === currentUUID; - const metadataLoaded = optionIndex in fileHistoryMetadata; - const metadata = fileHistoryMetadata[optionIndex]; - const numFilesChanged = metadata?.filesChanged && metadata.filesChanged.length; - return /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - height: isFileHistoryEnabled ? 3 : 2, - overflow: "hidden", - width: "100%", - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - width: 2, - minWidth: 2, - children: isSelected ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: "permission", - bold: true, - children: [ - figures_default.pointer, - " " - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexShrink: 1, - height: 1, - overflow: "hidden", - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(UserMessageOption, { - userMessage: msg, - color: isSelected ? "suggestion" : undefined, - isCurrent, - paddingRight: 10 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - isFileHistoryEnabled && metadataLoaded && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - height: 1, - flexDirection: "row", - children: metadata ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: !isSelected, - color: "inactive", - children: numFilesChanged ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: [ - numFilesChanged === 1 && metadata.filesChanged[0] ? `${path25.basename(metadata.filesChanged[0])} ` : `${numFilesChanged} files changed `, - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(DiffStatsText, { - diffStats: metadata - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: "No code changes" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - color: "warning", - children: [ - figures_default.warning, - " No code restore" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, msg.uuid, true, undefined, this); - }) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - !messageToRestore && /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: [ - !error46 && hasMessagesToSelect && "Enter to continue \xB7 ", - "Esc to exit" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -function getRestoreOptionConversationText(option) { - switch (option) { - case "summarize": - return "Messages after this point will be summarized."; - case "summarize_up_to": - return "Preceding messages will be summarized. This and subsequent messages will remain unchanged \u2014 you will stay at the end of the conversation."; - case "both": - case "conversation": - return "The conversation will be forked."; - case "code": - case "nevermind": - return "The conversation will be unchanged."; - } -} -function RestoreOptionDescription(t0) { - const $2 = import_compiler_runtime286.c(11); - const { - selectedRestoreOption, - canRestoreCode, - diffStatsForRestore - } = t0; - const showCodeRestore = canRestoreCode && (selectedRestoreOption === "both" || selectedRestoreOption === "code"); - let t1; - if ($2[0] !== selectedRestoreOption) { - t1 = getRestoreOptionConversationText(selectedRestoreOption); - $2[0] = selectedRestoreOption; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - children: t1 - }, undefined, false, undefined, this); - $2[2] = t1; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== diffStatsForRestore || $2[5] !== selectedRestoreOption || $2[6] !== showCodeRestore) { - t32 = !isSummarizeOption(selectedRestoreOption) && (showCodeRestore ? /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(RestoreCodeConfirmation, { - diffStatsForRestore - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - children: "The code will be unchanged." - }, undefined, false, undefined, this)); - $2[4] = diffStatsForRestore; - $2[5] = selectedRestoreOption; - $2[6] = showCodeRestore; - $2[7] = t32; - } else { - t32 = $2[7]; - } - let t4; - if ($2[8] !== t22 || $2[9] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t22, - t32 - ] - }, undefined, true, undefined, this); - $2[8] = t22; - $2[9] = t32; - $2[10] = t4; - } else { - t4 = $2[10]; - } - return t4; -} -function RestoreCodeConfirmation(t0) { - const $2 = import_compiler_runtime286.c(14); - const { - diffStatsForRestore - } = t0; - if (diffStatsForRestore === undefined) { - return; - } - if (!diffStatsForRestore.filesChanged || !diffStatsForRestore.filesChanged[0]) { - let t12; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - children: "The code has not changed (nothing will be restored)." - }, undefined, false, undefined, this); - $2[0] = t12; - } else { - t12 = $2[0]; - } - return t12; - } - const numFilesChanged = diffStatsForRestore.filesChanged.length; - let fileLabel; - if (numFilesChanged === 1) { - let t12; - if ($2[1] !== diffStatsForRestore.filesChanged[0]) { - t12 = path25.basename(diffStatsForRestore.filesChanged[0] || ""); - $2[1] = diffStatsForRestore.filesChanged[0]; - $2[2] = t12; - } else { - t12 = $2[2]; - } - fileLabel = t12; - } else { - if (numFilesChanged === 2) { - let t12; - if ($2[3] !== diffStatsForRestore.filesChanged[0]) { - t12 = path25.basename(diffStatsForRestore.filesChanged[0] || ""); - $2[3] = diffStatsForRestore.filesChanged[0]; - $2[4] = t12; - } else { - t12 = $2[4]; - } - const file1 = t12; - let t23; - if ($2[5] !== diffStatsForRestore.filesChanged[1]) { - t23 = path25.basename(diffStatsForRestore.filesChanged[1] || ""); - $2[5] = diffStatsForRestore.filesChanged[1]; - $2[6] = t23; - } else { - t23 = $2[6]; - } - const file2 = t23; - fileLabel = `${file1} and ${file2}`; - } else { - let t12; - if ($2[7] !== diffStatsForRestore.filesChanged[0]) { - t12 = path25.basename(diffStatsForRestore.filesChanged[0] || ""); - $2[7] = diffStatsForRestore.filesChanged[0]; - $2[8] = t12; - } else { - t12 = $2[8]; - } - const file1_0 = t12; - fileLabel = `${file1_0} and ${diffStatsForRestore.filesChanged.length - 1} other files`; - } - } - let t1; - if ($2[9] !== diffStatsForRestore) { - t1 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(DiffStatsText, { - diffStats: diffStatsForRestore - }, undefined, false, undefined, this); - $2[9] = diffStatsForRestore; - $2[10] = t1; - } else { - t1 = $2[10]; - } - let t22; - if ($2[11] !== fileLabel || $2[12] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "The code will be restored", - " ", - t1, - " in ", - fileLabel, - "." - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[11] = fileLabel; - $2[12] = t1; - $2[13] = t22; - } else { - t22 = $2[13]; - } - return t22; -} -function DiffStatsText(t0) { - const $2 = import_compiler_runtime286.c(7); - const { - diffStats - } = t0; - if (!diffStats || !diffStats.filesChanged) { - return; - } - let t1; - if ($2[0] !== diffStats.insertions) { - t1 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: "diffAddedWord", - children: [ - "+", - diffStats.insertions, - " " - ] - }, undefined, true, undefined, this); - $2[0] = diffStats.insertions; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== diffStats.deletions) { - t22 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: "diffRemovedWord", - children: [ - "-", - diffStats.deletions - ] - }, undefined, true, undefined, this); - $2[2] = diffStats.deletions; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== t1 || $2[5] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(jsx_dev_runtime369.Fragment, { - children: [ - t1, - t22 - ] - }, undefined, true, undefined, this); - $2[4] = t1; - $2[5] = t22; - $2[6] = t32; - } else { - t32 = $2[6]; - } - return t32; -} -function UserMessageOption(t0) { - const $2 = import_compiler_runtime286.c(31); - const { - userMessage, - color: color3, - dimColor, - isCurrent, - paddingRight - } = t0; - const { - columns - } = useTerminalSize(); - if (isCurrent) { - let t12; - if ($2[0] !== color3 || $2[1] !== dimColor) { - t12 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - width: "100%", - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - italic: true, - color: color3, - dimColor, - children: "(current)" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = color3; - $2[1] = dimColor; - $2[2] = t12; - } else { - t12 = $2[2]; - } - return t12; - } - const content = userMessage.message.content; - const lastBlock = typeof content === "string" ? null : content[content.length - 1]; - let T0; - let T1; - let t1; - let t22; - let t32; - let t4; - let t5; - let t6; - if ($2[3] !== color3 || $2[4] !== columns || $2[5] !== content || $2[6] !== dimColor || $2[7] !== lastBlock || $2[8] !== paddingRight) { - t6 = Symbol.for("react.early_return_sentinel"); - bb0: { - const rawMessageText = typeof content === "string" ? content.trim() : lastBlock && isTextBlock2(lastBlock) ? lastBlock.text.trim() : "(no prompt)"; - const messageText = stripDisplayTags(rawMessageText); - if (isEmptyMessageText(messageText)) { - let t72; - if ($2[17] !== color3 || $2[18] !== dimColor) { - t72 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "row", - width: "100%", - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - italic: true, - color: color3, - dimColor, - children: "((empty message))" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[17] = color3; - $2[18] = dimColor; - $2[19] = t72; - } else { - t72 = $2[19]; - } - t6 = t72; - break bb0; - } - if (messageText.includes("")) { - const input = extractTag(messageText, "bash-input"); - if (input) { - let t72; - if ($2[20] === Symbol.for("react.memo_cache_sentinel")) { - t72 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: "bashBorder", - children: "!" - }, undefined, false, undefined, this); - $2[20] = t72; - } else { - t72 = $2[20]; - } - t6 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "row", - width: "100%", - children: [ - t72, - /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: color3, - dimColor, - children: [ - " ", - input - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - break bb0; - } - } - if (messageText.includes(`<${COMMAND_MESSAGE_TAG}>`)) { - const commandMessage = extractTag(messageText, COMMAND_MESSAGE_TAG); - const args = extractTag(messageText, "command-args"); - const isSkillFormat = extractTag(messageText, "skill-format") === "true"; - if (commandMessage) { - if (isSkillFormat) { - t6 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "row", - width: "100%", - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: color3, - dimColor, - children: [ - "Skill(", - commandMessage, - ")" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - break bb0; - } else { - t6 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedBox_default, { - flexDirection: "row", - width: "100%", - children: /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(ThemedText, { - color: color3, - dimColor, - children: [ - "/", - commandMessage, - " ", - args - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - break bb0; - } - } - } - T1 = ThemedBox_default; - t4 = "row"; - t5 = "100%"; - T0 = ThemedText; - t1 = color3; - t22 = dimColor; - t32 = paddingRight ? truncate(messageText, columns - paddingRight, true) : messageText.slice(0, 500).split(` -`).slice(0, 4).join(` -`); - } - $2[3] = color3; - $2[4] = columns; - $2[5] = content; - $2[6] = dimColor; - $2[7] = lastBlock; - $2[8] = paddingRight; - $2[9] = T0; - $2[10] = T1; - $2[11] = t1; - $2[12] = t22; - $2[13] = t32; - $2[14] = t4; - $2[15] = t5; - $2[16] = t6; - } else { - T0 = $2[9]; - T1 = $2[10]; - t1 = $2[11]; - t22 = $2[12]; - t32 = $2[13]; - t4 = $2[14]; - t5 = $2[15]; - t6 = $2[16]; - } - if (t6 !== Symbol.for("react.early_return_sentinel")) { - return t6; - } - let t7; - if ($2[21] !== T0 || $2[22] !== t1 || $2[23] !== t22 || $2[24] !== t32) { - t7 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(T0, { - color: t1, - dimColor: t22, - children: t32 - }, undefined, false, undefined, this); - $2[21] = T0; - $2[22] = t1; - $2[23] = t22; - $2[24] = t32; - $2[25] = t7; - } else { - t7 = $2[25]; - } - let t8; - if ($2[26] !== T1 || $2[27] !== t4 || $2[28] !== t5 || $2[29] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime369.jsxDEV(T1, { - flexDirection: t4, - width: t5, - children: t7 - }, undefined, false, undefined, this); - $2[26] = T1; - $2[27] = t4; - $2[28] = t5; - $2[29] = t7; - $2[30] = t8; - } else { - t8 = $2[30]; - } - return t8; -} -function computeDiffStatsBetweenMessages(messages, fromMessageId, toMessageId) { - const startIndex = messages.findIndex((msg) => msg.uuid === fromMessageId); - if (startIndex === -1) { - return; - } - let endIndex = toMessageId ? messages.findIndex((msg) => msg.uuid === toMessageId) : messages.length; - if (endIndex === -1) { - endIndex = messages.length; - } - const filesChanged = []; - let insertions = 0; - let deletions = 0; - for (let i6 = startIndex + 1;i6 < endIndex; i6++) { - const msg = messages[i6]; - if (!msg || !isToolUseResultMessage(msg)) { - continue; - } - const result = msg.toolUseResult; - if (!result || !result.filePath || !result.structuredPatch) { - continue; - } - if (!filesChanged.includes(result.filePath)) { - filesChanged.push(result.filePath); - } - try { - if ("type" in result && result.type === "create") { - insertions += result.content.split(/\r?\n/).length; - } else { - for (const hunk of result.structuredPatch) { - const additions = count2(hunk.lines, (line) => line.startsWith("+")); - const removals = count2(hunk.lines, (line) => line.startsWith("-")); - insertions += additions; - deletions += removals; - } - } - } catch { - continue; - } - } - return { - filesChanged, - insertions, - deletions - }; -} -function selectableUserMessagesFilter(message) { - if (message.type !== "user") { - return false; - } - if (Array.isArray(message.message.content) && message.message.content[0]?.type === "tool_result") { - return false; - } - if (isSyntheticMessage(message)) { - return false; - } - if (message.isMeta) { - return false; - } - if (message.isCompactSummary || message.isVisibleInTranscriptOnly) { - return false; - } - const content = message.message.content; - const lastBlock = typeof content === "string" ? null : content[content.length - 1]; - const messageText = typeof content === "string" ? content.trim() : lastBlock && isTextBlock2(lastBlock) ? lastBlock.text.trim() : ""; - if (messageText.indexOf(`<${LOCAL_COMMAND_STDOUT_TAG}>`) !== -1 || messageText.indexOf(`<${LOCAL_COMMAND_STDERR_TAG}>`) !== -1 || messageText.indexOf(`<${BASH_STDOUT_TAG}>`) !== -1 || messageText.indexOf(`<${BASH_STDERR_TAG}>`) !== -1 || messageText.indexOf(`<${TASK_NOTIFICATION_TAG}>`) !== -1 || messageText.indexOf(`<${TICK_TAG}>`) !== -1 || messageText.indexOf(`<${TEAMMATE_MESSAGE_TAG}`) !== -1) { - return false; - } - return true; -} -function messagesAfterAreOnlySynthetic(messages, fromIndex) { - for (let i6 = fromIndex + 1;i6 < messages.length; i6++) { - const msg = messages[i6]; - if (!msg) - continue; - if (isSyntheticMessage(msg)) - continue; - if (isToolUseResultMessage(msg)) - continue; - if (msg.type === "progress") - continue; - if (msg.type === "system") - continue; - if (msg.type === "attachment") - continue; - if (msg.type === "user" && msg.isMeta) - continue; - if (msg.type === "assistant") { - const content = msg.message.content; - if (Array.isArray(content)) { - const hasMeaningfulContent = content.some((block2) => block2.type === "text" && block2.text.trim() || block2.type === "tool_use"); - if (hasMeaningfulContent) - return false; - } - continue; - } - if (msg.type === "user") { - return false; - } - } - return true; -} -var import_compiler_runtime286, import_react199, jsx_dev_runtime369, MAX_VISIBLE_MESSAGES = 7; -var init_MessageSelector = __esm(() => { - init_figures(); - init_analytics(); - init_AppState(); - init_fileHistory(); - init_log2(); - init_useExitOnCtrlCDWithKeybindings(); - init_ink2(); - init_useKeybinding(); - init_displayTags(); - init_messages9(); - init_select(); - init_Spinner2(); - init_useTerminalSize(); - init_xml(); - init_format(); - init_Divider(); - import_compiler_runtime286 = __toESM(require_compiler_runtime(), 1); - import_react199 = __toESM(require_react(), 1); - jsx_dev_runtime369 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useIdeLogging.ts -function useIdeLogging(mcpClients) { - import_react200.useEffect(() => { - if (!mcpClients.length) { - return; - } - const ideClient = getConnectedIdeClient(mcpClients); - if (ideClient) { - ideClient.client.setNotificationHandler(LogEventSchema(), (notification) => { - const { eventName, eventData } = notification.params; - logEvent(`tengu_ide_${eventName}`, eventData); - }); - } - }, [mcpClients]); -} -var import_react200, LogEventSchema; -var init_useIdeLogging = __esm(() => { - init_analytics(); - init_v4(); - init_ide(); - import_react200 = __toESM(require_react(), 1); - LogEventSchema = lazySchema(() => exports_external.object({ - method: exports_external.literal("log_event"), - params: exports_external.object({ - eventName: exports_external.string(), - eventData: exports_external.object({}).passthrough() - }) - })); -}); - -// src/hooks/useNotifyAfterTimeout.ts -function getTimeSinceLastInteraction() { - return Date.now() - getLastInteractionTime(); -} -function hasRecentInteraction(threshold) { - return getTimeSinceLastInteraction() < threshold; -} -function shouldNotify(threshold) { - return !hasRecentInteraction(threshold); -} -function useNotifyAfterTimeout(message, notificationType) { - const terminal = useTerminalNotification(); - import_react201.useEffect(() => { - updateLastInteractionTime(true); - }, []); - import_react201.useEffect(() => { - let hasNotified = false; - const timer = setInterval(() => { - if (shouldNotify(DEFAULT_INTERACTION_THRESHOLD_MS) && !hasNotified) { - hasNotified = true; - clearInterval(timer); - sendNotification({ message, notificationType }, terminal); - } - }, DEFAULT_INTERACTION_THRESHOLD_MS); - return () => clearInterval(timer); - }, [message, notificationType, terminal]); -} -var import_react201, DEFAULT_INTERACTION_THRESHOLD_MS = 6000; -var init_useNotifyAfterTimeout = __esm(() => { - init_state(); - init_useTerminalNotification(); - init_notifier(); - import_react201 = __toESM(require_react(), 1); -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/PreviewBox.tsx -function PreviewBox(props) { - const $2 = import_compiler_runtime287.c(4); - const settings = useSettings(); - if (settings.syntaxHighlightingDisabled) { - let t02; - if ($2[0] !== props) { - t02 = /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(PreviewBoxBody, { - ...props, - highlight: null - }, undefined, false, undefined, this); - $2[0] = props; - $2[1] = t02; - } else { - t02 = $2[1]; - } - return t02; - } - let t0; - if ($2[2] !== props) { - t0 = /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(import_react202.Suspense, { - fallback: /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(PreviewBoxBody, { - ...props, - highlight: null - }, undefined, false, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(PreviewBoxWithHighlight, { - ...props - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = props; - $2[3] = t0; - } else { - t0 = $2[3]; - } - return t0; -} -function PreviewBoxWithHighlight(props) { - const $2 = import_compiler_runtime287.c(4); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = getCliHighlightPromise(); - $2[0] = t0; - } else { - t0 = $2[0]; - } - const highlight = import_react202.use(t0); - let t1; - if ($2[1] !== highlight || $2[2] !== props) { - t1 = /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(PreviewBoxBody, { - ...props, - highlight - }, undefined, false, undefined, this); - $2[1] = highlight; - $2[2] = props; - $2[3] = t1; - } else { - t1 = $2[3]; - } - return t1; -} -function PreviewBoxBody(t0) { - const $2 = import_compiler_runtime287.c(34); - const { - content, - maxLines, - minHeight, - minWidth: t1, - maxWidth, - highlight - } = t0; - const minWidth = t1 === undefined ? 40 : t1; - const { - columns: terminalWidth - } = useTerminalSize(); - const [theme2] = useTheme(); - const effectiveMaxWidth = maxWidth ?? terminalWidth - 4; - const effectiveMaxLines = maxLines ?? 20; - let t22; - if ($2[0] !== content || $2[1] !== highlight || $2[2] !== theme2) { - t22 = applyMarkdown(content, theme2, highlight); - $2[0] = content; - $2[1] = highlight; - $2[2] = theme2; - $2[3] = t22; - } else { - t22 = $2[3]; - } - const rendered = t22; - let T0; - let bottomBorder; - let t32; - let t4; - let t5; - let truncationBar; - if ($2[4] !== effectiveMaxLines || $2[5] !== effectiveMaxWidth || $2[6] !== minHeight || $2[7] !== minWidth || $2[8] !== rendered) { - const contentLines = rendered.split(` -`); - const isTruncated = contentLines.length > effectiveMaxLines; - const truncatedLines = isTruncated ? contentLines.slice(0, effectiveMaxLines) : contentLines; - const effectiveMinHeight = Math.min(minHeight ?? 0, effectiveMaxLines); - const paddingNeeded = Math.max(0, effectiveMinHeight - truncatedLines.length - (isTruncated ? 1 : 0)); - const lines2 = paddingNeeded > 0 ? [...truncatedLines, ...Array(paddingNeeded).fill("")] : truncatedLines; - const contentWidth = Math.max(minWidth, ...lines2.map(_temp168)); - const boxWidth = Math.min(contentWidth + 4, effectiveMaxWidth); - const innerWidth = boxWidth - 4; - let t62; - if ($2[15] !== boxWidth) { - t62 = BOX_CHARS.horizontal.repeat(boxWidth - 2); - $2[15] = boxWidth; - $2[16] = t62; - } else { - t62 = $2[16]; - } - const topBorder = `${BOX_CHARS.topLeft}${t62}${BOX_CHARS.topRight}`; - let t72; - if ($2[17] !== boxWidth) { - t72 = BOX_CHARS.horizontal.repeat(boxWidth - 2); - $2[17] = boxWidth; - $2[18] = t72; - } else { - t72 = $2[18]; - } - bottomBorder = `${BOX_CHARS.bottomLeft}${t72}${BOX_CHARS.bottomRight}`; - truncationBar = isTruncated ? (() => { - const hiddenCount = contentLines.length - effectiveMaxLines; - const label = `${BOX_CHARS.horizontal.repeat(3)} \u2702 ${BOX_CHARS.horizontal.repeat(3)} ${hiddenCount} lines hidden `; - const labelWidth = stringWidth(label); - const fillWidth = Math.max(0, boxWidth - 2 - labelWidth); - return `${BOX_CHARS.teeLeft}${label}${BOX_CHARS.horizontal.repeat(fillWidth)}${BOX_CHARS.teeRight}`; - })() : null; - T0 = ThemedBox_default; - t32 = "column"; - if ($2[19] !== topBorder) { - t4 = /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(ThemedText, { - dimColor: true, - children: topBorder - }, undefined, false, undefined, this); - $2[19] = topBorder; - $2[20] = t4; - } else { - t4 = $2[20]; - } - let t82; - if ($2[21] !== innerWidth) { - t82 = (line_0, index2) => { - const lineWidth2 = stringWidth(line_0); - const displayLine = lineWidth2 > innerWidth ? sliceAnsi(line_0, 0, innerWidth) : line_0; - const padding = " ".repeat(Math.max(0, innerWidth - stringWidth(displayLine))); - return /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(ThemedText, { - dimColor: true, - children: [ - BOX_CHARS.vertical, - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(Ansi, { - children: displayLine - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(ThemedText, { - dimColor: true, - children: [ - padding, - " ", - BOX_CHARS.vertical - ] - }, undefined, true, undefined, this) - ] - }, index2, true, undefined, this); - }; - $2[21] = innerWidth; - $2[22] = t82; - } else { - t82 = $2[22]; - } - t5 = lines2.map(t82); - $2[4] = effectiveMaxLines; - $2[5] = effectiveMaxWidth; - $2[6] = minHeight; - $2[7] = minWidth; - $2[8] = rendered; - $2[9] = T0; - $2[10] = bottomBorder; - $2[11] = t32; - $2[12] = t4; - $2[13] = t5; - $2[14] = truncationBar; - } else { - T0 = $2[9]; - bottomBorder = $2[10]; - t32 = $2[11]; - t4 = $2[12]; - t5 = $2[13]; - truncationBar = $2[14]; - } - let t6; - if ($2[23] !== truncationBar) { - t6 = truncationBar && /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(ThemedText, { - color: "warning", - children: truncationBar - }, undefined, false, undefined, this); - $2[23] = truncationBar; - $2[24] = t6; - } else { - t6 = $2[24]; - } - let t7; - if ($2[25] !== bottomBorder) { - t7 = /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(ThemedText, { - dimColor: true, - children: bottomBorder - }, undefined, false, undefined, this); - $2[25] = bottomBorder; - $2[26] = t7; - } else { - t7 = $2[26]; - } - let t8; - if ($2[27] !== T0 || $2[28] !== t32 || $2[29] !== t4 || $2[30] !== t5 || $2[31] !== t6 || $2[32] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime370.jsxDEV(T0, { - flexDirection: t32, - children: [ - t4, - t5, - t6, - t7 - ] - }, undefined, true, undefined, this); - $2[27] = T0; - $2[28] = t32; - $2[29] = t4; - $2[30] = t5; - $2[31] = t6; - $2[32] = t7; - $2[33] = t8; - } else { - t8 = $2[33]; - } - return t8; -} -function _temp168(line) { - return stringWidth(line); -} -var import_compiler_runtime287, import_react202, jsx_dev_runtime370, BOX_CHARS; -var init_PreviewBox = __esm(() => { - init_useSettings(); - init_useTerminalSize(); - init_stringWidth(); - init_ink2(); - init_cliHighlight(); - init_markdown(); - init_sliceAnsi(); - import_compiler_runtime287 = __toESM(require_compiler_runtime(), 1); - import_react202 = __toESM(require_react(), 1); - jsx_dev_runtime370 = __toESM(require_jsx_dev_runtime(), 1); - BOX_CHARS = { - topLeft: "\u250C", - topRight: "\u2510", - bottomLeft: "\u2514", - bottomRight: "\u2518", - horizontal: "\u2500", - vertical: "\u2502", - teeLeft: "\u251C", - teeRight: "\u2524" - }; -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/QuestionNavigationBar.tsx -function QuestionNavigationBar(t0) { - const $2 = import_compiler_runtime288.c(39); - const { - questions, - currentQuestionIndex, - answers, - hideSubmitTab: t1 - } = t0; - const hideSubmitTab = t1 === undefined ? false : t1; - const { - columns - } = useTerminalSize(); - let t22; - if ($2[0] !== columns || $2[1] !== currentQuestionIndex || $2[2] !== hideSubmitTab || $2[3] !== questions) { - bb0: { - const submitText = hideSubmitTab ? "" : ` ${figures_default.tick} Submit `; - const fixedWidth = stringWidth("\u2190 ") + stringWidth(" \u2192") + stringWidth(submitText); - const availableForTabs = columns - fixedWidth; - if (availableForTabs <= 0) { - let t34; - if ($2[5] !== currentQuestionIndex || $2[6] !== questions) { - let t42; - if ($2[8] !== currentQuestionIndex) { - t42 = (q4, index2) => { - const header = q4?.header || `Q${index2 + 1}`; - return index2 === currentQuestionIndex ? header.slice(0, 3) : ""; - }; - $2[8] = currentQuestionIndex; - $2[9] = t42; - } else { - t42 = $2[9]; - } - t34 = questions.map(t42); - $2[5] = currentQuestionIndex; - $2[6] = questions; - $2[7] = t34; - } else { - t34 = $2[7]; - } - t22 = t34; - break bb0; - } - const tabHeaders = questions.map(_temp169); - const idealWidths = tabHeaders.map(_temp273); - const totalIdealWidth = idealWidths.reduce(_temp347, 0); - if (totalIdealWidth <= availableForTabs) { - t22 = tabHeaders; - break bb0; - } - const currentHeader = tabHeaders[currentQuestionIndex] || ""; - const currentIdealWidth = 4 + stringWidth(currentHeader); - const currentTabWidth = Math.min(currentIdealWidth, availableForTabs / 2); - const remainingWidth = availableForTabs - currentTabWidth; - const otherTabCount = questions.length - 1; - const widthPerOtherTab = Math.max(6, Math.floor(remainingWidth / Math.max(otherTabCount, 1))); - let t33; - if ($2[10] !== currentQuestionIndex || $2[11] !== currentTabWidth || $2[12] !== widthPerOtherTab) { - t33 = (header_1, index_1) => { - if (index_1 === currentQuestionIndex) { - const maxTextWidth = currentTabWidth - 2 - 2; - return truncateToWidth(header_1, maxTextWidth); - } else { - const maxTextWidth_0 = widthPerOtherTab - 2 - 2; - return truncateToWidth(header_1, maxTextWidth_0); - } - }; - $2[10] = currentQuestionIndex; - $2[11] = currentTabWidth; - $2[12] = widthPerOtherTab; - $2[13] = t33; - } else { - t33 = $2[13]; - } - t22 = tabHeaders.map(t33); - } - $2[0] = columns; - $2[1] = currentQuestionIndex; - $2[2] = hideSubmitTab; - $2[3] = questions; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const tabDisplayTexts = t22; - const hideArrows = questions.length === 1 && hideSubmitTab; - let t32; - if ($2[14] !== currentQuestionIndex || $2[15] !== hideArrows) { - t32 = !hideArrows && /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedText, { - color: currentQuestionIndex === 0 ? "inactive" : undefined, - children: [ - "\u2190", - " " - ] - }, undefined, true, undefined, this); - $2[14] = currentQuestionIndex; - $2[15] = hideArrows; - $2[16] = t32; - } else { - t32 = $2[16]; - } - let t4; - if ($2[17] !== answers || $2[18] !== currentQuestionIndex || $2[19] !== questions || $2[20] !== tabDisplayTexts) { - let t52; - if ($2[22] !== answers || $2[23] !== currentQuestionIndex || $2[24] !== tabDisplayTexts) { - t52 = (q_1, index_2) => { - const isSelected = index_2 === currentQuestionIndex; - const isAnswered = q_1?.question && !!answers[q_1.question]; - const checkbox = isAnswered ? figures_default.checkboxOn : figures_default.checkboxOff; - const displayText = tabDisplayTexts[index_2] || q_1?.header || `Q${index_2 + 1}`; - return /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedBox_default, { - children: isSelected ? /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedText, { - backgroundColor: "permission", - color: "inverseText", - children: [ - " ", - checkbox, - " ", - displayText, - " " - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedText, { - children: [ - " ", - checkbox, - " ", - displayText, - " " - ] - }, undefined, true, undefined, this) - }, q_1?.question || `question-${index_2}`, false, undefined, this); - }; - $2[22] = answers; - $2[23] = currentQuestionIndex; - $2[24] = tabDisplayTexts; - $2[25] = t52; - } else { - t52 = $2[25]; - } - t4 = questions.map(t52); - $2[17] = answers; - $2[18] = currentQuestionIndex; - $2[19] = questions; - $2[20] = tabDisplayTexts; - $2[21] = t4; - } else { - t4 = $2[21]; - } - let t5; - if ($2[26] !== currentQuestionIndex || $2[27] !== hideSubmitTab || $2[28] !== questions.length) { - t5 = !hideSubmitTab && /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedBox_default, { - children: currentQuestionIndex === questions.length ? /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedText, { - backgroundColor: "permission", - color: "inverseText", - children: [ - " ", - figures_default.tick, - " Submit", - " " - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedText, { - children: [ - " ", - figures_default.tick, - " Submit " - ] - }, undefined, true, undefined, this) - }, "submit", false, undefined, this); - $2[26] = currentQuestionIndex; - $2[27] = hideSubmitTab; - $2[28] = questions.length; - $2[29] = t5; - } else { - t5 = $2[29]; - } - let t6; - if ($2[30] !== currentQuestionIndex || $2[31] !== hideArrows || $2[32] !== questions.length) { - t6 = !hideArrows && /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedText, { - color: currentQuestionIndex === questions.length ? "inactive" : undefined, - children: [ - " ", - "\u2192" - ] - }, undefined, true, undefined, this); - $2[30] = currentQuestionIndex; - $2[31] = hideArrows; - $2[32] = questions.length; - $2[33] = t6; - } else { - t6 = $2[33]; - } - let t7; - if ($2[34] !== t32 || $2[35] !== t4 || $2[36] !== t5 || $2[37] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime371.jsxDEV(ThemedBox_default, { - flexDirection: "row", - marginBottom: 1, - children: [ - t32, - t4, - t5, - t6 - ] - }, undefined, true, undefined, this); - $2[34] = t32; - $2[35] = t4; - $2[36] = t5; - $2[37] = t6; - $2[38] = t7; - } else { - t7 = $2[38]; - } - return t7; -} -function _temp347(sum, w2) { - return sum + w2; -} -function _temp273(header_0) { - return 4 + stringWidth(header_0); -} -function _temp169(q_0, index_0) { - return q_0?.header || `Q${index_0 + 1}`; -} -var import_compiler_runtime288, jsx_dev_runtime371; -var init_QuestionNavigationBar = __esm(() => { - init_figures(); - init_useTerminalSize(); - init_stringWidth(); - init_ink2(); - init_format(); - import_compiler_runtime288 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime371 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.tsx -function PreviewQuestionView({ - question, - questions, - currentQuestionIndex, - answers, - questionStates, - hideSubmitTab = false, - minContentHeight, - minContentWidth, - onUpdateQuestionState, - onAnswer, - onTextInputFocus, - onCancel, - onTabPrev, - onTabNext, - onRespondToClaude, - onFinishPlanInterview -}) { - const isInPlanMode = useAppState((s4) => s4.toolPermissionContext.mode) === "plan"; - const [isFooterFocused, setIsFooterFocused] = import_react203.useState(false); - const [footerIndex, setFooterIndex] = import_react203.useState(0); - const [isInNotesInput, setIsInNotesInput] = import_react203.useState(false); - const [cursorOffset, setCursorOffset] = import_react203.useState(0); - const editor = getExternalEditor(); - const editorName = editor ? toIDEDisplayName(editor) : null; - const questionText = question.question; - const questionState = questionStates[questionText]; - const allOptions = question.options; - const [focusedIndex, setFocusedIndex] = import_react203.useState(0); - const prevQuestionText = import_react203.useRef(questionText); - if (prevQuestionText.current !== questionText) { - prevQuestionText.current = questionText; - const selected = questionState?.selectedValue; - const idx = selected ? allOptions.findIndex((opt) => opt.label === selected) : -1; - setFocusedIndex(idx >= 0 ? idx : 0); - } - const focusedOption = allOptions[focusedIndex]; - const selectedValue = questionState?.selectedValue; - const notesValue = questionState?.textInputValue || ""; - const handleSelectOption = import_react203.useCallback((index2) => { - const option = allOptions[index2]; - if (!option) - return; - setFocusedIndex(index2); - onUpdateQuestionState(questionText, { - selectedValue: option.label - }, false); - onAnswer(questionText, option.label); - }, [allOptions, questionText, onUpdateQuestionState, onAnswer]); - const handleNavigate = import_react203.useCallback((direction) => { - if (isInNotesInput) - return; - let newIndex; - if (typeof direction === "number") { - newIndex = direction; - } else if (direction === "up") { - newIndex = focusedIndex > 0 ? focusedIndex - 1 : focusedIndex; - } else { - newIndex = focusedIndex < allOptions.length - 1 ? focusedIndex + 1 : focusedIndex; - } - if (newIndex >= 0 && newIndex < allOptions.length) { - setFocusedIndex(newIndex); - } - }, [focusedIndex, allOptions.length, isInNotesInput]); - useKeybinding("chat:externalEditor", async () => { - const currentValue = questionState?.textInputValue || ""; - const result = await editPromptInEditor(currentValue); - if (result.content !== null && result.content !== currentValue) { - onUpdateQuestionState(questionText, { - textInputValue: result.content - }, false); - } - }, { - context: "Chat", - isActive: isInNotesInput && !!editor - }); - useKeybindings({ - "tabs:previous": () => onTabPrev?.(), - "tabs:next": () => onTabNext?.() - }, { - context: "Tabs", - isActive: !isInNotesInput && !isFooterFocused - }); - const handleNotesExit = import_react203.useCallback(() => { - setIsInNotesInput(false); - onTextInputFocus(false); - if (selectedValue) { - onAnswer(questionText, selectedValue); - } - }, [selectedValue, questionText, onAnswer, onTextInputFocus]); - const handleDownFromPreview = import_react203.useCallback(() => { - setIsFooterFocused(true); - }, []); - const handleUpFromFooter = import_react203.useCallback(() => { - setIsFooterFocused(false); - }, []); - const handleKeyDown = import_react203.useCallback((e4) => { - if (isFooterFocused) { - if (e4.key === "up" || e4.ctrl && e4.key === "p") { - e4.preventDefault(); - if (footerIndex === 0) { - handleUpFromFooter(); - } else { - setFooterIndex(0); - } - return; - } - if (e4.key === "down" || e4.ctrl && e4.key === "n") { - e4.preventDefault(); - if (isInPlanMode && footerIndex === 0) { - setFooterIndex(1); - } - return; - } - if (e4.key === "return") { - e4.preventDefault(); - if (footerIndex === 0) { - onRespondToClaude(); - } else { - onFinishPlanInterview(); - } - return; - } - if (e4.key === "escape") { - e4.preventDefault(); - onCancel(); - } - return; - } - if (isInNotesInput) { - if (e4.key === "escape") { - e4.preventDefault(); - handleNotesExit(); - } - return; - } - if (e4.key === "up" || e4.ctrl && e4.key === "p") { - e4.preventDefault(); - if (focusedIndex > 0) { - handleNavigate("up"); - } - } else if (e4.key === "down" || e4.ctrl && e4.key === "n") { - e4.preventDefault(); - if (focusedIndex === allOptions.length - 1) { - handleDownFromPreview(); - } else { - handleNavigate("down"); - } - } else if (e4.key === "return") { - e4.preventDefault(); - handleSelectOption(focusedIndex); - } else if (e4.key === "n" && !e4.ctrl && !e4.meta) { - e4.preventDefault(); - setIsInNotesInput(true); - onTextInputFocus(true); - } else if (e4.key === "escape") { - e4.preventDefault(); - onCancel(); - } else if (e4.key.length === 1 && e4.key >= "1" && e4.key <= "9") { - e4.preventDefault(); - const idx_0 = parseInt(e4.key, 10) - 1; - if (idx_0 < allOptions.length) { - handleNavigate(idx_0); - } - } - }, [isFooterFocused, footerIndex, isInPlanMode, isInNotesInput, focusedIndex, allOptions.length, handleUpFromFooter, handleDownFromPreview, handleNavigate, handleSelectOption, handleNotesExit, onRespondToClaude, onFinishPlanInterview, onCancel, onTextInputFocus]); - const previewContent = focusedOption?.preview || null; - const LEFT_PANEL_WIDTH = 30; - const GAP = 4; - const { - columns - } = useTerminalSize(); - const previewMaxWidth = columns - LEFT_PANEL_WIDTH - GAP; - const PREVIEW_OVERHEAD = 11; - const previewMaxLines = import_react203.useMemo(() => { - return minContentHeight ? Math.max(1, minContentHeight - PREVIEW_OVERHEAD) : undefined; - }, [minContentHeight]); - return /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - tabIndex: 0, - autoFocus: true, - onKeyDown: handleKeyDown, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(Divider, { - color: "inactive" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingTop: 0, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(QuestionNavigationBar, { - questions, - currentQuestionIndex, - answers, - hideSubmitTab - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(PermissionRequestTitle, { - title: question.question, - color: "text" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "column", - minHeight: minContentHeight, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "row", - gap: 4, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 30, - children: allOptions.map((option_0, index_0) => { - const isFocused = focusedIndex === index_0; - const isSelected = selectedValue === option_0.label; - return /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - isFocused ? /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: "suggestion", - children: figures_default.pointer - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - index_0 + 1, - "." - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: isSelected ? "success" : isFocused ? "suggestion" : undefined, - bold: isFocused, - children: [ - " ", - option_0.label - ] - }, undefined, true, undefined, this), - isSelected && /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: "success", - children: [ - " ", - figures_default.tick - ] - }, undefined, true, undefined, this) - ] - }, option_0.label, true, undefined, this); - }) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "column", - flexGrow: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(PreviewBox, { - content: previewContent || "No preview available", - maxLines: previewMaxLines, - minWidth: minContentWidth, - maxWidth: previewMaxWidth - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "row", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: "suggestion", - children: "Notes:" - }, undefined, false, undefined, this), - isInNotesInput ? /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(TextInput, { - value: notesValue, - placeholder: "Add notes on this design\u2026", - onChange: (value) => { - onUpdateQuestionState(questionText, { - textInputValue: value - }, false); - }, - onSubmit: handleNotesExit, - onExit: handleNotesExit, - focus: true, - showCursor: true, - columns: 60, - cursorOffset, - onChangeCursorOffset: setCursorOffset - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: notesValue || "press n to add notes" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(Divider, { - color: "inactive" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - isFooterFocused && footerIndex === 0 ? /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: "suggestion", - children: figures_default.pointer - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: isFooterFocused && footerIndex === 0 ? "suggestion" : undefined, - children: "Chat about this" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - isInPlanMode && /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - isFooterFocused && footerIndex === 1 ? /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: "suggestion", - children: figures_default.pointer - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: isFooterFocused && footerIndex === 1 ? "suggestion" : undefined, - children: "Skip interview and plan immediately" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(ThemedText, { - color: "inactive", - dimColor: true, - children: [ - "Enter to select \xB7 ", - figures_default.arrowUp, - "/", - figures_default.arrowDown, - " to navigate \xB7 n to add notes", - questions.length > 1 && /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(jsx_dev_runtime372.Fragment, { - children: " \xB7 Tab to switch questions" - }, undefined, false, undefined, this), - isInNotesInput && editorName && /* @__PURE__ */ jsx_dev_runtime372.jsxDEV(jsx_dev_runtime372.Fragment, { - children: [ - " \xB7 ctrl+g to edit in ", - editorName - ] - }, undefined, true, undefined, this), - " ", - "\xB7 Esc to cancel" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_react203, jsx_dev_runtime372; -var init_PreviewQuestionView = __esm(() => { - init_figures(); - init_useTerminalSize(); - init_ink2(); - init_useKeybinding(); - init_AppState(); - init_editor(); - init_ide(); - init_promptEditor(); - init_Divider(); - init_TextInput(); - init_PermissionRequestTitle(); - init_PreviewBox(); - init_QuestionNavigationBar(); - import_react203 = __toESM(require_react(), 1); - jsx_dev_runtime372 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/QuestionView.tsx -function QuestionView(t0) { - const $2 = import_compiler_runtime289.c(114); - const { - question, - questions, - currentQuestionIndex, - answers, - questionStates, - hideSubmitTab: t1, - planFilePath, - minContentHeight, - minContentWidth, - onUpdateQuestionState, - onAnswer, - onTextInputFocus, - onCancel, - onSubmit, - onTabPrev, - onTabNext, - onRespondToClaude, - onFinishPlanInterview, - onImagePaste, - pastedContents, - onRemoveImage - } = t0; - const hideSubmitTab = t1 === undefined ? false : t1; - const isInPlanMode = useAppState(_temp170) === "plan"; - const [isFooterFocused, setIsFooterFocused] = import_react204.useState(false); - const [footerIndex, setFooterIndex] = import_react204.useState(0); - const [isOtherFocused, setIsOtherFocused] = import_react204.useState(false); - let t22; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - const editor = getExternalEditor(); - t22 = editor ? toIDEDisplayName(editor) : null; - $2[0] = t22; - } else { - t22 = $2[0]; - } - const editorName = t22; - let t32; - if ($2[1] !== onTextInputFocus) { - t32 = (value) => { - const isOther = value === "__other__"; - setIsOtherFocused(isOther); - onTextInputFocus(isOther); - }; - $2[1] = onTextInputFocus; - $2[2] = t32; - } else { - t32 = $2[2]; - } - const handleFocus = t32; - let t4; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t4 = () => { - setIsFooterFocused(true); - }; - $2[3] = t4; - } else { - t4 = $2[3]; - } - const handleDownFromLastItem = t4; - let t5; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t5 = () => { - setIsFooterFocused(false); - }; - $2[4] = t5; - } else { - t5 = $2[4]; - } - const handleUpFromFooter = t5; - let t6; - if ($2[5] !== footerIndex || $2[6] !== isFooterFocused || $2[7] !== isInPlanMode || $2[8] !== onCancel || $2[9] !== onFinishPlanInterview || $2[10] !== onRespondToClaude) { - t6 = (e4) => { - if (!isFooterFocused) { - return; - } - if (e4.key === "up" || e4.ctrl && e4.key === "p") { - e4.preventDefault(); - if (footerIndex === 0) { - handleUpFromFooter(); - } else { - setFooterIndex(0); - } - return; - } - if (e4.key === "down" || e4.ctrl && e4.key === "n") { - e4.preventDefault(); - if (isInPlanMode && footerIndex === 0) { - setFooterIndex(1); - } - return; - } - if (e4.key === "return") { - e4.preventDefault(); - if (footerIndex === 0) { - onRespondToClaude(); - } else { - onFinishPlanInterview(); - } - return; - } - if (e4.key === "escape") { - e4.preventDefault(); - onCancel(); - } - }; - $2[5] = footerIndex; - $2[6] = isFooterFocused; - $2[7] = isInPlanMode; - $2[8] = onCancel; - $2[9] = onFinishPlanInterview; - $2[10] = onRespondToClaude; - $2[11] = t6; - } else { - t6 = $2[11]; - } - const handleKeyDown = t6; - let handleOpenEditor; - let questionText; - let t7; - if ($2[12] !== onUpdateQuestionState || $2[13] !== question || $2[14] !== questionStates) { - const textOptions = question.options.map(_temp274); - questionText = question.question; - const questionState = questionStates[questionText]; - let t82; - if ($2[18] !== onUpdateQuestionState || $2[19] !== question.multiSelect || $2[20] !== questionText) { - t82 = async (currentValue, setValue2) => { - const result = await editPromptInEditor(currentValue); - if (result.content !== null && result.content !== currentValue) { - setValue2(result.content); - onUpdateQuestionState(questionText, { - textInputValue: result.content - }, question.multiSelect ?? false); - } - }; - $2[18] = onUpdateQuestionState; - $2[19] = question.multiSelect; - $2[20] = questionText; - $2[21] = t82; - } else { - t82 = $2[21]; - } - handleOpenEditor = t82; - const t92 = question.multiSelect ? "Type something" : "Type something."; - const t102 = questionState?.textInputValue ?? ""; - let t112; - if ($2[22] !== onUpdateQuestionState || $2[23] !== question.multiSelect || $2[24] !== questionText) { - t112 = (value_0) => { - onUpdateQuestionState(questionText, { - textInputValue: value_0 - }, question.multiSelect ?? false); - }; - $2[22] = onUpdateQuestionState; - $2[23] = question.multiSelect; - $2[24] = questionText; - $2[25] = t112; - } else { - t112 = $2[25]; - } - let t122; - if ($2[26] !== t102 || $2[27] !== t112 || $2[28] !== t92) { - t122 = { - type: "input", - value: "__other__", - label: "Other", - placeholder: t92, - initialValue: t102, - onChange: t112 - }; - $2[26] = t102; - $2[27] = t112; - $2[28] = t92; - $2[29] = t122; - } else { - t122 = $2[29]; - } - const otherOption = t122; - t7 = [...textOptions, otherOption]; - $2[12] = onUpdateQuestionState; - $2[13] = question; - $2[14] = questionStates; - $2[15] = handleOpenEditor; - $2[16] = questionText; - $2[17] = t7; - } else { - handleOpenEditor = $2[15]; - questionText = $2[16]; - t7 = $2[17]; - } - const options2 = t7; - const hasAnyPreview = !question.multiSelect && question.options.some(_temp348); - if (hasAnyPreview) { - let t82; - if ($2[30] !== answers || $2[31] !== currentQuestionIndex || $2[32] !== hideSubmitTab || $2[33] !== minContentHeight || $2[34] !== minContentWidth || $2[35] !== onAnswer || $2[36] !== onCancel || $2[37] !== onFinishPlanInterview || $2[38] !== onRespondToClaude || $2[39] !== onTabNext || $2[40] !== onTabPrev || $2[41] !== onTextInputFocus || $2[42] !== onUpdateQuestionState || $2[43] !== question || $2[44] !== questionStates || $2[45] !== questions) { - t82 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(PreviewQuestionView, { - question, - questions, - currentQuestionIndex, - answers, - questionStates, - hideSubmitTab, - minContentHeight, - minContentWidth, - onUpdateQuestionState, - onAnswer, - onTextInputFocus, - onCancel, - onTabPrev, - onTabNext, - onRespondToClaude, - onFinishPlanInterview - }, undefined, false, undefined, this); - $2[30] = answers; - $2[31] = currentQuestionIndex; - $2[32] = hideSubmitTab; - $2[33] = minContentHeight; - $2[34] = minContentWidth; - $2[35] = onAnswer; - $2[36] = onCancel; - $2[37] = onFinishPlanInterview; - $2[38] = onRespondToClaude; - $2[39] = onTabNext; - $2[40] = onTabPrev; - $2[41] = onTextInputFocus; - $2[42] = onUpdateQuestionState; - $2[43] = question; - $2[44] = questionStates; - $2[45] = questions; - $2[46] = t82; - } else { - t82 = $2[46]; - } - return t82; - } - let t8; - if ($2[47] !== isInPlanMode || $2[48] !== planFilePath) { - t8 = isInPlanMode && planFilePath && /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 0, - children: [ - /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(Divider, { - color: "inactive" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - color: "inactive", - children: [ - "Planning: ", - /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(FilePathLink, { - filePath: planFilePath - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[47] = isInPlanMode; - $2[48] = planFilePath; - $2[49] = t8; - } else { - t8 = $2[49]; - } - let t9; - if ($2[50] === Symbol.for("react.memo_cache_sentinel")) { - t9 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - marginTop: -1, - children: /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(Divider, { - color: "inactive" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[50] = t9; - } else { - t9 = $2[50]; - } - let t10; - if ($2[51] !== answers || $2[52] !== currentQuestionIndex || $2[53] !== hideSubmitTab || $2[54] !== questions) { - t10 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(QuestionNavigationBar, { - questions, - currentQuestionIndex, - answers, - hideSubmitTab - }, undefined, false, undefined, this); - $2[51] = answers; - $2[52] = currentQuestionIndex; - $2[53] = hideSubmitTab; - $2[54] = questions; - $2[55] = t10; - } else { - t10 = $2[55]; - } - let t11; - if ($2[56] !== question.question) { - t11 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(PermissionRequestTitle, { - title: question.question, - color: "text" - }, undefined, false, undefined, this); - $2[56] = question.question; - $2[57] = t11; - } else { - t11 = $2[57]; - } - let t12; - if ($2[58] !== currentQuestionIndex || $2[59] !== handleFocus || $2[60] !== handleOpenEditor || $2[61] !== isFooterFocused || $2[62] !== onAnswer || $2[63] !== onCancel || $2[64] !== onImagePaste || $2[65] !== onRemoveImage || $2[66] !== onSubmit || $2[67] !== onUpdateQuestionState || $2[68] !== options2 || $2[69] !== pastedContents || $2[70] !== question.multiSelect || $2[71] !== question.question || $2[72] !== questionStates || $2[73] !== questionText || $2[74] !== questions.length) { - t12 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: question.multiSelect ? /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(SelectMulti, { - options: options2, - defaultValue: questionStates[question.question]?.selectedValue, - onChange: (values3) => { - onUpdateQuestionState(questionText, { - selectedValue: values3 - }, true); - const textInput = values3.includes("__other__") ? questionStates[questionText]?.textInputValue : undefined; - const finalValues = values3.filter(_temp435).concat(textInput ? [textInput] : []); - onAnswer(questionText, finalValues, undefined, false); - }, - onFocus: handleFocus, - onCancel, - submitButtonText: currentQuestionIndex === questions.length - 1 ? "Submit" : "Next", - onSubmit, - onDownFromLastItem: handleDownFromLastItem, - isDisabled: isFooterFocused, - onOpenEditor: handleOpenEditor, - onImagePaste, - pastedContents, - onRemoveImage - }, question.question, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(Select, { - options: options2, - defaultValue: questionStates[question.question]?.selectedValue, - onChange: (value_1) => { - onUpdateQuestionState(questionText, { - selectedValue: value_1 - }, false); - const textInput_0 = value_1 === "__other__" ? questionStates[questionText]?.textInputValue : undefined; - onAnswer(questionText, value_1, textInput_0); - }, - onFocus: handleFocus, - onCancel, - onDownFromLastItem: handleDownFromLastItem, - isDisabled: isFooterFocused, - layout: "compact-vertical", - onOpenEditor: handleOpenEditor, - onImagePaste, - pastedContents, - onRemoveImage - }, question.question, false, undefined, this) - }, undefined, false, undefined, this); - $2[58] = currentQuestionIndex; - $2[59] = handleFocus; - $2[60] = handleOpenEditor; - $2[61] = isFooterFocused; - $2[62] = onAnswer; - $2[63] = onCancel; - $2[64] = onImagePaste; - $2[65] = onRemoveImage; - $2[66] = onSubmit; - $2[67] = onUpdateQuestionState; - $2[68] = options2; - $2[69] = pastedContents; - $2[70] = question.multiSelect; - $2[71] = question.question; - $2[72] = questionStates; - $2[73] = questionText; - $2[74] = questions.length; - $2[75] = t12; - } else { - t12 = $2[75]; - } - let t13; - if ($2[76] === Symbol.for("react.memo_cache_sentinel")) { - t13 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(Divider, { - color: "inactive" - }, undefined, false, undefined, this); - $2[76] = t13; - } else { - t13 = $2[76]; - } - let t14; - if ($2[77] !== footerIndex || $2[78] !== isFooterFocused) { - t14 = isFooterFocused && footerIndex === 0 ? /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - color: "suggestion", - children: figures_default.pointer - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - $2[77] = footerIndex; - $2[78] = isFooterFocused; - $2[79] = t14; - } else { - t14 = $2[79]; - } - const t15 = isFooterFocused && footerIndex === 0 ? "suggestion" : undefined; - const t16 = options2.length + 1; - let t17; - if ($2[80] !== t15 || $2[81] !== t16) { - t17 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - color: t15, - children: [ - t16, - ". Chat about this" - ] - }, undefined, true, undefined, this); - $2[80] = t15; - $2[81] = t16; - $2[82] = t17; - } else { - t17 = $2[82]; - } - let t18; - if ($2[83] !== t14 || $2[84] !== t17) { - t18 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - t14, - t17 - ] - }, undefined, true, undefined, this); - $2[83] = t14; - $2[84] = t17; - $2[85] = t18; - } else { - t18 = $2[85]; - } - let t19; - if ($2[86] !== footerIndex || $2[87] !== isFooterFocused || $2[88] !== isInPlanMode || $2[89] !== options2.length) { - t19 = isInPlanMode && /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - isFooterFocused && footerIndex === 1 ? /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - color: "suggestion", - children: figures_default.pointer - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - color: isFooterFocused && footerIndex === 1 ? "suggestion" : undefined, - children: [ - options2.length + 2, - ". Skip interview and plan immediately" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[86] = footerIndex; - $2[87] = isFooterFocused; - $2[88] = isInPlanMode; - $2[89] = options2.length; - $2[90] = t19; - } else { - t19 = $2[90]; - } - let t20; - if ($2[91] !== t18 || $2[92] !== t19) { - t20 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t13, - t18, - t19 - ] - }, undefined, true, undefined, this); - $2[91] = t18; - $2[92] = t19; - $2[93] = t20; - } else { - t20 = $2[93]; - } - let t21; - if ($2[94] !== questions.length) { - t21 = questions.length === 1 ? /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(jsx_dev_runtime373.Fragment, { - children: [ - figures_default.arrowUp, - "/", - figures_default.arrowDown, - " to navigate" - ] - }, undefined, true, undefined, this) : "Tab/Arrow keys to navigate"; - $2[94] = questions.length; - $2[95] = t21; - } else { - t21 = $2[95]; - } - let t222; - if ($2[96] !== isOtherFocused) { - t222 = isOtherFocused && editorName && /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(jsx_dev_runtime373.Fragment, { - children: [ - " \xB7 ctrl+g to edit in ", - editorName - ] - }, undefined, true, undefined, this); - $2[96] = isOtherFocused; - $2[97] = t222; - } else { - t222 = $2[97]; - } - let t23; - if ($2[98] !== t21 || $2[99] !== t222) { - t23 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedText, { - color: "inactive", - dimColor: true, - children: [ - "Enter to select \xB7", - " ", - t21, - t222, - " ", - "\xB7 Esc to cancel" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[98] = t21; - $2[99] = t222; - $2[100] = t23; - } else { - t23 = $2[100]; - } - let t24; - if ($2[101] !== minContentHeight || $2[102] !== t12 || $2[103] !== t20 || $2[104] !== t23) { - t24 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "column", - minHeight: minContentHeight, - children: [ - t12, - t20, - t23 - ] - }, undefined, true, undefined, this); - $2[101] = minContentHeight; - $2[102] = t12; - $2[103] = t20; - $2[104] = t23; - $2[105] = t24; - } else { - t24 = $2[105]; - } - let t25; - if ($2[106] !== t10 || $2[107] !== t11 || $2[108] !== t24) { - t25 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingTop: 0, - children: [ - t10, - t11, - t24 - ] - }, undefined, true, undefined, this); - $2[106] = t10; - $2[107] = t11; - $2[108] = t24; - $2[109] = t25; - } else { - t25 = $2[109]; - } - let t26; - if ($2[110] !== handleKeyDown || $2[111] !== t25 || $2[112] !== t8) { - t26 = /* @__PURE__ */ jsx_dev_runtime373.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 0, - tabIndex: 0, - autoFocus: true, - onKeyDown: handleKeyDown, - children: [ - t8, - t9, - t25 - ] - }, undefined, true, undefined, this); - $2[110] = handleKeyDown; - $2[111] = t25; - $2[112] = t8; - $2[113] = t26; - } else { - t26 = $2[113]; - } - return t26; -} -function _temp435(v6) { - return v6 !== "__other__"; -} -function _temp348(opt_0) { - return opt_0.preview; -} -function _temp274(opt) { - return { - type: "text", - value: opt.label, - label: opt.label, - description: opt.description - }; -} -function _temp170(s4) { - return s4.toolPermissionContext.mode; -} -var import_compiler_runtime289, import_react204, jsx_dev_runtime373; -var init_QuestionView = __esm(() => { - init_figures(); - init_ink2(); - init_AppState(); - init_editor(); - init_ide(); - init_promptEditor(); - init_CustomSelect(); - init_Divider(); - init_FilePathLink(); - init_PermissionRequestTitle(); - init_PreviewQuestionView(); - init_QuestionNavigationBar(); - import_compiler_runtime289 = __toESM(require_compiler_runtime(), 1); - import_react204 = __toESM(require_react(), 1); - jsx_dev_runtime373 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/PermissionRuleExplanation.tsx -function stringsForDecisionReason(reason, toolType) { - if (!reason) { - return null; - } - if (false) {} - switch (reason.type) { - case "rule": - return { - reasonString: `Permission rule ${source_default.bold(permissionRuleValueToString(reason.rule.ruleValue))} requires confirmation for this ${toolType}.`, - configString: reason.rule.source === "policySettings" ? undefined : "/permissions to update rules" - }; - case "hook": { - const hookReasonString = reason.reason ? `: -${reason.reason}` : "."; - const sourceLabel = reason.hookSource ? ` ${source_default.dim(`[${reason.hookSource}]`)}` : ""; - return { - reasonString: `Hook ${source_default.bold(reason.hookName)} requires confirmation for this ${toolType}${hookReasonString}${sourceLabel}`, - configString: "/hooks to update" - }; - } - case "safetyCheck": - case "other": - return { - reasonString: reason.reason, - configString: undefined - }; - case "workingDir": - return { - reasonString: reason.reason, - configString: "/permissions to update rules" - }; - default: - return null; - } -} -function PermissionRuleExplanation(t0) { - const $2 = import_compiler_runtime290.c(11); - const { - permissionResult, - toolType - } = t0; - const permissionMode = useAppState(_temp171); - const t1 = permissionResult?.decisionReason; - let t22; - if ($2[0] !== t1 || $2[1] !== toolType) { - t22 = stringsForDecisionReason(t1, toolType); - $2[0] = t1; - $2[1] = toolType; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const strings = t22; - if (!strings) { - return null; - } - const themeColor = strings.themeColor ?? (permissionResult?.decisionReason?.type === "hook" && permissionMode === "auto" ? "warning" : undefined); - let t32; - if ($2[3] !== strings.reasonString || $2[4] !== themeColor) { - t32 = themeColor ? /* @__PURE__ */ jsx_dev_runtime374.jsxDEV(ThemedText, { - color: themeColor, - children: strings.reasonString - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime374.jsxDEV(ThemedText, { - children: /* @__PURE__ */ jsx_dev_runtime374.jsxDEV(Ansi, { - children: strings.reasonString - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[3] = strings.reasonString; - $2[4] = themeColor; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== strings.configString) { - t4 = strings.configString && /* @__PURE__ */ jsx_dev_runtime374.jsxDEV(ThemedText, { - dimColor: true, - children: strings.configString - }, undefined, false, undefined, this); - $2[6] = strings.configString; - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] !== t32 || $2[9] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime374.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: [ - t32, - t4 - ] - }, undefined, true, undefined, this); - $2[8] = t32; - $2[9] = t4; - $2[10] = t5; - } else { - t5 = $2[10]; - } - return t5; -} -function _temp171(s4) { - return s4.toolPermissionContext.mode; -} -var import_compiler_runtime290, jsx_dev_runtime374; -var init_PermissionRuleExplanation = __esm(() => { - init_source(); - init_ink2(); - init_AppState(); - init_permissionRuleParser(); - init_ThemedText(); - import_compiler_runtime290 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime374 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/SubmitQuestionsView.tsx -function SubmitQuestionsView(t0) { - const $2 = import_compiler_runtime291.c(27); - const { - questions, - currentQuestionIndex, - answers, - allQuestionsAnswered, - permissionResult, - minContentHeight, - onFinalResponse - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(Divider, { - color: "inactive" - }, undefined, false, undefined, this); - $2[0] = t1; - } else { - t1 = $2[0]; - } - let t22; - if ($2[1] !== answers || $2[2] !== currentQuestionIndex || $2[3] !== questions) { - t22 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(QuestionNavigationBar, { - questions, - currentQuestionIndex, - answers - }, undefined, false, undefined, this); - $2[1] = answers; - $2[2] = currentQuestionIndex; - $2[3] = questions; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(PermissionRequestTitle, { - title: "Review your answers", - color: "text" - }, undefined, false, undefined, this); - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== allQuestionsAnswered) { - t4 = !allQuestionsAnswered && /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedText, { - color: "warning", - children: [ - figures_default.warning, - " You have not answered all questions" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[6] = allQuestionsAnswered; - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] !== answers || $2[9] !== questions) { - t5 = Object.keys(answers).length > 0 && /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: questions.filter((q4) => q4?.question && answers[q4.question]).map((q_0) => { - const answer = answers[q_0?.question]; - return /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginLeft: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedText, { - children: [ - figures_default.bullet, - " ", - q_0?.question || "Question" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedText, { - color: "success", - children: [ - figures_default.arrowRight, - " ", - answer - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, q_0?.question || "answer", true, undefined, this); - }) - }, undefined, false, undefined, this); - $2[8] = answers; - $2[9] = questions; - $2[10] = t5; - } else { - t5 = $2[10]; - } - let t6; - if ($2[11] !== permissionResult) { - t6 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(PermissionRuleExplanation, { - permissionResult, - toolType: "tool" - }, undefined, false, undefined, this); - $2[11] = permissionResult; - $2[12] = t6; - } else { - t6 = $2[12]; - } - let t7; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedText, { - color: "inactive", - children: "Ready to submit your answers?" - }, undefined, false, undefined, this); - $2[13] = t7; - } else { - t7 = $2[13]; - } - let t8; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t8 = { - type: "text", - label: "Submit answers", - value: "submit" - }; - $2[14] = t8; - } else { - t8 = $2[14]; - } - let t9; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t9 = [t8, { - type: "text", - label: "Cancel", - value: "cancel" - }]; - $2[15] = t9; - } else { - t9 = $2[15]; - } - let t10; - if ($2[16] !== onFinalResponse) { - t10 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(Select, { - options: t9, - onChange: (value) => onFinalResponse(value), - onCancel: () => onFinalResponse("cancel") - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[16] = onFinalResponse; - $2[17] = t10; - } else { - t10 = $2[17]; - } - let t11; - if ($2[18] !== minContentHeight || $2[19] !== t10 || $2[20] !== t4 || $2[21] !== t5 || $2[22] !== t6) { - t11 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - minHeight: minContentHeight, - children: [ - t4, - t5, - t6, - t7, - t10 - ] - }, undefined, true, undefined, this); - $2[18] = minContentHeight; - $2[19] = t10; - $2[20] = t4; - $2[21] = t5; - $2[22] = t6; - $2[23] = t11; - } else { - t11 = $2[23]; - } - let t12; - if ($2[24] !== t11 || $2[25] !== t22) { - t12 = /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t1, - /* @__PURE__ */ jsx_dev_runtime375.jsxDEV(ThemedBox_default, { - flexDirection: "column", - borderTop: true, - borderColor: "inactive", - paddingTop: 0, - children: [ - t22, - t32, - t11 - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[24] = t11; - $2[25] = t22; - $2[26] = t12; - } else { - t12 = $2[26]; - } - return t12; -} -var import_compiler_runtime291, jsx_dev_runtime375; -var init_SubmitQuestionsView = __esm(() => { - init_figures(); - init_ink2(); - init_CustomSelect(); - init_Divider(); - init_PermissionRequestTitle(); - init_PermissionRuleExplanation(); - init_QuestionNavigationBar(); - import_compiler_runtime291 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime375 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/use-multiple-choice-state.ts -function reducer2(state4, action2) { - switch (action2.type) { - case "next-question": - return { - ...state4, - currentQuestionIndex: state4.currentQuestionIndex + 1, - isInTextInput: false - }; - case "prev-question": - return { - ...state4, - currentQuestionIndex: Math.max(0, state4.currentQuestionIndex - 1), - isInTextInput: false - }; - case "update-question-state": { - const existing = state4.questionStates[action2.questionText]; - const newState = { - selectedValue: action2.updates.selectedValue ?? existing?.selectedValue ?? (action2.isMultiSelect ? [] : undefined), - textInputValue: action2.updates.textInputValue ?? existing?.textInputValue ?? "" - }; - return { - ...state4, - questionStates: { - ...state4.questionStates, - [action2.questionText]: newState - } - }; - } - case "set-answer": { - const newState = { - ...state4, - answers: { - ...state4.answers, - [action2.questionText]: action2.answer - } - }; - if (action2.shouldAdvance) { - return { - ...newState, - currentQuestionIndex: newState.currentQuestionIndex + 1, - isInTextInput: false - }; - } - return newState; - } - case "set-text-input-mode": - return { - ...state4, - isInTextInput: action2.isInInput - }; - } -} -function useMultipleChoiceState() { - const [state4, dispatch] = import_react205.useReducer(reducer2, INITIAL_STATE3); - const nextQuestion = import_react205.useCallback(() => { - dispatch({ type: "next-question" }); - }, []); - const prevQuestion = import_react205.useCallback(() => { - dispatch({ type: "prev-question" }); - }, []); - const updateQuestionState = import_react205.useCallback((questionText, updates, isMultiSelect) => { - dispatch({ - type: "update-question-state", - questionText, - updates, - isMultiSelect - }); - }, []); - const setAnswer = import_react205.useCallback((questionText, answer, shouldAdvance = true) => { - dispatch({ - type: "set-answer", - questionText, - answer, - shouldAdvance - }); - }, []); - const setTextInputMode = import_react205.useCallback((isInInput) => { - dispatch({ type: "set-text-input-mode", isInInput }); - }, []); - return { - currentQuestionIndex: state4.currentQuestionIndex, - answers: state4.answers, - questionStates: state4.questionStates, - isInTextInput: state4.isInTextInput, - nextQuestion, - prevQuestion, - updateQuestionState, - setAnswer, - setTextInputMode - }; -} -var import_react205, INITIAL_STATE3; -var init_use_multiple_choice_state = __esm(() => { - import_react205 = __toESM(require_react(), 1); - INITIAL_STATE3 = { - currentQuestionIndex: 0, - answers: {}, - questionStates: {}, - isInTextInput: false - }; -}); - -// src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.tsx -function AskUserQuestionPermissionRequest(props) { - const $2 = import_compiler_runtime292.c(4); - const settings = useSettings(); - if (settings.syntaxHighlightingDisabled) { - let t02; - if ($2[0] !== props) { - t02 = /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(AskUserQuestionPermissionRequestBody, { - ...props, - highlight: null - }, undefined, false, undefined, this); - $2[0] = props; - $2[1] = t02; - } else { - t02 = $2[1]; - } - return t02; - } - let t0; - if ($2[2] !== props) { - t0 = /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(import_react206.Suspense, { - fallback: /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(AskUserQuestionPermissionRequestBody, { - ...props, - highlight: null - }, undefined, false, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(AskUserQuestionWithHighlight, { - ...props - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = props; - $2[3] = t0; - } else { - t0 = $2[3]; - } - return t0; -} -function AskUserQuestionWithHighlight(props) { - const $2 = import_compiler_runtime292.c(4); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = getCliHighlightPromise(); - $2[0] = t0; - } else { - t0 = $2[0]; - } - const highlight = import_react206.use(t0); - let t1; - if ($2[1] !== highlight || $2[2] !== props) { - t1 = /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(AskUserQuestionPermissionRequestBody, { - ...props, - highlight - }, undefined, false, undefined, this); - $2[1] = highlight; - $2[2] = props; - $2[3] = t1; - } else { - t1 = $2[3]; - } - return t1; -} -function AskUserQuestionPermissionRequestBody(t0) { - const $2 = import_compiler_runtime292.c(115); - const { - toolUseConfirm, - onDone, - onReject, - highlight - } = t0; - let t1; - if ($2[0] !== toolUseConfirm.input) { - t1 = AskUserQuestionTool.inputSchema.safeParse(toolUseConfirm.input); - $2[0] = toolUseConfirm.input; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const result = t1; - let t22; - if ($2[2] !== result.data || $2[3] !== result.success) { - t22 = result.success ? result.data.questions || [] : []; - $2[2] = result.data; - $2[3] = result.success; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const questions = t22; - const { - rows: terminalRows - } = useTerminalSize(); - const [theme2] = useTheme(); - let maxHeight = 0; - let maxWidth = 0; - const maxAllowedHeight = Math.max(MIN_CONTENT_HEIGHT, terminalRows - CONTENT_CHROME_OVERHEAD); - if ($2[5] !== highlight || $2[6] !== maxAllowedHeight || $2[7] !== maxHeight || $2[8] !== maxWidth || $2[9] !== questions || $2[10] !== theme2) { - for (const q4 of questions) { - const hasPreview = q4.options.some(_temp173); - if (hasPreview) { - const maxPreviewContentLines = Math.max(1, maxAllowedHeight - 11); - let maxPreviewBoxHeight = 0; - for (const opt_0 of q4.options) { - if (opt_0.preview) { - const rendered = applyMarkdown(opt_0.preview, theme2, highlight); - const previewLines = rendered.split(` -`); - const isTruncated = previewLines.length > maxPreviewContentLines; - const displayedLines = isTruncated ? maxPreviewContentLines : previewLines.length; - maxPreviewBoxHeight = Math.max(maxPreviewBoxHeight, displayedLines + (isTruncated ? 1 : 0) + 2); - for (const line of previewLines) { - maxWidth = Math.max(maxWidth, stringWidth(line)); - } - } - } - const rightPanelHeight = maxPreviewBoxHeight + 2; - const leftPanelHeight = q4.options.length + 2; - const sideByHeight = Math.max(leftPanelHeight, rightPanelHeight); - maxHeight = Math.max(maxHeight, sideByHeight + 7); - } else { - maxHeight = Math.max(maxHeight, q4.options.length + 3 + 7); - } - } - $2[5] = highlight; - $2[6] = maxAllowedHeight; - $2[7] = maxHeight; - $2[8] = maxWidth; - $2[9] = questions; - $2[10] = theme2; - $2[11] = maxHeight; - } else { - maxHeight = $2[11]; - } - const t32 = Math.min(Math.max(maxHeight, MIN_CONTENT_HEIGHT), maxAllowedHeight); - const t4 = Math.max(maxWidth, MIN_CONTENT_WIDTH); - let t5; - if ($2[12] !== t32 || $2[13] !== t4) { - t5 = { - globalContentHeight: t32, - globalContentWidth: t4 - }; - $2[12] = t32; - $2[13] = t4; - $2[14] = t5; - } else { - t5 = $2[14]; - } - const { - globalContentHeight, - globalContentWidth - } = t5; - const metadataSource = result.success ? result.data.metadata?.source : undefined; - let t6; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t6 = {}; - $2[15] = t6; - } else { - t6 = $2[15]; - } - const [pastedContentsByQuestion, setPastedContentsByQuestion] = import_react206.useState(t6); - const nextPasteIdRef = import_react206.useRef(0); - let t7; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t7 = function onImagePaste2(questionText, base64Image, mediaType, filename, dimensions, _sourcePath) { - nextPasteIdRef.current = nextPasteIdRef.current + 1; - const pasteId = nextPasteIdRef.current; - const newContent = { - id: pasteId, - type: "image", - content: base64Image, - mediaType: mediaType || "image/png", - filename: filename || "Pasted image", - dimensions - }; - cacheImagePath(newContent); - storeImage(newContent); - setPastedContentsByQuestion((prev) => ({ - ...prev, - [questionText]: { - ...prev[questionText] ?? {}, - [pasteId]: newContent - } - })); - }; - $2[16] = t7; - } else { - t7 = $2[16]; - } - const onImagePaste = t7; - let t8; - if ($2[17] === Symbol.for("react.memo_cache_sentinel")) { - t8 = (questionText_0, id) => { - setPastedContentsByQuestion((prev_0) => { - const questionContents = { - ...prev_0[questionText_0] ?? {} - }; - delete questionContents[id]; - return { - ...prev_0, - [questionText_0]: questionContents - }; - }); - }; - $2[17] = t8; - } else { - t8 = $2[17]; - } - const onRemoveImage = t8; - let t9; - if ($2[18] !== pastedContentsByQuestion) { - t9 = Object.values(pastedContentsByQuestion).flatMap(_temp275).filter(_temp349); - $2[18] = pastedContentsByQuestion; - $2[19] = t9; - } else { - t9 = $2[19]; - } - const allImageAttachments = t9; - const toolPermissionContextMode = useAppState(_temp436); - const isInPlanMode = toolPermissionContextMode === "plan"; - let t10; - if ($2[20] !== isInPlanMode) { - t10 = isInPlanMode ? getPlanFilePath() : undefined; - $2[20] = isInPlanMode; - $2[21] = t10; - } else { - t10 = $2[21]; - } - const planFilePath = t10; - const state4 = useMultipleChoiceState(); - const { - currentQuestionIndex, - answers, - questionStates, - isInTextInput, - nextQuestion, - prevQuestion, - updateQuestionState, - setAnswer, - setTextInputMode - } = state4; - const currentQuestion = currentQuestionIndex < (questions?.length || 0) ? questions?.[currentQuestionIndex] : null; - const isInSubmitView = currentQuestionIndex === (questions?.length || 0); - let t11; - if ($2[22] !== answers || $2[23] !== questions) { - t11 = questions?.every((q_0) => q_0?.question && !!answers[q_0.question]) ?? false; - $2[22] = answers; - $2[23] = questions; - $2[24] = t11; - } else { - t11 = $2[24]; - } - const allQuestionsAnswered = t11; - const hideSubmitTab = questions.length === 1 && !questions[0]?.multiSelect; - let t12; - if ($2[25] !== isInPlanMode || $2[26] !== metadataSource || $2[27] !== onDone || $2[28] !== onReject || $2[29] !== questions.length || $2[30] !== toolUseConfirm) { - t12 = () => { - if (metadataSource) { - logEvent("tengu_ask_user_question_rejected", { - source: metadataSource, - questionCount: questions.length, - isInPlanMode, - interviewPhaseEnabled: isInPlanMode && isPlanModeInterviewPhaseEnabled() - }); - } - onDone(); - onReject(); - toolUseConfirm.onReject(); - }; - $2[25] = isInPlanMode; - $2[26] = metadataSource; - $2[27] = onDone; - $2[28] = onReject; - $2[29] = questions.length; - $2[30] = toolUseConfirm; - $2[31] = t12; - } else { - t12 = $2[31]; - } - const handleCancel = t12; - let t13; - if ($2[32] !== allImageAttachments || $2[33] !== answers || $2[34] !== isInPlanMode || $2[35] !== metadataSource || $2[36] !== onDone || $2[37] !== questions || $2[38] !== toolUseConfirm) { - t13 = async () => { - const questionsWithAnswers = questions.map((q_1) => { - const answer = answers[q_1.question]; - if (answer) { - return `- "${q_1.question}" - Answer: ${answer}`; - } - return `- "${q_1.question}" - (No answer provided)`; - }).join(` -`); - const feedback2 = `The user wants to clarify these questions. - This means they may have additional information, context or questions for you. - Take their response into account and then reformulate the questions if appropriate. - Start by asking them what they would like to clarify. - - Questions asked: -${questionsWithAnswers}`; - if (metadataSource) { - logEvent("tengu_ask_user_question_respond_to_claude", { - source: metadataSource, - questionCount: questions.length, - isInPlanMode, - interviewPhaseEnabled: isInPlanMode && isPlanModeInterviewPhaseEnabled() - }); - } - const imageBlocks = await convertImagesToBlocks(allImageAttachments); - onDone(); - toolUseConfirm.onReject(feedback2, imageBlocks && imageBlocks.length > 0 ? imageBlocks : undefined); - }; - $2[32] = allImageAttachments; - $2[33] = answers; - $2[34] = isInPlanMode; - $2[35] = metadataSource; - $2[36] = onDone; - $2[37] = questions; - $2[38] = toolUseConfirm; - $2[39] = t13; - } else { - t13 = $2[39]; - } - const handleRespondToClaude = t13; - let t14; - if ($2[40] !== allImageAttachments || $2[41] !== answers || $2[42] !== isInPlanMode || $2[43] !== metadataSource || $2[44] !== onDone || $2[45] !== questions || $2[46] !== toolUseConfirm) { - t14 = async () => { - const questionsWithAnswers_0 = questions.map((q_2) => { - const answer_0 = answers[q_2.question]; - if (answer_0) { - return `- "${q_2.question}" - Answer: ${answer_0}`; - } - return `- "${q_2.question}" - (No answer provided)`; - }).join(` -`); - const feedback_0 = `The user has indicated they have provided enough answers for the plan interview. -Stop asking clarifying questions and proceed to finish the plan with the information you have. - -Questions asked and answers provided: -${questionsWithAnswers_0}`; - if (metadataSource) { - logEvent("tengu_ask_user_question_finish_plan_interview", { - source: metadataSource, - questionCount: questions.length, - isInPlanMode, - interviewPhaseEnabled: isInPlanMode && isPlanModeInterviewPhaseEnabled() - }); - } - const imageBlocks_0 = await convertImagesToBlocks(allImageAttachments); - onDone(); - toolUseConfirm.onReject(feedback_0, imageBlocks_0 && imageBlocks_0.length > 0 ? imageBlocks_0 : undefined); - }; - $2[40] = allImageAttachments; - $2[41] = answers; - $2[42] = isInPlanMode; - $2[43] = metadataSource; - $2[44] = onDone; - $2[45] = questions; - $2[46] = toolUseConfirm; - $2[47] = t14; - } else { - t14 = $2[47]; - } - const handleFinishPlanInterview = t14; - let t15; - if ($2[48] !== allImageAttachments || $2[49] !== isInPlanMode || $2[50] !== metadataSource || $2[51] !== onDone || $2[52] !== questionStates || $2[53] !== questions || $2[54] !== toolUseConfirm) { - t15 = async (answersToSubmit) => { - if (metadataSource) { - logEvent("tengu_ask_user_question_accepted", { - source: metadataSource, - questionCount: questions.length, - answerCount: Object.keys(answersToSubmit).length, - isInPlanMode, - interviewPhaseEnabled: isInPlanMode && isPlanModeInterviewPhaseEnabled() - }); - } - const annotations = {}; - for (const q_3 of questions) { - const answer_1 = answersToSubmit[q_3.question]; - const notes = questionStates[q_3.question]?.textInputValue; - const selectedOption = answer_1 ? q_3.options.find((opt_1) => opt_1.label === answer_1) : undefined; - const preview = selectedOption?.preview; - if (preview || notes?.trim()) { - annotations[q_3.question] = { - ...preview && { - preview - }, - ...notes?.trim() && { - notes: notes.trim() - } - }; - } - } - const updatedInput = { - ...toolUseConfirm.input, - answers: answersToSubmit, - ...Object.keys(annotations).length > 0 && { - annotations - } - }; - const contentBlocks = await convertImagesToBlocks(allImageAttachments); - onDone(); - toolUseConfirm.onAllow(updatedInput, [], undefined, contentBlocks && contentBlocks.length > 0 ? contentBlocks : undefined); - }; - $2[48] = allImageAttachments; - $2[49] = isInPlanMode; - $2[50] = metadataSource; - $2[51] = onDone; - $2[52] = questionStates; - $2[53] = questions; - $2[54] = toolUseConfirm; - $2[55] = t15; - } else { - t15 = $2[55]; - } - const submitAnswers = t15; - let t16; - if ($2[56] !== answers || $2[57] !== pastedContentsByQuestion || $2[58] !== questions.length || $2[59] !== setAnswer || $2[60] !== submitAnswers) { - t16 = (questionText_1, label, textInput, t172) => { - const shouldAdvance = t172 === undefined ? true : t172; - let answer_2; - const isMultiSelect = Array.isArray(label); - if (isMultiSelect) { - answer_2 = label.join(", "); - } else { - if (textInput) { - const questionImages = Object.values(pastedContentsByQuestion[questionText_1] ?? {}).filter(_temp526); - answer_2 = questionImages.length > 0 ? `${textInput} (Image attached)` : textInput; - } else { - if (label === "__other__") { - const questionImages_0 = Object.values(pastedContentsByQuestion[questionText_1] ?? {}).filter(_temp621); - answer_2 = questionImages_0.length > 0 ? "(Image attached)" : label; - } else { - answer_2 = label; - } - } - } - const isSingleQuestion = questions.length === 1; - if (!isMultiSelect && isSingleQuestion && shouldAdvance) { - const updatedAnswers = { - ...answers, - [questionText_1]: answer_2 - }; - submitAnswers(updatedAnswers).catch(logError2); - return; - } - setAnswer(questionText_1, answer_2, shouldAdvance); - }; - $2[56] = answers; - $2[57] = pastedContentsByQuestion; - $2[58] = questions.length; - $2[59] = setAnswer; - $2[60] = submitAnswers; - $2[61] = t16; - } else { - t16 = $2[61]; - } - const handleQuestionAnswer = t16; - let t17; - if ($2[62] !== answers || $2[63] !== handleCancel || $2[64] !== submitAnswers) { - t17 = function handleFinalResponse2(value) { - if (value === "cancel") { - handleCancel(); - return; - } - if (value === "submit") { - submitAnswers(answers).catch(logError2); - } - }; - $2[62] = answers; - $2[63] = handleCancel; - $2[64] = submitAnswers; - $2[65] = t17; - } else { - t17 = $2[65]; - } - const handleFinalResponse = t17; - const maxIndex = hideSubmitTab ? (questions?.length || 1) - 1 : questions?.length || 0; - let t18; - if ($2[66] !== currentQuestionIndex || $2[67] !== prevQuestion) { - t18 = () => { - if (currentQuestionIndex > 0) { - prevQuestion(); - } - }; - $2[66] = currentQuestionIndex; - $2[67] = prevQuestion; - $2[68] = t18; - } else { - t18 = $2[68]; - } - const handleTabPrev = t18; - let t19; - if ($2[69] !== currentQuestionIndex || $2[70] !== maxIndex || $2[71] !== nextQuestion) { - t19 = () => { - if (currentQuestionIndex < maxIndex) { - nextQuestion(); - } - }; - $2[69] = currentQuestionIndex; - $2[70] = maxIndex; - $2[71] = nextQuestion; - $2[72] = t19; - } else { - t19 = $2[72]; - } - const handleTabNext = t19; - let t20; - if ($2[73] !== handleTabNext || $2[74] !== handleTabPrev) { - t20 = { - "tabs:previous": handleTabPrev, - "tabs:next": handleTabNext - }; - $2[73] = handleTabNext; - $2[74] = handleTabPrev; - $2[75] = t20; - } else { - t20 = $2[75]; - } - const t21 = !(isInTextInput && !isInSubmitView); - let t222; - if ($2[76] !== t21) { - t222 = { - context: "Tabs", - isActive: t21 - }; - $2[76] = t21; - $2[77] = t222; - } else { - t222 = $2[77]; - } - useKeybindings(t20, t222); - if (currentQuestion) { - let t23; - if ($2[78] !== currentQuestion.question) { - t23 = (base644, mediaType_0, filename_0, dims, path26) => onImagePaste(currentQuestion.question, base644, mediaType_0, filename_0, dims, path26); - $2[78] = currentQuestion.question; - $2[79] = t23; - } else { - t23 = $2[79]; - } - let t24; - if ($2[80] !== currentQuestion.question || $2[81] !== pastedContentsByQuestion) { - t24 = pastedContentsByQuestion[currentQuestion.question] ?? {}; - $2[80] = currentQuestion.question; - $2[81] = pastedContentsByQuestion; - $2[82] = t24; - } else { - t24 = $2[82]; - } - let t25; - if ($2[83] !== currentQuestion.question) { - t25 = (id_0) => onRemoveImage(currentQuestion.question, id_0); - $2[83] = currentQuestion.question; - $2[84] = t25; - } else { - t25 = $2[84]; - } - let t26; - if ($2[85] !== answers || $2[86] !== currentQuestion || $2[87] !== currentQuestionIndex || $2[88] !== globalContentHeight || $2[89] !== globalContentWidth || $2[90] !== handleCancel || $2[91] !== handleFinishPlanInterview || $2[92] !== handleQuestionAnswer || $2[93] !== handleRespondToClaude || $2[94] !== handleTabNext || $2[95] !== handleTabPrev || $2[96] !== hideSubmitTab || $2[97] !== nextQuestion || $2[98] !== planFilePath || $2[99] !== questionStates || $2[100] !== questions || $2[101] !== setTextInputMode || $2[102] !== t23 || $2[103] !== t24 || $2[104] !== t25 || $2[105] !== updateQuestionState) { - t26 = /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(jsx_dev_runtime376.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(QuestionView, { - question: currentQuestion, - questions, - currentQuestionIndex, - answers, - questionStates, - hideSubmitTab, - minContentHeight: globalContentHeight, - minContentWidth: globalContentWidth, - planFilePath, - onUpdateQuestionState: updateQuestionState, - onAnswer: handleQuestionAnswer, - onTextInputFocus: setTextInputMode, - onCancel: handleCancel, - onSubmit: nextQuestion, - onTabPrev: handleTabPrev, - onTabNext: handleTabNext, - onRespondToClaude: handleRespondToClaude, - onFinishPlanInterview: handleFinishPlanInterview, - onImagePaste: t23, - pastedContents: t24, - onRemoveImage: t25 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[85] = answers; - $2[86] = currentQuestion; - $2[87] = currentQuestionIndex; - $2[88] = globalContentHeight; - $2[89] = globalContentWidth; - $2[90] = handleCancel; - $2[91] = handleFinishPlanInterview; - $2[92] = handleQuestionAnswer; - $2[93] = handleRespondToClaude; - $2[94] = handleTabNext; - $2[95] = handleTabPrev; - $2[96] = hideSubmitTab; - $2[97] = nextQuestion; - $2[98] = planFilePath; - $2[99] = questionStates; - $2[100] = questions; - $2[101] = setTextInputMode; - $2[102] = t23; - $2[103] = t24; - $2[104] = t25; - $2[105] = updateQuestionState; - $2[106] = t26; - } else { - t26 = $2[106]; - } - return t26; - } - if (isInSubmitView) { - let t23; - if ($2[107] !== allQuestionsAnswered || $2[108] !== answers || $2[109] !== currentQuestionIndex || $2[110] !== globalContentHeight || $2[111] !== handleFinalResponse || $2[112] !== questions || $2[113] !== toolUseConfirm.permissionResult) { - t23 = /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(jsx_dev_runtime376.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime376.jsxDEV(SubmitQuestionsView, { - questions, - currentQuestionIndex, - answers, - allQuestionsAnswered, - permissionResult: toolUseConfirm.permissionResult, - minContentHeight: globalContentHeight, - onFinalResponse: handleFinalResponse - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[107] = allQuestionsAnswered; - $2[108] = answers; - $2[109] = currentQuestionIndex; - $2[110] = globalContentHeight; - $2[111] = handleFinalResponse; - $2[112] = questions; - $2[113] = toolUseConfirm.permissionResult; - $2[114] = t23; - } else { - t23 = $2[114]; - } - return t23; - } - return null; -} -function _temp621(c_1) { - return c_1.type === "image"; -} -function _temp526(c_0) { - return c_0.type === "image"; -} -function _temp436(s4) { - return s4.toolPermissionContext.mode; -} -function _temp349(c9) { - return c9.type === "image"; -} -function _temp275(contents) { - return Object.values(contents); -} -function _temp173(opt) { - return opt.preview; -} -async function convertImagesToBlocks(images) { - if (images.length === 0) - return; - return Promise.all(images.map(async (img) => { - const block2 = { - type: "image", - source: { - type: "base64", - media_type: img.mediaType || "image/png", - data: img.content - } - }; - const resized = await maybeResizeAndDownsampleImageBlock(block2); - return resized.block; - })); -} -var import_compiler_runtime292, import_react206, jsx_dev_runtime376, MIN_CONTENT_HEIGHT = 12, MIN_CONTENT_WIDTH = 40, CONTENT_CHROME_OVERHEAD = 15; -var init_AskUserQuestionPermissionRequest = __esm(() => { - init_useSettings(); - init_useTerminalSize(); - init_stringWidth(); - init_ink2(); - init_useKeybinding(); - init_analytics(); - init_AppState(); - init_AskUserQuestionTool(); - init_cliHighlight(); - init_imageResizer(); - init_imageStore(); - init_log2(); - init_markdown(); - init_planModeV2(); - init_plans(); - init_QuestionView(); - init_SubmitQuestionsView(); - init_use_multiple_choice_state(); - import_compiler_runtime292 = __toESM(require_compiler_runtime(), 1); - import_react206 = __toESM(require_react(), 1); - jsx_dev_runtime376 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/tools/BashTool/destructiveCommandWarning.ts -function getDestructiveCommandWarning(command19) { - for (const { pattern, warning } of DESTRUCTIVE_PATTERNS) { - if (pattern.test(command19)) { - return warning; - } - } - return null; -} -var DESTRUCTIVE_PATTERNS; -var init_destructiveCommandWarning = __esm(() => { - DESTRUCTIVE_PATTERNS = [ - { - pattern: /\bgit\s+reset\s+--hard\b/, - warning: "Note: may discard uncommitted changes" - }, - { - pattern: /\bgit\s+push\b[^;&|\n]*[ \t](--force|--force-with-lease|-f)\b/, - warning: "Note: may overwrite remote history" - }, - { - pattern: /\bgit\s+clean\b(?![^;&|\n]*(?:-[a-zA-Z]*n|--dry-run))[^;&|\n]*-[a-zA-Z]*f/, - warning: "Note: may permanently delete untracked files" - }, - { - pattern: /\bgit\s+checkout\s+(--\s+)?\.[ \t]*($|[;&|\n])/, - warning: "Note: may discard all working tree changes" - }, - { - pattern: /\bgit\s+restore\s+(--\s+)?\.[ \t]*($|[;&|\n])/, - warning: "Note: may discard all working tree changes" - }, - { - pattern: /\bgit\s+stash[ \t]+(drop|clear)\b/, - warning: "Note: may permanently remove stashed changes" - }, - { - pattern: /\bgit\s+branch\s+(-D[ \t]|--delete\s+--force|--force\s+--delete)\b/, - warning: "Note: may force-delete a branch" - }, - { - pattern: /\bgit\s+(commit|push|merge)\b[^;&|\n]*--no-verify\b/, - warning: "Note: may skip safety hooks" - }, - { - pattern: /\bgit\s+commit\b[^;&|\n]*--amend\b/, - warning: "Note: may rewrite the last commit" - }, - { - pattern: /(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*[rR][a-zA-Z]*f|(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*f[a-zA-Z]*[rR]/, - warning: "Note: may recursively force-remove files" - }, - { - pattern: /(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*[rR]/, - warning: "Note: may recursively remove files" - }, - { - pattern: /(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*f/, - warning: "Note: may force-remove files" - }, - { - pattern: /\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA)\b/i, - warning: "Note: may drop or truncate database objects" - }, - { - pattern: /\bDELETE\s+FROM\s+\w+[ \t]*(;|"|'|\n|$)/i, - warning: "Note: may delete all rows from a database table" - }, - { - pattern: /\bkubectl\s+delete\b/, - warning: "Note: may delete Kubernetes resources" - }, - { - pattern: /\bterraform\s+destroy\b/, - warning: "Note: may destroy Terraform infrastructure" - } - ]; -}); - -// src/utils/shell/specPrefix.ts -function isKnownSubcommand(arg, spec) { - if (!spec?.subcommands?.length) - return false; - const argLower = arg.toLowerCase(); - return spec.subcommands.some((sub) => Array.isArray(sub.name) ? sub.name.some((n6) => n6.toLowerCase() === argLower) : sub.name.toLowerCase() === argLower); -} -function flagTakesArg(flag, nextArg, spec) { - if (spec?.options) { - const option = spec.options.find((opt) => Array.isArray(opt.name) ? opt.name.includes(flag) : opt.name === flag); - if (option) - return !!option.args; - } - if (spec?.subcommands?.length && nextArg && !nextArg.startsWith("-")) { - return !isKnownSubcommand(nextArg, spec); - } - return false; -} -function findFirstSubcommand(args, spec) { - for (let i6 = 0;i6 < args.length; i6++) { - const arg = args[i6]; - if (!arg) - continue; - if (arg.startsWith("-")) { - if (flagTakesArg(arg, args[i6 + 1], spec)) - i6++; - continue; - } - if (!spec?.subcommands?.length) - return arg; - if (isKnownSubcommand(arg, spec)) - return arg; - } - return; -} -async function buildPrefix(command19, args, spec) { - const maxDepth = await calculateDepth(command19, args, spec); - const parts = [command19]; - const hasSubcommands = !!spec?.subcommands?.length; - let foundSubcommand = false; - for (let i6 = 0;i6 < args.length; i6++) { - const arg = args[i6]; - if (!arg || parts.length >= maxDepth) - break; - if (arg.startsWith("-")) { - if (arg === "-c" && ["python", "python3"].includes(command19.toLowerCase())) - break; - if (spec?.options) { - const option = spec.options.find((opt) => Array.isArray(opt.name) ? opt.name.includes(arg) : opt.name === arg); - if (option?.args && toArray3(option.args).some((a5) => a5?.isCommand || a5?.isModule)) { - parts.push(arg); - continue; - } - } - if (hasSubcommands && !foundSubcommand) { - if (flagTakesArg(arg, args[i6 + 1], spec)) - i6++; - continue; - } - break; - } - if (await shouldStopAtArg(arg, args.slice(0, i6), spec)) - break; - if (hasSubcommands && !foundSubcommand) { - foundSubcommand = isKnownSubcommand(arg, spec); - } - parts.push(arg); - } - return parts.join(" "); -} -async function calculateDepth(command19, args, spec) { - const firstSubcommand = findFirstSubcommand(args, spec); - const commandLower = command19.toLowerCase(); - const key2 = firstSubcommand ? `${commandLower} ${firstSubcommand.toLowerCase()}` : commandLower; - if (DEPTH_RULES[key2]) - return DEPTH_RULES[key2]; - if (DEPTH_RULES[commandLower]) - return DEPTH_RULES[commandLower]; - if (!spec) - return 2; - if (spec.options && args.some((arg) => arg?.startsWith("-"))) { - for (const arg of args) { - if (!arg?.startsWith("-")) - continue; - const option = spec.options.find((opt) => Array.isArray(opt.name) ? opt.name.includes(arg) : opt.name === arg); - if (option?.args && toArray3(option.args).some((arg2) => arg2?.isCommand || arg2?.isModule)) - return 3; - } - } - if (firstSubcommand && spec.subcommands?.length) { - const firstSubLower = firstSubcommand.toLowerCase(); - const subcommand = spec.subcommands.find((sub) => Array.isArray(sub.name) ? sub.name.some((n6) => n6.toLowerCase() === firstSubLower) : sub.name.toLowerCase() === firstSubLower); - if (subcommand) { - if (subcommand.args) { - const subArgs = toArray3(subcommand.args); - if (subArgs.some((arg) => arg?.isCommand)) - return 3; - if (subArgs.some((arg) => arg?.isVariadic)) - return 2; - } - if (subcommand.subcommands?.length) - return 4; - if (!subcommand.args) - return 2; - return 3; - } - } - if (spec.args) { - const argsArray = toArray3(spec.args); - if (argsArray.some((arg) => arg?.isCommand)) { - return !Array.isArray(spec.args) && spec.args.isCommand ? 2 : Math.min(2 + argsArray.findIndex((arg) => arg?.isCommand), 3); - } - if (!spec.subcommands?.length) { - if (argsArray.some((arg) => arg?.isVariadic)) - return 1; - if (argsArray[0] && !argsArray[0].isOptional) - return 2; - } - } - return spec.args && toArray3(spec.args).some((arg) => arg?.isDangerous) ? 3 : 2; -} -async function shouldStopAtArg(arg, args, spec) { - if (arg.startsWith("-")) - return true; - const dotIndex = arg.lastIndexOf("."); - const hasExtension = dotIndex > 0 && dotIndex < arg.length - 1 && !arg.substring(dotIndex + 1).includes(":"); - const hasFile = arg.includes("/") || hasExtension; - const hasUrl = URL_PROTOCOLS.some((proto2) => arg.startsWith(proto2)); - if (!hasFile && !hasUrl) - return false; - if (spec?.options && args.length > 0 && args[args.length - 1] === "-m") { - const option = spec.options.find((opt) => Array.isArray(opt.name) ? opt.name.includes("-m") : opt.name === "-m"); - if (option?.args && toArray3(option.args).some((arg2) => arg2?.isModule)) { - return false; - } - } - return true; -} -var URL_PROTOCOLS, DEPTH_RULES, toArray3 = (val) => Array.isArray(val) ? val : [val]; -var init_specPrefix = __esm(() => { - URL_PROTOCOLS = ["http://", "https://", "ftp://"]; - DEPTH_RULES = { - rg: 2, - "pre-commit": 2, - gcloud: 4, - "gcloud compute": 6, - "gcloud beta": 6, - aws: 4, - az: 4, - kubectl: 3, - docker: 3, - dotnet: 3, - "git push": 2 - }; -}); - -// src/utils/bash/specs/alias.ts -var alias, alias_default; -var init_alias = __esm(() => { - alias = { - name: "alias", - description: "Create or list command aliases", - args: { - name: "definition", - description: "Alias definition in the form name=value", - isOptional: true, - isVariadic: true - } - }; - alias_default = alias; -}); - -// src/utils/bash/specs/nohup.ts -var nohup, nohup_default; -var init_nohup = __esm(() => { - nohup = { - name: "nohup", - description: "Run a command immune to hangups", - args: { - name: "command", - description: "Command to run with nohup", - isCommand: true - } - }; - nohup_default = nohup; -}); - -// src/utils/bash/specs/pyright.ts -var pyright_default; -var init_pyright = __esm(() => { - pyright_default = { - name: "pyright", - description: "Type checker for Python", - options: [ - { name: ["--help", "-h"], description: "Show help message" }, - { name: "--version", description: "Print pyright version and exit" }, - { - name: ["--watch", "-w"], - description: "Continue to run and watch for changes" - }, - { - name: ["--project", "-p"], - description: "Use the configuration file at this location", - args: { name: "FILE OR DIRECTORY" } - }, - { name: "-", description: "Read file or directory list from stdin" }, - { - name: "--createstub", - description: "Create type stub file(s) for import", - args: { name: "IMPORT" } - }, - { - name: ["--typeshedpath", "-t"], - description: "Use typeshed type stubs at this location", - args: { name: "DIRECTORY" } - }, - { - name: "--verifytypes", - description: "Verify completeness of types in py.typed package", - args: { name: "IMPORT" } - }, - { - name: "--ignoreexternal", - description: "Ignore external imports for --verifytypes" - }, - { - name: "--pythonpath", - description: "Path to the Python interpreter", - args: { name: "FILE" } - }, - { - name: "--pythonplatform", - description: "Analyze for platform", - args: { name: "PLATFORM" } - }, - { - name: "--pythonversion", - description: "Analyze for Python version", - args: { name: "VERSION" } - }, - { - name: ["--venvpath", "-v"], - description: "Directory that contains virtual environments", - args: { name: "DIRECTORY" } - }, - { name: "--outputjson", description: "Output results in JSON format" }, - { name: "--verbose", description: "Emit verbose diagnostics" }, - { name: "--stats", description: "Print detailed performance stats" }, - { - name: "--dependencies", - description: "Emit import dependency information" - }, - { - name: "--level", - description: "Minimum diagnostic level", - args: { name: "LEVEL" } - }, - { - name: "--skipunannotated", - description: "Skip type analysis of unannotated functions" - }, - { - name: "--warnings", - description: "Use exit code of 1 if warnings are reported" - }, - { - name: "--threads", - description: "Use up to N threads to parallelize type checking", - args: { name: "N", isOptional: true } - } - ], - args: { - name: "files", - description: "Specify files or directories to analyze (overrides config file)", - isVariadic: true, - isOptional: true - } - }; -}); - -// src/utils/bash/specs/sleep.ts -var sleep8, sleep_default; -var init_sleep = __esm(() => { - sleep8 = { - name: "sleep", - description: "Delay for a specified amount of time", - args: { - name: "duration", - description: "Duration to sleep (seconds or with suffix like 5s, 2m, 1h)", - isOptional: false - } - }; - sleep_default = sleep8; -}); - -// src/utils/bash/specs/srun.ts -var srun, srun_default; -var init_srun = __esm(() => { - srun = { - name: "srun", - description: "Run a command on SLURM cluster nodes", - options: [ - { - name: ["-n", "--ntasks"], - description: "Number of tasks", - args: { - name: "count", - description: "Number of tasks to run" - } - }, - { - name: ["-N", "--nodes"], - description: "Number of nodes", - args: { - name: "count", - description: "Number of nodes to allocate" - } - } - ], - args: { - name: "command", - description: "Command to run on the cluster", - isCommand: true - } - }; - srun_default = srun; -}); - -// src/utils/bash/specs/time.ts -var time3, time_default; -var init_time = __esm(() => { - time3 = { - name: "time", - description: "Time a command", - args: { - name: "command", - description: "Command to time", - isCommand: true - } - }; - time_default = time3; -}); - -// src/utils/bash/specs/timeout.ts -var timeout, timeout_default; -var init_timeout2 = __esm(() => { - timeout = { - name: "timeout", - description: "Run a command with a time limit", - args: [ - { - name: "duration", - description: "Duration to wait before timing out (e.g., 10, 5s, 2m)", - isOptional: false - }, - { - name: "command", - description: "Command to run", - isCommand: true - } - ] - }; - timeout_default = timeout; -}); - -// src/utils/bash/specs/index.ts -var specs_default; -var init_specs = __esm(() => { - init_alias(); - init_nohup(); - init_pyright(); - init_sleep(); - init_srun(); - init_time(); - init_timeout2(); - specs_default = [ - pyright_default, - timeout_default, - sleep_default, - alias_default, - nohup_default, - time_default, - srun_default - ]; -}); - -// src/utils/bash/registry.ts -async function loadFigSpec(command19) { - if (!command19 || command19.includes("/") || command19.includes("\\")) - return null; - if (command19.includes("..")) - return null; - if (command19.startsWith("-") && command19 !== "-") - return null; - try { - const module = await import(`@withfig/autocomplete/build/${command19}.js`); - return module.default || module; - } catch { - return null; - } -} -var getCommandSpec; -var init_registry2 = __esm(() => { - init_memoize2(); - init_specs(); - getCommandSpec = memoizeWithLRU(async (command19) => { - const spec = specs_default.find((s4) => s4.name === command19) || await loadFigSpec(command19) || null; - return spec; - }, (command19) => command19); -}); - -// src/utils/bash/prefix.ts -function isKnownSubcommand2(arg, spec) { - if (!spec?.subcommands?.length) - return false; - return spec.subcommands.some((sub) => Array.isArray(sub.name) ? sub.name.includes(arg) : sub.name === arg); -} -async function getCommandPrefixStatic(command19, recursionDepth = 0, wrapperCount = 0) { - if (wrapperCount > 2 || recursionDepth > 10) - return null; - const parsed = await parseCommand2(command19); - if (!parsed) - return null; - if (!parsed.commandNode) { - return { commandPrefix: null }; - } - const { envVars, commandNode } = parsed; - const cmdArgs = extractCommandArguments(commandNode); - const [cmd, ...args] = cmdArgs; - if (!cmd) - return { commandPrefix: null }; - const spec = await getCommandSpec(cmd); - let isWrapper = WRAPPER_COMMANDS.has(cmd) || spec?.args && toArray4(spec.args).some((arg) => arg?.isCommand); - if (isWrapper && args[0] && isKnownSubcommand2(args[0], spec)) { - isWrapper = false; - } - const prefix = isWrapper ? await handleWrapper(cmd, args, recursionDepth, wrapperCount) : await buildPrefix(cmd, args, spec); - if (prefix === null && recursionDepth === 0 && isWrapper) { - return null; - } - const envPrefix = envVars.length ? `${envVars.join(" ")} ` : ""; - return { commandPrefix: prefix ? envPrefix + prefix : null }; -} -async function handleWrapper(command19, args, recursionDepth, wrapperCount) { - const spec = await getCommandSpec(command19); - if (spec?.args) { - const commandArgIndex = toArray4(spec.args).findIndex((arg) => arg?.isCommand); - if (commandArgIndex !== -1) { - const parts = [command19]; - for (let i6 = 0;i6 < args.length && i6 <= commandArgIndex; i6++) { - if (i6 === commandArgIndex) { - const result2 = await getCommandPrefixStatic(args.slice(i6).join(" "), recursionDepth + 1, wrapperCount + 1); - if (result2?.commandPrefix) { - parts.push(...result2.commandPrefix.split(" ")); - return parts.join(" "); - } - break; - } else if (args[i6] && !args[i6].startsWith("-") && !ENV_VAR.test(args[i6])) { - parts.push(args[i6]); - } - } - } - } - const wrapped = args.find((arg) => !arg.startsWith("-") && !NUMERIC.test(arg) && !ENV_VAR.test(arg)); - if (!wrapped) - return command19; - const result = await getCommandPrefixStatic(args.slice(args.indexOf(wrapped)).join(" "), recursionDepth + 1, wrapperCount + 1); - return !result?.commandPrefix ? null : `${command19} ${result.commandPrefix}`; -} -async function getCompoundCommandPrefixesStatic(command19, excludeSubcommand) { - const subcommands = splitCommand_DEPRECATED(command19); - if (subcommands.length <= 1) { - const result = await getCommandPrefixStatic(command19); - return result?.commandPrefix ? [result.commandPrefix] : []; - } - const prefixes = []; - for (const subcmd of subcommands) { - const trimmed = subcmd.trim(); - if (excludeSubcommand?.(trimmed)) - continue; - const result = await getCommandPrefixStatic(trimmed); - if (result?.commandPrefix) { - prefixes.push(result.commandPrefix); - } - } - if (prefixes.length === 0) - return []; - const groups = new Map; - for (const prefix of prefixes) { - const root3 = prefix.split(" ")[0]; - const group = groups.get(root3); - if (group) { - group.push(prefix); - } else { - groups.set(root3, [prefix]); - } - } - const collapsed = []; - for (const [, group] of groups) { - collapsed.push(longestCommonPrefix2(group)); - } - return collapsed; -} -function longestCommonPrefix2(strings) { - if (strings.length === 0) - return ""; - if (strings.length === 1) - return strings[0]; - const first = strings[0]; - const words = first.split(" "); - let commonWords = words.length; - for (let i6 = 1;i6 < strings.length; i6++) { - const otherWords = strings[i6].split(" "); - let shared11 = 0; - while (shared11 < commonWords && shared11 < otherWords.length && words[shared11] === otherWords[shared11]) { - shared11++; - } - commonWords = shared11; - } - return words.slice(0, Math.max(1, commonWords)).join(" "); -} -var NUMERIC, ENV_VAR, WRAPPER_COMMANDS, toArray4 = (val) => Array.isArray(val) ? val : [val]; -var init_prefix2 = __esm(() => { - init_specPrefix(); - init_commands4(); - init_parser10(); - init_registry2(); - NUMERIC = /^\d+$/; - ENV_VAR = /^[A-Za-z_][A-Za-z0-9_]*=/; - WRAPPER_COMMANDS = new Set([ - "nice" - ]); -}); - -// src/utils/unaryLogging.ts -async function logUnaryEvent(event) { - logEvent("tengu_unary_event", { - event: event.event, - completion_type: event.completion_type, - language_name: await event.metadata.language_name, - message_id: event.metadata.message_id, - platform: event.metadata.platform, - ...event.metadata.hasFeedback !== undefined && { - hasFeedback: event.metadata.hasFeedback - } - }); -} -var init_unaryLogging = __esm(() => { - init_analytics(); -}); - -// src/components/permissions/hooks.ts -function permissionResultToLog(permissionResult) { - switch (permissionResult.behavior) { - case "allow": - return "allow"; - case "ask": { - const rules2 = extractRules(permissionResult.suggestions); - const suggestions = rules2.length > 0 ? rules2.map((r4) => permissionRuleValueToString(r4)).join(", ") : "none"; - return `ask: ${permissionResult.message}, -suggestions: ${suggestions} -reason: ${decisionReasonToString(permissionResult.decisionReason)}`; - } - case "deny": - return `deny: ${permissionResult.message}, -reason: ${decisionReasonToString(permissionResult.decisionReason)}`; - case "passthrough": { - const rules2 = extractRules(permissionResult.suggestions); - const suggestions = rules2.length > 0 ? rules2.map((r4) => permissionRuleValueToString(r4)).join(", ") : "none"; - return `passthrough: ${permissionResult.message}, -suggestions: ${suggestions} -reason: ${decisionReasonToString(permissionResult.decisionReason)}`; - } - } -} -function decisionReasonToString(decisionReason) { - if (!decisionReason) { - return "No decision reason"; - } - if (false) {} - switch (decisionReason.type) { - case "rule": - return `Rule: ${permissionRuleValueToString(decisionReason.rule.ruleValue)}`; - case "mode": - return `Mode: ${decisionReason.mode}`; - case "subcommandResults": - return `Subcommand Results: ${Array.from(decisionReason.reasons.entries()).map(([key2, value]) => `${key2}: ${permissionResultToLog(value)}`).join(`, -`)}`; - case "permissionPromptTool": - return `Permission Tool: ${decisionReason.permissionPromptToolName}, Result: ${jsonStringify(decisionReason.toolResult)}`; - case "hook": - return `Hook: ${decisionReason.hookName}${decisionReason.reason ? `, Reason: ${decisionReason.reason}` : ""}`; - case "workingDir": - return `Working Directory: ${decisionReason.reason}`; - case "safetyCheck": - return `Safety check: ${decisionReason.reason}`; - case "other": - return `Other: ${decisionReason.reason}`; - default: - return jsonStringify(decisionReason, null, 2); - } -} -function usePermissionRequestLogging(toolUseConfirm, unaryEvent) { - const setAppState = useSetAppState(); - const loggedToolUseID = import_react207.useRef(null); - import_react207.useEffect(() => { - if (loggedToolUseID.current === toolUseConfirm.toolUseID) { - return; - } - loggedToolUseID.current = toolUseConfirm.toolUseID; - setAppState((prev) => ({ - ...prev, - attribution: { - ...prev.attribution, - permissionPromptCount: prev.attribution.permissionPromptCount + 1 - } - })); - logEvent("tengu_tool_use_show_permission_request", { - messageID: toolUseConfirm.assistantMessage.message.id, - toolName: sanitizeToolNameForAnalytics(toolUseConfirm.tool.name), - isMcp: toolUseConfirm.tool.isMcp ?? false, - decisionReasonType: toolUseConfirm.permissionResult.decisionReason?.type, - sandboxEnabled: SandboxManager.isSandboxingEnabled() - }); - if (process.env.USER_TYPE === "ant") { - const permissionResult = toolUseConfirm.permissionResult; - if (toolUseConfirm.tool.name === BashTool.name && permissionResult.behavior === "ask" && !hasRules(permissionResult.suggestions)) { - logEvent("tengu_internal_tool_use_permission_request_no_always_allow", { - messageID: toolUseConfirm.assistantMessage.message.id, - toolName: sanitizeToolNameForAnalytics(toolUseConfirm.tool.name), - isMcp: toolUseConfirm.tool.isMcp ?? false, - decisionReasonType: permissionResult.decisionReason?.type ?? "unknown", - sandboxEnabled: SandboxManager.isSandboxingEnabled(), - decisionReasonDetails: decisionReasonToString(permissionResult.decisionReason) - }); - } - } - if (process.env.USER_TYPE === "ant") { - const parsedInput = BashTool.inputSchema.safeParse(toolUseConfirm.input); - if (toolUseConfirm.tool.name === BashTool.name && toolUseConfirm.permissionResult.behavior === "ask" && parsedInput.success) { - let split2 = [parsedInput.data.command]; - try { - split2 = splitCommand_DEPRECATED(parsedInput.data.command); - } catch {} - logEvent("tengu_internal_bash_tool_use_permission_request", { - parts: jsonStringify(split2), - input: jsonStringify(toolUseConfirm.input), - decisionReasonType: toolUseConfirm.permissionResult.decisionReason?.type, - decisionReason: decisionReasonToString(toolUseConfirm.permissionResult.decisionReason) - }); - } - } - logUnaryEvent({ - completion_type: unaryEvent.completion_type, - event: "response", - metadata: { - language_name: unaryEvent.language_name, - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - }, [toolUseConfirm, unaryEvent, setAppState]); -} -var import_react207; -var init_hooks6 = __esm(() => { - init_analytics(); - init_metadata(); - init_BashTool(); - init_commands4(); - init_PermissionUpdate(); - init_permissionRuleParser(); - init_sandbox_adapter(); - init_AppState(); - init_env(); - init_slowOperations(); - init_unaryLogging(); - import_react207 = __toESM(require_react(), 1); -}); - -// src/components/permissions/PermissionDecisionDebugInfo.tsx -function decisionReasonDisplayString(decisionReason) { - if (false) {} - switch (decisionReason.type) { - case "rule": - return `${source_default.bold(permissionRuleValueToString(decisionReason.rule.ruleValue))} rule from ${getSettingSourceDisplayNameLowercase(decisionReason.rule.source)}`; - case "mode": - return `${permissionModeTitle(decisionReason.mode)} mode`; - case "sandboxOverride": - return "Requires permission to bypass sandbox"; - case "workingDir": - return decisionReason.reason; - case "safetyCheck": - case "other": - return decisionReason.reason; - case "permissionPromptTool": - return `${source_default.bold(decisionReason.permissionPromptToolName)} permission prompt tool`; - case "hook": - return decisionReason.reason ? `${source_default.bold(decisionReason.hookName)} hook: ${decisionReason.reason}` : `${source_default.bold(decisionReason.hookName)} hook`; - case "asyncAgent": - return decisionReason.reason; - default: - return ""; - } -} -function PermissionDecisionInfoItem(t0) { - const $2 = import_compiler_runtime293.c(10); - const { - title, - decisionReason - } = t0; - const [theme2] = useTheme(); - let t1; - if ($2[0] !== decisionReason || $2[1] !== theme2) { - t1 = function formatDecisionReason2() { - switch (decisionReason.type) { - case "subcommandResults": { - return /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: Array.from(decisionReason.reasons.entries()).map((t23) => { - const [subcommand, result] = t23; - const icon = result.behavior === "allow" ? color("success", theme2)(figures_default.tick) : color("error", theme2)(figures_default.cross); - return /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: [ - icon, - " ", - subcommand - ] - }, undefined, true, undefined, this), - result.decisionReason !== undefined && result.decisionReason.type !== "subcommandResults" && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\u23BF", - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(Ansi, { - children: decisionReasonDisplayString(result.decisionReason) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - result.behavior === "ask" && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(SuggestedRules, { - suggestions: result.suggestions - }, undefined, false, undefined, this) - ] - }, subcommand, true, undefined, this); - }) - }, undefined, false, undefined, this); - } - default: { - return /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(Ansi, { - children: decisionReasonDisplayString(decisionReason) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - } - } - }; - $2[0] = decisionReason; - $2[1] = theme2; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const formatDecisionReason = t1; - let t22; - if ($2[3] !== title) { - t22 = title && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: title - }, undefined, false, undefined, this); - $2[3] = title; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] !== formatDecisionReason) { - t32 = formatDecisionReason(); - $2[5] = formatDecisionReason; - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] !== t22 || $2[8] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t22, - t32 - ] - }, undefined, true, undefined, this); - $2[7] = t22; - $2[8] = t32; - $2[9] = t4; - } else { - t4 = $2[9]; - } - return t4; -} -function SuggestedRules(t0) { - const $2 = import_compiler_runtime293.c(18); - const { - suggestions - } = t0; - let T0; - let T1; - let t1; - let t22; - let t32; - let t4; - let t5; - if ($2[0] !== suggestions) { - t5 = Symbol.for("react.early_return_sentinel"); - bb0: { - const rules2 = extractRules(suggestions); - if (rules2.length === 0) { - t5 = null; - break bb0; - } - T1 = ThemedText; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\u23BF", - " " - ] - }, undefined, true, undefined, this); - $2[8] = t22; - } else { - t22 = $2[8]; - } - t32 = "Suggested rules:"; - t4 = " "; - T0 = Ansi; - t1 = rules2.map(_temp175).join(", "); - } - $2[0] = suggestions; - $2[1] = T0; - $2[2] = T1; - $2[3] = t1; - $2[4] = t22; - $2[5] = t32; - $2[6] = t4; - $2[7] = t5; - } else { - T0 = $2[1]; - T1 = $2[2]; - t1 = $2[3]; - t22 = $2[4]; - t32 = $2[5]; - t4 = $2[6]; - t5 = $2[7]; - } - if (t5 !== Symbol.for("react.early_return_sentinel")) { - return t5; - } - let t6; - if ($2[9] !== T0 || $2[10] !== t1) { - t6 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(T0, { - children: t1 - }, undefined, false, undefined, this); - $2[9] = T0; - $2[10] = t1; - $2[11] = t6; - } else { - t6 = $2[11]; - } - let t7; - if ($2[12] !== T1 || $2[13] !== t22 || $2[14] !== t32 || $2[15] !== t4 || $2[16] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(T1, { - children: [ - t22, - t32, - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[12] = T1; - $2[13] = t22; - $2[14] = t32; - $2[15] = t4; - $2[16] = t6; - $2[17] = t7; - } else { - t7 = $2[17]; - } - return t7; -} -function _temp175(rule) { - return source_default.bold(permissionRuleValueToString(rule)); -} -function extractDirectories(updates) { - if (!updates) - return []; - return updates.flatMap((update) => { - switch (update.type) { - case "addDirectories": - return update.directories; - default: - return []; - } - }); -} -function extractMode(updates) { - if (!updates) - return; - const update = updates.findLast((u5) => u5.type === "setMode"); - return update?.type === "setMode" ? update.mode : undefined; -} -function SuggestionDisplay(t0) { - const $2 = import_compiler_runtime293.c(22); - const { - suggestions, - width - } = t0; - if (!suggestions || suggestions.length === 0) { - let t12; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: "Suggestions " - }, undefined, false, undefined, this); - $2[0] = t12; - } else { - t12 = $2[0]; - } - let t23; - if ($2[1] !== width) { - t23 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: width, - children: t12 - }, undefined, false, undefined, this); - $2[1] = width; - $2[2] = t23; - } else { - t23 = $2[2]; - } - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: "None" - }, undefined, false, undefined, this); - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] !== t23) { - t4 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - t23, - t32 - ] - }, undefined, true, undefined, this); - $2[4] = t23; - $2[5] = t4; - } else { - t4 = $2[5]; - } - return t4; - } - let t1; - let t22; - if ($2[6] !== suggestions || $2[7] !== width) { - t22 = Symbol.for("react.early_return_sentinel"); - bb0: { - const rules2 = extractRules(suggestions); - const directories = extractDirectories(suggestions); - const mode = extractMode(suggestions); - if (rules2.length === 0 && directories.length === 0 && !mode) { - let t33; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t33 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: "Suggestion " - }, undefined, false, undefined, this); - $2[10] = t33; - } else { - t33 = $2[10]; - } - let t42; - if ($2[11] !== width) { - t42 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: width, - children: t33 - }, undefined, false, undefined, this); - $2[11] = width; - $2[12] = t42; - } else { - t42 = $2[12]; - } - let t52; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t52 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: "None" - }, undefined, false, undefined, this); - $2[13] = t52; - } else { - t52 = $2[13]; - } - let t62; - if ($2[14] !== t42) { - t62 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - t42, - t52 - ] - }, undefined, true, undefined, this); - $2[14] = t42; - $2[15] = t62; - } else { - t62 = $2[15]; - } - t22 = t62; - break bb0; - } - let t32; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: "Suggestions " - }, undefined, false, undefined, this); - $2[16] = t32; - } else { - t32 = $2[16]; - } - let t4; - if ($2[17] !== width) { - t4 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: width, - children: t32 - }, undefined, false, undefined, this); - $2[17] = width; - $2[18] = t4; - } else { - t4 = $2[18]; - } - let t5; - if ($2[19] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - $2[19] = t5; - } else { - t5 = $2[19]; - } - let t6; - if ($2[20] !== t4) { - t6 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[20] = t4; - $2[21] = t6; - } else { - t6 = $2[21]; - } - t1 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t6, - rules2.length > 0 && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: width, - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: " Rules " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: rules2.map(_temp276) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - directories.length > 0 && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: width, - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: " Directories " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: directories.map(_temp350) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - mode && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: width, - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: " Mode " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: permissionModeTitle(mode) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - } - $2[6] = suggestions; - $2[7] = width; - $2[8] = t1; - $2[9] = t22; - } else { - t1 = $2[8]; - t22 = $2[9]; - } - if (t22 !== Symbol.for("react.early_return_sentinel")) { - return t22; - } - return t1; -} -function _temp350(dir, index_0) { - return /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: [ - figures_default.bullet, - " ", - dir - ] - }, index_0, true, undefined, this); -} -function _temp276(rule, index2) { - return /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: [ - figures_default.bullet, - " ", - permissionRuleValueToString(rule) - ] - }, index2, true, undefined, this); -} -function PermissionDecisionDebugInfo(t0) { - const $2 = import_compiler_runtime293.c(25); - const { - permissionResult, - toolName - } = t0; - const toolPermissionContext = useAppState(_temp437); - const decisionReason = permissionResult.decisionReason; - const suggestions = "suggestions" in permissionResult ? permissionResult.suggestions : undefined; - let t1; - if ($2[0] !== suggestions || $2[1] !== toolName || $2[2] !== toolPermissionContext) { - bb0: { - const sandboxAutoAllowEnabled = SandboxManager.isSandboxingEnabled() && SandboxManager.isAutoAllowBashIfSandboxedEnabled(); - const all4 = detectUnreachableRules(toolPermissionContext, { - sandboxAutoAllowEnabled - }); - const suggestedRules = extractRules(suggestions); - if (suggestedRules.length > 0) { - t1 = all4.filter((u5) => suggestedRules.some((suggested) => suggested.toolName === u5.rule.ruleValue.toolName && suggested.ruleContent === u5.rule.ruleValue.ruleContent)); - break bb0; - } - if (toolName) { - let t23; - if ($2[4] !== toolName) { - t23 = (u_0) => u_0.rule.ruleValue.toolName === toolName; - $2[4] = toolName; - $2[5] = t23; - } else { - t23 = $2[5]; - } - t1 = all4.filter(t23); - break bb0; - } - t1 = all4; - } - $2[0] = suggestions; - $2[1] = toolName; - $2[2] = toolPermissionContext; - $2[3] = t1; - } else { - t1 = $2[3]; - } - const unreachableRules = t1; - let t22; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: 10, - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: "Behavior " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[6] = t22; - } else { - t22 = $2[6]; - } - let t32; - if ($2[7] !== permissionResult.behavior) { - t32 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - t22, - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: permissionResult.behavior - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[7] = permissionResult.behavior; - $2[8] = t32; - } else { - t32 = $2[8]; - } - let t4; - if ($2[9] !== permissionResult.behavior || $2[10] !== permissionResult.message) { - t4 = permissionResult.behavior !== "allow" && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: 10, - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: "Message " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: permissionResult.message - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[9] = permissionResult.behavior; - $2[10] = permissionResult.message; - $2[11] = t4; - } else { - t4 = $2[11]; - } - let t5; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - minWidth: 10, - children: /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: "Reason " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[12] = t5; - } else { - t5 = $2[12]; - } - let t6; - if ($2[13] !== decisionReason) { - t6 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - t5, - decisionReason === undefined ? /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - children: "undefined" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(PermissionDecisionInfoItem, { - decisionReason - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[13] = decisionReason; - $2[14] = t6; - } else { - t6 = $2[14]; - } - let t7; - if ($2[15] !== suggestions) { - t7 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(SuggestionDisplay, { - suggestions, - width: 10 - }, undefined, false, undefined, this); - $2[15] = suggestions; - $2[16] = t7; - } else { - t7 = $2[16]; - } - let t8; - if ($2[17] !== unreachableRules) { - t8 = unreachableRules.length > 0 && /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - color: "warning", - children: [ - figures_default.warning, - " Unreachable Rules (", - unreachableRules.length, - ")" - ] - }, undefined, true, undefined, this), - unreachableRules.map(_temp527) - ] - }, undefined, true, undefined, this); - $2[17] = unreachableRules; - $2[18] = t8; - } else { - t8 = $2[18]; - } - let t9; - if ($2[19] !== t32 || $2[20] !== t4 || $2[21] !== t6 || $2[22] !== t7 || $2[23] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t32, - t4, - t6, - t7, - t8 - ] - }, undefined, true, undefined, this); - $2[19] = t32; - $2[20] = t4; - $2[21] = t6; - $2[22] = t7; - $2[23] = t8; - $2[24] = t9; - } else { - t9 = $2[24]; - } - return t9; -} -function _temp527(u_1, i6) { - return /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginLeft: 2, - children: [ - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - color: "warning", - children: permissionRuleValueToString(u_1.rule.ruleValue) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - u_1.reason - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime377.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "Fix: ", - u_1.fix - ] - }, undefined, true, undefined, this) - ] - }, i6, true, undefined, this); -} -function _temp437(s4) { - return s4.toolPermissionContext; -} -var import_compiler_runtime293, jsx_dev_runtime377; -var init_PermissionDecisionDebugInfo = __esm(() => { - init_source(); - init_figures(); - init_ink2(); - init_AppState(); - init_PermissionMode(); - init_PermissionUpdate(); - init_permissionRuleParser(); - init_shadowedRuleDetection(); - init_sandbox_adapter(); - init_constants2(); - import_compiler_runtime293 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime377 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/permissions/permissionExplainer.ts -function formatToolInput(input) { - if (typeof input === "string") { - return input; - } - try { - return jsonStringify(input, null, 2); - } catch { - return String(input); - } -} -function extractConversationContext(messages, maxChars = 1000) { - const assistantMessages = messages.filter((m4) => m4.type === "assistant").slice(-3); - const contextParts = []; - let totalChars = 0; - for (const msg of assistantMessages.reverse()) { - const textBlocks = msg.message.content.filter((c9) => c9.type === "text").map((c9) => ("text" in c9) ? c9.text : "").join(" "); - if (textBlocks && totalChars < maxChars) { - const remaining = maxChars - totalChars; - const truncated = textBlocks.length > remaining ? textBlocks.slice(0, remaining) + "..." : textBlocks; - contextParts.unshift(truncated); - totalChars += truncated.length; - } - } - return contextParts.join(` - -`); -} -function isPermissionExplainerEnabled() { - return getGlobalConfig().permissionExplainerEnabled !== false; -} -async function generatePermissionExplanation({ - toolName, - toolInput, - toolDescription, - messages, - signal -}) { - if (!isPermissionExplainerEnabled()) { - return null; - } - const startTime = Date.now(); - try { - const formattedInput = formatToolInput(toolInput); - const conversationContext = messages?.length ? extractConversationContext(messages) : ""; - const userPrompt = `Tool: ${toolName} -${toolDescription ? `Description: ${toolDescription} -` : ""} -Input: -${formattedInput} -${conversationContext ? ` -Recent conversation context: -${conversationContext}` : ""} - -Explain this command in context.`; - const model = getMainLoopModel(); - const response7 = await sideQuery({ - model, - system: SYSTEM_PROMPT, - messages: [{ role: "user", content: userPrompt }], - tools: [EXPLAIN_COMMAND_TOOL], - tool_choice: { type: "tool", name: "explain_command" }, - signal, - querySource: "permission_explainer" - }); - const latencyMs = Date.now() - startTime; - logForDebugging(`Permission explainer: API returned in ${latencyMs}ms, stop_reason=${response7.stop_reason}`); - const toolUseBlock = response7.content.find((c9) => c9.type === "tool_use"); - if (toolUseBlock && toolUseBlock.type === "tool_use") { - logForDebugging(`Permission explainer: tool input: ${jsonStringify(toolUseBlock.input).slice(0, 500)}`); - const result = RiskAssessmentSchema().safeParse(toolUseBlock.input); - if (result.success) { - const explanation = { - riskLevel: result.data.riskLevel, - explanation: result.data.explanation, - reasoning: result.data.reasoning, - risk: result.data.risk - }; - logEvent("tengu_permission_explainer_generated", { - tool_name: sanitizeToolNameForAnalytics(toolName), - risk_level: RISK_LEVEL_NUMERIC[explanation.riskLevel], - latency_ms: latencyMs - }); - logForDebugging(`Permission explainer: ${explanation.riskLevel} risk for ${toolName} (${latencyMs}ms)`); - return explanation; - } - } - logEvent("tengu_permission_explainer_error", { - tool_name: sanitizeToolNameForAnalytics(toolName), - error_type: ERROR_TYPE_PARSE, - latency_ms: latencyMs - }); - logForDebugging(`Permission explainer: no parsed output in response`); - return null; - } catch (error46) { - const latencyMs = Date.now() - startTime; - if (signal.aborted) { - logForDebugging(`Permission explainer: request aborted for ${toolName}`); - return null; - } - logForDebugging(`Permission explainer error: ${errorMessage(error46)}`); - logError2(error46); - logEvent("tengu_permission_explainer_error", { - tool_name: sanitizeToolNameForAnalytics(toolName), - error_type: error46 instanceof Error && error46.name === "AbortError" ? ERROR_TYPE_NETWORK : ERROR_TYPE_UNKNOWN2, - latency_ms: latencyMs - }); - return null; - } -} -var RISK_LEVEL_NUMERIC, ERROR_TYPE_PARSE = 1, ERROR_TYPE_NETWORK = 2, ERROR_TYPE_UNKNOWN2 = 3, SYSTEM_PROMPT = `Analyze shell commands and explain what they do, why you're running them, and potential risks.`, EXPLAIN_COMMAND_TOOL, RiskAssessmentSchema; -var init_permissionExplainer = __esm(() => { - init_v4(); - init_analytics(); - init_metadata(); - init_config(); - init_debug(); - init_errors(); - init_log2(); - init_model(); - init_sideQuery(); - init_slowOperations(); - RISK_LEVEL_NUMERIC = { - LOW: 1, - MEDIUM: 2, - HIGH: 3 - }; - EXPLAIN_COMMAND_TOOL = { - name: "explain_command", - description: "Provide an explanation of a shell command", - input_schema: { - type: "object", - properties: { - explanation: { - type: "string", - description: "What this command does (1-2 sentences)" - }, - reasoning: { - type: "string", - description: 'Why YOU are running this command. Start with "I" - e.g. "I need to check the file contents"' - }, - risk: { - type: "string", - description: "What could go wrong, under 15 words" - }, - riskLevel: { - type: "string", - enum: ["LOW", "MEDIUM", "HIGH"], - description: "LOW (safe dev workflows), MEDIUM (recoverable changes), HIGH (dangerous/irreversible)" - } - }, - required: ["explanation", "reasoning", "risk", "riskLevel"] - } - }; - RiskAssessmentSchema = lazySchema(() => exports_external.object({ - riskLevel: exports_external.enum(["LOW", "MEDIUM", "HIGH"]), - explanation: exports_external.string(), - reasoning: exports_external.string(), - risk: exports_external.string() - })); -}); - -// src/components/permissions/PermissionExplanation.tsx -function ShimmerLoadingText() { - const $2 = import_compiler_runtime294.c(7); - const [ref, glimmerIndex] = useShimmerAnimation("responding", LOADING_MESSAGE, false); - let t0; - if ($2[0] !== glimmerIndex) { - t0 = LOADING_MESSAGE.split("").map((char, index2) => /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ShimmerChar, { - char, - index: index2, - glimmerIndex, - messageColor: "inactive", - shimmerColor: "text" - }, index2, false, undefined, this)); - $2[0] = glimmerIndex; - $2[1] = t0; - } else { - t0 = $2[1]; - } - let t1; - if ($2[2] !== t0) { - t1 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - children: t0 - }, undefined, false, undefined, this); - $2[2] = t0; - $2[3] = t1; - } else { - t1 = $2[3]; - } - let t22; - if ($2[4] !== ref || $2[5] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedBox_default, { - ref, - children: t1 - }, undefined, false, undefined, this); - $2[4] = ref; - $2[5] = t1; - $2[6] = t22; - } else { - t22 = $2[6]; - } - return t22; -} -function getRiskColor(riskLevel) { - switch (riskLevel) { - case "LOW": - return "success"; - case "MEDIUM": - return "warning"; - case "HIGH": - return "error"; - } -} -function getRiskLabel(riskLevel) { - switch (riskLevel) { - case "LOW": - return "Low risk"; - case "MEDIUM": - return "Med risk"; - case "HIGH": - return "High risk"; - } -} -function createExplanationPromise(props) { - return generatePermissionExplanation({ - toolName: props.toolName, - toolInput: props.toolInput, - toolDescription: props.toolDescription, - messages: props.messages, - signal: new AbortController().signal - }).catch(() => null); -} -function usePermissionExplainerUI(props) { - const $2 = import_compiler_runtime294.c(9); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = isPermissionExplainerEnabled(); - $2[0] = t0; - } else { - t0 = $2[0]; - } - const enabled2 = t0; - const [visible, setVisible] = import_react208.useState(false); - const [promise3, setPromise] = import_react208.useState(null); - let t1; - if ($2[1] !== promise3 || $2[2] !== props || $2[3] !== visible) { - t1 = () => { - if (!visible) { - logEvent("tengu_permission_explainer_shortcut_used", {}); - if (!promise3) { - setPromise(createExplanationPromise(props)); - } - } - setVisible(_temp176); - }; - $2[1] = promise3; - $2[2] = props; - $2[3] = visible; - $2[4] = t1; - } else { - t1 = $2[4]; - } - let t22; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t22 = { - context: "Confirmation", - isActive: enabled2 - }; - $2[5] = t22; - } else { - t22 = $2[5]; - } - useKeybinding("confirm:toggleExplanation", t1, t22); - let t32; - if ($2[6] !== promise3 || $2[7] !== visible) { - t32 = { - visible, - enabled: enabled2, - promise: promise3 - }; - $2[6] = promise3; - $2[7] = visible; - $2[8] = t32; - } else { - t32 = $2[8]; - } - return t32; -} -function _temp176(v6) { - return !v6; -} -function ExplanationResult(t0) { - const $2 = import_compiler_runtime294.c(21); - const { - promise: promise3 - } = t0; - const explanation = import_react208.use(promise3); - if (!explanation) { - let t12; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - dimColor: true, - children: "Explanation unavailable" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = t12; - } else { - t12 = $2[0]; - } - return t12; - } - let t1; - if ($2[1] !== explanation.explanation) { - t1 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - children: explanation.explanation - }, undefined, false, undefined, this); - $2[1] = explanation.explanation; - $2[2] = t1; - } else { - t1 = $2[2]; - } - let t22; - if ($2[3] !== explanation.reasoning) { - t22 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - children: explanation.reasoning - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[3] = explanation.reasoning; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] !== explanation.riskLevel) { - t32 = getRiskColor(explanation.riskLevel); - $2[5] = explanation.riskLevel; - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] !== explanation.riskLevel) { - t4 = getRiskLabel(explanation.riskLevel); - $2[7] = explanation.riskLevel; - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] !== t32 || $2[10] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - color: t32, - children: [ - t4, - ":" - ] - }, undefined, true, undefined, this); - $2[9] = t32; - $2[10] = t4; - $2[11] = t5; - } else { - t5 = $2[11]; - } - let t6; - if ($2[12] !== explanation.risk) { - t6 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - children: [ - " ", - explanation.risk - ] - }, undefined, true, undefined, this); - $2[12] = explanation.risk; - $2[13] = t6; - } else { - t6 = $2[13]; - } - let t7; - if ($2[14] !== t5 || $2[15] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedText, { - children: [ - t5, - t6 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[14] = t5; - $2[15] = t6; - $2[16] = t7; - } else { - t7 = $2[16]; - } - let t8; - if ($2[17] !== t1 || $2[18] !== t22 || $2[19] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t1, - t22, - t7 - ] - }, undefined, true, undefined, this); - $2[17] = t1; - $2[18] = t22; - $2[19] = t7; - $2[20] = t8; - } else { - t8 = $2[20]; - } - return t8; -} -function PermissionExplainerContent(t0) { - const $2 = import_compiler_runtime294.c(3); - const { - visible, - promise: promise3 - } = t0; - if (!visible || !promise3) { - return null; - } - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ShimmerLoadingText, {}, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = t1; - } else { - t1 = $2[0]; - } - let t22; - if ($2[1] !== promise3) { - t22 = /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(import_react208.Suspense, { - fallback: t1, - children: /* @__PURE__ */ jsx_dev_runtime378.jsxDEV(ExplanationResult, { - promise: promise3 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[1] = promise3; - $2[2] = t22; - } else { - t22 = $2[2]; - } - return t22; -} -var import_compiler_runtime294, import_react208, jsx_dev_runtime378, LOADING_MESSAGE = "Loading explanation\u2026"; -var init_PermissionExplanation = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_analytics(); - init_permissionExplainer(); - init_ShimmerChar(); - init_useShimmerAnimation(); - import_compiler_runtime294 = __toESM(require_compiler_runtime(), 1); - import_react208 = __toESM(require_react(), 1); - jsx_dev_runtime378 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/FileEditToolDiff.tsx -function FileEditToolDiff(props) { - const $2 = import_compiler_runtime295.c(7); - let t0; - if ($2[0] !== props.edits || $2[1] !== props.file_path) { - t0 = () => loadDiffData(props.file_path, props.edits); - $2[0] = props.edits; - $2[1] = props.file_path; - $2[2] = t0; - } else { - t0 = $2[2]; - } - const [dataPromise] = import_react209.useState(t0); - let t1; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(DiffFrame, { - placeholder: true - }, undefined, false, undefined, this); - $2[3] = t1; - } else { - t1 = $2[3]; - } - let t22; - if ($2[4] !== dataPromise || $2[5] !== props.file_path) { - t22 = /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(import_react209.Suspense, { - fallback: t1, - children: /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(DiffBody, { - promise: dataPromise, - file_path: props.file_path - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[4] = dataPromise; - $2[5] = props.file_path; - $2[6] = t22; - } else { - t22 = $2[6]; - } - return t22; -} -function DiffBody(t0) { - const $2 = import_compiler_runtime295.c(6); - const { - promise: promise3, - file_path - } = t0; - const { - patch, - firstLine, - fileContent - } = import_react209.use(promise3); - const { - columns - } = useTerminalSize(); - let t1; - if ($2[0] !== columns || $2[1] !== fileContent || $2[2] !== file_path || $2[3] !== firstLine || $2[4] !== patch) { - t1 = /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(DiffFrame, { - children: /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(StructuredDiffList, { - hunks: patch, - dim: false, - width: columns, - filePath: file_path, - firstLine, - fileContent - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = columns; - $2[1] = fileContent; - $2[2] = file_path; - $2[3] = firstLine; - $2[4] = patch; - $2[5] = t1; - } else { - t1 = $2[5]; - } - return t1; -} -function DiffFrame(t0) { - const $2 = import_compiler_runtime295.c(5); - const { - children, - placeholder - } = t0; - let t1; - if ($2[0] !== children || $2[1] !== placeholder) { - t1 = placeholder ? /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(ThemedText, { - dimColor: true, - children: "\u2026" - }, undefined, false, undefined, this) : children; - $2[0] = children; - $2[1] = placeholder; - $2[2] = t1; - } else { - t1 = $2[2]; - } - let t22; - if ($2[3] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime379.jsxDEV(ThemedBox_default, { - borderColor: "subtle", - borderStyle: "dashed", - flexDirection: "column", - borderLeft: false, - borderRight: false, - children: t1 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[3] = t1; - $2[4] = t22; - } else { - t22 = $2[4]; - } - return t22; -} -async function loadDiffData(file_path, edits) { - const valid = edits.filter((e4) => e4.old_string != null && e4.new_string != null); - const single = valid.length === 1 ? valid[0] : undefined; - if (single && single.old_string.length >= CHUNK_SIZE) { - return diffToolInputsOnly(file_path, [single]); - } - try { - const handle = await openForScan(file_path); - if (handle === null) - return diffToolInputsOnly(file_path, valid); - try { - if (!single || single.old_string === "") { - const file2 = await readCapped(handle); - if (file2 === null) - return diffToolInputsOnly(file_path, valid); - const normalized2 = valid.map((e4) => normalizeEdit(file2, e4)); - return { - patch: getPatchForDisplay({ - filePath: file_path, - fileContents: file2, - edits: normalized2 - }), - firstLine: firstLineOf(file2), - fileContent: file2 - }; - } - const ctx = await scanForContext(handle, single.old_string, CONTEXT_LINES); - if (ctx.truncated || ctx.content === "") { - return diffToolInputsOnly(file_path, [single]); - } - const normalized = normalizeEdit(ctx.content, single); - const hunks = getPatchForDisplay({ - filePath: file_path, - fileContents: ctx.content, - edits: [normalized] - }); - return { - patch: adjustHunkLineNumbers(hunks, ctx.lineOffset - 1), - firstLine: ctx.lineOffset === 1 ? firstLineOf(ctx.content) : null, - fileContent: ctx.content - }; - } finally { - await handle.close(); - } - } catch (e4) { - logError2(e4); - return diffToolInputsOnly(file_path, valid); - } -} -function diffToolInputsOnly(filePath, edits) { - return { - patch: edits.flatMap((e4) => getPatchForDisplay({ - filePath, - fileContents: e4.old_string, - edits: [e4] - })), - firstLine: null, - fileContent: undefined - }; -} -function normalizeEdit(fileContent, edit2) { - const actualOld = findActualString(fileContent, edit2.old_string) || edit2.old_string; - const actualNew = preserveQuoteStyle(edit2.old_string, actualOld, edit2.new_string); - return { - ...edit2, - old_string: actualOld, - new_string: actualNew - }; -} -var import_compiler_runtime295, import_react209, jsx_dev_runtime379; -var init_FileEditToolDiff = __esm(() => { - init_useTerminalSize(); - init_ink2(); - init_utils9(); - init_diff2(); - init_log2(); - init_readEditContext(); - init_stringUtils(); - init_StructuredDiffList(); - import_compiler_runtime295 = __toESM(require_compiler_runtime(), 1); - import_react209 = __toESM(require_react(), 1); - jsx_dev_runtime379 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useDiffInIDE.ts -import { randomUUID as randomUUID36 } from "crypto"; -import { basename as basename45 } from "path"; -function useDiffInIDE({ - onChange, - toolUseContext, - filePath, - edits, - editMode -}) { - const isUnmounted = import_react210.useRef(false); - const [hasError, setHasError] = import_react210.useState(false); - const sha = import_react210.useMemo(() => randomUUID36().slice(0, 6), []); - const tabName = import_react210.useMemo(() => `\u273B [Claude Code] ${basename45(filePath)} (${sha}) \u29C9`, [filePath, sha]); - const shouldShowDiffInIDE = hasAccessToIDEExtensionDiffFeature(toolUseContext.options.mcpClients) && getGlobalConfig().diffTool === "auto" && !filePath.endsWith(".ipynb"); - const ideName = getConnectedIdeName(toolUseContext.options.mcpClients) ?? "IDE"; - async function showDiff() { - if (!shouldShowDiffInIDE) { - return; - } - try { - logEvent("tengu_ext_will_show_diff", {}); - const { oldContent, newContent } = await showDiffInIDE(filePath, edits, toolUseContext, tabName); - if (isUnmounted.current) { - return; - } - logEvent("tengu_ext_diff_accepted", {}); - const newEdits = computeEditsFromContents(filePath, oldContent, newContent, editMode); - if (newEdits.length === 0) { - logEvent("tengu_ext_diff_rejected", {}); - const ideClient = getConnectedIdeClient(toolUseContext.options.mcpClients); - if (ideClient) { - await closeTabInIDE(tabName, ideClient); - } - onChange({ type: "reject" }, { - file_path: filePath, - edits - }); - return; - } - onChange({ type: "accept-once" }, { - file_path: filePath, - edits: newEdits - }); - } catch (error46) { - logError2(error46); - setHasError(true); - } - } - import_react210.useEffect(() => { - showDiff(); - return () => { - isUnmounted.current = true; - }; - }, []); - return { - closeTabInIDE() { - const ideClient = getConnectedIdeClient(toolUseContext.options.mcpClients); - if (!ideClient) { - return Promise.resolve(); - } - return closeTabInIDE(tabName, ideClient); - }, - showingDiffInIDE: shouldShowDiffInIDE && !hasError, - ideName, - hasError - }; -} -function computeEditsFromContents(filePath, oldContent, newContent, editMode) { - const singleHunk = editMode === "single"; - const patch = getPatchFromContents({ - filePath, - oldContent, - newContent, - singleHunk - }); - if (patch.length === 0) { - return []; - } - if (singleHunk && patch.length > 1) { - logError2(new Error(`Unexpected number of hunks: ${patch.length}. Expected 1 hunk.`)); - } - return getEditsForPatch(patch); -} -async function showDiffInIDE(file_path, edits, toolUseContext, tabName) { - let isCleanedUp = false; - const oldFilePath = expandPath(file_path); - let oldContent = ""; - try { - oldContent = readFileSync4(oldFilePath); - } catch (e4) { - if (!isENOENT(e4)) { - throw e4; - } - } - async function cleanup() { - if (isCleanedUp) { - return; - } - isCleanedUp = true; - try { - await closeTabInIDE(tabName, ideClient); - } catch (e4) { - logError2(e4); - } - process.off("beforeExit", cleanup); - toolUseContext.abortController.signal.removeEventListener("abort", cleanup); - } - toolUseContext.abortController.signal.addEventListener("abort", cleanup); - process.on("beforeExit", cleanup); - const ideClient = getConnectedIdeClient(toolUseContext.options.mcpClients); - try { - const { updatedFile } = getPatchForEdits({ - filePath: oldFilePath, - fileContents: oldContent, - edits - }); - if (!ideClient || ideClient.type !== "connected") { - throw new Error("IDE client not available"); - } - let ideOldPath = oldFilePath; - const ideRunningInWindows = ideClient.config.ideRunningInWindows === true; - if (getPlatform() === "wsl" && ideRunningInWindows && process.env.WSL_DISTRO_NAME) { - const converter = new WindowsToWSLConverter(process.env.WSL_DISTRO_NAME); - ideOldPath = converter.toIDEPath(oldFilePath); - } - const rpcResult = await callIdeRpc("openDiff", { - old_file_path: ideOldPath, - new_file_path: ideOldPath, - new_file_contents: updatedFile, - tab_name: tabName - }, ideClient); - const data = Array.isArray(rpcResult) ? rpcResult : [rpcResult]; - if (isSaveMessage(data)) { - cleanup(); - return { - oldContent, - newContent: data[1].text - }; - } else if (isClosedMessage(data)) { - cleanup(); - return { - oldContent, - newContent: updatedFile - }; - } else if (isRejectedMessage(data)) { - cleanup(); - return { - oldContent, - newContent: oldContent - }; - } - throw new Error("Not accepted"); - } catch (error46) { - logError2(error46); - cleanup(); - throw error46; - } -} -async function closeTabInIDE(tabName, ideClient) { - try { - if (!ideClient || ideClient.type !== "connected") { - throw new Error("IDE client not available"); - } - await callIdeRpc("close_tab", { tab_name: tabName }, ideClient); - } catch (error46) { - logError2(error46); - } -} -function isClosedMessage(data) { - return Array.isArray(data) && typeof data[0] === "object" && data[0] !== null && "type" in data[0] && data[0].type === "text" && "text" in data[0] && data[0].text === "TAB_CLOSED"; -} -function isRejectedMessage(data) { - return Array.isArray(data) && typeof data[0] === "object" && data[0] !== null && "type" in data[0] && data[0].type === "text" && "text" in data[0] && data[0].text === "DIFF_REJECTED"; -} -function isSaveMessage(data) { - return Array.isArray(data) && data[0]?.type === "text" && data[0].text === "FILE_SAVED" && typeof data[1].text === "string"; -} -var import_react210; -var init_useDiffInIDE = __esm(() => { - init_analytics(); - init_fileRead(); - init_path(); - init_utils9(); - init_config(); - init_diff2(); - init_errors(); - init_ide(); - init_idePathConversion(); - init_log2(); - init_platform2(); - import_react210 = __toESM(require_react(), 1); -}); - -// src/components/ShowInIDEPrompt.tsx -import { basename as basename46, relative as relative29 } from "path"; -function ShowInIDEPrompt(t0) { - const $2 = import_compiler_runtime296.c(36); - const { - onChange, - options: options2, - input, - filePath, - ideName, - symlinkTarget, - rejectFeedback, - acceptFeedback, - setFocusedOption, - onInputModeToggle, - focusedOption, - yesInputMode, - noInputMode - } = t0; - let t1; - if ($2[0] !== ideName) { - t1 = /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: [ - "Opened changes in ", - ideName, - " \u29C9" - ] - }, undefined, true, undefined, this); - $2[0] = ideName; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== symlinkTarget) { - t22 = symlinkTarget && /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedText, { - color: "warning", - children: relative29(getCwd(), symlinkTarget).startsWith("..") ? `This will modify ${symlinkTarget} (outside working directory) via a symlink` : `Symlink target: ${symlinkTarget}` - }, undefined, false, undefined, this); - $2[2] = symlinkTarget; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = isSupportedVSCodeTerminal() && /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedText, { - dimColor: true, - children: "Save file to continue\u2026" - }, undefined, false, undefined, this); - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== filePath) { - t4 = basename46(filePath); - $2[5] = filePath; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedText, { - children: [ - "Do you want to make this edit to", - " ", - /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedText, { - bold: true, - children: t4 - }, undefined, false, undefined, this), - "?" - ] - }, undefined, true, undefined, this); - $2[7] = t4; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== acceptFeedback || $2[10] !== input || $2[11] !== onChange || $2[12] !== options2 || $2[13] !== rejectFeedback) { - t6 = (value) => { - const selected = options2.find((opt) => opt.value === value); - if (selected) { - if (selected.option.type === "reject") { - const trimmedFeedback = rejectFeedback.trim(); - onChange(selected.option, input, trimmedFeedback || undefined); - return; - } - if (selected.option.type === "accept-once") { - const trimmedFeedback_0 = acceptFeedback.trim(); - onChange(selected.option, input, trimmedFeedback_0 || undefined); - return; - } - onChange(selected.option, input); - } - }; - $2[9] = acceptFeedback; - $2[10] = input; - $2[11] = onChange; - $2[12] = options2; - $2[13] = rejectFeedback; - $2[14] = t6; - } else { - t6 = $2[14]; - } - let t7; - if ($2[15] !== input || $2[16] !== onChange) { - t7 = () => onChange({ - type: "reject" - }, input); - $2[15] = input; - $2[16] = onChange; - $2[17] = t7; - } else { - t7 = $2[17]; - } - let t8; - if ($2[18] !== setFocusedOption) { - t8 = (value_0) => setFocusedOption(value_0); - $2[18] = setFocusedOption; - $2[19] = t8; - } else { - t8 = $2[19]; - } - let t9; - if ($2[20] !== onInputModeToggle || $2[21] !== options2 || $2[22] !== t6 || $2[23] !== t7 || $2[24] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(Select, { - options: options2, - inlineDescriptions: true, - onChange: t6, - onCancel: t7, - onFocus: t8, - onInputModeToggle - }, undefined, false, undefined, this); - $2[20] = onInputModeToggle; - $2[21] = options2; - $2[22] = t6; - $2[23] = t7; - $2[24] = t8; - $2[25] = t9; - } else { - t9 = $2[25]; - } - let t10; - if ($2[26] !== t5 || $2[27] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t5, - t9 - ] - }, undefined, true, undefined, this); - $2[26] = t5; - $2[27] = t9; - $2[28] = t10; - } else { - t10 = $2[28]; - } - const t11 = (focusedOption === "yes" && !yesInputMode || focusedOption === "no" && !noInputMode) && " \xB7 Tab to amend"; - let t12; - if ($2[29] !== t11) { - t12 = /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Esc to cancel", - t11 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[29] = t11; - $2[30] = t12; - } else { - t12 = $2[30]; - } - let t13; - if ($2[31] !== t1 || $2[32] !== t10 || $2[33] !== t12 || $2[34] !== t22) { - t13 = /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(Pane, { - color: "permission", - children: /* @__PURE__ */ jsx_dev_runtime380.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t1, - t22, - t32, - t10, - t12 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[31] = t1; - $2[32] = t10; - $2[33] = t12; - $2[34] = t22; - $2[35] = t13; - } else { - t13 = $2[35]; - } - return t13; -} -var import_compiler_runtime296, jsx_dev_runtime380; -var init_ShowInIDEPrompt = __esm(() => { - init_ink2(); - init_cwd(); - init_ide(); - init_CustomSelect(); - init_Pane(); - import_compiler_runtime296 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime380 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/FilePermissionDialog/permissionOptions.tsx -import { homedir as homedir34 } from "os"; -import { basename as basename47, join as join143, sep as sep36 } from "path"; -function isInClaudeFolder(filePath) { - const absolutePath = expandPath(filePath); - const claudeFolderPath = expandPath(`${getOriginalCwd()}/.claude`); - const normalizedAbsolutePath = normalizeCaseForComparison(absolutePath); - const normalizedClaudeFolderPath = normalizeCaseForComparison(claudeFolderPath); - return normalizedAbsolutePath.startsWith(normalizedClaudeFolderPath + sep36.toLowerCase()) || normalizedAbsolutePath.startsWith(normalizedClaudeFolderPath + "/"); -} -function isInGlobalClaudeFolder(filePath) { - const absolutePath = expandPath(filePath); - const globalClaudeFolderPath = join143(homedir34(), ".claude"); - const normalizedAbsolutePath = normalizeCaseForComparison(absolutePath); - const normalizedGlobalClaudeFolderPath = normalizeCaseForComparison(globalClaudeFolderPath); - return normalizedAbsolutePath.startsWith(normalizedGlobalClaudeFolderPath + sep36.toLowerCase()) || normalizedAbsolutePath.startsWith(normalizedGlobalClaudeFolderPath + "/"); -} -function getFilePermissionOptions({ - filePath, - toolPermissionContext, - operationType = "write", - onRejectFeedbackChange, - onAcceptFeedbackChange, - yesInputMode = false, - noInputMode = false -}) { - const options2 = []; - const modeCycleShortcut = getShortcutDisplay("chat:cycleMode", "Chat", "shift+tab"); - if (yesInputMode && onAcceptFeedbackChange) { - options2.push({ - type: "input", - label: "Yes", - value: "yes", - placeholder: "and tell Claude what to do next", - onChange: onAcceptFeedbackChange, - allowEmptySubmitToCancel: true, - option: { - type: "accept-once" - } - }); - } else { - options2.push({ - label: "Yes", - value: "yes", - option: { - type: "accept-once" - } - }); - } - const inAllowedPath = pathInAllowedWorkingPath(filePath, toolPermissionContext); - const inClaudeFolder = isInClaudeFolder(filePath); - const inGlobalClaudeFolder = isInGlobalClaudeFolder(filePath); - if ((inClaudeFolder || inGlobalClaudeFolder) && operationType !== "read") { - options2.push({ - label: "Yes, and allow Claude to edit its own settings for this session", - value: "yes-claude-folder", - option: { - type: "accept-session", - scope: inGlobalClaudeFolder ? "global-claude-folder" : "claude-folder" - } - }); - } else { - let sessionLabel; - if (inAllowedPath) { - if (operationType === "read") { - sessionLabel = "Yes, during this session"; - } else { - sessionLabel = /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - children: [ - "Yes, allow all edits during this session", - " ", - /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - bold: true, - children: [ - "(", - modeCycleShortcut, - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - } - } else { - const dirPath = getDirectoryForPath(filePath); - const dirName = basename47(dirPath) || "this directory"; - if (operationType === "read") { - sessionLabel = /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - children: [ - "Yes, allow reading from ", - /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - bold: true, - children: [ - dirName, - "/" - ] - }, undefined, true, undefined, this), - " during this session" - ] - }, undefined, true, undefined, this); - } else { - sessionLabel = /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - children: [ - "Yes, allow all edits in ", - /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - bold: true, - children: [ - dirName, - "/" - ] - }, undefined, true, undefined, this), - " during this session ", - /* @__PURE__ */ jsx_dev_runtime381.jsxDEV(ThemedText, { - bold: true, - children: [ - "(", - modeCycleShortcut, - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - } - } - options2.push({ - label: sessionLabel, - value: "yes-session", - option: { - type: "accept-session" - } - }); - } - if (noInputMode && onRejectFeedbackChange) { - options2.push({ - type: "input", - label: "No", - value: "no", - placeholder: "and tell Claude what to do differently", - onChange: onRejectFeedbackChange, - allowEmptySubmitToCancel: true, - option: { - type: "reject" - } - }); - } else { - options2.push({ - label: "No", - value: "no", - option: { - type: "reject" - } - }); - } - return options2; -} -var jsx_dev_runtime381; -var init_permissionOptions = __esm(() => { - init_state(); - init_ink2(); - init_shortcutFormat(); - init_path(); - init_filesystem(); - jsx_dev_runtime381 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/FilePermissionDialog/usePermissionHandler.ts -function logPermissionEvent(event, completionType, languageName, messageId, hasFeedback) { - logUnaryEvent({ - completion_type: completionType, - event, - metadata: { - language_name: languageName, - message_id: messageId, - platform: env2.platform, - hasFeedback: hasFeedback ?? false - } - }); -} -function handleAcceptOnce(params, options2) { - const { messageId, toolUseConfirm, onDone, completionType, languageName } = params; - logPermissionEvent("accept", completionType, languageName, messageId); - logEvent("tengu_accept_submitted", { - toolName: sanitizeToolNameForAnalytics(toolUseConfirm.tool.name), - isMcp: toolUseConfirm.tool.isMcp ?? false, - has_instructions: !!options2?.feedback, - instructions_length: options2?.feedback?.length ?? 0, - entered_feedback_mode: options2?.enteredFeedbackMode ?? false - }); - onDone(); - toolUseConfirm.onAllow(toolUseConfirm.input, [], options2?.feedback); -} -function handleAcceptSession(params, options2) { - const { - messageId, - path: path26, - toolUseConfirm, - toolPermissionContext, - onDone, - completionType, - languageName, - operationType - } = params; - logPermissionEvent("accept", completionType, languageName, messageId); - if (options2?.scope === "claude-folder" || options2?.scope === "global-claude-folder") { - const pattern = options2.scope === "global-claude-folder" ? GLOBAL_CLAUDE_FOLDER_PERMISSION_PATTERN : CLAUDE_FOLDER_PERMISSION_PATTERN; - const suggestions2 = [ - { - type: "addRules", - rules: [ - { - toolName: FILE_EDIT_TOOL_NAME, - ruleContent: pattern - } - ], - behavior: "allow", - destination: "session" - } - ]; - onDone(); - toolUseConfirm.onAllow(toolUseConfirm.input, suggestions2); - return; - } - const suggestions = path26 ? generateSuggestions(path26, operationType, toolPermissionContext) : []; - onDone(); - toolUseConfirm.onAllow(toolUseConfirm.input, suggestions); -} -function handleReject(params, options2) { - const { - messageId, - toolUseConfirm, - onDone, - onReject, - completionType, - languageName - } = params; - logPermissionEvent("reject", completionType, languageName, messageId, options2?.hasFeedback); - logEvent("tengu_reject_submitted", { - toolName: sanitizeToolNameForAnalytics(toolUseConfirm.tool.name), - isMcp: toolUseConfirm.tool.isMcp ?? false, - has_instructions: !!options2?.feedback, - instructions_length: options2?.feedback?.length ?? 0, - entered_feedback_mode: options2?.enteredFeedbackMode ?? false - }); - onDone(); - onReject(); - toolUseConfirm.onReject(options2?.feedback); -} -var PERMISSION_HANDLERS; -var init_usePermissionHandler = __esm(() => { - init_analytics(); - init_metadata(); - init_env(); - init_filesystem(); - init_unaryLogging(); - PERMISSION_HANDLERS = { - "accept-once": handleAcceptOnce, - "accept-session": handleAcceptSession, - reject: handleReject - }; -}); - -// src/components/permissions/FilePermissionDialog/useFilePermissionDialog.ts -function useFilePermissionDialog({ - filePath, - completionType, - languageName, - toolUseConfirm, - onDone, - onReject, - parseInput, - operationType = "write" -}) { - const toolPermissionContext = useAppState((s4) => s4.toolPermissionContext); - const [acceptFeedback, setAcceptFeedback] = import_react211.useState(""); - const [rejectFeedback, setRejectFeedback] = import_react211.useState(""); - const [focusedOption, setFocusedOption] = import_react211.useState("yes"); - const [yesInputMode, setYesInputMode] = import_react211.useState(false); - const [noInputMode, setNoInputMode] = import_react211.useState(false); - const [yesFeedbackModeEntered, setYesFeedbackModeEntered] = import_react211.useState(false); - const [noFeedbackModeEntered, setNoFeedbackModeEntered] = import_react211.useState(false); - const options2 = import_react211.useMemo(() => getFilePermissionOptions({ - filePath, - toolPermissionContext, - operationType, - onRejectFeedbackChange: setRejectFeedback, - onAcceptFeedbackChange: setAcceptFeedback, - yesInputMode, - noInputMode - }), [filePath, toolPermissionContext, operationType, yesInputMode, noInputMode]); - const onChange = import_react211.useCallback((option, input, feedback2) => { - const params = { - messageId: toolUseConfirm.assistantMessage.message.id, - path: filePath, - toolUseConfirm, - toolPermissionContext, - onDone, - onReject, - completionType, - languageName, - operationType - }; - const originalOnAllow = toolUseConfirm.onAllow; - toolUseConfirm.onAllow = (_input, permissionUpdates, feedback3) => { - originalOnAllow(input, permissionUpdates, feedback3); - }; - const handler = PERMISSION_HANDLERS[option.type]; - handler(params, { - feedback: feedback2, - hasFeedback: !!feedback2, - enteredFeedbackMode: option.type === "accept-once" ? yesFeedbackModeEntered : noFeedbackModeEntered, - scope: option.type === "accept-session" ? option.scope : undefined - }); - }, [ - filePath, - completionType, - languageName, - toolUseConfirm, - toolPermissionContext, - onDone, - onReject, - operationType, - yesFeedbackModeEntered, - noFeedbackModeEntered - ]); - const handleCycleMode = import_react211.useCallback(() => { - const sessionOption = options2.find((o5) => o5.option.type === "accept-session"); - if (sessionOption) { - const parsedInput = parseInput(toolUseConfirm.input); - onChange(sessionOption.option, parsedInput); - } - }, [options2, parseInput, toolUseConfirm.input, onChange]); - useKeybindings({ "confirm:cycleMode": handleCycleMode }, { context: "Confirmation" }); - const handleFocusedOptionChange = import_react211.useCallback((value) => { - if (value !== "yes" && yesInputMode && !acceptFeedback.trim()) { - setYesInputMode(false); - } - if (value !== "no" && noInputMode && !rejectFeedback.trim()) { - setNoInputMode(false); - } - setFocusedOption(value); - }, [yesInputMode, noInputMode, acceptFeedback, rejectFeedback]); - const handleInputModeToggle = import_react211.useCallback((value) => { - const analyticsProps = { - toolName: sanitizeToolNameForAnalytics(toolUseConfirm.tool.name), - isMcp: toolUseConfirm.tool.isMcp ?? false - }; - if (value === "yes") { - if (yesInputMode) { - setYesInputMode(false); - logEvent("tengu_accept_feedback_mode_collapsed", analyticsProps); - } else { - setYesInputMode(true); - setYesFeedbackModeEntered(true); - logEvent("tengu_accept_feedback_mode_entered", analyticsProps); - } - } else if (value === "no") { - if (noInputMode) { - setNoInputMode(false); - logEvent("tengu_reject_feedback_mode_collapsed", analyticsProps); - } else { - setNoInputMode(true); - setNoFeedbackModeEntered(true); - logEvent("tengu_reject_feedback_mode_entered", analyticsProps); - } - } - }, [yesInputMode, noInputMode, toolUseConfirm]); - return { - options: options2, - onChange, - acceptFeedback, - rejectFeedback, - focusedOption, - setFocusedOption: handleFocusedOptionChange, - handleInputModeToggle, - yesInputMode, - noInputMode - }; -} -var import_react211; -var init_useFilePermissionDialog = __esm(() => { - init_AppState(); - init_useKeybinding(); - init_analytics(); - init_metadata(); - init_permissionOptions(); - init_usePermissionHandler(); - import_react211 = __toESM(require_react(), 1); -}); - -// src/components/permissions/FilePermissionDialog/FilePermissionDialog.tsx -import { relative as relative30 } from "path"; -function FilePermissionDialog({ - toolUseConfirm, - toolUseContext, - onDone, - onReject, - title, - subtitle, - question = "Do you want to proceed?", - content, - completionType = "tool_use_single", - path: path26, - parseInput, - operationType = "write", - ideDiffSupport, - workerBadge, - languageName: languageNameOverride -}) { - const languageName = import_react212.useMemo(() => languageNameOverride ?? (path26 ? getLanguageName(path26) : "none"), [languageNameOverride, path26]); - const unaryEvent = import_react212.useMemo(() => ({ - completion_type: completionType, - language_name: languageName - }), [completionType, languageName]); - usePermissionRequestLogging(toolUseConfirm, unaryEvent); - const symlinkTarget = import_react212.useMemo(() => { - if (!path26 || operationType === "read") { - return null; - } - const expandedPath = expandPath(path26); - const fs13 = getFsImplementation(); - const { - resolvedPath: resolvedPath5, - isSymlink - } = safeResolvePath(fs13, expandedPath); - if (isSymlink) { - return resolvedPath5; - } - return null; - }, [path26, operationType]); - const fileDialogResult = useFilePermissionDialog({ - filePath: path26 || "", - completionType, - languageName, - toolUseConfirm, - onDone, - onReject, - parseInput, - operationType - }); - const { - options: options2, - acceptFeedback, - rejectFeedback, - setFocusedOption, - handleInputModeToggle, - focusedOption, - yesInputMode, - noInputMode - } = fileDialogResult; - const parsedInput = parseInput(toolUseConfirm.input); - const ideDiffConfig = import_react212.useMemo(() => ideDiffSupport ? ideDiffSupport.getConfig(parseInput(toolUseConfirm.input)) : null, [ideDiffSupport, toolUseConfirm.input]); - const diffParams = ideDiffConfig ? { - onChange: (option, input) => { - const transformedInput = ideDiffSupport.applyChanges(parsedInput, input.edits); - fileDialogResult.onChange(option, transformedInput); - }, - toolUseContext, - filePath: ideDiffConfig.filePath, - edits: (ideDiffConfig.edits || []).map((e4) => ({ - old_string: e4.old_string, - new_string: e4.new_string, - replace_all: e4.replace_all || false - })), - editMode: ideDiffConfig.editMode || "single" - } : { - onChange: () => {}, - toolUseContext, - filePath: "", - edits: [], - editMode: "single" - }; - const { - closeTabInIDE: closeTabInIDE2, - showingDiffInIDE, - ideName - } = useDiffInIDE(diffParams); - const onChange = (option_0, feedback2) => { - closeTabInIDE2?.(); - fileDialogResult.onChange(option_0, parsedInput, feedback2?.trim()); - }; - if (showingDiffInIDE && ideDiffConfig && path26) { - return /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ShowInIDEPrompt, { - onChange: (option_1, _input, feedback_0) => onChange(option_1, feedback_0), - options: options2, - filePath: path26, - input: parsedInput, - ideName, - symlinkTarget, - rejectFeedback, - acceptFeedback, - setFocusedOption, - onInputModeToggle: handleInputModeToggle, - focusedOption, - yesInputMode, - noInputMode - }, undefined, false, undefined, this); - } - const isSymlinkOutsideCwd = symlinkTarget != null && relative30(getCwd(), symlinkTarget).startsWith(".."); - const symlinkWarning = symlinkTarget ? /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ThemedBox_default, { - paddingX: 1, - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ThemedText, { - color: "warning", - children: isSymlinkOutsideCwd ? `This will modify ${symlinkTarget} (outside working directory) via a symlink` : `Symlink target: ${symlinkTarget}` - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : null; - return /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(jsx_dev_runtime382.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(PermissionDialog, { - title, - subtitle, - innerPaddingX: 0, - workerBadge, - children: [ - symlinkWarning, - content, - /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 1, - children: [ - typeof question === "string" ? /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ThemedText, { - children: question - }, undefined, false, undefined, this) : question, - /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(Select, { - options: options2, - inlineDescriptions: true, - onChange: (value) => { - const selected = options2.find((opt) => opt.value === value); - if (selected) { - if (selected.option.type === "reject") { - const trimmedFeedback = rejectFeedback.trim(); - onChange(selected.option, trimmedFeedback || undefined); - return; - } - if (selected.option.type === "accept-once") { - const trimmedFeedback_0 = acceptFeedback.trim(); - onChange(selected.option, trimmedFeedback_0 || undefined); - return; - } - onChange(selected.option); - } - }, - onCancel: () => onChange({ - type: "reject" - }), - onFocus: (value_0) => setFocusedOption(value_0), - onInputModeToggle: handleInputModeToggle - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ThemedBox_default, { - paddingX: 1, - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime382.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Esc to cancel", - (focusedOption === "yes" && !yesInputMode || focusedOption === "no" && !noInputMode) && " \xB7 Tab to amend" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_react212, jsx_dev_runtime382; -var init_FilePermissionDialog = __esm(() => { - init_useDiffInIDE(); - init_ink2(); - init_cliHighlight(); - init_cwd(); - init_fsOperations(); - init_path(); - init_CustomSelect(); - init_ShowInIDEPrompt(); - init_hooks6(); - init_PermissionDialog(); - init_useFilePermissionDialog(); - import_react212 = __toESM(require_react(), 1); - jsx_dev_runtime382 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.tsx -import { basename as basename48, relative as relative31 } from "path"; -function SedEditPermissionRequest(t0) { - const $2 = import_compiler_runtime297.c(9); - let props; - let sedInfo; - if ($2[0] !== t0) { - ({ - sedInfo, - ...props - } = t0); - $2[0] = t0; - $2[1] = props; - $2[2] = sedInfo; - } else { - props = $2[1]; - sedInfo = $2[2]; - } - const { - filePath - } = sedInfo; - let t1; - if ($2[3] !== filePath) { - t1 = (async () => { - const encoding = detectEncodingForResolvedPath(filePath); - const raw = await getFsImplementation().readFile(filePath, { - encoding - }); - return { - oldContent: raw.replaceAll(`\r -`, ` -`), - fileExists: true - }; - })().catch(_temp177); - $2[3] = filePath; - $2[4] = t1; - } else { - t1 = $2[4]; - } - const contentPromise = t1; - let t22; - if ($2[5] !== contentPromise || $2[6] !== props || $2[7] !== sedInfo) { - t22 = /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(import_react213.Suspense, { - fallback: null, - children: /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(SedEditPermissionRequestInner, { - sedInfo, - contentPromise, - ...props - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[5] = contentPromise; - $2[6] = props; - $2[7] = sedInfo; - $2[8] = t22; - } else { - t22 = $2[8]; - } - return t22; -} -function _temp177(e4) { - if (!isENOENT(e4)) { - throw e4; - } - return { - oldContent: "", - fileExists: false - }; -} -function SedEditPermissionRequestInner(t0) { - const $2 = import_compiler_runtime297.c(35); - let contentPromise; - let props; - let sedInfo; - if ($2[0] !== t0) { - ({ - sedInfo, - contentPromise, - ...props - } = t0); - $2[0] = t0; - $2[1] = contentPromise; - $2[2] = props; - $2[3] = sedInfo; - } else { - contentPromise = $2[1]; - props = $2[2]; - sedInfo = $2[3]; - } - const { - filePath - } = sedInfo; - const { - oldContent, - fileExists - } = import_react213.use(contentPromise); - let t1; - if ($2[4] !== oldContent || $2[5] !== sedInfo) { - t1 = applySedSubstitution(oldContent, sedInfo); - $2[4] = oldContent; - $2[5] = sedInfo; - $2[6] = t1; - } else { - t1 = $2[6]; - } - const newContent = t1; - let t22; - bb0: { - if (oldContent === newContent) { - let t34; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t34 = []; - $2[7] = t34; - } else { - t34 = $2[7]; - } - t22 = t34; - break bb0; - } - let t33; - if ($2[8] !== newContent || $2[9] !== oldContent) { - t33 = [{ - old_string: oldContent, - new_string: newContent, - replace_all: false - }]; - $2[8] = newContent; - $2[9] = oldContent; - $2[10] = t33; - } else { - t33 = $2[10]; - } - t22 = t33; - } - const edits = t22; - let t32; - bb1: { - if (!fileExists) { - t32 = "File does not exist"; - break bb1; - } - t32 = "Pattern did not match any content"; - } - const noChangesMessage = t32; - let t4; - if ($2[11] !== filePath || $2[12] !== newContent) { - t4 = (input) => { - const parsed = BashTool.inputSchema.parse(input); - return { - ...parsed, - _simulatedSedEdit: { - filePath, - newContent - } - }; - }; - $2[11] = filePath; - $2[12] = newContent; - $2[13] = t4; - } else { - t4 = $2[13]; - } - const parseInput = t4; - const t5 = props.toolUseConfirm; - const t6 = props.toolUseContext; - const t7 = props.onDone; - const t8 = props.onReject; - let t9; - if ($2[14] !== filePath) { - t9 = relative31(getCwd(), filePath); - $2[14] = filePath; - $2[15] = t9; - } else { - t9 = $2[15]; - } - let t10; - if ($2[16] !== filePath) { - t10 = basename48(filePath); - $2[16] = filePath; - $2[17] = t10; - } else { - t10 = $2[17]; - } - let t11; - if ($2[18] !== t10) { - t11 = /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(ThemedText, { - children: [ - "Do you want to make this edit to", - " ", - /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(ThemedText, { - bold: true, - children: t10 - }, undefined, false, undefined, this), - "?" - ] - }, undefined, true, undefined, this); - $2[18] = t10; - $2[19] = t11; - } else { - t11 = $2[19]; - } - let t12; - if ($2[20] !== edits || $2[21] !== filePath || $2[22] !== noChangesMessage) { - t12 = edits.length > 0 ? /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(FileEditToolDiff, { - file_path: filePath, - edits - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(ThemedText, { - dimColor: true, - children: noChangesMessage - }, undefined, false, undefined, this); - $2[20] = edits; - $2[21] = filePath; - $2[22] = noChangesMessage; - $2[23] = t12; - } else { - t12 = $2[23]; - } - let t13; - if ($2[24] !== filePath || $2[25] !== parseInput || $2[26] !== props.onDone || $2[27] !== props.onReject || $2[28] !== props.toolUseConfirm || $2[29] !== props.toolUseContext || $2[30] !== props.workerBadge || $2[31] !== t11 || $2[32] !== t12 || $2[33] !== t9) { - t13 = /* @__PURE__ */ jsx_dev_runtime383.jsxDEV(FilePermissionDialog, { - toolUseConfirm: t5, - toolUseContext: t6, - onDone: t7, - onReject: t8, - title: "Edit file", - subtitle: t9, - question: t11, - content: t12, - path: filePath, - completionType: "str_replace_single", - parseInput, - workerBadge: props.workerBadge - }, undefined, false, undefined, this); - $2[24] = filePath; - $2[25] = parseInput; - $2[26] = props.onDone; - $2[27] = props.onReject; - $2[28] = props.toolUseConfirm; - $2[29] = props.toolUseContext; - $2[30] = props.workerBadge; - $2[31] = t11; - $2[32] = t12; - $2[33] = t9; - $2[34] = t13; - } else { - t13 = $2[34]; - } - return t13; -} -var import_compiler_runtime297, import_react213, jsx_dev_runtime383; -var init_SedEditPermissionRequest = __esm(() => { - init_FileEditToolDiff(); - init_cwd(); - init_errors(); - init_fileRead(); - init_fsOperations(); - init_ink2(); - init_BashTool(); - init_sedEditParser(); - init_FilePermissionDialog(); - import_compiler_runtime297 = __toESM(require_compiler_runtime(), 1); - import_react213 = __toESM(require_react(), 1); - jsx_dev_runtime383 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/utils.ts -function logUnaryPermissionEvent(completion_type, { - assistantMessage: { - message: { id: message_id } - } -}, event, hasFeedback) { - logUnaryEvent({ - completion_type, - event, - metadata: { - language_name: "none", - message_id, - platform: getHostPlatformForAnalytics(), - hasFeedback: hasFeedback ?? false - } - }); -} -var init_utils16 = __esm(() => { - init_env(); - init_unaryLogging(); -}); - -// src/components/permissions/useShellPermissionFeedback.ts -function useShellPermissionFeedback({ - toolUseConfirm, - onDone, - onReject, - explainerVisible -}) { - const setAppState = useSetAppState(); - const [rejectFeedback, setRejectFeedback] = import_react214.useState(""); - const [acceptFeedback, setAcceptFeedback] = import_react214.useState(""); - const [yesInputMode, setYesInputMode] = import_react214.useState(false); - const [noInputMode, setNoInputMode] = import_react214.useState(false); - const [focusedOption, setFocusedOption] = import_react214.useState("yes"); - const [yesFeedbackModeEntered, setYesFeedbackModeEntered] = import_react214.useState(false); - const [noFeedbackModeEntered, setNoFeedbackModeEntered] = import_react214.useState(false); - function handleInputModeToggle(option) { - toolUseConfirm.onUserInteraction(); - const analyticsProps = { - toolName: sanitizeToolNameForAnalytics(toolUseConfirm.tool.name), - isMcp: toolUseConfirm.tool.isMcp ?? false - }; - if (option === "yes") { - if (yesInputMode) { - setYesInputMode(false); - logEvent("tengu_accept_feedback_mode_collapsed", analyticsProps); - } else { - setYesInputMode(true); - setYesFeedbackModeEntered(true); - logEvent("tengu_accept_feedback_mode_entered", analyticsProps); - } - } else if (option === "no") { - if (noInputMode) { - setNoInputMode(false); - logEvent("tengu_reject_feedback_mode_collapsed", analyticsProps); - } else { - setNoInputMode(true); - setNoFeedbackModeEntered(true); - logEvent("tengu_reject_feedback_mode_entered", analyticsProps); - } - } - } - function handleReject2(feedback2) { - const trimmedFeedback = feedback2?.trim(); - const hasFeedback = !!trimmedFeedback; - if (!hasFeedback) { - logEvent("tengu_permission_request_escape", { - explainer_visible: explainerVisible - }); - setAppState((prev) => ({ - ...prev, - attribution: { - ...prev.attribution, - escapeCount: prev.attribution.escapeCount + 1 - } - })); - } - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "reject", hasFeedback); - if (trimmedFeedback) { - toolUseConfirm.onReject(trimmedFeedback); - } else { - toolUseConfirm.onReject(); - } - onReject(); - onDone(); - } - function handleFocus(value) { - if (value !== focusedOption) { - toolUseConfirm.onUserInteraction(); - } - if (value !== "yes" && yesInputMode && !acceptFeedback.trim()) { - setYesInputMode(false); - } - if (value !== "no" && noInputMode && !rejectFeedback.trim()) { - setNoInputMode(false); - } - setFocusedOption(value); - } - return { - yesInputMode, - noInputMode, - yesFeedbackModeEntered, - noFeedbackModeEntered, - acceptFeedback, - rejectFeedback, - setAcceptFeedback, - setRejectFeedback, - focusedOption, - handleInputModeToggle, - handleReject: handleReject2, - handleFocus - }; -} -var import_react214; -var init_useShellPermissionFeedback = __esm(() => { - init_analytics(); - init_metadata(); - init_AppState(); - init_utils16(); - import_react214 = __toESM(require_react(), 1); -}); - -// src/components/permissions/shellPermissionHelpers.tsx -import { basename as basename49, sep as sep37 } from "path"; -function commandListDisplay(commands7) { - switch (commands7.length) { - case 0: - return ""; - case 1: - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: commands7[0] - }, undefined, false, undefined, this); - case 2: - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: commands7[0] - }, undefined, false, undefined, this), - " and ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: commands7[1] - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - default: - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: commands7.slice(0, -1).join(", ") - }, undefined, false, undefined, this), - ", and", - " ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: commands7.slice(-1)[0] - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } -} -function commandListDisplayTruncated(commands7) { - const plainText = commands7.join(", "); - if (plainText.length > 50) { - return "similar"; - } - return commandListDisplay(commands7); -} -function formatPathList(paths2) { - if (paths2.length === 0) - return ""; - const names = paths2.map((p4) => basename49(p4) || p4); - if (names.length === 1) { - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: names[0] - }, undefined, false, undefined, this), - sep37 - ] - }, undefined, true, undefined, this); - } - if (names.length === 2) { - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: names[0] - }, undefined, false, undefined, this), - sep37, - " and ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: names[1] - }, undefined, false, undefined, this), - sep37 - ] - }, undefined, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: names[0] - }, undefined, false, undefined, this), - sep37, - ", ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: names[1] - }, undefined, false, undefined, this), - sep37, - " and ", - paths2.length - 2, - " more" - ] - }, undefined, true, undefined, this); -} -function generateShellSuggestionsLabel(suggestions, shellToolName, commandTransform) { - const allRules = suggestions.filter((s4) => s4.type === "addRules").flatMap((s4) => s4.rules || []); - const readRules = allRules.filter((r4) => r4.toolName === "Read"); - const shellRules = allRules.filter((r4) => r4.toolName === shellToolName); - const directories = suggestions.filter((s4) => s4.type === "addDirectories").flatMap((s4) => s4.directories || []); - const readPaths = readRules.map((r4) => r4.ruleContent?.replace("/**", "") || "").filter((p4) => p4); - const shellCommands = [...new Set(shellRules.flatMap((rule) => { - if (!rule.ruleContent) - return []; - const command19 = permissionRuleExtractPrefix2(rule.ruleContent) ?? rule.ruleContent; - return commandTransform ? commandTransform(command19) : command19; - }))]; - const hasDirectories = directories.length > 0; - const hasReadPaths = readPaths.length > 0; - const hasCommands = shellCommands.length > 0; - if (hasReadPaths && !hasDirectories && !hasCommands) { - if (readPaths.length === 1) { - const firstPath = readPaths[0]; - const dirName = basename49(firstPath) || firstPath; - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, allow reading from ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: dirName - }, undefined, false, undefined, this), - sep37, - " from this project" - ] - }, undefined, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, allow reading from ", - formatPathList(readPaths), - " from this project" - ] - }, undefined, true, undefined, this); - } - if (hasDirectories && !hasReadPaths && !hasCommands) { - if (directories.length === 1) { - const firstDir = directories[0]; - const dirName = basename49(firstDir) || firstDir; - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, and always allow access to ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: dirName - }, undefined, false, undefined, this), - sep37, - " from this project" - ] - }, undefined, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, and always allow access to ", - formatPathList(directories), - " from this project" - ] - }, undefined, true, undefined, this); - } - if (hasCommands && !hasDirectories && !hasReadPaths) { - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, and don't ask again for ", - commandListDisplayTruncated(shellCommands), - " commands in", - " ", - /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - bold: true, - children: getOriginalCwd() - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - if ((hasDirectories || hasReadPaths) && !hasCommands) { - const allPaths = [...directories, ...readPaths]; - if (hasDirectories && hasReadPaths) { - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, and always allow access to ", - formatPathList(allPaths), - " from this project" - ] - }, undefined, true, undefined, this); - } - } - if ((hasDirectories || hasReadPaths) && hasCommands) { - const allPaths = [...directories, ...readPaths]; - if (allPaths.length === 1 && shellCommands.length === 1) { - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, and allow access to ", - formatPathList(allPaths), - " and", - " ", - commandListDisplayTruncated(shellCommands), - " commands" - ] - }, undefined, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime384.jsxDEV(ThemedText, { - children: [ - "Yes, and allow ", - formatPathList(allPaths), - " access and", - " ", - commandListDisplayTruncated(shellCommands), - " commands" - ] - }, undefined, true, undefined, this); - } - return null; -} -var jsx_dev_runtime384; -var init_shellPermissionHelpers = __esm(() => { - init_state(); - init_ink2(); - init_shellRuleMatching(); - jsx_dev_runtime384 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/BashPermissionRequest/bashToolUseOptions.tsx -function stripBashRedirections(command19) { - const { - commandWithoutRedirections, - redirections - } = extractOutputRedirections(command19); - return redirections.length > 0 ? commandWithoutRedirections : command19; -} -function bashToolUseOptions({ - suggestions = [], - decisionReason, - onRejectFeedbackChange, - onAcceptFeedbackChange, - onClassifierDescriptionChange, - classifierDescription, - initialClassifierDescriptionEmpty = false, - existingAllowDescriptions = [], - yesInputMode = false, - noInputMode = false, - editablePrefix, - onEditablePrefixChange -}) { - const options2 = []; - if (yesInputMode) { - options2.push({ - type: "input", - label: "Yes", - value: "yes", - placeholder: "and tell Claude what to do next", - onChange: onAcceptFeedbackChange, - allowEmptySubmitToCancel: true - }); - } else { - options2.push({ - label: "Yes", - value: "yes" - }); - } - if (shouldShowAlwaysAllowOptions()) { - const hasNonBashSuggestions = suggestions.some((s4) => s4.type === "addDirectories" || s4.type === "addRules" && s4.rules?.some((r4) => r4.toolName !== BASH_TOOL_NAME)); - if (editablePrefix !== undefined && onEditablePrefixChange && !hasNonBashSuggestions && suggestions.length > 0) { - options2.push({ - type: "input", - label: "Yes, and don\u2019t ask again for", - value: "yes-prefix-edited", - placeholder: "command prefix (e.g., npm run:*)", - initialValue: editablePrefix, - onChange: onEditablePrefixChange, - allowEmptySubmitToCancel: true, - showLabelWithValue: true, - labelValueSeparator: ": ", - resetCursorOnUpdate: true - }); - } else if (suggestions.length > 0) { - const label = generateShellSuggestionsLabel(suggestions, BASH_TOOL_NAME, stripBashRedirections); - if (label) { - options2.push({ - label, - value: "yes-apply-suggestions" - }); - } - } - const editablePrefixShown = options2.some((o5) => o5.value === "yes-prefix-edited"); - if (false) {} - } - if (noInputMode) { - options2.push({ - type: "input", - label: "No", - value: "no", - placeholder: "and tell Claude what to do differently", - onChange: onRejectFeedbackChange, - allowEmptySubmitToCancel: true - }); - } else { - options2.push({ - label: "No", - value: "no" - }); - } - return options2; -} -var init_bashToolUseOptions = __esm(() => { - init_commands4(); - init_permissionsLoader(); - init_shellPermissionHelpers(); -}); - -// src/components/permissions/BashPermissionRequest/BashPermissionRequest.tsx -function BashPermissionRequest(props) { - const $2 = import_compiler_runtime298.c(21); - const { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - verbose, - workerBadge - } = props; - let command19; - let description; - let t0; - if ($2[0] !== toolUseConfirm.input) { - ({ - command: command19, - description - } = BashTool.inputSchema.parse(toolUseConfirm.input)); - t0 = parseSedEditCommand(command19); - $2[0] = toolUseConfirm.input; - $2[1] = command19; - $2[2] = description; - $2[3] = t0; - } else { - command19 = $2[1]; - description = $2[2]; - t0 = $2[3]; - } - const sedInfo = t0; - if (sedInfo) { - let t12; - if ($2[4] !== onDone || $2[5] !== onReject || $2[6] !== sedInfo || $2[7] !== toolUseConfirm || $2[8] !== toolUseContext || $2[9] !== verbose || $2[10] !== workerBadge) { - t12 = /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(SedEditPermissionRequest, { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - verbose, - workerBadge, - sedInfo - }, undefined, false, undefined, this); - $2[4] = onDone; - $2[5] = onReject; - $2[6] = sedInfo; - $2[7] = toolUseConfirm; - $2[8] = toolUseContext; - $2[9] = verbose; - $2[10] = workerBadge; - $2[11] = t12; - } else { - t12 = $2[11]; - } - return t12; - } - let t1; - if ($2[12] !== command19 || $2[13] !== description || $2[14] !== onDone || $2[15] !== onReject || $2[16] !== toolUseConfirm || $2[17] !== toolUseContext || $2[18] !== verbose || $2[19] !== workerBadge) { - t1 = /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(BashPermissionRequestInner, { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - verbose, - workerBadge, - command: command19, - description - }, undefined, false, undefined, this); - $2[12] = command19; - $2[13] = description; - $2[14] = onDone; - $2[15] = onReject; - $2[16] = toolUseConfirm; - $2[17] = toolUseContext; - $2[18] = verbose; - $2[19] = workerBadge; - $2[20] = t1; - } else { - t1 = $2[20]; - } - return t1; -} -function BashPermissionRequestInner({ - toolUseConfirm, - toolUseContext, - onDone, - onReject, - verbose: _verbose, - workerBadge, - command: command19, - description -}) { - const [theme2] = useTheme(); - const toolPermissionContext = useAppState((s4) => s4.toolPermissionContext); - const explainerState = usePermissionExplainerUI({ - toolName: toolUseConfirm.tool.name, - toolInput: toolUseConfirm.input, - toolDescription: toolUseConfirm.description, - messages: toolUseContext.messages - }); - const { - yesInputMode, - noInputMode, - yesFeedbackModeEntered, - noFeedbackModeEntered, - acceptFeedback, - rejectFeedback, - setAcceptFeedback, - setRejectFeedback, - focusedOption, - handleInputModeToggle, - handleReject: handleReject2, - handleFocus - } = useShellPermissionFeedback({ - toolUseConfirm, - onDone, - onReject, - explainerVisible: explainerState.visible - }); - const [showPermissionDebug, setShowPermissionDebug] = import_react215.useState(false); - const [classifierDescription, setClassifierDescription] = import_react215.useState(description || ""); - const [initialClassifierDescriptionEmpty, setInitialClassifierDescriptionEmpty] = import_react215.useState(!description?.trim()); - import_react215.useEffect(() => { - if (!isClassifierPermissionsEnabled()) - return; - const abortController = new AbortController; - generateGenericDescription(command19, description, abortController.signal).then((generic) => { - if (generic && !abortController.signal.aborted) { - setClassifierDescription(generic); - setInitialClassifierDescriptionEmpty(false); - } - }).catch(() => {}); - return () => abortController.abort(); - }, [command19, description]); - const isCompound = toolUseConfirm.permissionResult.decisionReason?.type === "subcommandResults"; - const [editablePrefix, setEditablePrefix] = import_react215.useState(() => { - if (isCompound) { - const backendBashRules = extractRules("suggestions" in toolUseConfirm.permissionResult ? toolUseConfirm.permissionResult.suggestions : undefined).filter((r4) => r4.toolName === BashTool.name && r4.ruleContent); - return backendBashRules.length === 1 ? backendBashRules[0].ruleContent : undefined; - } - const two = getSimpleCommandPrefix(command19); - if (two) - return `${two}:*`; - const one = getFirstWordPrefix(command19); - if (one) - return `${one}:*`; - return command19; - }); - const hasUserEditedPrefix = import_react215.useRef(false); - const onEditablePrefixChange = import_react215.useCallback((value) => { - hasUserEditedPrefix.current = true; - setEditablePrefix(value); - }, []); - import_react215.useEffect(() => { - if (isCompound) - return; - let cancelled = false; - getCompoundCommandPrefixesStatic(command19, (subcmd) => BashTool.isReadOnly({ - command: subcmd - })).then((prefixes) => { - if (cancelled || hasUserEditedPrefix.current) - return; - if (prefixes.length > 0) { - setEditablePrefix(`${prefixes[0]}:*`); - } - }).catch(() => {}); - return () => { - cancelled = true; - }; - }, [command19, isCompound]); - const [classifierWasChecking] = import_react215.useState(false); - const { - destructiveWarning: destructiveWarning_0, - sandboxingEnabled: sandboxingEnabled_0, - isSandboxed: isSandboxed_0 - } = import_react215.useMemo(() => { - const destructiveWarning = getFeatureValue_CACHED_MAY_BE_STALE("tengu_destructive_command_warning", false) ? getDestructiveCommandWarning(command19) : null; - const sandboxingEnabled = SandboxManager.isSandboxingEnabled(); - const isSandboxed = sandboxingEnabled && shouldUseSandbox(toolUseConfirm.input); - return { - destructiveWarning, - sandboxingEnabled, - isSandboxed - }; - }, [command19, toolUseConfirm.input]); - const unaryEvent = import_react215.useMemo(() => ({ - completion_type: "tool_use_single", - language_name: "none" - }), []); - usePermissionRequestLogging(toolUseConfirm, unaryEvent); - const existingAllowDescriptions = import_react215.useMemo(() => getBashPromptAllowDescriptions(toolPermissionContext), [toolPermissionContext]); - const options2 = import_react215.useMemo(() => bashToolUseOptions({ - suggestions: toolUseConfirm.permissionResult.behavior === "ask" ? toolUseConfirm.permissionResult.suggestions : undefined, - decisionReason: toolUseConfirm.permissionResult.decisionReason, - onRejectFeedbackChange: setRejectFeedback, - onAcceptFeedbackChange: setAcceptFeedback, - onClassifierDescriptionChange: setClassifierDescription, - classifierDescription, - initialClassifierDescriptionEmpty, - existingAllowDescriptions, - yesInputMode, - noInputMode, - editablePrefix, - onEditablePrefixChange - }), [toolUseConfirm, classifierDescription, initialClassifierDescriptionEmpty, existingAllowDescriptions, yesInputMode, noInputMode, editablePrefix, onEditablePrefixChange]); - const handleToggleDebug = import_react215.useCallback(() => { - setShowPermissionDebug((prev) => !prev); - }, []); - useKeybinding("permission:toggleDebug", handleToggleDebug, { - context: "Confirmation" - }); - const handleDismissCheckmark = import_react215.useCallback(() => { - toolUseConfirm.onDismissCheckmark?.(); - }, [toolUseConfirm]); - useKeybinding("confirm:no", handleDismissCheckmark, { - context: "Confirmation", - isActive: false - }); - function onSelect(value_0) { - let optionIndex = { - yes: 1, - "yes-apply-suggestions": 2, - "yes-prefix-edited": 2, - no: 3 - }; - if (false) {} - logEvent("tengu_permission_request_option_selected", { - option_index: optionIndex[value_0], - explainer_visible: explainerState.visible - }); - const toolNameForAnalytics = sanitizeToolNameForAnalytics(toolUseConfirm.tool.name); - if (value_0 === "yes-prefix-edited") { - const trimmedPrefix = (editablePrefix ?? "").trim(); - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - if (!trimmedPrefix) { - toolUseConfirm.onAllow(toolUseConfirm.input, []); - } else { - const prefixUpdates = [{ - type: "addRules", - rules: [{ - toolName: BashTool.name, - ruleContent: trimmedPrefix - }], - behavior: "allow", - destination: "localSettings" - }]; - toolUseConfirm.onAllow(toolUseConfirm.input, prefixUpdates); - } - onDone(); - return; - } - if (false) {} - switch (value_0) { - case "yes": { - const trimmedFeedback_0 = acceptFeedback.trim(); - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - logEvent("tengu_accept_submitted", { - toolName: toolNameForAnalytics, - isMcp: toolUseConfirm.tool.isMcp ?? false, - has_instructions: !!trimmedFeedback_0, - instructions_length: trimmedFeedback_0.length, - entered_feedback_mode: yesFeedbackModeEntered - }); - toolUseConfirm.onAllow(toolUseConfirm.input, [], trimmedFeedback_0 || undefined); - onDone(); - break; - } - case "yes-apply-suggestions": { - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - const permissionUpdates_0 = "suggestions" in toolUseConfirm.permissionResult ? toolUseConfirm.permissionResult.suggestions || [] : []; - toolUseConfirm.onAllow(toolUseConfirm.input, permissionUpdates_0); - onDone(); - break; - } - case "no": { - const trimmedFeedback = rejectFeedback.trim(); - logEvent("tengu_reject_submitted", { - toolName: toolNameForAnalytics, - isMcp: toolUseConfirm.tool.isMcp ?? false, - has_instructions: !!trimmedFeedback, - instructions_length: trimmedFeedback.length, - entered_feedback_mode: noFeedbackModeEntered - }); - handleReject2(trimmedFeedback || undefined); - break; - } - } - } - const classifierSubtitle = undefined; - return /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(PermissionDialog, { - workerBadge, - title: sandboxingEnabled_0 && !isSandboxed_0 ? "Bash command (unsandboxed)" : "Bash command", - subtitle: classifierSubtitle, - children: [ - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - dimColor: explainerState.visible, - children: BashTool.renderToolUseMessage({ - command: command19, - description - }, { - theme: theme2, - verbose: true - }) - }, undefined, false, undefined, this), - !explainerState.visible && /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - dimColor: true, - children: toolUseConfirm.description - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(PermissionExplainerContent, { - visible: explainerState.visible, - promise: explainerState.promise - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - showPermissionDebug ? /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(jsx_dev_runtime385.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(PermissionDecisionDebugInfo, { - permissionResult: toolUseConfirm.permissionResult, - toolName: "Bash" - }, undefined, false, undefined, this), - toolUseContext.options.debug && /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - dimColor: true, - children: "Ctrl-D to hide debug info" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(jsx_dev_runtime385.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(PermissionRuleExplanation, { - permissionResult: toolUseConfirm.permissionResult, - toolType: "command" - }, undefined, false, undefined, this), - destructiveWarning_0 && /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - color: "warning", - dimColor: false, - children: destructiveWarning_0 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - dimColor: false, - children: "Do you want to proceed?" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(Select, { - options: options2, - isDisabled: false, - inlineDescriptions: true, - onChange: onSelect, - onCancel: () => handleReject2(), - onFocus: handleFocus, - onInputModeToggle: handleInputModeToggle - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedBox_default, { - justifyContent: "space-between", - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Esc to cancel", - (focusedOption === "yes" && !yesInputMode || focusedOption === "no" && !noInputMode) && " \xB7 Tab to amend", - explainerState.enabled && ` \xB7 ctrl+e to ${explainerState.visible ? "hide" : "explain"}` - ] - }, undefined, true, undefined, this), - toolUseContext.options.debug && /* @__PURE__ */ jsx_dev_runtime385.jsxDEV(ThemedText, { - dimColor: true, - children: "Ctrl+d to show debug info" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_compiler_runtime298, import_react215, jsx_dev_runtime385; -var init_BashPermissionRequest = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_growthbook(); - init_analytics(); - init_metadata(); - init_AppState(); - init_BashTool(); - init_bashPermissions(); - init_destructiveCommandWarning(); - init_sedEditParser(); - init_shouldUseSandbox(); - init_prefix2(); - init_PermissionUpdate(); - init_sandbox_adapter(); - init_select(); - init_ShimmerChar(); - init_useShimmerAnimation(); - init_hooks6(); - init_PermissionDecisionDebugInfo(); - init_PermissionDialog(); - init_PermissionExplanation(); - init_PermissionRuleExplanation(); - init_SedEditPermissionRequest(); - init_useShellPermissionFeedback(); - init_utils16(); - init_bashToolUseOptions(); - import_compiler_runtime298 = __toESM(require_compiler_runtime(), 1); - import_react215 = __toESM(require_react(), 1); - jsx_dev_runtime385 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/EnterPlanModePermissionRequest/EnterPlanModePermissionRequest.tsx -function EnterPlanModePermissionRequest(t0) { - const $2 = import_compiler_runtime299.c(18); - const { - toolUseConfirm, - onDone, - onReject, - workerBadge - } = t0; - const toolPermissionContextMode = useAppState(_temp178); - let t1; - if ($2[0] !== onDone || $2[1] !== onReject || $2[2] !== toolPermissionContextMode || $2[3] !== toolUseConfirm) { - t1 = function handleResponse2(value) { - if (value === "yes") { - logEvent("tengu_plan_enter", { - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - entryMethod: "tool" - }); - handlePlanModeTransition(toolPermissionContextMode, "plan"); - onDone(); - toolUseConfirm.onAllow({}, [{ - type: "setMode", - mode: "plan", - destination: "session" - }]); - } else { - onDone(); - onReject(); - toolUseConfirm.onReject(); - } - }; - $2[0] = onDone; - $2[1] = onReject; - $2[2] = toolPermissionContextMode; - $2[3] = toolUseConfirm; - $2[4] = t1; - } else { - t1 = $2[4]; - } - const handleResponse = t1; - let t22; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - children: "Claude wants to enter plan mode to explore and design an implementation approach." - }, undefined, false, undefined, this); - $2[5] = t22; - } else { - t22 = $2[5]; - } - let t32; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - dimColor: true, - children: "In plan mode, Claude will:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 Explore the codebase thoroughly" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 Identify existing patterns" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 Design an implementation strategy" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 Present a plan for your approval" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedText, { - dimColor: true, - children: "No code changes will be made until you approve the plan." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t5 = { - label: "Yes, enter plan mode", - value: "yes" - }; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t6 = [t5, { - label: "No, start implementing now", - value: "no" - }]; - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] !== handleResponse) { - t7 = () => handleResponse("no"); - $2[10] = handleResponse; - $2[11] = t7; - } else { - t7 = $2[11]; - } - let t8; - if ($2[12] !== handleResponse || $2[13] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - paddingX: 1, - children: [ - t22, - t32, - t4, - /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(Select, { - options: t6, - onChange: handleResponse, - onCancel: t7 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[12] = handleResponse; - $2[13] = t7; - $2[14] = t8; - } else { - t8 = $2[14]; - } - let t9; - if ($2[15] !== t8 || $2[16] !== workerBadge) { - t9 = /* @__PURE__ */ jsx_dev_runtime386.jsxDEV(PermissionDialog, { - color: "planMode", - title: "Enter plan mode?", - workerBadge, - children: t8 - }, undefined, false, undefined, this); - $2[15] = t8; - $2[16] = workerBadge; - $2[17] = t9; - } else { - t9 = $2[17]; - } - return t9; -} -function _temp178(s4) { - return s4.toolPermissionContext.mode; -} -var import_compiler_runtime299, jsx_dev_runtime386; -var init_EnterPlanModePermissionRequest = __esm(() => { - init_state(); - init_ink2(); - init_analytics(); - init_AppState(); - init_planModeV2(); - init_CustomSelect(); - init_PermissionDialog(); - import_compiler_runtime299 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime386 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.tsx -function buildPermissionUpdates(mode, allowedPrompts) { - const updates = [{ - type: "setMode", - mode: toExternalPermissionMode(mode), - destination: "session" - }]; - if (isClassifierPermissionsEnabled() && allowedPrompts && allowedPrompts.length > 0) { - updates.push({ - type: "addRules", - rules: allowedPrompts.map((p4) => ({ - toolName: p4.tool, - ruleContent: createPromptRuleContent(p4.prompt) - })), - behavior: "allow", - destination: "session" - }); - } - return updates; -} -function autoNameSessionFromPlan(plan2, setAppState, isClearContext) { - if (isSessionPersistenceDisabled() || getSettings_DEPRECATED()?.cleanupPeriodDays === 0) { - return; - } - if (!isClearContext && getCurrentSessionTitle(getSessionId())) - return; - generateSessionName([createUserMessage({ - content: plan2.slice(0, 1000) - })], new AbortController().signal).then(async (name3) => { - if (!name3 || getCurrentSessionTitle(getSessionId())) - return; - const sessionId = getSessionId(); - const fullPath = getTranscriptPath(); - await saveCustomTitle(sessionId, name3, fullPath, "auto"); - await saveAgentName(sessionId, name3, fullPath, "auto"); - setAppState((prev) => { - if (prev.standaloneAgentContext?.name === name3) - return prev; - return { - ...prev, - standaloneAgentContext: { - ...prev.standaloneAgentContext, - name: name3 - } - }; - }); - }).catch(logError2); -} -function ExitPlanModePermissionRequest({ - toolUseConfirm, - onDone, - onReject, - workerBadge, - setStickyFooter -}) { - const toolPermissionContext = useAppState((s4) => s4.toolPermissionContext); - const setAppState = useSetAppState(); - const store = useAppStateStore(); - const { - addNotification - } = useNotifications(); - const [planFeedback, setPlanFeedback] = import_react216.useState(""); - const [pastedContents, setPastedContents] = import_react216.useState({}); - const nextPasteIdRef = import_react216.useRef(0); - const showClearContext = useAppState((s4) => s4.settings.showClearContextOnPlanAccept) ?? false; - const ultraplanSessionUrl = useAppState((s4) => s4.ultraplanSessionUrl); - const ultraplanLaunching = useAppState((s4) => s4.ultraplanLaunching); - const showUltraplan = false; - const usage = toolUseConfirm.assistantMessage.message.usage; - const { - mode, - isAutoModeAvailable, - isBypassPermissionsModeAvailable - } = toolPermissionContext; - const options2 = import_react216.useMemo(() => buildPlanApprovalOptions({ - showClearContext, - showUltraplan, - usedPercent: showClearContext ? getContextUsedPercent(usage, mode) : null, - isAutoModeAvailable, - isBypassPermissionsModeAvailable, - onFeedbackChange: setPlanFeedback - }), [showClearContext, showUltraplan, usage, mode, isAutoModeAvailable, isBypassPermissionsModeAvailable]); - function onImagePaste(base64Image, mediaType, filename, dimensions, _sourcePath) { - const pasteId = nextPasteIdRef.current++; - const newContent = { - id: pasteId, - type: "image", - content: base64Image, - mediaType: mediaType || "image/png", - filename: filename || "Pasted image", - dimensions - }; - cacheImagePath(newContent); - storeImage(newContent); - setPastedContents((prev) => ({ - ...prev, - [pasteId]: newContent - })); - } - const onRemoveImage = import_react216.useCallback((id) => { - setPastedContents((prev) => { - const next2 = { - ...prev - }; - delete next2[id]; - return next2; - }); - }, []); - const imageAttachments = Object.values(pastedContents).filter((c9) => c9.type === "image"); - const hasImages = imageAttachments.length > 0; - const isV2 = toolUseConfirm.tool.name === EXIT_PLAN_MODE_V2_TOOL_NAME; - const inputPlan = isV2 ? undefined : toolUseConfirm.input.plan; - const planFilePath = isV2 ? getPlanFilePath() : undefined; - const allowedPrompts = toolUseConfirm.input.allowedPrompts; - const rawPlan = inputPlan ?? getPlan(); - const isEmpty = !rawPlan || rawPlan.trim() === ""; - const [planStructureVariant] = import_react216.useState(() => getPewterLedgerVariant() ?? undefined); - const [currentPlan, setCurrentPlan] = import_react216.useState(() => { - if (inputPlan) - return inputPlan; - const plan2 = getPlan(); - return plan2 ?? "No plan found. Please write your plan to the plan file first."; - }); - const [showSaveMessage, setShowSaveMessage] = import_react216.useState(false); - const [planEditedLocally, setPlanEditedLocally] = import_react216.useState(false); - import_react216.useEffect(() => { - if (showSaveMessage) { - const timer = setTimeout(setShowSaveMessage, 5000, false); - return () => clearTimeout(timer); - } - }, [showSaveMessage]); - const handleKeyDown = (e4) => { - if (e4.ctrl && e4.key === "g") { - e4.preventDefault(); - logEvent("tengu_plan_external_editor_used", {}); - (async () => { - if (isV2 && planFilePath) { - const result = await editFileInEditor(planFilePath); - if (result.error) { - addNotification({ - key: "external-editor-error", - text: result.error, - color: "warning", - priority: "high" - }); - } - if (result.content !== null) { - if (result.content !== currentPlan) - setPlanEditedLocally(true); - setCurrentPlan(result.content); - setShowSaveMessage(true); - } - } else { - const result = await editPromptInEditor(currentPlan); - if (result.error) { - addNotification({ - key: "external-editor-error", - text: result.error, - color: "warning", - priority: "high" - }); - } - if (result.content !== null && result.content !== currentPlan) { - setCurrentPlan(result.content); - setShowSaveMessage(true); - } - } - })(); - return; - } - if (e4.shift && e4.key === "tab") { - e4.preventDefault(); - handleResponse(showClearContext ? "yes-accept-edits" : "yes-accept-edits-keep-context"); - return; - } - }; - async function handleResponse(value) { - const trimmedFeedback = planFeedback.trim(); - const acceptFeedback = trimmedFeedback || undefined; - if (value === "ultraplan") { - logEvent("tengu_plan_exit", { - planLengthChars: currentPlan.length, - outcome: "ultraplan", - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant - }); - onDone(); - onReject(); - toolUseConfirm.onReject("Plan being refined via Ultraplan \u2014 please wait for the result."); - launchUltraplan2({ - blurb: "", - seedPlan: currentPlan, - getAppState: store.getState, - setAppState: store.setState, - signal: new AbortController().signal - }).then((msg) => enqueuePendingNotification({ - value: msg, - mode: "task-notification" - })).catch(logError2); - return; - } - const updatedInput = isV2 && !planEditedLocally ? {} : { - plan: currentPlan - }; - if (false) {} - const isResumeAutoOption = false; - const isKeepContextOption = value === "yes-accept-edits-keep-context" || value === "yes-default-keep-context" || isResumeAutoOption; - if (value !== "no") { - autoNameSessionFromPlan(currentPlan, setAppState, !isKeepContextOption); - } - if (value !== "no" && !isKeepContextOption) { - let mode2 = "default"; - if (value === "yes-bypass-permissions") { - mode2 = "bypassPermissions"; - } else if (value === "yes-accept-edits") { - mode2 = "acceptEdits"; - } else if (false) {} - logEvent("tengu_plan_exit", { - planLengthChars: currentPlan.length, - outcome: value, - clearContext: true, - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant, - hasFeedback: !!acceptFeedback - }); - const verificationInstruction = ""; - const transcriptPath = getTranscriptPath(); - const transcriptHint = ` - -If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: ${transcriptPath}`; - const teamHint = isAgentSwarmsEnabled() ? ` - -If this plan can be broken down into multiple independent tasks, consider using the ${TEAM_CREATE_TOOL_NAME} tool to create a team and parallelize the work.` : ""; - const feedbackSuffix = acceptFeedback ? ` - -User feedback on this plan: ${acceptFeedback}` : ""; - setAppState((prev) => ({ - ...prev, - initialMessage: { - message: { - ...createUserMessage({ - content: `Implement the following plan: - -${currentPlan}${verificationInstruction}${transcriptHint}${teamHint}${feedbackSuffix}` - }), - planContent: currentPlan - }, - clearContext: true, - mode: mode2, - allowedPrompts - } - })); - setHasExitedPlanMode(true); - onDone(); - onReject(); - toolUseConfirm.onReject(); - return; - } - if (false) {} - const keepContextModes = { - "yes-accept-edits-keep-context": toolPermissionContext.isBypassPermissionsModeAvailable ? "bypassPermissions" : "acceptEdits", - "yes-default-keep-context": "default", - ...{} - }; - const keepContextMode = keepContextModes[value]; - if (keepContextMode) { - logEvent("tengu_plan_exit", { - planLengthChars: currentPlan.length, - outcome: value, - clearContext: false, - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant, - hasFeedback: !!acceptFeedback - }); - setHasExitedPlanMode(true); - setNeedsPlanModeExitAttachment(true); - onDone(); - toolUseConfirm.onAllow(updatedInput, buildPermissionUpdates(keepContextMode, allowedPrompts), acceptFeedback); - return; - } - const standardModes = { - "yes-bypass-permissions": "bypassPermissions", - "yes-accept-edits": "acceptEdits" - }; - const standardMode = standardModes[value]; - if (standardMode) { - logEvent("tengu_plan_exit", { - planLengthChars: currentPlan.length, - outcome: value, - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant, - hasFeedback: !!acceptFeedback - }); - setHasExitedPlanMode(true); - setNeedsPlanModeExitAttachment(true); - onDone(); - toolUseConfirm.onAllow(updatedInput, buildPermissionUpdates(standardMode, allowedPrompts), acceptFeedback); - return; - } - if (value === "no") { - if (!trimmedFeedback && !hasImages) { - return; - } - logEvent("tengu_plan_exit", { - planLengthChars: currentPlan.length, - outcome: "no", - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant - }); - let imageBlocks; - if (hasImages) { - imageBlocks = await Promise.all(imageAttachments.map(async (img) => { - const block2 = { - type: "image", - source: { - type: "base64", - media_type: img.mediaType || "image/png", - data: img.content - } - }; - const resized = await maybeResizeAndDownsampleImageBlock(block2); - return resized.block; - })); - } - onDone(); - onReject(); - toolUseConfirm.onReject(trimmedFeedback || (hasImages ? "(See attached image)" : undefined), imageBlocks && imageBlocks.length > 0 ? imageBlocks : undefined); - } - } - const editor = getExternalEditor(); - const editorName = editor ? toIDEDisplayName(editor) : null; - const handleResponseRef = import_react216.useRef(handleResponse); - handleResponseRef.current = handleResponse; - const handleCancelRef = import_react216.useRef(undefined); - handleCancelRef.current = () => { - logEvent("tengu_plan_exit", { - planLengthChars: currentPlan.length, - outcome: "no", - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant - }); - onDone(); - onReject(); - toolUseConfirm.onReject(); - }; - const useStickyFooter = !isEmpty && !!setStickyFooter; - import_react216.useLayoutEffect(() => { - if (!useStickyFooter) - return; - setStickyFooter(/* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "column", - borderStyle: "round", - borderColor: "planMode", - borderLeft: false, - borderRight: false, - borderBottom: false, - paddingX: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: "Would you like to proceed?" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(Select, { - options: options2, - onChange: (v6) => void handleResponseRef.current(v6), - onCancel: () => handleCancelRef.current?.(), - onImagePaste, - pastedContents, - onRemoveImage - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - editorName && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: "ctrl-g to edit in " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: editorName - }, undefined, false, undefined, this), - isV2 && planFilePath && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " \xB7 ", - getDisplayPath(planFilePath) - ] - }, undefined, true, undefined, this), - showSaveMessage && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(jsx_dev_runtime387.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - color: "success", - children: [ - figures_default.tick, - "Plan saved!" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this)); - return () => setStickyFooter(null); - }, [useStickyFooter, setStickyFooter, options2, pastedContents, editorName, isV2, planFilePath, showSaveMessage]); - if (isEmpty) { - let handleEmptyPlanResponse = function(value) { - if (value === "yes") { - logEvent("tengu_plan_exit", { - planLengthChars: 0, - outcome: "yes-default", - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant - }); - if (false) {} - setHasExitedPlanMode(true); - setNeedsPlanModeExitAttachment(true); - onDone(); - toolUseConfirm.onAllow({}, [{ - type: "setMode", - mode: "default", - destination: "session" - }]); - } else { - logEvent("tengu_plan_exit", { - planLengthChars: 0, - outcome: "no", - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant - }); - onDone(); - onReject(); - toolUseConfirm.onReject(); - } - }; - return /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(PermissionDialog, { - color: "planMode", - title: "Exit plan mode?", - workerBadge, - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 1, - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - children: "Claude wants to exit plan mode" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(Select, { - options: [{ - label: "Yes", - value: "yes" - }, { - label: "No", - value: "no" - }], - onChange: handleEmptyPlanResponse, - onCancel: () => { - logEvent("tengu_plan_exit", { - planLengthChars: 0, - outcome: "no", - interviewPhaseEnabled: isPlanModeInterviewPhaseEnabled(), - planStructureVariant - }); - onDone(); - onReject(); - toolUseConfirm.onReject(); - } - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "column", - tabIndex: 0, - autoFocus: true, - onKeyDown: handleKeyDown, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(PermissionDialog, { - color: "planMode", - title: "Ready to code?", - innerPaddingX: 0, - workerBadge, - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - paddingX: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - children: "Here is Claude's plan:" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - borderColor: "subtle", - borderStyle: "dashed", - flexDirection: "column", - borderLeft: false, - borderRight: false, - paddingX: 1, - marginBottom: 1, - overflow: "hidden", - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(Markdown, { - children: currentPlan - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(PermissionRuleExplanation, { - permissionResult: toolUseConfirm.permissionResult, - toolType: "tool" - }, undefined, false, undefined, this), - isClassifierPermissionsEnabled() && allowedPrompts && allowedPrompts.length > 0 && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - bold: true, - children: "Requested permissions:" - }, undefined, false, undefined, this), - allowedPrompts.map((p4, i6) => /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "\xB7 ", - p4.tool, - "(", - PROMPT_PREFIX, - " ", - p4.prompt, - ")" - ] - }, i6, true, undefined, this)) - ] - }, undefined, true, undefined, this), - !useStickyFooter && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(jsx_dev_runtime387.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: "Claude has written up a plan and is ready to execute. Would you like to proceed?" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(Select, { - options: options2, - onChange: handleResponse, - onCancel: () => handleCancelRef.current?.(), - onImagePaste, - pastedContents, - onRemoveImage - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - !useStickyFooter && editorName && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - paddingX: 1, - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: "ctrl-g to edit in " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - bold: true, - dimColor: true, - children: editorName - }, undefined, false, undefined, this), - isV2 && planFilePath && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " \xB7 ", - getDisplayPath(planFilePath) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - showSaveMessage && /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime387.jsxDEV(ThemedText, { - color: "success", - children: [ - figures_default.tick, - "Plan saved!" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -function buildPlanApprovalOptions({ - showClearContext, - showUltraplan, - usedPercent, - isAutoModeAvailable, - isBypassPermissionsModeAvailable, - onFeedbackChange -}) { - const options2 = []; - const usedLabel = usedPercent !== null ? ` (${usedPercent}% used)` : ""; - if (showClearContext) { - if (false) {} else if (isBypassPermissionsModeAvailable) { - options2.push({ - label: `Yes, clear context${usedLabel} and bypass permissions`, - value: "yes-bypass-permissions" - }); - } else { - options2.push({ - label: `Yes, clear context${usedLabel} and auto-accept edits`, - value: "yes-accept-edits" - }); - } - } - if (false) {} else if (isBypassPermissionsModeAvailable) { - options2.push({ - label: "Yes, and bypass permissions", - value: "yes-accept-edits-keep-context" - }); - } else { - options2.push({ - label: "Yes, auto-accept edits", - value: "yes-accept-edits-keep-context" - }); - } - options2.push({ - label: "Yes, manually approve edits", - value: "yes-default-keep-context" - }); - if (showUltraplan) { - options2.push({ - label: "No, refine with Ultraplan on Claude Code on the web", - value: "ultraplan" - }); - } - options2.push({ - type: "input", - label: "No, keep planning", - value: "no", - placeholder: "Tell Claude what to change", - description: "shift+tab to approve with this feedback", - onChange: onFeedbackChange - }); - return options2; -} -function getContextUsedPercent(usage, permissionMode) { - if (!usage) - return null; - const runtimeModel = getRuntimeMainLoopModel({ - permissionMode, - mainLoopModel: getMainLoopModel(), - exceeds200kTokens: false - }); - const contextWindowSize = getContextWindowForModel(runtimeModel, getSdkBetas()); - const { - used - } = calculateContextPercentages({ - input_tokens: usage.input_tokens, - cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0, - cache_read_input_tokens: usage.cache_read_input_tokens ?? 0 - }, contextWindowSize); - return used; -} -var import_react216, jsx_dev_runtime387; -var init_ExitPlanModePermissionRequest = __esm(() => { - init_figures(); - init_notifications(); - init_analytics(); - init_AppState(); - init_state(); - init_generateSessionName(); - init_ultraplan(); - init_ink2(); - init_constants3(); - init_agentSwarmsEnabled(); - init_context(); - init_editor(); - init_file(); - init_ide(); - init_log2(); - init_messageQueueManager(); - init_messages9(); - init_model(); - init_PermissionMode(); - init_permissionSetup(); - init_planModeV2(); - init_plans(); - init_promptEditor(); - init_sessionStorage(); - init_settings2(); - init_CustomSelect(); - init_Markdown(); - init_PermissionDialog(); - init_PermissionRuleExplanation(); - init_imageResizer(); - init_imageStore(); - import_react216 = __toESM(require_react(), 1); - jsx_dev_runtime387 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/PermissionPrompt.tsx -function PermissionPrompt(t0) { - const $2 = import_compiler_runtime300.c(54); - const { - options: options2, - onSelect, - onCancel, - question: t1, - toolAnalyticsContext - } = t0; - const question = t1 === undefined ? "Do you want to proceed?" : t1; - const setAppState = useSetAppState(); - const [acceptFeedback, setAcceptFeedback] = import_react217.useState(""); - const [rejectFeedback, setRejectFeedback] = import_react217.useState(""); - const [acceptInputMode, setAcceptInputMode] = import_react217.useState(false); - const [rejectInputMode, setRejectInputMode] = import_react217.useState(false); - const [focusedValue, setFocusedValue] = import_react217.useState(null); - const [acceptFeedbackModeEntered, setAcceptFeedbackModeEntered] = import_react217.useState(false); - const [rejectFeedbackModeEntered, setRejectFeedbackModeEntered] = import_react217.useState(false); - let t22; - if ($2[0] !== focusedValue || $2[1] !== options2) { - let t33; - if ($2[3] !== focusedValue) { - t33 = (opt) => opt.value === focusedValue; - $2[3] = focusedValue; - $2[4] = t33; - } else { - t33 = $2[4]; - } - t22 = options2.find(t33); - $2[0] = focusedValue; - $2[1] = options2; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const focusedOption = t22; - const focusedFeedbackType = focusedOption?.feedbackConfig?.type; - const showTabHint = focusedFeedbackType === "accept" && !acceptInputMode || focusedFeedbackType === "reject" && !rejectInputMode; - let t32; - if ($2[5] !== acceptInputMode || $2[6] !== options2 || $2[7] !== rejectInputMode) { - let t42; - if ($2[9] !== acceptInputMode || $2[10] !== rejectInputMode) { - t42 = (opt_0) => { - const { - value, - label, - feedbackConfig - } = opt_0; - if (!feedbackConfig) { - return { - label, - value - }; - } - const { - type, - placeholder - } = feedbackConfig; - const isInputMode = type === "accept" ? acceptInputMode : rejectInputMode; - const onChange = type === "accept" ? setAcceptFeedback : setRejectFeedback; - const defaultPlaceholder = DEFAULT_PLACEHOLDERS[type]; - if (isInputMode) { - return { - type: "input", - label, - value, - placeholder: placeholder ?? defaultPlaceholder, - onChange, - allowEmptySubmitToCancel: true - }; - } - return { - label, - value - }; - }; - $2[9] = acceptInputMode; - $2[10] = rejectInputMode; - $2[11] = t42; - } else { - t42 = $2[11]; - } - t32 = options2.map(t42); - $2[5] = acceptInputMode; - $2[6] = options2; - $2[7] = rejectInputMode; - $2[8] = t32; - } else { - t32 = $2[8]; - } - const selectOptions = t32; - let t4; - if ($2[12] !== acceptInputMode || $2[13] !== options2 || $2[14] !== rejectInputMode || $2[15] !== toolAnalyticsContext?.isMcp || $2[16] !== toolAnalyticsContext?.toolName) { - t4 = (value_0) => { - const option = options2.find((opt_1) => opt_1.value === value_0); - if (!option?.feedbackConfig) { - return; - } - const { - type: type_0 - } = option.feedbackConfig; - const analyticsProps = { - toolName: toolAnalyticsContext?.toolName, - isMcp: toolAnalyticsContext?.isMcp ?? false - }; - if (type_0 === "accept") { - if (acceptInputMode) { - setAcceptInputMode(false); - logEvent("tengu_accept_feedback_mode_collapsed", analyticsProps); - } else { - setAcceptInputMode(true); - setAcceptFeedbackModeEntered(true); - logEvent("tengu_accept_feedback_mode_entered", analyticsProps); - } - } else { - if (type_0 === "reject") { - if (rejectInputMode) { - setRejectInputMode(false); - logEvent("tengu_reject_feedback_mode_collapsed", analyticsProps); - } else { - setRejectInputMode(true); - setRejectFeedbackModeEntered(true); - logEvent("tengu_reject_feedback_mode_entered", analyticsProps); - } - } - } - }; - $2[12] = acceptInputMode; - $2[13] = options2; - $2[14] = rejectInputMode; - $2[15] = toolAnalyticsContext?.isMcp; - $2[16] = toolAnalyticsContext?.toolName; - $2[17] = t4; - } else { - t4 = $2[17]; - } - const handleInputModeToggle = t4; - let t5; - if ($2[18] !== acceptFeedback || $2[19] !== acceptFeedbackModeEntered || $2[20] !== onSelect || $2[21] !== options2 || $2[22] !== rejectFeedback || $2[23] !== rejectFeedbackModeEntered || $2[24] !== toolAnalyticsContext?.isMcp || $2[25] !== toolAnalyticsContext?.toolName) { - t5 = (value_1) => { - const option_0 = options2.find((opt_2) => opt_2.value === value_1); - if (!option_0) { - return; - } - let feedback2; - if (option_0.feedbackConfig) { - const rawFeedback = option_0.feedbackConfig.type === "accept" ? acceptFeedback : rejectFeedback; - const trimmedFeedback = rawFeedback.trim(); - if (trimmedFeedback) { - feedback2 = trimmedFeedback; - } - const analyticsProps_0 = { - toolName: toolAnalyticsContext?.toolName, - isMcp: toolAnalyticsContext?.isMcp ?? false, - has_instructions: !!trimmedFeedback, - instructions_length: trimmedFeedback?.length ?? 0, - entered_feedback_mode: option_0.feedbackConfig.type === "accept" ? acceptFeedbackModeEntered : rejectFeedbackModeEntered - }; - if (option_0.feedbackConfig.type === "accept") { - logEvent("tengu_accept_submitted", analyticsProps_0); - } else { - if (option_0.feedbackConfig.type === "reject") { - logEvent("tengu_reject_submitted", analyticsProps_0); - } - } - } - onSelect(value_1, feedback2); - }; - $2[18] = acceptFeedback; - $2[19] = acceptFeedbackModeEntered; - $2[20] = onSelect; - $2[21] = options2; - $2[22] = rejectFeedback; - $2[23] = rejectFeedbackModeEntered; - $2[24] = toolAnalyticsContext?.isMcp; - $2[25] = toolAnalyticsContext?.toolName; - $2[26] = t5; - } else { - t5 = $2[26]; - } - const handleSelect = t5; - let handlers; - if ($2[27] !== handleSelect || $2[28] !== options2) { - handlers = {}; - for (const opt_3 of options2) { - if (opt_3.keybinding) { - handlers[opt_3.keybinding] = () => handleSelect(opt_3.value); - } - } - $2[27] = handleSelect; - $2[28] = options2; - $2[29] = handlers; - } else { - handlers = $2[29]; - } - const keybindingHandlers = handlers; - let t6; - if ($2[30] === Symbol.for("react.memo_cache_sentinel")) { - t6 = { - context: "Confirmation" - }; - $2[30] = t6; - } else { - t6 = $2[30]; - } - useKeybindings(keybindingHandlers, t6); - let t7; - if ($2[31] !== onCancel || $2[32] !== setAppState) { - t7 = () => { - logEvent("tengu_permission_request_escape", {}); - setAppState(_temp179); - onCancel?.(); - }; - $2[31] = onCancel; - $2[32] = setAppState; - $2[33] = t7; - } else { - t7 = $2[33]; - } - const handleCancel = t7; - let t8; - if ($2[34] !== question) { - t8 = typeof question === "string" ? /* @__PURE__ */ jsx_dev_runtime388.jsxDEV(ThemedText, { - children: question - }, undefined, false, undefined, this) : question; - $2[34] = question; - $2[35] = t8; - } else { - t8 = $2[35]; - } - let t9; - if ($2[36] !== acceptFeedback || $2[37] !== acceptInputMode || $2[38] !== options2 || $2[39] !== rejectFeedback || $2[40] !== rejectInputMode) { - t9 = (value_2) => { - const newOption = options2.find((opt_4) => opt_4.value === value_2); - if (newOption?.feedbackConfig?.type !== "accept" && acceptInputMode && !acceptFeedback.trim()) { - setAcceptInputMode(false); - } - if (newOption?.feedbackConfig?.type !== "reject" && rejectInputMode && !rejectFeedback.trim()) { - setRejectInputMode(false); - } - setFocusedValue(value_2); - }; - $2[36] = acceptFeedback; - $2[37] = acceptInputMode; - $2[38] = options2; - $2[39] = rejectFeedback; - $2[40] = rejectInputMode; - $2[41] = t9; - } else { - t9 = $2[41]; - } - let t10; - if ($2[42] !== handleCancel || $2[43] !== handleInputModeToggle || $2[44] !== handleSelect || $2[45] !== selectOptions || $2[46] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime388.jsxDEV(Select, { - options: selectOptions, - inlineDescriptions: true, - onChange: handleSelect, - onCancel: handleCancel, - onFocus: t9, - onInputModeToggle: handleInputModeToggle - }, undefined, false, undefined, this); - $2[42] = handleCancel; - $2[43] = handleInputModeToggle; - $2[44] = handleSelect; - $2[45] = selectOptions; - $2[46] = t9; - $2[47] = t10; - } else { - t10 = $2[47]; - } - const t11 = showTabHint && " \xB7 Tab to amend"; - let t12; - if ($2[48] !== t11) { - t12 = /* @__PURE__ */ jsx_dev_runtime388.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime388.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Esc to cancel", - t11 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[48] = t11; - $2[49] = t12; - } else { - t12 = $2[49]; - } - let t13; - if ($2[50] !== t10 || $2[51] !== t12 || $2[52] !== t8) { - t13 = /* @__PURE__ */ jsx_dev_runtime388.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t8, - t10, - t12 - ] - }, undefined, true, undefined, this); - $2[50] = t10; - $2[51] = t12; - $2[52] = t8; - $2[53] = t13; - } else { - t13 = $2[53]; - } - return t13; -} -function _temp179(prev) { - return { - ...prev, - attribution: { - ...prev.attribution, - escapeCount: prev.attribution.escapeCount + 1 - } - }; -} -var import_compiler_runtime300, import_react217, jsx_dev_runtime388, DEFAULT_PLACEHOLDERS; -var init_PermissionPrompt = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_analytics(); - init_AppState(); - init_select(); - import_compiler_runtime300 = __toESM(require_compiler_runtime(), 1); - import_react217 = __toESM(require_react(), 1); - jsx_dev_runtime388 = __toESM(require_jsx_dev_runtime(), 1); - DEFAULT_PLACEHOLDERS = { - accept: "tell Claude what to do next", - reject: "tell Claude what to do differently" - }; -}); - -// src/components/permissions/FallbackPermissionRequest.tsx -function FallbackPermissionRequest(t0) { - const $2 = import_compiler_runtime301.c(58); - const { - toolUseConfirm, - onDone, - onReject, - workerBadge - } = t0; - const [theme2] = useTheme(); - let originalUserFacingName; - let t1; - if ($2[0] !== toolUseConfirm.input || $2[1] !== toolUseConfirm.tool) { - originalUserFacingName = toolUseConfirm.tool.userFacingName(toolUseConfirm.input); - t1 = originalUserFacingName.endsWith(" (MCP)") ? originalUserFacingName.slice(0, -6) : originalUserFacingName; - $2[0] = toolUseConfirm.input; - $2[1] = toolUseConfirm.tool; - $2[2] = originalUserFacingName; - $2[3] = t1; - } else { - originalUserFacingName = $2[2]; - t1 = $2[3]; - } - const userFacingName8 = t1; - let t22; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t22 = { - completion_type: "tool_use_single", - language_name: "none" - }; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const unaryEvent = t22; - usePermissionRequestLogging(toolUseConfirm, unaryEvent); - let t32; - if ($2[5] !== onDone || $2[6] !== onReject || $2[7] !== toolUseConfirm) { - t32 = (value, feedback2) => { - bb8: - switch (value) { - case "yes": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "accept", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onAllow(toolUseConfirm.input, [], feedback2); - onDone(); - break bb8; - } - case "yes-dont-ask-again": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "accept", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onAllow(toolUseConfirm.input, [{ - type: "addRules", - rules: [{ - toolName: toolUseConfirm.tool.name - }], - behavior: "allow", - destination: "localSettings" - }]); - onDone(); - break bb8; - } - case "no": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "reject", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onReject(feedback2); - onReject(); - onDone(); - } - } - }; - $2[5] = onDone; - $2[6] = onReject; - $2[7] = toolUseConfirm; - $2[8] = t32; - } else { - t32 = $2[8]; - } - const handleSelect = t32; - let t4; - if ($2[9] !== onDone || $2[10] !== onReject || $2[11] !== toolUseConfirm) { - t4 = () => { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "reject", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onReject(); - onReject(); - onDone(); - }; - $2[9] = onDone; - $2[10] = onReject; - $2[11] = toolUseConfirm; - $2[12] = t4; - } else { - t4 = $2[12]; - } - const handleCancel = t4; - let t5; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t5 = getOriginalCwd(); - $2[13] = t5; - } else { - t5 = $2[13]; - } - const originalCwd = t5; - let t6; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t6 = shouldShowAlwaysAllowOptions(); - $2[14] = t6; - } else { - t6 = $2[14]; - } - const showAlwaysAllowOptions = t6; - let t7; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t7 = { - label: "Yes", - value: "yes", - feedbackConfig: { - type: "accept" - } - }; - $2[15] = t7; - } else { - t7 = $2[15]; - } - let result; - if ($2[16] !== userFacingName8) { - result = [t7]; - if (showAlwaysAllowOptions) { - const t83 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedText, { - bold: true, - children: userFacingName8 - }, undefined, false, undefined, this); - let t92; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t92 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedText, { - bold: true, - children: originalCwd - }, undefined, false, undefined, this); - $2[18] = t92; - } else { - t92 = $2[18]; - } - let t102; - if ($2[19] !== t83) { - t102 = { - label: /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedText, { - children: [ - "Yes, and don't ask again for ", - t83, - " ", - "commands in ", - t92 - ] - }, undefined, true, undefined, this), - value: "yes-dont-ask-again" - }; - $2[19] = t83; - $2[20] = t102; - } else { - t102 = $2[20]; - } - result.push(t102); - } - let t82; - if ($2[21] === Symbol.for("react.memo_cache_sentinel")) { - t82 = { - label: "No", - value: "no", - feedbackConfig: { - type: "reject" - } - }; - $2[21] = t82; - } else { - t82 = $2[21]; - } - result.push(t82); - $2[16] = userFacingName8; - $2[17] = result; - } else { - result = $2[17]; - } - const options2 = result; - let t8; - if ($2[22] !== toolUseConfirm.tool.name) { - t8 = sanitizeToolNameForAnalytics(toolUseConfirm.tool.name); - $2[22] = toolUseConfirm.tool.name; - $2[23] = t8; - } else { - t8 = $2[23]; - } - const t9 = toolUseConfirm.tool.isMcp ?? false; - let t10; - if ($2[24] !== t8 || $2[25] !== t9) { - t10 = { - toolName: t8, - isMcp: t9 - }; - $2[24] = t8; - $2[25] = t9; - $2[26] = t10; - } else { - t10 = $2[26]; - } - const toolAnalyticsContext = t10; - let t11; - if ($2[27] !== theme2 || $2[28] !== toolUseConfirm.input || $2[29] !== toolUseConfirm.tool) { - t11 = toolUseConfirm.tool.renderToolUseMessage(toolUseConfirm.input, { - theme: theme2, - verbose: true - }); - $2[27] = theme2; - $2[28] = toolUseConfirm.input; - $2[29] = toolUseConfirm.tool; - $2[30] = t11; - } else { - t11 = $2[30]; - } - let t12; - if ($2[31] !== originalUserFacingName) { - t12 = originalUserFacingName.endsWith(" (MCP)") ? /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedText, { - dimColor: true, - children: " (MCP)" - }, undefined, false, undefined, this) : ""; - $2[31] = originalUserFacingName; - $2[32] = t12; - } else { - t12 = $2[32]; - } - let t13; - if ($2[33] !== t11 || $2[34] !== t12 || $2[35] !== userFacingName8) { - t13 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedText, { - children: [ - userFacingName8, - "(", - t11, - ")", - t12 - ] - }, undefined, true, undefined, this); - $2[33] = t11; - $2[34] = t12; - $2[35] = userFacingName8; - $2[36] = t13; - } else { - t13 = $2[36]; - } - let t14; - if ($2[37] !== toolUseConfirm.description) { - t14 = truncateToLines(toolUseConfirm.description, 3); - $2[37] = toolUseConfirm.description; - $2[38] = t14; - } else { - t14 = $2[38]; - } - let t15; - if ($2[39] !== t14) { - t15 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedText, { - dimColor: true, - children: t14 - }, undefined, false, undefined, this); - $2[39] = t14; - $2[40] = t15; - } else { - t15 = $2[40]; - } - let t16; - if ($2[41] !== t13 || $2[42] !== t15) { - t16 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - t13, - t15 - ] - }, undefined, true, undefined, this); - $2[41] = t13; - $2[42] = t15; - $2[43] = t16; - } else { - t16 = $2[43]; - } - let t17; - if ($2[44] !== toolUseConfirm.permissionResult) { - t17 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(PermissionRuleExplanation, { - permissionResult: toolUseConfirm.permissionResult, - toolType: "tool" - }, undefined, false, undefined, this); - $2[44] = toolUseConfirm.permissionResult; - $2[45] = t17; - } else { - t17 = $2[45]; - } - let t18; - if ($2[46] !== handleCancel || $2[47] !== handleSelect || $2[48] !== options2 || $2[49] !== toolAnalyticsContext) { - t18 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(PermissionPrompt, { - options: options2, - onSelect: handleSelect, - onCancel: handleCancel, - toolAnalyticsContext - }, undefined, false, undefined, this); - $2[46] = handleCancel; - $2[47] = handleSelect; - $2[48] = options2; - $2[49] = toolAnalyticsContext; - $2[50] = t18; - } else { - t18 = $2[50]; - } - let t19; - if ($2[51] !== t17 || $2[52] !== t18) { - t19 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t17, - t18 - ] - }, undefined, true, undefined, this); - $2[51] = t17; - $2[52] = t18; - $2[53] = t19; - } else { - t19 = $2[53]; - } - let t20; - if ($2[54] !== t16 || $2[55] !== t19 || $2[56] !== workerBadge) { - t20 = /* @__PURE__ */ jsx_dev_runtime389.jsxDEV(PermissionDialog, { - title: "Tool use", - workerBadge, - children: [ - t16, - t19 - ] - }, undefined, true, undefined, this); - $2[54] = t16; - $2[55] = t19; - $2[56] = workerBadge; - $2[57] = t20; - } else { - t20 = $2[57]; - } - return t20; -} -var import_compiler_runtime301, jsx_dev_runtime389; -var init_FallbackPermissionRequest = __esm(() => { - init_state(); - init_ink2(); - init_metadata(); - init_env(); - init_permissionsLoader(); - init_stringUtils(); - init_unaryLogging(); - init_hooks6(); - init_PermissionDialog(); - init_PermissionPrompt(); - init_PermissionRuleExplanation(); - import_compiler_runtime301 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime389 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/FilePermissionDialog/ideDiffConfig.ts -function createSingleEditDiffConfig(filePath, oldString, newString, replaceAll2) { - return { - filePath, - edits: [ - { - old_string: oldString, - new_string: newString, - replace_all: replaceAll2 - } - ], - editMode: "single" - }; -} - -// src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.tsx -import { basename as basename50, relative as relative32 } from "path"; -function FileEditPermissionRequest(props) { - const $2 = import_compiler_runtime302.c(51); - const parseInput = _temp180; - let T0; - let T1; - let T2; - let file_path; - let new_string; - let old_string; - let replace_all; - let t0; - let t1; - let t10; - let t22; - let t32; - let t4; - let t5; - let t6; - let t7; - let t8; - let t9; - if ($2[0] !== props.onDone || $2[1] !== props.onReject || $2[2] !== props.toolUseConfirm || $2[3] !== props.toolUseContext || $2[4] !== props.workerBadge) { - const parsed = parseInput(props.toolUseConfirm.input); - ({ - file_path, - old_string, - new_string, - replace_all - } = parsed); - T2 = FilePermissionDialog; - t4 = props.toolUseConfirm; - t5 = props.toolUseContext; - t6 = props.onDone; - t7 = props.onReject; - t8 = props.workerBadge; - t9 = "Edit file"; - t10 = relative32(getCwd(), file_path); - T1 = ThemedText; - t22 = "Do you want to make this edit to"; - t32 = " "; - T0 = ThemedText; - t0 = true; - t1 = basename50(file_path); - $2[0] = props.onDone; - $2[1] = props.onReject; - $2[2] = props.toolUseConfirm; - $2[3] = props.toolUseContext; - $2[4] = props.workerBadge; - $2[5] = T0; - $2[6] = T1; - $2[7] = T2; - $2[8] = file_path; - $2[9] = new_string; - $2[10] = old_string; - $2[11] = replace_all; - $2[12] = t0; - $2[13] = t1; - $2[14] = t10; - $2[15] = t22; - $2[16] = t32; - $2[17] = t4; - $2[18] = t5; - $2[19] = t6; - $2[20] = t7; - $2[21] = t8; - $2[22] = t9; - } else { - T0 = $2[5]; - T1 = $2[6]; - T2 = $2[7]; - file_path = $2[8]; - new_string = $2[9]; - old_string = $2[10]; - replace_all = $2[11]; - t0 = $2[12]; - t1 = $2[13]; - t10 = $2[14]; - t22 = $2[15]; - t32 = $2[16]; - t4 = $2[17]; - t5 = $2[18]; - t6 = $2[19]; - t7 = $2[20]; - t8 = $2[21]; - t9 = $2[22]; - } - let t11; - if ($2[23] !== T0 || $2[24] !== t0 || $2[25] !== t1) { - t11 = /* @__PURE__ */ jsx_dev_runtime390.jsxDEV(T0, { - bold: t0, - children: t1 - }, undefined, false, undefined, this); - $2[23] = T0; - $2[24] = t0; - $2[25] = t1; - $2[26] = t11; - } else { - t11 = $2[26]; - } - let t12; - if ($2[27] !== T1 || $2[28] !== t11 || $2[29] !== t22 || $2[30] !== t32) { - t12 = /* @__PURE__ */ jsx_dev_runtime390.jsxDEV(T1, { - children: [ - t22, - t32, - t11, - "?" - ] - }, undefined, true, undefined, this); - $2[27] = T1; - $2[28] = t11; - $2[29] = t22; - $2[30] = t32; - $2[31] = t12; - } else { - t12 = $2[31]; - } - const t13 = replace_all || false; - let t14; - if ($2[32] !== new_string || $2[33] !== old_string || $2[34] !== t13) { - t14 = [{ - old_string, - new_string, - replace_all: t13 - }]; - $2[32] = new_string; - $2[33] = old_string; - $2[34] = t13; - $2[35] = t14; - } else { - t14 = $2[35]; - } - let t15; - if ($2[36] !== file_path || $2[37] !== t14) { - t15 = /* @__PURE__ */ jsx_dev_runtime390.jsxDEV(FileEditToolDiff, { - file_path, - edits: t14 - }, undefined, false, undefined, this); - $2[36] = file_path; - $2[37] = t14; - $2[38] = t15; - } else { - t15 = $2[38]; - } - let t16; - if ($2[39] !== T2 || $2[40] !== file_path || $2[41] !== t10 || $2[42] !== t12 || $2[43] !== t15 || $2[44] !== t4 || $2[45] !== t5 || $2[46] !== t6 || $2[47] !== t7 || $2[48] !== t8 || $2[49] !== t9) { - t16 = /* @__PURE__ */ jsx_dev_runtime390.jsxDEV(T2, { - toolUseConfirm: t4, - toolUseContext: t5, - onDone: t6, - onReject: t7, - workerBadge: t8, - title: t9, - subtitle: t10, - question: t12, - content: t15, - path: file_path, - completionType: "str_replace_single", - parseInput, - ideDiffSupport - }, undefined, false, undefined, this); - $2[39] = T2; - $2[40] = file_path; - $2[41] = t10; - $2[42] = t12; - $2[43] = t15; - $2[44] = t4; - $2[45] = t5; - $2[46] = t6; - $2[47] = t7; - $2[48] = t8; - $2[49] = t9; - $2[50] = t16; - } else { - t16 = $2[50]; - } - return t16; -} -function _temp180(input) { - return FileEditTool.inputSchema.parse(input); -} -var import_compiler_runtime302, jsx_dev_runtime390, ideDiffSupport; -var init_FileEditPermissionRequest = __esm(() => { - init_FileEditToolDiff(); - init_cwd(); - init_ink2(); - init_FileEditTool(); - init_FilePermissionDialog(); - import_compiler_runtime302 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime390 = __toESM(require_jsx_dev_runtime(), 1); - ideDiffSupport = { - getConfig: (input) => createSingleEditDiffConfig(input.file_path, input.old_string, input.new_string, input.replace_all), - applyChanges: (input, modifiedEdits) => { - const firstEdit = modifiedEdits[0]; - if (firstEdit) { - return { - ...input, - old_string: firstEdit.old_string, - new_string: firstEdit.new_string, - replace_all: firstEdit.replace_all - }; - } - return input; - } - }; -}); - -// src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsx -function pathFromToolUse(toolUseConfirm) { - const tool = toolUseConfirm.tool; - if ("getPath" in tool && typeof tool.getPath === "function") { - try { - return tool.getPath(toolUseConfirm.input); - } catch { - return null; - } - } - return null; -} -function FilesystemPermissionRequest(t0) { - const $2 = import_compiler_runtime303.c(30); - const { - toolUseConfirm, - onDone, - onReject, - verbose, - toolUseContext, - workerBadge - } = t0; - const [theme2] = useTheme(); - let t1; - if ($2[0] !== toolUseConfirm) { - t1 = pathFromToolUse(toolUseConfirm); - $2[0] = toolUseConfirm; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const path26 = t1; - let t22; - if ($2[2] !== toolUseConfirm.input || $2[3] !== toolUseConfirm.tool) { - t22 = toolUseConfirm.tool.userFacingName(toolUseConfirm.input); - $2[2] = toolUseConfirm.input; - $2[3] = toolUseConfirm.tool; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const userFacingName8 = t22; - const isReadOnly = toolUseConfirm.tool.isReadOnly(toolUseConfirm.input); - const userFacingReadOrEdit = isReadOnly ? "Read" : "Edit"; - const title = `${userFacingReadOrEdit} file`; - const parseInput = _temp181; - if (!path26) { - let t33; - if ($2[5] !== onDone || $2[6] !== onReject || $2[7] !== toolUseConfirm || $2[8] !== toolUseContext || $2[9] !== verbose || $2[10] !== workerBadge) { - t33 = /* @__PURE__ */ jsx_dev_runtime391.jsxDEV(FallbackPermissionRequest, { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - verbose, - workerBadge - }, undefined, false, undefined, this); - $2[5] = onDone; - $2[6] = onReject; - $2[7] = toolUseConfirm; - $2[8] = toolUseContext; - $2[9] = verbose; - $2[10] = workerBadge; - $2[11] = t33; - } else { - t33 = $2[11]; - } - return t33; - } - let t32; - if ($2[12] !== theme2 || $2[13] !== toolUseConfirm.input || $2[14] !== toolUseConfirm.tool || $2[15] !== verbose) { - t32 = toolUseConfirm.tool.renderToolUseMessage(toolUseConfirm.input, { - theme: theme2, - verbose - }); - $2[12] = theme2; - $2[13] = toolUseConfirm.input; - $2[14] = toolUseConfirm.tool; - $2[15] = verbose; - $2[16] = t32; - } else { - t32 = $2[16]; - } - let t4; - if ($2[17] !== t32 || $2[18] !== userFacingName8) { - t4 = /* @__PURE__ */ jsx_dev_runtime391.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: /* @__PURE__ */ jsx_dev_runtime391.jsxDEV(ThemedText, { - children: [ - userFacingName8, - "(", - t32, - ")" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[17] = t32; - $2[18] = userFacingName8; - $2[19] = t4; - } else { - t4 = $2[19]; - } - const content = t4; - const t5 = isReadOnly ? "read" : "write"; - let t6; - if ($2[20] !== content || $2[21] !== onDone || $2[22] !== onReject || $2[23] !== path26 || $2[24] !== t5 || $2[25] !== title || $2[26] !== toolUseConfirm || $2[27] !== toolUseContext || $2[28] !== workerBadge) { - t6 = /* @__PURE__ */ jsx_dev_runtime391.jsxDEV(FilePermissionDialog, { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - workerBadge, - title, - content, - path: path26, - parseInput, - operationType: t5, - completionType: "tool_use_single" - }, undefined, false, undefined, this); - $2[20] = content; - $2[21] = onDone; - $2[22] = onReject; - $2[23] = path26; - $2[24] = t5; - $2[25] = title; - $2[26] = toolUseConfirm; - $2[27] = toolUseContext; - $2[28] = workerBadge; - $2[29] = t6; - } else { - t6 = $2[29]; - } - return t6; -} -function _temp181(input) { - return input; -} -var import_compiler_runtime303, jsx_dev_runtime391; -var init_FilesystemPermissionRequest = __esm(() => { - init_ink2(); - init_FallbackPermissionRequest(); - init_FilePermissionDialog(); - import_compiler_runtime303 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime391 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.tsx -function FileWriteToolDiff(t0) { - const $2 = import_compiler_runtime304.c(15); - const { - file_path, - content, - fileExists, - oldContent - } = t0; - const { - columns - } = useTerminalSize(); - let t1; - bb0: { - if (!fileExists) { - t1 = null; - break bb0; - } - let t23; - if ($2[0] !== content || $2[1] !== file_path || $2[2] !== oldContent) { - t23 = getPatchForDisplay({ - filePath: file_path, - fileContents: oldContent, - edits: [{ - old_string: oldContent, - new_string: content, - replace_all: false - }] - }); - $2[0] = content; - $2[1] = file_path; - $2[2] = oldContent; - $2[3] = t23; - } else { - t23 = $2[3]; - } - t1 = t23; - } - const hunks = t1; - let t22; - if ($2[4] !== content) { - t22 = content.split(` -`)[0] ?? null; - $2[4] = content; - $2[5] = t22; - } else { - t22 = $2[5]; - } - const firstLine = t22; - let t32; - if ($2[6] !== columns || $2[7] !== content || $2[8] !== file_path || $2[9] !== firstLine || $2[10] !== hunks || $2[11] !== oldContent) { - t32 = hunks ? intersperse(hunks.map((_) => /* @__PURE__ */ jsx_dev_runtime392.jsxDEV(StructuredDiff, { - patch: _, - dim: false, - filePath: file_path, - firstLine, - fileContent: oldContent, - width: columns - 2 - }, _.newStart, false, undefined, this)), _temp183) : /* @__PURE__ */ jsx_dev_runtime392.jsxDEV(HighlightedCode, { - code: content || "(No content)", - filePath: file_path - }, undefined, false, undefined, this); - $2[6] = columns; - $2[7] = content; - $2[8] = file_path; - $2[9] = firstLine; - $2[10] = hunks; - $2[11] = oldContent; - $2[12] = t32; - } else { - t32 = $2[12]; - } - let t4; - if ($2[13] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime392.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime392.jsxDEV(ThemedBox_default, { - borderColor: "subtle", - borderStyle: "dashed", - flexDirection: "column", - borderLeft: false, - borderRight: false, - paddingX: 1, - children: t32 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[13] = t32; - $2[14] = t4; - } else { - t4 = $2[14]; - } - return t4; -} -function _temp183(i6) { - return /* @__PURE__ */ jsx_dev_runtime392.jsxDEV(NoSelect, { - fromLeftEdge: true, - children: /* @__PURE__ */ jsx_dev_runtime392.jsxDEV(ThemedText, { - dimColor: true, - children: "..." - }, undefined, false, undefined, this) - }, `ellipsis-${i6}`, false, undefined, this); -} -var import_compiler_runtime304, jsx_dev_runtime392; -var init_FileWriteToolDiff = __esm(() => { - init_useTerminalSize(); - init_ink2(); - init_diff2(); - init_HighlightedCode(); - init_StructuredDiff(); - import_compiler_runtime304 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime392 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.tsx -import { basename as basename51, relative as relative33 } from "path"; -function FileWritePermissionRequest(props) { - const $2 = import_compiler_runtime305.c(30); - const parseInput = _temp185; - let t0; - if ($2[0] !== props.toolUseConfirm.input) { - t0 = parseInput(props.toolUseConfirm.input); - $2[0] = props.toolUseConfirm.input; - $2[1] = t0; - } else { - t0 = $2[1]; - } - const parsed = t0; - const { - file_path, - content - } = parsed; - let t1; - if ($2[2] !== file_path) { - try { - t1 = { - fileExists: true, - oldContent: readFileSync4(file_path) - }; - } catch (t23) { - const e4 = t23; - if (!isENOENT(e4)) { - throw e4; - } - let t33; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t33 = { - fileExists: false, - oldContent: "" - }; - $2[4] = t33; - } else { - t33 = $2[4]; - } - t1 = t33; - } - $2[2] = file_path; - $2[3] = t1; - } else { - t1 = $2[3]; - } - const { - fileExists, - oldContent - } = t1; - const actionText = fileExists ? "overwrite" : "create"; - const t22 = props.toolUseConfirm; - const t32 = props.toolUseContext; - const t4 = props.onDone; - const t5 = props.onReject; - const t6 = props.workerBadge; - const t7 = fileExists ? "Overwrite file" : "Create file"; - let t8; - if ($2[5] !== file_path) { - t8 = relative33(getCwd(), file_path); - $2[5] = file_path; - $2[6] = t8; - } else { - t8 = $2[6]; - } - let t9; - if ($2[7] !== file_path) { - t9 = basename51(file_path); - $2[7] = file_path; - $2[8] = t9; - } else { - t9 = $2[8]; - } - let t10; - if ($2[9] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime393.jsxDEV(ThemedText, { - bold: true, - children: t9 - }, undefined, false, undefined, this); - $2[9] = t9; - $2[10] = t10; - } else { - t10 = $2[10]; - } - let t11; - if ($2[11] !== actionText || $2[12] !== t10) { - t11 = /* @__PURE__ */ jsx_dev_runtime393.jsxDEV(ThemedText, { - children: [ - "Do you want to ", - actionText, - " ", - t10, - "?" - ] - }, undefined, true, undefined, this); - $2[11] = actionText; - $2[12] = t10; - $2[13] = t11; - } else { - t11 = $2[13]; - } - let t12; - if ($2[14] !== content || $2[15] !== fileExists || $2[16] !== file_path || $2[17] !== oldContent) { - t12 = /* @__PURE__ */ jsx_dev_runtime393.jsxDEV(FileWriteToolDiff, { - file_path, - content, - fileExists, - oldContent - }, undefined, false, undefined, this); - $2[14] = content; - $2[15] = fileExists; - $2[16] = file_path; - $2[17] = oldContent; - $2[18] = t12; - } else { - t12 = $2[18]; - } - let t13; - if ($2[19] !== file_path || $2[20] !== props.onDone || $2[21] !== props.onReject || $2[22] !== props.toolUseConfirm || $2[23] !== props.toolUseContext || $2[24] !== props.workerBadge || $2[25] !== t11 || $2[26] !== t12 || $2[27] !== t7 || $2[28] !== t8) { - t13 = /* @__PURE__ */ jsx_dev_runtime393.jsxDEV(FilePermissionDialog, { - toolUseConfirm: t22, - toolUseContext: t32, - onDone: t4, - onReject: t5, - workerBadge: t6, - title: t7, - subtitle: t8, - question: t11, - content: t12, - path: file_path, - completionType: "write_file_single", - parseInput, - ideDiffSupport: ideDiffSupport2 - }, undefined, false, undefined, this); - $2[19] = file_path; - $2[20] = props.onDone; - $2[21] = props.onReject; - $2[22] = props.toolUseConfirm; - $2[23] = props.toolUseContext; - $2[24] = props.workerBadge; - $2[25] = t11; - $2[26] = t12; - $2[27] = t7; - $2[28] = t8; - $2[29] = t13; - } else { - t13 = $2[29]; - } - return t13; -} -function _temp185(input) { - return FileWriteTool.inputSchema.parse(input); -} -var import_compiler_runtime305, jsx_dev_runtime393, ideDiffSupport2; -var init_FileWritePermissionRequest = __esm(() => { - init_ink2(); - init_FileWriteTool(); - init_cwd(); - init_errors(); - init_fileRead(); - init_FilePermissionDialog(); - init_FileWriteToolDiff(); - import_compiler_runtime305 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime393 = __toESM(require_jsx_dev_runtime(), 1); - ideDiffSupport2 = { - getConfig: (input) => { - let oldContent; - try { - oldContent = readFileSync4(input.file_path); - } catch (e4) { - if (!isENOENT(e4)) - throw e4; - oldContent = ""; - } - return createSingleEditDiffConfig(input.file_path, oldContent, input.content, false); - }, - applyChanges: (input, modifiedEdits) => { - const firstEdit = modifiedEdits[0]; - if (firstEdit) { - return { - ...input, - content: firstEdit.new_string - }; - } - return input; - } - }; -}); - -// src/components/permissions/NotebookEditPermissionRequest/NotebookEditToolDiff.tsx -import { relative as relative34 } from "path"; -function NotebookEditToolDiff(props) { - const $2 = import_compiler_runtime306.c(5); - let t0; - if ($2[0] !== props.notebook_path) { - t0 = getFsImplementation().readFile(props.notebook_path, { - encoding: "utf-8" - }).then(_temp186).catch(_temp277); - $2[0] = props.notebook_path; - $2[1] = t0; - } else { - t0 = $2[1]; - } - const notebookDataPromise = t0; - let t1; - if ($2[2] !== notebookDataPromise || $2[3] !== props) { - t1 = /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(import_react218.Suspense, { - fallback: null, - children: /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(NotebookEditToolDiffInner, { - ...props, - promise: notebookDataPromise - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[2] = notebookDataPromise; - $2[3] = props; - $2[4] = t1; - } else { - t1 = $2[4]; - } - return t1; -} -function _temp277() { - return null; -} -function _temp186(content) { - return safeParseJSON(content); -} -function NotebookEditToolDiffInner(t0) { - const $2 = import_compiler_runtime306.c(34); - const { - notebook_path, - cell_id, - new_source, - cell_type, - edit_mode: t1, - verbose, - width, - promise: promise3 - } = t0; - const edit_mode = t1 === undefined ? "replace" : t1; - const notebookData = import_react218.use(promise3); - let t22; - if ($2[0] !== cell_id || $2[1] !== notebookData) { - bb0: { - if (!notebookData || !cell_id) { - t22 = ""; - break bb0; - } - const cellIndex = parseCellId(cell_id); - if (cellIndex !== undefined) { - if (notebookData.cells[cellIndex]) { - const source = notebookData.cells[cellIndex].source; - let t34; - if ($2[3] !== source) { - t34 = Array.isArray(source) ? source.join("") : source; - $2[3] = source; - $2[4] = t34; - } else { - t34 = $2[4]; - } - t22 = t34; - break bb0; - } - t22 = ""; - break bb0; - } - let t33; - if ($2[5] !== cell_id) { - t33 = (cell) => cell.id === cell_id; - $2[5] = cell_id; - $2[6] = t33; - } else { - t33 = $2[6]; - } - const cell_0 = notebookData.cells.find(t33); - if (!cell_0) { - t22 = ""; - break bb0; - } - t22 = Array.isArray(cell_0.source) ? cell_0.source.join("") : cell_0.source; - } - $2[0] = cell_id; - $2[1] = notebookData; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const oldSource = t22; - let t32; - bb1: { - if (!notebookData || edit_mode === "insert" || edit_mode === "delete") { - t32 = null; - break bb1; - } - let t42; - if ($2[7] !== new_source || $2[8] !== notebook_path || $2[9] !== oldSource) { - t42 = getPatchForDisplay({ - filePath: notebook_path, - fileContents: oldSource, - edits: [{ - old_string: oldSource, - new_string: new_source, - replace_all: false - }], - ignoreWhitespace: false - }); - $2[7] = new_source; - $2[8] = notebook_path; - $2[9] = oldSource; - $2[10] = t42; - } else { - t42 = $2[10]; - } - t32 = t42; - } - const hunks = t32; - let editTypeDescription; - bb2: - switch (edit_mode) { - case "insert": { - editTypeDescription = "Insert new cell"; - break bb2; - } - case "delete": { - editTypeDescription = "Delete cell"; - break bb2; - } - default: { - editTypeDescription = "Replace cell contents"; - } - } - let t4; - if ($2[11] !== notebook_path || $2[12] !== verbose) { - t4 = verbose ? notebook_path : relative34(getCwd(), notebook_path); - $2[11] = notebook_path; - $2[12] = verbose; - $2[13] = t4; - } else { - t4 = $2[13]; - } - let t5; - if ($2[14] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedText, { - bold: true, - children: t4 - }, undefined, false, undefined, this); - $2[14] = t4; - $2[15] = t5; - } else { - t5 = $2[15]; - } - const t6 = cell_type ? ` (${cell_type})` : ""; - let t7; - if ($2[16] !== cell_id || $2[17] !== editTypeDescription || $2[18] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedText, { - dimColor: true, - children: [ - editTypeDescription, - " for cell ", - cell_id, - t6 - ] - }, undefined, true, undefined, this); - $2[16] = cell_id; - $2[17] = editTypeDescription; - $2[18] = t6; - $2[19] = t7; - } else { - t7 = $2[19]; - } - let t8; - if ($2[20] !== t5 || $2[21] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedBox_default, { - paddingBottom: 1, - flexDirection: "column", - children: [ - t5, - t7 - ] - }, undefined, true, undefined, this); - $2[20] = t5; - $2[21] = t7; - $2[22] = t8; - } else { - t8 = $2[22]; - } - let t9; - if ($2[23] !== cell_type || $2[24] !== edit_mode || $2[25] !== hunks || $2[26] !== new_source || $2[27] !== notebook_path || $2[28] !== oldSource || $2[29] !== width) { - t9 = edit_mode === "delete" ? /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(HighlightedCode, { - code: oldSource, - filePath: notebook_path - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : edit_mode === "insert" ? /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(HighlightedCode, { - code: new_source, - filePath: cell_type === "markdown" ? "file.md" : notebook_path - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : hunks ? intersperse(hunks.map((_) => /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(StructuredDiff, { - patch: _, - dim: false, - width, - filePath: notebook_path, - firstLine: new_source.split(` -`)[0] ?? null, - fileContent: oldSource - }, _.newStart, false, undefined, this)), _temp351) : /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(HighlightedCode, { - code: new_source, - filePath: cell_type === "markdown" ? "file.md" : notebook_path - }, undefined, false, undefined, this); - $2[23] = cell_type; - $2[24] = edit_mode; - $2[25] = hunks; - $2[26] = new_source; - $2[27] = notebook_path; - $2[28] = oldSource; - $2[29] = width; - $2[30] = t9; - } else { - t9 = $2[30]; - } - let t10; - if ($2[31] !== t8 || $2[32] !== t9) { - t10 = /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedBox_default, { - borderStyle: "round", - flexDirection: "column", - paddingX: 1, - children: [ - t8, - t9 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[31] = t8; - $2[32] = t9; - $2[33] = t10; - } else { - t10 = $2[33]; - } - return t10; -} -function _temp351(i6) { - return /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(NoSelect, { - fromLeftEdge: true, - children: /* @__PURE__ */ jsx_dev_runtime394.jsxDEV(ThemedText, { - dimColor: true, - children: "..." - }, undefined, false, undefined, this) - }, `ellipsis-${i6}`, false, undefined, this); -} -var import_compiler_runtime306, import_react218, jsx_dev_runtime394; -var init_NotebookEditToolDiff = __esm(() => { - init_ink2(); - init_cwd(); - init_diff2(); - init_fsOperations(); - init_json(); - init_notebook(); - init_HighlightedCode(); - init_StructuredDiff(); - import_compiler_runtime306 = __toESM(require_compiler_runtime(), 1); - import_react218 = __toESM(require_react(), 1); - jsx_dev_runtime394 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/NotebookEditPermissionRequest/NotebookEditPermissionRequest.tsx -import { basename as basename52 } from "path"; -function NotebookEditPermissionRequest(props) { - const $2 = import_compiler_runtime307.c(52); - const parseInput = _temp187; - let T0; - let T1; - let T2; - let language; - let notebook_path; - let parsed; - let t0; - let t1; - let t10; - let t22; - let t32; - let t4; - let t5; - let t6; - let t7; - let t8; - let t9; - if ($2[0] !== props.onDone || $2[1] !== props.onReject || $2[2] !== props.toolUseConfirm || $2[3] !== props.toolUseContext || $2[4] !== props.workerBadge) { - parsed = parseInput(props.toolUseConfirm.input); - const { - notebook_path: t112, - edit_mode, - cell_type - } = parsed; - notebook_path = t112; - language = cell_type === "markdown" ? "markdown" : "python"; - const editTypeText = edit_mode === "insert" ? "insert this cell into" : edit_mode === "delete" ? "delete this cell from" : "make this edit to"; - T2 = FilePermissionDialog; - t5 = props.toolUseConfirm; - t6 = props.toolUseContext; - t7 = props.onDone; - t8 = props.onReject; - t9 = props.workerBadge; - t10 = "Edit notebook"; - T1 = ThemedText; - t22 = "Do you want to "; - t32 = editTypeText; - t4 = " "; - T0 = ThemedText; - t0 = true; - t1 = basename52(notebook_path); - $2[0] = props.onDone; - $2[1] = props.onReject; - $2[2] = props.toolUseConfirm; - $2[3] = props.toolUseContext; - $2[4] = props.workerBadge; - $2[5] = T0; - $2[6] = T1; - $2[7] = T2; - $2[8] = language; - $2[9] = notebook_path; - $2[10] = parsed; - $2[11] = t0; - $2[12] = t1; - $2[13] = t10; - $2[14] = t22; - $2[15] = t32; - $2[16] = t4; - $2[17] = t5; - $2[18] = t6; - $2[19] = t7; - $2[20] = t8; - $2[21] = t9; - } else { - T0 = $2[5]; - T1 = $2[6]; - T2 = $2[7]; - language = $2[8]; - notebook_path = $2[9]; - parsed = $2[10]; - t0 = $2[11]; - t1 = $2[12]; - t10 = $2[13]; - t22 = $2[14]; - t32 = $2[15]; - t4 = $2[16]; - t5 = $2[17]; - t6 = $2[18]; - t7 = $2[19]; - t8 = $2[20]; - t9 = $2[21]; - } - let t11; - if ($2[22] !== T0 || $2[23] !== t0 || $2[24] !== t1) { - t11 = /* @__PURE__ */ jsx_dev_runtime395.jsxDEV(T0, { - bold: t0, - children: t1 - }, undefined, false, undefined, this); - $2[22] = T0; - $2[23] = t0; - $2[24] = t1; - $2[25] = t11; - } else { - t11 = $2[25]; - } - let t12; - if ($2[26] !== T1 || $2[27] !== t11 || $2[28] !== t22 || $2[29] !== t32 || $2[30] !== t4) { - t12 = /* @__PURE__ */ jsx_dev_runtime395.jsxDEV(T1, { - children: [ - t22, - t32, - t4, - t11, - "?" - ] - }, undefined, true, undefined, this); - $2[26] = T1; - $2[27] = t11; - $2[28] = t22; - $2[29] = t32; - $2[30] = t4; - $2[31] = t12; - } else { - t12 = $2[31]; - } - const t13 = props.verbose ? 120 : 80; - let t14; - if ($2[32] !== parsed.cell_id || $2[33] !== parsed.cell_type || $2[34] !== parsed.edit_mode || $2[35] !== parsed.new_source || $2[36] !== parsed.notebook_path || $2[37] !== props.verbose || $2[38] !== t13) { - t14 = /* @__PURE__ */ jsx_dev_runtime395.jsxDEV(NotebookEditToolDiff, { - notebook_path: parsed.notebook_path, - cell_id: parsed.cell_id, - new_source: parsed.new_source, - cell_type: parsed.cell_type, - edit_mode: parsed.edit_mode, - verbose: props.verbose, - width: t13 - }, undefined, false, undefined, this); - $2[32] = parsed.cell_id; - $2[33] = parsed.cell_type; - $2[34] = parsed.edit_mode; - $2[35] = parsed.new_source; - $2[36] = parsed.notebook_path; - $2[37] = props.verbose; - $2[38] = t13; - $2[39] = t14; - } else { - t14 = $2[39]; - } - let t15; - if ($2[40] !== T2 || $2[41] !== language || $2[42] !== notebook_path || $2[43] !== t10 || $2[44] !== t12 || $2[45] !== t14 || $2[46] !== t5 || $2[47] !== t6 || $2[48] !== t7 || $2[49] !== t8 || $2[50] !== t9) { - t15 = /* @__PURE__ */ jsx_dev_runtime395.jsxDEV(T2, { - toolUseConfirm: t5, - toolUseContext: t6, - onDone: t7, - onReject: t8, - workerBadge: t9, - title: t10, - question: t12, - content: t14, - path: notebook_path, - completionType: "tool_use_single", - languageName: language, - parseInput - }, undefined, false, undefined, this); - $2[40] = T2; - $2[41] = language; - $2[42] = notebook_path; - $2[43] = t10; - $2[44] = t12; - $2[45] = t14; - $2[46] = t5; - $2[47] = t6; - $2[48] = t7; - $2[49] = t8; - $2[50] = t9; - $2[51] = t15; - } else { - t15 = $2[51]; - } - return t15; -} -function _temp187(input) { - const result = NotebookEditTool.inputSchema.safeParse(input); - if (!result.success) { - logError2(new Error(`Failed to parse notebook edit input: ${result.error.message}`)); - return { - notebook_path: "", - new_source: "", - cell_id: "" - }; - } - return result.data; -} -var import_compiler_runtime307, jsx_dev_runtime395; -var init_NotebookEditPermissionRequest = __esm(() => { - init_ink2(); - init_NotebookEditTool(); - init_log2(); - init_FilePermissionDialog(); - init_NotebookEditToolDiff(); - import_compiler_runtime307 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime395 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/tools/PowerShellTool/destructiveCommandWarning.ts -function getDestructiveCommandWarning2(command19) { - for (const { pattern, warning } of DESTRUCTIVE_PATTERNS2) { - if (pattern.test(command19)) { - return warning; - } - } - return null; -} -var DESTRUCTIVE_PATTERNS2; -var init_destructiveCommandWarning2 = __esm(() => { - DESTRUCTIVE_PATTERNS2 = [ - { - pattern: /(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Recurse\b[^|;&\n}]*-Force\b/i, - warning: "Note: may recursively force-remove files" - }, - { - pattern: /(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Force\b[^|;&\n}]*-Recurse\b/i, - warning: "Note: may recursively force-remove files" - }, - { - pattern: /(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Recurse\b/i, - warning: "Note: may recursively remove files" - }, - { - pattern: /(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Force\b/i, - warning: "Note: may force-remove files" - }, - { - pattern: /\bClear-Content\b[^|;&\n]*\*/i, - warning: "Note: may clear content of multiple files" - }, - { - pattern: /\bFormat-Volume\b/i, - warning: "Note: may format a disk volume" - }, - { - pattern: /\bClear-Disk\b/i, - warning: "Note: may clear a disk" - }, - { - pattern: /\bgit\s+reset\s+--hard\b/i, - warning: "Note: may discard uncommitted changes" - }, - { - pattern: /\bgit\s+push\b[^|;&\n]*\s+(--force|--force-with-lease|-f)\b/i, - warning: "Note: may overwrite remote history" - }, - { - pattern: /\bgit\s+clean\b(?![^|;&\n]*(?:-[a-zA-Z]*n|--dry-run))[^|;&\n]*-[a-zA-Z]*f/i, - warning: "Note: may permanently delete untracked files" - }, - { - pattern: /\bgit\s+stash\s+(drop|clear)\b/i, - warning: "Note: may permanently remove stashed changes" - }, - { - pattern: /\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA)\b/i, - warning: "Note: may drop or truncate database objects" - }, - { - pattern: /\bStop-Computer\b/i, - warning: "Note: will shut down the computer" - }, - { - pattern: /\bRestart-Computer\b/i, - warning: "Note: will restart the computer" - }, - { - pattern: /\bClear-RecycleBin\b/i, - warning: "Note: permanently deletes recycled files" - } - ]; -}); - -// src/utils/powershell/staticPrefix.ts -async function extractPrefixFromElement(cmd) { - if (cmd.nameType === "application") { - return null; - } - const name3 = cmd.name; - if (!name3) { - return null; - } - if (NEVER_SUGGEST.has(name3.toLowerCase())) { - return null; - } - if (cmd.nameType === "cmdlet") { - return name3; - } - if (cmd.elementTypes?.[0] !== "StringConstant") { - return null; - } - for (let i6 = 0;i6 < cmd.args.length; i6++) { - const t4 = cmd.elementTypes[i6 + 1]; - if (t4 !== "StringConstant" && t4 !== "Parameter") { - return null; - } - } - const nameLower = name3.toLowerCase(); - const spec = await getCommandSpec(nameLower); - const prefix = await buildPrefix(name3, cmd.args, spec); - let argIdx = 0; - for (const word of prefix.split(" ").slice(1)) { - if (word.includes("\\")) - return null; - while (argIdx < cmd.args.length) { - const a5 = cmd.args[argIdx]; - if (a5 === word) - break; - if (a5.startsWith("-")) { - argIdx++; - if (spec?.options && argIdx < cmd.args.length && cmd.args[argIdx] !== word && !cmd.args[argIdx].startsWith("-")) { - const flagLower = a5.toLowerCase(); - const opt = spec.options.find((o5) => Array.isArray(o5.name) ? o5.name.includes(flagLower) : o5.name === flagLower); - if (opt?.args) { - argIdx++; - } - } - continue; - } - return null; - } - if (argIdx >= cmd.args.length) - return null; - argIdx++; - } - if (!prefix.includes(" ") && (spec?.subcommands?.length || DEPTH_RULES[nameLower])) { - return null; - } - return prefix; -} -async function getCompoundCommandPrefixesStatic2(command19, excludeSubcommand) { - const parsed = await parsePowerShellCommandCached(command19); - if (!parsed.valid) { - return []; - } - const commands7 = getAllCommands(parsed).filter((cmd) => cmd.elementType === "CommandAst"); - if (commands7.length <= 1) { - const prefix = commands7[0] ? await extractPrefixFromElement(commands7[0]) : null; - return prefix ? [prefix] : []; - } - const prefixes = []; - for (const cmd of commands7) { - if (excludeSubcommand?.(cmd)) { - continue; - } - const prefix = await extractPrefixFromElement(cmd); - if (prefix) { - prefixes.push(prefix); - } - } - if (prefixes.length === 0) { - return []; - } - const groups = new Map; - for (const prefix of prefixes) { - const root3 = prefix.split(" ")[0]; - const key2 = root3.toLowerCase(); - const group = groups.get(key2); - if (group) { - group.push(prefix); - } else { - groups.set(key2, [prefix]); - } - } - const collapsed = []; - for (const [rootLower, group] of groups) { - const lcp = wordAlignedLCP(group); - const lcpWordCount = lcp === "" ? 0 : countCharInString(lcp, " ") + 1; - if (lcpWordCount <= 1) { - const rootSpec = await getCommandSpec(rootLower); - if (rootSpec?.subcommands?.length || DEPTH_RULES[rootLower]) { - continue; - } - } - collapsed.push(lcp); - } - return collapsed; -} -function wordAlignedLCP(strings) { - if (strings.length === 0) - return ""; - if (strings.length === 1) - return strings[0]; - const firstWords = strings[0].split(" "); - let commonWordCount = firstWords.length; - for (let i6 = 1;i6 < strings.length; i6++) { - const words = strings[i6].split(" "); - let matchCount = 0; - while (matchCount < commonWordCount && matchCount < words.length && words[matchCount].toLowerCase() === firstWords[matchCount].toLowerCase()) { - matchCount++; - } - commonWordCount = matchCount; - if (commonWordCount === 0) - break; - } - return firstWords.slice(0, commonWordCount).join(" "); -} -var init_staticPrefix = __esm(() => { - init_registry2(); - init_specPrefix(); - init_stringUtils(); - init_dangerousCmdlets(); - init_parser11(); -}); - -// src/components/permissions/PowerShellPermissionRequest/powershellToolUseOptions.tsx -function powershellToolUseOptions({ - suggestions = [], - onRejectFeedbackChange, - onAcceptFeedbackChange, - yesInputMode = false, - noInputMode = false, - editablePrefix, - onEditablePrefixChange -}) { - const options2 = []; - if (yesInputMode) { - options2.push({ - type: "input", - label: "Yes", - value: "yes", - placeholder: "and tell Claude what to do next", - onChange: onAcceptFeedbackChange, - allowEmptySubmitToCancel: true - }); - } else { - options2.push({ - label: "Yes", - value: "yes" - }); - } - if (shouldShowAlwaysAllowOptions() && suggestions.length > 0) { - const hasNonPowerShellSuggestions = suggestions.some((s4) => s4.type === "addDirectories" || s4.type === "addRules" && s4.rules?.some((r4) => r4.toolName !== POWERSHELL_TOOL_NAME)); - if (editablePrefix !== undefined && onEditablePrefixChange && !hasNonPowerShellSuggestions) { - options2.push({ - type: "input", - label: "Yes, and don\u2019t ask again for", - value: "yes-prefix-edited", - placeholder: "command prefix (e.g., Get-Process:*)", - initialValue: editablePrefix, - onChange: onEditablePrefixChange, - allowEmptySubmitToCancel: true, - showLabelWithValue: true, - labelValueSeparator: ": ", - resetCursorOnUpdate: true - }); - } else { - const label = generateShellSuggestionsLabel(suggestions, POWERSHELL_TOOL_NAME); - if (label) { - options2.push({ - label, - value: "yes-apply-suggestions" - }); - } - } - } - if (noInputMode) { - options2.push({ - type: "input", - label: "No", - value: "no", - placeholder: "and tell Claude what to do differently", - onChange: onRejectFeedbackChange, - allowEmptySubmitToCancel: true - }); - } else { - options2.push({ - label: "No", - value: "no" - }); - } - return options2; -} -var init_powershellToolUseOptions = __esm(() => { - init_permissionsLoader(); - init_shellPermissionHelpers(); -}); - -// src/components/permissions/PowerShellPermissionRequest/PowerShellPermissionRequest.tsx -function PowerShellPermissionRequest(props) { - const { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - workerBadge - } = props; - const { - command: command19, - description - } = PowerShellTool.inputSchema.parse(toolUseConfirm.input); - const [theme2] = useTheme(); - const explainerState = usePermissionExplainerUI({ - toolName: toolUseConfirm.tool.name, - toolInput: toolUseConfirm.input, - toolDescription: toolUseConfirm.description, - messages: toolUseContext.messages - }); - const { - yesInputMode, - noInputMode, - yesFeedbackModeEntered, - noFeedbackModeEntered, - acceptFeedback, - rejectFeedback, - setAcceptFeedback, - setRejectFeedback, - focusedOption, - handleInputModeToggle, - handleReject: handleReject2, - handleFocus - } = useShellPermissionFeedback({ - toolUseConfirm, - onDone, - onReject, - explainerVisible: explainerState.visible - }); - const destructiveWarning = getFeatureValue_CACHED_MAY_BE_STALE("tengu_destructive_command_warning", false) ? getDestructiveCommandWarning2(command19) : null; - const [showPermissionDebug, setShowPermissionDebug] = import_react219.useState(false); - const [editablePrefix, setEditablePrefix] = import_react219.useState(command19.includes(` -`) ? undefined : command19); - const hasUserEditedPrefix = import_react219.useRef(false); - import_react219.useEffect(() => { - let cancelled = false; - getCompoundCommandPrefixesStatic2(command19, (element) => isAllowlistedCommand(element, element.text)).then((prefixes) => { - if (cancelled || hasUserEditedPrefix.current) - return; - if (prefixes.length > 0) { - setEditablePrefix(`${prefixes[0]}:*`); - } - }).catch(() => {}); - return () => { - cancelled = true; - }; - }, [command19]); - const onEditablePrefixChange = import_react219.useCallback((value) => { - hasUserEditedPrefix.current = true; - setEditablePrefix(value); - }, []); - const unaryEvent = import_react219.useMemo(() => ({ - completion_type: "tool_use_single", - language_name: "none" - }), []); - usePermissionRequestLogging(toolUseConfirm, unaryEvent); - const options2 = import_react219.useMemo(() => powershellToolUseOptions({ - suggestions: toolUseConfirm.permissionResult.behavior === "ask" ? toolUseConfirm.permissionResult.suggestions : undefined, - onRejectFeedbackChange: setRejectFeedback, - onAcceptFeedbackChange: setAcceptFeedback, - yesInputMode, - noInputMode, - editablePrefix, - onEditablePrefixChange - }), [toolUseConfirm, yesInputMode, noInputMode, editablePrefix, onEditablePrefixChange]); - const handleToggleDebug = import_react219.useCallback(() => { - setShowPermissionDebug((prev) => !prev); - }, []); - useKeybinding("permission:toggleDebug", handleToggleDebug, { - context: "Confirmation" - }); - function onSelect(value) { - const optionIndex = { - yes: 1, - "yes-apply-suggestions": 2, - "yes-prefix-edited": 2, - no: 3 - }; - logEvent("tengu_permission_request_option_selected", { - option_index: optionIndex[value], - explainer_visible: explainerState.visible - }); - const toolNameForAnalytics = sanitizeToolNameForAnalytics(toolUseConfirm.tool.name); - if (value === "yes-prefix-edited") { - const trimmedPrefix = (editablePrefix ?? "").trim(); - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - if (!trimmedPrefix) { - toolUseConfirm.onAllow(toolUseConfirm.input, []); - } else { - const prefixUpdates = [{ - type: "addRules", - rules: [{ - toolName: PowerShellTool.name, - ruleContent: trimmedPrefix - }], - behavior: "allow", - destination: "localSettings" - }]; - toolUseConfirm.onAllow(toolUseConfirm.input, prefixUpdates); - } - onDone(); - return; - } - switch (value) { - case "yes": { - const trimmedFeedback = acceptFeedback.trim(); - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - logEvent("tengu_accept_submitted", { - toolName: toolNameForAnalytics, - isMcp: toolUseConfirm.tool.isMcp ?? false, - has_instructions: !!trimmedFeedback, - instructions_length: trimmedFeedback.length, - entered_feedback_mode: yesFeedbackModeEntered - }); - toolUseConfirm.onAllow(toolUseConfirm.input, [], trimmedFeedback || undefined); - onDone(); - break; - } - case "yes-apply-suggestions": { - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - const permissionUpdates = "suggestions" in toolUseConfirm.permissionResult ? toolUseConfirm.permissionResult.suggestions || [] : []; - toolUseConfirm.onAllow(toolUseConfirm.input, permissionUpdates); - onDone(); - break; - } - case "no": { - const trimmedFeedback = rejectFeedback.trim(); - logEvent("tengu_reject_submitted", { - toolName: toolNameForAnalytics, - isMcp: toolUseConfirm.tool.isMcp ?? false, - has_instructions: !!trimmedFeedback, - instructions_length: trimmedFeedback.length, - entered_feedback_mode: noFeedbackModeEntered - }); - handleReject2(trimmedFeedback || undefined); - break; - } - } - } - return /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(PermissionDialog, { - workerBadge, - title: "PowerShell command", - children: [ - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - dimColor: explainerState.visible, - children: PowerShellTool.renderToolUseMessage({ - command: command19, - description - }, { - theme: theme2, - verbose: true - }) - }, undefined, false, undefined, this), - !explainerState.visible && /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - dimColor: true, - children: toolUseConfirm.description - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(PermissionExplainerContent, { - visible: explainerState.visible, - promise: explainerState.promise - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - showPermissionDebug ? /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(jsx_dev_runtime396.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(PermissionDecisionDebugInfo, { - permissionResult: toolUseConfirm.permissionResult, - toolName: "PowerShell" - }, undefined, false, undefined, this), - toolUseContext.options.debug && /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedBox_default, { - justifyContent: "flex-end", - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - dimColor: true, - children: "Ctrl-D to hide debug info" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(jsx_dev_runtime396.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(PermissionRuleExplanation, { - permissionResult: toolUseConfirm.permissionResult, - toolType: "command" - }, undefined, false, undefined, this), - destructiveWarning && /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - color: "warning", - children: destructiveWarning - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - children: "Do you want to proceed?" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(Select, { - options: options2, - inlineDescriptions: true, - onChange: onSelect, - onCancel: () => handleReject2(), - onFocus: handleFocus, - onInputModeToggle: handleInputModeToggle - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedBox_default, { - justifyContent: "space-between", - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Esc to cancel", - (focusedOption === "yes" && !yesInputMode || focusedOption === "no" && !noInputMode) && " \xB7 Tab to amend", - explainerState.enabled && ` \xB7 ctrl+e to ${explainerState.visible ? "hide" : "explain"}` - ] - }, undefined, true, undefined, this), - toolUseContext.options.debug && /* @__PURE__ */ jsx_dev_runtime396.jsxDEV(ThemedText, { - dimColor: true, - children: "Ctrl+d to show debug info" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_react219, jsx_dev_runtime396; -var init_PowerShellPermissionRequest = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_growthbook(); - init_analytics(); - init_metadata(); - init_destructiveCommandWarning2(); - init_PowerShellTool(); - init_readOnlyValidation2(); - init_staticPrefix(); - init_select(); - init_hooks6(); - init_PermissionDecisionDebugInfo(); - init_PermissionDialog(); - init_PermissionExplanation(); - init_PermissionRuleExplanation(); - init_useShellPermissionFeedback(); - init_utils16(); - init_powershellToolUseOptions(); - import_react219 = __toESM(require_react(), 1); - jsx_dev_runtime396 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.tsx -function SkillPermissionRequest(props) { - const $2 = import_compiler_runtime308.c(51); - const { - toolUseConfirm, - onDone, - onReject, - workerBadge - } = props; - const parseInput = _temp188; - let t0; - if ($2[0] !== toolUseConfirm.input) { - t0 = parseInput(toolUseConfirm.input); - $2[0] = toolUseConfirm.input; - $2[1] = t0; - } else { - t0 = $2[1]; - } - const skill = t0; - const commandObj = toolUseConfirm.permissionResult.behavior === "ask" && toolUseConfirm.permissionResult.metadata && "command" in toolUseConfirm.permissionResult.metadata ? toolUseConfirm.permissionResult.metadata.command : undefined; - let t1; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - completion_type: "tool_use_single", - language_name: "none" - }; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const unaryEvent = t1; - usePermissionRequestLogging(toolUseConfirm, unaryEvent); - let t22; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t22 = getOriginalCwd(); - $2[3] = t22; - } else { - t22 = $2[3]; - } - const originalCwd = t22; - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = shouldShowAlwaysAllowOptions(); - $2[4] = t32; - } else { - t32 = $2[4]; - } - const showAlwaysAllowOptions = t32; - let t4; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t4 = [{ - label: "Yes", - value: "yes", - feedbackConfig: { - type: "accept" - } - }]; - $2[5] = t4; - } else { - t4 = $2[5]; - } - const baseOptions = t4; - let alwaysAllowOptions; - if ($2[6] !== skill) { - alwaysAllowOptions = []; - if (showAlwaysAllowOptions) { - const t52 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - bold: true, - children: skill - }, undefined, false, undefined, this); - let t62; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t62 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - bold: true, - children: originalCwd - }, undefined, false, undefined, this); - $2[8] = t62; - } else { - t62 = $2[8]; - } - let t72; - if ($2[9] !== t52) { - t72 = { - label: /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - children: [ - "Yes, and don't ask again for ", - t52, - " in", - " ", - t62 - ] - }, undefined, true, undefined, this), - value: "yes-exact" - }; - $2[9] = t52; - $2[10] = t72; - } else { - t72 = $2[10]; - } - alwaysAllowOptions.push(t72); - const spaceIndex = skill.indexOf(" "); - if (spaceIndex > 0) { - const commandPrefix = skill.substring(0, spaceIndex); - const t82 = commandPrefix + ":*"; - let t92; - if ($2[11] !== t82) { - t92 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - bold: true, - children: t82 - }, undefined, false, undefined, this); - $2[11] = t82; - $2[12] = t92; - } else { - t92 = $2[12]; - } - let t102; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t102 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - bold: true, - children: originalCwd - }, undefined, false, undefined, this); - $2[13] = t102; - } else { - t102 = $2[13]; - } - let t112; - if ($2[14] !== t92) { - t112 = { - label: /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - children: [ - "Yes, and don't ask again for", - " ", - t92, - " commands in", - " ", - t102 - ] - }, undefined, true, undefined, this), - value: "yes-prefix" - }; - $2[14] = t92; - $2[15] = t112; - } else { - t112 = $2[15]; - } - alwaysAllowOptions.push(t112); - } - } - $2[6] = skill; - $2[7] = alwaysAllowOptions; - } else { - alwaysAllowOptions = $2[7]; - } - let t5; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t5 = { - label: "No", - value: "no", - feedbackConfig: { - type: "reject" - } - }; - $2[16] = t5; - } else { - t5 = $2[16]; - } - const noOption = t5; - let t6; - if ($2[17] !== alwaysAllowOptions) { - t6 = [...baseOptions, ...alwaysAllowOptions, noOption]; - $2[17] = alwaysAllowOptions; - $2[18] = t6; - } else { - t6 = $2[18]; - } - const options2 = t6; - let t7; - if ($2[19] !== toolUseConfirm.tool.name) { - t7 = sanitizeToolNameForAnalytics(toolUseConfirm.tool.name); - $2[19] = toolUseConfirm.tool.name; - $2[20] = t7; - } else { - t7 = $2[20]; - } - const t8 = toolUseConfirm.tool.isMcp ?? false; - let t9; - if ($2[21] !== t7 || $2[22] !== t8) { - t9 = { - toolName: t7, - isMcp: t8 - }; - $2[21] = t7; - $2[22] = t8; - $2[23] = t9; - } else { - t9 = $2[23]; - } - const toolAnalyticsContext = t9; - let t10; - if ($2[24] !== onDone || $2[25] !== onReject || $2[26] !== skill || $2[27] !== toolUseConfirm) { - t10 = (value, feedback2) => { - bb33: - switch (value) { - case "yes": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "accept", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onAllow(toolUseConfirm.input, [], feedback2); - onDone(); - break bb33; - } - case "yes-exact": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "accept", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onAllow(toolUseConfirm.input, [{ - type: "addRules", - rules: [{ - toolName: SKILL_TOOL_NAME, - ruleContent: skill - }], - behavior: "allow", - destination: "localSettings" - }]); - onDone(); - break bb33; - } - case "yes-prefix": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "accept", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - const spaceIndex_0 = skill.indexOf(" "); - const commandPrefix_0 = spaceIndex_0 > 0 ? skill.substring(0, spaceIndex_0) : skill; - toolUseConfirm.onAllow(toolUseConfirm.input, [{ - type: "addRules", - rules: [{ - toolName: SKILL_TOOL_NAME, - ruleContent: `${commandPrefix_0}:*` - }], - behavior: "allow", - destination: "localSettings" - }]); - onDone(); - break bb33; - } - case "no": { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "reject", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onReject(feedback2); - onReject(); - onDone(); - } - } - }; - $2[24] = onDone; - $2[25] = onReject; - $2[26] = skill; - $2[27] = toolUseConfirm; - $2[28] = t10; - } else { - t10 = $2[28]; - } - const handleSelect = t10; - let t11; - if ($2[29] !== onDone || $2[30] !== onReject || $2[31] !== toolUseConfirm) { - t11 = () => { - logUnaryEvent({ - completion_type: "tool_use_single", - event: "reject", - metadata: { - language_name: "none", - message_id: toolUseConfirm.assistantMessage.message.id, - platform: env2.platform - } - }); - toolUseConfirm.onReject(); - onReject(); - onDone(); - }; - $2[29] = onDone; - $2[30] = onReject; - $2[31] = toolUseConfirm; - $2[32] = t11; - } else { - t11 = $2[32]; - } - const handleCancel = t11; - const t12 = `Use skill "${skill}"?`; - let t13; - if ($2[33] === Symbol.for("react.memo_cache_sentinel")) { - t13 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - children: "Claude may use instructions, code, or files from this Skill." - }, undefined, false, undefined, this); - $2[33] = t13; - } else { - t13 = $2[33]; - } - const t14 = commandObj?.description; - let t15; - if ($2[34] !== t14) { - t15 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedText, { - dimColor: true, - children: t14 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[34] = t14; - $2[35] = t15; - } else { - t15 = $2[35]; - } - let t16; - if ($2[36] !== toolUseConfirm.permissionResult) { - t16 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(PermissionRuleExplanation, { - permissionResult: toolUseConfirm.permissionResult, - toolType: "tool" - }, undefined, false, undefined, this); - $2[36] = toolUseConfirm.permissionResult; - $2[37] = t16; - } else { - t16 = $2[37]; - } - let t17; - if ($2[38] !== handleCancel || $2[39] !== handleSelect || $2[40] !== options2 || $2[41] !== toolAnalyticsContext) { - t17 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(PermissionPrompt, { - options: options2, - onSelect: handleSelect, - onCancel: handleCancel, - toolAnalyticsContext - }, undefined, false, undefined, this); - $2[38] = handleCancel; - $2[39] = handleSelect; - $2[40] = options2; - $2[41] = toolAnalyticsContext; - $2[42] = t17; - } else { - t17 = $2[42]; - } - let t18; - if ($2[43] !== t16 || $2[44] !== t17) { - t18 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t16, - t17 - ] - }, undefined, true, undefined, this); - $2[43] = t16; - $2[44] = t17; - $2[45] = t18; - } else { - t18 = $2[45]; - } - let t19; - if ($2[46] !== t12 || $2[47] !== t15 || $2[48] !== t18 || $2[49] !== workerBadge) { - t19 = /* @__PURE__ */ jsx_dev_runtime397.jsxDEV(PermissionDialog, { - title: t12, - workerBadge, - children: [ - t13, - t15, - t18 - ] - }, undefined, true, undefined, this); - $2[46] = t12; - $2[47] = t15; - $2[48] = t18; - $2[49] = workerBadge; - $2[50] = t19; - } else { - t19 = $2[50]; - } - return t19; -} -function _temp188(input) { - const result = SkillTool.inputSchema.safeParse(input); - if (!result.success) { - logError2(new Error(`Failed to parse skill tool input: ${result.error.message}`)); - return ""; - } - return result.data.skill; -} -var import_compiler_runtime308, jsx_dev_runtime397; -var init_SkillPermissionRequest = __esm(() => { - init_log2(); - init_state(); - init_ink2(); - init_metadata(); - init_SkillTool(); - init_env(); - init_permissionsLoader(); - init_unaryLogging(); - init_hooks6(); - init_PermissionDialog(); - init_PermissionPrompt(); - init_PermissionRuleExplanation(); - import_compiler_runtime308 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime397 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.tsx -function inputToPermissionRuleContent(input) { - try { - const parsedInput = WebFetchTool.inputSchema.safeParse(input); - if (!parsedInput.success) { - return `input:${input.toString()}`; - } - const { - url: url3 - } = parsedInput.data; - const hostname3 = new URL(url3).hostname; - return `domain:${hostname3}`; - } catch { - return `input:${input.toString()}`; - } -} -function WebFetchPermissionRequest(t0) { - const $2 = import_compiler_runtime309.c(41); - const { - toolUseConfirm, - onDone, - onReject, - verbose, - workerBadge - } = t0; - const [theme2] = useTheme(); - const { - url: url3 - } = toolUseConfirm.input; - let t1; - if ($2[0] !== url3) { - t1 = new URL(url3); - $2[0] = url3; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const hostname3 = t1.hostname; - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = { - completion_type: "tool_use_single", - language_name: "none" - }; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const unaryEvent = t22; - usePermissionRequestLogging(toolUseConfirm, unaryEvent); - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = shouldShowAlwaysAllowOptions(); - $2[3] = t32; - } else { - t32 = $2[3]; - } - const showAlwaysAllowOptions = t32; - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = { - label: "Yes", - value: "yes" - }; - $2[4] = t4; - } else { - t4 = $2[4]; - } - let result; - if ($2[5] !== hostname3) { - result = [t4]; - if (showAlwaysAllowOptions) { - const t53 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - bold: true, - children: hostname3 - }, undefined, false, undefined, this); - let t62; - if ($2[7] !== t53) { - t62 = { - label: /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - children: [ - "Yes, and don't ask again for ", - t53 - ] - }, undefined, true, undefined, this), - value: "yes-dont-ask-again-domain" - }; - $2[7] = t53; - $2[8] = t62; - } else { - t62 = $2[8]; - } - result.push(t62); - } - let t52; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t52 = { - label: /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - children: [ - "No, and tell Claude what to do differently ", - /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - bold: true, - children: "(esc)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "no" - }; - $2[9] = t52; - } else { - t52 = $2[9]; - } - result.push(t52); - $2[5] = hostname3; - $2[6] = result; - } else { - result = $2[6]; - } - const options2 = result; - let t5; - if ($2[10] !== onDone || $2[11] !== onReject || $2[12] !== toolUseConfirm) { - t5 = function onChange2(newValue) { - bb8: - switch (newValue) { - case "yes": { - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - toolUseConfirm.onAllow(toolUseConfirm.input, []); - onDone(); - break bb8; - } - case "yes-dont-ask-again-domain": { - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "accept"); - const ruleContent = inputToPermissionRuleContent(toolUseConfirm.input); - const ruleValue = { - toolName: toolUseConfirm.tool.name, - ruleContent - }; - toolUseConfirm.onAllow(toolUseConfirm.input, [{ - type: "addRules", - rules: [ruleValue], - behavior: "allow", - destination: "localSettings" - }]); - onDone(); - break bb8; - } - case "no": { - logUnaryPermissionEvent("tool_use_single", toolUseConfirm, "reject"); - toolUseConfirm.onReject(); - onReject(); - onDone(); - } - } - }; - $2[10] = onDone; - $2[11] = onReject; - $2[12] = toolUseConfirm; - $2[13] = t5; - } else { - t5 = $2[13]; - } - const onChange = t5; - let t6; - if ($2[14] !== theme2 || $2[15] !== toolUseConfirm.input || $2[16] !== verbose) { - t6 = WebFetchTool.renderToolUseMessage(toolUseConfirm.input, { - theme: theme2, - verbose - }); - $2[14] = theme2; - $2[15] = toolUseConfirm.input; - $2[16] = verbose; - $2[17] = t6; - } else { - t6 = $2[17]; - } - let t7; - if ($2[18] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - children: t6 - }, undefined, false, undefined, this); - $2[18] = t6; - $2[19] = t7; - } else { - t7 = $2[19]; - } - let t8; - if ($2[20] !== toolUseConfirm.description) { - t8 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - dimColor: true, - children: toolUseConfirm.description - }, undefined, false, undefined, this); - $2[20] = toolUseConfirm.description; - $2[21] = t8; - } else { - t8 = $2[21]; - } - let t9; - if ($2[22] !== t7 || $2[23] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - t7, - t8 - ] - }, undefined, true, undefined, this); - $2[22] = t7; - $2[23] = t8; - $2[24] = t9; - } else { - t9 = $2[24]; - } - let t10; - if ($2[25] !== toolUseConfirm.permissionResult) { - t10 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(PermissionRuleExplanation, { - permissionResult: toolUseConfirm.permissionResult, - toolType: "tool" - }, undefined, false, undefined, this); - $2[25] = toolUseConfirm.permissionResult; - $2[26] = t10; - } else { - t10 = $2[26]; - } - let t11; - if ($2[27] === Symbol.for("react.memo_cache_sentinel")) { - t11 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedText, { - children: "Do you want to allow Claude to fetch this content?" - }, undefined, false, undefined, this); - $2[27] = t11; - } else { - t11 = $2[27]; - } - let t12; - if ($2[28] !== onChange) { - t12 = () => onChange("no"); - $2[28] = onChange; - $2[29] = t12; - } else { - t12 = $2[29]; - } - let t13; - if ($2[30] !== onChange || $2[31] !== options2 || $2[32] !== t12) { - t13 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(Select, { - options: options2, - onChange, - onCancel: t12 - }, undefined, false, undefined, this); - $2[30] = onChange; - $2[31] = options2; - $2[32] = t12; - $2[33] = t13; - } else { - t13 = $2[33]; - } - let t14; - if ($2[34] !== t10 || $2[35] !== t13) { - t14 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t10, - t11, - t13 - ] - }, undefined, true, undefined, this); - $2[34] = t10; - $2[35] = t13; - $2[36] = t14; - } else { - t14 = $2[36]; - } - let t15; - if ($2[37] !== t14 || $2[38] !== t9 || $2[39] !== workerBadge) { - t15 = /* @__PURE__ */ jsx_dev_runtime398.jsxDEV(PermissionDialog, { - title: "Fetch", - workerBadge, - children: [ - t9, - t14 - ] - }, undefined, true, undefined, this); - $2[37] = t14; - $2[38] = t9; - $2[39] = workerBadge; - $2[40] = t15; - } else { - t15 = $2[40]; - } - return t15; -} -var import_compiler_runtime309, jsx_dev_runtime398; -var init_WebFetchPermissionRequest = __esm(() => { - init_ink2(); - init_WebFetchTool(); - init_permissionsLoader(); - init_select(); - init_hooks6(); - init_PermissionDialog(); - init_PermissionRuleExplanation(); - init_utils16(); - import_compiler_runtime309 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime398 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/permissions/PermissionRequest.tsx -function permissionComponentForTool(tool) { - switch (tool) { - case FileEditTool: - return FileEditPermissionRequest; - case FileWriteTool: - return FileWritePermissionRequest; - case BashTool: - return BashPermissionRequest; - case PowerShellTool: - return PowerShellPermissionRequest; - case ReviewArtifactTool: - return ReviewArtifactPermissionRequest ?? FallbackPermissionRequest; - case WebFetchTool: - return WebFetchPermissionRequest; - case NotebookEditTool: - return NotebookEditPermissionRequest; - case ExitPlanModeV2Tool: - return ExitPlanModePermissionRequest; - case EnterPlanModeTool: - return EnterPlanModePermissionRequest; - case SkillTool: - return SkillPermissionRequest; - case AskUserQuestionTool: - return AskUserQuestionPermissionRequest; - case WorkflowTool2: - return WorkflowPermissionRequest ?? FallbackPermissionRequest; - case MonitorTool2: - return MonitorPermissionRequest ?? FallbackPermissionRequest; - case GlobTool: - case GrepTool: - case FileReadTool: - return FilesystemPermissionRequest; - default: - return FallbackPermissionRequest; - } -} -function getNotificationMessage(toolUseConfirm) { - const toolName = toolUseConfirm.tool.userFacingName(toolUseConfirm.input); - if (toolUseConfirm.tool === ExitPlanModeV2Tool) { - return "Claude Code needs your approval for the plan"; - } - if (toolUseConfirm.tool === EnterPlanModeTool) { - return "Claude Code wants to enter plan mode"; - } - if (false) {} - if (!toolName || toolName.trim() === "") { - return "Claude Code needs your attention"; - } - return `Claude needs your permission to use ${toolName}`; -} -function PermissionRequest(t0) { - const $2 = import_compiler_runtime310.c(18); - const { - toolUseConfirm, - toolUseContext, - onDone, - onReject, - verbose, - workerBadge, - setStickyFooter - } = t0; - let t1; - if ($2[0] !== onDone || $2[1] !== onReject || $2[2] !== toolUseConfirm) { - t1 = () => { - onDone(); - onReject(); - toolUseConfirm.onReject(); - }; - $2[0] = onDone; - $2[1] = onReject; - $2[2] = toolUseConfirm; - $2[3] = t1; - } else { - t1 = $2[3]; - } - let t22; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t22 = { - context: "Confirmation" - }; - $2[4] = t22; - } else { - t22 = $2[4]; - } - useKeybinding("app:interrupt", t1, t22); - let t32; - if ($2[5] !== toolUseConfirm) { - t32 = getNotificationMessage(toolUseConfirm); - $2[5] = toolUseConfirm; - $2[6] = t32; - } else { - t32 = $2[6]; - } - const notificationMessage = t32; - useNotifyAfterTimeout(notificationMessage, "permission_prompt"); - let t4; - if ($2[7] !== toolUseConfirm.tool) { - t4 = permissionComponentForTool(toolUseConfirm.tool); - $2[7] = toolUseConfirm.tool; - $2[8] = t4; - } else { - t4 = $2[8]; - } - const PermissionComponent = t4; - let t5; - if ($2[9] !== PermissionComponent || $2[10] !== onDone || $2[11] !== onReject || $2[12] !== setStickyFooter || $2[13] !== toolUseConfirm || $2[14] !== toolUseContext || $2[15] !== verbose || $2[16] !== workerBadge) { - t5 = /* @__PURE__ */ jsx_dev_runtime399.jsxDEV(PermissionComponent, { - toolUseContext, - toolUseConfirm, - onDone, - onReject, - verbose, - workerBadge, - setStickyFooter - }, undefined, false, undefined, this); - $2[9] = PermissionComponent; - $2[10] = onDone; - $2[11] = onReject; - $2[12] = setStickyFooter; - $2[13] = toolUseConfirm; - $2[14] = toolUseContext; - $2[15] = verbose; - $2[16] = workerBadge; - $2[17] = t5; - } else { - t5 = $2[17]; - } - return t5; -} -var import_compiler_runtime310, jsx_dev_runtime399, ReviewArtifactTool = null, ReviewArtifactPermissionRequest = null, WorkflowTool2 = null, WorkflowPermissionRequest = null, MonitorTool2 = null, MonitorPermissionRequest = null; -var init_PermissionRequest = __esm(() => { - init_EnterPlanModeTool(); - init_ExitPlanModeV2Tool(); - init_useNotifyAfterTimeout(); - init_useKeybinding(); - init_AskUserQuestionTool(); - init_BashTool(); - init_FileEditTool(); - init_FileReadTool(); - init_FileWriteTool(); - init_GlobTool(); - init_GrepTool(); - init_NotebookEditTool(); - init_PowerShellTool(); - init_SkillTool(); - init_WebFetchTool(); - init_AskUserQuestionPermissionRequest(); - init_BashPermissionRequest(); - init_EnterPlanModePermissionRequest(); - init_ExitPlanModePermissionRequest(); - init_FallbackPermissionRequest(); - init_FileEditPermissionRequest(); - init_FilesystemPermissionRequest(); - init_FileWritePermissionRequest(); - init_NotebookEditPermissionRequest(); - init_PowerShellPermissionRequest(); - init_SkillPermissionRequest(); - init_WebFetchPermissionRequest(); - import_compiler_runtime310 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime399 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/mcp/dateTimeParser.ts -async function parseNaturalLanguageDateTime(input, format5, signal) { - const now2 = new Date; - const currentDateTime = now2.toISOString(); - const timezoneOffset = -now2.getTimezoneOffset(); - const tzHours = Math.floor(Math.abs(timezoneOffset) / 60); - const tzMinutes = Math.abs(timezoneOffset) % 60; - const tzSign = timezoneOffset >= 0 ? "+" : "-"; - const timezone = `${tzSign}${String(tzHours).padStart(2, "0")}:${String(tzMinutes).padStart(2, "0")}`; - const dayOfWeek = now2.toLocaleDateString("en-US", { weekday: "long" }); - const systemPrompt = asSystemPrompt([ - "You are a date/time parser that converts natural language into ISO 8601 format.", - "You MUST respond with ONLY the ISO 8601 formatted string, with no explanation or additional text.", - "If the input is ambiguous, prefer future dates over past dates.", - "For times without dates, use today's date.", - "For dates without times, do not include a time component.", - 'If the input is incomplete or you cannot confidently parse it into a valid date, respond with exactly "INVALID" (nothing else).', - 'Examples of INVALID input: partial dates like "2025-01-", lone numbers like "13", gibberish.', - 'Examples of valid natural language: "tomorrow", "next Monday", "jan 1st 2025", "in 2 hours", "yesterday".' - ]); - const formatDescription = format5 === "date" ? "YYYY-MM-DD (date only, no time)" : `YYYY-MM-DDTHH:MM:SS${timezone} (full date-time with timezone)`; - const userPrompt = `Current context: -- Current date and time: ${currentDateTime} (UTC) -- Local timezone: ${timezone} -- Day of week: ${dayOfWeek} - -User input: "${input}" - -Output format: ${formatDescription} - -Parse the user's input into ISO 8601 format. Return ONLY the formatted string, or "INVALID" if the input is incomplete or unparseable.`; - try { - const result = await queryHaiku({ - systemPrompt, - userPrompt, - signal, - options: { - querySource: "mcp_datetime_parse", - agents: [], - isNonInteractiveSession: false, - hasAppendSystemPrompt: false, - mcpTools: [], - enablePromptCaching: false - } - }); - const parsedText = extractTextContent(result.message.content).trim(); - if (!parsedText || parsedText === "INVALID") { - return { - success: false, - error: "Unable to parse date/time from input" - }; - } - if (!/^\d{4}/.test(parsedText)) { - return { - success: false, - error: "Unable to parse date/time from input" - }; - } - return { success: true, value: parsedText }; - } catch (error46) { - logError2(error46); - return { - success: false, - error: "Unable to parse date/time. Please enter in ISO 8601 format manually." - }; - } -} -function looksLikeISO8601(input) { - return /^\d{4}-\d{2}-\d{2}(T|$)/.test(input.trim()); -} -var init_dateTimeParser = __esm(() => { - init_claude(); - init_log2(); - init_messages9(); -}); - -// src/utils/mcp/elicitationValidation.ts -function isMultiSelectEnumSchema(schema5) { - return schema5.type === "array" && "items" in schema5 && typeof schema5.items === "object" && schema5.items !== null && (("enum" in schema5.items) || ("anyOf" in schema5.items)); -} -function getMultiSelectValues(schema5) { - if ("anyOf" in schema5.items) { - return schema5.items.anyOf.map((item) => item.const); - } - if ("enum" in schema5.items) { - return schema5.items.enum; - } - return []; -} -function getMultiSelectLabels(schema5) { - if ("anyOf" in schema5.items) { - return schema5.items.anyOf.map((item) => item.title); - } - if ("enum" in schema5.items) { - return schema5.items.enum; - } - return []; -} -function getMultiSelectLabel(schema5, value) { - const index2 = getMultiSelectValues(schema5).indexOf(value); - return index2 >= 0 ? getMultiSelectLabels(schema5)[index2] ?? value : value; -} -function getEnumValues2(schema5) { - if ("oneOf" in schema5) { - return schema5.oneOf.map((item) => item.const); - } - if ("enum" in schema5) { - return schema5.enum; - } - return []; -} -function getEnumLabels(schema5) { - if ("oneOf" in schema5) { - return schema5.oneOf.map((item) => item.title); - } - if ("enum" in schema5) { - return ("enumNames" in schema5 ? schema5.enumNames : undefined) ?? schema5.enum; - } - return []; -} -function getEnumLabel(schema5, value) { - const index2 = getEnumValues2(schema5).indexOf(value); - return index2 >= 0 ? getEnumLabels(schema5)[index2] ?? value : value; -} -function getZodSchema(schema5) { - if (isEnumSchema(schema5)) { - const [first, ...rest] = getEnumValues2(schema5); - if (!first) { - return exports_external.never(); - } - return exports_external.enum([first, ...rest]); - } - if (schema5.type === "string") { - let stringSchema = exports_external.string(); - if (schema5.minLength !== undefined) { - stringSchema = stringSchema.min(schema5.minLength, { - message: `Must be at least ${schema5.minLength} ${plural(schema5.minLength, "character")}` - }); - } - if (schema5.maxLength !== undefined) { - stringSchema = stringSchema.max(schema5.maxLength, { - message: `Must be at most ${schema5.maxLength} ${plural(schema5.maxLength, "character")}` - }); - } - switch (schema5.format) { - case "email": - stringSchema = stringSchema.email({ - message: "Must be a valid email address, e.g. user@example.com" - }); - break; - case "uri": - stringSchema = stringSchema.url({ - message: "Must be a valid URI, e.g. https://example.com" - }); - break; - case "date": - stringSchema = stringSchema.date("Must be a valid date, e.g. 2024-03-15, today, next Monday"); - break; - case "date-time": - stringSchema = stringSchema.datetime({ - offset: true, - message: "Must be a valid date-time, e.g. 2024-03-15T14:30:00Z, tomorrow at 3pm" - }); - break; - default: - break; - } - return stringSchema; - } - if (schema5.type === "number" || schema5.type === "integer") { - const typeLabel = schema5.type === "integer" ? "an integer" : "a number"; - const isInteger = schema5.type === "integer"; - const formatNum = (n6) => Number.isInteger(n6) && !isInteger ? `${n6}.0` : String(n6); - const rangeMsg = schema5.minimum !== undefined && schema5.maximum !== undefined ? `Must be ${typeLabel} between ${formatNum(schema5.minimum)} and ${formatNum(schema5.maximum)}` : schema5.minimum !== undefined ? `Must be ${typeLabel} >= ${formatNum(schema5.minimum)}` : schema5.maximum !== undefined ? `Must be ${typeLabel} <= ${formatNum(schema5.maximum)}` : `Must be ${typeLabel}`; - let numberSchema = exports_external.coerce.number({ - error: rangeMsg - }); - if (schema5.type === "integer") { - numberSchema = numberSchema.int({ message: rangeMsg }); - } - if (schema5.minimum !== undefined) { - numberSchema = numberSchema.min(schema5.minimum, { - message: rangeMsg - }); - } - if (schema5.maximum !== undefined) { - numberSchema = numberSchema.max(schema5.maximum, { - message: rangeMsg - }); - } - return numberSchema; - } - if (schema5.type === "boolean") { - return exports_external.coerce.boolean(); - } - throw new Error(`Unsupported schema: ${jsonStringify(schema5)}`); -} -function validateElicitationInput(stringValue, schema5) { - const zodSchema = getZodSchema(schema5); - const parseResult = zodSchema.safeParse(stringValue); - if (parseResult.success) { - return { - value: parseResult.data, - isValid: true - }; - } - return { - isValid: false, - error: parseResult.error.issues.map((e4) => e4.message).join("; ") - }; -} -function isDateTimeSchema(schema5) { - return schema5.type === "string" && "format" in schema5 && (schema5.format === "date" || schema5.format === "date-time"); -} -async function validateElicitationInputAsync(stringValue, schema5, signal) { - const syncResult = validateElicitationInput(stringValue, schema5); - if (syncResult.isValid) { - return syncResult; - } - if (isDateTimeSchema(schema5) && !looksLikeISO8601(stringValue)) { - const parseResult = await parseNaturalLanguageDateTime(stringValue, schema5.format, signal); - if (parseResult.success) { - const validatedParsed = validateElicitationInput(parseResult.value, schema5); - if (validatedParsed.isValid) { - return validatedParsed; - } - } - } - return syncResult; -} -var isEnumSchema = (schema5) => { - return schema5.type === "string" && (("enum" in schema5) || ("oneOf" in schema5)); -}; -var init_elicitationValidation = __esm(() => { - init_v4(); - init_slowOperations(); - init_stringUtils(); - init_dateTimeParser(); -}); - -// src/components/mcp/ElicitationDialog.tsx -function resetTypeahead(ta) { - ta.buffer = ""; - ta.timer = undefined; -} -function ResolvingSpinner() { - const $2 = import_compiler_runtime311.c(4); - const [frame, setFrame] = import_react220.useState(0); - let t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = () => { - const timer = setInterval(setFrame, 80, advanceSpinnerFrame); - return () => clearInterval(timer); - }; - t1 = []; - $2[0] = t0; - $2[1] = t1; - } else { - t0 = $2[0]; - t1 = $2[1]; - } - import_react220.useEffect(t0, t1); - const t22 = RESOLVING_SPINNER_CHARS[frame]; - let t32; - if ($2[2] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "warning", - children: t22 - }, undefined, false, undefined, this); - $2[2] = t22; - $2[3] = t32; - } else { - t32 = $2[3]; - } - return t32; -} -function formatDateDisplay(isoValue, schema5) { - try { - const date6 = new Date(isoValue); - if (Number.isNaN(date6.getTime())) - return isoValue; - const format5 = "format" in schema5 ? schema5.format : undefined; - if (format5 === "date-time") { - return date6.toLocaleDateString("en-US", { - weekday: "short", - year: "numeric", - month: "short", - day: "numeric", - hour: "numeric", - minute: "2-digit", - timeZoneName: "short" - }); - } - const parts = isoValue.split("-"); - if (parts.length === 3) { - const local = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])); - return local.toLocaleDateString("en-US", { - weekday: "short", - year: "numeric", - month: "short", - day: "numeric" - }); - } - return isoValue; - } catch { - return isoValue; - } -} -function ElicitationDialog(t0) { - const $2 = import_compiler_runtime311.c(7); - const { - event, - onResponse, - onWaitingDismiss - } = t0; - if (event.params.mode === "url") { - let t12; - if ($2[0] !== event || $2[1] !== onResponse || $2[2] !== onWaitingDismiss) { - t12 = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ElicitationURLDialog, { - event, - onResponse, - onWaitingDismiss - }, undefined, false, undefined, this); - $2[0] = event; - $2[1] = onResponse; - $2[2] = onWaitingDismiss; - $2[3] = t12; - } else { - t12 = $2[3]; - } - return t12; - } - let t1; - if ($2[4] !== event || $2[5] !== onResponse) { - t1 = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ElicitationFormDialog, { - event, - onResponse - }, undefined, false, undefined, this); - $2[4] = event; - $2[5] = onResponse; - $2[6] = t1; - } else { - t1 = $2[6]; - } - return t1; -} -function ElicitationFormDialog({ - event, - onResponse -}) { - const { - serverName, - signal - } = event; - const request2 = event.params; - const { - message, - requestedSchema - } = request2; - const hasFields = Object.keys(requestedSchema.properties).length > 0; - const [focusedButton, setFocusedButton] = import_react220.useState(hasFields ? null : "accept"); - const [formValues, setFormValues] = import_react220.useState(() => { - const initialValues = {}; - if (requestedSchema.properties) { - for (const [propName, propSchema] of Object.entries(requestedSchema.properties)) { - if (typeof propSchema === "object" && propSchema !== null) { - if (propSchema.default !== undefined) { - initialValues[propName] = propSchema.default; - } - } - } - } - return initialValues; - }); - const [validationErrors, setValidationErrors] = import_react220.useState(() => { - const initialErrors = {}; - for (const [propName_0, propSchema_0] of Object.entries(requestedSchema.properties)) { - if (isTextField(propSchema_0) && propSchema_0?.default !== undefined) { - const validation = validateElicitationInput(String(propSchema_0.default), propSchema_0); - if (!validation.isValid && validation.error) { - initialErrors[propName_0] = validation.error; - } - } - } - return initialErrors; - }); - import_react220.useEffect(() => { - if (!signal) - return; - const handleAbort2 = () => { - onResponse("cancel"); - }; - if (signal.aborted) { - handleAbort2(); - return; - } - signal.addEventListener("abort", handleAbort2); - return () => { - signal.removeEventListener("abort", handleAbort2); - }; - }, [signal, onResponse]); - const schemaFields = import_react220.useMemo(() => { - const requiredFields = requestedSchema.required ?? []; - return Object.entries(requestedSchema.properties).map(([name3, schema5]) => ({ - name: name3, - schema: schema5, - isRequired: requiredFields.includes(name3) - })); - }, [requestedSchema]); - const [currentFieldIndex, setCurrentFieldIndex] = import_react220.useState(hasFields ? 0 : undefined); - const [textInputValue, setTextInputValue] = import_react220.useState(() => { - const firstField = schemaFields[0]; - if (firstField && isTextField(firstField.schema)) { - const val = formValues[firstField.name]; - if (val === undefined) - return ""; - return String(val); - } - return ""; - }); - const [textInputCursorOffset, setTextInputCursorOffset] = import_react220.useState(textInputValue.length); - const [resolvingFields, setResolvingFields] = import_react220.useState(() => new Set); - const [expandedAccordion, setExpandedAccordion] = import_react220.useState(); - const [accordionOptionIndex, setAccordionOptionIndex] = import_react220.useState(0); - const dateDebounceRef = import_react220.useRef(undefined); - const resolveAbortRef = import_react220.useRef(new Map); - const enumTypeaheadRef = import_react220.useRef({ - buffer: "", - timer: undefined - }); - import_react220.useEffect(() => () => { - if (dateDebounceRef.current !== undefined) { - clearTimeout(dateDebounceRef.current); - } - const ta = enumTypeaheadRef.current; - if (ta.timer !== undefined) { - clearTimeout(ta.timer); - } - for (const controller of resolveAbortRef.current.values()) { - controller.abort(); - } - resolveAbortRef.current.clear(); - }, []); - const { - columns, - rows - } = useTerminalSize(); - const currentField = currentFieldIndex !== undefined ? schemaFields[currentFieldIndex] : undefined; - const currentFieldIsText = currentField !== undefined && isTextField(currentField.schema) && !isEnumSchema(currentField.schema); - const isEditingTextField = currentFieldIsText && !focusedButton; - useRegisterOverlay("elicitation"); - useNotifyAfterTimeout("Claude Code needs your input", "elicitation_dialog"); - const syncTextInput = import_react220.useCallback((fieldIndex) => { - if (fieldIndex === undefined) { - setTextInputValue(""); - setTextInputCursorOffset(0); - return; - } - const field = schemaFields[fieldIndex]; - if (field && isTextField(field.schema) && !isEnumSchema(field.schema)) { - const val_0 = formValues[field.name]; - const text = val_0 !== undefined ? String(val_0) : ""; - setTextInputValue(text); - setTextInputCursorOffset(text.length); - } - }, [schemaFields, formValues]); - function validateMultiSelect(fieldName, schema_0) { - if (!isMultiSelectEnumSchema(schema_0)) - return; - const selected = formValues[fieldName] ?? []; - const fieldRequired = schemaFields.find((f4) => f4.name === fieldName)?.isRequired ?? false; - const min = schema_0.minItems; - const max2 = schema_0.maxItems; - if (min !== undefined && selected.length < min && (selected.length > 0 || fieldRequired)) { - updateValidationError(fieldName, `Select at least ${min} ${plural(min, "item")}`); - } else if (max2 !== undefined && selected.length > max2) { - updateValidationError(fieldName, `Select at most ${max2} ${plural(max2, "item")}`); - } else { - updateValidationError(fieldName); - } - } - function handleNavigation(direction) { - if (currentField && isMultiSelectEnumSchema(currentField.schema)) { - validateMultiSelect(currentField.name, currentField.schema); - setExpandedAccordion(undefined); - } else if (currentField && isEnumSchema(currentField.schema)) { - setExpandedAccordion(undefined); - } - if (isEditingTextField && currentField) { - commitTextField(currentField.name, currentField.schema, textInputValue); - if (dateDebounceRef.current !== undefined) { - clearTimeout(dateDebounceRef.current); - dateDebounceRef.current = undefined; - } - if (isDateTimeSchema(currentField.schema) && textInputValue.trim() !== "" && validationErrors[currentField.name]) { - resolveFieldAsync(currentField.name, currentField.schema, textInputValue); - } - } - const itemCount = schemaFields.length + 2; - const index2 = currentFieldIndex ?? (focusedButton === "accept" ? schemaFields.length : focusedButton === "decline" ? schemaFields.length + 1 : undefined); - const nextIndex = index2 !== undefined ? (index2 + (direction === "up" ? itemCount - 1 : 1)) % itemCount : 0; - if (nextIndex < schemaFields.length) { - setCurrentFieldIndex(nextIndex); - setFocusedButton(null); - syncTextInput(nextIndex); - } else { - setCurrentFieldIndex(undefined); - setFocusedButton(nextIndex === schemaFields.length ? "accept" : "decline"); - setTextInputValue(""); - } - } - function setField(fieldName_0, value) { - setFormValues((prev) => { - const next2 = { - ...prev - }; - if (value === undefined) { - delete next2[fieldName_0]; - } else { - next2[fieldName_0] = value; - } - return next2; - }); - if (value !== undefined && validationErrors[fieldName_0] === "This field is required") { - updateValidationError(fieldName_0); - } - } - function updateValidationError(fieldName_1, error46) { - setValidationErrors((prev_0) => { - const next_0 = { - ...prev_0 - }; - if (error46) { - next_0[fieldName_1] = error46; - } else { - delete next_0[fieldName_1]; - } - return next_0; - }); - } - function unsetField(fieldName_2) { - if (!fieldName_2) - return; - setField(fieldName_2, undefined); - updateValidationError(fieldName_2); - setTextInputValue(""); - setTextInputCursorOffset(0); - } - function commitTextField(fieldName_3, schema_1, value_0) { - const trimmedValue = value_0.trim(); - if (trimmedValue === "" && (schema_1.type !== "string" || ("format" in schema_1) && schema_1.format !== undefined)) { - unsetField(fieldName_3); - return; - } - if (trimmedValue === "") { - if (formValues[fieldName_3] !== undefined) { - setField(fieldName_3, ""); - } - return; - } - const validation_0 = validateElicitationInput(value_0, schema_1); - setField(fieldName_3, validation_0.isValid ? validation_0.value : value_0); - updateValidationError(fieldName_3, validation_0.isValid ? undefined : validation_0.error); - } - function resolveFieldAsync(fieldName_4, schema_2, rawValue) { - if (!signal) - return; - const existing = resolveAbortRef.current.get(fieldName_4); - if (existing) { - existing.abort(); - } - const controller_0 = new AbortController; - resolveAbortRef.current.set(fieldName_4, controller_0); - setResolvingFields((prev_1) => new Set(prev_1).add(fieldName_4)); - validateElicitationInputAsync(rawValue, schema_2, controller_0.signal).then((result) => { - resolveAbortRef.current.delete(fieldName_4); - setResolvingFields((prev_2) => { - const next_1 = new Set(prev_2); - next_1.delete(fieldName_4); - return next_1; - }); - if (controller_0.signal.aborted) - return; - if (result.isValid) { - setField(fieldName_4, result.value); - updateValidationError(fieldName_4); - const isoText = String(result.value); - setTextInputValue((prev_3) => { - if (prev_3 === rawValue) { - setTextInputCursorOffset(isoText.length); - return isoText; - } - return prev_3; - }); - } else { - updateValidationError(fieldName_4, result.error); - } - }, () => { - resolveAbortRef.current.delete(fieldName_4); - setResolvingFields((prev_4) => { - const next_2 = new Set(prev_4); - next_2.delete(fieldName_4); - return next_2; - }); - }); - } - function handleTextInputChange(newValue) { - setTextInputValue(newValue); - if (currentField) { - commitTextField(currentField.name, currentField.schema, newValue); - if (dateDebounceRef.current !== undefined) { - clearTimeout(dateDebounceRef.current); - dateDebounceRef.current = undefined; - } - if (isDateTimeSchema(currentField.schema) && newValue.trim() !== "" && validationErrors[currentField.name]) { - const fieldName_5 = currentField.name; - const schema_3 = currentField.schema; - dateDebounceRef.current = setTimeout((dateDebounceRef_0, resolveFieldAsync_0, fieldName_6, schema_4, newValue_0) => { - dateDebounceRef_0.current = undefined; - resolveFieldAsync_0(fieldName_6, schema_4, newValue_0); - }, 2000, dateDebounceRef, resolveFieldAsync, fieldName_5, schema_3, newValue); - } - } - } - function handleTextInputSubmit() { - handleNavigation("down"); - } - function runTypeahead(char, labels, onMatch) { - const ta_0 = enumTypeaheadRef.current; - if (ta_0.timer !== undefined) - clearTimeout(ta_0.timer); - ta_0.buffer += char.toLowerCase(); - ta_0.timer = setTimeout(resetTypeahead, 2000, ta_0); - const match = labels.findIndex((l4) => l4.startsWith(ta_0.buffer)); - if (match !== -1) - onMatch(match); - } - useKeybinding("confirm:no", () => { - if (isEditingTextField && currentField) { - const val_1 = formValues[currentField.name]; - setTextInputValue(val_1 !== undefined ? String(val_1) : ""); - setTextInputCursorOffset(0); - } - onResponse("cancel"); - }, { - context: "Settings", - isActive: !!currentField && !focusedButton && !expandedAccordion - }); - use_input_default((_input, key2) => { - if (isEditingTextField && !key2.upArrow && !key2.downArrow && !key2.return && !key2.backspace) { - return; - } - if (expandedAccordion && currentField && isMultiSelectEnumSchema(currentField.schema)) { - const msSchema = currentField.schema; - const msValues = getMultiSelectValues(msSchema); - const selected_0 = formValues[currentField.name] ?? []; - if (key2.leftArrow || key2.escape) { - setExpandedAccordion(undefined); - validateMultiSelect(currentField.name, msSchema); - return; - } - if (key2.upArrow) { - if (accordionOptionIndex === 0) { - setExpandedAccordion(undefined); - validateMultiSelect(currentField.name, msSchema); - } else { - setAccordionOptionIndex(accordionOptionIndex - 1); - } - return; - } - if (key2.downArrow) { - if (accordionOptionIndex >= msValues.length - 1) { - setExpandedAccordion(undefined); - handleNavigation("down"); - } else { - setAccordionOptionIndex(accordionOptionIndex + 1); - } - return; - } - if (_input === " ") { - const optionValue = msValues[accordionOptionIndex]; - if (optionValue !== undefined) { - const newSelected = selected_0.includes(optionValue) ? selected_0.filter((v6) => v6 !== optionValue) : [...selected_0, optionValue]; - const newValue_1 = newSelected.length > 0 ? newSelected : undefined; - setField(currentField.name, newValue_1); - const min_0 = msSchema.minItems; - const max_0 = msSchema.maxItems; - if (min_0 !== undefined && newSelected.length < min_0 && (newSelected.length > 0 || currentField.isRequired)) { - updateValidationError(currentField.name, `Select at least ${min_0} ${plural(min_0, "item")}`); - } else if (max_0 !== undefined && newSelected.length > max_0) { - updateValidationError(currentField.name, `Select at most ${max_0} ${plural(max_0, "item")}`); - } else { - updateValidationError(currentField.name); - } - } - return; - } - if (key2.return) { - const optionValue_0 = msValues[accordionOptionIndex]; - if (optionValue_0 !== undefined && !selected_0.includes(optionValue_0)) { - setField(currentField.name, [...selected_0, optionValue_0]); - } - setExpandedAccordion(undefined); - handleNavigation("down"); - return; - } - if (_input) { - const labels_0 = msValues.map((v_0) => getMultiSelectLabel(msSchema, v_0).toLowerCase()); - runTypeahead(_input, labels_0, setAccordionOptionIndex); - return; - } - return; - } - if (expandedAccordion && currentField && isEnumSchema(currentField.schema)) { - const enumSchema = currentField.schema; - const enumValues = getEnumValues2(enumSchema); - if (key2.leftArrow || key2.escape) { - setExpandedAccordion(undefined); - return; - } - if (key2.upArrow) { - if (accordionOptionIndex === 0) { - setExpandedAccordion(undefined); - } else { - setAccordionOptionIndex(accordionOptionIndex - 1); - } - return; - } - if (key2.downArrow) { - if (accordionOptionIndex >= enumValues.length - 1) { - setExpandedAccordion(undefined); - handleNavigation("down"); - } else { - setAccordionOptionIndex(accordionOptionIndex + 1); - } - return; - } - if (_input === " ") { - const optionValue_1 = enumValues[accordionOptionIndex]; - if (optionValue_1 !== undefined) { - setField(currentField.name, optionValue_1); - } - setExpandedAccordion(undefined); - return; - } - if (key2.return) { - const optionValue_2 = enumValues[accordionOptionIndex]; - if (optionValue_2 !== undefined) { - setField(currentField.name, optionValue_2); - } - setExpandedAccordion(undefined); - handleNavigation("down"); - return; - } - if (_input) { - const labels_1 = enumValues.map((v_1) => getEnumLabel(enumSchema, v_1).toLowerCase()); - runTypeahead(_input, labels_1, setAccordionOptionIndex); - return; - } - return; - } - if (key2.return && focusedButton === "accept") { - if (validateRequired() && Object.keys(validationErrors).length === 0) { - onResponse("accept", formValues); - } else { - const requiredFields_0 = requestedSchema.required || []; - for (const fieldName_7 of requiredFields_0) { - if (formValues[fieldName_7] === undefined) { - updateValidationError(fieldName_7, "This field is required"); - } - } - const firstBadIndex = schemaFields.findIndex((f_0) => requiredFields_0.includes(f_0.name) && formValues[f_0.name] === undefined || validationErrors[f_0.name] !== undefined); - if (firstBadIndex !== -1) { - setCurrentFieldIndex(firstBadIndex); - setFocusedButton(null); - syncTextInput(firstBadIndex); - } - } - return; - } - if (key2.return && focusedButton === "decline") { - onResponse("decline"); - return; - } - if (key2.upArrow || key2.downArrow) { - const ta_1 = enumTypeaheadRef.current; - ta_1.buffer = ""; - if (ta_1.timer !== undefined) { - clearTimeout(ta_1.timer); - ta_1.timer = undefined; - } - handleNavigation(key2.upArrow ? "up" : "down"); - return; - } - if (focusedButton && (key2.leftArrow || key2.rightArrow)) { - setFocusedButton(focusedButton === "accept" ? "decline" : "accept"); - return; - } - if (!currentField) - return; - const { - schema: schema_5, - name: name_0 - } = currentField; - const value_1 = formValues[name_0]; - if (schema_5.type === "boolean") { - if (_input === " ") { - setField(name_0, value_1 === undefined ? true : !value_1); - return; - } - if (key2.return) { - handleNavigation("down"); - return; - } - if (key2.backspace && value_1 !== undefined) { - unsetField(name_0); - return; - } - if (_input && !key2.return) { - runTypeahead(_input, ["yes", "no"], (i6) => setField(name_0, i6 === 0)); - return; - } - return; - } - if (isEnumSchema(schema_5) || isMultiSelectEnumSchema(schema_5)) { - if (key2.return) { - handleNavigation("down"); - return; - } - if (key2.backspace && value_1 !== undefined) { - unsetField(name_0); - return; - } - let labels_2; - let startIdx = 0; - if (isEnumSchema(schema_5)) { - const vals = getEnumValues2(schema_5); - labels_2 = vals.map((v_2) => getEnumLabel(schema_5, v_2).toLowerCase()); - if (value_1 !== undefined) { - startIdx = Math.max(0, vals.indexOf(value_1)); - } - } else { - const vals_0 = getMultiSelectValues(schema_5); - labels_2 = vals_0.map((v_3) => getMultiSelectLabel(schema_5, v_3).toLowerCase()); - } - if (key2.rightArrow) { - setExpandedAccordion(name_0); - setAccordionOptionIndex(startIdx); - return; - } - if (_input && !key2.leftArrow) { - runTypeahead(_input, labels_2, (i_0) => { - setExpandedAccordion(name_0); - setAccordionOptionIndex(i_0); - }); - return; - } - return; - } - if (key2.backspace) { - if (isEditingTextField && textInputValue === "") { - unsetField(name_0); - return; - } - } - }, { - isActive: true - }); - function validateRequired() { - const requiredFields_1 = requestedSchema.required || []; - for (const fieldName_8 of requiredFields_1) { - const value_2 = formValues[fieldName_8]; - if (value_2 === undefined || value_2 === null || value_2 === "") { - return false; - } - if (Array.isArray(value_2) && value_2.length === 0) { - return false; - } - } - return true; - } - const LINES_PER_FIELD = 3; - const DIALOG_OVERHEAD = 14; - const maxVisibleFields = Math.max(2, Math.floor((rows - DIALOG_OVERHEAD) / LINES_PER_FIELD)); - const scrollWindow = import_react220.useMemo(() => { - const total = schemaFields.length; - if (total <= maxVisibleFields) { - return { - start: 0, - end: total - }; - } - const focusIdx = currentFieldIndex ?? total - 1; - let start = Math.max(0, focusIdx - Math.floor(maxVisibleFields / 2)); - const end = Math.min(start + maxVisibleFields, total); - start = Math.max(0, end - maxVisibleFields); - return { - start, - end - }; - }, [schemaFields.length, maxVisibleFields, currentFieldIndex]); - const hasFieldsAbove = scrollWindow.start > 0; - const hasFieldsBelow = scrollWindow.end < schemaFields.length; - function renderFormFields() { - if (!schemaFields.length) - return null; - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - hasFieldsAbove && /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.arrowUp, - " ", - scrollWindow.start, - " more above" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - schemaFields.slice(scrollWindow.start, scrollWindow.end).map((field_0, visibleIdx) => { - const index_0 = scrollWindow.start + visibleIdx; - const { - name: name_1, - schema: schema_6, - isRequired - } = field_0; - const isActive = index_0 === currentFieldIndex && !focusedButton; - const value_3 = formValues[name_1]; - const hasValue = value_3 !== undefined && (!Array.isArray(value_3) || value_3.length > 0); - const error_0 = validationErrors[name_1]; - const isResolving = resolvingFields.has(name_1); - const checkbox = isResolving ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ResolvingSpinner, {}, undefined, false, undefined, this) : error_0 ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "error", - children: figures_default.warning - }, undefined, false, undefined, this) : hasValue ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "success", - dimColor: !isActive, - children: figures_default.tick - }, undefined, false, undefined, this) : isRequired ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "error", - children: "*" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - const selectionColor = error_0 ? "error" : hasValue ? "success" : isRequired ? "error" : "suggestion"; - const activeColor = isActive ? selectionColor : undefined; - const label = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: activeColor, - bold: isActive, - children: schema_6.title || name_1 - }, undefined, false, undefined, this); - let valueContent; - let accordionContent = null; - if (isMultiSelectEnumSchema(schema_6)) { - const msValues_0 = getMultiSelectValues(schema_6); - const selected_1 = value_3 ?? []; - const isExpanded = expandedAccordion === name_1 && isActive; - if (isExpanded) { - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: figures_default.triangleDownSmall - }, undefined, false, undefined, this); - accordionContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginLeft: 6, - children: msValues_0.map((optVal, optIdx) => { - const optLabel = getMultiSelectLabel(schema_6, optVal); - const isChecked = selected_1.includes(optVal); - const isFocused = optIdx === accordionOptionIndex; - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "suggestion", - children: isFocused ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: isChecked ? "success" : undefined, - children: isChecked ? figures_default.checkboxOn : figures_default.checkboxOff - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: isFocused ? "suggestion" : undefined, - bold: isFocused, - children: optLabel - }, undefined, false, undefined, this) - ] - }, optVal, true, undefined, this); - }) - }, undefined, false, undefined, this); - } else { - const arrow = isActive ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.triangleRightSmall, - " " - ] - }, undefined, true, undefined, this) : null; - if (selected_1.length > 0) { - const displayLabels = selected_1.map((v_4) => getMultiSelectLabel(schema_6, v_4)); - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - arrow, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: activeColor, - bold: isActive, - children: displayLabels.join(", ") - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } else { - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - arrow, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "not set" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - } - } else if (isEnumSchema(schema_6)) { - const enumValues_0 = getEnumValues2(schema_6); - const isExpanded_0 = expandedAccordion === name_1 && isActive; - if (isExpanded_0) { - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: figures_default.triangleDownSmall - }, undefined, false, undefined, this); - accordionContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginLeft: 6, - children: enumValues_0.map((optVal_0, optIdx_0) => { - const optLabel_0 = getEnumLabel(schema_6, optVal_0); - const isSelected = value_3 === optVal_0; - const isFocused_0 = optIdx_0 === accordionOptionIndex; - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "suggestion", - children: isFocused_0 ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: isSelected ? "success" : undefined, - children: isSelected ? figures_default.radioOn : figures_default.radioOff - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: isFocused_0 ? "suggestion" : undefined, - bold: isFocused_0, - children: optLabel_0 - }, undefined, false, undefined, this) - ] - }, optVal_0, true, undefined, this); - }) - }, undefined, false, undefined, this); - } else { - const arrow_0 = isActive ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.triangleRightSmall, - " " - ] - }, undefined, true, undefined, this) : null; - if (hasValue) { - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - arrow_0, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: activeColor, - bold: isActive, - children: getEnumLabel(schema_6, value_3) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } else { - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - arrow_0, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "not set" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - } - } else if (schema_6.type === "boolean") { - if (isActive) { - valueContent = hasValue ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: activeColor, - bold: true, - children: value_3 ? figures_default.checkboxOn : figures_default.checkboxOff - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: figures_default.checkboxOff - }, undefined, false, undefined, this); - } else { - valueContent = hasValue ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: value_3 ? figures_default.checkboxOn : figures_default.checkboxOff - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "not set" - }, undefined, false, undefined, this); - } - } else if (isTextField(schema_6)) { - if (isActive) { - valueContent = /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(TextInput, { - value: textInputValue, - onChange: handleTextInputChange, - onSubmit: handleTextInputSubmit, - placeholder: `Type something\u2026`, - columns: Math.min(columns - 20, 60), - cursorOffset: textInputCursorOffset, - onChangeCursorOffset: setTextInputCursorOffset, - focus: true, - showCursor: true - }, undefined, false, undefined, this); - } else { - const displayValue = hasValue && isDateTimeSchema(schema_6) ? formatDateDisplay(String(value_3), schema_6) : String(value_3); - valueContent = hasValue ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: displayValue - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "not set" - }, undefined, false, undefined, this); - } - } else { - valueContent = hasValue ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: String(value_3) - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "not set" - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: selectionColor, - children: isActive ? figures_default.pointer : " " - }, undefined, false, undefined, this), - checkbox, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - children: [ - label, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: activeColor, - children: ": " - }, undefined, false, undefined, this), - valueContent - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - accordionContent, - schema_6.description && /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginLeft: 6, - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: schema_6.description - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginLeft: 6, - height: 1, - children: error_0 ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "error", - italic: true, - children: error_0 - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, name_1, true, undefined, this); - }), - hasFieldsBelow && /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.arrowDown, - " ", - schemaFields.length - scrollWindow.end, - " more below" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(Dialog, { - title: `MCP server \u201C${serverName}\u201D requests your input`, - subtitle: ` -${message}`, - color: "permission", - onCancel: () => onResponse("cancel"), - isCancelActive: (!currentField || !!focusedButton) && !expandedAccordion, - inputGuide: (exitState) => exitState.pending ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191\u2193", - action: "navigate" - }, undefined, false, undefined, this), - currentField && /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "Backspace", - action: "unset" - }, undefined, false, undefined, this), - currentField && currentField.schema.type === "boolean" && /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "Space", - action: "toggle" - }, undefined, false, undefined, this), - currentField && isEnumSchema(currentField.schema) && (expandedAccordion ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "Space", - action: "select" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2192", - action: "expand" - }, undefined, false, undefined, this)), - currentField && isMultiSelectEnumSchema(currentField.schema) && (expandedAccordion ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "Space", - action: "toggle" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2192", - action: "expand" - }, undefined, false, undefined, this)) - ] - }, undefined, true, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - renderFormFields(), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "success", - children: focusedButton === "accept" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "accept", - color: focusedButton === "accept" ? "success" : undefined, - dimColor: focusedButton !== "accept", - children: " Accept " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "error", - children: focusedButton === "decline" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "decline", - color: focusedButton === "decline" ? "error" : undefined, - dimColor: focusedButton !== "decline", - children: " Decline" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -function ElicitationURLDialog({ - event, - onResponse, - onWaitingDismiss -}) { - const { - serverName, - signal, - waitingState - } = event; - const urlParams = event.params; - const { - message, - url: url3 - } = urlParams; - const [phase, setPhase] = import_react220.useState("prompt"); - const phaseRef = import_react220.useRef("prompt"); - const [focusedButton, setFocusedButton] = import_react220.useState("accept"); - const showCancel = waitingState?.showCancel ?? false; - useNotifyAfterTimeout("Claude Code needs your input", "elicitation_url_dialog"); - useRegisterOverlay("elicitation-url"); - phaseRef.current = phase; - const onWaitingDismissRef = import_react220.useRef(onWaitingDismiss); - onWaitingDismissRef.current = onWaitingDismiss; - import_react220.useEffect(() => { - const handleAbort2 = () => { - if (phaseRef.current === "waiting") { - onWaitingDismissRef.current?.("cancel"); - } else { - onResponse("cancel"); - } - }; - if (signal.aborted) { - handleAbort2(); - return; - } - signal.addEventListener("abort", handleAbort2); - return () => signal.removeEventListener("abort", handleAbort2); - }, [signal, onResponse]); - let domain2 = ""; - let urlBeforeDomain = ""; - let urlAfterDomain = ""; - try { - const parsed = new URL(url3); - domain2 = parsed.hostname; - const domainStart = url3.indexOf(domain2); - urlBeforeDomain = url3.slice(0, domainStart); - urlAfterDomain = url3.slice(domainStart + domain2.length); - } catch { - domain2 = url3; - } - import_react220.useEffect(() => { - if (phase === "waiting" && event.completed) { - onWaitingDismiss?.(showCancel ? "retry" : "dismiss"); - } - }, [phase, event.completed, onWaitingDismiss, showCancel]); - const handleAccept = import_react220.useCallback(() => { - openBrowser(url3); - onResponse("accept"); - setPhase("waiting"); - phaseRef.current = "waiting"; - setFocusedButton("open"); - }, [onResponse, url3]); - use_input_default((_input, key2) => { - if (phase === "prompt") { - if (key2.leftArrow || key2.rightArrow) { - setFocusedButton((prev) => prev === "accept" ? "decline" : "accept"); - return; - } - if (key2.return) { - if (focusedButton === "accept") { - handleAccept(); - } else { - onResponse("decline"); - } - } - } else { - const waitingButtons = showCancel ? ["open", "action", "cancel"] : ["open", "action"]; - if (key2.leftArrow || key2.rightArrow) { - setFocusedButton((prev_0) => { - const idx = waitingButtons.indexOf(prev_0); - const delta = key2.rightArrow ? 1 : -1; - return waitingButtons[(idx + delta + waitingButtons.length) % waitingButtons.length]; - }); - return; - } - if (key2.return) { - if (focusedButton === "open") { - openBrowser(url3); - } else if (focusedButton === "cancel") { - onWaitingDismiss?.("cancel"); - } else { - onWaitingDismiss?.(showCancel ? "retry" : "dismiss"); - } - } - } - }); - if (phase === "waiting") { - const actionLabel = waitingState?.actionLabel ?? "Continue without waiting"; - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(Dialog, { - title: `MCP server \u201C${serverName}\u201D \u2014 waiting for completion`, - subtitle: ` -${message}`, - color: "permission", - onCancel: () => onWaitingDismiss?.("cancel"), - isCancelActive: true, - inputGuide: (exitState) => exitState.pending ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "\\u2190\\u2192", - action: "switch" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - urlBeforeDomain, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: true, - children: domain2 - }, undefined, false, undefined, this), - urlAfterDomain - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "Waiting for the server to confirm completion\u2026" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "success", - children: focusedButton === "open" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "open", - color: focusedButton === "open" ? "success" : undefined, - dimColor: focusedButton !== "open", - children: " Reopen URL " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "success", - children: focusedButton === "action" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "action", - color: focusedButton === "action" ? "success" : undefined, - dimColor: focusedButton !== "action", - children: ` ${actionLabel}` - }, undefined, false, undefined, this), - showCancel && /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(jsx_dev_runtime400.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "error", - children: focusedButton === "cancel" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "cancel", - color: focusedButton === "cancel" ? "error" : undefined, - dimColor: focusedButton !== "cancel", - children: " Cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(Dialog, { - title: `MCP server \u201C${serverName}\u201D wants to open a URL`, - subtitle: ` -${message}`, - color: "permission", - onCancel: () => onResponse("cancel"), - isCancelActive: true, - inputGuide: (exitState_0) => exitState_0.pending ? /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - "Press ", - exitState_0.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(KeyboardShortcutHint, { - shortcut: "\\u2190\\u2192", - action: "switch" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - children: [ - urlBeforeDomain, - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: true, - children: domain2 - }, undefined, false, undefined, this), - urlAfterDomain - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "success", - children: focusedButton === "accept" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "accept", - color: focusedButton === "accept" ? "success" : undefined, - dimColor: focusedButton !== "accept", - children: " Accept " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - color: "error", - children: focusedButton === "decline" ? figures_default.pointer : " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime400.jsxDEV(ThemedText, { - bold: focusedButton === "decline", - color: focusedButton === "decline" ? "error" : undefined, - dimColor: focusedButton !== "decline", - children: " Decline" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var import_compiler_runtime311, import_react220, jsx_dev_runtime400, isTextField = (s4) => ["string", "number", "integer"].includes(s4.type), RESOLVING_SPINNER_CHARS = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F", advanceSpinnerFrame = (f4) => (f4 + 1) % RESOLVING_SPINNER_CHARS.length; -var init_ElicitationDialog = __esm(() => { - init_figures(); - init_overlayContext(); - init_useNotifyAfterTimeout(); - init_useTerminalSize(); - init_ink2(); - init_useKeybinding(); - init_browser(); - init_elicitationValidation(); - init_stringUtils(); - init_ConfigurableShortcutHint(); - init_Byline(); - init_Dialog(); - init_KeyboardShortcutHint(); - init_TextInput(); - import_compiler_runtime311 = __toESM(require_compiler_runtime(), 1); - import_react220 = __toESM(require_react(), 1); - jsx_dev_runtime400 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/hooks/PromptDialog.tsx -function PromptDialog(t0) { - const $2 = import_compiler_runtime312.c(15); - const { - title, - toolInputSummary, - request: request2, - onRespond, - onAbort - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - isActive: true - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - useKeybinding("app:interrupt", onAbort, t1); - let t22; - if ($2[1] !== request2.options) { - t22 = request2.options.map(_temp189); - $2[1] = request2.options; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const options2 = t22; - let t32; - if ($2[3] !== toolInputSummary) { - t32 = toolInputSummary ? /* @__PURE__ */ jsx_dev_runtime401.jsxDEV(ThemedText, { - dimColor: true, - children: toolInputSummary - }, undefined, false, undefined, this) : undefined; - $2[3] = toolInputSummary; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== onRespond) { - t4 = (value) => { - onRespond(value); - }; - $2[5] = onRespond; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== options2 || $2[8] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime401.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingY: 1, - children: /* @__PURE__ */ jsx_dev_runtime401.jsxDEV(Select, { - options: options2, - onChange: t4 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[7] = options2; - $2[8] = t4; - $2[9] = t5; - } else { - t5 = $2[9]; - } - let t6; - if ($2[10] !== request2.message || $2[11] !== t32 || $2[12] !== t5 || $2[13] !== title) { - t6 = /* @__PURE__ */ jsx_dev_runtime401.jsxDEV(PermissionDialog, { - title, - subtitle: request2.message, - titleRight: t32, - children: t5 - }, undefined, false, undefined, this); - $2[10] = request2.message; - $2[11] = t32; - $2[12] = t5; - $2[13] = title; - $2[14] = t6; - } else { - t6 = $2[14]; - } - return t6; -} -function _temp189(opt) { - return { - label: opt.label, - value: opt.key, - description: opt.description - }; -} -var import_compiler_runtime312, jsx_dev_runtime401; -var init_PromptDialog = __esm(() => { - init_ink2(); - init_useKeybinding(); - init_select(); - init_PermissionDialog(); - import_compiler_runtime312 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime401 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useCommandQueue.ts -function useCommandQueue() { - return import_react221.useSyncExternalStore(subscribeToCommandQueue, getCommandQueueSnapshot); -} -var import_react221; -var init_useCommandQueue = __esm(() => { - init_messageQueueManager(); - import_react221 = __toESM(require_react(), 1); -}); - -// src/hooks/useIdeAtMentioned.ts -function useIdeAtMentioned(mcpClients, onAtMentioned) { - const ideClientRef = import_react222.useRef(undefined); - import_react222.useEffect(() => { - const ideClient = getConnectedIdeClient(mcpClients); - if (ideClientRef.current !== ideClient) { - ideClientRef.current = ideClient; - } - if (ideClient) { - ideClient.client.setNotificationHandler(AtMentionedSchema(), (notification) => { - if (ideClientRef.current !== ideClient) { - return; - } - try { - const data = notification.params; - const lineStart = data.lineStart !== undefined ? data.lineStart + 1 : undefined; - const lineEnd = data.lineEnd !== undefined ? data.lineEnd + 1 : undefined; - onAtMentioned({ - filePath: data.filePath, - lineStart, - lineEnd - }); - } catch (error46) { - logError2(error46); - } - }); - } - }, [mcpClients, onAtMentioned]); -} -var import_react222, NOTIFICATION_METHOD = "at_mentioned", AtMentionedSchema; -var init_useIdeAtMentioned = __esm(() => { - init_log2(); - init_v4(); - init_ide(); - import_react222 = __toESM(require_react(), 1); - AtMentionedSchema = lazySchema(() => exports_external.object({ - method: exports_external.literal(NOTIFICATION_METHOD), - params: exports_external.object({ - filePath: exports_external.string(), - lineStart: exports_external.number().optional(), - lineEnd: exports_external.number().optional() - }) - })); -}); - -// src/buddy/sprites.ts -var BODIES; -var init_sprites = __esm(() => { - init_types16(); - BODIES = { - [duck]: [ - [ - " ", - " __ ", - " <({E} )___ ", - " ( ._> ", - " `--\xB4 " - ], - [ - " ", - " __ ", - " <({E} )___ ", - " ( ._> ", - " `--\xB4~ " - ], - [ - " ", - " __ ", - " <({E} )___ ", - " ( .__> ", - " `--\xB4 " - ] - ], - [goose]: [ - [ - " ", - " ({E}> ", - " || ", - " _(__)_ ", - " ^^^^ " - ], - [ - " ", - " ({E}> ", - " || ", - " _(__)_ ", - " ^^^^ " - ], - [ - " ", - " ({E}>> ", - " || ", - " _(__)_ ", - " ^^^^ " - ] - ], - [blob]: [ - [ - " ", - " .----. ", - " ( {E} {E} ) ", - " ( ) ", - " `----\xB4 " - ], - [ - " ", - " .------. ", - " ( {E} {E} ) ", - " ( ) ", - " `------\xB4 " - ], - [ - " ", - " .--. ", - " ({E} {E}) ", - " ( ) ", - " `--\xB4 " - ] - ], - [cat]: [ - [ - " ", - " /\\_/\\ ", - " ( {E} {E}) ", - " ( \u03C9 ) ", - ' (")_(") ' - ], - [ - " ", - " /\\_/\\ ", - " ( {E} {E}) ", - " ( \u03C9 ) ", - ' (")_(")~ ' - ], - [ - " ", - " /\\-/\\ ", - " ( {E} {E}) ", - " ( \u03C9 ) ", - ' (")_(") ' - ] - ], - [dragon]: [ - [ - " ", - " /^\\ /^\\ ", - " < {E} {E} > ", - " ( ~~ ) ", - " `-vvvv-\xB4 " - ], - [ - " ", - " /^\\ /^\\ ", - " < {E} {E} > ", - " ( ) ", - " `-vvvv-\xB4 " - ], - [ - " ~ ~ ", - " /^\\ /^\\ ", - " < {E} {E} > ", - " ( ~~ ) ", - " `-vvvv-\xB4 " - ] - ], - [octopus]: [ - [ - " ", - " .----. ", - " ( {E} {E} ) ", - " (______) ", - " /\\/\\/\\/\\ " - ], - [ - " ", - " .----. ", - " ( {E} {E} ) ", - " (______) ", - " \\/\\/\\/\\/ " - ], - [ - " o ", - " .----. ", - " ( {E} {E} ) ", - " (______) ", - " /\\/\\/\\/\\ " - ] - ], - [owl]: [ - [ - " ", - " /\\ /\\ ", - " (({E})({E})) ", - " ( >< ) ", - " `----\xB4 " - ], - [ - " ", - " /\\ /\\ ", - " (({E})({E})) ", - " ( >< ) ", - " .----. " - ], - [ - " ", - " /\\ /\\ ", - " (({E})(-)) ", - " ( >< ) ", - " `----\xB4 " - ] - ], - [penguin]: [ - [ - " ", - " .---. ", - " ({E}>{E}) ", - " /( )\\ ", - " `---\xB4 " - ], - [ - " ", - " .---. ", - " ({E}>{E}) ", - " |( )| ", - " `---\xB4 " - ], - [ - " .---. ", - " ({E}>{E}) ", - " /( )\\ ", - " `---\xB4 ", - " ~ ~ " - ] - ], - [turtle]: [ - [ - " ", - " _,--._ ", - " ( {E} {E} ) ", - " /[______]\\ ", - " `` `` " - ], - [ - " ", - " _,--._ ", - " ( {E} {E} ) ", - " /[______]\\ ", - " `` `` " - ], - [ - " ", - " _,--._ ", - " ( {E} {E} ) ", - " /[======]\\ ", - " `` `` " - ] - ], - [snail]: [ - [ - " ", - " {E} .--. ", - " \\ ( @ ) ", - " \\_`--\xB4 ", - " ~~~~~~~ " - ], - [ - " ", - " {E} .--. ", - " | ( @ ) ", - " \\_`--\xB4 ", - " ~~~~~~~ " - ], - [ - " ", - " {E} .--. ", - " \\ ( @ ) ", - " \\_`--\xB4 ", - " ~~~~~~ " - ] - ], - [ghost]: [ - [ - " ", - " .----. ", - " / {E} {E} \\ ", - " | | ", - " ~`~``~`~ " - ], - [ - " ", - " .----. ", - " / {E} {E} \\ ", - " | | ", - " `~`~~`~` " - ], - [ - " ~ ~ ", - " .----. ", - " / {E} {E} \\ ", - " | | ", - " ~~`~~`~~ " - ] - ], - [axolotl]: [ - [ - " ", - "}~(______)~{", - "}~({E} .. {E})~{", - " ( .--. ) ", - " (_/ \\_) " - ], - [ - " ", - "~}(______){~", - "~}({E} .. {E}){~", - " ( .--. ) ", - " (_/ \\_) " - ], - [ - " ", - "}~(______)~{", - "}~({E} .. {E})~{", - " ( -- ) ", - " ~_/ \\_~ " - ] - ], - [capybara]: [ - [ - " ", - " n______n ", - " ( {E} {E} ) ", - " ( oo ) ", - " `------\xB4 " - ], - [ - " ", - " n______n ", - " ( {E} {E} ) ", - " ( Oo ) ", - " `------\xB4 " - ], - [ - " ~ ~ ", - " u______n ", - " ( {E} {E} ) ", - " ( oo ) ", - " `------\xB4 " - ] - ], - [cactus]: [ - [ - " ", - " n ____ n ", - " | |{E} {E}| | ", - " |_| |_| ", - " | | " - ], - [ - " ", - " ____ ", - " n |{E} {E}| n ", - " |_| |_| ", - " | | " - ], - [ - " n n ", - " | ____ | ", - " | |{E} {E}| | ", - " |_| |_| ", - " | | " - ] - ], - [robot]: [ - [ - " ", - " .[||]. ", - " [ {E} {E} ] ", - " [ ==== ] ", - " `------\xB4 " - ], - [ - " ", - " .[||]. ", - " [ {E} {E} ] ", - " [ -==- ] ", - " `------\xB4 " - ], - [ - " * ", - " .[||]. ", - " [ {E} {E} ] ", - " [ ==== ] ", - " `------\xB4 " - ] - ], - [rabbit]: [ - [ - " ", - " (\\__/) ", - " ( {E} {E} ) ", - " =( .. )= ", - ' (")__(") ' - ], - [ - " ", - " (|__/) ", - " ( {E} {E} ) ", - " =( .. )= ", - ' (")__(") ' - ], - [ - " ", - " (\\__/) ", - " ( {E} {E} ) ", - " =( . . )= ", - ' (")__(") ' - ] - ], - [mushroom]: [ - [ - " ", - " .-o-OO-o-. ", - "(__________)", - " |{E} {E}| ", - " |____| " - ], - [ - " ", - " .-O-oo-O-. ", - "(__________)", - " |{E} {E}| ", - " |____| " - ], - [ - " . o . ", - " .-o-OO-o-. ", - "(__________)", - " |{E} {E}| ", - " |____| " - ] - ], - [chonk]: [ - [ - " ", - " /\\ /\\ ", - " ( {E} {E} ) ", - " ( .. ) ", - " `------\xB4 " - ], - [ - " ", - " /\\ /| ", - " ( {E} {E} ) ", - " ( .. ) ", - " `------\xB4 " - ], - [ - " ", - " /\\ /\\ ", - " ( {E} {E} ) ", - " ( .. ) ", - " `------\xB4~ " - ] - ] - }; -}); - -// src/buddy/CompanionSprite.tsx -function spriteColWidth(nameWidth) { - return Math.max(SPRITE_BODY_WIDTH, nameWidth + NAME_ROW_PAD); -} -function companionReservedColumns(terminalColumns, speaking) { - if (true) - return 0; - const companion = getCompanion(); - if (!companion || getGlobalConfig().companionMuted) - return 0; - if (terminalColumns < MIN_COLS_FOR_FULL_SPRITE) - return 0; - const nameWidth = stringWidth(companion.name); - const bubble = speaking && !isFullscreenActive() ? BUBBLE_WIDTH : 0; - return spriteColWidth(nameWidth) + SPRITE_PADDING_X + bubble; -} -var import_compiler_runtime313, import_react223, jsx_dev_runtime402, H3, PET_HEARTS, MIN_COLS_FOR_FULL_SPRITE = 100, SPRITE_BODY_WIDTH = 12, NAME_ROW_PAD = 2, SPRITE_PADDING_X = 2, BUBBLE_WIDTH = 36; -var init_CompanionSprite = __esm(() => { - init_figures(); - init_useTerminalSize(); - init_stringWidth(); - init_ink2(); - init_AppState(); - init_config(); - init_fullscreen(); - init_companion(); - init_sprites(); - init_types16(); - import_compiler_runtime313 = __toESM(require_compiler_runtime(), 1); - import_react223 = __toESM(require_react(), 1); - jsx_dev_runtime402 = __toESM(require_jsx_dev_runtime(), 1); - H3 = figures_default.heart; - PET_HEARTS = [` ${H3} ${H3} `, ` ${H3} ${H3} ${H3} `, ` ${H3} ${H3} ${H3} `, `${H3} ${H3} ${H3} `, "\xB7 \xB7 \xB7 "]; -}); - -// src/buddy/useBuddyNotification.tsx -function isBuddyTeaserWindow() { - if (false) - ; - const d4 = new Date; - return d4.getFullYear() === 2026 && d4.getMonth() === 3 && d4.getDate() <= 7; -} -function RainbowText2(t0) { - const $2 = import_compiler_runtime314.c(2); - const { - text - } = t0; - let t1; - if ($2[0] !== text) { - t1 = /* @__PURE__ */ jsx_dev_runtime403.jsxDEV(jsx_dev_runtime403.Fragment, { - children: [...text].map(_temp190) - }, undefined, false, undefined, this); - $2[0] = text; - $2[1] = t1; - } else { - t1 = $2[1]; - } - return t1; -} -function _temp190(ch2, i6) { - return /* @__PURE__ */ jsx_dev_runtime403.jsxDEV(ThemedText, { - color: getRainbowColor(i6), - children: ch2 - }, i6, false, undefined, this); -} -function useBuddyNotification() { - const $2 = import_compiler_runtime314.c(4); - const { - addNotification, - removeNotification - } = useNotifications(); - let t0; - let t1; - if ($2[0] !== addNotification || $2[1] !== removeNotification) { - t0 = () => { - if (true) { - return; - } - const config10 = getGlobalConfig(); - if (config10.companion || !isBuddyTeaserWindow()) { - return; - } - addNotification({ - key: "buddy-teaser", - jsx: /* @__PURE__ */ jsx_dev_runtime403.jsxDEV(RainbowText2, { - text: "/buddy" - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 15000 - }); - return () => removeNotification("buddy-teaser"); - }; - t1 = [addNotification, removeNotification]; - $2[0] = addNotification; - $2[1] = removeNotification; - $2[2] = t0; - $2[3] = t1; - } else { - t0 = $2[2]; - t1 = $2[3]; - } - import_react224.useEffect(t0, t1); -} -function findBuddyTriggerPositions(text) { - if (true) - return []; - const triggers = []; - const re = /\/buddy\b/g; - let m4; - while ((m4 = re.exec(text)) !== null) { - triggers.push({ - start: m4.index, - end: m4.index + m4[0].length - }); - } - return triggers; -} -var import_compiler_runtime314, import_react224, jsx_dev_runtime403; -var init_useBuddyNotification = __esm(() => { - init_notifications(); - init_ink2(); - init_config(); - init_thinking(); - import_compiler_runtime314 = __toESM(require_compiler_runtime(), 1); - import_react224 = __toESM(require_react(), 1); - jsx_dev_runtime403 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useIdeConnectionStatus.ts -function useIdeConnectionStatus(mcpClients) { - return import_react225.useMemo(() => { - const ideClient = mcpClients?.find((client16) => client16.name === "ide"); - if (!ideClient) { - return { status: null, ideName: null }; - } - const config10 = ideClient.config; - const ideName = config10.type === "sse-ide" || config10.type === "ws-ide" ? config10.ideName : null; - if (ideClient.type === "connected") { - return { status: "connected", ideName }; - } - if (ideClient.type === "pending") { - return { status: "pending", ideName }; - } - return { status: "disconnected", ideName }; - }, [mcpClients]); -} -var import_react225; -var init_useIdeConnectionStatus = __esm(() => { - import_react225 = __toESM(require_react(), 1); -}); - -// src/hooks/useVoiceEnabled.ts -var import_react226; -var init_useVoiceEnabled = __esm(() => { - init_AppState(); - init_voiceModeEnabled(); - import_react226 = __toESM(require_react(), 1); -}); - -// src/hooks/useUpdateNotification.ts -function getSemverPart(version7) { - return `${import_semver13.major(version7, { loose: true })}.${import_semver13.minor(version7, { loose: true })}.${import_semver13.patch(version7, { loose: true })}`; -} -function useUpdateNotification(updatedVersion, initialVersion = MACRO.VERSION) { - const [lastNotifiedSemver, setLastNotifiedSemver] = import_react227.useState(() => getSemverPart(initialVersion)); - if (!updatedVersion) { - return null; - } - const updatedSemver = getSemverPart(updatedVersion); - if (updatedSemver !== lastNotifiedSemver) { - setLastNotifiedSemver(updatedSemver); - return updatedSemver; - } - return null; -} -var import_react227, import_semver13; -var init_useUpdateNotification = __esm(() => { - import_react227 = __toESM(require_react(), 1); - import_semver13 = __toESM(require_semver2(), 1); -}); - -// src/components/AutoUpdater.tsx -function AutoUpdater({ - isUpdating, - onChangeIsUpdating, - onAutoUpdaterResult, - autoUpdaterResult, - showSuccessMessage, - verbose -}) { - const [versions2, setVersions] = import_react228.useState({}); - const [hasLocalInstall, setHasLocalInstall] = import_react228.useState(false); - const updateSemver = useUpdateNotification(autoUpdaterResult?.version); - import_react228.useEffect(() => { - localInstallationExists().then(setHasLocalInstall); - }, []); - const isUpdatingRef = import_react228.useRef(isUpdating); - isUpdatingRef.current = isUpdating; - const checkForUpdates = React129.useCallback(async () => { - if (isUpdatingRef.current) { - return; - } - if (false) {} - const currentVersion = MACRO.VERSION; - const channel = getInitialSettings()?.autoUpdatesChannel ?? "latest"; - let latestVersion = await getLatestVersion(channel); - const isDisabled = isAutoUpdaterDisabled(); - const maxVersion = await getMaxVersion(); - if (maxVersion && latestVersion && gt(latestVersion, maxVersion)) { - logForDebugging(`AutoUpdater: maxVersion ${maxVersion} is set, capping update from ${latestVersion} to ${maxVersion}`); - if (gte(currentVersion, maxVersion)) { - logForDebugging(`AutoUpdater: current version ${currentVersion} is already at or above maxVersion ${maxVersion}, skipping update`); - setVersions({ - global: currentVersion, - latest: latestVersion - }); - return; - } - latestVersion = maxVersion; - } - setVersions({ - global: currentVersion, - latest: latestVersion - }); - if (!isDisabled && currentVersion && latestVersion && !gte(currentVersion, latestVersion) && !shouldSkipVersion(latestVersion)) { - const startTime = Date.now(); - onChangeIsUpdating(true); - const config10 = getGlobalConfig(); - if (config10.installMethod !== "native") { - await removeInstalledSymlink(); - } - const installationType = await getCurrentInstallationType(); - logForDebugging(`AutoUpdater: Detected installation type: ${installationType}`); - if (installationType === "development") { - logForDebugging("AutoUpdater: Cannot auto-update development build"); - onChangeIsUpdating(false); - return; - } - let installStatus; - let updateMethod; - if (installationType === "npm-local") { - logForDebugging("AutoUpdater: Using local update method"); - updateMethod = "local"; - installStatus = await installOrUpdateClaudePackage(channel); - } else if (installationType === "npm-global") { - logForDebugging("AutoUpdater: Using global update method"); - updateMethod = "global"; - installStatus = await installGlobalPackage(); - } else if (installationType === "native") { - logForDebugging("AutoUpdater: Unexpected native installation in non-native updater"); - onChangeIsUpdating(false); - return; - } else { - logForDebugging(`AutoUpdater: Unknown installation type, falling back to config`); - const isMigrated = config10.installMethod === "local"; - updateMethod = isMigrated ? "local" : "global"; - if (isMigrated) { - installStatus = await installOrUpdateClaudePackage(channel); - } else { - installStatus = await installGlobalPackage(); - } - } - onChangeIsUpdating(false); - if (installStatus === "success") { - logEvent("tengu_auto_updater_success", { - fromVersion: currentVersion, - toVersion: latestVersion, - durationMs: Date.now() - startTime, - wasMigrated: updateMethod === "local", - installationType - }); - } else { - logEvent("tengu_auto_updater_fail", { - fromVersion: currentVersion, - attemptedVersion: latestVersion, - status: installStatus, - durationMs: Date.now() - startTime, - wasMigrated: updateMethod === "local", - installationType - }); - } - onAutoUpdaterResult({ - version: latestVersion, - status: installStatus - }); - } - }, [onAutoUpdaterResult]); - import_react228.useEffect(() => { - checkForUpdates(); - }, [checkForUpdates]); - useInterval(checkForUpdates, 30 * 60 * 1000); - if (!autoUpdaterResult?.version && (!versions2.global || !versions2.latest)) { - return null; - } - if (!autoUpdaterResult?.version && !isUpdating) { - return null; - } - return /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - verbose && /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: [ - "globalVersion: ", - versions2.global, - " \xB7 latestVersion:", - " ", - versions2.latest - ] - }, undefined, true, undefined, this), - isUpdating ? /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(jsx_dev_runtime404.Fragment, { - children: /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedText, { - color: "text", - dimColor: true, - wrap: "truncate", - children: "Auto-updating\u2026" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : autoUpdaterResult?.status === "success" && showSuccessMessage && updateSemver && /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedText, { - color: "success", - wrap: "truncate", - children: "\u2713 Update installed \xB7 Restart to apply" - }, undefined, false, undefined, this), - (autoUpdaterResult?.status === "install_failed" || autoUpdaterResult?.status === "no_permissions") && /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedText, { - color: "error", - wrap: "truncate", - children: [ - "\u2717 Auto-update failed \xB7 Try ", - /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedText, { - bold: true, - children: "claude doctor" - }, undefined, false, undefined, this), - " or", - " ", - /* @__PURE__ */ jsx_dev_runtime404.jsxDEV(ThemedText, { - bold: true, - children: hasLocalInstall ? `cd ~/.claude/local && npm update ${MACRO.PACKAGE_URL}` : `npm i -g ${MACRO.PACKAGE_URL}` - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -var React129, import_react228, jsx_dev_runtime404; -var init_AutoUpdater = __esm(() => { - init_analytics(); - init_dist4(); - init_useUpdateNotification(); - init_ink2(); - init_autoUpdater(); - init_config(); - init_debug(); - init_doctorDiagnostic(); - init_localInstaller(); - init_nativeInstaller(); - init_settings2(); - React129 = __toESM(require_react(), 1); - import_react228 = __toESM(require_react(), 1); - jsx_dev_runtime404 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/NativeAutoUpdater.tsx -function getErrorType(errorMessage3) { - if (errorMessage3.includes("timeout")) { - return "timeout"; - } - if (errorMessage3.includes("Checksum mismatch")) { - return "checksum_mismatch"; - } - if (errorMessage3.includes("ENOENT") || errorMessage3.includes("not found")) { - return "not_found"; - } - if (errorMessage3.includes("EACCES") || errorMessage3.includes("permission")) { - return "permission_denied"; - } - if (errorMessage3.includes("ENOSPC")) { - return "disk_full"; - } - if (errorMessage3.includes("npm")) { - return "npm_error"; - } - if (errorMessage3.includes("network") || errorMessage3.includes("ECONNREFUSED") || errorMessage3.includes("ENOTFOUND")) { - return "network_error"; - } - return "unknown"; -} -function NativeAutoUpdater({ - isUpdating, - onChangeIsUpdating, - onAutoUpdaterResult, - autoUpdaterResult, - showSuccessMessage, - verbose -}) { - const [versions2, setVersions] = import_react229.useState({}); - const [maxVersionIssue, setMaxVersionIssue] = import_react229.useState(null); - const updateSemver = useUpdateNotification(autoUpdaterResult?.version); - const channel = getInitialSettings()?.autoUpdatesChannel ?? "latest"; - const isUpdatingRef = import_react229.useRef(isUpdating); - isUpdatingRef.current = isUpdating; - const checkForUpdates = React130.useCallback(async () => { - if (isUpdatingRef.current) { - return; - } - if (false) {} - if (isAutoUpdaterDisabled()) { - return; - } - onChangeIsUpdating(true); - const startTime = Date.now(); - logEvent("tengu_native_auto_updater_start", {}); - try { - const maxVersion = await getMaxVersion(); - if (maxVersion && gt(MACRO.VERSION, maxVersion)) { - const msg = await getMaxVersionMessage(); - setMaxVersionIssue(msg ?? "affects your version"); - } - const result = await installLatest(channel); - const currentVersion = MACRO.VERSION; - const latencyMs = Date.now() - startTime; - if (result.lockFailed) { - logEvent("tengu_native_auto_updater_lock_contention", { - latency_ms: latencyMs - }); - return; - } - setVersions({ - current: currentVersion, - latest: result.latestVersion - }); - if (result.wasUpdated) { - logEvent("tengu_native_auto_updater_success", { - latency_ms: latencyMs - }); - onAutoUpdaterResult({ - version: result.latestVersion, - status: "success" - }); - } else { - logEvent("tengu_native_auto_updater_up_to_date", { - latency_ms: latencyMs - }); - } - } catch (error46) { - const latencyMs = Date.now() - startTime; - const errorMessage3 = error46 instanceof Error ? error46.message : String(error46); - logError2(error46); - const errorType = getErrorType(errorMessage3); - logEvent("tengu_native_auto_updater_fail", { - latency_ms: latencyMs, - error_timeout: errorType === "timeout", - error_checksum: errorType === "checksum_mismatch", - error_not_found: errorType === "not_found", - error_permission: errorType === "permission_denied", - error_disk_full: errorType === "disk_full", - error_npm: errorType === "npm_error", - error_network: errorType === "network_error" - }); - onAutoUpdaterResult({ - version: null, - status: "install_failed" - }); - } finally { - onChangeIsUpdating(false); - } - }, [onAutoUpdaterResult, channel]); - import_react229.useEffect(() => { - checkForUpdates(); - }, [checkForUpdates]); - useInterval(checkForUpdates, 30 * 60 * 1000); - const hasUpdateResult = !!autoUpdaterResult?.version; - const hasVersionInfo = !!versions2.current && !!versions2.latest; - const shouldRender = !!maxVersionIssue || hasUpdateResult || isUpdating && hasVersionInfo; - if (!shouldRender) { - return null; - } - return /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedBox_default, { - flexDirection: "row", - gap: 1, - children: [ - verbose && /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: [ - "current: ", - versions2.current, - " \xB7 ", - channel, - ": ", - versions2.latest - ] - }, undefined, true, undefined, this), - isUpdating ? /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: "Checking for updates" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : autoUpdaterResult?.status === "success" && showSuccessMessage && updateSemver && /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedText, { - color: "success", - wrap: "truncate", - children: "\u2713 Update installed \xB7 Restart to update" - }, undefined, false, undefined, this), - autoUpdaterResult?.status === "install_failed" && /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedText, { - color: "error", - wrap: "truncate", - children: [ - "\u2717 Auto-update failed \xB7 Try ", - /* @__PURE__ */ jsx_dev_runtime405.jsxDEV(ThemedText, { - bold: true, - children: "/status" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - maxVersionIssue && false - ] - }, undefined, true, undefined, this); -} -var React130, import_react229, jsx_dev_runtime405; -var init_NativeAutoUpdater = __esm(() => { - init_analytics(); - init_debug(); - init_log2(); - init_dist4(); - init_useUpdateNotification(); - init_ink2(); - init_autoUpdater(); - init_config(); - init_nativeInstaller(); - init_settings2(); - React130 = __toESM(require_react(), 1); - import_react229 = __toESM(require_react(), 1); - jsx_dev_runtime405 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PackageManagerAutoUpdater.tsx -function PackageManagerAutoUpdater(t0) { - const $2 = import_compiler_runtime315.c(10); - const { - verbose - } = t0; - const [updateAvailable, setUpdateAvailable] = import_react230.useState(false); - const [packageManager, setPackageManager] = import_react230.useState("unknown"); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = async () => { - if (isAutoUpdaterDisabled()) { - return; - } - const [channel, pm] = await Promise.all([Promise.resolve(getInitialSettings()?.autoUpdatesChannel ?? "latest"), getPackageManager()]); - setPackageManager(pm); - let latest = await getLatestVersionFromGcs(channel); - const maxVersion = await getMaxVersion(); - if (maxVersion && latest && gt(latest, maxVersion)) { - logForDebugging(`PackageManagerAutoUpdater: maxVersion ${maxVersion} is set, capping update from ${latest} to ${maxVersion}`); - if (gte(MACRO.VERSION, maxVersion)) { - logForDebugging(`PackageManagerAutoUpdater: current version ${MACRO.VERSION} is already at or above maxVersion ${maxVersion}, skipping update`); - setUpdateAvailable(false); - return; - } - latest = maxVersion; - } - const hasUpdate = latest && !gte(MACRO.VERSION, latest) && !shouldSkipVersion(latest); - setUpdateAvailable(!!hasUpdate); - if (hasUpdate) { - logForDebugging(`PackageManagerAutoUpdater: Update available ${MACRO.VERSION} -> ${latest}`); - } - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const checkForUpdates = t1; - let t22; - let t32; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = () => { - checkForUpdates(); - }; - t32 = [checkForUpdates]; - $2[1] = t22; - $2[2] = t32; - } else { - t22 = $2[1]; - t32 = $2[2]; - } - React131.useEffect(t22, t32); - useInterval(checkForUpdates, 1800000); - if (!updateAvailable) { - return null; - } - const updateCommand = packageManager === "homebrew" ? "brew upgrade claude-code" : packageManager === "winget" ? "winget upgrade Anthropic.ClaudeCode" : packageManager === "apk" ? "apk upgrade claude-code" : "your package manager update command"; - let t4; - if ($2[3] !== verbose) { - t4 = verbose && /* @__PURE__ */ jsx_dev_runtime406.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: [ - "currentVersion: ", - MACRO.VERSION - ] - }, undefined, true, undefined, this); - $2[3] = verbose; - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] !== updateCommand) { - t5 = /* @__PURE__ */ jsx_dev_runtime406.jsxDEV(ThemedText, { - color: "warning", - wrap: "truncate", - children: [ - "Update available! Run: ", - /* @__PURE__ */ jsx_dev_runtime406.jsxDEV(ThemedText, { - bold: true, - children: updateCommand - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[5] = updateCommand; - $2[6] = t5; - } else { - t5 = $2[6]; - } - let t6; - if ($2[7] !== t4 || $2[8] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime406.jsxDEV(jsx_dev_runtime406.Fragment, { - children: [ - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[7] = t4; - $2[8] = t5; - $2[9] = t6; - } else { - t6 = $2[9]; - } - return t6; -} -var import_compiler_runtime315, React131, import_react230, jsx_dev_runtime406; -var init_PackageManagerAutoUpdater = __esm(() => { - init_dist4(); - init_ink2(); - init_autoUpdater(); - init_config(); - init_debug(); - init_packageManagers(); - init_settings2(); - import_compiler_runtime315 = __toESM(require_compiler_runtime(), 1); - React131 = __toESM(require_react(), 1); - import_react230 = __toESM(require_react(), 1); - jsx_dev_runtime406 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/AutoUpdaterWrapper.tsx -function AutoUpdaterWrapper(t0) { - const $2 = import_compiler_runtime316.c(17); - const { - isUpdating, - onChangeIsUpdating, - onAutoUpdaterResult, - autoUpdaterResult, - showSuccessMessage, - verbose - } = t0; - const [useNativeInstaller, setUseNativeInstaller] = React132.useState(null); - const [isPackageManager, setIsPackageManager] = React132.useState(null); - let t1; - let t22; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - const checkInstallation = async function checkInstallation2() { - if (false) {} - const installationType = await getCurrentInstallationType(); - logForDebugging(`AutoUpdaterWrapper: Installation type: ${installationType}`); - setUseNativeInstaller(installationType === "native"); - setIsPackageManager(installationType === "package-manager"); - }; - checkInstallation(); - }; - t22 = []; - $2[0] = t1; - $2[1] = t22; - } else { - t1 = $2[0]; - t22 = $2[1]; - } - React132.useEffect(t1, t22); - if (useNativeInstaller === null || isPackageManager === null) { - return null; - } - if (isPackageManager) { - let t33; - if ($2[2] !== autoUpdaterResult || $2[3] !== isUpdating || $2[4] !== onAutoUpdaterResult || $2[5] !== onChangeIsUpdating || $2[6] !== showSuccessMessage || $2[7] !== verbose) { - t33 = /* @__PURE__ */ jsx_dev_runtime407.jsxDEV(PackageManagerAutoUpdater, { - verbose, - onAutoUpdaterResult, - autoUpdaterResult, - isUpdating, - onChangeIsUpdating, - showSuccessMessage - }, undefined, false, undefined, this); - $2[2] = autoUpdaterResult; - $2[3] = isUpdating; - $2[4] = onAutoUpdaterResult; - $2[5] = onChangeIsUpdating; - $2[6] = showSuccessMessage; - $2[7] = verbose; - $2[8] = t33; - } else { - t33 = $2[8]; - } - return t33; - } - const Updater = useNativeInstaller ? NativeAutoUpdater : AutoUpdater; - let t32; - if ($2[9] !== Updater || $2[10] !== autoUpdaterResult || $2[11] !== isUpdating || $2[12] !== onAutoUpdaterResult || $2[13] !== onChangeIsUpdating || $2[14] !== showSuccessMessage || $2[15] !== verbose) { - t32 = /* @__PURE__ */ jsx_dev_runtime407.jsxDEV(Updater, { - verbose, - onAutoUpdaterResult, - autoUpdaterResult, - isUpdating, - onChangeIsUpdating, - showSuccessMessage - }, undefined, false, undefined, this); - $2[9] = Updater; - $2[10] = autoUpdaterResult; - $2[11] = isUpdating; - $2[12] = onAutoUpdaterResult; - $2[13] = onChangeIsUpdating; - $2[14] = showSuccessMessage; - $2[15] = verbose; - $2[16] = t32; - } else { - t32 = $2[16]; - } - return t32; -} -var import_compiler_runtime316, React132, jsx_dev_runtime407; -var init_AutoUpdaterWrapper = __esm(() => { - init_config(); - init_debug(); - init_doctorDiagnostic(); - init_AutoUpdater(); - init_NativeAutoUpdater(); - init_PackageManagerAutoUpdater(); - import_compiler_runtime316 = __toESM(require_compiler_runtime(), 1); - React132 = __toESM(require_react(), 1); - jsx_dev_runtime407 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/IdeStatusIndicator.tsx -import { basename as basename53 } from "path"; -function IdeStatusIndicator(t0) { - const $2 = import_compiler_runtime317.c(7); - const { - ideSelection, - mcpClients - } = t0; - const { - status: ideStatus - } = useIdeConnectionStatus(mcpClients); - const shouldShowIdeSelection = ideStatus === "connected" && (ideSelection?.filePath || ideSelection?.text && ideSelection.lineCount > 0); - if (ideStatus === null || !shouldShowIdeSelection || !ideSelection) { - return null; - } - if (ideSelection.text && ideSelection.lineCount > 0) { - const t1 = ideSelection.lineCount === 1 ? "line" : "lines"; - let t22; - if ($2[0] !== ideSelection.lineCount || $2[1] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime408.jsxDEV(ThemedText, { - color: "ide", - wrap: "truncate", - children: [ - "\u29C9 ", - ideSelection.lineCount, - " ", - t1, - " selected" - ] - }, "selection-indicator", true, undefined, this); - $2[0] = ideSelection.lineCount; - $2[1] = t1; - $2[2] = t22; - } else { - t22 = $2[2]; - } - return t22; - } - if (ideSelection.filePath) { - let t1; - if ($2[3] !== ideSelection.filePath) { - t1 = basename53(ideSelection.filePath); - $2[3] = ideSelection.filePath; - $2[4] = t1; - } else { - t1 = $2[4]; - } - let t22; - if ($2[5] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime408.jsxDEV(ThemedText, { - color: "ide", - wrap: "truncate", - children: [ - "\u29C9 In ", - t1 - ] - }, "selection-indicator", true, undefined, this); - $2[5] = t1; - $2[6] = t22; - } else { - t22 = $2[6]; - } - return t22; - } -} -var import_compiler_runtime317, jsx_dev_runtime408; -var init_IdeStatusIndicator = __esm(() => { - init_useIdeConnectionStatus(); - init_ink2(); - import_compiler_runtime317 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime408 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useMemoryUsage.ts -function useMemoryUsage() { - const [memoryUsage, setMemoryUsage] = import_react231.useState(null); - useInterval(() => { - const heapUsed = process.memoryUsage().heapUsed; - const status2 = heapUsed >= CRITICAL_MEMORY_THRESHOLD ? "critical" : heapUsed >= HIGH_MEMORY_THRESHOLD ? "high" : "normal"; - setMemoryUsage((prev) => { - if (status2 === "normal") - return prev === null ? prev : null; - return { heapUsed, status: status2 }; - }); - }, 1e4); - return memoryUsage; -} -var import_react231, HIGH_MEMORY_THRESHOLD, CRITICAL_MEMORY_THRESHOLD; -var init_useMemoryUsage = __esm(() => { - init_dist4(); - import_react231 = __toESM(require_react(), 1); - HIGH_MEMORY_THRESHOLD = 1.5 * 1024 * 1024 * 1024; - CRITICAL_MEMORY_THRESHOLD = 2.5 * 1024 * 1024 * 1024; -}); - -// src/components/MemoryUsageIndicator.tsx -function MemoryUsageIndicator() { - if (true) { - return null; - } - const memoryUsage = useMemoryUsage(); - if (!memoryUsage) { - return null; - } - const { - heapUsed, - status: status2 - } = memoryUsage; - if (status2 === "normal") { - return null; - } - const formattedSize = formatFileSize(heapUsed); - const color3 = status2 === "critical" ? "error" : "warning"; - return /* @__PURE__ */ jsx_dev_runtime409.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime409.jsxDEV(ThemedText, { - color: color3, - wrap: "truncate", - children: [ - "High memory usage (", - formattedSize, - ") \xB7 /heapdump" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var jsx_dev_runtime409; -var init_MemoryUsageIndicator = __esm(() => { - init_useMemoryUsage(); - init_ink2(); - init_format(); - jsx_dev_runtime409 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/services/compact/compactWarningHook.ts -function useCompactWarningSuppression() { - return import_react232.useSyncExternalStore(compactWarningStore.subscribe, compactWarningStore.getState); -} -var import_react232; -var init_compactWarningHook = __esm(() => { - init_compactWarningState(); - import_react232 = __toESM(require_react(), 1); -}); - -// src/components/TokenWarning.tsx -function TokenWarning(t0) { - const $2 = import_compiler_runtime318.c(13); - const { - tokenUsage, - model - } = t0; - let t1; - if ($2[0] !== model || $2[1] !== tokenUsage) { - t1 = calculateTokenWarningState(tokenUsage, model); - $2[0] = model; - $2[1] = tokenUsage; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const { - percentLeft, - isAboveWarningThreshold, - isAboveErrorThreshold - } = t1; - const suppressWarning = useCompactWarningSuppression(); - if (!isAboveWarningThreshold || suppressWarning) { - return null; - } - let t22; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t22 = isAutoCompactEnabled(); - $2[3] = t22; - } else { - t22 = $2[3]; - } - const showAutoCompactWarning = t22; - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = getUpgradeMessage("warning"); - $2[4] = t32; - } else { - t32 = $2[4]; - } - const upgradeMessage = t32; - let displayPercentLeft = percentLeft; - let reactiveOnlyMode = false; - let collapseMode = false; - if (false) {} - if (false) {} - if (reactiveOnlyMode || collapseMode) { - const effectiveWindow = getEffectiveContextWindowSize(model); - let t42; - if ($2[5] !== effectiveWindow || $2[6] !== tokenUsage) { - t42 = Math.round((effectiveWindow - tokenUsage) / effectiveWindow * 100); - $2[5] = effectiveWindow; - $2[6] = tokenUsage; - $2[7] = t42; - } else { - t42 = $2[7]; - } - displayPercentLeft = Math.max(0, t42); - } - if (collapseMode && false) {} - const autocompactLabel = reactiveOnlyMode ? `${100 - displayPercentLeft}% context used` : `${displayPercentLeft}% until auto-compact`; - let t4; - if ($2[9] !== autocompactLabel || $2[10] !== isAboveErrorThreshold || $2[11] !== percentLeft) { - t4 = /* @__PURE__ */ jsx_dev_runtime410.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: showAutoCompactWarning ? /* @__PURE__ */ jsx_dev_runtime410.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: upgradeMessage ? `${autocompactLabel} \xB7 ${upgradeMessage}` : autocompactLabel - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime410.jsxDEV(ThemedText, { - color: isAboveErrorThreshold ? "error" : "warning", - wrap: "truncate", - children: upgradeMessage ? `Context low (${percentLeft}% remaining) \xB7 ${upgradeMessage}` : `Context low (${percentLeft}% remaining) \xB7 Run /compact to compact & continue` - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[9] = autocompactLabel; - $2[10] = isAboveErrorThreshold; - $2[11] = percentLeft; - $2[12] = t4; - } else { - t4 = $2[12]; - } - return t4; -} -var import_compiler_runtime318, import_react233, jsx_dev_runtime410; -var init_TokenWarning = __esm(() => { - init_ink2(); - init_growthbook(); - init_autoCompact(); - init_compactWarningHook(); - init_contextWindowUpgradeCheck(); - import_compiler_runtime318 = __toESM(require_compiler_runtime(), 1); - import_react233 = __toESM(require_react(), 1); - jsx_dev_runtime410 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/SandboxPromptFooterHint.tsx -function SandboxPromptFooterHint() { - const $2 = import_compiler_runtime319.c(6); - const [recentViolationCount, setRecentViolationCount] = import_react234.useState(0); - const timerRef = import_react234.useRef(null); - const detailsShortcut = useShortcutDisplay("app:toggleTranscript", "Global", "ctrl+o"); - let t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = () => { - if (!SandboxManager.isSandboxingEnabled()) { - return; - } - const store = SandboxManager.getSandboxViolationStore(); - let lastCount = store.getTotalCount(); - const unsubscribe2 = store.subscribe(() => { - const currentCount = store.getTotalCount(); - const newViolations = currentCount - lastCount; - if (newViolations > 0) { - setRecentViolationCount(newViolations); - lastCount = currentCount; - if (timerRef.current) { - clearTimeout(timerRef.current); - } - timerRef.current = setTimeout(setRecentViolationCount, 5000, 0); - } - }); - return () => { - unsubscribe2(); - if (timerRef.current) { - clearTimeout(timerRef.current); - } - }; - }; - t1 = []; - $2[0] = t0; - $2[1] = t1; - } else { - t0 = $2[0]; - t1 = $2[1]; - } - import_react234.useEffect(t0, t1); - if (!SandboxManager.isSandboxingEnabled() || recentViolationCount === 0) { - return null; - } - const t22 = recentViolationCount === 1 ? "operation" : "operations"; - let t32; - if ($2[2] !== detailsShortcut || $2[3] !== recentViolationCount || $2[4] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime411.jsxDEV(ThemedBox_default, { - paddingX: 0, - paddingY: 0, - children: /* @__PURE__ */ jsx_dev_runtime411.jsxDEV(ThemedText, { - color: "inactive", - wrap: "truncate", - children: [ - "\u29C8 Sandbox blocked ", - recentViolationCount, - " ", - t22, - " \xB7", - " ", - detailsShortcut, - " for details \xB7 /sandbox to disable" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[2] = detailsShortcut; - $2[3] = recentViolationCount; - $2[4] = t22; - $2[5] = t32; - } else { - t32 = $2[5]; - } - return t32; -} -var import_compiler_runtime319, import_react234, jsx_dev_runtime411; -var init_SandboxPromptFooterHint = __esm(() => { - init_ink2(); - init_useShortcutDisplay(); - init_sandbox_adapter(); - import_compiler_runtime319 = __toESM(require_compiler_runtime(), 1); - import_react234 = __toESM(require_react(), 1); - jsx_dev_runtime411 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/Notifications.tsx -function Notifications(t0) { - const $2 = import_compiler_runtime320.c(34); - const { - apiKeyStatus, - autoUpdaterResult, - debug: debug2, - isAutoUpdating, - verbose, - messages, - onAutoUpdaterResult, - onChangeIsUpdating, - ideSelection, - mcpClients, - isInputWrapped: t1, - isNarrow: t22 - } = t0; - const isInputWrapped = t1 === undefined ? false : t1; - const isNarrow = t22 === undefined ? false : t22; - let t32; - if ($2[0] !== messages) { - const messagesForTokenCount = getMessagesAfterCompactBoundary(messages); - t32 = tokenCountFromLastAPIResponse(messagesForTokenCount); - $2[0] = messages; - $2[1] = t32; - } else { - t32 = $2[1]; - } - const tokenUsage = t32; - const mainLoopModel = useMainLoopModel(); - let t4; - if ($2[2] !== mainLoopModel || $2[3] !== tokenUsage) { - t4 = calculateTokenWarningState(tokenUsage, mainLoopModel); - $2[2] = mainLoopModel; - $2[3] = tokenUsage; - $2[4] = t4; - } else { - t4 = $2[4]; - } - const isShowingCompactMessage = t4.isAboveWarningThreshold; - const { - status: ideStatus - } = useIdeConnectionStatus(mcpClients); - const notifications = useAppState(_temp191); - const { - addNotification, - removeNotification - } = useNotifications(); - const claudeAiLimits = useClaudeAiLimits(); - let t5; - let t6; - if ($2[5] !== addNotification) { - t5 = () => { - setEnvHookNotifier((text, isError3) => { - addNotification({ - key: "env-hook", - text, - color: isError3 ? "error" : undefined, - priority: isError3 ? "medium" : "low", - timeoutMs: isError3 ? 8000 : 5000 - }); - }); - return _temp278; - }; - t6 = [addNotification]; - $2[5] = addNotification; - $2[6] = t5; - $2[7] = t6; - } else { - t5 = $2[6]; - t6 = $2[7]; - } - import_react235.useEffect(t5, t6); - const shouldShowIdeSelection = ideStatus === "connected" && (ideSelection?.filePath || ideSelection?.text && ideSelection.lineCount > 0); - const shouldShowAutoUpdater = !shouldShowIdeSelection || isAutoUpdating || autoUpdaterResult?.status !== "success"; - const isInOverageMode = claudeAiLimits.isUsingOverage; - let t7; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t7 = getSubscriptionType(); - $2[8] = t7; - } else { - t7 = $2[8]; - } - const subscriptionType = t7; - const isTeamOrEnterprise = subscriptionType === "team" || subscriptionType === "enterprise"; - let t8; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t8 = getExternalEditor(); - $2[9] = t8; - } else { - t8 = $2[9]; - } - const editor = t8; - const shouldShowExternalEditorHint = isInputWrapped && !isShowingCompactMessage && apiKeyStatus !== "invalid" && apiKeyStatus !== "missing" && editor !== undefined; - let t10; - let t9; - if ($2[10] !== addNotification || $2[11] !== removeNotification || $2[12] !== shouldShowExternalEditorHint) { - t9 = () => { - if (shouldShowExternalEditorHint && editor) { - logEvent("tengu_external_editor_hint_shown", {}); - addNotification({ - key: "external-editor-hint", - jsx: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ConfigurableShortcutHint, { - action: "chat:externalEditor", - context: "Chat", - fallback: "ctrl+g", - description: `edit in ${toIDEDisplayName(editor)}` - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 5000 - }); - } else { - removeNotification("external-editor-hint"); - } - }; - t10 = [shouldShowExternalEditorHint, editor, addNotification, removeNotification]; - $2[10] = addNotification; - $2[11] = removeNotification; - $2[12] = shouldShowExternalEditorHint; - $2[13] = t10; - $2[14] = t9; - } else { - t10 = $2[13]; - t9 = $2[14]; - } - import_react235.useEffect(t9, t10); - const t11 = isNarrow ? "flex-start" : "flex-end"; - const t12 = isInOverageMode ?? false; - let t13; - if ($2[15] !== apiKeyStatus || $2[16] !== autoUpdaterResult || $2[17] !== debug2 || $2[18] !== ideSelection || $2[19] !== isAutoUpdating || $2[20] !== isShowingCompactMessage || $2[21] !== mainLoopModel || $2[22] !== mcpClients || $2[23] !== notifications || $2[24] !== onAutoUpdaterResult || $2[25] !== onChangeIsUpdating || $2[26] !== shouldShowAutoUpdater || $2[27] !== t12 || $2[28] !== tokenUsage || $2[29] !== verbose) { - t13 = /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(NotificationContent, { - ideSelection, - mcpClients, - notifications, - isInOverageMode: t12, - isTeamOrEnterprise, - apiKeyStatus, - debug: debug2, - verbose, - tokenUsage, - mainLoopModel, - shouldShowAutoUpdater, - autoUpdaterResult, - isAutoUpdating, - isShowingCompactMessage, - onAutoUpdaterResult, - onChangeIsUpdating - }, undefined, false, undefined, this); - $2[15] = apiKeyStatus; - $2[16] = autoUpdaterResult; - $2[17] = debug2; - $2[18] = ideSelection; - $2[19] = isAutoUpdating; - $2[20] = isShowingCompactMessage; - $2[21] = mainLoopModel; - $2[22] = mcpClients; - $2[23] = notifications; - $2[24] = onAutoUpdaterResult; - $2[25] = onChangeIsUpdating; - $2[26] = shouldShowAutoUpdater; - $2[27] = t12; - $2[28] = tokenUsage; - $2[29] = verbose; - $2[30] = t13; - } else { - t13 = $2[30]; - } - let t14; - if ($2[31] !== t11 || $2[32] !== t13) { - t14 = /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(SentryErrorBoundary, { - children: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedBox_default, { - flexDirection: "column", - alignItems: t11, - flexShrink: 0, - overflowX: "hidden", - children: t13 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[31] = t11; - $2[32] = t13; - $2[33] = t14; - } else { - t14 = $2[33]; - } - return t14; -} -function _temp278() { - return setEnvHookNotifier(null); -} -function _temp191(s4) { - return s4.notifications; -} -function NotificationContent({ - ideSelection, - mcpClients, - notifications, - isInOverageMode, - isTeamOrEnterprise, - apiKeyStatus, - debug: debug2, - verbose, - tokenUsage, - mainLoopModel, - shouldShowAutoUpdater, - autoUpdaterResult, - isAutoUpdating, - isShowingCompactMessage, - onAutoUpdaterResult, - onChangeIsUpdating -}) { - const [apiKeyHelperSlow, setApiKeyHelperSlow] = import_react235.useState(null); - import_react235.useEffect(() => { - if (!getConfiguredApiKeyHelper()) - return; - const interval = setInterval((setSlow) => { - const ms = getApiKeyHelperElapsedMs(); - const next2 = ms >= 1e4 ? formatDuration(ms) : null; - setSlow((prev) => next2 === prev ? prev : next2); - }, 1000, setApiKeyHelperSlow); - return () => clearInterval(interval); - }, []); - const voiceState = "idle"; - const voiceEnabled = false; - const voiceError = null; - const isBriefOnly = false; - if (false) {} - return /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(jsx_dev_runtime412.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(IdeStatusIndicator, { - ideSelection, - mcpClients - }, undefined, false, undefined, this), - notifications.current && ("jsx" in notifications.current ? /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - wrap: "truncate", - children: notifications.current.jsx - }, notifications.current.key, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - color: notifications.current.color, - dimColor: !notifications.current.color, - wrap: "truncate", - children: notifications.current.text - }, undefined, false, undefined, this)), - isInOverageMode && !isTeamOrEnterprise && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: "Now using extra usage" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - apiKeyHelperSlow && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - color: "warning", - wrap: "truncate", - children: [ - "apiKeyHelper is taking a while", - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: [ - "(", - apiKeyHelperSlow, - ")" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - (apiKeyStatus === "invalid" || apiKeyStatus === "missing") && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - color: "error", - wrap: "truncate", - children: isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) ? "Authentication error \xB7 Try again" : "Not logged in \xB7 Run /login" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - debug2 && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - color: "warning", - wrap: "truncate", - children: "Debug mode" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - apiKeyStatus !== "invalid" && apiKeyStatus !== "missing" && verbose && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: [ - tokenUsage, - " tokens" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - !isBriefOnly && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(TokenWarning, { - tokenUsage, - model: mainLoopModel - }, undefined, false, undefined, this), - shouldShowAutoUpdater && /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(AutoUpdaterWrapper, { - verbose, - onAutoUpdaterResult, - autoUpdaterResult, - isUpdating: isAutoUpdating, - onChangeIsUpdating, - showSuccessMessage: !isShowingCompactMessage - }, undefined, false, undefined, this), - null, - /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(MemoryUsageIndicator, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime412.jsxDEV(SandboxPromptFooterHint, {}, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_compiler_runtime320, import_react235, jsx_dev_runtime412, FOOTER_TEMPORARY_STATUS_TIMEOUT = 5000; -var init_Notifications = __esm(() => { - init_notifications(); - init_analytics(); - init_AppState(); - init_voice(); - init_useIdeConnectionStatus(); - init_useMainLoopModel(); - init_useVoiceEnabled(); - init_ink2(); - init_claudeAiLimitsHook(); - init_autoCompact(); - init_auth14(); - init_editor(); - init_envUtils(); - init_format(); - init_fileChangedWatcher(); - init_ide(); - init_messages9(); - init_tokens(); - init_AutoUpdaterWrapper(); - init_ConfigurableShortcutHint(); - init_IdeStatusIndicator(); - init_MemoryUsageIndicator(); - init_SentryErrorBoundary(); - init_TokenWarning(); - init_SandboxPromptFooterHint(); - import_compiler_runtime320 = __toESM(require_compiler_runtime(), 1); - import_react235 = __toESM(require_react(), 1); - jsx_dev_runtime412 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useArrowKeyHistory.tsx -async function loadHistoryEntries(minCount, modeFilter) { - const target = Math.ceil(minCount / HISTORY_CHUNK_SIZE) * HISTORY_CHUNK_SIZE; - if (pendingLoad && pendingLoadTarget >= target && pendingLoadModeFilter === modeFilter) { - return pendingLoad; - } - if (pendingLoad) { - await pendingLoad; - } - pendingLoadTarget = target; - pendingLoadModeFilter = modeFilter; - pendingLoad = (async () => { - const entries = []; - let loaded = 0; - for await (const entry of getHistory()) { - if (modeFilter) { - const entryMode = getModeFromInput(entry.display); - if (entryMode !== modeFilter) { - continue; - } - } - entries.push(entry); - loaded++; - if (loaded >= pendingLoadTarget) - break; - } - return entries; - })(); - try { - return await pendingLoad; - } finally { - pendingLoad = null; - pendingLoadTarget = 0; - pendingLoadModeFilter = undefined; - } -} -function useArrowKeyHistory(onSetInput, currentInput, pastedContents, setCursorOffset, currentMode) { - const [historyIndex, setHistoryIndex] = import_react236.useState(0); - const [lastShownHistoryEntry, setLastShownHistoryEntry] = import_react236.useState(undefined); - const hasShownSearchHintRef = import_react236.useRef(false); - const { - addNotification, - removeNotification - } = useNotifications(); - const historyCache = import_react236.useRef([]); - const historyCacheModeFilter = import_react236.useRef(undefined); - const historyIndexRef = import_react236.useRef(0); - const initialModeFilterRef = import_react236.useRef(undefined); - const currentInputRef = import_react236.useRef(currentInput); - const pastedContentsRef = import_react236.useRef(pastedContents); - const currentModeRef = import_react236.useRef(currentMode); - currentInputRef.current = currentInput; - pastedContentsRef.current = pastedContents; - currentModeRef.current = currentMode; - const setInputWithCursor = import_react236.useCallback((value, mode, contents, cursorToStart = false) => { - onSetInput(value, mode, contents); - setCursorOffset?.(cursorToStart ? 0 : value.length); - }, [onSetInput, setCursorOffset]); - const updateInput = import_react236.useCallback((input, cursorToStart_0 = false) => { - if (!input || !input.display) - return; - const mode_0 = getModeFromInput(input.display); - const value_0 = mode_0 === "bash" ? input.display.slice(1) : input.display; - setInputWithCursor(value_0, mode_0, input.pastedContents ?? {}, cursorToStart_0); - }, [setInputWithCursor]); - const showSearchHint = import_react236.useCallback(() => { - addNotification({ - key: "search-history-hint", - jsx: /* @__PURE__ */ jsx_dev_runtime413.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime413.jsxDEV(ConfigurableShortcutHint, { - action: "history:search", - context: "Global", - fallback: "ctrl+r", - description: "search history" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: FOOTER_TEMPORARY_STATUS_TIMEOUT - }); - }, [addNotification]); - const onHistoryUp = import_react236.useCallback(() => { - const targetIndex = historyIndexRef.current; - historyIndexRef.current++; - const inputAtPress = currentInputRef.current; - const pastedContentsAtPress = pastedContentsRef.current; - const modeAtPress = currentModeRef.current; - if (targetIndex === 0) { - initialModeFilterRef.current = modeAtPress === "bash" ? modeAtPress : undefined; - const hasInput = inputAtPress.trim() !== ""; - setLastShownHistoryEntry(hasInput ? { - display: inputAtPress, - pastedContents: pastedContentsAtPress, - mode: modeAtPress - } : undefined); - } - const modeFilter = initialModeFilterRef.current; - (async () => { - const neededCount = targetIndex + 1; - if (historyCacheModeFilter.current !== modeFilter) { - historyCache.current = []; - historyCacheModeFilter.current = modeFilter; - historyIndexRef.current = 0; - } - if (historyCache.current.length < neededCount) { - const entries = await loadHistoryEntries(neededCount, modeFilter); - if (entries.length > historyCache.current.length) { - historyCache.current = entries; - } - } - if (targetIndex >= historyCache.current.length) { - historyIndexRef.current--; - return; - } - const newIndex = targetIndex + 1; - setHistoryIndex(newIndex); - updateInput(historyCache.current[targetIndex], true); - if (newIndex >= 2 && !hasShownSearchHintRef.current) { - hasShownSearchHintRef.current = true; - showSearchHint(); - } - })(); - }, [updateInput, showSearchHint]); - const onHistoryDown = import_react236.useCallback(() => { - const currentIndex = historyIndexRef.current; - if (currentIndex > 1) { - historyIndexRef.current--; - setHistoryIndex(currentIndex - 1); - updateInput(historyCache.current[currentIndex - 2]); - } else if (currentIndex === 1) { - historyIndexRef.current = 0; - setHistoryIndex(0); - if (lastShownHistoryEntry) { - const savedMode = lastShownHistoryEntry.mode; - if (savedMode) { - setInputWithCursor(lastShownHistoryEntry.display, savedMode, lastShownHistoryEntry.pastedContents ?? {}); - } else { - updateInput(lastShownHistoryEntry); - } - } else { - setInputWithCursor("", initialModeFilterRef.current ?? "prompt", {}); - } - } - return currentIndex <= 0; - }, [lastShownHistoryEntry, updateInput, setInputWithCursor]); - const resetHistory = import_react236.useCallback(() => { - setLastShownHistoryEntry(undefined); - setHistoryIndex(0); - historyIndexRef.current = 0; - initialModeFilterRef.current = undefined; - removeNotification("search-history-hint"); - historyCache.current = []; - historyCacheModeFilter.current = undefined; - }, [removeNotification]); - const dismissSearchHint = import_react236.useCallback(() => { - removeNotification("search-history-hint"); - }, [removeNotification]); - return { - historyIndex, - setHistoryIndex, - onHistoryUp, - onHistoryDown, - resetHistory, - dismissSearchHint - }; -} -var import_react236, jsx_dev_runtime413, HISTORY_CHUNK_SIZE = 10, pendingLoad = null, pendingLoadTarget = 0, pendingLoadModeFilter = undefined; -var init_useArrowKeyHistory = __esm(() => { - init_notifications(); - init_ConfigurableShortcutHint(); - init_Notifications(); - init_history(); - init_ink2(); - import_react236 = __toESM(require_react(), 1); - jsx_dev_runtime413 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useHistorySearch.ts -function useHistorySearch(onAcceptHistory, currentInput, onInputChange, onCursorChange, currentCursorOffset, onModeChange, currentMode, isSearching, setIsSearching, setPastedContents, currentPastedContents) { - const [historyQuery, setHistoryQuery] = import_react237.useState(""); - const [historyFailedMatch, setHistoryFailedMatch] = import_react237.useState(false); - const [originalInput, setOriginalInput] = import_react237.useState(""); - const [originalCursorOffset, setOriginalCursorOffset] = import_react237.useState(0); - const [originalMode, setOriginalMode] = import_react237.useState("prompt"); - const [originalPastedContents, setOriginalPastedContents] = import_react237.useState({}); - const [historyMatch, setHistoryMatch] = import_react237.useState(undefined); - const historyReader = import_react237.useRef(undefined); - const seenPrompts = import_react237.useRef(new Set); - const searchAbortController = import_react237.useRef(null); - const closeHistoryReader = import_react237.useCallback(() => { - if (historyReader.current) { - historyReader.current.return(undefined); - historyReader.current = undefined; - } - }, []); - const reset3 = import_react237.useCallback(() => { - setIsSearching(false); - setHistoryQuery(""); - setHistoryFailedMatch(false); - setOriginalInput(""); - setOriginalCursorOffset(0); - setOriginalMode("prompt"); - setOriginalPastedContents({}); - setHistoryMatch(undefined); - closeHistoryReader(); - seenPrompts.current.clear(); - }, [setIsSearching, closeHistoryReader]); - const searchHistory = import_react237.useCallback(async (resume2, signal) => { - if (!isSearching) { - return; - } - if (historyQuery.length === 0) { - closeHistoryReader(); - seenPrompts.current.clear(); - setHistoryMatch(undefined); - setHistoryFailedMatch(false); - onInputChange(originalInput); - onCursorChange(originalCursorOffset); - onModeChange(originalMode); - setPastedContents(originalPastedContents); - return; - } - if (!resume2) { - closeHistoryReader(); - historyReader.current = makeHistoryReader(); - seenPrompts.current.clear(); - } - if (!historyReader.current) { - return; - } - while (true) { - if (signal?.aborted) { - return; - } - const item = await historyReader.current.next(); - if (item.done) { - setHistoryFailedMatch(true); - return; - } - const display = item.value.display; - const matchPosition = display.lastIndexOf(historyQuery); - if (matchPosition !== -1 && !seenPrompts.current.has(display)) { - seenPrompts.current.add(display); - setHistoryMatch(item.value); - setHistoryFailedMatch(false); - const mode = getModeFromInput(display); - onModeChange(mode); - onInputChange(display); - setPastedContents(item.value.pastedContents); - const value = getValueFromInput(display); - const cleanMatchPosition = value.lastIndexOf(historyQuery); - onCursorChange(cleanMatchPosition !== -1 ? cleanMatchPosition : matchPosition); - return; - } - } - }, [ - isSearching, - historyQuery, - closeHistoryReader, - onInputChange, - onCursorChange, - onModeChange, - setPastedContents, - originalInput, - originalCursorOffset, - originalMode, - originalPastedContents - ]); - const handleStartSearch = import_react237.useCallback(() => { - setIsSearching(true); - setOriginalInput(currentInput); - setOriginalCursorOffset(currentCursorOffset); - setOriginalMode(currentMode); - setOriginalPastedContents(currentPastedContents); - historyReader.current = makeHistoryReader(); - seenPrompts.current.clear(); - }, [ - setIsSearching, - currentInput, - currentCursorOffset, - currentMode, - currentPastedContents - ]); - const handleNextMatch = import_react237.useCallback(() => { - searchHistory(true); - }, [searchHistory]); - const handleAccept = import_react237.useCallback(() => { - if (historyMatch) { - const mode = getModeFromInput(historyMatch.display); - const value = getValueFromInput(historyMatch.display); - onInputChange(value); - onModeChange(mode); - setPastedContents(historyMatch.pastedContents); - } else { - setPastedContents(originalPastedContents); - } - reset3(); - }, [ - historyMatch, - onInputChange, - onModeChange, - setPastedContents, - originalPastedContents, - reset3 - ]); - const handleCancel = import_react237.useCallback(() => { - onInputChange(originalInput); - onCursorChange(originalCursorOffset); - setPastedContents(originalPastedContents); - reset3(); - }, [ - onInputChange, - onCursorChange, - setPastedContents, - originalInput, - originalCursorOffset, - originalPastedContents, - reset3 - ]); - const handleExecute = import_react237.useCallback(() => { - if (historyQuery.length === 0) { - onAcceptHistory({ - display: originalInput, - pastedContents: originalPastedContents - }); - } else if (historyMatch) { - const mode = getModeFromInput(historyMatch.display); - const value = getValueFromInput(historyMatch.display); - onModeChange(mode); - onAcceptHistory({ - display: value, - pastedContents: historyMatch.pastedContents - }); - } - reset3(); - }, [ - historyQuery, - historyMatch, - onAcceptHistory, - onModeChange, - originalInput, - originalPastedContents, - reset3 - ]); - useKeybinding("history:search", handleStartSearch, { - context: "Global", - isActive: !isSearching - }); - const historySearchHandlers = import_react237.useMemo(() => ({ - "historySearch:next": handleNextMatch, - "historySearch:accept": handleAccept, - "historySearch:cancel": handleCancel, - "historySearch:execute": handleExecute - }), [handleNextMatch, handleAccept, handleCancel, handleExecute]); - useKeybindings(historySearchHandlers, { - context: "HistorySearch", - isActive: isSearching - }); - const handleKeyDown = (e4) => { - if (!isSearching) - return; - if (e4.key === "backspace" && historyQuery === "") { - e4.preventDefault(); - handleCancel(); - } - }; - use_input_default((_input, _key, event) => { - handleKeyDown(new KeyboardEvent(event.keypress)); - }, { isActive: isSearching }); - const searchHistoryRef = import_react237.useRef(searchHistory); - searchHistoryRef.current = searchHistory; - import_react237.useEffect(() => { - searchAbortController.current?.abort(); - const controller = new AbortController; - searchAbortController.current = controller; - searchHistoryRef.current(false, controller.signal); - return () => { - controller.abort(); - }; - }, [historyQuery]); - return { - historyQuery, - setHistoryQuery, - historyMatch, - historyFailedMatch, - handleKeyDown - }; -} -var import_react237; -var init_useHistorySearch = __esm(() => { - init_history(); - init_keyboard_event(); - init_ink2(); - init_useKeybinding(); - import_react237 = __toESM(require_react(), 1); -}); - -// src/hooks/useInputBuffer.ts -function useInputBuffer({ - maxBufferSize, - debounceMs -}) { - const [buffer, setBuffer] = import_react238.useState([]); - const [currentIndex, setCurrentIndex] = import_react238.useState(-1); - const lastPushTime = import_react238.useRef(0); - const pendingPush = import_react238.useRef(null); - const pushToBuffer = import_react238.useCallback((text, cursorOffset, pastedContents = {}) => { - const now2 = Date.now(); - if (pendingPush.current) { - clearTimeout(pendingPush.current); - pendingPush.current = null; - } - if (now2 - lastPushTime.current < debounceMs) { - pendingPush.current = setTimeout(pushToBuffer, debounceMs, text, cursorOffset, pastedContents); - return; - } - lastPushTime.current = now2; - setBuffer((prevBuffer) => { - const newBuffer = currentIndex >= 0 ? prevBuffer.slice(0, currentIndex + 1) : prevBuffer; - const lastEntry = newBuffer[newBuffer.length - 1]; - if (lastEntry && lastEntry.text === text) { - return newBuffer; - } - const updatedBuffer = [ - ...newBuffer, - { text, cursorOffset, pastedContents, timestamp: now2 } - ]; - if (updatedBuffer.length > maxBufferSize) { - return updatedBuffer.slice(-maxBufferSize); - } - return updatedBuffer; - }); - setCurrentIndex((prev) => { - const newIndex = prev >= 0 ? prev + 1 : buffer.length; - return Math.min(newIndex, maxBufferSize - 1); - }); - }, [debounceMs, maxBufferSize, currentIndex, buffer.length]); - const undo = import_react238.useCallback(() => { - if (currentIndex < 0 || buffer.length === 0) { - return; - } - const targetIndex = Math.max(0, currentIndex - 1); - const entry = buffer[targetIndex]; - if (entry) { - setCurrentIndex(targetIndex); - return entry; - } - return; - }, [buffer, currentIndex]); - const clearBuffer = import_react238.useCallback(() => { - setBuffer([]); - setCurrentIndex(-1); - lastPushTime.current = 0; - if (pendingPush.current) { - clearTimeout(pendingPush.current); - pendingPush.current = null; - } - }, [lastPushTime, pendingPush]); - const canUndo = currentIndex > 0 && buffer.length > 1; - return { - pushToBuffer, - undo, - canUndo, - clearBuffer - }; -} -var import_react238; -var init_useInputBuffer = __esm(() => { - import_react238 = __toESM(require_react(), 1); -}); - -// src/hooks/usePromptSuggestion.ts -function usePromptSuggestion({ - inputValue, - isAssistantResponding -}) { - const promptSuggestion = useAppState((s4) => s4.promptSuggestion); - const setAppState = useSetAppState(); - const isTerminalFocused = useTerminalFocus(); - const { - text: suggestionText, - promptId, - shownAt, - acceptedAt, - generationRequestId - } = promptSuggestion; - const suggestion = isAssistantResponding || inputValue.length > 0 ? null : suggestionText; - const isValidSuggestion = suggestionText && shownAt > 0; - const firstKeystrokeAt = import_react239.useRef(0); - const wasFocusedWhenShown = import_react239.useRef(true); - const prevShownAt = import_react239.useRef(0); - if (shownAt > 0 && shownAt !== prevShownAt.current) { - prevShownAt.current = shownAt; - wasFocusedWhenShown.current = isTerminalFocused; - firstKeystrokeAt.current = 0; - } else if (shownAt === 0) { - prevShownAt.current = 0; - } - if (inputValue.length > 0 && firstKeystrokeAt.current === 0 && isValidSuggestion) { - firstKeystrokeAt.current = Date.now(); - } - const resetSuggestion = import_react239.useCallback(() => { - abortSpeculation(setAppState); - setAppState((prev) => ({ - ...prev, - promptSuggestion: { - text: null, - promptId: null, - shownAt: 0, - acceptedAt: 0, - generationRequestId: null - } - })); - }, [setAppState]); - const markAccepted = import_react239.useCallback(() => { - if (!isValidSuggestion) - return; - setAppState((prev) => ({ - ...prev, - promptSuggestion: { - ...prev.promptSuggestion, - acceptedAt: Date.now() - } - })); - }, [isValidSuggestion, setAppState]); - const markShown = import_react239.useCallback(() => { - setAppState((prev) => { - if (prev.promptSuggestion.shownAt !== 0 || !prev.promptSuggestion.text) { - return prev; - } - return { - ...prev, - promptSuggestion: { - ...prev.promptSuggestion, - shownAt: Date.now() - } - }; - }); - }, [setAppState]); - const logOutcomeAtSubmission = import_react239.useCallback((finalInput, opts) => { - if (!isValidSuggestion) - return; - const tabWasPressed = acceptedAt > shownAt; - const wasAccepted = tabWasPressed || finalInput === suggestionText; - const timeMs = wasAccepted ? acceptedAt || Date.now() : Date.now(); - logEvent("tengu_prompt_suggestion", { - source: "cli", - outcome: wasAccepted ? "accepted" : "ignored", - prompt_id: promptId, - ...generationRequestId && { - generationRequestId - }, - ...wasAccepted && { - acceptMethod: tabWasPressed ? "tab" : "enter" - }, - ...wasAccepted && { - timeToAcceptMs: timeMs - shownAt - }, - ...!wasAccepted && { - timeToIgnoreMs: timeMs - shownAt - }, - ...firstKeystrokeAt.current > 0 && { - timeToFirstKeystrokeMs: firstKeystrokeAt.current - shownAt - }, - wasFocusedWhenShown: wasFocusedWhenShown.current, - similarity: Math.round(finalInput.length / (suggestionText?.length || 1) * 100) / 100, - ...process.env.USER_TYPE === "ant" && { - suggestion: suggestionText, - userInput: finalInput - } - }); - if (!opts?.skipReset) - resetSuggestion(); - }, [ - isValidSuggestion, - acceptedAt, - shownAt, - suggestionText, - promptId, - generationRequestId, - resetSuggestion - ]); - return { - suggestion, - markAccepted, - markShown, - logOutcomeAtSubmission - }; -} -var import_react239; -var init_usePromptSuggestion = __esm(() => { - init_use_terminal_focus(); - init_analytics(); - init_speculation(); - init_AppState(); - import_react239 = __toESM(require_react(), 1); -}); - -// src/utils/bash/shellCompletion.ts -function isCommandOperator(token) { - return typeof token === "object" && token !== null && "op" in token && COMMAND_OPERATORS.includes(token.op); -} -function getCompletionTypeFromPrefix(prefix) { - if (prefix.startsWith("$")) { - return "variable"; - } - if (prefix.includes("/") || prefix.startsWith("~") || prefix.startsWith(".")) { - return "file"; - } - return "command"; -} -function findLastStringToken(tokens) { - const i6 = tokens.findLastIndex((t4) => typeof t4 === "string"); - return i6 !== -1 ? { token: tokens[i6], index: i6 } : null; -} -function isNewCommandContext(tokens, currentTokenIndex) { - if (currentTokenIndex === 0) { - return true; - } - const prevToken = tokens[currentTokenIndex - 1]; - return prevToken !== undefined && isCommandOperator(prevToken); -} -function parseInputContext(input, cursorOffset) { - const beforeCursor = input.slice(0, cursorOffset); - const varMatch = beforeCursor.match(/\$[a-zA-Z_][a-zA-Z0-9_]*$/); - if (varMatch) { - return { prefix: varMatch[0], completionType: "variable" }; - } - const parseResult = tryParseShellCommand(beforeCursor); - if (!parseResult.success) { - const tokens = beforeCursor.split(/\s+/); - const prefix = tokens[tokens.length - 1] || ""; - const isFirstToken = tokens.length === 1 && !beforeCursor.includes(" "); - const completionType2 = isFirstToken ? "command" : getCompletionTypeFromPrefix(prefix); - return { prefix, completionType: completionType2 }; - } - const lastToken = findLastStringToken(parseResult.tokens); - if (!lastToken) { - const lastParsedToken = parseResult.tokens[parseResult.tokens.length - 1]; - const completionType2 = lastParsedToken && isCommandOperator(lastParsedToken) ? "command" : "command"; - return { prefix: "", completionType: completionType2 }; - } - if (beforeCursor.endsWith(" ")) { - return { prefix: "", completionType: "file" }; - } - const baseType = getCompletionTypeFromPrefix(lastToken.token); - if (baseType === "variable" || baseType === "file") { - return { prefix: lastToken.token, completionType: baseType }; - } - const completionType = isNewCommandContext(parseResult.tokens, lastToken.index) ? "command" : "file"; - return { prefix: lastToken.token, completionType }; -} -function getBashCompletionCommand(prefix, completionType) { - if (completionType === "variable") { - const varName = prefix.slice(1); - return `compgen -v ${quote([varName])} 2>/dev/null`; - } else if (completionType === "file") { - return `compgen -f ${quote([prefix])} 2>/dev/null | head -${MAX_SHELL_COMPLETIONS} | while IFS= read -r f; do [ -d "$f" ] && echo "$f/" || echo "$f "; done`; - } else { - return `compgen -c ${quote([prefix])} 2>/dev/null`; - } -} -function getZshCompletionCommand(prefix, completionType) { - if (completionType === "variable") { - const varName = prefix.slice(1); - return `print -rl -- \${(k)parameters[(I)${quote([varName])}*]} 2>/dev/null`; - } else if (completionType === "file") { - return `for f in ${quote([prefix])}*(N[1,${MAX_SHELL_COMPLETIONS}]); do [[ -d "$f" ]] && echo "$f/" || echo "$f "; done`; - } else { - return `print -rl -- \${(k)commands[(I)${quote([prefix])}*]} 2>/dev/null`; - } -} -async function getCompletionsForShell(shellType, prefix, completionType, abortSignal) { - let command19; - if (shellType === "bash") { - command19 = getBashCompletionCommand(prefix, completionType); - } else if (shellType === "zsh") { - command19 = getZshCompletionCommand(prefix, completionType); - } else { - return []; - } - const shellCommand = await exec4(command19, abortSignal, "bash", { - timeout: SHELL_COMPLETION_TIMEOUT_MS - }); - const result = await shellCommand.result; - return result.stdout.split(` -`).filter((line) => line.trim()).slice(0, MAX_SHELL_COMPLETIONS).map((text) => ({ - id: text, - displayText: text, - description: undefined, - metadata: { completionType } - })); -} -async function getShellCompletions(input, cursorOffset, abortSignal) { - const shellType = getShellType(); - if (shellType !== "bash" && shellType !== "zsh") { - return []; - } - try { - const { prefix, completionType } = parseInputContext(input, cursorOffset); - if (!prefix) { - return []; - } - const completions = await getCompletionsForShell(shellType, prefix, completionType, abortSignal); - return completions.map((suggestion) => ({ - ...suggestion, - metadata: { - ...suggestion.metadata, - inputSnapshot: input - } - })); - } catch (error46) { - logForDebugging(`Shell completion failed: ${error46}`); - return []; - } -} -var MAX_SHELL_COMPLETIONS = 15, SHELL_COMPLETION_TIMEOUT_MS = 1000, COMMAND_OPERATORS; -var init_shellCompletion = __esm(() => { - init_shellQuote(); - init_debug(); - init_localInstaller(); - init_Shell(); - COMMAND_OPERATORS = ["|", "||", "&&", ";"]; -}); - -// node_modules/fuse.js/dist/fuse.mjs -function isArray9(value) { - return !Array.isArray ? getTag2(value) === "[object Array]" : Array.isArray(value); -} -function baseToString2(value) { - if (typeof value == "string") { - return value; - } - let result = value + ""; - return result == "0" && 1 / value == -INFINITY4 ? "-0" : result; -} -function toString7(value) { - return value == null ? "" : baseToString2(value); -} -function isString2(value) { - return typeof value === "string"; -} -function isNumber2(value) { - return typeof value === "number"; -} -function isBoolean2(value) { - return value === true || value === false || isObjectLike2(value) && getTag2(value) == "[object Boolean]"; -} -function isObject6(value) { - return typeof value === "object"; -} -function isObjectLike2(value) { - return isObject6(value) && value !== null; -} -function isDefined2(value) { - return value !== undefined && value !== null; -} -function isBlank2(value) { - return !value.trim().length; -} -function getTag2(value) { - return value == null ? value === undefined ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value); -} - -class KeyStore { - constructor(keys2) { - this._keys = []; - this._keyMap = {}; - let totalWeight = 0; - keys2.forEach((key2) => { - let obj = createKey(key2); - this._keys.push(obj); - this._keyMap[obj.id] = obj; - totalWeight += obj.weight; - }); - this._keys.forEach((key2) => { - key2.weight /= totalWeight; - }); - } - get(keyId) { - return this._keyMap[keyId]; - } - keys() { - return this._keys; - } - toJSON() { - return JSON.stringify(this._keys); - } -} -function createKey(key2) { - let path26 = null; - let id = null; - let src = null; - let weight = 1; - let getFn = null; - if (isString2(key2) || isArray9(key2)) { - src = key2; - path26 = createKeyPath(key2); - id = createKeyId(key2); - } else { - if (!hasOwn7.call(key2, "name")) { - throw new Error(MISSING_KEY_PROPERTY("name")); - } - const name3 = key2.name; - src = name3; - if (hasOwn7.call(key2, "weight")) { - weight = key2.weight; - if (weight <= 0) { - throw new Error(INVALID_KEY_WEIGHT_VALUE(name3)); - } - } - path26 = createKeyPath(name3); - id = createKeyId(name3); - getFn = key2.getFn; - } - return { path: path26, id, weight, src, getFn }; -} -function createKeyPath(key2) { - return isArray9(key2) ? key2 : key2.split("."); -} -function createKeyId(key2) { - return isArray9(key2) ? key2.join(".") : key2; -} -function get2(obj, path26) { - let list2 = []; - let arr = false; - const deepGet = (obj2, path27, index2) => { - if (!isDefined2(obj2)) { - return; - } - if (!path27[index2]) { - list2.push(obj2); - } else { - let key2 = path27[index2]; - const value = obj2[key2]; - if (!isDefined2(value)) { - return; - } - if (index2 === path27.length - 1 && (isString2(value) || isNumber2(value) || isBoolean2(value))) { - list2.push(toString7(value)); - } else if (isArray9(value)) { - arr = true; - for (let i6 = 0, len = value.length;i6 < len; i6 += 1) { - deepGet(value[i6], path27, index2 + 1); - } - } else if (path27.length) { - deepGet(value, path27, index2 + 1); - } - } - }; - deepGet(obj, isString2(path26) ? path26.split(".") : path26, 0); - return arr ? list2 : list2[0]; -} -function norm(weight = 1, mantissa = 3) { - const cache8 = new Map; - const m4 = Math.pow(10, mantissa); - return { - get(value) { - const numTokens = value.match(SPACE).length; - if (cache8.has(numTokens)) { - return cache8.get(numTokens); - } - const norm2 = 1 / Math.pow(numTokens, 0.5 * weight); - const n6 = parseFloat(Math.round(norm2 * m4) / m4); - cache8.set(numTokens, n6); - return n6; - }, - clear() { - cache8.clear(); - } - }; -} - -class FuseIndex { - constructor({ - getFn = Config2.getFn, - fieldNormWeight = Config2.fieldNormWeight - } = {}) { - this.norm = norm(fieldNormWeight, 3); - this.getFn = getFn; - this.isCreated = false; - this.setIndexRecords(); - } - setSources(docs = []) { - this.docs = docs; - } - setIndexRecords(records = []) { - this.records = records; - } - setKeys(keys2 = []) { - this.keys = keys2; - this._keysMap = {}; - keys2.forEach((key2, idx) => { - this._keysMap[key2.id] = idx; - }); - } - create() { - if (this.isCreated || !this.docs.length) { - return; - } - this.isCreated = true; - if (isString2(this.docs[0])) { - this.docs.forEach((doc2, docIndex) => { - this._addString(doc2, docIndex); - }); - } else { - this.docs.forEach((doc2, docIndex) => { - this._addObject(doc2, docIndex); - }); - } - this.norm.clear(); - } - add(doc2) { - const idx = this.size(); - if (isString2(doc2)) { - this._addString(doc2, idx); - } else { - this._addObject(doc2, idx); - } - } - removeAt(idx) { - this.records.splice(idx, 1); - for (let i6 = idx, len = this.size();i6 < len; i6 += 1) { - this.records[i6].i -= 1; - } - } - getValueForItemAtKeyId(item, keyId) { - return item[this._keysMap[keyId]]; - } - size() { - return this.records.length; - } - _addString(doc2, docIndex) { - if (!isDefined2(doc2) || isBlank2(doc2)) { - return; - } - let record3 = { - v: doc2, - i: docIndex, - n: this.norm.get(doc2) - }; - this.records.push(record3); - } - _addObject(doc2, docIndex) { - let record3 = { i: docIndex, $: {} }; - this.keys.forEach((key2, keyIndex) => { - let value = key2.getFn ? key2.getFn(doc2) : this.getFn(doc2, key2.path); - if (!isDefined2(value)) { - return; - } - if (isArray9(value)) { - let subRecords = []; - const stack = [{ nestedArrIndex: -1, value }]; - while (stack.length) { - const { nestedArrIndex, value: value2 } = stack.pop(); - if (!isDefined2(value2)) { - continue; - } - if (isString2(value2) && !isBlank2(value2)) { - let subRecord = { - v: value2, - i: nestedArrIndex, - n: this.norm.get(value2) - }; - subRecords.push(subRecord); - } else if (isArray9(value2)) { - value2.forEach((item, k4) => { - stack.push({ - nestedArrIndex: k4, - value: item - }); - }); - } else - ; - } - record3.$[keyIndex] = subRecords; - } else if (isString2(value) && !isBlank2(value)) { - let subRecord = { - v: value, - n: this.norm.get(value) - }; - record3.$[keyIndex] = subRecord; - } - }); - this.records.push(record3); - } - toJSON() { - return { - keys: this.keys, - records: this.records - }; - } -} -function createIndex(keys2, docs, { getFn = Config2.getFn, fieldNormWeight = Config2.fieldNormWeight } = {}) { - const myIndex = new FuseIndex({ getFn, fieldNormWeight }); - myIndex.setKeys(keys2.map(createKey)); - myIndex.setSources(docs); - myIndex.create(); - return myIndex; -} -function parseIndex(data, { getFn = Config2.getFn, fieldNormWeight = Config2.fieldNormWeight } = {}) { - const { keys: keys2, records } = data; - const myIndex = new FuseIndex({ getFn, fieldNormWeight }); - myIndex.setKeys(keys2); - myIndex.setIndexRecords(records); - return myIndex; -} -function computeScore$1(pattern, { - errors: errors8 = 0, - currentLocation = 0, - expectedLocation = 0, - distance = Config2.distance, - ignoreLocation = Config2.ignoreLocation -} = {}) { - const accuracy = errors8 / pattern.length; - if (ignoreLocation) { - return accuracy; - } - const proximity = Math.abs(expectedLocation - currentLocation); - if (!distance) { - return proximity ? 1 : accuracy; - } - return accuracy + proximity / distance; -} -function convertMaskToIndices(matchmask = [], minMatchCharLength = Config2.minMatchCharLength) { - let indices = []; - let start = -1; - let end = -1; - let i6 = 0; - for (let len = matchmask.length;i6 < len; i6 += 1) { - let match = matchmask[i6]; - if (match && start === -1) { - start = i6; - } else if (!match && start !== -1) { - end = i6 - 1; - if (end - start + 1 >= minMatchCharLength) { - indices.push([start, end]); - } - start = -1; - } - } - if (matchmask[i6 - 1] && i6 - start >= minMatchCharLength) { - indices.push([start, i6 - 1]); - } - return indices; -} -function search(text, pattern, patternAlphabet, { - location = Config2.location, - distance = Config2.distance, - threshold = Config2.threshold, - findAllMatches = Config2.findAllMatches, - minMatchCharLength = Config2.minMatchCharLength, - includeMatches = Config2.includeMatches, - ignoreLocation = Config2.ignoreLocation -} = {}) { - if (pattern.length > MAX_BITS) { - throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS)); - } - const patternLen = pattern.length; - const textLen = text.length; - const expectedLocation = Math.max(0, Math.min(location, textLen)); - let currentThreshold = threshold; - let bestLocation = expectedLocation; - const computeMatches = minMatchCharLength > 1 || includeMatches; - const matchMask = computeMatches ? Array(textLen) : []; - let index2; - while ((index2 = text.indexOf(pattern, bestLocation)) > -1) { - let score = computeScore$1(pattern, { - currentLocation: index2, - expectedLocation, - distance, - ignoreLocation - }); - currentThreshold = Math.min(score, currentThreshold); - bestLocation = index2 + patternLen; - if (computeMatches) { - let i6 = 0; - while (i6 < patternLen) { - matchMask[index2 + i6] = 1; - i6 += 1; - } - } - } - bestLocation = -1; - let lastBitArr = []; - let finalScore = 1; - let binMax = patternLen + textLen; - const mask = 1 << patternLen - 1; - for (let i6 = 0;i6 < patternLen; i6 += 1) { - let binMin = 0; - let binMid = binMax; - while (binMin < binMid) { - const score2 = computeScore$1(pattern, { - errors: i6, - currentLocation: expectedLocation + binMid, - expectedLocation, - distance, - ignoreLocation - }); - if (score2 <= currentThreshold) { - binMin = binMid; - } else { - binMax = binMid; - } - binMid = Math.floor((binMax - binMin) / 2 + binMin); - } - binMax = binMid; - let start = Math.max(1, expectedLocation - binMid + 1); - let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen; - let bitArr = Array(finish + 2); - bitArr[finish + 1] = (1 << i6) - 1; - for (let j4 = finish;j4 >= start; j4 -= 1) { - let currentLocation = j4 - 1; - let charMatch = patternAlphabet[text.charAt(currentLocation)]; - if (computeMatches) { - matchMask[currentLocation] = +!!charMatch; - } - bitArr[j4] = (bitArr[j4 + 1] << 1 | 1) & charMatch; - if (i6) { - bitArr[j4] |= (lastBitArr[j4 + 1] | lastBitArr[j4]) << 1 | 1 | lastBitArr[j4 + 1]; - } - if (bitArr[j4] & mask) { - finalScore = computeScore$1(pattern, { - errors: i6, - currentLocation, - expectedLocation, - distance, - ignoreLocation - }); - if (finalScore <= currentThreshold) { - currentThreshold = finalScore; - bestLocation = currentLocation; - if (bestLocation <= expectedLocation) { - break; - } - start = Math.max(1, 2 * expectedLocation - bestLocation); - } - } - } - const score = computeScore$1(pattern, { - errors: i6 + 1, - currentLocation: expectedLocation, - expectedLocation, - distance, - ignoreLocation - }); - if (score > currentThreshold) { - break; - } - lastBitArr = bitArr; - } - const result = { - isMatch: bestLocation >= 0, - score: Math.max(0.001, finalScore) - }; - if (computeMatches) { - const indices = convertMaskToIndices(matchMask, minMatchCharLength); - if (!indices.length) { - result.isMatch = false; - } else if (includeMatches) { - result.indices = indices; - } - } - return result; -} -function createPatternAlphabet(pattern) { - let mask = {}; - for (let i6 = 0, len = pattern.length;i6 < len; i6 += 1) { - const char = pattern.charAt(i6); - mask[char] = (mask[char] || 0) | 1 << len - i6 - 1; - } - return mask; -} - -class BitapSearch { - constructor(pattern, { - location = Config2.location, - threshold = Config2.threshold, - distance = Config2.distance, - includeMatches = Config2.includeMatches, - findAllMatches = Config2.findAllMatches, - minMatchCharLength = Config2.minMatchCharLength, - isCaseSensitive = Config2.isCaseSensitive, - ignoreDiacritics = Config2.ignoreDiacritics, - ignoreLocation = Config2.ignoreLocation - } = {}) { - this.options = { - location, - threshold, - distance, - includeMatches, - findAllMatches, - minMatchCharLength, - isCaseSensitive, - ignoreDiacritics, - ignoreLocation - }; - pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); - pattern = ignoreDiacritics ? stripDiacritics(pattern) : pattern; - this.pattern = pattern; - this.chunks = []; - if (!this.pattern.length) { - return; - } - const addChunk = (pattern2, startIndex) => { - this.chunks.push({ - pattern: pattern2, - alphabet: createPatternAlphabet(pattern2), - startIndex - }); - }; - const len = this.pattern.length; - if (len > MAX_BITS) { - let i6 = 0; - const remainder = len % MAX_BITS; - const end = len - remainder; - while (i6 < end) { - addChunk(this.pattern.substr(i6, MAX_BITS), i6); - i6 += MAX_BITS; - } - if (remainder) { - const startIndex = len - MAX_BITS; - addChunk(this.pattern.substr(startIndex), startIndex); - } - } else { - addChunk(this.pattern, 0); - } - } - searchIn(text) { - const { isCaseSensitive, ignoreDiacritics, includeMatches } = this.options; - text = isCaseSensitive ? text : text.toLowerCase(); - text = ignoreDiacritics ? stripDiacritics(text) : text; - if (this.pattern === text) { - let result2 = { - isMatch: true, - score: 0 - }; - if (includeMatches) { - result2.indices = [[0, text.length - 1]]; - } - return result2; - } - const { - location, - distance, - threshold, - findAllMatches, - minMatchCharLength, - ignoreLocation - } = this.options; - let allIndices = []; - let totalScore = 0; - let hasMatches = false; - this.chunks.forEach(({ pattern, alphabet, startIndex }) => { - const { isMatch, score, indices } = search(text, pattern, alphabet, { - location: location + startIndex, - distance, - threshold, - findAllMatches, - minMatchCharLength, - includeMatches, - ignoreLocation - }); - if (isMatch) { - hasMatches = true; - } - totalScore += score; - if (isMatch && indices) { - allIndices = [...allIndices, ...indices]; - } - }); - let result = { - isMatch: hasMatches, - score: hasMatches ? totalScore / this.chunks.length : 1 - }; - if (hasMatches && includeMatches) { - result.indices = allIndices; - } - return result; - } -} - -class BaseMatch { - constructor(pattern) { - this.pattern = pattern; - } - static isMultiMatch(pattern) { - return getMatch(pattern, this.multiRegex); - } - static isSingleMatch(pattern) { - return getMatch(pattern, this.singleRegex); - } - search() {} -} -function getMatch(pattern, exp) { - const matches = pattern.match(exp); - return matches ? matches[1] : null; -} -function parseQuery(pattern, options2 = {}) { - return pattern.split(OR_TOKEN).map((item) => { - let query2 = item.trim().split(SPACE_RE).filter((item2) => item2 && !!item2.trim()); - let results = []; - for (let i6 = 0, len = query2.length;i6 < len; i6 += 1) { - const queryItem = query2[i6]; - let found = false; - let idx = -1; - while (!found && ++idx < searchersLen) { - const searcher = searchers[idx]; - let token = searcher.isMultiMatch(queryItem); - if (token) { - results.push(new searcher(token, options2)); - found = true; - } - } - if (found) { - continue; - } - idx = -1; - while (++idx < searchersLen) { - const searcher = searchers[idx]; - let token = searcher.isSingleMatch(queryItem); - if (token) { - results.push(new searcher(token, options2)); - break; - } - } - } - return results; - }); -} - -class ExtendedSearch { - constructor(pattern, { - isCaseSensitive = Config2.isCaseSensitive, - ignoreDiacritics = Config2.ignoreDiacritics, - includeMatches = Config2.includeMatches, - minMatchCharLength = Config2.minMatchCharLength, - ignoreLocation = Config2.ignoreLocation, - findAllMatches = Config2.findAllMatches, - location = Config2.location, - threshold = Config2.threshold, - distance = Config2.distance - } = {}) { - this.query = null; - this.options = { - isCaseSensitive, - ignoreDiacritics, - includeMatches, - minMatchCharLength, - findAllMatches, - ignoreLocation, - location, - threshold, - distance - }; - pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); - pattern = ignoreDiacritics ? stripDiacritics(pattern) : pattern; - this.pattern = pattern; - this.query = parseQuery(this.pattern, this.options); - } - static condition(_, options2) { - return options2.useExtendedSearch; - } - searchIn(text) { - const query2 = this.query; - if (!query2) { - return { - isMatch: false, - score: 1 - }; - } - const { includeMatches, isCaseSensitive, ignoreDiacritics } = this.options; - text = isCaseSensitive ? text : text.toLowerCase(); - text = ignoreDiacritics ? stripDiacritics(text) : text; - let numMatches = 0; - let allIndices = []; - let totalScore = 0; - for (let i6 = 0, qLen = query2.length;i6 < qLen; i6 += 1) { - const searchers2 = query2[i6]; - allIndices.length = 0; - numMatches = 0; - for (let j4 = 0, pLen = searchers2.length;j4 < pLen; j4 += 1) { - const searcher = searchers2[j4]; - const { isMatch, indices, score } = searcher.search(text); - if (isMatch) { - numMatches += 1; - totalScore += score; - if (includeMatches) { - const type = searcher.constructor.type; - if (MultiMatchSet.has(type)) { - allIndices = [...allIndices, ...indices]; - } else { - allIndices.push(indices); - } - } - } else { - totalScore = 0; - numMatches = 0; - allIndices.length = 0; - break; - } - } - if (numMatches) { - let result = { - isMatch: true, - score: totalScore / numMatches - }; - if (includeMatches) { - result.indices = allIndices; - } - return result; - } - } - return { - isMatch: false, - score: 1 - }; - } -} -function register(...args) { - registeredSearchers.push(...args); -} -function createSearcher(pattern, options2) { - for (let i6 = 0, len = registeredSearchers.length;i6 < len; i6 += 1) { - let searcherClass = registeredSearchers[i6]; - if (searcherClass.condition(pattern, options2)) { - return new searcherClass(pattern, options2); - } - } - return new BitapSearch(pattern, options2); -} -function parse16(query2, options2, { auto: auto2 = true } = {}) { - const next2 = (query3) => { - let keys2 = Object.keys(query3); - const isQueryPath = isPath(query3); - if (!isQueryPath && keys2.length > 1 && !isExpression(query3)) { - return next2(convertToExplicit(query3)); - } - if (isLeaf(query3)) { - const key2 = isQueryPath ? query3[KeyType.PATH] : keys2[0]; - const pattern = isQueryPath ? query3[KeyType.PATTERN] : query3[key2]; - if (!isString2(pattern)) { - throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key2)); - } - const obj = { - keyId: createKeyId(key2), - pattern - }; - if (auto2) { - obj.searcher = createSearcher(pattern, options2); - } - return obj; - } - let node = { - children: [], - operator: keys2[0] - }; - keys2.forEach((key2) => { - const value = query3[key2]; - if (isArray9(value)) { - value.forEach((item) => { - node.children.push(next2(item)); - }); - } - }); - return node; - }; - if (!isExpression(query2)) { - query2 = convertToExplicit(query2); - } - return next2(query2); -} -function computeScore(results, { ignoreFieldNorm = Config2.ignoreFieldNorm }) { - results.forEach((result) => { - let totalScore = 1; - result.matches.forEach(({ key: key2, norm: norm2, score }) => { - const weight = key2 ? key2.weight : null; - totalScore *= Math.pow(score === 0 && weight ? Number.EPSILON : score, (weight || 1) * (ignoreFieldNorm ? 1 : norm2)); - }); - result.score = totalScore; - }); -} -function transformMatches(result, data) { - const matches = result.matches; - data.matches = []; - if (!isDefined2(matches)) { - return; - } - matches.forEach((match) => { - if (!isDefined2(match.indices) || !match.indices.length) { - return; - } - const { indices, value } = match; - let obj = { - indices, - value - }; - if (match.key) { - obj.key = match.key.src; - } - if (match.idx > -1) { - obj.refIndex = match.idx; - } - data.matches.push(obj); - }); -} -function transformScore(result, data) { - data.score = result.score; -} -function format5(results, docs, { - includeMatches = Config2.includeMatches, - includeScore = Config2.includeScore -} = {}) { - const transformers = []; - if (includeMatches) - transformers.push(transformMatches); - if (includeScore) - transformers.push(transformScore); - return results.map((result) => { - const { idx } = result; - const data = { - item: docs[idx], - refIndex: idx - }; - if (transformers.length) { - transformers.forEach((transformer) => { - transformer(result, data); - }); - } - return data; - }); -} - -class Fuse { - constructor(docs, options2 = {}, index2) { - this.options = { ...Config2, ...options2 }; - if (this.options.useExtendedSearch && false) {} - this._keyStore = new KeyStore(this.options.keys); - this.setCollection(docs, index2); - } - setCollection(docs, index2) { - this._docs = docs; - if (index2 && !(index2 instanceof FuseIndex)) { - throw new Error(INCORRECT_INDEX_TYPE); - } - this._myIndex = index2 || createIndex(this.options.keys, this._docs, { - getFn: this.options.getFn, - fieldNormWeight: this.options.fieldNormWeight - }); - } - add(doc2) { - if (!isDefined2(doc2)) { - return; - } - this._docs.push(doc2); - this._myIndex.add(doc2); - } - remove(predicate = () => false) { - const results = []; - for (let i6 = 0, len = this._docs.length;i6 < len; i6 += 1) { - const doc2 = this._docs[i6]; - if (predicate(doc2, i6)) { - this.removeAt(i6); - i6 -= 1; - len -= 1; - results.push(doc2); - } - } - return results; - } - removeAt(idx) { - this._docs.splice(idx, 1); - this._myIndex.removeAt(idx); - } - getIndex() { - return this._myIndex; - } - search(query2, { limit = -1 } = {}) { - const { - includeMatches, - includeScore, - shouldSort, - sortFn, - ignoreFieldNorm - } = this.options; - let results = isString2(query2) ? isString2(this._docs[0]) ? this._searchStringList(query2) : this._searchObjectList(query2) : this._searchLogical(query2); - computeScore(results, { ignoreFieldNorm }); - if (shouldSort) { - results.sort(sortFn); - } - if (isNumber2(limit) && limit > -1) { - results = results.slice(0, limit); - } - return format5(results, this._docs, { - includeMatches, - includeScore - }); - } - _searchStringList(query2) { - const searcher = createSearcher(query2, this.options); - const { records } = this._myIndex; - const results = []; - records.forEach(({ v: text, i: idx, n: norm2 }) => { - if (!isDefined2(text)) { - return; - } - const { isMatch, score, indices } = searcher.searchIn(text); - if (isMatch) { - results.push({ - item: text, - idx, - matches: [{ score, value: text, norm: norm2, indices }] - }); - } - }); - return results; - } - _searchLogical(query2) { - const expression = parse16(query2, this.options); - const evaluate = (node, item, idx) => { - if (!node.children) { - const { keyId, searcher } = node; - const matches = this._findMatches({ - key: this._keyStore.get(keyId), - value: this._myIndex.getValueForItemAtKeyId(item, keyId), - searcher - }); - if (matches && matches.length) { - return [ - { - idx, - item, - matches - } - ]; - } - return []; - } - const res = []; - for (let i6 = 0, len = node.children.length;i6 < len; i6 += 1) { - const child = node.children[i6]; - const result = evaluate(child, item, idx); - if (result.length) { - res.push(...result); - } else if (node.operator === LogicalOperator.AND) { - return []; - } - } - return res; - }; - const records = this._myIndex.records; - const resultMap = {}; - const results = []; - records.forEach(({ $: item, i: idx }) => { - if (isDefined2(item)) { - let expResults = evaluate(expression, item, idx); - if (expResults.length) { - if (!resultMap[idx]) { - resultMap[idx] = { idx, item, matches: [] }; - results.push(resultMap[idx]); - } - expResults.forEach(({ matches }) => { - resultMap[idx].matches.push(...matches); - }); - } - } - }); - return results; - } - _searchObjectList(query2) { - const searcher = createSearcher(query2, this.options); - const { keys: keys2, records } = this._myIndex; - const results = []; - records.forEach(({ $: item, i: idx }) => { - if (!isDefined2(item)) { - return; - } - let matches = []; - keys2.forEach((key2, keyIndex) => { - matches.push(...this._findMatches({ - key: key2, - value: item[keyIndex], - searcher - })); - }); - if (matches.length) { - results.push({ - idx, - item, - matches - }); - } - }); - return results; - } - _findMatches({ key: key2, value, searcher }) { - if (!isDefined2(value)) { - return []; - } - let matches = []; - if (isArray9(value)) { - value.forEach(({ v: text, i: idx, n: norm2 }) => { - if (!isDefined2(text)) { - return; - } - const { isMatch, score, indices } = searcher.searchIn(text); - if (isMatch) { - matches.push({ - score, - key: key2, - value: text, - idx, - norm: norm2, - indices - }); - } - }); - } else { - const { v: text, n: norm2 } = value; - const { isMatch, score, indices } = searcher.searchIn(text); - if (isMatch) { - matches.push({ score, key: key2, value: text, norm: norm2, indices }); - } - } - return matches; - } -} -var INFINITY4, INCORRECT_INDEX_TYPE = "Incorrect 'index' type", LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key2) => `Invalid value for key ${key2}`, PATTERN_LENGTH_TOO_LARGE = (max2) => `Pattern length exceeds max of ${max2}.`, MISSING_KEY_PROPERTY = (name3) => `Missing ${name3} property in key`, INVALID_KEY_WEIGHT_VALUE = (key2) => `Property 'weight' in key '${key2}' must be a positive integer`, hasOwn7, MatchOptions, BasicOptions, FuzzyOptions, AdvancedOptions, Config2, SPACE, MAX_BITS = 32, stripDiacritics, ExactMatch, InverseExactMatch, PrefixExactMatch, InversePrefixExactMatch, SuffixExactMatch, InverseSuffixExactMatch, FuzzyMatch, IncludeMatch, searchers, searchersLen, SPACE_RE, OR_TOKEN = "|", MultiMatchSet, registeredSearchers, LogicalOperator, KeyType, isExpression = (query2) => !!(query2[LogicalOperator.AND] || query2[LogicalOperator.OR]), isPath = (query2) => !!query2[KeyType.PATH], isLeaf = (query2) => !isArray9(query2) && isObject6(query2) && !isExpression(query2), convertToExplicit = (query2) => ({ - [LogicalOperator.AND]: Object.keys(query2).map((key2) => ({ - [key2]: query2[key2] - })) -}); -var init_fuse = __esm(() => { - INFINITY4 = 1 / 0; - hasOwn7 = Object.prototype.hasOwnProperty; - MatchOptions = { - includeMatches: false, - findAllMatches: false, - minMatchCharLength: 1 - }; - BasicOptions = { - isCaseSensitive: false, - ignoreDiacritics: false, - includeScore: false, - keys: [], - shouldSort: true, - sortFn: (a5, b5) => a5.score === b5.score ? a5.idx < b5.idx ? -1 : 1 : a5.score < b5.score ? -1 : 1 - }; - FuzzyOptions = { - location: 0, - threshold: 0.6, - distance: 100 - }; - AdvancedOptions = { - useExtendedSearch: false, - getFn: get2, - ignoreLocation: false, - ignoreFieldNorm: false, - fieldNormWeight: 1 - }; - Config2 = { - ...BasicOptions, - ...MatchOptions, - ...FuzzyOptions, - ...AdvancedOptions - }; - SPACE = /[^ ]+/g; - stripDiacritics = String.prototype.normalize ? (str2) => str2.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g, "") : (str2) => str2; - ExactMatch = class ExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "exact"; - } - static get multiRegex() { - return /^="(.*)"$/; - } - static get singleRegex() { - return /^=(.*)$/; - } - search(text) { - const isMatch = text === this.pattern; - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, this.pattern.length - 1] - }; - } - }; - InverseExactMatch = class InverseExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "inverse-exact"; - } - static get multiRegex() { - return /^!"(.*)"$/; - } - static get singleRegex() { - return /^!(.*)$/; - } - search(text) { - const index2 = text.indexOf(this.pattern); - const isMatch = index2 === -1; - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, text.length - 1] - }; - } - }; - PrefixExactMatch = class PrefixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "prefix-exact"; - } - static get multiRegex() { - return /^\^"(.*)"$/; - } - static get singleRegex() { - return /^\^(.*)$/; - } - search(text) { - const isMatch = text.startsWith(this.pattern); - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, this.pattern.length - 1] - }; - } - }; - InversePrefixExactMatch = class InversePrefixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "inverse-prefix-exact"; - } - static get multiRegex() { - return /^!\^"(.*)"$/; - } - static get singleRegex() { - return /^!\^(.*)$/; - } - search(text) { - const isMatch = !text.startsWith(this.pattern); - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, text.length - 1] - }; - } - }; - SuffixExactMatch = class SuffixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "suffix-exact"; - } - static get multiRegex() { - return /^"(.*)"\$$/; - } - static get singleRegex() { - return /^(.*)\$$/; - } - search(text) { - const isMatch = text.endsWith(this.pattern); - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [text.length - this.pattern.length, text.length - 1] - }; - } - }; - InverseSuffixExactMatch = class InverseSuffixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "inverse-suffix-exact"; - } - static get multiRegex() { - return /^!"(.*)"\$$/; - } - static get singleRegex() { - return /^!(.*)\$$/; - } - search(text) { - const isMatch = !text.endsWith(this.pattern); - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, text.length - 1] - }; - } - }; - FuzzyMatch = class FuzzyMatch extends BaseMatch { - constructor(pattern, { - location = Config2.location, - threshold = Config2.threshold, - distance = Config2.distance, - includeMatches = Config2.includeMatches, - findAllMatches = Config2.findAllMatches, - minMatchCharLength = Config2.minMatchCharLength, - isCaseSensitive = Config2.isCaseSensitive, - ignoreDiacritics = Config2.ignoreDiacritics, - ignoreLocation = Config2.ignoreLocation - } = {}) { - super(pattern); - this._bitapSearch = new BitapSearch(pattern, { - location, - threshold, - distance, - includeMatches, - findAllMatches, - minMatchCharLength, - isCaseSensitive, - ignoreDiacritics, - ignoreLocation - }); - } - static get type() { - return "fuzzy"; - } - static get multiRegex() { - return /^"(.*)"$/; - } - static get singleRegex() { - return /^(.*)$/; - } - search(text) { - return this._bitapSearch.searchIn(text); - } - }; - IncludeMatch = class IncludeMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return "include"; - } - static get multiRegex() { - return /^'"(.*)"$/; - } - static get singleRegex() { - return /^'(.*)$/; - } - search(text) { - let location = 0; - let index2; - const indices = []; - const patternLen = this.pattern.length; - while ((index2 = text.indexOf(this.pattern, location)) > -1) { - location = index2 + patternLen; - indices.push([index2, location - 1]); - } - const isMatch = !!indices.length; - return { - isMatch, - score: isMatch ? 0 : 1, - indices - }; - } - }; - searchers = [ - ExactMatch, - IncludeMatch, - PrefixExactMatch, - InversePrefixExactMatch, - InverseSuffixExactMatch, - SuffixExactMatch, - InverseExactMatch, - FuzzyMatch - ]; - searchersLen = searchers.length; - SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/; - MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]); - registeredSearchers = []; - LogicalOperator = { - AND: "$and", - OR: "$or" - }; - KeyType = { - PATH: "$path", - PATTERN: "$val" - }; - Fuse.version = "7.1.0"; - Fuse.createIndex = createIndex; - Fuse.parseIndex = parseIndex; - Fuse.config = Config2; - { - Fuse.parseQuery = parse16; - } - { - register(ExtendedSearch); - } -}); - -// src/utils/suggestions/commandSuggestions.ts -function getCommandFuse(commands7) { - if (fuseCache?.commands === commands7) { - return fuseCache.fuse; - } - const commandData = commands7.filter((cmd) => !cmd.isHidden).map((cmd) => { - const commandName = getCommandName(cmd); - const parts = commandName.split(SEPARATORS).filter(Boolean); - return { - descriptionKey: (cmd.description ?? "").split(" ").map((word) => cleanWord(word)).filter(Boolean), - partKey: parts.length > 1 ? parts : undefined, - commandName, - command: cmd, - aliasKey: cmd.aliases - }; - }); - const fuse = new Fuse(commandData, { - includeScore: true, - threshold: 0.3, - location: 0, - distance: 100, - keys: [ - { - name: "commandName", - weight: 3 - }, - { - name: "partKey", - weight: 2 - }, - { - name: "aliasKey", - weight: 2 - }, - { - name: "descriptionKey", - weight: 0.5 - } - ] - }); - fuseCache = { commands: commands7, fuse }; - return fuse; -} -function isCommandMetadata(metadata) { - return typeof metadata === "object" && metadata !== null && "name" in metadata && typeof metadata.name === "string" && "type" in metadata; -} -function findMidInputSlashCommand(input, cursorOffset) { - if (input.startsWith("/")) { - return null; - } - const beforeCursor = input.slice(0, cursorOffset); - const match = beforeCursor.match(/\s\/([a-zA-Z0-9_:-]*)$/); - if (!match || match.index === undefined) { - return null; - } - const slashPos = match.index + 1; - const textAfterSlash = input.slice(slashPos + 1); - const commandMatch = textAfterSlash.match(/^[a-zA-Z0-9_:-]*/); - const fullCommand = commandMatch ? commandMatch[0] : ""; - if (cursorOffset > slashPos + 1 + fullCommand.length) { - return null; - } - return { - token: "/" + fullCommand, - startPos: slashPos, - partialCommand: fullCommand - }; -} -function getBestCommandMatch(partialCommand, commands7) { - if (!partialCommand) { - return null; - } - const suggestions = generateCommandSuggestions("/" + partialCommand, commands7); - if (suggestions.length === 0) { - return null; - } - const query2 = partialCommand.toLowerCase(); - for (const suggestion of suggestions) { - if (!isCommandMetadata(suggestion.metadata)) { - continue; - } - const name3 = getCommandName(suggestion.metadata); - if (name3.toLowerCase().startsWith(query2)) { - const suffix = name3.slice(partialCommand.length); - if (suffix) { - return { suffix, fullCommand: name3 }; - } - } - } - return null; -} -function isCommandInput(input) { - return input.startsWith("/"); -} -function hasCommandArgs(input) { - if (!isCommandInput(input)) - return false; - if (!input.includes(" ")) - return false; - if (input.endsWith(" ")) - return false; - return true; -} -function formatCommand2(command19) { - return `/${command19} `; -} -function getCommandId2(cmd) { - const commandName = getCommandName(cmd); - if (cmd.type === "prompt") { - if (cmd.source === "plugin" && cmd.pluginInfo?.repository) { - return `${commandName}:${cmd.source}:${cmd.pluginInfo.repository}`; - } - return `${commandName}:${cmd.source}`; - } - return `${commandName}:${cmd.type}`; -} -function findMatchedAlias(query2, aliases) { - if (!aliases || aliases.length === 0 || query2 === "") { - return; - } - return aliases.find((alias2) => alias2.toLowerCase().startsWith(query2)); -} -function createCommandSuggestionItem(cmd, matchedAlias) { - const commandName = getCommandName(cmd); - const aliasText = matchedAlias ? ` (${matchedAlias})` : ""; - const isWorkflow = cmd.type === "prompt" && cmd.kind === "workflow"; - const fullDescription = (isWorkflow ? cmd.description : formatDescriptionWithSource(cmd)) + (cmd.type === "prompt" && cmd.argNames?.length ? ` (arguments: ${cmd.argNames.join(", ")})` : ""); - return { - id: getCommandId2(cmd), - displayText: `/${commandName}${aliasText}`, - tag: isWorkflow ? "workflow" : undefined, - description: fullDescription, - metadata: cmd - }; -} -function generateCommandSuggestions(input, commands7) { - if (!isCommandInput(input)) { - return []; - } - if (hasCommandArgs(input)) { - return []; - } - const query2 = input.slice(1).toLowerCase().trim(); - if (query2 === "") { - const visibleCommands = commands7.filter((cmd) => !cmd.isHidden); - const recentlyUsed = []; - const commandsWithScores = visibleCommands.filter((cmd) => cmd.type === "prompt").map((cmd) => ({ - cmd, - score: getSkillUsageScore(getCommandName(cmd)) - })).filter((item) => item.score > 0).sort((a5, b5) => b5.score - a5.score); - for (const item of commandsWithScores.slice(0, 5)) { - recentlyUsed.push(item.cmd); - } - const recentlyUsedIds = new Set(recentlyUsed.map((cmd) => getCommandId2(cmd))); - const builtinCommands = []; - const userCommands = []; - const projectCommands = []; - const policyCommands = []; - const otherCommands = []; - visibleCommands.forEach((cmd) => { - if (recentlyUsedIds.has(getCommandId2(cmd))) { - return; - } - if (cmd.type === "local" || cmd.type === "local-jsx") { - builtinCommands.push(cmd); - } else if (cmd.type === "prompt" && (cmd.source === "userSettings" || cmd.source === "localSettings")) { - userCommands.push(cmd); - } else if (cmd.type === "prompt" && cmd.source === "projectSettings") { - projectCommands.push(cmd); - } else if (cmd.type === "prompt" && cmd.source === "policySettings") { - policyCommands.push(cmd); - } else { - otherCommands.push(cmd); - } - }); - const sortAlphabetically = (a5, b5) => getCommandName(a5).localeCompare(getCommandName(b5)); - builtinCommands.sort(sortAlphabetically); - userCommands.sort(sortAlphabetically); - projectCommands.sort(sortAlphabetically); - policyCommands.sort(sortAlphabetically); - otherCommands.sort(sortAlphabetically); - return [ - ...recentlyUsed, - ...builtinCommands, - ...userCommands, - ...projectCommands, - ...policyCommands, - ...otherCommands - ].map((cmd) => createCommandSuggestionItem(cmd)); - } - let hiddenExact = commands7.find((cmd) => cmd.isHidden && getCommandName(cmd).toLowerCase() === query2); - if (hiddenExact && commands7.some((cmd) => !cmd.isHidden && getCommandName(cmd).toLowerCase() === query2)) { - hiddenExact = undefined; - } - const fuse = getCommandFuse(commands7); - const searchResults = fuse.search(query2); - const withMeta = searchResults.map((r4) => { - const name3 = r4.item.commandName.toLowerCase(); - const aliases = r4.item.aliasKey?.map((alias2) => alias2.toLowerCase()) ?? []; - const usage = r4.item.command.type === "prompt" ? getSkillUsageScore(getCommandName(r4.item.command)) : 0; - return { r: r4, name: name3, aliases, usage }; - }); - const sortedResults = withMeta.sort((a5, b5) => { - const aName = a5.name; - const bName = b5.name; - const aAliases = a5.aliases; - const bAliases = b5.aliases; - const aExactName = aName === query2; - const bExactName = bName === query2; - if (aExactName && !bExactName) - return -1; - if (bExactName && !aExactName) - return 1; - const aExactAlias = aAliases.some((alias2) => alias2 === query2); - const bExactAlias = bAliases.some((alias2) => alias2 === query2); - if (aExactAlias && !bExactAlias) - return -1; - if (bExactAlias && !aExactAlias) - return 1; - const aPrefixName = aName.startsWith(query2); - const bPrefixName = bName.startsWith(query2); - if (aPrefixName && !bPrefixName) - return -1; - if (bPrefixName && !aPrefixName) - return 1; - if (aPrefixName && bPrefixName && aName.length !== bName.length) { - return aName.length - bName.length; - } - const aPrefixAlias = aAliases.find((alias2) => alias2.startsWith(query2)); - const bPrefixAlias = bAliases.find((alias2) => alias2.startsWith(query2)); - if (aPrefixAlias && !bPrefixAlias) - return -1; - if (bPrefixAlias && !aPrefixAlias) - return 1; - if (aPrefixAlias && bPrefixAlias && aPrefixAlias.length !== bPrefixAlias.length) { - return aPrefixAlias.length - bPrefixAlias.length; - } - const scoreDiff = (a5.r.score ?? 0) - (b5.r.score ?? 0); - if (Math.abs(scoreDiff) > 0.1) { - return scoreDiff; - } - return b5.usage - a5.usage; - }); - const fuseSuggestions = sortedResults.map((result) => { - const cmd = result.r.item.command; - const matchedAlias = findMatchedAlias(query2, cmd.aliases); - return createCommandSuggestionItem(cmd, matchedAlias); - }); - if (hiddenExact) { - const hiddenId = getCommandId2(hiddenExact); - if (!fuseSuggestions.some((s4) => s4.id === hiddenId)) { - return [createCommandSuggestionItem(hiddenExact), ...fuseSuggestions]; - } - } - return fuseSuggestions; -} -function applyCommandSuggestion(suggestion, shouldExecute, commands7, onInputChange, setCursorOffset, onSubmit) { - let commandName; - let commandObj; - if (typeof suggestion === "string") { - commandName = suggestion; - commandObj = shouldExecute ? getCommand(commandName, commands7) : undefined; - } else { - if (!isCommandMetadata(suggestion.metadata)) { - return; - } - commandName = getCommandName(suggestion.metadata); - commandObj = suggestion.metadata; - } - const newInput = formatCommand2(commandName); - onInputChange(newInput); - setCursorOffset(newInput.length); - if (shouldExecute && commandObj) { - if (commandObj.type !== "prompt" || (commandObj.argNames ?? []).length === 0) { - onSubmit(newInput, true); - } - } -} -function cleanWord(word) { - return word.toLowerCase().replace(/[^a-z0-9]/g, ""); -} -function findSlashCommandPositions(text) { - const positions = []; - const regex2 = /(^|[\s])(\/[a-zA-Z][a-zA-Z0-9:\-_]*)/g; - let match = null; - while ((match = regex2.exec(text)) !== null) { - const precedingChar = match[1] ?? ""; - const commandName = match[2] ?? ""; - const start = match.index + precedingChar.length; - positions.push({ start, end: start + commandName.length }); - } - return positions; -} -var SEPARATORS, fuseCache = null; -var init_commandSuggestions = __esm(() => { - init_fuse(); - init_commands5(); - init_skillUsageTracking(); - SEPARATORS = /[:_-]/g; -}); - -// src/utils/suggestions/shellHistoryCompletion.ts -async function getShellHistoryCommands() { - const now2 = Date.now(); - if (shellHistoryCache && now2 - shellHistoryCacheTimestamp < CACHE_TTL_MS5) { - return shellHistoryCache; - } - const commands7 = []; - const seen = new Set; - try { - for await (const entry of getHistory()) { - if (entry.display && entry.display.startsWith("!")) { - const command19 = entry.display.slice(1).trim(); - if (command19 && !seen.has(command19)) { - seen.add(command19); - commands7.push(command19); - } - } - if (commands7.length >= 50) { - break; - } - } - } catch (error46) { - logForDebugging(`Failed to read shell history: ${error46}`); - } - shellHistoryCache = commands7; - shellHistoryCacheTimestamp = now2; - return commands7; -} -function prependToShellHistoryCache(command19) { - if (!shellHistoryCache) { - return; - } - const idx = shellHistoryCache.indexOf(command19); - if (idx !== -1) { - shellHistoryCache.splice(idx, 1); - } - shellHistoryCache.unshift(command19); -} -async function getShellHistoryCompletion(input) { - if (!input || input.length < 2) { - return null; - } - const trimmedInput = input.trim(); - if (!trimmedInput) { - return null; - } - const commands7 = await getShellHistoryCommands(); - for (const command19 of commands7) { - if (command19.startsWith(input) && command19 !== input) { - return { - fullCommand: command19, - suffix: command19.slice(input.length) - }; - } - } - return null; -} -var shellHistoryCache = null, shellHistoryCacheTimestamp = 0, CACHE_TTL_MS5 = 60000; -var init_shellHistoryCompletion = __esm(() => { - init_history(); - init_debug(); -}); - -// src/utils/suggestions/slackChannelSuggestions.ts -function findSlackClient(clients) { - return clients.find((c9) => c9.type === "connected" && c9.name.includes("slack")); -} -async function fetchChannels(clients, query2) { - const slackClient = findSlackClient(clients); - if (!slackClient || slackClient.type !== "connected") { - return []; - } - try { - const result = await slackClient.client.callTool({ - name: SLACK_SEARCH_TOOL, - arguments: { - query: query2, - limit: 20, - channel_types: "public_channel,private_channel" - } - }, undefined, { timeout: 5000 }); - const content = result.content; - if (!Array.isArray(content)) - return []; - const rawText = content.filter((c9) => c9.type === "text").map((c9) => c9.text).join(` -`); - return parseChannels(unwrapResults(rawText)); - } catch (error46) { - logForDebugging(`Failed to fetch Slack channels: ${error46}`); - return []; - } -} -function unwrapResults(text) { - const trimmed = text.trim(); - if (!trimmed.startsWith("{")) - return text; - try { - const parsed = resultsEnvelopeSchema().safeParse(jsonParse(trimmed)); - if (parsed.success) - return parsed.data.results; - } catch {} - return text; -} -function parseChannels(text) { - const channels = []; - const seen = new Set; - for (const line of text.split(` -`)) { - const m4 = line.match(/^Name:\s*#?([a-z0-9][a-z0-9_-]{0,79})\s*$/); - if (m4 && !seen.has(m4[1])) { - seen.add(m4[1]); - channels.push(m4[1]); - } - } - return channels; -} -function hasSlackMcpServer(clients) { - return findSlackClient(clients) !== undefined; -} -function getKnownChannelsVersion() { - return knownChannelsVersion; -} -function findSlackChannelPositions(text) { - const positions = []; - const re = /(^|\s)#([a-z0-9][a-z0-9_-]{0,79})(?=\s|$)/g; - let m4; - while ((m4 = re.exec(text)) !== null) { - if (!knownChannels.has(m4[2])) - continue; - const start = m4.index + m4[1].length; - positions.push({ start, end: start + 1 + m4[2].length }); - } - return positions; -} -function mcpQueryFor(searchToken) { - const lastSep = Math.max(searchToken.lastIndexOf("-"), searchToken.lastIndexOf("_")); - return lastSep > 0 ? searchToken.slice(0, lastSep) : searchToken; -} -function findReusableCacheEntry(mcpQuery, searchToken) { - let best; - let bestLen = 0; - for (const [key2, channels] of cache8) { - if (mcpQuery.startsWith(key2) && key2.length > bestLen && channels.some((c9) => c9.startsWith(searchToken))) { - best = channels; - bestLen = key2.length; - } - } - return best; -} -async function getSlackChannelSuggestions(clients, searchToken) { - if (!searchToken) - return []; - const mcpQuery = mcpQueryFor(searchToken); - const lower = searchToken.toLowerCase(); - let channels = cache8.get(mcpQuery) ?? findReusableCacheEntry(mcpQuery, lower); - if (!channels) { - if (inflightQuery === mcpQuery && inflightPromise) { - channels = await inflightPromise; - } else { - inflightQuery = mcpQuery; - inflightPromise = fetchChannels(clients, mcpQuery); - channels = await inflightPromise; - cache8.set(mcpQuery, channels); - const before = knownChannels.size; - for (const c9 of channels) - knownChannels.add(c9); - if (knownChannels.size !== before) { - knownChannelsVersion++; - knownChannelsChanged.emit(); - } - if (cache8.size > 50) { - cache8.delete(cache8.keys().next().value); - } - if (inflightQuery === mcpQuery) { - inflightQuery = null; - inflightPromise = null; - } - } - } - return channels.filter((c9) => c9.startsWith(lower)).sort().slice(0, 10).map((c9) => ({ - id: `slack-channel-${c9}`, - displayText: `#${c9}` - })); -} -var SLACK_SEARCH_TOOL = "slack_search_channels", cache8, knownChannels, knownChannelsVersion = 0, knownChannelsChanged, subscribeKnownChannels, inflightQuery = null, inflightPromise = null, resultsEnvelopeSchema; -var init_slackChannelSuggestions = __esm(() => { - init_zod(); - init_debug(); - init_slowOperations(); - cache8 = new Map; - knownChannels = new Set; - knownChannelsChanged = createSignal(); - subscribeKnownChannels = knownChannelsChanged.subscribe; - resultsEnvelopeSchema = lazySchema(() => exports_external2.object({ results: exports_external2.string() })); -}); - -// src/hooks/unifiedSuggestions.ts -import { basename as basename54 } from "path"; -function createSuggestionFromSource(source) { - switch (source.type) { - case "file": - return { - id: `file-${source.path}`, - displayText: source.displayText, - description: source.description - }; - case "mcp_resource": - return { - id: `mcp-resource-${source.server}__${source.uri}`, - displayText: source.displayText, - description: source.description - }; - case "agent": - return { - id: `agent-${source.agentType}`, - displayText: source.displayText, - description: source.description, - color: source.color - }; - } -} -function truncateDescription(description) { - return truncateToWidth(description, DESCRIPTION_MAX_LENGTH); -} -function generateAgentSuggestions(agents2, query2, showOnEmpty = false) { - if (!query2 && !showOnEmpty) { - return []; - } - try { - const agentSources = agents2.map((agent) => ({ - type: "agent", - displayText: `${agent.agentType} (agent)`, - description: truncateDescription(agent.whenToUse), - agentType: agent.agentType, - color: getAgentColor(agent.agentType) - })); - if (!query2) { - return agentSources; - } - const queryLower = query2.toLowerCase(); - return agentSources.filter((agent) => agent.agentType.toLowerCase().includes(queryLower) || agent.displayText.toLowerCase().includes(queryLower)); - } catch (error46) { - logError2(error46); - return []; - } -} -async function generateUnifiedSuggestions(query2, mcpResources, agents2, showOnEmpty = false) { - if (!query2 && !showOnEmpty) { - return []; - } - const [fileSuggestions, agentSources] = await Promise.all([ - generateFileSuggestions(query2, showOnEmpty), - Promise.resolve(generateAgentSuggestions(agents2, query2, showOnEmpty)) - ]); - const fileSources = fileSuggestions.map((suggestion) => ({ - type: "file", - displayText: suggestion.displayText, - description: suggestion.description, - path: suggestion.displayText, - filename: basename54(suggestion.displayText), - score: suggestion.metadata?.score - })); - const mcpSources = Object.values(mcpResources).flat().map((resource) => ({ - type: "mcp_resource", - displayText: `${resource.server}:${resource.uri}`, - description: truncateDescription(resource.description || resource.name || resource.uri), - server: resource.server, - uri: resource.uri, - name: resource.name || resource.uri - })); - if (!query2) { - const allSources = [...fileSources, ...mcpSources, ...agentSources]; - return allSources.slice(0, MAX_UNIFIED_SUGGESTIONS).map(createSuggestionFromSource); - } - const nonFileSources = [...mcpSources, ...agentSources]; - const scoredResults = []; - for (const fileSource of fileSources) { - scoredResults.push({ - source: fileSource, - score: fileSource.score ?? 0.5 - }); - } - if (nonFileSources.length > 0) { - const fuse = new Fuse(nonFileSources, { - includeScore: true, - threshold: 0.6, - keys: [ - { name: "displayText", weight: 2 }, - { name: "name", weight: 3 }, - { name: "server", weight: 1 }, - { name: "description", weight: 1 }, - { name: "agentType", weight: 3 } - ] - }); - const fuseResults = fuse.search(query2, { limit: MAX_UNIFIED_SUGGESTIONS }); - for (const result of fuseResults) { - scoredResults.push({ - source: result.item, - score: result.score ?? 0.5 - }); - } - } - scoredResults.sort((a5, b5) => a5.score - b5.score); - return scoredResults.slice(0, MAX_UNIFIED_SUGGESTIONS).map((r4) => r4.source).map(createSuggestionFromSource); -} -var MAX_UNIFIED_SUGGESTIONS = 15, DESCRIPTION_MAX_LENGTH = 60; -var init_unifiedSuggestions = __esm(() => { - init_fuse(); - init_fileSuggestions(); - init_agentColorManager(); - init_format(); - init_log2(); -}); - -// src/hooks/useTypeahead.tsx -function isPathMetadata(metadata) { - return typeof metadata === "object" && metadata !== null && "type" in metadata && (metadata.type === "directory" || metadata.type === "file"); -} -function getPreservedSelection(prevSuggestions, prevSelection, newSuggestions) { - if (newSuggestions.length === 0) { - return -1; - } - if (prevSelection < 0) { - return 0; - } - const prevSelectedItem = prevSuggestions[prevSelection]; - if (!prevSelectedItem) { - return 0; - } - const newIndex = newSuggestions.findIndex((item) => item.id === prevSelectedItem.id); - return newIndex >= 0 ? newIndex : 0; -} -function buildResumeInputFromSuggestion(suggestion) { - const metadata = suggestion.metadata; - return metadata?.sessionId ? `/resume ${metadata.sessionId}` : `/resume ${suggestion.displayText}`; -} -function extractSearchToken(completionToken) { - if (completionToken.isQuoted) { - return completionToken.token.slice(2).replace(/"$/, ""); - } else if (completionToken.token.startsWith("@")) { - return completionToken.token.substring(1); - } else { - return completionToken.token; - } -} -function formatReplacementValue(options2) { - const { - displayText, - mode, - hasAtPrefix, - needsQuotes, - isQuoted, - isComplete - } = options2; - const space = isComplete ? " " : ""; - if (isQuoted || needsQuotes) { - return mode === "bash" ? `"${displayText}"${space}` : `@"${displayText}"${space}`; - } else if (hasAtPrefix) { - return mode === "bash" ? `${displayText}${space}` : `@${displayText}${space}`; - } else { - return displayText; - } -} -function applyShellSuggestion(suggestion, input, cursorOffset, onInputChange, setCursorOffset, completionType) { - const beforeCursor = input.slice(0, cursorOffset); - const lastSpaceIndex = beforeCursor.lastIndexOf(" "); - const wordStart = lastSpaceIndex + 1; - let replacementText; - if (completionType === "variable") { - replacementText = "$" + suggestion.displayText + " "; - } else if (completionType === "command") { - replacementText = suggestion.displayText + " "; - } else { - replacementText = suggestion.displayText; - } - const newInput = input.slice(0, wordStart) + replacementText + input.slice(cursorOffset); - onInputChange(newInput); - setCursorOffset(wordStart + replacementText.length); -} -function applyTriggerSuggestion(suggestion, input, cursorOffset, triggerRe, onInputChange, setCursorOffset) { - const m4 = input.slice(0, cursorOffset).match(triggerRe); - if (!m4 || m4.index === undefined) - return; - const prefixStart = m4.index + (m4[1]?.length ?? 0); - const before = input.slice(0, prefixStart); - const newInput = before + suggestion.displayText + " " + input.slice(cursorOffset); - onInputChange(newInput); - setCursorOffset(before.length + suggestion.displayText.length + 1); -} -async function generateBashSuggestions(input, cursorOffset) { - try { - if (currentShellCompletionAbortController) { - currentShellCompletionAbortController.abort(); - } - currentShellCompletionAbortController = new AbortController; - const suggestions = await getShellCompletions(input, cursorOffset, currentShellCompletionAbortController.signal); - return suggestions; - } catch { - logEvent("tengu_shell_completion_failed", {}); - return []; - } -} -function applyDirectorySuggestion(input, suggestionId, tokenStartPos, tokenLength, isDirectory) { - const suffix = isDirectory ? "/" : " "; - const before = input.slice(0, tokenStartPos); - const after = input.slice(tokenStartPos + tokenLength); - const replacement = "@" + suggestionId + suffix; - const newInput = before + replacement + after; - return { - newInput, - cursorPos: before.length + replacement.length - }; -} -function extractCompletionToken(text, cursorPos, includeAtSymbol = false) { - if (!text) - return null; - const textBeforeCursor = text.substring(0, cursorPos); - if (includeAtSymbol) { - const quotedAtRegex = /@"([^"]*)"?$/; - const quotedMatch = textBeforeCursor.match(quotedAtRegex); - if (quotedMatch && quotedMatch.index !== undefined) { - const textAfterCursor2 = text.substring(cursorPos); - const afterQuotedMatch = textAfterCursor2.match(/^[^"]*"?/); - const quotedSuffix = afterQuotedMatch ? afterQuotedMatch[0] : ""; - return { - token: quotedMatch[0] + quotedSuffix, - startPos: quotedMatch.index, - isQuoted: true - }; - } - } - if (includeAtSymbol) { - const atIdx = textBeforeCursor.lastIndexOf("@"); - if (atIdx >= 0 && (atIdx === 0 || /\s/.test(textBeforeCursor[atIdx - 1]))) { - const fromAt = textBeforeCursor.substring(atIdx); - const atHeadMatch = fromAt.match(AT_TOKEN_HEAD_RE); - if (atHeadMatch && atHeadMatch[0].length === fromAt.length) { - const textAfterCursor2 = text.substring(cursorPos); - const afterMatch2 = textAfterCursor2.match(PATH_CHAR_HEAD_RE); - const tokenSuffix2 = afterMatch2 ? afterMatch2[0] : ""; - return { - token: atHeadMatch[0] + tokenSuffix2, - startPos: atIdx, - isQuoted: false - }; - } - } - } - const tokenRegex = includeAtSymbol ? TOKEN_WITH_AT_RE : TOKEN_WITHOUT_AT_RE; - const match = textBeforeCursor.match(tokenRegex); - if (!match || match.index === undefined) { - return null; - } - const textAfterCursor = text.substring(cursorPos); - const afterMatch = textAfterCursor.match(PATH_CHAR_HEAD_RE); - const tokenSuffix = afterMatch ? afterMatch[0] : ""; - return { - token: match[0] + tokenSuffix, - startPos: match.index, - isQuoted: false - }; -} -function extractCommandNameAndArgs(value) { - if (isCommandInput(value)) { - const spaceIndex = value.indexOf(" "); - if (spaceIndex === -1) - return { - commandName: value.slice(1), - args: "" - }; - return { - commandName: value.slice(1, spaceIndex), - args: value.slice(spaceIndex + 1) - }; - } - return null; -} -function hasCommandWithArguments(isAtEndWithWhitespace, value) { - return !isAtEndWithWhitespace && value.includes(" ") && !value.endsWith(" "); -} -function useTypeahead({ - commands: commands7, - onInputChange, - onSubmit, - setCursorOffset, - input, - cursorOffset, - mode, - agents: agents2, - setSuggestionsState, - suggestionsState: { - suggestions, - selectedSuggestion, - commandArgumentHint - }, - suppressSuggestions = false, - markAccepted, - onModeChange -}) { - const { - addNotification - } = useNotifications(); - const thinkingToggleShortcut = useShortcutDisplay("chat:thinkingToggle", "Chat", "alt+t"); - const [suggestionType, setSuggestionType] = import_react240.useState("none"); - const allCommandsMaxWidth = import_react240.useMemo(() => { - const visibleCommands = commands7.filter((cmd) => !cmd.isHidden); - if (visibleCommands.length === 0) - return; - const maxLen = Math.max(...visibleCommands.map((cmd) => getCommandName(cmd).length)); - return maxLen + 6; - }, [commands7]); - const [maxColumnWidth, setMaxColumnWidth] = import_react240.useState(undefined); - const mcpResources = useAppState((s4) => s4.mcp.resources); - const store = useAppStateStore(); - const promptSuggestion = useAppState((s4) => s4.promptSuggestion); - const isViewingTeammate = useAppState((s4) => !!s4.viewingAgentTaskId); - const keybindingContext = useOptionalKeybindingContext(); - const [inlineGhostText, setInlineGhostText] = import_react240.useState(undefined); - const syncPromptGhostText = import_react240.useMemo(() => { - if (mode !== "prompt" || suppressSuggestions) - return; - const midInputCommand = findMidInputSlashCommand(input, cursorOffset); - if (!midInputCommand) - return; - const match = getBestCommandMatch(midInputCommand.partialCommand, commands7); - if (!match) - return; - return { - text: match.suffix, - fullCommand: match.fullCommand, - insertPosition: midInputCommand.startPos + 1 + midInputCommand.partialCommand.length - }; - }, [input, cursorOffset, mode, commands7, suppressSuggestions]); - const effectiveGhostText = suppressSuggestions ? undefined : mode === "prompt" ? syncPromptGhostText : inlineGhostText; - const cursorOffsetRef = import_react240.useRef(cursorOffset); - cursorOffsetRef.current = cursorOffset; - const latestSearchTokenRef = import_react240.useRef(null); - const prevInputRef = import_react240.useRef(""); - const latestPathTokenRef = import_react240.useRef(""); - const latestBashInputRef = import_react240.useRef(""); - const latestSlackTokenRef = import_react240.useRef(""); - const suggestionsRef = import_react240.useRef(suggestions); - suggestionsRef.current = suggestions; - const dismissedForInputRef = import_react240.useRef(null); - const clearSuggestions = import_react240.useCallback(() => { - setSuggestionsState(() => ({ - commandArgumentHint: undefined, - suggestions: [], - selectedSuggestion: -1 - })); - setSuggestionType("none"); - setMaxColumnWidth(undefined); - setInlineGhostText(undefined); - }, [setSuggestionsState]); - const fetchFileSuggestions = import_react240.useCallback(async (searchToken, isAtSymbol = false) => { - latestSearchTokenRef.current = searchToken; - const combinedItems = await generateUnifiedSuggestions(searchToken, mcpResources, agents2, isAtSymbol); - if (latestSearchTokenRef.current !== searchToken) { - return; - } - if (combinedItems.length === 0) { - setSuggestionsState(() => ({ - commandArgumentHint: undefined, - suggestions: [], - selectedSuggestion: -1 - })); - setSuggestionType("none"); - setMaxColumnWidth(undefined); - return; - } - setSuggestionsState((prev) => ({ - commandArgumentHint: undefined, - suggestions: combinedItems, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, combinedItems) - })); - setSuggestionType(combinedItems.length > 0 ? "file" : "none"); - setMaxColumnWidth(undefined); - }, [mcpResources, setSuggestionsState, setSuggestionType, setMaxColumnWidth, agents2]); - import_react240.useEffect(() => { - if (true) { - startBackgroundCacheRefresh(); - } - return onIndexBuildComplete(() => { - const token = latestSearchTokenRef.current; - if (token !== null) { - latestSearchTokenRef.current = null; - fetchFileSuggestions(token, token === ""); - } - }); - }, [fetchFileSuggestions]); - const debouncedFetchFileSuggestions = useDebounceCallback(fetchFileSuggestions, 50); - const fetchSlackChannels = import_react240.useCallback(async (partial2) => { - latestSlackTokenRef.current = partial2; - const channels = await getSlackChannelSuggestions(store.getState().mcp.clients, partial2); - if (latestSlackTokenRef.current !== partial2) - return; - setSuggestionsState((prev) => ({ - commandArgumentHint: undefined, - suggestions: channels, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, channels) - })); - setSuggestionType(channels.length > 0 ? "slack-channel" : "none"); - setMaxColumnWidth(undefined); - }, [setSuggestionsState]); - const debouncedFetchSlackChannels = useDebounceCallback(fetchSlackChannels, 150); - const updateSuggestions = import_react240.useCallback(async (value, inputCursorOffset) => { - const effectiveCursorOffset = inputCursorOffset ?? cursorOffsetRef.current; - if (suppressSuggestions) { - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - return; - } - if (mode === "prompt") { - const midInputCommand = findMidInputSlashCommand(value, effectiveCursorOffset); - if (midInputCommand) { - const match = getBestCommandMatch(midInputCommand.partialCommand, commands7); - if (match) { - setSuggestionsState(() => ({ - commandArgumentHint: undefined, - suggestions: [], - selectedSuggestion: -1 - })); - setSuggestionType("none"); - setMaxColumnWidth(undefined); - return; - } - } - } - if (mode === "bash" && value.trim()) { - latestBashInputRef.current = value; - const historyMatch = await getShellHistoryCompletion(value); - if (latestBashInputRef.current !== value) { - return; - } - if (historyMatch) { - setInlineGhostText({ - text: historyMatch.suffix, - fullCommand: historyMatch.fullCommand, - insertPosition: value.length - }); - setSuggestionsState(() => ({ - commandArgumentHint: undefined, - suggestions: [], - selectedSuggestion: -1 - })); - setSuggestionType("none"); - setMaxColumnWidth(undefined); - return; - } else { - setInlineGhostText(undefined); - } - } - const atMatch = mode !== "bash" ? value.substring(0, effectiveCursorOffset).match(/(^|\s)@([\w-]*)$/) : null; - if (atMatch) { - const partialName = (atMatch[2] ?? "").toLowerCase(); - const state4 = store.getState(); - const members = []; - const seen = new Set; - if (isAgentSwarmsEnabled() && state4.teamContext) { - for (const t4 of Object.values(state4.teamContext.teammates ?? {})) { - if (t4.name === TEAM_LEAD_NAME) - continue; - if (!t4.name.toLowerCase().startsWith(partialName)) - continue; - seen.add(t4.name); - members.push({ - id: `dm-${t4.name}`, - displayText: `@${t4.name}`, - description: "send message" - }); - } - } - for (const [name3, agentId] of state4.agentNameRegistry) { - if (seen.has(name3)) - continue; - if (!name3.toLowerCase().startsWith(partialName)) - continue; - const status2 = state4.tasks[agentId]?.status; - members.push({ - id: `dm-${name3}`, - displayText: `@${name3}`, - description: status2 ? `send message \xB7 ${status2}` : "send message" - }); - } - if (members.length > 0) { - debouncedFetchFileSuggestions.cancel(); - setSuggestionsState((prev) => ({ - commandArgumentHint: undefined, - suggestions: members, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, members) - })); - setSuggestionType("agent"); - setMaxColumnWidth(undefined); - return; - } - } - if (mode === "prompt") { - const hashMatch = value.substring(0, effectiveCursorOffset).match(HASH_CHANNEL_RE); - if (hashMatch && hasSlackMcpServer(store.getState().mcp.clients)) { - debouncedFetchSlackChannels(hashMatch[2]); - return; - } else if (suggestionType === "slack-channel") { - debouncedFetchSlackChannels.cancel(); - clearSuggestions(); - } - } - const hasAtSymbol = value.substring(0, effectiveCursorOffset).match(HAS_AT_SYMBOL_RE); - const isAtEndWithWhitespace = effectiveCursorOffset === value.length && effectiveCursorOffset > 0 && value.length > 0 && value[effectiveCursorOffset - 1] === " "; - if (mode === "prompt" && isCommandInput(value) && effectiveCursorOffset > 0) { - const parsedCommand = extractCommandNameAndArgs(value); - if (parsedCommand && parsedCommand.commandName === "add-dir" && parsedCommand.args) { - const { - args - } = parsedCommand; - if (args.match(/\s+$/)) { - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - return; - } - const dirSuggestions = await getDirectoryCompletions(args); - if (dirSuggestions.length > 0) { - setSuggestionsState((prev) => ({ - suggestions: dirSuggestions, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, dirSuggestions), - commandArgumentHint: undefined - })); - setSuggestionType("directory"); - return; - } - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - return; - } - if (parsedCommand && parsedCommand.commandName === "resume" && parsedCommand.args !== undefined && value.includes(" ")) { - const { - args - } = parsedCommand; - const matches = await searchSessionsByCustomTitle(args, { - limit: 10 - }); - const suggestions2 = matches.map((log3) => { - const sessionId = getSessionIdFromLog(log3); - return { - id: `resume-title-${sessionId}`, - displayText: log3.customTitle, - description: formatLogMetadata(log3), - metadata: { - sessionId - } - }; - }); - if (suggestions2.length > 0) { - setSuggestionsState((prev) => ({ - suggestions: suggestions2, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, suggestions2), - commandArgumentHint: undefined - })); - setSuggestionType("custom-title"); - return; - } - clearSuggestions(); - return; - } - } - if (mode === "prompt" && isCommandInput(value) && effectiveCursorOffset > 0 && !hasCommandWithArguments(isAtEndWithWhitespace, value)) { - let commandArgumentHint2 = undefined; - if (value.length > 1) { - const spaceIndex = value.indexOf(" "); - const commandName = spaceIndex === -1 ? value.slice(1) : value.slice(1, spaceIndex); - const hasRealArguments = spaceIndex !== -1 && value.slice(spaceIndex + 1).trim().length > 0; - const hasExactlyOneTrailingSpace = spaceIndex !== -1 && value.length === spaceIndex + 1; - if (spaceIndex !== -1) { - const exactMatch = commands7.find((cmd) => getCommandName(cmd) === commandName); - if (exactMatch || hasRealArguments) { - if (exactMatch?.argumentHint && hasExactlyOneTrailingSpace) { - commandArgumentHint2 = exactMatch.argumentHint; - } else if (exactMatch?.type === "prompt" && exactMatch.argNames?.length && value.endsWith(" ")) { - const argsText = value.slice(spaceIndex + 1); - const typedArgs = parseArguments2(argsText); - commandArgumentHint2 = generateProgressiveArgumentHint(exactMatch.argNames, typedArgs); - } - setSuggestionsState(() => ({ - commandArgumentHint: commandArgumentHint2, - suggestions: [], - selectedSuggestion: -1 - })); - setSuggestionType("none"); - setMaxColumnWidth(undefined); - return; - } - } - } - const commandItems = generateCommandSuggestions(value, commands7); - setSuggestionsState(() => ({ - commandArgumentHint: commandArgumentHint2, - suggestions: commandItems, - selectedSuggestion: commandItems.length > 0 ? 0 : -1 - })); - setSuggestionType(commandItems.length > 0 ? "command" : "none"); - if (commandItems.length > 0) { - setMaxColumnWidth(allCommandsMaxWidth); - } - return; - } - if (suggestionType === "command") { - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } else if (isCommandInput(value) && hasCommandWithArguments(isAtEndWithWhitespace, value)) { - setSuggestionsState((prev) => prev.commandArgumentHint ? { - ...prev, - commandArgumentHint: undefined - } : prev); - } - if (suggestionType === "custom-title") { - clearSuggestions(); - } - if (suggestionType === "agent" && suggestionsRef.current.some((s4) => s4.id?.startsWith("dm-"))) { - const hasAt = value.substring(0, effectiveCursorOffset).match(/(^|\s)@([\w-]*)$/); - if (!hasAt) { - clearSuggestions(); - } - } - if (hasAtSymbol && mode !== "bash") { - const completionToken = extractCompletionToken(value, effectiveCursorOffset, true); - if (completionToken && completionToken.token.startsWith("@")) { - const searchToken = extractSearchToken(completionToken); - if (isPathLikeToken(searchToken)) { - latestPathTokenRef.current = searchToken; - const pathSuggestions = await getPathCompletions(searchToken, { - maxResults: 10 - }); - if (latestPathTokenRef.current !== searchToken) { - return; - } - if (pathSuggestions.length > 0) { - setSuggestionsState((prev) => ({ - suggestions: pathSuggestions, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, pathSuggestions), - commandArgumentHint: undefined - })); - setSuggestionType("directory"); - return; - } - } - if (latestSearchTokenRef.current === searchToken) { - return; - } - debouncedFetchFileSuggestions(searchToken, true); - return; - } - } - if (suggestionType === "file") { - const completionToken = extractCompletionToken(value, effectiveCursorOffset, true); - if (completionToken) { - const searchToken = extractSearchToken(completionToken); - if (latestSearchTokenRef.current === searchToken) { - return; - } - debouncedFetchFileSuggestions(searchToken, false); - } else { - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } - if (suggestionType === "shell") { - const inputSnapshot = suggestionsRef.current[0]?.metadata?.inputSnapshot; - if (mode !== "bash" || value !== inputSnapshot) { - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } - }, [ - suggestionType, - commands7, - setSuggestionsState, - clearSuggestions, - debouncedFetchFileSuggestions, - debouncedFetchSlackChannels, - mode, - suppressSuggestions, - allCommandsMaxWidth - ]); - import_react240.useEffect(() => { - if (dismissedForInputRef.current === input) { - return; - } - if (prevInputRef.current !== input) { - prevInputRef.current = input; - latestSearchTokenRef.current = null; - } - dismissedForInputRef.current = null; - updateSuggestions(input); - }, [input, updateSuggestions]); - const handleTab = import_react240.useCallback(async () => { - if (effectiveGhostText) { - if (mode === "bash") { - onInputChange(effectiveGhostText.fullCommand); - setCursorOffset(effectiveGhostText.fullCommand.length); - setInlineGhostText(undefined); - return; - } - const midInputCommand = findMidInputSlashCommand(input, cursorOffset); - if (midInputCommand) { - const before = input.slice(0, midInputCommand.startPos); - const after = input.slice(midInputCommand.startPos + midInputCommand.token.length); - const newInput = before + "/" + effectiveGhostText.fullCommand + " " + after; - const newCursorOffset = midInputCommand.startPos + 1 + effectiveGhostText.fullCommand.length + 1; - onInputChange(newInput); - setCursorOffset(newCursorOffset); - return; - } - } - if (suggestions.length > 0) { - debouncedFetchFileSuggestions.cancel(); - debouncedFetchSlackChannels.cancel(); - const index2 = selectedSuggestion === -1 ? 0 : selectedSuggestion; - const suggestion = suggestions[index2]; - if (suggestionType === "command" && index2 < suggestions.length) { - if (suggestion) { - applyCommandSuggestion(suggestion, false, commands7, onInputChange, setCursorOffset, onSubmit); - clearSuggestions(); - } - } else if (suggestionType === "custom-title" && suggestions.length > 0) { - if (suggestion) { - const newInput = buildResumeInputFromSuggestion(suggestion); - onInputChange(newInput); - setCursorOffset(newInput.length); - clearSuggestions(); - } - } else if (suggestionType === "directory" && suggestions.length > 0) { - const suggestion2 = suggestions[index2]; - if (suggestion2) { - const isInCommandContext = isCommandInput(input); - let newInput; - if (isInCommandContext) { - const spaceIndex = input.indexOf(" "); - const commandPart = input.slice(0, spaceIndex + 1); - const cmdSuffix = isPathMetadata(suggestion2.metadata) && suggestion2.metadata.type === "directory" ? "/" : " "; - newInput = commandPart + suggestion2.id + cmdSuffix; - onInputChange(newInput); - setCursorOffset(newInput.length); - if (isPathMetadata(suggestion2.metadata) && suggestion2.metadata.type === "directory") { - setSuggestionsState((prev) => ({ - ...prev, - commandArgumentHint: undefined - })); - updateSuggestions(newInput, newInput.length); - } else { - clearSuggestions(); - } - } else { - const completionTokenWithAt = extractCompletionToken(input, cursorOffset, true); - const completionToken = completionTokenWithAt ?? extractCompletionToken(input, cursorOffset, false); - if (completionToken) { - const isDir = isPathMetadata(suggestion2.metadata) && suggestion2.metadata.type === "directory"; - const result = applyDirectorySuggestion(input, suggestion2.id, completionToken.startPos, completionToken.token.length, isDir); - newInput = result.newInput; - onInputChange(newInput); - setCursorOffset(result.cursorPos); - if (isDir) { - setSuggestionsState((prev) => ({ - ...prev, - commandArgumentHint: undefined - })); - updateSuggestions(newInput, result.cursorPos); - } else { - clearSuggestions(); - } - } else { - clearSuggestions(); - } - } - } - } else if (suggestionType === "shell" && suggestions.length > 0) { - const suggestion2 = suggestions[index2]; - if (suggestion2) { - const metadata = suggestion2.metadata; - applyShellSuggestion(suggestion2, input, cursorOffset, onInputChange, setCursorOffset, metadata?.completionType); - clearSuggestions(); - } - } else if (suggestionType === "agent" && suggestions.length > 0 && suggestions[index2]?.id?.startsWith("dm-")) { - const suggestion2 = suggestions[index2]; - if (suggestion2) { - applyTriggerSuggestion(suggestion2, input, cursorOffset, DM_MEMBER_RE, onInputChange, setCursorOffset); - clearSuggestions(); - } - } else if (suggestionType === "slack-channel" && suggestions.length > 0) { - const suggestion2 = suggestions[index2]; - if (suggestion2) { - applyTriggerSuggestion(suggestion2, input, cursorOffset, HASH_CHANNEL_RE, onInputChange, setCursorOffset); - clearSuggestions(); - } - } else if (suggestionType === "file" && suggestions.length > 0) { - const completionToken = extractCompletionToken(input, cursorOffset, true); - if (!completionToken) { - clearSuggestions(); - return; - } - const commonPrefix = findLongestCommonPrefix(suggestions); - const hasAtPrefix = completionToken.token.startsWith("@"); - let effectiveTokenLength; - if (completionToken.isQuoted) { - effectiveTokenLength = completionToken.token.slice(2).replace(/"$/, "").length; - } else if (hasAtPrefix) { - effectiveTokenLength = completionToken.token.length - 1; - } else { - effectiveTokenLength = completionToken.token.length; - } - if (commonPrefix.length > effectiveTokenLength) { - const replacementValue = formatReplacementValue({ - displayText: commonPrefix, - mode, - hasAtPrefix, - needsQuotes: false, - isQuoted: completionToken.isQuoted, - isComplete: false - }); - applyFileSuggestion(replacementValue, input, completionToken.token, completionToken.startPos, onInputChange, setCursorOffset); - updateSuggestions(input.replace(completionToken.token, replacementValue), cursorOffset); - } else if (index2 < suggestions.length) { - const suggestion2 = suggestions[index2]; - if (suggestion2) { - const needsQuotes = suggestion2.displayText.includes(" "); - const replacementValue = formatReplacementValue({ - displayText: suggestion2.displayText, - mode, - hasAtPrefix, - needsQuotes, - isQuoted: completionToken.isQuoted, - isComplete: true - }); - applyFileSuggestion(replacementValue, input, completionToken.token, completionToken.startPos, onInputChange, setCursorOffset); - clearSuggestions(); - } - } - } - } else if (input.trim() !== "") { - let suggestionType2; - let suggestionItems; - if (mode === "bash") { - suggestionType2 = "shell"; - const bashSuggestions = await generateBashSuggestions(input, cursorOffset); - if (bashSuggestions.length === 1) { - const suggestion = bashSuggestions[0]; - if (suggestion) { - const metadata = suggestion.metadata; - applyShellSuggestion(suggestion, input, cursorOffset, onInputChange, setCursorOffset, metadata?.completionType); - } - suggestionItems = []; - } else { - suggestionItems = bashSuggestions; - } - } else { - suggestionType2 = "file"; - const completionInfo = extractCompletionToken(input, cursorOffset, true); - if (completionInfo) { - const isAtSymbol = completionInfo.token.startsWith("@"); - const searchToken = isAtSymbol ? completionInfo.token.substring(1) : completionInfo.token; - suggestionItems = await generateUnifiedSuggestions(searchToken, mcpResources, agents2, isAtSymbol); - } else { - suggestionItems = []; - } - } - if (suggestionItems.length > 0) { - setSuggestionsState((prev) => ({ - commandArgumentHint: undefined, - suggestions: suggestionItems, - selectedSuggestion: getPreservedSelection(prev.suggestions, prev.selectedSuggestion, suggestionItems) - })); - setSuggestionType(suggestionType2); - setMaxColumnWidth(undefined); - } - } - }, [suggestions, selectedSuggestion, input, suggestionType, commands7, mode, onInputChange, setCursorOffset, onSubmit, clearSuggestions, cursorOffset, updateSuggestions, mcpResources, setSuggestionsState, agents2, debouncedFetchFileSuggestions, debouncedFetchSlackChannels, effectiveGhostText]); - const handleEnter = import_react240.useCallback(() => { - if (selectedSuggestion < 0 || suggestions.length === 0) - return; - const suggestion = suggestions[selectedSuggestion]; - if (suggestionType === "command" && selectedSuggestion < suggestions.length) { - if (suggestion) { - applyCommandSuggestion(suggestion, true, commands7, onInputChange, setCursorOffset, onSubmit); - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } else if (suggestionType === "custom-title" && selectedSuggestion < suggestions.length) { - if (suggestion) { - const newInput = buildResumeInputFromSuggestion(suggestion); - onInputChange(newInput); - setCursorOffset(newInput.length); - onSubmit(newInput, true); - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } else if (suggestionType === "shell" && selectedSuggestion < suggestions.length) { - const suggestion2 = suggestions[selectedSuggestion]; - if (suggestion2) { - const metadata = suggestion2.metadata; - applyShellSuggestion(suggestion2, input, cursorOffset, onInputChange, setCursorOffset, metadata?.completionType); - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } else if (suggestionType === "agent" && selectedSuggestion < suggestions.length && suggestion?.id?.startsWith("dm-")) { - applyTriggerSuggestion(suggestion, input, cursorOffset, DM_MEMBER_RE, onInputChange, setCursorOffset); - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } else if (suggestionType === "slack-channel" && selectedSuggestion < suggestions.length) { - if (suggestion) { - applyTriggerSuggestion(suggestion, input, cursorOffset, HASH_CHANNEL_RE, onInputChange, setCursorOffset); - debouncedFetchSlackChannels.cancel(); - clearSuggestions(); - } - } else if (suggestionType === "file" && selectedSuggestion < suggestions.length) { - const completionInfo = extractCompletionToken(input, cursorOffset, true); - if (completionInfo) { - if (suggestion) { - const hasAtPrefix = completionInfo.token.startsWith("@"); - const needsQuotes = suggestion.displayText.includes(" "); - const replacementValue = formatReplacementValue({ - displayText: suggestion.displayText, - mode, - hasAtPrefix, - needsQuotes, - isQuoted: completionInfo.isQuoted, - isComplete: true - }); - applyFileSuggestion(replacementValue, input, completionInfo.token, completionInfo.startPos, onInputChange, setCursorOffset); - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } - } else if (suggestionType === "directory" && selectedSuggestion < suggestions.length) { - if (suggestion) { - if (isCommandInput(input)) { - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - return; - } - const completionTokenWithAt = extractCompletionToken(input, cursorOffset, true); - const completionToken = completionTokenWithAt ?? extractCompletionToken(input, cursorOffset, false); - if (completionToken) { - const isDir = isPathMetadata(suggestion.metadata) && suggestion.metadata.type === "directory"; - const result = applyDirectorySuggestion(input, suggestion.id, completionToken.startPos, completionToken.token.length, isDir); - onInputChange(result.newInput); - setCursorOffset(result.cursorPos); - } - debouncedFetchFileSuggestions.cancel(); - clearSuggestions(); - } - } - }, [suggestions, selectedSuggestion, suggestionType, commands7, input, cursorOffset, mode, onInputChange, setCursorOffset, onSubmit, clearSuggestions, debouncedFetchFileSuggestions, debouncedFetchSlackChannels]); - const handleAutocompleteAccept = import_react240.useCallback(() => { - handleTab(); - }, [handleTab]); - const handleAutocompleteDismiss = import_react240.useCallback(() => { - debouncedFetchFileSuggestions.cancel(); - debouncedFetchSlackChannels.cancel(); - clearSuggestions(); - dismissedForInputRef.current = input; - }, [debouncedFetchFileSuggestions, debouncedFetchSlackChannels, clearSuggestions, input]); - const handleAutocompletePrevious = import_react240.useCallback(() => { - setSuggestionsState((prev) => ({ - ...prev, - selectedSuggestion: prev.selectedSuggestion <= 0 ? suggestions.length - 1 : prev.selectedSuggestion - 1 - })); - }, [suggestions.length, setSuggestionsState]); - const handleAutocompleteNext = import_react240.useCallback(() => { - setSuggestionsState((prev) => ({ - ...prev, - selectedSuggestion: prev.selectedSuggestion >= suggestions.length - 1 ? 0 : prev.selectedSuggestion + 1 - })); - }, [suggestions.length, setSuggestionsState]); - const autocompleteHandlers = import_react240.useMemo(() => ({ - "autocomplete:accept": handleAutocompleteAccept, - "autocomplete:dismiss": handleAutocompleteDismiss, - "autocomplete:previous": handleAutocompletePrevious, - "autocomplete:next": handleAutocompleteNext - }), [handleAutocompleteAccept, handleAutocompleteDismiss, handleAutocompletePrevious, handleAutocompleteNext]); - const isAutocompleteActive = suggestions.length > 0 || !!effectiveGhostText; - const isModalOverlayActive = useIsModalOverlayActive(); - useRegisterOverlay("autocomplete", isAutocompleteActive); - useRegisterKeybindingContext("Autocomplete", isAutocompleteActive); - useKeybindings(autocompleteHandlers, { - context: "Autocomplete", - isActive: isAutocompleteActive && !isModalOverlayActive - }); - function acceptSuggestionText(text) { - const detectedMode = getModeFromInput(text); - if (detectedMode !== "prompt" && onModeChange) { - onModeChange(detectedMode); - const stripped = getValueFromInput(text); - onInputChange(stripped); - setCursorOffset(stripped.length); - } else { - onInputChange(text); - setCursorOffset(text.length); - } - } - const handleKeyDown = (e4) => { - if (e4.key === "right" && !isViewingTeammate) { - const suggestionText = promptSuggestion.text; - const suggestionShownAt = promptSuggestion.shownAt; - if (suggestionText && suggestionShownAt > 0 && input === "") { - markAccepted(); - acceptSuggestionText(suggestionText); - e4.stopImmediatePropagation(); - return; - } - } - if (e4.key === "tab" && !e4.shift) { - if (suggestions.length > 0 || effectiveGhostText) { - return; - } - const suggestionText = promptSuggestion.text; - const suggestionShownAt = promptSuggestion.shownAt; - if (suggestionText && suggestionShownAt > 0 && input === "" && !isViewingTeammate) { - e4.preventDefault(); - markAccepted(); - acceptSuggestionText(suggestionText); - return; - } - if (input.trim() === "") { - e4.preventDefault(); - addNotification({ - key: "thinking-toggle-hint", - jsx: /* @__PURE__ */ jsx_dev_runtime414.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Use ", - thinkingToggleShortcut, - " to toggle thinking" - ] - }, undefined, true, undefined, this), - priority: "immediate", - timeoutMs: 3000 - }); - } - return; - } - if (suggestions.length === 0) - return; - const hasPendingChord = keybindingContext?.pendingChord != null; - if (e4.ctrl && e4.key === "n" && !hasPendingChord) { - e4.preventDefault(); - handleAutocompleteNext(); - return; - } - if (e4.ctrl && e4.key === "p" && !hasPendingChord) { - e4.preventDefault(); - handleAutocompletePrevious(); - return; - } - if (e4.key === "return" && !e4.shift && !e4.meta) { - e4.preventDefault(); - handleEnter(); - } - }; - use_input_default((_input, _key, event) => { - const kbEvent = new KeyboardEvent(event.keypress); - handleKeyDown(kbEvent); - if (kbEvent.didStopImmediatePropagation()) { - event.stopImmediatePropagation(); - } - }); - return { - suggestions, - selectedSuggestion, - suggestionType, - maxColumnWidth, - commandArgumentHint, - inlineGhostText: effectiveGhostText, - handleKeyDown - }; -} -var import_react240, jsx_dev_runtime414, AT_TOKEN_HEAD_RE, PATH_CHAR_HEAD_RE, TOKEN_WITH_AT_RE, TOKEN_WITHOUT_AT_RE, HAS_AT_SYMBOL_RE, HASH_CHANNEL_RE, DM_MEMBER_RE, currentShellCompletionAbortController = null; -var init_useTypeahead = __esm(() => { - init_notifications(); - init_ink2(); - init_analytics(); - init_dist4(); - init_commands5(); - init_overlayContext(); - init_keyboard_event(); - init_ink2(); - init_KeybindingContext(); - init_useKeybinding(); - init_useShortcutDisplay(); - init_AppState(); - init_agentSwarmsEnabled(); - init_argumentSubstitution(); - init_shellCompletion(); - init_format(); - init_sessionStorage(); - init_commandSuggestions(); - init_directoryCompletion(); - init_shellHistoryCompletion(); - init_slackChannelSuggestions(); - init_fileSuggestions(); - init_unifiedSuggestions(); - import_react240 = __toESM(require_react(), 1); - jsx_dev_runtime414 = __toESM(require_jsx_dev_runtime(), 1); - AT_TOKEN_HEAD_RE = /^@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*/u; - PATH_CHAR_HEAD_RE = /^[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+/u; - TOKEN_WITH_AT_RE = /(@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*|[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+)$/u; - TOKEN_WITHOUT_AT_RE = /[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+$/u; - HAS_AT_SYMBOL_RE = /(^|\s)@([\p{L}\p{N}\p{M}_\-./\\()[\]~:]*|"[^"]*"?)$/u; - HASH_CHANNEL_RE = /(^|\s)#([a-z0-9][a-z0-9_-]*)$/; - DM_MEMBER_RE = /(^|\s)@[\w-]*$/; -}); - -// src/utils/directMemberMessage.ts -function parseDirectMemberMessage(input) { - const match = input.match(/^@([\w-]+)\s+(.+)$/s); - if (!match) - return null; - const [, recipientName, message] = match; - if (!recipientName || !message) - return null; - const trimmedMessage = message.trim(); - if (!trimmedMessage) - return null; - return { recipientName, message: trimmedMessage }; -} -async function sendDirectMemberMessage(recipientName, message, teamContext, writeToMailbox2) { - if (!teamContext || !writeToMailbox2) { - return { success: false, error: "no_team_context" }; - } - const member = Object.values(teamContext.teammates ?? {}).find((t4) => t4.name === recipientName); - if (!member) { - return { success: false, error: "unknown_recipient", recipientName }; - } - await writeToMailbox2(recipientName, { - from: "user", - text: message, - timestamp: new Date().toISOString() - }, teamContext.teamName); - return { success: true, recipientName }; -} - -// src/utils/keyboardShortcuts.ts -function isMacosOptionChar(char) { - return char in MACOS_OPTION_SPECIAL_CHARS; -} -var MACOS_OPTION_SPECIAL_CHARS; -var init_keyboardShortcuts = __esm(() => { - MACOS_OPTION_SPECIAL_CHARS = { - "\u2020": "alt+t", - \u{3c0}: "alt+p", - \u{f8}: "alt+o" - }; -}); -// src/utils/permissions/getNextPermissionMode.ts -function canCycleToAuto(ctx) { - if (false) {} - return false; -} -function getNextPermissionMode(toolPermissionContext, _teamContext) { - switch (toolPermissionContext.mode) { - case "default": - if (process.env.USER_TYPE === "ant") { - if (toolPermissionContext.isBypassPermissionsModeAvailable) { - return "bypassPermissions"; - } - if (canCycleToAuto(toolPermissionContext)) { - return "auto"; - } - return "default"; - } - return "acceptEdits"; - case "acceptEdits": - return "plan"; - case "plan": - if (toolPermissionContext.isBypassPermissionsModeAvailable) { - return "bypassPermissions"; - } - if (canCycleToAuto(toolPermissionContext)) { - return "auto"; - } - return "default"; - case "bypassPermissions": - if (canCycleToAuto(toolPermissionContext)) { - return "auto"; - } - return "default"; - case "dontAsk": - return "default"; - default: - return "default"; - } -} -function cyclePermissionMode(toolPermissionContext, teamContext) { - const nextMode = getNextPermissionMode(toolPermissionContext, teamContext); - return { - nextMode, - context: transitionPermissionMode(toolPermissionContext.mode, nextMode, toolPermissionContext) - }; -} -var init_getNextPermissionMode = __esm(() => { - init_debug(); - init_permissionSetup(); -}); - -// src/utils/ultraplan/keyword.ts -function findKeywordTriggerPositions(text, keyword) { - const re = new RegExp(keyword, "i"); - if (!re.test(text)) - return []; - if (text.startsWith("/")) - return []; - const quotedRanges = []; - let openQuote = null; - let openAt = 0; - const isWord = (ch2) => !!ch2 && /[\p{L}\p{N}_]/u.test(ch2); - for (let i6 = 0;i6 < text.length; i6++) { - const ch2 = text[i6]; - if (openQuote) { - if (openQuote === "[" && ch2 === "[") { - openAt = i6; - continue; - } - if (ch2 !== OPEN_TO_CLOSE[openQuote]) - continue; - if (openQuote === "'" && isWord(text[i6 + 1])) - continue; - quotedRanges.push({ start: openAt, end: i6 + 1 }); - openQuote = null; - } else if (ch2 === "<" && i6 + 1 < text.length && /[a-zA-Z/]/.test(text[i6 + 1]) || ch2 === "'" && !isWord(text[i6 - 1]) || ch2 !== "<" && ch2 !== "'" && ch2 in OPEN_TO_CLOSE) { - openQuote = ch2; - openAt = i6; - } - } - const positions = []; - const wordRe = new RegExp(`\\b${keyword}\\b`, "gi"); - const matches = text.matchAll(wordRe); - for (const match of matches) { - if (match.index === undefined) - continue; - const start = match.index; - const end = start + match[0].length; - if (quotedRanges.some((r4) => start >= r4.start && start < r4.end)) - continue; - const before = text[start - 1]; - const after = text[end]; - if (before === "/" || before === "\\" || before === "-") - continue; - if (after === "/" || after === "\\" || after === "-" || after === "?") - continue; - if (after === "." && isWord(text[end + 1])) - continue; - positions.push({ word: match[0], start, end }); - } - return positions; -} -function findUltrareviewTriggerPositions(text) { - return findKeywordTriggerPositions(text, "ultrareview"); -} -var OPEN_TO_CLOSE; -var init_keyword = __esm(() => { - OPEN_TO_CLOSE = { - "`": "`", - '"': '"', - "<": ">", - "{": "}", - "[": "]", - "(": ")", - "'": "'" - }; -}); - -// src/components/AutoModeOptInDialog.tsx -var import_compiler_runtime321, import_react241, jsx_dev_runtime415; -var init_AutoModeOptInDialog = __esm(() => { - init_analytics(); - init_ink2(); - init_settings2(); - init_CustomSelect(); - init_Dialog(); - import_compiler_runtime321 = __toESM(require_compiler_runtime(), 1); - import_react241 = __toESM(require_react(), 1); - jsx_dev_runtime415 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/BridgeDialog.tsx -import { basename as basename55 } from "path"; -function BridgeDialog(t0) { - const $2 = import_compiler_runtime322.c(87); - const { - onDone - } = t0; - useRegisterOverlay("bridge-dialog"); - const connected = useAppState(_temp192); - const sessionActive = useAppState(_temp279); - const reconnecting = useAppState(_temp352); - const connectUrl = useAppState(_temp438); - const sessionUrl = useAppState(_temp528); - const error46 = useAppState(_temp622); - const explicit = useAppState(_temp719); - const environmentId = useAppState(_temp815); - const sessionId = useAppState(_temp915); - const verbose = useAppState(_temp07); - const setAppState = useSetAppState(); - const [showQR, setShowQR] = import_react242.useState(false); - const [qrText, setQrText] = import_react242.useState(""); - const [branchName, setBranchName] = import_react242.useState(""); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = basename55(getOriginalCwd()); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const repoName = t1; - let t22; - let t32; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = () => { - getBranch().then(setBranchName).catch(_temp154); - }; - t32 = []; - $2[1] = t22; - $2[2] = t32; - } else { - t22 = $2[1]; - t32 = $2[2]; - } - import_react242.useEffect(t22, t32); - const displayUrl = sessionActive ? sessionUrl : connectUrl; - let t4; - let t5; - if ($2[3] !== displayUrl || $2[4] !== showQR) { - t4 = () => { - if (!showQR || !displayUrl) { - setQrText(""); - return; - } - $toString(displayUrl, { - type: "utf8", - errorCorrectionLevel: "L", - small: true - }).then(setQrText).catch(() => setQrText("")); - }; - t5 = [showQR, displayUrl]; - $2[3] = displayUrl; - $2[4] = showQR; - $2[5] = t4; - $2[6] = t5; - } else { - t4 = $2[5]; - t5 = $2[6]; - } - import_react242.useEffect(t4, t5); - let t6; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t6 = () => { - setShowQR(_temp105); - }; - $2[7] = t6; - } else { - t6 = $2[7]; - } - let t7; - if ($2[8] !== onDone) { - t7 = { - "confirm:yes": onDone, - "confirm:toggle": t6 - }; - $2[8] = onDone; - $2[9] = t7; - } else { - t7 = $2[9]; - } - let t8; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t8 = { - context: "Confirmation" - }; - $2[10] = t8; - } else { - t8 = $2[10]; - } - useKeybindings(t7, t8); - let t9; - if ($2[11] !== explicit || $2[12] !== onDone || $2[13] !== setAppState) { - t9 = (input) => { - if (input === "d") { - if (explicit) { - saveGlobalConfig(_temp1110); - } - setAppState(_temp1210); - onDone(); - } - }; - $2[11] = explicit; - $2[12] = onDone; - $2[13] = setAppState; - $2[14] = t9; - } else { - t9 = $2[14]; - } - use_input_default(t9); - let t10; - if ($2[15] !== connected || $2[16] !== error46 || $2[17] !== reconnecting || $2[18] !== sessionActive) { - t10 = getBridgeStatus({ - error: error46, - connected, - sessionActive, - reconnecting - }); - $2[15] = connected; - $2[16] = error46; - $2[17] = reconnecting; - $2[18] = sessionActive; - $2[19] = t10; - } else { - t10 = $2[19]; - } - const { - label: statusLabel, - color: statusColor - } = t10; - const indicator = error46 ? BRIDGE_FAILED_INDICATOR : BRIDGE_READY_INDICATOR; - let T0; - let T1; - let footerText; - let t11; - let t12; - let t13; - let t14; - let t15; - let t16; - let t17; - if ($2[20] !== branchName || $2[21] !== displayUrl || $2[22] !== environmentId || $2[23] !== error46 || $2[24] !== indicator || $2[25] !== onDone || $2[26] !== qrText || $2[27] !== sessionActive || $2[28] !== sessionId || $2[29] !== showQR || $2[30] !== statusColor || $2[31] !== statusLabel || $2[32] !== verbose) { - const qrLines = qrText ? qrText.split(` -`).filter(_temp135) : []; - let contextParts; - if ($2[43] !== branchName) { - contextParts = []; - if (repoName) { - contextParts.push(repoName); - } - if (branchName) { - contextParts.push(branchName); - } - $2[43] = branchName; - $2[44] = contextParts; - } else { - contextParts = $2[44]; - } - const contextSuffix = contextParts.length > 0 ? " \xB7 " + contextParts.join(" \xB7 ") : ""; - let t182; - if ($2[45] !== displayUrl || $2[46] !== error46 || $2[47] !== sessionActive) { - t182 = error46 ? FAILED_FOOTER_TEXT : displayUrl ? sessionActive ? buildActiveFooterText(displayUrl) : buildIdleFooterText(displayUrl) : undefined; - $2[45] = displayUrl; - $2[46] = error46; - $2[47] = sessionActive; - $2[48] = t182; - } else { - t182 = $2[48]; - } - footerText = t182; - T1 = Dialog; - t15 = "Remote Control"; - t16 = onDone; - t17 = true; - T0 = ThemedBox_default; - t11 = "column"; - t12 = 1; - let t192; - if ($2[49] !== indicator || $2[50] !== statusColor || $2[51] !== statusLabel) { - t192 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - color: statusColor, - children: [ - indicator, - " ", - statusLabel - ] - }, undefined, true, undefined, this); - $2[49] = indicator; - $2[50] = statusColor; - $2[51] = statusLabel; - $2[52] = t192; - } else { - t192 = $2[52]; - } - let t202; - if ($2[53] !== contextSuffix) { - t202 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - dimColor: true, - children: contextSuffix - }, undefined, false, undefined, this); - $2[53] = contextSuffix; - $2[54] = t202; - } else { - t202 = $2[54]; - } - let t212; - if ($2[55] !== t192 || $2[56] !== t202) { - t212 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - children: [ - t192, - t202 - ] - }, undefined, true, undefined, this); - $2[55] = t192; - $2[56] = t202; - $2[57] = t212; - } else { - t212 = $2[57]; - } - let t222; - if ($2[58] !== error46) { - t222 = error46 && /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - color: "error", - children: error46 - }, undefined, false, undefined, this); - $2[58] = error46; - $2[59] = t222; - } else { - t222 = $2[59]; - } - let t23; - if ($2[60] !== environmentId || $2[61] !== verbose) { - t23 = verbose && environmentId && /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Environment: ", - environmentId - ] - }, undefined, true, undefined, this); - $2[60] = environmentId; - $2[61] = verbose; - $2[62] = t23; - } else { - t23 = $2[62]; - } - let t24; - if ($2[63] !== sessionId || $2[64] !== verbose) { - t24 = verbose && sessionId && /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Session: ", - sessionId - ] - }, undefined, true, undefined, this); - $2[63] = sessionId; - $2[64] = verbose; - $2[65] = t24; - } else { - t24 = $2[65]; - } - if ($2[66] !== t212 || $2[67] !== t222 || $2[68] !== t23 || $2[69] !== t24) { - t13 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t212, - t222, - t23, - t24 - ] - }, undefined, true, undefined, this); - $2[66] = t212; - $2[67] = t222; - $2[68] = t23; - $2[69] = t24; - $2[70] = t13; - } else { - t13 = $2[70]; - } - t14 = showQR && qrLines.length > 0 && /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: qrLines.map(_temp144) - }, undefined, false, undefined, this); - $2[20] = branchName; - $2[21] = displayUrl; - $2[22] = environmentId; - $2[23] = error46; - $2[24] = indicator; - $2[25] = onDone; - $2[26] = qrText; - $2[27] = sessionActive; - $2[28] = sessionId; - $2[29] = showQR; - $2[30] = statusColor; - $2[31] = statusLabel; - $2[32] = verbose; - $2[33] = T0; - $2[34] = T1; - $2[35] = footerText; - $2[36] = t11; - $2[37] = t12; - $2[38] = t13; - $2[39] = t14; - $2[40] = t15; - $2[41] = t16; - $2[42] = t17; - } else { - T0 = $2[33]; - T1 = $2[34]; - footerText = $2[35]; - t11 = $2[36]; - t12 = $2[37]; - t13 = $2[38]; - t14 = $2[39]; - t15 = $2[40]; - t16 = $2[41]; - t17 = $2[42]; - } - let t18; - if ($2[71] !== footerText) { - t18 = footerText && /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - dimColor: true, - children: footerText - }, undefined, false, undefined, this); - $2[71] = footerText; - $2[72] = t18; - } else { - t18 = $2[72]; - } - let t19; - if ($2[73] === Symbol.for("react.memo_cache_sentinel")) { - t19 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - dimColor: true, - children: "d to disconnect \xB7 space for QR code \xB7 Enter/Esc to close" - }, undefined, false, undefined, this); - $2[73] = t19; - } else { - t19 = $2[73]; - } - let t20; - if ($2[74] !== T0 || $2[75] !== t11 || $2[76] !== t12 || $2[77] !== t13 || $2[78] !== t14 || $2[79] !== t18) { - t20 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(T0, { - flexDirection: t11, - gap: t12, - children: [ - t13, - t14, - t18, - t19 - ] - }, undefined, true, undefined, this); - $2[74] = T0; - $2[75] = t11; - $2[76] = t12; - $2[77] = t13; - $2[78] = t14; - $2[79] = t18; - $2[80] = t20; - } else { - t20 = $2[80]; - } - let t21; - if ($2[81] !== T1 || $2[82] !== t15 || $2[83] !== t16 || $2[84] !== t17 || $2[85] !== t20) { - t21 = /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(T1, { - title: t15, - onCancel: t16, - hideInputGuide: t17, - children: t20 - }, undefined, false, undefined, this); - $2[81] = T1; - $2[82] = t15; - $2[83] = t16; - $2[84] = t17; - $2[85] = t20; - $2[86] = t21; - } else { - t21 = $2[86]; - } - return t21; -} -function _temp144(line, i6) { - return /* @__PURE__ */ jsx_dev_runtime416.jsxDEV(ThemedText, { - children: line - }, i6, false, undefined, this); -} -function _temp135(l4) { - return l4.length > 0; -} -function _temp1210(prev_0) { - if (!prev_0.replBridgeEnabled) { - return prev_0; - } - return { - ...prev_0, - replBridgeEnabled: false - }; -} -function _temp1110(current) { - if (current.remoteControlAtStartup === false) { - return current; - } - return { - ...current, - remoteControlAtStartup: false - }; -} -function _temp105(prev) { - return !prev; -} -function _temp154() {} -function _temp07(s_8) { - return s_8.verbose; -} -function _temp915(s_7) { - return s_7.replBridgeSessionId; -} -function _temp815(s_6) { - return s_6.replBridgeEnvironmentId; -} -function _temp719(s_5) { - return s_5.replBridgeExplicit; -} -function _temp622(s_4) { - return s_4.replBridgeError; -} -function _temp528(s_3) { - return s_3.replBridgeSessionUrl; -} -function _temp438(s_2) { - return s_2.replBridgeConnectUrl; -} -function _temp352(s_1) { - return s_1.replBridgeReconnecting; -} -function _temp279(s_0) { - return s_0.replBridgeSessionActive; -} -function _temp192(s4) { - return s4.replBridgeConnected; -} -var import_compiler_runtime322, import_react242, jsx_dev_runtime416; -var init_BridgeDialog = __esm(() => { - init_server(); - init_state(); - init_bridgeStatusUtil(); - init_figures2(); - init_overlayContext(); - init_ink2(); - init_useKeybinding(); - init_AppState(); - init_config(); - init_git(); - init_Dialog(); - import_compiler_runtime322 = __toESM(require_compiler_runtime(), 1); - import_react242 = __toESM(require_react(), 1); - jsx_dev_runtime416 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/CoordinatorAgentStatus.tsx -function getVisibleAgentTasks(tasks2) { - return Object.values(tasks2).filter((t4) => isPanelAgentTask(t4) && t4.evictAfter !== 0).sort((a5, b5) => a5.startTime - b5.startTime); -} -function useCoordinatorTaskCount() { - const tasks2 = useAppState(_temp193); - let t0; - t0 = 0; - return t0; -} -function _temp193(s4) { - return s4.tasks; -} -var import_compiler_runtime323, React135, jsx_dev_runtime417; -var init_CoordinatorAgentStatus = __esm(() => { - init_figures2(); - init_useTerminalSize(); - init_stringWidth(); - init_ink2(); - init_AppState(); - init_teammateViewHelpers(); - init_LocalAgentTask(); - init_format(); - init_framework(); - init_taskStatusUtils(); - import_compiler_runtime323 = __toESM(require_compiler_runtime(), 1); - React135 = __toESM(require_react(), 1); - jsx_dev_runtime417 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/highlightMatch.tsx -var jsx_dev_runtime418; -var init_highlightMatch = __esm(() => { - init_ink2(); - jsx_dev_runtime418 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/design-system/FuzzyPicker.tsx -var import_compiler_runtime324, import_react243, jsx_dev_runtime419; -var init_FuzzyPicker = __esm(() => { - init_useSearchInput(); - init_useTerminalSize(); - init_geometry(); - init_ink2(); - init_SearchBox(); - init_Byline(); - init_KeyboardShortcutHint(); - init_ListItem(); - init_Pane(); - import_compiler_runtime324 = __toESM(require_compiler_runtime(), 1); - import_react243 = __toESM(require_react(), 1); - jsx_dev_runtime419 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/GlobalSearchDialog.tsx -var import_compiler_runtime325, import_react244, jsx_dev_runtime420; -var init_GlobalSearchDialog = __esm(() => { - init_overlayContext(); - init_useTerminalSize(); - init_ink2(); - init_analytics(); - init_cwd(); - init_editor(); - init_format(); - init_highlightMatch(); - init_filesystem(); - init_readFileInRange(); - init_ripgrep(); - init_FuzzyPicker(); - init_LoadingState(); - import_compiler_runtime325 = __toESM(require_compiler_runtime(), 1); - import_react244 = __toESM(require_react(), 1); - jsx_dev_runtime420 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/HistorySearchDialog.tsx -var import_react245, jsx_dev_runtime421; -var init_HistorySearchDialog = __esm(() => { - init_overlayContext(); - init_history(); - init_useTerminalSize(); - init_stringWidth(); - init_wrapAnsi(); - init_ink2(); - init_analytics(); - init_format(); - init_FuzzyPicker(); - import_react245 = __toESM(require_react(), 1); - jsx_dev_runtime421 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/QuickOpenDialog.tsx -var import_compiler_runtime326, import_react246, jsx_dev_runtime422; -var init_QuickOpenDialog = __esm(() => { - init_overlayContext(); - init_fileSuggestions(); - init_useTerminalSize(); - init_ink2(); - init_analytics(); - init_cwd(); - init_editor(); - init_format(); - init_highlightMatch(); - init_readFileInRange(); - init_FuzzyPicker(); - init_LoadingState(); - import_compiler_runtime326 = __toESM(require_compiler_runtime(), 1); - import_react246 = __toESM(require_react(), 1); - jsx_dev_runtime422 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/ThinkingToggle.tsx -function ThinkingToggle(t0) { - const $2 = import_compiler_runtime327.c(27); - const { - currentValue, - onSelect, - onCancel, - isMidConversation - } = t0; - const exitState = useExitOnCtrlCDWithKeybindings(); - const [confirmationPending, setConfirmationPending] = import_react247.useState(null); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = [{ - value: "true", - label: "Enabled", - description: "Claude will think before responding" - }, { - value: "false", - label: "Disabled", - description: "Claude will respond without extended thinking" - }]; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const options2 = t1; - let t22; - if ($2[1] !== confirmationPending || $2[2] !== onCancel) { - t22 = () => { - if (confirmationPending !== null) { - setConfirmationPending(null); - } else { - onCancel?.(); - } - }; - $2[1] = confirmationPending; - $2[2] = onCancel; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t32 = { - context: "Confirmation" - }; - $2[4] = t32; - } else { - t32 = $2[4]; - } - useKeybinding("confirm:no", t22, t32); - let t4; - if ($2[5] !== confirmationPending || $2[6] !== onSelect) { - t4 = () => { - if (confirmationPending !== null) { - onSelect(confirmationPending); - } - }; - $2[5] = confirmationPending; - $2[6] = onSelect; - $2[7] = t4; - } else { - t4 = $2[7]; - } - const t5 = confirmationPending !== null; - let t6; - if ($2[8] !== t5) { - t6 = { - context: "Confirmation", - isActive: t5 - }; - $2[8] = t5; - $2[9] = t6; - } else { - t6 = $2[9]; - } - useKeybinding("confirm:yes", t4, t6); - let t7; - if ($2[10] !== currentValue || $2[11] !== isMidConversation || $2[12] !== onSelect) { - t7 = function handleSelectChange2(value) { - const selected = value === "true"; - if (isMidConversation && selected !== currentValue) { - setConfirmationPending(selected); - } else { - onSelect(selected); - } - }; - $2[10] = currentValue; - $2[11] = isMidConversation; - $2[12] = onSelect; - $2[13] = t7; - } else { - t7 = $2[13]; - } - const handleSelectChange = t7; - let t8; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedText, { - color: "remember", - bold: true, - children: "Toggle thinking mode" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedText, { - dimColor: true, - children: "Enable or disable thinking for this session." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[14] = t8; - } else { - t8 = $2[14]; - } - let t9; - if ($2[15] !== confirmationPending || $2[16] !== currentValue || $2[17] !== handleSelectChange || $2[18] !== onCancel) { - t9 = /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t8, - confirmationPending !== null ? /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedText, { - color: "warning", - children: "Changing thinking mode mid-conversation will increase latency and may reduce quality. For best results, set this at the start of a session." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedText, { - color: "warning", - children: "Do you want to proceed?" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(Select, { - defaultValue: currentValue ? "true" : "false", - defaultFocusValue: currentValue ? "true" : "false", - options: options2, - onChange: handleSelectChange, - onCancel: onCancel ?? _temp194, - visibleOptionCount: 2 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[15] = confirmationPending; - $2[16] = currentValue; - $2[17] = handleSelectChange; - $2[18] = onCancel; - $2[19] = t9; - } else { - t9 = $2[19]; - } - let t10; - if ($2[20] !== confirmationPending || $2[21] !== exitState.keyName || $2[22] !== exitState.pending) { - t10 = /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(jsx_dev_runtime423.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : confirmationPending !== null ? /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "confirm" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "confirm" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "exit" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[20] = confirmationPending; - $2[21] = exitState.keyName; - $2[22] = exitState.pending; - $2[23] = t10; - } else { - t10 = $2[23]; - } - let t11; - if ($2[24] !== t10 || $2[25] !== t9) { - t11 = /* @__PURE__ */ jsx_dev_runtime423.jsxDEV(Pane, { - color: "permission", - children: [ - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[24] = t10; - $2[25] = t9; - $2[26] = t11; - } else { - t11 = $2[26]; - } - return t11; -} -function _temp194() {} -var import_compiler_runtime327, import_react247, jsx_dev_runtime423; -var init_ThinkingToggle = __esm(() => { - init_useExitOnCtrlCDWithKeybindings(); - init_ink2(); - init_useKeybinding(); - init_ConfigurableShortcutHint(); - init_CustomSelect(); - init_Byline(); - init_KeyboardShortcutHint(); - init_Pane(); - import_compiler_runtime327 = __toESM(require_compiler_runtime(), 1); - import_react247 = __toESM(require_react(), 1); - jsx_dev_runtime423 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/teamDiscovery.ts -function getTeammateStatuses(teamName) { - const teamFile = readTeamFile(teamName); - if (!teamFile) { - return []; - } - const hiddenPaneIds = new Set(teamFile.hiddenPaneIds ?? []); - const statuses = []; - for (const member of teamFile.members) { - if (member.name === "team-lead") { - continue; - } - const isActive = member.isActive !== false; - const status2 = isActive ? "running" : "idle"; - statuses.push({ - name: member.name, - agentId: member.agentId, - agentType: member.agentType, - model: member.model, - prompt: member.prompt, - status: status2, - color: member.color, - tmuxPaneId: member.tmuxPaneId, - cwd: member.cwd, - worktreePath: member.worktreePath, - isHidden: hiddenPaneIds.has(member.tmuxPaneId), - backendType: member.backendType && isPaneBackend(member.backendType) ? member.backendType : undefined, - mode: member.mode - }); - } - return statuses; -} -var init_teamDiscovery = __esm(() => { - init_teamHelpers(); -}); - -// src/components/teams/TeamsDialog.tsx -import { randomUUID as randomUUID37 } from "crypto"; -function TeamsDialog({ - initialTeams, - onDone -}) { - useRegisterOverlay("teams-dialog"); - const setAppState = useSetAppState(); - const firstTeamName = initialTeams?.[0]?.name ?? ""; - const [dialogLevel, setDialogLevel] = import_react248.useState({ - type: "teammateList", - teamName: firstTeamName - }); - const [selectedIndex, setSelectedIndex] = import_react248.useState(0); - const [refreshKey, setRefreshKey] = import_react248.useState(0); - const teammateStatuses = import_react248.useMemo(() => { - return getTeammateStatuses(dialogLevel.teamName); - }, [dialogLevel.teamName, refreshKey]); - useInterval(() => { - setRefreshKey((k4) => k4 + 1); - }, 1000); - const currentTeammate = import_react248.useMemo(() => { - if (dialogLevel.type !== "teammateDetail") - return null; - return teammateStatuses.find((t4) => t4.name === dialogLevel.memberName) ?? null; - }, [dialogLevel, teammateStatuses]); - const isBypassAvailable = useAppState((s4) => s4.toolPermissionContext.isBypassPermissionsModeAvailable); - const goBackToList = () => { - setDialogLevel({ - type: "teammateList", - teamName: dialogLevel.teamName - }); - setSelectedIndex(0); - }; - const handleCycleMode = import_react248.useCallback(() => { - if (dialogLevel.type === "teammateDetail" && currentTeammate) { - cycleTeammateMode(currentTeammate, dialogLevel.teamName, isBypassAvailable); - setRefreshKey((k4) => k4 + 1); - } else if (dialogLevel.type === "teammateList" && teammateStatuses.length > 0) { - cycleAllTeammateModes(teammateStatuses, dialogLevel.teamName, isBypassAvailable); - setRefreshKey((k4) => k4 + 1); - } - }, [dialogLevel, currentTeammate, teammateStatuses, isBypassAvailable]); - useKeybindings({ - "confirm:cycleMode": handleCycleMode - }, { - context: "Confirmation" - }); - use_input_default((input, key2) => { - if (key2.leftArrow) { - if (dialogLevel.type === "teammateDetail") { - goBackToList(); - } - return; - } - if (key2.upArrow || key2.downArrow) { - const maxIndex = getMaxIndex(); - if (key2.upArrow) { - setSelectedIndex((prev) => Math.max(0, prev - 1)); - } else { - setSelectedIndex((prev) => Math.min(maxIndex, prev + 1)); - } - return; - } - if (key2.return) { - if (dialogLevel.type === "teammateList" && teammateStatuses[selectedIndex]) { - setDialogLevel({ - type: "teammateDetail", - teamName: dialogLevel.teamName, - memberName: teammateStatuses[selectedIndex].name - }); - } else if (dialogLevel.type === "teammateDetail" && currentTeammate) { - viewTeammateOutput(currentTeammate.tmuxPaneId, currentTeammate.backendType); - onDone(); - } - return; - } - if (input === "k") { - if (dialogLevel.type === "teammateList" && teammateStatuses[selectedIndex]) { - killTeammate(teammateStatuses[selectedIndex].tmuxPaneId, teammateStatuses[selectedIndex].backendType, dialogLevel.teamName, teammateStatuses[selectedIndex].agentId, teammateStatuses[selectedIndex].name, setAppState).then(() => { - setRefreshKey((k4) => k4 + 1); - setSelectedIndex((prev) => Math.max(0, Math.min(prev, teammateStatuses.length - 2))); - }); - } else if (dialogLevel.type === "teammateDetail" && currentTeammate) { - killTeammate(currentTeammate.tmuxPaneId, currentTeammate.backendType, dialogLevel.teamName, currentTeammate.agentId, currentTeammate.name, setAppState); - goBackToList(); - } - return; - } - if (input === "s") { - if (dialogLevel.type === "teammateList" && teammateStatuses[selectedIndex]) { - const teammate = teammateStatuses[selectedIndex]; - sendShutdownRequestToMailbox(teammate.name, dialogLevel.teamName, "Graceful shutdown requested by team lead"); - } else if (dialogLevel.type === "teammateDetail" && currentTeammate) { - sendShutdownRequestToMailbox(currentTeammate.name, dialogLevel.teamName, "Graceful shutdown requested by team lead"); - goBackToList(); - } - return; - } - if (input === "h") { - const backend = getCachedBackend(); - const teammate = dialogLevel.type === "teammateList" ? teammateStatuses[selectedIndex] : dialogLevel.type === "teammateDetail" ? currentTeammate : null; - if (teammate && backend?.supportsHideShow) { - toggleTeammateVisibility(teammate, dialogLevel.teamName).then(() => { - setRefreshKey((k4) => k4 + 1); - }); - if (dialogLevel.type === "teammateDetail") { - goBackToList(); - } - } - return; - } - if (input === "H" && dialogLevel.type === "teammateList") { - const backend = getCachedBackend(); - if (backend?.supportsHideShow && teammateStatuses.length > 0) { - const anyVisible = teammateStatuses.some((t4) => !t4.isHidden); - Promise.all(teammateStatuses.map((t4) => anyVisible ? hideTeammate(t4, dialogLevel.teamName) : showTeammate(t4, dialogLevel.teamName))).then(() => { - setRefreshKey((k4) => k4 + 1); - }); - } - return; - } - if (input === "p" && dialogLevel.type === "teammateList") { - const idleTeammates = teammateStatuses.filter((t4) => t4.status === "idle"); - if (idleTeammates.length > 0) { - Promise.all(idleTeammates.map((t4) => killTeammate(t4.tmuxPaneId, t4.backendType, dialogLevel.teamName, t4.agentId, t4.name, setAppState))).then(() => { - setRefreshKey((k4) => k4 + 1); - setSelectedIndex((prev) => Math.max(0, Math.min(prev, teammateStatuses.length - idleTeammates.length - 1))); - }); - } - return; - } - }); - function getMaxIndex() { - if (dialogLevel.type === "teammateList") { - return Math.max(0, teammateStatuses.length - 1); - } - return 0; - } - if (dialogLevel.type === "teammateList") { - return /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(TeamDetailView, { - teamName: dialogLevel.teamName, - teammates: teammateStatuses, - selectedIndex, - onCancel: onDone - }, undefined, false, undefined, this); - } - if (dialogLevel.type === "teammateDetail" && currentTeammate) { - return /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(TeammateDetailView, { - teammate: currentTeammate, - teamName: dialogLevel.teamName, - onCancel: goBackToList - }, undefined, false, undefined, this); - } - return null; -} -function TeamDetailView(t0) { - const $2 = import_compiler_runtime328.c(13); - const { - teamName, - teammates, - selectedIndex, - onCancel - } = t0; - const subtitle = `${teammates.length} ${teammates.length === 1 ? "teammate" : "teammates"}`; - const supportsHideShow = getCachedBackend()?.supportsHideShow ?? false; - const cycleModeShortcut = useShortcutDisplay("confirm:cycleMode", "Confirmation", "shift+tab"); - const t1 = `Team ${teamName}`; - let t22; - if ($2[0] !== selectedIndex || $2[1] !== teammates) { - t22 = teammates.length === 0 ? /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: "No teammates" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: teammates.map((teammate, index2) => /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(TeammateListItem, { - teammate, - isSelected: index2 === selectedIndex - }, teammate.agentId, false, undefined, this)) - }, undefined, false, undefined, this); - $2[0] = selectedIndex; - $2[1] = teammates; - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== onCancel || $2[4] !== subtitle || $2[5] !== t1 || $2[6] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(Dialog, { - title: t1, - subtitle, - onCancel, - color: "background", - hideInputGuide: true, - children: t22 - }, undefined, false, undefined, this); - $2[3] = onCancel; - $2[4] = subtitle; - $2[5] = t1; - $2[6] = t22; - $2[7] = t32; - } else { - t32 = $2[7]; - } - let t4; - if ($2[8] !== cycleModeShortcut) { - t4 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedBox_default, { - marginLeft: 1, - children: /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.arrowUp, - "/", - figures_default.arrowDown, - " select \xB7 Enter view \xB7 k kill \xB7 s shutdown \xB7 p prune idle", - supportsHideShow && " \xB7 h hide/show \xB7 H hide/show all", - " \xB7 ", - cycleModeShortcut, - " sync cycle modes for all \xB7 Esc close" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[8] = cycleModeShortcut; - $2[9] = t4; - } else { - t4 = $2[9]; - } - let t5; - if ($2[10] !== t32 || $2[11] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(jsx_dev_runtime424.Fragment, { - children: [ - t32, - t4 - ] - }, undefined, true, undefined, this); - $2[10] = t32; - $2[11] = t4; - $2[12] = t5; - } else { - t5 = $2[12]; - } - return t5; -} -function TeammateListItem(t0) { - const $2 = import_compiler_runtime328.c(21); - const { - teammate, - isSelected - } = t0; - const isIdle = teammate.status === "idle"; - const shouldDim = isIdle && !isSelected; - let modeSymbol; - let t1; - if ($2[0] !== teammate.mode) { - const mode = teammate.mode ? permissionModeFromString(teammate.mode) : "default"; - modeSymbol = permissionModeSymbol(mode); - t1 = getModeColor(mode); - $2[0] = teammate.mode; - $2[1] = modeSymbol; - $2[2] = t1; - } else { - modeSymbol = $2[1]; - t1 = $2[2]; - } - const modeColor = t1; - const t22 = isSelected ? "suggestion" : undefined; - const t32 = isSelected ? figures_default.pointer + " " : " "; - let t4; - if ($2[3] !== teammate.isHidden) { - t4 = teammate.isHidden && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: "[hidden] " - }, undefined, false, undefined, this); - $2[3] = teammate.isHidden; - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] !== isIdle) { - t5 = isIdle && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: "[idle] " - }, undefined, false, undefined, this); - $2[5] = isIdle; - $2[6] = t5; - } else { - t5 = $2[6]; - } - let t6; - if ($2[7] !== modeColor || $2[8] !== modeSymbol) { - t6 = modeSymbol && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - color: modeColor, - children: [ - modeSymbol, - " " - ] - }, undefined, true, undefined, this); - $2[7] = modeColor; - $2[8] = modeSymbol; - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] !== teammate.model) { - t7 = teammate.model && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " (", - teammate.model, - ")" - ] - }, undefined, true, undefined, this); - $2[10] = teammate.model; - $2[11] = t7; - } else { - t7 = $2[11]; - } - let t8; - if ($2[12] !== shouldDim || $2[13] !== t22 || $2[14] !== t32 || $2[15] !== t4 || $2[16] !== t5 || $2[17] !== t6 || $2[18] !== t7 || $2[19] !== teammate.name) { - t8 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - color: t22, - dimColor: shouldDim, - children: [ - t32, - t4, - t5, - t6, - "@", - teammate.name, - t7 - ] - }, undefined, true, undefined, this); - $2[12] = shouldDim; - $2[13] = t22; - $2[14] = t32; - $2[15] = t4; - $2[16] = t5; - $2[17] = t6; - $2[18] = t7; - $2[19] = teammate.name; - $2[20] = t8; - } else { - t8 = $2[20]; - } - return t8; -} -function TeammateDetailView(t0) { - const $2 = import_compiler_runtime328.c(39); - const { - teammate, - teamName, - onCancel - } = t0; - const [promptExpanded, setPromptExpanded] = import_react248.useState(false); - const cycleModeShortcut = useShortcutDisplay("confirm:cycleMode", "Confirmation", "shift+tab"); - const themeColor = teammate.color ? AGENT_COLOR_TO_THEME_COLOR[teammate.color] : undefined; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = []; - $2[0] = t1; - } else { - t1 = $2[0]; - } - const [teammateTasks, setTeammateTasks] = import_react248.useState(t1); - let t22; - let t32; - if ($2[1] !== teamName || $2[2] !== teammate.agentId || $2[3] !== teammate.name) { - t22 = () => { - let cancelled = false; - listTasks(teamName).then((allTasks) => { - if (cancelled) { - return; - } - setTeammateTasks(allTasks.filter((task) => task.owner === teammate.agentId || task.owner === teammate.name)); - }); - return () => { - cancelled = true; - }; - }; - t32 = [teamName, teammate.agentId, teammate.name]; - $2[1] = teamName; - $2[2] = teammate.agentId; - $2[3] = teammate.name; - $2[4] = t22; - $2[5] = t32; - } else { - t22 = $2[4]; - t32 = $2[5]; - } - import_react248.useEffect(t22, t32); - let t4; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t4 = (input) => { - if (input === "p") { - setPromptExpanded(_temp195); - } - }; - $2[6] = t4; - } else { - t4 = $2[6]; - } - use_input_default(t4); - const workingPath = teammate.worktreePath || teammate.cwd; - let subtitleParts; - if ($2[7] !== teammate.model || $2[8] !== teammate.worktreePath || $2[9] !== workingPath) { - subtitleParts = []; - if (teammate.model) { - subtitleParts.push(teammate.model); - } - if (workingPath) { - subtitleParts.push(teammate.worktreePath ? `worktree: ${workingPath}` : workingPath); - } - $2[7] = teammate.model; - $2[8] = teammate.worktreePath; - $2[9] = workingPath; - $2[10] = subtitleParts; - } else { - subtitleParts = $2[10]; - } - const subtitle = subtitleParts.join(" \xB7 ") || undefined; - let modeSymbol; - let t5; - if ($2[11] !== teammate.mode) { - const mode = teammate.mode ? permissionModeFromString(teammate.mode) : "default"; - modeSymbol = permissionModeSymbol(mode); - t5 = getModeColor(mode); - $2[11] = teammate.mode; - $2[12] = modeSymbol; - $2[13] = t5; - } else { - modeSymbol = $2[12]; - t5 = $2[13]; - } - const modeColor = t5; - let t6; - if ($2[14] !== modeColor || $2[15] !== modeSymbol) { - t6 = modeSymbol && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - color: modeColor, - children: [ - modeSymbol, - " " - ] - }, undefined, true, undefined, this); - $2[14] = modeColor; - $2[15] = modeSymbol; - $2[16] = t6; - } else { - t6 = $2[16]; - } - let t7; - if ($2[17] !== teammate.name || $2[18] !== themeColor) { - t7 = themeColor ? /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - color: themeColor, - children: `@${teammate.name}` - }, undefined, false, undefined, this) : `@${teammate.name}`; - $2[17] = teammate.name; - $2[18] = themeColor; - $2[19] = t7; - } else { - t7 = $2[19]; - } - let t8; - if ($2[20] !== t6 || $2[21] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(jsx_dev_runtime424.Fragment, { - children: [ - t6, - t7 - ] - }, undefined, true, undefined, this); - $2[20] = t6; - $2[21] = t7; - $2[22] = t8; - } else { - t8 = $2[22]; - } - const title = t8; - let t9; - if ($2[23] !== teammateTasks) { - t9 = teammateTasks.length > 0 && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - bold: true, - children: "Tasks" - }, undefined, false, undefined, this), - teammateTasks.map(_temp280) - ] - }, undefined, true, undefined, this); - $2[23] = teammateTasks; - $2[24] = t9; - } else { - t9 = $2[24]; - } - let t10; - if ($2[25] !== promptExpanded || $2[26] !== teammate.prompt) { - t10 = teammate.prompt && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - bold: true, - children: "Prompt" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - children: [ - promptExpanded ? teammate.prompt : truncateToWidth(teammate.prompt, 80), - stringWidth(teammate.prompt) > 80 && !promptExpanded && /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: " (p to expand)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[25] = promptExpanded; - $2[26] = teammate.prompt; - $2[27] = t10; - } else { - t10 = $2[27]; - } - let t11; - if ($2[28] !== onCancel || $2[29] !== subtitle || $2[30] !== t10 || $2[31] !== t9 || $2[32] !== title) { - t11 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(Dialog, { - title, - subtitle, - onCancel, - color: "background", - hideInputGuide: true, - children: [ - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[28] = onCancel; - $2[29] = subtitle; - $2[30] = t10; - $2[31] = t9; - $2[32] = title; - $2[33] = t11; - } else { - t11 = $2[33]; - } - let t12; - if ($2[34] !== cycleModeShortcut) { - t12 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedBox_default, { - marginLeft: 1, - children: /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.arrowLeft, - " back \xB7 Esc close \xB7 k kill \xB7 s shutdown", - getCachedBackend()?.supportsHideShow && " \xB7 h hide/show", - " \xB7 ", - cycleModeShortcut, - " cycle mode" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[34] = cycleModeShortcut; - $2[35] = t12; - } else { - t12 = $2[35]; - } - let t13; - if ($2[36] !== t11 || $2[37] !== t12) { - t13 = /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(jsx_dev_runtime424.Fragment, { - children: [ - t11, - t12 - ] - }, undefined, true, undefined, this); - $2[36] = t11; - $2[37] = t12; - $2[38] = t13; - } else { - t13 = $2[38]; - } - return t13; -} -function _temp280(task_0) { - return /* @__PURE__ */ jsx_dev_runtime424.jsxDEV(ThemedText, { - color: task_0.status === "completed" ? "success" : undefined, - children: [ - task_0.status === "completed" ? figures_default.tick : "\u25FC", - " ", - task_0.subject - ] - }, task_0.id, true, undefined, this); -} -function _temp195(prev) { - return !prev; -} -async function killTeammate(paneId, backendType, teamName, teammateId, teammateName, setAppState) { - if (backendType) { - try { - await ensureBackendsRegistered(); - await getBackendByType(backendType).killPane(paneId, !isInsideTmuxSync()); - } catch (error46) { - logForDebugging(`[TeamsDialog] Failed to kill pane ${paneId}: ${error46}`); - } - } else { - logForDebugging(`[TeamsDialog] Skipping pane kill for ${paneId}: no backendType recorded`); - } - removeMemberFromTeam(teamName, paneId); - const { - notificationMessage - } = await unassignTeammateTasks(teamName, teammateId, teammateName, "terminated"); - setAppState((prev) => { - if (!prev.teamContext?.teammates) - return prev; - if (!(teammateId in prev.teamContext.teammates)) - return prev; - const { - [teammateId]: _, - ...remainingTeammates - } = prev.teamContext.teammates; - return { - ...prev, - teamContext: { - ...prev.teamContext, - teammates: remainingTeammates - }, - inbox: { - messages: [...prev.inbox.messages, { - id: randomUUID37(), - from: "system", - text: jsonStringify({ - type: "teammate_terminated", - message: notificationMessage - }), - timestamp: new Date().toISOString(), - status: "pending" - }] - } - }; - }); - logForDebugging(`[TeamsDialog] Removed ${teammateId} from teamContext`); -} -async function viewTeammateOutput(paneId, backendType) { - if (backendType === "iterm2") { - await execFileNoThrow(IT2_COMMAND, ["session", "focus", "-s", paneId]); - } else { - const args = isInsideTmuxSync() ? ["select-pane", "-t", paneId] : ["-L", getSwarmSocketName(), "select-pane", "-t", paneId]; - await execFileNoThrow(TMUX_COMMAND2, args); - } -} -async function toggleTeammateVisibility(teammate, teamName) { - if (teammate.isHidden) { - await showTeammate(teammate, teamName); - } else { - await hideTeammate(teammate, teamName); - } -} -async function hideTeammate(teammate, teamName) {} -async function showTeammate(teammate, teamName) {} -function sendModeChangeToTeammate(teammateName, teamName, targetMode) { - setMemberMode(teamName, teammateName, targetMode); - const message = createModeSetRequestMessage({ - mode: targetMode, - from: "team-lead" - }); - writeToMailbox(teammateName, { - from: "team-lead", - text: jsonStringify(message), - timestamp: new Date().toISOString() - }, teamName); - logForDebugging(`[TeamsDialog] Sent mode change to ${teammateName}: ${targetMode}`); -} -function cycleTeammateMode(teammate, teamName, isBypassAvailable) { - const currentMode = teammate.mode ? permissionModeFromString(teammate.mode) : "default"; - const context7 = { - ...getEmptyToolPermissionContext(), - mode: currentMode, - isBypassPermissionsModeAvailable: isBypassAvailable - }; - const nextMode = getNextPermissionMode(context7); - sendModeChangeToTeammate(teammate.name, teamName, nextMode); -} -function cycleAllTeammateModes(teammates, teamName, isBypassAvailable) { - if (teammates.length === 0) - return; - const modes = teammates.map((t4) => t4.mode ? permissionModeFromString(t4.mode) : "default"); - const allSame = modes.every((m4) => m4 === modes[0]); - const targetMode = !allSame ? "default" : getNextPermissionMode({ - ...getEmptyToolPermissionContext(), - mode: modes[0] ?? "default", - isBypassPermissionsModeAvailable: isBypassAvailable - }); - const modeUpdates = teammates.map((t4) => ({ - memberName: t4.name, - mode: targetMode - })); - setMultipleMemberModes(teamName, modeUpdates); - for (const teammate of teammates) { - const message = createModeSetRequestMessage({ - mode: targetMode, - from: "team-lead" - }); - writeToMailbox(teammate.name, { - from: "team-lead", - text: jsonStringify(message), - timestamp: new Date().toISOString() - }, teamName); - } - logForDebugging(`[TeamsDialog] Sent mode change to all ${teammates.length} teammates: ${targetMode}`); -} -var import_compiler_runtime328, import_react248, jsx_dev_runtime424; -var init_TeamsDialog = __esm(() => { - init_figures(); - init_dist4(); - init_overlayContext(); - init_stringWidth(); - init_ink2(); - init_useKeybinding(); - init_useShortcutDisplay(); - init_AppState(); - init_Tool(); - init_agentColorManager(); - init_debug(); - init_execFileNoThrow(); - init_format(); - init_getNextPermissionMode(); - init_PermissionMode(); - init_slowOperations(); - init_detection(); - init_registry(); - init_teamHelpers(); - init_tasks(); - init_teamDiscovery(); - init_teammateMailbox(); - init_Dialog(); - init_ThemedText(); - import_compiler_runtime328 = __toESM(require_compiler_runtime(), 1); - import_react248 = __toESM(require_react(), 1); - jsx_dev_runtime424 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/vim/motions.ts -function resolveMotion(key2, cursor, count4) { - let result = cursor; - for (let i6 = 0;i6 < count4; i6++) { - const next2 = applySingleMotion(key2, result); - if (next2.equals(result)) - break; - result = next2; - } - return result; -} -function applySingleMotion(key2, cursor) { - switch (key2) { - case "h": - return cursor.left(); - case "l": - return cursor.right(); - case "j": - return cursor.downLogicalLine(); - case "k": - return cursor.upLogicalLine(); - case "gj": - return cursor.down(); - case "gk": - return cursor.up(); - case "w": - return cursor.nextVimWord(); - case "b": - return cursor.prevVimWord(); - case "e": - return cursor.endOfVimWord(); - case "W": - return cursor.nextWORD(); - case "B": - return cursor.prevWORD(); - case "E": - return cursor.endOfWORD(); - case "0": - return cursor.startOfLogicalLine(); - case "^": - return cursor.firstNonBlankInLogicalLine(); - case "$": - return cursor.endOfLogicalLine(); - case "G": - return cursor.startOfLastLine(); - default: - return cursor; - } -} -function isInclusiveMotion(key2) { - return "eE$".includes(key2); -} -function isLinewiseMotion(key2) { - return "jkG".includes(key2) || key2 === "gg"; -} - -// src/vim/textObjects.ts -function findTextObject(text, offset, objectType2, isInner) { - if (objectType2 === "w") - return findWordObject(text, offset, isInner, isVimWordChar); - if (objectType2 === "W") - return findWordObject(text, offset, isInner, (ch2) => !isVimWhitespace(ch2)); - const pair = PAIRS[objectType2]; - if (pair) { - const [open18, close] = pair; - return open18 === close ? findQuoteObject(text, offset, open18, isInner) : findBracketObject(text, offset, open18, close, isInner); - } - return null; -} -function findWordObject(text, offset, isInner, isWordChar) { - const graphemes = []; - for (const { segment, index: index2 } of getGraphemeSegmenter().segment(text)) { - graphemes.push({ segment, index: index2 }); - } - let graphemeIdx = graphemes.length - 1; - for (let i6 = 0;i6 < graphemes.length; i6++) { - const g4 = graphemes[i6]; - const nextStart = i6 + 1 < graphemes.length ? graphemes[i6 + 1].index : text.length; - if (offset >= g4.index && offset < nextStart) { - graphemeIdx = i6; - break; - } - } - const graphemeAt = (idx) => graphemes[idx]?.segment ?? ""; - const offsetAt = (idx) => idx < graphemes.length ? graphemes[idx].index : text.length; - const isWs = (idx) => isVimWhitespace(graphemeAt(idx)); - const isWord = (idx) => isWordChar(graphemeAt(idx)); - const isPunct = (idx) => isVimPunctuation(graphemeAt(idx)); - let startIdx = graphemeIdx; - let endIdx = graphemeIdx; - if (isWord(graphemeIdx)) { - while (startIdx > 0 && isWord(startIdx - 1)) - startIdx--; - while (endIdx < graphemes.length && isWord(endIdx)) - endIdx++; - } else if (isWs(graphemeIdx)) { - while (startIdx > 0 && isWs(startIdx - 1)) - startIdx--; - while (endIdx < graphemes.length && isWs(endIdx)) - endIdx++; - return { start: offsetAt(startIdx), end: offsetAt(endIdx) }; - } else if (isPunct(graphemeIdx)) { - while (startIdx > 0 && isPunct(startIdx - 1)) - startIdx--; - while (endIdx < graphemes.length && isPunct(endIdx)) - endIdx++; - } - if (!isInner) { - if (endIdx < graphemes.length && isWs(endIdx)) { - while (endIdx < graphemes.length && isWs(endIdx)) - endIdx++; - } else if (startIdx > 0 && isWs(startIdx - 1)) { - while (startIdx > 0 && isWs(startIdx - 1)) - startIdx--; - } - } - return { start: offsetAt(startIdx), end: offsetAt(endIdx) }; -} -function findQuoteObject(text, offset, quote2, isInner) { - const lineStart = text.lastIndexOf(` -`, offset - 1) + 1; - const lineEnd = text.indexOf(` -`, offset); - const effectiveEnd = lineEnd === -1 ? text.length : lineEnd; - const line = text.slice(lineStart, effectiveEnd); - const posInLine = offset - lineStart; - const positions = []; - for (let i6 = 0;i6 < line.length; i6++) { - if (line[i6] === quote2) - positions.push(i6); - } - for (let i6 = 0;i6 < positions.length - 1; i6 += 2) { - const qs = positions[i6]; - const qe = positions[i6 + 1]; - if (qs <= posInLine && posInLine <= qe) { - return isInner ? { start: lineStart + qs + 1, end: lineStart + qe } : { start: lineStart + qs, end: lineStart + qe + 1 }; - } - } - return null; -} -function findBracketObject(text, offset, open18, close, isInner) { - let depth = 0; - let start = -1; - for (let i6 = offset;i6 >= 0; i6--) { - if (text[i6] === close && i6 !== offset) - depth++; - else if (text[i6] === open18) { - if (depth === 0) { - start = i6; - break; - } - depth--; - } - } - if (start === -1) - return null; - depth = 0; - let end = -1; - for (let i6 = start + 1;i6 < text.length; i6++) { - if (text[i6] === open18) - depth++; - else if (text[i6] === close) { - if (depth === 0) { - end = i6; - break; - } - depth--; - } - } - if (end === -1) - return null; - return isInner ? { start: start + 1, end } : { start, end: end + 1 }; -} -var PAIRS; -var init_textObjects = __esm(() => { - init_Cursor(); - init_intl(); - PAIRS = { - "(": ["(", ")"], - ")": ["(", ")"], - b: ["(", ")"], - "[": ["[", "]"], - "]": ["[", "]"], - "{": ["{", "}"], - "}": ["{", "}"], - B: ["{", "}"], - "<": ["<", ">"], - ">": ["<", ">"], - '"': ['"', '"'], - "'": ["'", "'"], - "`": ["`", "`"] - }; -}); - -// src/vim/operators.ts -function executeOperatorMotion(op, motion, count4, ctx) { - const target = resolveMotion(motion, ctx.cursor, count4); - if (target.equals(ctx.cursor)) - return; - const range = getOperatorRange(ctx.cursor, target, motion, op, count4); - applyOperator(op, range.from, range.to, ctx, range.linewise); - ctx.recordChange({ type: "operator", op, motion, count: count4 }); -} -function executeOperatorFind(op, findType, char, count4, ctx) { - const targetOffset = ctx.cursor.findCharacter(char, findType, count4); - if (targetOffset === null) - return; - const target = new Cursor(ctx.cursor.measuredText, targetOffset); - const range = getOperatorRangeForFind(ctx.cursor, target, findType); - applyOperator(op, range.from, range.to, ctx); - ctx.setLastFind(findType, char); - ctx.recordChange({ type: "operatorFind", op, find: findType, char, count: count4 }); -} -function executeOperatorTextObj(op, scope, objType, count4, ctx) { - const range = findTextObject(ctx.text, ctx.cursor.offset, objType, scope === "inner"); - if (!range) - return; - applyOperator(op, range.start, range.end, ctx); - ctx.recordChange({ type: "operatorTextObj", op, objType, scope, count: count4 }); -} -function executeLineOp(op, count4, ctx) { - const text = ctx.text; - const lines2 = text.split(` -`); - const currentLine = countCharInString(text.slice(0, ctx.cursor.offset), ` -`); - const linesToAffect = Math.min(count4, lines2.length - currentLine); - const lineStart = ctx.cursor.startOfLogicalLine().offset; - let lineEnd = lineStart; - for (let i6 = 0;i6 < linesToAffect; i6++) { - const nextNewline = text.indexOf(` -`, lineEnd); - lineEnd = nextNewline === -1 ? text.length : nextNewline + 1; - } - let content = text.slice(lineStart, lineEnd); - if (!content.endsWith(` -`)) { - content = content + ` -`; - } - ctx.setRegister(content, true); - if (op === "yank") { - ctx.setOffset(lineStart); - } else if (op === "delete") { - let deleteStart = lineStart; - const deleteEnd = lineEnd; - if (deleteEnd === text.length && deleteStart > 0 && text[deleteStart - 1] === ` -`) { - deleteStart -= 1; - } - const newText = text.slice(0, deleteStart) + text.slice(deleteEnd); - ctx.setText(newText || ""); - const maxOff = Math.max(0, newText.length - (lastGrapheme(newText).length || 1)); - ctx.setOffset(Math.min(deleteStart, maxOff)); - } else if (op === "change") { - if (lines2.length === 1) { - ctx.setText(""); - ctx.enterInsert(0); - } else { - const beforeLines = lines2.slice(0, currentLine); - const afterLines = lines2.slice(currentLine + linesToAffect); - const newText = [...beforeLines, "", ...afterLines].join(` -`); - ctx.setText(newText); - ctx.enterInsert(lineStart); - } - } - ctx.recordChange({ type: "operator", op, motion: op[0], count: count4 }); -} -function executeX(count4, ctx) { - const from = ctx.cursor.offset; - if (from >= ctx.text.length) - return; - let endCursor = ctx.cursor; - for (let i6 = 0;i6 < count4 && !endCursor.isAtEnd(); i6++) { - endCursor = endCursor.right(); - } - const to = endCursor.offset; - const deleted = ctx.text.slice(from, to); - const newText = ctx.text.slice(0, from) + ctx.text.slice(to); - ctx.setRegister(deleted, false); - ctx.setText(newText); - const maxOff = Math.max(0, newText.length - (lastGrapheme(newText).length || 1)); - ctx.setOffset(Math.min(from, maxOff)); - ctx.recordChange({ type: "x", count: count4 }); -} -function executeReplace(char, count4, ctx) { - let offset = ctx.cursor.offset; - let newText = ctx.text; - for (let i6 = 0;i6 < count4 && offset < newText.length; i6++) { - const graphemeLen = firstGrapheme(newText.slice(offset)).length || 1; - newText = newText.slice(0, offset) + char + newText.slice(offset + graphemeLen); - offset += char.length; - } - ctx.setText(newText); - ctx.setOffset(Math.max(0, offset - char.length)); - ctx.recordChange({ type: "replace", char, count: count4 }); -} -function executeToggleCase(count4, ctx) { - const startOffset = ctx.cursor.offset; - if (startOffset >= ctx.text.length) - return; - let newText = ctx.text; - let offset = startOffset; - let toggled = 0; - while (offset < newText.length && toggled < count4) { - const grapheme = firstGrapheme(newText.slice(offset)); - const graphemeLen = grapheme.length; - const toggledGrapheme = grapheme === grapheme.toUpperCase() ? grapheme.toLowerCase() : grapheme.toUpperCase(); - newText = newText.slice(0, offset) + toggledGrapheme + newText.slice(offset + graphemeLen); - offset += toggledGrapheme.length; - toggled++; - } - ctx.setText(newText); - ctx.setOffset(offset); - ctx.recordChange({ type: "toggleCase", count: count4 }); -} -function executeJoin(count4, ctx) { - const text = ctx.text; - const lines2 = text.split(` -`); - const { line: currentLine } = ctx.cursor.getPosition(); - if (currentLine >= lines2.length - 1) - return; - const linesToJoin = Math.min(count4, lines2.length - currentLine - 1); - let joinedLine = lines2[currentLine]; - const cursorPos = joinedLine.length; - for (let i6 = 1;i6 <= linesToJoin; i6++) { - const nextLine = (lines2[currentLine + i6] ?? "").trimStart(); - if (nextLine.length > 0) { - if (!joinedLine.endsWith(" ") && joinedLine.length > 0) { - joinedLine += " "; - } - joinedLine += nextLine; - } - } - const newLines = [ - ...lines2.slice(0, currentLine), - joinedLine, - ...lines2.slice(currentLine + linesToJoin + 1) - ]; - const newText = newLines.join(` -`); - ctx.setText(newText); - ctx.setOffset(getLineStartOffset(newLines, currentLine) + cursorPos); - ctx.recordChange({ type: "join", count: count4 }); -} -function executePaste(after, count4, ctx) { - const register2 = ctx.getRegister(); - if (!register2) - return; - const isLinewise = register2.endsWith(` -`); - const content = isLinewise ? register2.slice(0, -1) : register2; - if (isLinewise) { - const text = ctx.text; - const lines2 = text.split(` -`); - const { line: currentLine } = ctx.cursor.getPosition(); - const insertLine = after ? currentLine + 1 : currentLine; - const contentLines = content.split(` -`); - const repeatedLines = []; - for (let i6 = 0;i6 < count4; i6++) { - repeatedLines.push(...contentLines); - } - const newLines = [ - ...lines2.slice(0, insertLine), - ...repeatedLines, - ...lines2.slice(insertLine) - ]; - const newText = newLines.join(` -`); - ctx.setText(newText); - ctx.setOffset(getLineStartOffset(newLines, insertLine)); - } else { - const textToInsert = content.repeat(count4); - const insertPoint = after && ctx.cursor.offset < ctx.text.length ? ctx.cursor.measuredText.nextOffset(ctx.cursor.offset) : ctx.cursor.offset; - const newText = ctx.text.slice(0, insertPoint) + textToInsert + ctx.text.slice(insertPoint); - const lastGr = lastGrapheme(textToInsert); - const newOffset = insertPoint + textToInsert.length - (lastGr.length || 1); - ctx.setText(newText); - ctx.setOffset(Math.max(insertPoint, newOffset)); - } -} -function executeIndent(dir, count4, ctx) { - const text = ctx.text; - const lines2 = text.split(` -`); - const { line: currentLine } = ctx.cursor.getPosition(); - const linesToAffect = Math.min(count4, lines2.length - currentLine); - const indent = " "; - for (let i6 = 0;i6 < linesToAffect; i6++) { - const lineIdx = currentLine + i6; - const line = lines2[lineIdx] ?? ""; - if (dir === ">") { - lines2[lineIdx] = indent + line; - } else if (line.startsWith(indent)) { - lines2[lineIdx] = line.slice(indent.length); - } else if (line.startsWith("\t")) { - lines2[lineIdx] = line.slice(1); - } else { - let removed = 0; - let idx = 0; - while (idx < line.length && removed < indent.length && /\s/.test(line[idx])) { - removed++; - idx++; - } - lines2[lineIdx] = line.slice(idx); - } - } - const newText = lines2.join(` -`); - const currentLineText = lines2[currentLine] ?? ""; - const firstNonBlank = (currentLineText.match(/^\s*/)?.[0] ?? "").length; - ctx.setText(newText); - ctx.setOffset(getLineStartOffset(lines2, currentLine) + firstNonBlank); - ctx.recordChange({ type: "indent", dir, count: count4 }); -} -function executeOpenLine(direction, ctx) { - const text = ctx.text; - const lines2 = text.split(` -`); - const { line: currentLine } = ctx.cursor.getPosition(); - const insertLine = direction === "below" ? currentLine + 1 : currentLine; - const newLines = [ - ...lines2.slice(0, insertLine), - "", - ...lines2.slice(insertLine) - ]; - const newText = newLines.join(` -`); - ctx.setText(newText); - ctx.enterInsert(getLineStartOffset(newLines, insertLine)); - ctx.recordChange({ type: "openLine", direction }); -} -function getLineStartOffset(lines2, lineIndex) { - return lines2.slice(0, lineIndex).join(` -`).length + (lineIndex > 0 ? 1 : 0); -} -function getOperatorRange(cursor, target, motion, op, count4) { - let from = Math.min(cursor.offset, target.offset); - let to = Math.max(cursor.offset, target.offset); - let linewise = false; - if (op === "change" && (motion === "w" || motion === "W")) { - let wordCursor = cursor; - for (let i6 = 0;i6 < count4 - 1; i6++) { - wordCursor = motion === "w" ? wordCursor.nextVimWord() : wordCursor.nextWORD(); - } - const wordEnd = motion === "w" ? wordCursor.endOfVimWord() : wordCursor.endOfWORD(); - to = cursor.measuredText.nextOffset(wordEnd.offset); - } else if (isLinewiseMotion(motion)) { - linewise = true; - const text = cursor.text; - const nextNewline = text.indexOf(` -`, to); - if (nextNewline === -1) { - to = text.length; - if (from > 0 && text[from - 1] === ` -`) { - from -= 1; - } - } else { - to = nextNewline + 1; - } - } else if (isInclusiveMotion(motion) && cursor.offset <= target.offset) { - to = cursor.measuredText.nextOffset(to); - } - from = cursor.snapOutOfImageRef(from, "start"); - to = cursor.snapOutOfImageRef(to, "end"); - return { from, to, linewise }; -} -function getOperatorRangeForFind(cursor, target, _findType) { - const from = Math.min(cursor.offset, target.offset); - const maxOffset = Math.max(cursor.offset, target.offset); - const to = cursor.measuredText.nextOffset(maxOffset); - return { from, to }; -} -function applyOperator(op, from, to, ctx, linewise = false) { - let content = ctx.text.slice(from, to); - if (linewise && !content.endsWith(` -`)) { - content = content + ` -`; - } - ctx.setRegister(content, linewise); - if (op === "yank") { - ctx.setOffset(from); - } else if (op === "delete") { - const newText = ctx.text.slice(0, from) + ctx.text.slice(to); - ctx.setText(newText); - const maxOff = Math.max(0, newText.length - (lastGrapheme(newText).length || 1)); - ctx.setOffset(Math.min(from, maxOff)); - } else if (op === "change") { - const newText = ctx.text.slice(0, from) + ctx.text.slice(to); - ctx.setText(newText); - ctx.enterInsert(from); - } -} -function executeOperatorG(op, count4, ctx) { - const target = count4 === 1 ? ctx.cursor.startOfLastLine() : ctx.cursor.goToLine(count4); - if (target.equals(ctx.cursor)) - return; - const range = getOperatorRange(ctx.cursor, target, "G", op, count4); - applyOperator(op, range.from, range.to, ctx, range.linewise); - ctx.recordChange({ type: "operator", op, motion: "G", count: count4 }); -} -function executeOperatorGg(op, count4, ctx) { - const target = count4 === 1 ? ctx.cursor.startOfFirstLine() : ctx.cursor.goToLine(count4); - if (target.equals(ctx.cursor)) - return; - const range = getOperatorRange(ctx.cursor, target, "gg", op, count4); - applyOperator(op, range.from, range.to, ctx, range.linewise); - ctx.recordChange({ type: "operator", op, motion: "gg", count: count4 }); -} -var init_operators = __esm(() => { - init_Cursor(); - init_intl(); - init_stringUtils(); - init_textObjects(); -}); - -// src/vim/types.ts -function isOperatorKey(key2) { - return key2 in OPERATORS; -} -function isTextObjScopeKey(key2) { - return key2 in TEXT_OBJ_SCOPES; -} -function createInitialVimState() { - return { mode: "INSERT", insertedText: "" }; -} -function createInitialPersistentState() { - return { - lastChange: null, - lastFind: null, - register: "", - registerIsLinewise: false - }; -} -var OPERATORS, SIMPLE_MOTIONS, FIND_KEYS, TEXT_OBJ_SCOPES, TEXT_OBJ_TYPES, MAX_VIM_COUNT = 1e4; -var init_types26 = __esm(() => { - OPERATORS = { - d: "delete", - c: "change", - y: "yank" - }; - SIMPLE_MOTIONS = new Set([ - "h", - "l", - "j", - "k", - "w", - "b", - "e", - "W", - "B", - "E", - "0", - "^", - "$" - ]); - FIND_KEYS = new Set(["f", "F", "t", "T"]); - TEXT_OBJ_SCOPES = { - i: "inner", - a: "around" - }; - TEXT_OBJ_TYPES = new Set([ - "w", - "W", - '"', - "'", - "`", - "(", - ")", - "b", - "[", - "]", - "{", - "}", - "B", - "<", - ">" - ]); -}); - -// src/vim/transitions.ts -function transition(state4, input, ctx) { - switch (state4.type) { - case "idle": - return fromIdle(input, ctx); - case "count": - return fromCount(state4, input, ctx); - case "operator": - return fromOperator(state4, input, ctx); - case "operatorCount": - return fromOperatorCount(state4, input, ctx); - case "operatorFind": - return fromOperatorFind(state4, input, ctx); - case "operatorTextObj": - return fromOperatorTextObj(state4, input, ctx); - case "find": - return fromFind(state4, input, ctx); - case "g": - return fromG(state4, input, ctx); - case "operatorG": - return fromOperatorG(state4, input, ctx); - case "replace": - return fromReplace(state4, input, ctx); - case "indent": - return fromIndent(state4, input, ctx); - } -} -function handleNormalInput(input, count4, ctx) { - if (isOperatorKey(input)) { - return { next: { type: "operator", op: OPERATORS[input], count: count4 } }; - } - if (SIMPLE_MOTIONS.has(input)) { - return { - execute: () => { - const target = resolveMotion(input, ctx.cursor, count4); - ctx.setOffset(target.offset); - } - }; - } - if (FIND_KEYS.has(input)) { - return { next: { type: "find", find: input, count: count4 } }; - } - if (input === "g") - return { next: { type: "g", count: count4 } }; - if (input === "r") - return { next: { type: "replace", count: count4 } }; - if (input === ">" || input === "<") { - return { next: { type: "indent", dir: input, count: count4 } }; - } - if (input === "~") { - return { execute: () => executeToggleCase(count4, ctx) }; - } - if (input === "x") { - return { execute: () => executeX(count4, ctx) }; - } - if (input === "J") { - return { execute: () => executeJoin(count4, ctx) }; - } - if (input === "p" || input === "P") { - return { execute: () => executePaste(input === "p", count4, ctx) }; - } - if (input === "D") { - return { execute: () => executeOperatorMotion("delete", "$", 1, ctx) }; - } - if (input === "C") { - return { execute: () => executeOperatorMotion("change", "$", 1, ctx) }; - } - if (input === "Y") { - return { execute: () => executeLineOp("yank", count4, ctx) }; - } - if (input === "G") { - return { - execute: () => { - if (count4 === 1) { - ctx.setOffset(ctx.cursor.startOfLastLine().offset); - } else { - ctx.setOffset(ctx.cursor.goToLine(count4).offset); - } - } - }; - } - if (input === ".") { - return { execute: () => ctx.onDotRepeat?.() }; - } - if (input === ";" || input === ",") { - return { execute: () => executeRepeatFind(input === ",", count4, ctx) }; - } - if (input === "u") { - return { execute: () => ctx.onUndo?.() }; - } - if (input === "i") { - return { execute: () => ctx.enterInsert(ctx.cursor.offset) }; - } - if (input === "I") { - return { - execute: () => ctx.enterInsert(ctx.cursor.firstNonBlankInLogicalLine().offset) - }; - } - if (input === "a") { - return { - execute: () => { - const newOffset = ctx.cursor.isAtEnd() ? ctx.cursor.offset : ctx.cursor.right().offset; - ctx.enterInsert(newOffset); - } - }; - } - if (input === "A") { - return { - execute: () => ctx.enterInsert(ctx.cursor.endOfLogicalLine().offset) - }; - } - if (input === "o") { - return { execute: () => executeOpenLine("below", ctx) }; - } - if (input === "O") { - return { execute: () => executeOpenLine("above", ctx) }; - } - return null; -} -function handleOperatorInput(op, count4, input, ctx) { - if (isTextObjScopeKey(input)) { - return { - next: { - type: "operatorTextObj", - op, - count: count4, - scope: TEXT_OBJ_SCOPES[input] - } - }; - } - if (FIND_KEYS.has(input)) { - return { - next: { type: "operatorFind", op, count: count4, find: input } - }; - } - if (SIMPLE_MOTIONS.has(input)) { - return { execute: () => executeOperatorMotion(op, input, count4, ctx) }; - } - if (input === "G") { - return { execute: () => executeOperatorG(op, count4, ctx) }; - } - if (input === "g") { - return { next: { type: "operatorG", op, count: count4 } }; - } - return null; -} -function fromIdle(input, ctx) { - if (/[1-9]/.test(input)) { - return { next: { type: "count", digits: input } }; - } - if (input === "0") { - return { - execute: () => ctx.setOffset(ctx.cursor.startOfLogicalLine().offset) - }; - } - const result = handleNormalInput(input, 1, ctx); - if (result) - return result; - return {}; -} -function fromCount(state4, input, ctx) { - if (/[0-9]/.test(input)) { - const newDigits = state4.digits + input; - const count5 = Math.min(parseInt(newDigits, 10), MAX_VIM_COUNT); - return { next: { type: "count", digits: String(count5) } }; - } - const count4 = parseInt(state4.digits, 10); - const result = handleNormalInput(input, count4, ctx); - if (result) - return result; - return { next: { type: "idle" } }; -} -function fromOperator(state4, input, ctx) { - if (input === state4.op[0]) { - return { execute: () => executeLineOp(state4.op, state4.count, ctx) }; - } - if (/[0-9]/.test(input)) { - return { - next: { - type: "operatorCount", - op: state4.op, - count: state4.count, - digits: input - } - }; - } - const result = handleOperatorInput(state4.op, state4.count, input, ctx); - if (result) - return result; - return { next: { type: "idle" } }; -} -function fromOperatorCount(state4, input, ctx) { - if (/[0-9]/.test(input)) { - const newDigits = state4.digits + input; - const parsedDigits = Math.min(parseInt(newDigits, 10), MAX_VIM_COUNT); - return { next: { ...state4, digits: String(parsedDigits) } }; - } - const motionCount = parseInt(state4.digits, 10); - const effectiveCount = state4.count * motionCount; - const result = handleOperatorInput(state4.op, effectiveCount, input, ctx); - if (result) - return result; - return { next: { type: "idle" } }; -} -function fromOperatorFind(state4, input, ctx) { - return { - execute: () => executeOperatorFind(state4.op, state4.find, input, state4.count, ctx) - }; -} -function fromOperatorTextObj(state4, input, ctx) { - if (TEXT_OBJ_TYPES.has(input)) { - return { - execute: () => executeOperatorTextObj(state4.op, state4.scope, input, state4.count, ctx) - }; - } - return { next: { type: "idle" } }; -} -function fromFind(state4, input, ctx) { - return { - execute: () => { - const result = ctx.cursor.findCharacter(input, state4.find, state4.count); - if (result !== null) { - ctx.setOffset(result); - ctx.setLastFind(state4.find, input); - } - } - }; -} -function fromG(state4, input, ctx) { - if (input === "j" || input === "k") { - return { - execute: () => { - const target = resolveMotion(`g${input}`, ctx.cursor, state4.count); - ctx.setOffset(target.offset); - } - }; - } - if (input === "g") { - if (state4.count > 1) { - return { - execute: () => { - const lines2 = ctx.text.split(` -`); - const targetLine = Math.min(state4.count - 1, lines2.length - 1); - let offset = 0; - for (let i6 = 0;i6 < targetLine; i6++) { - offset += (lines2[i6]?.length ?? 0) + 1; - } - ctx.setOffset(offset); - } - }; - } - return { - execute: () => ctx.setOffset(ctx.cursor.startOfFirstLine().offset) - }; - } - return { next: { type: "idle" } }; -} -function fromOperatorG(state4, input, ctx) { - if (input === "j" || input === "k") { - return { - execute: () => executeOperatorMotion(state4.op, `g${input}`, state4.count, ctx) - }; - } - if (input === "g") { - return { execute: () => executeOperatorGg(state4.op, state4.count, ctx) }; - } - return { next: { type: "idle" } }; -} -function fromReplace(state4, input, ctx) { - if (input === "") - return { next: { type: "idle" } }; - return { execute: () => executeReplace(input, state4.count, ctx) }; -} -function fromIndent(state4, input, ctx) { - if (input === state4.dir) { - return { execute: () => executeIndent(state4.dir, state4.count, ctx) }; - } - return { next: { type: "idle" } }; -} -function executeRepeatFind(reverse, count4, ctx) { - const lastFind = ctx.getLastFind(); - if (!lastFind) - return; - let findType = lastFind.type; - if (reverse) { - const flipMap = { - f: "F", - F: "f", - t: "T", - T: "t" - }; - findType = flipMap[findType]; - } - const result = ctx.cursor.findCharacter(lastFind.char, findType, count4); - if (result !== null) { - ctx.setOffset(result); - } -} -var init_transitions = __esm(() => { - init_operators(); - init_types26(); -}); - -// src/hooks/useVimInput.ts -function useVimInput(props) { - const vimStateRef = import_react249.default.useRef(createInitialVimState()); - const [mode, setMode] = import_react249.useState("INSERT"); - const persistentRef = import_react249.default.useRef(createInitialPersistentState()); - const textInput = useTextInput({ ...props, inputFilter: undefined }); - const { onModeChange, inputFilter } = props; - const switchToInsertMode = import_react249.useCallback((offset) => { - if (offset !== undefined) { - textInput.setOffset(offset); - } - vimStateRef.current = { mode: "INSERT", insertedText: "" }; - setMode("INSERT"); - onModeChange?.("INSERT"); - }, [textInput, onModeChange]); - const switchToNormalMode = import_react249.useCallback(() => { - const current = vimStateRef.current; - if (current.mode === "INSERT" && current.insertedText) { - persistentRef.current.lastChange = { - type: "insert", - text: current.insertedText - }; - } - const offset = textInput.offset; - if (offset > 0 && props.value[offset - 1] !== ` -`) { - textInput.setOffset(offset - 1); - } - vimStateRef.current = { mode: "NORMAL", command: { type: "idle" } }; - setMode("NORMAL"); - onModeChange?.("NORMAL"); - }, [onModeChange, textInput, props.value]); - function createOperatorContext(cursor, isReplay = false) { - return { - cursor, - text: props.value, - setText: (newText) => props.onChange(newText), - setOffset: (offset) => textInput.setOffset(offset), - enterInsert: (offset) => switchToInsertMode(offset), - getRegister: () => persistentRef.current.register, - setRegister: (content, linewise) => { - persistentRef.current.register = content; - persistentRef.current.registerIsLinewise = linewise; - }, - getLastFind: () => persistentRef.current.lastFind, - setLastFind: (type, char) => { - persistentRef.current.lastFind = { type, char }; - }, - recordChange: isReplay ? () => {} : (change) => { - persistentRef.current.lastChange = change; - } - }; - } - function replayLastChange() { - const change = persistentRef.current.lastChange; - if (!change) - return; - const cursor = Cursor.fromText(props.value, props.columns, textInput.offset); - const ctx = createOperatorContext(cursor, true); - switch (change.type) { - case "insert": - if (change.text) { - const newCursor = cursor.insert(change.text); - props.onChange(newCursor.text); - textInput.setOffset(newCursor.offset); - } - break; - case "x": - executeX(change.count, ctx); - break; - case "replace": - executeReplace(change.char, change.count, ctx); - break; - case "toggleCase": - executeToggleCase(change.count, ctx); - break; - case "indent": - executeIndent(change.dir, change.count, ctx); - break; - case "join": - executeJoin(change.count, ctx); - break; - case "openLine": - executeOpenLine(change.direction, ctx); - break; - case "operator": - executeOperatorMotion(change.op, change.motion, change.count, ctx); - break; - case "operatorFind": - executeOperatorFind(change.op, change.find, change.char, change.count, ctx); - break; - case "operatorTextObj": - executeOperatorTextObj(change.op, change.scope, change.objType, change.count, ctx); - break; - } - } - function handleVimInput(rawInput, key2) { - const state4 = vimStateRef.current; - const filtered = inputFilter ? inputFilter(rawInput, key2) : rawInput; - const input = state4.mode === "INSERT" ? filtered : rawInput; - const cursor = Cursor.fromText(props.value, props.columns, textInput.offset); - if (key2.ctrl) { - textInput.onInput(input, key2); - return; - } - if (key2.escape && state4.mode === "INSERT") { - switchToNormalMode(); - return; - } - if (key2.escape && state4.mode === "NORMAL") { - vimStateRef.current = { mode: "NORMAL", command: { type: "idle" } }; - return; - } - if (key2.return) { - textInput.onInput(input, key2); - return; - } - if (state4.mode === "INSERT") { - if (key2.backspace || key2.delete) { - if (state4.insertedText.length > 0) { - vimStateRef.current = { - mode: "INSERT", - insertedText: state4.insertedText.slice(0, -(lastGrapheme(state4.insertedText).length || 1)) - }; - } - } else { - vimStateRef.current = { - mode: "INSERT", - insertedText: state4.insertedText + input - }; - } - textInput.onInput(input, key2); - return; - } - if (state4.mode !== "NORMAL") { - return; - } - if (state4.command.type === "idle" && (key2.upArrow || key2.downArrow || key2.leftArrow || key2.rightArrow)) { - textInput.onInput(input, key2); - return; - } - const ctx = { - ...createOperatorContext(cursor, false), - onUndo: props.onUndo, - onDotRepeat: replayLastChange - }; - const expectsMotion = state4.command.type === "idle" || state4.command.type === "count" || state4.command.type === "operator" || state4.command.type === "operatorCount"; - let vimInput = input; - if (key2.leftArrow) - vimInput = "h"; - else if (key2.rightArrow) - vimInput = "l"; - else if (key2.upArrow) - vimInput = "k"; - else if (key2.downArrow) - vimInput = "j"; - else if (expectsMotion && key2.backspace) - vimInput = "h"; - else if (expectsMotion && state4.command.type !== "count" && key2.delete) - vimInput = "x"; - const result = transition(state4.command, vimInput, ctx); - if (result.execute) { - result.execute(); - } - if (vimStateRef.current.mode === "NORMAL") { - if (result.next) { - vimStateRef.current = { mode: "NORMAL", command: result.next }; - } else if (result.execute) { - vimStateRef.current = { mode: "NORMAL", command: { type: "idle" } }; - } - } - if (input === "?" && state4.mode === "NORMAL" && state4.command.type === "idle") { - props.onChange("?"); - } - } - const setModeExternal = import_react249.useCallback((newMode) => { - if (newMode === "INSERT") { - vimStateRef.current = { mode: "INSERT", insertedText: "" }; - } else { - vimStateRef.current = { mode: "NORMAL", command: { type: "idle" } }; - } - setMode(newMode); - onModeChange?.(newMode); - }, [onModeChange]); - return { - ...textInput, - onInput: handleVimInput, - mode, - setMode: setModeExternal - }; -} -var import_react249; -var init_useVimInput = __esm(() => { - init_Cursor(); - init_intl(); - init_operators(); - init_transitions(); - init_types26(); - init_useTextInput(); - import_react249 = __toESM(require_react(), 1); -}); - -// src/components/VimTextInput.tsx -function VimTextInput(props) { - const $2 = import_compiler_runtime329.c(38); - const [theme2] = useTheme(); - const isTerminalFocused = useTerminalFocus(); - useClipboardImageHint(isTerminalFocused, !!props.onImagePaste); - const t0 = props.value; - const t1 = props.onChange; - const t22 = props.onSubmit; - const t32 = props.onExit; - const t4 = props.onExitMessage; - const t5 = props.onHistoryReset; - const t6 = props.onHistoryUp; - const t7 = props.onHistoryDown; - const t8 = props.onClearInput; - const t9 = props.focus; - const t10 = props.mask; - const t11 = props.multiline; - const t12 = props.showCursor ? " " : ""; - const t13 = props.highlightPastedText; - const t14 = isTerminalFocused ? source_default.inverse : _temp196; - let t15; - if ($2[0] !== theme2) { - t15 = color("text", theme2); - $2[0] = theme2; - $2[1] = t15; - } else { - t15 = $2[1]; - } - let t16; - if ($2[2] !== props.columns || $2[3] !== props.cursorOffset || $2[4] !== props.disableCursorMovementForUpDownKeys || $2[5] !== props.disableEscapeDoublePress || $2[6] !== props.focus || $2[7] !== props.highlightPastedText || $2[8] !== props.inputFilter || $2[9] !== props.mask || $2[10] !== props.maxVisibleLines || $2[11] !== props.multiline || $2[12] !== props.onChange || $2[13] !== props.onChangeCursorOffset || $2[14] !== props.onClearInput || $2[15] !== props.onExit || $2[16] !== props.onExitMessage || $2[17] !== props.onHistoryDown || $2[18] !== props.onHistoryReset || $2[19] !== props.onHistoryUp || $2[20] !== props.onImagePaste || $2[21] !== props.onModeChange || $2[22] !== props.onSubmit || $2[23] !== props.onUndo || $2[24] !== props.value || $2[25] !== t12 || $2[26] !== t14 || $2[27] !== t15) { - t16 = { - value: t0, - onChange: t1, - onSubmit: t22, - onExit: t32, - onExitMessage: t4, - onHistoryReset: t5, - onHistoryUp: t6, - onHistoryDown: t7, - onClearInput: t8, - focus: t9, - mask: t10, - multiline: t11, - cursorChar: t12, - highlightPastedText: t13, - invert: t14, - themeText: t15, - columns: props.columns, - maxVisibleLines: props.maxVisibleLines, - onImagePaste: props.onImagePaste, - disableCursorMovementForUpDownKeys: props.disableCursorMovementForUpDownKeys, - disableEscapeDoublePress: props.disableEscapeDoublePress, - externalOffset: props.cursorOffset, - onOffsetChange: props.onChangeCursorOffset, - inputFilter: props.inputFilter, - onModeChange: props.onModeChange, - onUndo: props.onUndo - }; - $2[2] = props.columns; - $2[3] = props.cursorOffset; - $2[4] = props.disableCursorMovementForUpDownKeys; - $2[5] = props.disableEscapeDoublePress; - $2[6] = props.focus; - $2[7] = props.highlightPastedText; - $2[8] = props.inputFilter; - $2[9] = props.mask; - $2[10] = props.maxVisibleLines; - $2[11] = props.multiline; - $2[12] = props.onChange; - $2[13] = props.onChangeCursorOffset; - $2[14] = props.onClearInput; - $2[15] = props.onExit; - $2[16] = props.onExitMessage; - $2[17] = props.onHistoryDown; - $2[18] = props.onHistoryReset; - $2[19] = props.onHistoryUp; - $2[20] = props.onImagePaste; - $2[21] = props.onModeChange; - $2[22] = props.onSubmit; - $2[23] = props.onUndo; - $2[24] = props.value; - $2[25] = t12; - $2[26] = t14; - $2[27] = t15; - $2[28] = t16; - } else { - t16 = $2[28]; - } - const vimInputState = useVimInput(t16); - const { - mode, - setMode - } = vimInputState; - let t17; - let t18; - if ($2[29] !== mode || $2[30] !== props.initialMode || $2[31] !== setMode) { - t17 = () => { - if (props.initialMode && props.initialMode !== mode) { - setMode(props.initialMode); - } - }; - t18 = [props.initialMode, mode, setMode]; - $2[29] = mode; - $2[30] = props.initialMode; - $2[31] = setMode; - $2[32] = t17; - $2[33] = t18; - } else { - t17 = $2[32]; - t18 = $2[33]; - } - import_react250.default.useEffect(t17, t18); - let t19; - if ($2[34] !== isTerminalFocused || $2[35] !== props || $2[36] !== vimInputState) { - t19 = /* @__PURE__ */ jsx_dev_runtime425.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime425.jsxDEV(BaseTextInput, { - inputState: vimInputState, - terminalFocus: isTerminalFocused, - highlights: props.highlights, - ...props - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[34] = isTerminalFocused; - $2[35] = props; - $2[36] = vimInputState; - $2[37] = t19; - } else { - t19 = $2[37]; - } - return t19; -} -function _temp196(text) { - return text; -} -var import_compiler_runtime329, import_react250, jsx_dev_runtime425; -var init_VimTextInput = __esm(() => { - init_source(); - init_useClipboardImageHint(); - init_useVimInput(); - init_ink2(); - init_BaseTextInput(); - import_compiler_runtime329 = __toESM(require_compiler_runtime(), 1); - import_react250 = __toESM(require_react(), 1); - jsx_dev_runtime425 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/StatusLine.tsx -function statusLineShouldDisplay(settings) { - if (false) - ; - return settings?.statusLine !== undefined; -} -function buildStatusLineCommandInput(permissionMode, exceeds200kTokens, settings, messages, addedDirs, mainLoopModel, vimMode) { - const agentType = getMainThreadAgentType(); - const worktreeSession = getCurrentWorktreeSession(); - const runtimeModel = getRuntimeMainLoopModel({ - permissionMode, - mainLoopModel, - exceeds200kTokens - }); - const outputStyleName = settings?.outputStyle || DEFAULT_OUTPUT_STYLE_NAME; - const currentUsage = getCurrentUsage(messages); - const contextWindowSize = getContextWindowForModel(runtimeModel, getSdkBetas()); - const contextPercentages = calculateContextPercentages(currentUsage, contextWindowSize); - const sessionId = getSessionId(); - const sessionName = getCurrentSessionTitle(sessionId); - const rawUtil = getRawUtilization(); - const rateLimits = { - ...rawUtil.five_hour && { - five_hour: { - used_percentage: rawUtil.five_hour.utilization * 100, - resets_at: rawUtil.five_hour.resets_at - } - }, - ...rawUtil.seven_day && { - seven_day: { - used_percentage: rawUtil.seven_day.utilization * 100, - resets_at: rawUtil.seven_day.resets_at - } - } - }; - return { - ...createBaseHookInput(), - ...sessionName && { - session_name: sessionName - }, - model: { - id: runtimeModel, - display_name: renderModelName(runtimeModel) - }, - workspace: { - current_dir: getCwd(), - project_dir: getOriginalCwd(), - added_dirs: addedDirs - }, - version: MACRO.VERSION, - output_style: { - name: outputStyleName - }, - cost: { - total_cost_usd: getTotalCostUSD(), - total_duration_ms: getTotalDuration(), - total_api_duration_ms: getTotalAPIDuration(), - total_lines_added: getTotalLinesAdded(), - total_lines_removed: getTotalLinesRemoved() - }, - context_window: { - total_input_tokens: getTotalInputTokens(), - total_output_tokens: getTotalOutputTokens(), - context_window_size: contextWindowSize, - current_usage: currentUsage, - used_percentage: contextPercentages.used, - remaining_percentage: contextPercentages.remaining - }, - exceeds_200k_tokens: exceeds200kTokens, - ...(rateLimits.five_hour || rateLimits.seven_day) && { - rate_limits: rateLimits - }, - ...isVimModeEnabled() && { - vim: { - mode: vimMode ?? "INSERT" - } - }, - ...agentType && { - agent: { - name: agentType - } - }, - ...getIsRemoteMode() && { - remote: { - session_id: getSessionId() - } - }, - ...worktreeSession && { - worktree: { - name: worktreeSession.worktreeName, - path: worktreeSession.worktreePath, - branch: worktreeSession.worktreeBranch, - original_cwd: worktreeSession.originalCwd, - original_branch: worktreeSession.originalBranch - } - } - }; -} -function getLastAssistantMessageId(messages) { - return getLastAssistantMessage(messages)?.uuid ?? null; -} -function StatusLineInner({ - messagesRef, - lastAssistantMessageId, - vimMode -}) { - const abortControllerRef = import_react251.useRef(undefined); - const permissionMode = useAppState((s4) => s4.toolPermissionContext.mode); - const additionalWorkingDirectories = useAppState((s4) => s4.toolPermissionContext.additionalWorkingDirectories); - const statusLineText = useAppState((s4) => s4.statusLineText); - const setAppState = useSetAppState(); - const settings = useSettings(); - const { - addNotification - } = useNotifications(); - const mainLoopModel = useMainLoopModel(); - const settingsRef = import_react251.useRef(settings); - settingsRef.current = settings; - const vimModeRef = import_react251.useRef(vimMode); - vimModeRef.current = vimMode; - const permissionModeRef = import_react251.useRef(permissionMode); - permissionModeRef.current = permissionMode; - const addedDirsRef = import_react251.useRef(additionalWorkingDirectories); - addedDirsRef.current = additionalWorkingDirectories; - const mainLoopModelRef = import_react251.useRef(mainLoopModel); - mainLoopModelRef.current = mainLoopModel; - const previousStateRef = import_react251.useRef({ - messageId: null, - exceeds200kTokens: false, - permissionMode, - vimMode, - mainLoopModel - }); - const debounceTimerRef = import_react251.useRef(undefined); - const logNextResultRef = import_react251.useRef(true); - const doUpdate = import_react251.useCallback(async () => { - abortControllerRef.current?.abort(); - const controller = new AbortController; - abortControllerRef.current = controller; - const msgs = messagesRef.current; - const logResult2 = logNextResultRef.current; - logNextResultRef.current = false; - try { - let exceeds200kTokens = previousStateRef.current.exceeds200kTokens; - const currentMessageId = getLastAssistantMessageId(msgs); - if (currentMessageId !== previousStateRef.current.messageId) { - exceeds200kTokens = doesMostRecentAssistantMessageExceed200k(msgs); - previousStateRef.current.messageId = currentMessageId; - previousStateRef.current.exceeds200kTokens = exceeds200kTokens; - } - const statusInput = buildStatusLineCommandInput(permissionModeRef.current, exceeds200kTokens, settingsRef.current, msgs, Array.from(addedDirsRef.current.keys()), mainLoopModelRef.current, vimModeRef.current); - const text = await executeStatusLineCommand(statusInput, controller.signal, undefined, logResult2); - if (!controller.signal.aborted) { - setAppState((prev) => { - if (prev.statusLineText === text) - return prev; - return { - ...prev, - statusLineText: text - }; - }); - } - } catch {} - }, [messagesRef, setAppState]); - const scheduleUpdate = import_react251.useCallback(() => { - if (debounceTimerRef.current !== undefined) { - clearTimeout(debounceTimerRef.current); - } - debounceTimerRef.current = setTimeout((ref, doUpdate2) => { - ref.current = undefined; - doUpdate2(); - }, 300, debounceTimerRef, doUpdate); - }, [doUpdate]); - import_react251.useEffect(() => { - if (lastAssistantMessageId !== previousStateRef.current.messageId || permissionMode !== previousStateRef.current.permissionMode || vimMode !== previousStateRef.current.vimMode || mainLoopModel !== previousStateRef.current.mainLoopModel) { - previousStateRef.current.permissionMode = permissionMode; - previousStateRef.current.vimMode = vimMode; - previousStateRef.current.mainLoopModel = mainLoopModel; - scheduleUpdate(); - } - }, [lastAssistantMessageId, permissionMode, vimMode, mainLoopModel, scheduleUpdate]); - const statusLineCommand = settings?.statusLine?.command; - const isFirstSettingsRender = import_react251.useRef(true); - import_react251.useEffect(() => { - if (isFirstSettingsRender.current) { - isFirstSettingsRender.current = false; - return; - } - logNextResultRef.current = true; - doUpdate(); - }, [statusLineCommand, doUpdate]); - import_react251.useEffect(() => { - const statusLine = settings?.statusLine; - if (statusLine) { - logEvent("tengu_status_line_mount", { - command_length: statusLine.command.length, - padding: statusLine.padding - }); - if (settings.disableAllHooks === true) { - logForDebugging("Status line is configured but disableAllHooks is true", { - level: "warn" - }); - } - if (!checkHasTrustDialogAccepted()) { - addNotification({ - key: "statusline-trust-blocked", - text: "statusline skipped \xB7 restart to fix", - color: "warning", - priority: "low" - }); - logForDebugging("Status line command skipped: workspace trust not accepted", { - level: "warn" - }); - } - } - }, []); - import_react251.useEffect(() => { - doUpdate(); - return () => { - abortControllerRef.current?.abort(); - if (debounceTimerRef.current !== undefined) { - clearTimeout(debounceTimerRef.current); - } - }; - }, []); - const paddingX = settings?.statusLine?.padding ?? 0; - return /* @__PURE__ */ jsx_dev_runtime426.jsxDEV(ThemedBox_default, { - paddingX, - gap: 2, - children: statusLineText ? /* @__PURE__ */ jsx_dev_runtime426.jsxDEV(ThemedText, { - dimColor: true, - wrap: "truncate", - children: /* @__PURE__ */ jsx_dev_runtime426.jsxDEV(Ansi, { - children: statusLineText - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : isFullscreenEnvEnabled() ? /* @__PURE__ */ jsx_dev_runtime426.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) : null - }, undefined, false, undefined, this); -} -var import_react251, jsx_dev_runtime426, StatusLine; -var init_StatusLine = __esm(() => { - init_analytics(); - init_AppState(); - init_state(); - init_outputStyles(); - init_notifications(); - init_cost_tracker(); - init_useMainLoopModel(); - init_useSettings(); - init_ink2(); - init_claudeAiLimits(); - init_config(); - init_context(); - init_cwd(); - init_debug(); - init_fullscreen(); - init_hooks3(); - init_messages9(); - init_model(); - init_sessionStorage(); - init_tokens(); - init_worktree(); - init_utils14(); - import_react251 = __toESM(require_react(), 1); - jsx_dev_runtime426 = __toESM(require_jsx_dev_runtime(), 1); - StatusLine = import_react251.memo(StatusLineInner); -}); - -// src/utils/horizontalScroll.ts -function calculateHorizontalScrollWindow(itemWidths, availableWidth, arrowWidth, selectedIdx, firstItemHasSeparator = true) { - const totalItems = itemWidths.length; - if (totalItems === 0) { - return { - startIndex: 0, - endIndex: 0, - showLeftArrow: false, - showRightArrow: false - }; - } - const clampedSelected = Math.max(0, Math.min(selectedIdx, totalItems - 1)); - const totalWidth = itemWidths.reduce((sum, w2) => sum + w2, 0); - if (totalWidth <= availableWidth) { - return { - startIndex: 0, - endIndex: totalItems, - showLeftArrow: false, - showRightArrow: false - }; - } - const cumulativeWidths = [0]; - for (let i6 = 0;i6 < totalItems; i6++) { - cumulativeWidths.push(cumulativeWidths[i6] + itemWidths[i6]); - } - function rangeWidth(start, end) { - const baseWidth = cumulativeWidths[end] - cumulativeWidths[start]; - if (firstItemHasSeparator && start > 0) { - return baseWidth - 1; - } - return baseWidth; - } - function getEffectiveWidth(start, end) { - let width = availableWidth; - if (start > 0) - width -= arrowWidth; - if (end < totalItems) - width -= arrowWidth; - return width; - } - let startIndex = 0; - let endIndex = 1; - while (endIndex < totalItems && rangeWidth(startIndex, endIndex + 1) <= getEffectiveWidth(startIndex, endIndex + 1)) { - endIndex++; - } - if (clampedSelected >= startIndex && clampedSelected < endIndex) { - return { - startIndex, - endIndex, - showLeftArrow: startIndex > 0, - showRightArrow: endIndex < totalItems - }; - } - if (clampedSelected >= endIndex) { - endIndex = clampedSelected + 1; - startIndex = clampedSelected; - while (startIndex > 0 && rangeWidth(startIndex - 1, endIndex) <= getEffectiveWidth(startIndex - 1, endIndex)) { - startIndex--; - } - } else { - startIndex = clampedSelected; - endIndex = clampedSelected + 1; - while (endIndex < totalItems && rangeWidth(startIndex, endIndex + 1) <= getEffectiveWidth(startIndex, endIndex + 1)) { - endIndex++; - } - } - return { - startIndex, - endIndex, - showLeftArrow: startIndex > 0, - showRightArrow: endIndex < totalItems - }; -} - -// src/components/tasks/BackgroundTaskStatus.tsx -function BackgroundTaskStatus(t0) { - const $2 = import_compiler_runtime330.c(48); - const { - tasksSelected, - isViewingTeammate, - teammateFooterIndex: t1, - isLeaderIdle: t22, - onOpenDialog - } = t0; - const teammateFooterIndex = t1 === undefined ? 0 : t1; - const isLeaderIdle = t22 === undefined ? false : t22; - const setAppState = useSetAppState(); - const { - columns - } = useTerminalSize(); - const tasks2 = useAppState(_temp197); - const viewingAgentTaskId = useAppState(_temp281); - let t32; - if ($2[0] !== tasks2) { - t32 = Object.values(tasks2 ?? {}).filter(_temp353); - $2[0] = tasks2; - $2[1] = t32; - } else { - t32 = $2[1]; - } - const runningTasks = t32; - const expandedView = useAppState(_temp439); - const showSpinnerTree = expandedView === "teammates"; - const allTeammates = !showSpinnerTree && runningTasks.length > 0 && runningTasks.every(_temp529); - let t4; - if ($2[2] !== runningTasks) { - t4 = runningTasks.filter(_temp623).sort(_temp720); - $2[2] = runningTasks; - $2[3] = t4; - } else { - t4 = $2[3]; - } - const teammateEntries = t4; - let t5; - if ($2[4] !== isLeaderIdle) { - t5 = { - name: "main", - color: undefined, - isIdle: isLeaderIdle, - taskId: undefined - }; - $2[4] = isLeaderIdle; - $2[5] = t5; - } else { - t5 = $2[5]; - } - const mainPill = t5; - let t6; - if ($2[6] !== mainPill || $2[7] !== tasksSelected || $2[8] !== teammateEntries) { - const teammatePills = teammateEntries.map(_temp816); - if (!tasksSelected) { - teammatePills.sort(_temp916); - } - const pills = [mainPill, ...teammatePills]; - t6 = pills.map(_temp08); - $2[6] = mainPill; - $2[7] = tasksSelected; - $2[8] = teammateEntries; - $2[9] = t6; - } else { - t6 = $2[9]; - } - const allPills = t6; - let t7; - if ($2[10] !== allPills) { - t7 = allPills.map(_temp164); - $2[10] = allPills; - $2[11] = t7; - } else { - t7 = $2[11]; - } - const pillWidths = t7; - if (allTeammates || !showSpinnerTree && isViewingTeammate) { - const selectedIdx = tasksSelected ? teammateFooterIndex : -1; - let t82; - if ($2[12] !== teammateEntries || $2[13] !== viewingAgentTaskId) { - t82 = viewingAgentTaskId ? teammateEntries.findIndex((t_3) => t_3.id === viewingAgentTaskId) + 1 : 0; - $2[12] = teammateEntries; - $2[13] = viewingAgentTaskId; - $2[14] = t82; - } else { - t82 = $2[14]; - } - const viewedIdx = t82; - const availableWidth = Math.max(20, columns - 20 - 4); - const t92 = selectedIdx >= 0 ? selectedIdx : 0; - let t102; - if ($2[15] !== availableWidth || $2[16] !== pillWidths || $2[17] !== t92) { - t102 = calculateHorizontalScrollWindow(pillWidths, availableWidth, 2, t92); - $2[15] = availableWidth; - $2[16] = pillWidths; - $2[17] = t92; - $2[18] = t102; - } else { - t102 = $2[18]; - } - const { - startIndex, - endIndex, - showLeftArrow, - showRightArrow - } = t102; - let t112; - if ($2[19] !== allPills || $2[20] !== endIndex || $2[21] !== startIndex) { - t112 = allPills.slice(startIndex, endIndex); - $2[19] = allPills; - $2[20] = endIndex; - $2[21] = startIndex; - $2[22] = t112; - } else { - t112 = $2[22]; - } - const visiblePills = t112; - let t12; - if ($2[23] !== showLeftArrow) { - t12 = showLeftArrow && /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.arrowLeft, - " " - ] - }, undefined, true, undefined, this); - $2[23] = showLeftArrow; - $2[24] = t12; - } else { - t12 = $2[24]; - } - let t13; - if ($2[25] !== selectedIdx || $2[26] !== setAppState || $2[27] !== viewedIdx || $2[28] !== visiblePills) { - t13 = visiblePills.map((pill_1, i_1) => { - const needsSeparator = i_1 > 0; - return /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(React138.Fragment, { - children: [ - needsSeparator && /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(AgentPill, { - name: pill_1.name, - color: pill_1.color, - isSelected: selectedIdx === pill_1.idx, - isViewed: viewedIdx === pill_1.idx, - isIdle: pill_1.isIdle, - onClick: () => pill_1.taskId ? enterTeammateView(pill_1.taskId, setAppState) : exitTeammateView(setAppState) - }, undefined, false, undefined, this) - ] - }, pill_1.name, true, undefined, this); - }); - $2[25] = selectedIdx; - $2[26] = setAppState; - $2[27] = viewedIdx; - $2[28] = visiblePills; - $2[29] = t13; - } else { - t13 = $2[29]; - } - let t14; - if ($2[30] !== showRightArrow) { - t14 = showRightArrow && /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - figures_default.arrowRight - ] - }, undefined, true, undefined, this); - $2[30] = showRightArrow; - $2[31] = t14; - } else { - t14 = $2[31]; - } - let t15; - if ($2[32] === Symbol.for("react.memo_cache_sentinel")) { - t15 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " \xB7 ", - /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(KeyboardShortcutHint, { - shortcut: "shift + \u2193", - action: "expand" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[32] = t15; - } else { - t15 = $2[32]; - } - let t16; - if ($2[33] !== t12 || $2[34] !== t13 || $2[35] !== t14) { - t16 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(jsx_dev_runtime427.Fragment, { - children: [ - t12, - t13, - t14, - t15 - ] - }, undefined, true, undefined, this); - $2[33] = t12; - $2[34] = t13; - $2[35] = t14; - $2[36] = t16; - } else { - t16 = $2[36]; - } - return t16; - } - if (shouldHideTasksFooter(tasks2 ?? {}, showSpinnerTree)) { - return null; - } - if (runningTasks.length === 0) { - return null; - } - let t8; - if ($2[37] !== runningTasks) { - t8 = getPillLabel(runningTasks); - $2[37] = runningTasks; - $2[38] = t8; - } else { - t8 = $2[38]; - } - let t9; - if ($2[39] !== onOpenDialog || $2[40] !== t8 || $2[41] !== tasksSelected) { - t9 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(SummaryPill, { - selected: tasksSelected, - onClick: onOpenDialog, - children: t8 - }, undefined, false, undefined, this); - $2[39] = onOpenDialog; - $2[40] = t8; - $2[41] = tasksSelected; - $2[42] = t9; - } else { - t9 = $2[42]; - } - let t10; - if ($2[43] !== runningTasks) { - t10 = pillNeedsCta(runningTasks) && /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " \xB7 ", - figures_default.arrowDown, - " to view" - ] - }, undefined, true, undefined, this); - $2[43] = runningTasks; - $2[44] = t10; - } else { - t10 = $2[44]; - } - let t11; - if ($2[45] !== t10 || $2[46] !== t9) { - t11 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(jsx_dev_runtime427.Fragment, { - children: [ - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[45] = t10; - $2[46] = t9; - $2[47] = t11; - } else { - t11 = $2[47]; - } - return t11; -} -function _temp164(pill_0, i_0) { - const pillText = `@${pill_0.name}`; - return stringWidth(pillText) + (i_0 > 0 ? 1 : 0); -} -function _temp08(pill, i6) { - return { - ...pill, - idx: i6 - }; -} -function _temp916(a_0, b_0) { - if (a_0.isIdle !== b_0.isIdle) { - return a_0.isIdle ? 1 : -1; - } - return 0; -} -function _temp816(t_2) { - return { - name: t_2.identity.agentName, - color: getAgentThemeColor(t_2.identity.color), - isIdle: t_2.isIdle, - taskId: t_2.id - }; -} -function _temp720(a5, b5) { - return a5.identity.agentName.localeCompare(b5.identity.agentName); -} -function _temp623(t_1) { - return t_1.type === "in_process_teammate"; -} -function _temp529(t_0) { - return t_0.type === "in_process_teammate"; -} -function _temp439(s_1) { - return s_1.expandedView; -} -function _temp353(t4) { - return isBackgroundTask(t4) && true; -} -function _temp281(s_0) { - return s_0.viewingAgentTaskId; -} -function _temp197(s4) { - return s4.tasks; -} -function AgentPill(t0) { - const $2 = import_compiler_runtime330.c(19); - const { - name: name3, - color: color3, - isSelected, - isViewed, - isIdle, - onClick - } = t0; - const [hover, setHover] = import_react252.useState(false); - const highlighted = isSelected || hover; - let label; - if (highlighted) { - let t12; - if ($2[0] !== color3 || $2[1] !== isViewed || $2[2] !== name3) { - t12 = color3 ? /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - backgroundColor: color3, - color: "inverseText", - bold: isViewed, - children: [ - "@", - name3 - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - color: "background", - inverse: true, - bold: isViewed, - children: [ - "@", - name3 - ] - }, undefined, true, undefined, this); - $2[0] = color3; - $2[1] = isViewed; - $2[2] = name3; - $2[3] = t12; - } else { - t12 = $2[3]; - } - label = t12; - } else { - if (isIdle) { - let t12; - if ($2[4] !== isViewed || $2[5] !== name3) { - t12 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - dimColor: true, - bold: isViewed, - children: [ - "@", - name3 - ] - }, undefined, true, undefined, this); - $2[4] = isViewed; - $2[5] = name3; - $2[6] = t12; - } else { - t12 = $2[6]; - } - label = t12; - } else { - if (isViewed) { - let t12; - if ($2[7] !== color3 || $2[8] !== name3) { - t12 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - color: color3, - bold: true, - children: [ - "@", - name3 - ] - }, undefined, true, undefined, this); - $2[7] = color3; - $2[8] = name3; - $2[9] = t12; - } else { - t12 = $2[9]; - } - label = t12; - } else { - const t12 = !color3; - let t23; - if ($2[10] !== color3 || $2[11] !== name3 || $2[12] !== t12) { - t23 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - color: color3, - dimColor: t12, - children: [ - "@", - name3 - ] - }, undefined, true, undefined, this); - $2[10] = color3; - $2[11] = name3; - $2[12] = t12; - $2[13] = t23; - } else { - t23 = $2[13]; - } - label = t23; - } - } - } - if (!onClick) { - return label; - } - let t1; - let t22; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => setHover(true); - t22 = () => setHover(false); - $2[14] = t1; - $2[15] = t22; - } else { - t1 = $2[14]; - t22 = $2[15]; - } - let t32; - if ($2[16] !== label || $2[17] !== onClick) { - t32 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedBox_default, { - onClick, - onMouseEnter: t1, - onMouseLeave: t22, - children: label - }, undefined, false, undefined, this); - $2[16] = label; - $2[17] = onClick; - $2[18] = t32; - } else { - t32 = $2[18]; - } - return t32; -} -function SummaryPill(t0) { - const $2 = import_compiler_runtime330.c(8); - const { - selected, - onClick, - children - } = t0; - const [hover, setHover] = import_react252.useState(false); - const t1 = selected || hover; - let t22; - if ($2[0] !== children || $2[1] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedText, { - color: "background", - inverse: t1, - children - }, undefined, false, undefined, this); - $2[0] = children; - $2[1] = t1; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const label = t22; - if (!onClick) { - return label; - } - let t32; - let t4; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = () => setHover(true); - t4 = () => setHover(false); - $2[3] = t32; - $2[4] = t4; - } else { - t32 = $2[3]; - t4 = $2[4]; - } - let t5; - if ($2[5] !== label || $2[6] !== onClick) { - t5 = /* @__PURE__ */ jsx_dev_runtime427.jsxDEV(ThemedBox_default, { - onClick, - onMouseEnter: t32, - onMouseLeave: t4, - children: label - }, undefined, false, undefined, this); - $2[5] = label; - $2[6] = onClick; - $2[7] = t5; - } else { - t5 = $2[7]; - } - return t5; -} -function getAgentThemeColor(colorName) { - if (!colorName) - return; - if (AGENT_COLORS.includes(colorName)) { - return AGENT_COLOR_TO_THEME_COLOR[colorName]; - } - return; -} -var import_compiler_runtime330, React138, import_react252, jsx_dev_runtime427; -var init_BackgroundTaskStatus = __esm(() => { - init_figures(); - init_useTerminalSize(); - init_stringWidth(); - init_AppState(); - init_teammateViewHelpers(); - init_LocalAgentTask(); - init_pillLabel(); - init_ink2(); - init_agentColorManager(); - init_KeyboardShortcutHint(); - init_taskStatusUtils(); - import_compiler_runtime330 = __toESM(require_compiler_runtime(), 1); - React138 = __toESM(require_react(), 1); - import_react252 = __toESM(require_react(), 1); - jsx_dev_runtime427 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/teams/TeamStatus.tsx -function TeamStatus(t0) { - const $2 = import_compiler_runtime331.c(14); - const { - teamsSelected, - showHint - } = t0; - const teamContext = useAppState(_temp198); - let t1; - if ($2[0] !== teamContext) { - t1 = teamContext ? Object.values(teamContext.teammates).filter(_temp282).length : 0; - $2[0] = teamContext; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const totalTeammates = t1; - if (totalTeammates === 0) { - return null; - } - let t22; - if ($2[2] !== showHint || $2[3] !== teamsSelected) { - t22 = showHint && teamsSelected ? /* @__PURE__ */ jsx_dev_runtime428.jsxDEV(jsx_dev_runtime428.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime428.jsxDEV(ThemedText, { - dimColor: true, - children: "\xB7 " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime428.jsxDEV(ThemedText, { - dimColor: true, - children: "Enter to view" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : null; - $2[2] = showHint; - $2[3] = teamsSelected; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const hint = t22; - const statusText = `${totalTeammates} ${totalTeammates === 1 ? "teammate" : "teammates"}`; - const t32 = teamsSelected ? "selected" : "normal"; - let t4; - if ($2[5] !== statusText || $2[6] !== t32 || $2[7] !== teamsSelected) { - t4 = /* @__PURE__ */ jsx_dev_runtime428.jsxDEV(ThemedText, { - color: "background", - inverse: teamsSelected, - children: statusText - }, t32, false, undefined, this); - $2[5] = statusText; - $2[6] = t32; - $2[7] = teamsSelected; - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] !== hint) { - t5 = hint ? /* @__PURE__ */ jsx_dev_runtime428.jsxDEV(ThemedText, { - children: [ - " ", - hint - ] - }, undefined, true, undefined, this) : null; - $2[9] = hint; - $2[10] = t5; - } else { - t5 = $2[10]; - } - let t6; - if ($2[11] !== t4 || $2[12] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime428.jsxDEV(jsx_dev_runtime428.Fragment, { - children: [ - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[11] = t4; - $2[12] = t5; - $2[13] = t6; - } else { - t6 = $2[13]; - } - return t6; -} -function _temp282(t4) { - return t4.name !== "team-lead"; -} -function _temp198(s4) { - return s4.teamContext; -} -var import_compiler_runtime331, jsx_dev_runtime428; -var init_TeamStatus = __esm(() => { - init_ink2(); - init_AppState(); - import_compiler_runtime331 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime428 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/HistorySearchInput.tsx -function HistorySearchInput(t0) { - const $2 = import_compiler_runtime332.c(9); - const { - value, - onChange, - historyFailedMatch - } = t0; - const t1 = historyFailedMatch ? "no matching prompt:" : "search prompts:"; - let t22; - if ($2[0] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime429.jsxDEV(ThemedText, { - dimColor: true, - children: t1 - }, undefined, false, undefined, this); - $2[0] = t1; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const t32 = stringWidth(value) + 1; - let t4; - if ($2[2] !== onChange || $2[3] !== t32 || $2[4] !== value) { - t4 = /* @__PURE__ */ jsx_dev_runtime429.jsxDEV(TextInput, { - value, - onChange, - cursorOffset: value.length, - onChangeCursorOffset: _temp199, - columns: t32, - focus: true, - showCursor: true, - multiline: false, - dimColor: true - }, undefined, false, undefined, this); - $2[2] = onChange; - $2[3] = t32; - $2[4] = value; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== t22 || $2[7] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime429.jsxDEV(ThemedBox_default, { - gap: 1, - children: [ - t22, - t4 - ] - }, undefined, true, undefined, this); - $2[6] = t22; - $2[7] = t4; - $2[8] = t5; - } else { - t5 = $2[8]; - } - return t5; -} -function _temp199() {} -var import_compiler_runtime332, jsx_dev_runtime429, HistorySearchInput_default; -var init_HistorySearchInput = __esm(() => { - init_stringWidth(); - init_ink2(); - init_TextInput(); - import_compiler_runtime332 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime429 = __toESM(require_jsx_dev_runtime(), 1); - HistorySearchInput_default = HistorySearchInput; -}); - -// src/utils/ghPrStatus.ts -function deriveReviewState(isDraft, reviewDecision) { - if (isDraft) - return "draft"; - switch (reviewDecision) { - case "APPROVED": - return "approved"; - case "CHANGES_REQUESTED": - return "changes_requested"; - default: - return "pending"; - } -} -async function fetchPrStatus() { - const isGit = await getIsGit(); - if (!isGit) - return null; - const [branch2, defaultBranch] = await Promise.all([ - getBranch(), - getDefaultBranch() - ]); - if (branch2 === defaultBranch) - return null; - const { stdout, code } = await execFileNoThrow("gh", [ - "pr", - "view", - "--json", - "number,url,reviewDecision,isDraft,headRefName,state" - ], { timeout: GH_TIMEOUT_MS, preserveOutputOnError: false }); - if (code !== 0 || !stdout.trim()) - return null; - try { - const data = jsonParse(stdout); - if (data.headRefName === defaultBranch || data.headRefName === "main" || data.headRefName === "master") { - return null; - } - if (data.state === "MERGED" || data.state === "CLOSED") { - return null; - } - return { - number: data.number, - url: data.url, - reviewState: deriveReviewState(data.isDraft, data.reviewDecision) - }; - } catch { - return null; - } -} -var GH_TIMEOUT_MS = 5000; -var init_ghPrStatus = __esm(() => { - init_execFileNoThrow(); - init_git(); - init_slowOperations(); -}); - -// src/hooks/usePrStatus.ts -function usePrStatus(isLoading, enabled2 = true) { - const [prStatus, setPrStatus] = import_react253.useState(INITIAL_STATE4); - const timeoutRef = import_react253.useRef(null); - const disabledRef = import_react253.useRef(false); - const lastFetchRef = import_react253.useRef(0); - import_react253.useEffect(() => { - if (!enabled2) - return; - if (disabledRef.current) - return; - let cancelled = false; - let lastSeenInteractionTime = -1; - let lastActivityTimestamp = Date.now(); - async function poll() { - if (cancelled) - return; - const currentInteractionTime = getLastInteractionTime(); - if (lastSeenInteractionTime !== currentInteractionTime) { - lastSeenInteractionTime = currentInteractionTime; - lastActivityTimestamp = Date.now(); - } else if (Date.now() - lastActivityTimestamp >= IDLE_STOP_MS) { - return; - } - const start = Date.now(); - const result = await fetchPrStatus(); - if (cancelled) - return; - lastFetchRef.current = start; - setPrStatus((prev) => { - const newNumber = result?.number ?? null; - const newReviewState = result?.reviewState ?? null; - if (prev.number === newNumber && prev.reviewState === newReviewState) { - return prev; - } - return { - number: newNumber, - url: result?.url ?? null, - reviewState: newReviewState, - lastUpdated: Date.now() - }; - }); - if (Date.now() - start > SLOW_GH_THRESHOLD_MS) { - disabledRef.current = true; - return; - } - if (!cancelled) { - timeoutRef.current = setTimeout(poll, POLL_INTERVAL_MS3); - } - } - const elapsed = Date.now() - lastFetchRef.current; - if (elapsed >= POLL_INTERVAL_MS3) { - poll(); - } else { - timeoutRef.current = setTimeout(poll, POLL_INTERVAL_MS3 - elapsed); - } - return () => { - cancelled = true; - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - timeoutRef.current = null; - } - }; - }, [isLoading, enabled2]); - return prStatus; -} -var import_react253, POLL_INTERVAL_MS3 = 60000, SLOW_GH_THRESHOLD_MS = 4000, IDLE_STOP_MS, INITIAL_STATE4; -var init_usePrStatus = __esm(() => { - init_state(); - init_ghPrStatus(); - import_react253 = __toESM(require_react(), 1); - IDLE_STOP_MS = 60 * 60000; - INITIAL_STATE4 = { - number: null, - url: null, - reviewState: null, - lastUpdated: 0 - }; -}); - -// src/components/PromptInput/VoiceIndicator.tsx -var import_compiler_runtime333, jsx_dev_runtime430; -var init_VoiceIndicator = __esm(() => { - init_useSettings(); - init_ink2(); - init_utils10(); - import_compiler_runtime333 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime430 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/PromptInputFooterLeftSide.tsx -function PromptInputFooterLeftSide(t0) { - const $2 = import_compiler_runtime334.c(27); - const { - exitMessage, - vimMode, - mode, - toolPermissionContext, - suppressHint, - isLoading, - tasksSelected, - teamsSelected, - tmuxSelected, - teammateFooterIndex, - isPasting, - isSearching, - historyQuery, - setHistoryQuery, - historyFailedMatch, - onOpenTasksDialog - } = t0; - if (exitMessage.show) { - let t12; - if ($2[0] !== exitMessage.key) { - t12 = /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - exitMessage.key, - " again to exit" - ] - }, "exit-message", true, undefined, this); - $2[0] = exitMessage.key; - $2[1] = t12; - } else { - t12 = $2[1]; - } - return t12; - } - if (isPasting) { - let t12; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: "Pasting text\u2026" - }, "pasting-message", false, undefined, this); - $2[2] = t12; - } else { - t12 = $2[2]; - } - return t12; - } - let t1; - if ($2[3] !== isSearching || $2[4] !== vimMode) { - t1 = isVimModeEnabled() && vimMode === "INSERT" && !isSearching; - $2[3] = isSearching; - $2[4] = vimMode; - $2[5] = t1; - } else { - t1 = $2[5]; - } - const showVim = t1; - let t22; - if ($2[6] !== historyFailedMatch || $2[7] !== historyQuery || $2[8] !== isSearching || $2[9] !== setHistoryQuery) { - t22 = isSearching && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(HistorySearchInput_default, { - value: historyQuery, - onChange: setHistoryQuery, - historyFailedMatch - }, undefined, false, undefined, this); - $2[6] = historyFailedMatch; - $2[7] = historyQuery; - $2[8] = isSearching; - $2[9] = setHistoryQuery; - $2[10] = t22; - } else { - t22 = $2[10]; - } - let t32; - if ($2[11] !== showVim) { - t32 = showVim ? /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: "-- INSERT --" - }, "vim-insert", false, undefined, this) : null; - $2[11] = showVim; - $2[12] = t32; - } else { - t32 = $2[12]; - } - const t4 = !suppressHint && !showVim; - let t5; - if ($2[13] !== isLoading || $2[14] !== mode || $2[15] !== onOpenTasksDialog || $2[16] !== t4 || $2[17] !== tasksSelected || $2[18] !== teammateFooterIndex || $2[19] !== teamsSelected || $2[20] !== tmuxSelected || $2[21] !== toolPermissionContext) { - t5 = /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ModeIndicator, { - mode, - toolPermissionContext, - showHint: t4, - isLoading, - tasksSelected, - teamsSelected, - teammateFooterIndex, - tmuxSelected, - onOpenTasksDialog - }, undefined, false, undefined, this); - $2[13] = isLoading; - $2[14] = mode; - $2[15] = onOpenTasksDialog; - $2[16] = t4; - $2[17] = tasksSelected; - $2[18] = teammateFooterIndex; - $2[19] = teamsSelected; - $2[20] = tmuxSelected; - $2[21] = toolPermissionContext; - $2[22] = t5; - } else { - t5 = $2[22]; - } - let t6; - if ($2[23] !== t22 || $2[24] !== t32 || $2[25] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - justifyContent: "flex-start", - gap: 1, - children: [ - t22, - t32, - t5 - ] - }, undefined, true, undefined, this); - $2[23] = t22; - $2[24] = t32; - $2[25] = t5; - $2[26] = t6; - } else { - t6 = $2[26]; - } - return t6; -} -function ModeIndicator({ - mode, - toolPermissionContext, - showHint, - isLoading, - tasksSelected, - teamsSelected, - tmuxSelected, - teammateFooterIndex, - onOpenTasksDialog -}) { - const { - columns - } = useTerminalSize(); - const modeCycleShortcut = useShortcutDisplay("chat:cycleMode", "Chat", "shift+tab"); - const tasks2 = useAppState((s4) => s4.tasks); - const teamContext = useAppState((s_0) => s_0.teamContext); - const store = useAppStateStore(); - const [remoteSessionUrl] = import_react254.useState(() => store.getState().remoteSessionUrl); - const viewSelectionMode = useAppState((s_1) => s_1.viewSelectionMode); - const viewingAgentTaskId = useAppState((s_2) => s_2.viewingAgentTaskId); - const expandedView = useAppState((s_3) => s_3.expandedView); - const showSpinnerTree = expandedView === "teammates"; - const prStatus = usePrStatus(isLoading, isPrStatusEnabled()); - const hasTmuxSession = useAppState((s_4) => false); - const nextTickAt = import_react254.useSyncExternalStore(proactiveModule3?.subscribeToProactiveChanges ?? NO_OP_SUBSCRIBE, proactiveModule3?.getNextTickAt ?? NULL, NULL); - const voiceEnabled = false; - const voiceState = "idle"; - const voiceWarmingUp = false; - const hasSelection2 = useHasSelection(); - const selGetState = useSelection().getState; - const hasNextTick = nextTickAt !== null; - const isCoordinator = false; - const runningTaskCount = import_react254.useMemo(() => count2(Object.values(tasks2), (t4) => isBackgroundTask(t4) && true), [tasks2]); - const tasksV2 = useTasksV2(); - const hasTaskItems = tasksV2 !== undefined && tasksV2.length > 0; - const escShortcut = useShortcutDisplay("chat:cancel", "Chat", "esc").toLowerCase(); - const todosShortcut = useShortcutDisplay("app:toggleTodos", "Global", "ctrl+t"); - const killAgentsShortcut = useShortcutDisplay("chat:killAgents", "Chat", "ctrl+x ctrl+k"); - const voiceKeyShortcut = ""; - const [voiceHintUnderCap] = [false]; - const voiceHintIncrementedRef = null; - import_react254.useEffect(() => { - if (false) {} - }, [voiceEnabled, voiceHintUnderCap]); - const isKillAgentsConfirmShowing = useAppState((s_7) => s_7.notifications.current?.key === "kill-agents-confirm"); - const hasTeams = isAgentSwarmsEnabled() && !isInProcessEnabled() && teamContext !== undefined && count2(Object.values(teamContext.teammates), (t_0) => t_0.name !== "team-lead") > 0; - if (mode === "bash") { - return /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - color: "bashBorder", - children: "! for bash mode" - }, undefined, false, undefined, this); - } - const currentMode = toolPermissionContext?.mode; - const hasActiveMode = !isDefaultMode(currentMode); - const viewedTask = viewingAgentTaskId ? tasks2[viewingAgentTaskId] : undefined; - const isViewingTeammate = viewSelectionMode === "viewing-agent" && viewedTask?.type === "in_process_teammate"; - const isViewingCompletedTeammate = isViewingTeammate && viewedTask != null && viewedTask.status !== "running"; - const hasBackgroundTasks = runningTaskCount > 0 || isViewingTeammate; - const primaryItemCount = (isCoordinator || hasActiveMode ? 1 : 0) + (hasBackgroundTasks ? 1 : 0) + (hasTeams ? 1 : 0); - const shouldShowPrStatus = isPrStatusEnabled() && prStatus.number !== null && prStatus.reviewState !== null && prStatus.url !== null && primaryItemCount < 2 && (primaryItemCount === 0 || columns >= 80); - const shouldShowModeHint = primaryItemCount < 2; - const hasInProcessTeammates = !showSpinnerTree && hasBackgroundTasks && Object.values(tasks2).some((t_1) => t_1.type === "in_process_teammate"); - const hasTeammatePills = hasInProcessTeammates || !showSpinnerTree && isViewingTeammate; - const modePart = currentMode && hasActiveMode && !getIsRemoteMode() ? /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - color: getModeColor(currentMode), - children: [ - permissionModeSymbol(currentMode), - " ", - permissionModeTitle(currentMode).toLowerCase(), - " on", - shouldShowModeHint && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: modeCycleShortcut, - action: "cycle", - parens: true - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, "mode", true, undefined, this) : null; - const parts = [ - ...remoteSessionUrl ? [/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(Link, { - url: remoteSessionUrl, - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - color: "ide", - children: [ - figures_default.circleDouble, - " remote" - ] - }, undefined, true, undefined, this) - }, "remote", false, undefined, this)] : [], - ...[], - ...isAgentSwarmsEnabled() && hasTeams ? [/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(TeamStatus, { - teamsSelected, - showHint: showHint && !hasBackgroundTasks - }, "teams", false, undefined, this)] : [], - ...shouldShowPrStatus ? [/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(PrBadge, { - number: prStatus.number, - url: prStatus.url, - reviewState: prStatus.reviewState - }, "pr-status", false, undefined, this)] : [] - ]; - const hasAnyInProcessTeammates = Object.values(tasks2).some((t_2) => t_2.type === "in_process_teammate" && t_2.status === "running"); - const hasRunningAgentTasks = Object.values(tasks2).some((t_3) => t_3.type === "local_agent" && t_3.status === "running"); - const hintParts = showHint ? getSpinnerHintParts(isLoading, escShortcut, todosShortcut, killAgentsShortcut, hasTaskItems, expandedView, hasAnyInProcessTeammates, hasRunningAgentTasks, isKillAgentsConfirmShowing) : []; - if (isViewingCompletedTeammate) { - parts.push(/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: escShortcut, - action: "return to team lead" - }, undefined, false, undefined, this) - }, "esc-return", false, undefined, this)); - } else if (false) {} else if (!hasTeammatePills && showHint) { - parts.push(...hintParts); - } - if (hasTeammatePills) { - const otherParts = [...modePart ? [modePart] : [], ...parts, ...isViewingCompletedTeammate ? [] : hintParts]; - return /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(BackgroundTaskStatus, { - tasksSelected, - isViewingTeammate, - teammateFooterIndex, - isLeaderIdle: !isLoading, - onOpenDialog: onOpenTasksDialog - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - otherParts.length > 0 && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(Byline, { - children: otherParts - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - const hasCoordinatorTasks = false; - const tasksPart = hasBackgroundTasks && !hasTeammatePills && !shouldHideTasksFooter(tasks2, showSpinnerTree) ? /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(BackgroundTaskStatus, { - tasksSelected, - isViewingTeammate, - teammateFooterIndex, - isLeaderIdle: !isLoading, - onOpenDialog: onOpenTasksDialog - }, undefined, false, undefined, this) : null; - if (parts.length === 0 && !tasksPart && !modePart && showHint) { - parts.push(/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: "? for shortcuts" - }, "shortcuts-hint", false, undefined, this)); - } - const copyOnSelect = getGlobalConfig().copyOnSelect ?? true; - const selectionHintHasContent = hasSelection2 && (!copyOnSelect || isXtermJs()); - if (false) {} else if (isFullscreenEnvEnabled() && selectionHintHasContent) { - const isMac = getPlatform() === "macos"; - const altClickFailed = isMac && (selGetState()?.lastPressHadAlt ?? false); - parts.push(/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(Byline, { - children: [ - !copyOnSelect && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: "ctrl+c", - action: "copy" - }, undefined, false, undefined, this), - isXtermJs() && (altClickFailed ? /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - children: "set macOptionClickForcesSelection in VS Code settings" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: isMac ? "option+click" : "shift+click", - action: "native select" - }, undefined, false, undefined, this)) - ] - }, undefined, true, undefined, this) - }, "selection-copy", false, undefined, this)); - } else if (false) {} - if ((tasksPart || hasCoordinatorTasks) && showHint && !hasTeams) { - parts.push(/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: tasksSelected ? /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "view tasks" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2193", - action: "manage" - }, undefined, false, undefined, this) - }, "manage-tasks", false, undefined, this)); - } - if (parts.length === 0 && !tasksPart && !modePart) { - return isFullscreenEnvEnabled() ? /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) : null; - } - return /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - height: 1, - overflow: "hidden", - children: [ - modePart && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - flexShrink: 0, - children: [ - modePart, - (tasksPart || parts.length > 0) && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - tasksPart && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedBox_default, { - flexShrink: 0, - children: [ - tasksPart, - parts.length > 0 && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - parts.length > 0 && /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - wrap: "truncate", - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(Byline, { - children: parts - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -function getSpinnerHintParts(isLoading, escShortcut, todosShortcut, killAgentsShortcut, hasTaskItems, expandedView, hasTeammates, hasRunningAgentTasks, isKillAgentsConfirmShowing) { - let toggleAction; - if (hasTeammates) { - switch (expandedView) { - case "none": - toggleAction = "show tasks"; - break; - case "tasks": - toggleAction = "show teammates"; - break; - case "teammates": - toggleAction = "hide"; - break; - } - } else { - toggleAction = expandedView === "tasks" ? "hide tasks" : "show tasks"; - } - const showToggleHint = hasTaskItems || hasTeammates; - return [...isLoading ? [/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: escShortcut, - action: "interrupt" - }, undefined, false, undefined, this) - }, "esc", false, undefined, this)] : [], ...!isLoading && hasRunningAgentTasks && !isKillAgentsConfirmShowing ? [/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: killAgentsShortcut, - action: "stop agents" - }, undefined, false, undefined, this) - }, "kill-agents", false, undefined, this)] : [], ...showToggleHint ? [/* @__PURE__ */ jsx_dev_runtime431.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime431.jsxDEV(KeyboardShortcutHint, { - shortcut: todosShortcut, - action: toggleAction - }, undefined, false, undefined, this) - }, "toggle-tasks", false, undefined, this)] : []]; -} -function isPrStatusEnabled() { - return getGlobalConfig().prStatusFooterEnabled ?? true; -} -var import_compiler_runtime334, import_react254, jsx_dev_runtime431, proactiveModule3 = null, NO_OP_SUBSCRIBE = (_cb) => () => {}, NULL = () => null; -var init_PromptInputFooterLeftSide = __esm(() => { - init_ink2(); - init_figures(); - init_utils14(); - init_useShortcutDisplay(); - init_PermissionMode(); - init_BackgroundTaskStatus(); - init_LocalAgentTask(); - init_CoordinatorAgentStatus(); - init_taskStatusUtils(); - init_agentSwarmsEnabled(); - init_TeamStatus(); - init_registry(); - init_AppState(); - init_state(); - init_HistorySearchInput(); - init_usePrStatus(); - init_KeyboardShortcutHint(); - init_Byline(); - init_useTerminalSize(); - init_useTasksV2(); - init_format(); - init_VoiceIndicator(); - init_useVoiceEnabled(); - init_voice(); - init_fullscreen(); - init_terminal(); - init_use_selection(); - init_config(); - init_platform2(); - init_PrBadge(); - import_compiler_runtime334 = __toESM(require_compiler_runtime(), 1); - import_react254 = __toESM(require_react(), 1); - jsx_dev_runtime431 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/PromptInputFooter.tsx -function PromptInputFooter({ - apiKeyStatus, - debug: debug2, - exitMessage, - vimMode, - mode, - autoUpdaterResult, - isAutoUpdating, - verbose, - onAutoUpdaterResult, - onChangeIsUpdating, - suggestions, - selectedSuggestion, - maxColumnWidth, - toolPermissionContext, - helpOpen, - suppressHint: suppressHintFromProps, - isLoading, - tasksSelected, - teamsSelected, - bridgeSelected, - tmuxSelected, - teammateFooterIndex, - ideSelection, - mcpClients, - isPasting = false, - isInputWrapped = false, - messages, - isSearching, - historyQuery, - setHistoryQuery, - historyFailedMatch, - onOpenTasksDialog -}) { - const settings = useSettings(); - const { - columns, - rows - } = useTerminalSize(); - const messagesRef = import_react255.useRef(messages); - messagesRef.current = messages; - const lastAssistantMessageId = import_react255.useMemo(() => getLastAssistantMessageId(messages), [messages]); - const isNarrow = columns < 80; - const isFullscreen = isFullscreenEnvEnabled(); - const isShort = isFullscreen && rows < 24; - const coordinatorTaskCount = useCoordinatorTaskCount(); - const coordinatorTaskIndex = useAppState((s4) => s4.coordinatorTaskIndex); - const pillSelected = tasksSelected && (coordinatorTaskCount === 0 || coordinatorTaskIndex < 0); - const suppressHint = suppressHintFromProps || statusLineShouldDisplay(settings) || isSearching; - const overlayData = import_react255.useMemo(() => isFullscreen && suggestions.length ? { - suggestions, - selectedSuggestion, - maxColumnWidth - } : null, [isFullscreen, suggestions, selectedSuggestion, maxColumnWidth]); - useSetPromptOverlay(overlayData); - if (suggestions.length && !isFullscreen) { - return /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(ThemedBox_default, { - paddingX: 2, - paddingY: 0, - children: /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(PromptInputFooterSuggestions, { - suggestions, - selectedSuggestion, - maxColumnWidth - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - } - if (helpOpen) { - return /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(PromptInputHelpMenu, { - dimColor: true, - fixedWidth: true, - paddingX: 2 - }, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(jsx_dev_runtime432.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(ThemedBox_default, { - flexDirection: isNarrow ? "column" : "row", - justifyContent: isNarrow ? "flex-start" : "space-between", - paddingX: 2, - gap: isNarrow ? 0 : 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(ThemedBox_default, { - flexDirection: "column", - flexShrink: isNarrow ? 0 : 1, - children: [ - mode === "prompt" && !isShort && !exitMessage.show && !isPasting && statusLineShouldDisplay(settings) && /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(StatusLine, { - messagesRef, - lastAssistantMessageId, - vimMode - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(PromptInputFooterLeftSide, { - exitMessage, - vimMode, - mode, - toolPermissionContext, - suppressHint, - isLoading, - tasksSelected: pillSelected, - teamsSelected, - teammateFooterIndex, - tmuxSelected, - isPasting, - isSearching, - historyQuery, - setHistoryQuery, - historyFailedMatch, - onOpenTasksDialog - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(ThemedBox_default, { - flexShrink: 1, - gap: 1, - children: [ - isFullscreen ? null : /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(Notifications, { - apiKeyStatus, - autoUpdaterResult, - debug: debug2, - isAutoUpdating, - verbose, - messages, - onAutoUpdaterResult, - onChangeIsUpdating, - ideSelection, - mcpClients, - isInputWrapped, - isNarrow - }, undefined, false, undefined, this), - false, - /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(BridgeStatusIndicator, { - bridgeSelected - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - false - ] - }, undefined, true, undefined, this); -} -function BridgeStatusIndicator({ - bridgeSelected -}) { - if (true) - return null; - const enabled2 = useAppState((s4) => s4.replBridgeEnabled); - const connected = useAppState((s_0) => s_0.replBridgeConnected); - const sessionActive = useAppState((s_1) => s_1.replBridgeSessionActive); - const reconnecting = useAppState((s_2) => s_2.replBridgeReconnecting); - const explicit = useAppState((s_3) => s_3.replBridgeExplicit); - if (!isBridgeEnabled() || !enabled2) - return null; - const status2 = getBridgeStatus({ - error: undefined, - connected, - sessionActive, - reconnecting - }); - if (!explicit && status2.label !== "Remote Control reconnecting") { - return null; - } - return /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(ThemedText, { - color: bridgeSelected ? "background" : status2.color, - inverse: bridgeSelected, - wrap: "truncate", - children: [ - status2.label, - bridgeSelected && /* @__PURE__ */ jsx_dev_runtime432.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 Enter to view" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_react255, jsx_dev_runtime432, PromptInputFooter_default; -var init_PromptInputFooter = __esm(() => { - init_bridgeEnabled(); - init_bridgeStatusUtil(); - init_promptOverlayContext(); - init_useSettings(); - init_useTerminalSize(); - init_ink2(); - init_AppState(); - init_fullscreen(); - init_undercover(); - init_CoordinatorAgentStatus(); - init_StatusLine(); - init_Notifications(); - init_PromptInputFooterLeftSide(); - init_PromptInputFooterSuggestions(); - init_PromptInputHelpMenu(); - import_react255 = __toESM(require_react(), 1); - jsx_dev_runtime432 = __toESM(require_jsx_dev_runtime(), 1); - PromptInputFooter_default = import_react255.memo(PromptInputFooter); -}); - -// src/components/PromptInput/PromptInputModeIndicator.tsx -function getTeammateThemeColor() { - if (!isAgentSwarmsEnabled()) { - return; - } - const colorName = getTeammateColor(); - if (!colorName) { - return; - } - if (AGENT_COLORS.includes(colorName)) { - return AGENT_COLOR_TO_THEME_COLOR[colorName]; - } - return; -} -function PromptChar(t0) { - const $2 = import_compiler_runtime335.c(3); - const { - isLoading, - themeColor - } = t0; - const teammateColor = themeColor; - const color3 = teammateColor ?? undefined; - let t1; - if ($2[0] !== color3 || $2[1] !== isLoading) { - t1 = /* @__PURE__ */ jsx_dev_runtime433.jsxDEV(ThemedText, { - color: color3, - dimColor: isLoading, - children: [ - figures_default.pointer, - "\xA0" - ] - }, undefined, true, undefined, this); - $2[0] = color3; - $2[1] = isLoading; - $2[2] = t1; - } else { - t1 = $2[2]; - } - return t1; -} -function PromptInputModeIndicator(t0) { - const $2 = import_compiler_runtime335.c(6); - const { - mode, - isLoading, - viewingAgentName, - viewingAgentColor - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getTeammateThemeColor(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const teammateColor = t1; - const viewedTeammateThemeColor = viewingAgentColor ? AGENT_COLOR_TO_THEME_COLOR[viewingAgentColor] : undefined; - let t22; - if ($2[1] !== isLoading || $2[2] !== mode || $2[3] !== viewedTeammateThemeColor || $2[4] !== viewingAgentName) { - t22 = /* @__PURE__ */ jsx_dev_runtime433.jsxDEV(ThemedBox_default, { - alignItems: "flex-start", - alignSelf: "flex-start", - flexWrap: "nowrap", - justifyContent: "flex-start", - children: viewingAgentName ? /* @__PURE__ */ jsx_dev_runtime433.jsxDEV(PromptChar, { - isLoading, - themeColor: viewedTeammateThemeColor - }, undefined, false, undefined, this) : mode === "bash" ? /* @__PURE__ */ jsx_dev_runtime433.jsxDEV(ThemedText, { - color: "bashBorder", - dimColor: isLoading, - children: "!\xA0" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime433.jsxDEV(PromptChar, { - isLoading, - themeColor: isAgentSwarmsEnabled() ? teammateColor : undefined - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[1] = isLoading; - $2[2] = mode; - $2[3] = viewedTeammateThemeColor; - $2[4] = viewingAgentName; - $2[5] = t22; - } else { - t22 = $2[5]; - } - return t22; -} -var import_compiler_runtime335, jsx_dev_runtime433; -var init_PromptInputModeIndicator = __esm(() => { - init_figures(); - init_ink2(); - init_agentColorManager(); - init_teammate(); - init_agentSwarmsEnabled(); - import_compiler_runtime335 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime433 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/PromptInputQueuedCommands.tsx -function isIdleNotification2(value) { - try { - const parsed = jsonParse(value); - return parsed?.type === "idle_notification"; - } catch { - return false; - } -} -function createOverflowNotificationMessage(count4) { - return `<${TASK_NOTIFICATION_TAG}> -<${SUMMARY_TAG}>+${count4} more tasks completed -<${STATUS_TAG}>completed -`; -} -function processQueuedCommands(queuedCommands) { - const filteredCommands = queuedCommands.filter((cmd) => typeof cmd.value !== "string" || !isIdleNotification2(cmd.value)); - const taskNotifications = filteredCommands.filter((cmd) => cmd.mode === "task-notification"); - const otherCommands = filteredCommands.filter((cmd) => cmd.mode !== "task-notification"); - if (taskNotifications.length <= MAX_VISIBLE_NOTIFICATIONS) { - return [...otherCommands, ...taskNotifications]; - } - const visibleNotifications = taskNotifications.slice(0, MAX_VISIBLE_NOTIFICATIONS - 1); - const overflowCount = taskNotifications.length - (MAX_VISIBLE_NOTIFICATIONS - 1); - const overflowCommand = { - value: createOverflowNotificationMessage(overflowCount), - mode: "task-notification" - }; - return [...otherCommands, ...visibleNotifications, overflowCommand]; -} -function PromptInputQueuedCommandsImpl() { - const queuedCommands = useCommandQueue(); - const viewingAgent = useAppState((s4) => !!s4.viewingAgentTaskId); - const useBriefLayout = false; - const messages = import_react256.useMemo(() => { - if (queuedCommands.length === 0) - return null; - const visibleCommands = queuedCommands.filter(isQueuedCommandVisible); - if (visibleCommands.length === 0) - return null; - const processedCommands = processQueuedCommands(visibleCommands); - return normalizeMessages(processedCommands.map((cmd) => { - let content = cmd.value; - if (cmd.mode === "bash" && typeof content === "string") { - content = `${content}`; - } - return createUserMessage({ - content - }); - })); - }, [queuedCommands]); - if (viewingAgent || messages === null) { - return null; - } - return /* @__PURE__ */ jsx_dev_runtime434.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: messages.map((message, i6) => /* @__PURE__ */ jsx_dev_runtime434.jsxDEV(QueuedMessageProvider, { - isFirst: i6 === 0, - useBriefLayout, - children: /* @__PURE__ */ jsx_dev_runtime434.jsxDEV(Message4, { - message, - lookups: EMPTY_LOOKUPS, - addMargin: false, - tools: [], - commands: [], - verbose: false, - inProgressToolUseIDs: EMPTY_SET2, - progressMessagesForMessage: [], - shouldAnimate: false, - shouldShowDot: false, - isTranscriptMode: false, - isStatic: true - }, undefined, false, undefined, this) - }, i6, false, undefined, this)) - }, undefined, false, undefined, this); -} -var React139, import_react256, jsx_dev_runtime434, EMPTY_SET2, MAX_VISIBLE_NOTIFICATIONS = 3, PromptInputQueuedCommands; -var init_PromptInputQueuedCommands = __esm(() => { - init_ink2(); - init_AppState(); - init_xml(); - init_QueuedMessageContext(); - init_useCommandQueue(); - init_messageQueueManager(); - init_messages9(); - init_slowOperations(); - init_Message3(); - React139 = __toESM(require_react(), 1); - import_react256 = __toESM(require_react(), 1); - jsx_dev_runtime434 = __toESM(require_jsx_dev_runtime(), 1); - EMPTY_SET2 = new Set; - PromptInputQueuedCommands = React139.memo(PromptInputQueuedCommandsImpl); -}); - -// src/components/PromptInput/PromptInputStashNotice.tsx -function PromptInputStashNotice(t0) { - const $2 = import_compiler_runtime336.c(1); - const { - hasStash - } = t0; - if (!hasStash) { - return null; - } - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime435.jsxDEV(ThemedBox_default, { - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime435.jsxDEV(ThemedText, { - dimColor: true, - children: [ - figures_default.pointerSmall, - " Stashed (auto-restores after submit)" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[0] = t1; - } else { - t1 = $2[0]; - } - return t1; -} -var import_compiler_runtime336, jsx_dev_runtime435; -var init_PromptInputStashNotice = __esm(() => { - init_figures(); - init_ink2(); - import_compiler_runtime336 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime435 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/PromptInput/inputPaste.ts -function maybeTruncateMessageForInput(text, nextPasteId) { - if (text.length <= TRUNCATION_THRESHOLD) { - return { - truncatedText: text, - placeholderContent: "" - }; - } - const startLength = Math.floor(PREVIEW_LENGTH / 2); - const endLength = Math.floor(PREVIEW_LENGTH / 2); - const startText = text.slice(0, startLength); - const endText = text.slice(-endLength); - const placeholderContent = text.slice(startLength, -endLength); - const truncatedLines = getPastedTextRefNumLines(placeholderContent); - const placeholderId = nextPasteId; - const placeholderRef = formatTruncatedTextRef(placeholderId, truncatedLines); - const truncatedText = startText + placeholderRef + endText; - return { - truncatedText, - placeholderContent - }; -} -function formatTruncatedTextRef(id, numLines) { - return `[...Truncated text #${id} +${numLines} lines...]`; -} -function maybeTruncateInput(input, pastedContents) { - const existingIds = Object.keys(pastedContents).map(Number); - const nextPasteId = existingIds.length > 0 ? Math.max(...existingIds) + 1 : 1; - const { truncatedText, placeholderContent } = maybeTruncateMessageForInput(input, nextPasteId); - if (!placeholderContent) { - return { newInput: input, newPastedContents: pastedContents }; - } - return { - newInput: truncatedText, - newPastedContents: { - ...pastedContents, - [nextPasteId]: { - id: nextPasteId, - type: "text", - content: placeholderContent - } - } - }; -} -var TRUNCATION_THRESHOLD = 1e4, PREVIEW_LENGTH = 1000; -var init_inputPaste = __esm(() => { - init_history(); -}); - -// src/components/PromptInput/useMaybeTruncateInput.ts -function useMaybeTruncateInput({ - input, - pastedContents, - onInputChange, - setCursorOffset, - setPastedContents -}) { - const [hasAppliedTruncationToInput, setHasAppliedTruncationToInput] = import_react257.useState(false); - import_react257.useEffect(() => { - if (hasAppliedTruncationToInput) { - return; - } - if (input.length <= 1e4) { - return; - } - const { newInput, newPastedContents } = maybeTruncateInput(input, pastedContents); - onInputChange(newInput); - setCursorOffset(newInput.length); - setPastedContents(newPastedContents); - setHasAppliedTruncationToInput(true); - }, [ - input, - hasAppliedTruncationToInput, - pastedContents, - onInputChange, - setPastedContents, - setCursorOffset - ]); - import_react257.useEffect(() => { - if (input === "") { - setHasAppliedTruncationToInput(false); - } - }, [input]); -} -var import_react257; -var init_useMaybeTruncateInput = __esm(() => { - init_inputPaste(); - import_react257 = __toESM(require_react(), 1); -}); - -// src/utils/exampleCommands.ts -function isCoreFile(path26) { - return !NON_CORE_PATTERNS.some((p4) => p4.test(path26)); -} -function pickDiverseCoreFiles(sortedPaths, want) { - const picked = []; - const seenBasenames = new Set; - const dirTally = new Map; - for (let cap = 1;picked.length < want && cap <= want; cap++) { - for (const p4 of sortedPaths) { - if (picked.length >= want) - break; - if (!isCoreFile(p4)) - continue; - const lastSep = Math.max(p4.lastIndexOf("/"), p4.lastIndexOf("\\")); - const base2 = lastSep >= 0 ? p4.slice(lastSep + 1) : p4; - if (!base2 || seenBasenames.has(base2)) - continue; - const dir = lastSep >= 0 ? p4.slice(0, lastSep) : "."; - if ((dirTally.get(dir) ?? 0) >= cap) - continue; - picked.push(base2); - seenBasenames.add(base2); - dirTally.set(dir, (dirTally.get(dir) ?? 0) + 1); - } - } - return picked.length >= want ? picked : []; -} -async function getFrequentlyModifiedFiles() { - if (false) - ; - if (env2.platform === "win32") - return []; - if (!await getIsGit()) - return []; - try { - const userEmail = await getGitEmail(); - const logArgs = [ - "log", - "-n", - "1000", - "--pretty=format:", - "--name-only", - "--diff-filter=M" - ]; - const counts = new Map; - const tallyInto = (stdout) => { - for (const line of stdout.split(` -`)) { - const f4 = line.trim(); - if (f4) - counts.set(f4, (counts.get(f4) ?? 0) + 1); - } - }; - if (userEmail) { - const { stdout } = await execFileNoThrowWithCwd("git", [...logArgs, `--author=${userEmail}`], { cwd: getCwd() }); - tallyInto(stdout); - } - if (counts.size < 10) { - const { stdout } = await execFileNoThrowWithCwd(gitExe(), logArgs, { - cwd: getCwd() - }); - tallyInto(stdout); - } - const sorted = Array.from(counts.entries()).sort((a5, b5) => b5[1] - a5[1]).map(([p4]) => p4); - return pickDiverseCoreFiles(sorted, 5); - } catch (err2) { - logError2(err2); - return []; - } -} -var NON_CORE_PATTERNS, ONE_WEEK_IN_MS, getExampleCommandFromCache, refreshExampleCommands; -var init_exampleCommands = __esm(() => { - init_memoize(); - init_sample(); - init_cwd(); - init_config(); - init_env(); - init_execFileNoThrow(); - init_git(); - init_log2(); - init_user(); - NON_CORE_PATTERNS = [ - /(?:^|\/)(?:package-lock\.json|yarn\.lock|bun\.lock|bun\.lockb|pnpm-lock\.yaml|Pipfile\.lock|poetry\.lock|Cargo\.lock|Gemfile\.lock|go\.sum|composer\.lock|uv\.lock)$/, - /\.generated\./, - /(?:^|\/)(?:dist|build|out|target|node_modules|\.next|__pycache__)\//, - /\.(?:min\.js|min\.css|map|pyc|pyo)$/, - /\.(?:json|ya?ml|toml|xml|ini|cfg|conf|env|lock|txt|md|mdx|rst|csv|log|svg)$/i, - /(?:^|\/)\.?(?:eslintrc|prettierrc|babelrc|editorconfig|gitignore|gitattributes|dockerignore|npmrc)/, - /(?:^|\/)(?:tsconfig|jsconfig|biome|vitest\.config|jest\.config|webpack\.config|vite\.config|rollup\.config)\.[a-z]+$/, - /(?:^|\/)\.(?:github|vscode|idea|claude)\//, - /(?:^|\/)(?:CHANGELOG|LICENSE|CONTRIBUTING|CODEOWNERS|README)(?:\.[a-z]+)?$/i - ]; - ONE_WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000; - getExampleCommandFromCache = memoize_default(() => { - const projectConfig = getCurrentProjectConfig(); - const frequentFile = projectConfig.exampleFiles?.length ? sample_default(projectConfig.exampleFiles) : ""; - const commands7 = [ - "fix lint errors", - "fix typecheck errors", - `how does ${frequentFile} work?`, - `refactor ${frequentFile}`, - "how do I log an error?", - `edit ${frequentFile} to...`, - `write a test for ${frequentFile}`, - "create a util logging.py that..." - ]; - return `Try "${sample_default(commands7)}"`; - }); - refreshExampleCommands = memoize_default(async () => { - const projectConfig = getCurrentProjectConfig(); - const now2 = Date.now(); - const lastGenerated = projectConfig.exampleFilesGeneratedAt ?? 0; - if (now2 - lastGenerated > ONE_WEEK_IN_MS) { - projectConfig.exampleFiles = []; - } - if (!projectConfig.exampleFiles?.length) { - getFrequentlyModifiedFiles().then((files3) => { - if (files3.length) { - saveCurrentProjectConfig((current) => ({ - ...current, - exampleFiles: files3, - exampleFilesGeneratedAt: Date.now() - })); - } - }); - } - }); -}); - -// src/components/PromptInput/usePromptInputPlaceholder.ts -function usePromptInputPlaceholder({ - input, - submitCount, - viewingAgentName -}) { - const queuedCommands = useCommandQueue(); - const promptSuggestionEnabled = useAppState((s4) => s4.promptSuggestionEnabled); - const placeholder = import_react258.useMemo(() => { - if (input !== "") { - return; - } - if (viewingAgentName) { - const displayName = viewingAgentName.length > MAX_TEAMMATE_NAME_LENGTH ? viewingAgentName.slice(0, MAX_TEAMMATE_NAME_LENGTH - 3) + "..." : viewingAgentName; - return `Message @${displayName}\u2026`; - } - if (queuedCommands.some(isQueuedCommandEditable) && (getGlobalConfig().queuedCommandUpHintCount || 0) < NUM_TIMES_QUEUE_HINT_SHOWN) { - return "Press up to edit queued messages"; - } - if (submitCount < 1 && promptSuggestionEnabled && !proactiveModule4?.isProactiveActive()) { - return getExampleCommandFromCache(); - } - }, [ - input, - queuedCommands, - submitCount, - promptSuggestionEnabled, - viewingAgentName - ]); - return placeholder; -} -var import_react258, proactiveModule4 = null, NUM_TIMES_QUEUE_HINT_SHOWN = 3, MAX_TEAMMATE_NAME_LENGTH = 20; -var init_usePromptInputPlaceholder = __esm(() => { - init_useCommandQueue(); - init_AppState(); - init_config(); - init_exampleCommands(); - init_messageQueueManager(); - import_react258 = __toESM(require_react(), 1); -}); - -// src/components/PromptInput/useShowFastIconHint.ts -function useShowFastIconHint(showFastIcon) { - const [showHint, setShowHint] = import_react259.useState(false); - import_react259.useEffect(() => { - if (hasShownThisSession || !showFastIcon) { - return; - } - hasShownThisSession = true; - setShowHint(true); - const timer = setTimeout(setShowHint, HINT_DISPLAY_DURATION_MS, false); - return () => { - clearTimeout(timer); - setShowHint(false); - }; - }, [showFastIcon]); - return showHint; -} -var import_react259, HINT_DISPLAY_DURATION_MS = 5000, hasShownThisSession = false; -var init_useShowFastIconHint = __esm(() => { - import_react259 = __toESM(require_react(), 1); -}); - -// src/utils/standaloneAgent.ts -function getStandaloneAgentName(appState) { - if (getTeamName()) { - return; - } - return appState.standaloneAgentContext?.name; -} -var init_standaloneAgent = __esm(() => { - init_teammate(); -}); - -// src/components/PromptInput/useSwarmBanner.ts -function useSwarmBanner() { - const teamContext = useAppState((s4) => s4.teamContext); - const standaloneAgentContext = useAppState((s4) => s4.standaloneAgentContext); - const agent = useAppState((s4) => s4.agent); - useAppState((s4) => s4.viewingAgentTaskId); - const store = useAppStateStore(); - const [insideTmux, setInsideTmux] = React140.useState(null); - React140.useEffect(() => { - isInsideTmux().then(setInsideTmux); - }, []); - const state4 = store.getState(); - if (isTeammate() && !isInProcessTeammate()) { - const agentName = getAgentName(); - if (agentName && getTeamName()) { - return { - text: `@${agentName}`, - bgColor: toThemeColor(teamContext?.selfAgentColor ?? getTeammateColor()) - }; - } - } - const hasTeammates = teamContext?.teamName && teamContext.teammates && Object.keys(teamContext.teammates).length > 0; - if (hasTeammates) { - const viewedTeammate = getViewedTeammateTask(state4); - const viewedColor = toThemeColor(viewedTeammate?.identity.color); - const inProcessMode = isInProcessEnabled(); - const nativePanes = getCachedDetectionResult()?.isNative ?? false; - if (insideTmux === false && !inProcessMode && !nativePanes) { - return { - text: `View teammates: \`tmux -L ${getSwarmSocketName()} a\``, - bgColor: viewedColor - }; - } - if ((insideTmux === true || inProcessMode || nativePanes) && viewedTeammate) { - return { - text: `@${viewedTeammate.identity.agentName}`, - bgColor: viewedColor - }; - } - } - const active = getActiveAgentForInput(state4); - if (active.type === "named_agent") { - const task = active.task; - let name3; - for (const [n6, id] of state4.agentNameRegistry) { - if (id === task.id) { - name3 = n6; - break; - } - } - return { - text: name3 ? `@${name3}` : task.description, - bgColor: getAgentColor(task.agentType) ?? "cyan_FOR_SUBAGENTS_ONLY" - }; - } - const standaloneName = getStandaloneAgentName(state4); - const standaloneColor = standaloneAgentContext?.color; - if (standaloneName || standaloneColor) { - return { - text: standaloneName ?? "", - bgColor: toThemeColor(standaloneColor) - }; - } - if (agent) { - const agentDef = state4.agentDefinitions.activeAgents.find((a5) => a5.agentType === agent); - return { - text: agent, - bgColor: toThemeColor(agentDef?.color, "promptBorder") - }; - } - return null; -} -function toThemeColor(colorName, fallback = "cyan_FOR_SUBAGENTS_ONLY") { - return colorName && AGENT_COLORS.includes(colorName) ? AGENT_COLOR_TO_THEME_COLOR[colorName] : fallback; -} -var React140; -var init_useSwarmBanner = __esm(() => { - init_AppState(); - init_selectors(); - init_agentColorManager(); - init_standaloneAgent(); - init_detection(); - init_registry(); - init_teammate(); - init_teammateContext(); - React140 = __toESM(require_react(), 1); -}); - -// src/components/PromptInput/PromptInput.tsx -import * as path26 from "path"; -function PromptInput({ - debug: debug2, - ideSelection, - toolPermissionContext, - setToolPermissionContext, - apiKeyStatus, - commands: commands7, - agents: agents2, - isLoading, - verbose, - messages, - onAutoUpdaterResult, - autoUpdaterResult, - input, - onInputChange, - mode, - onModeChange, - stashedPrompt, - setStashedPrompt, - submitCount, - onShowMessageSelector, - onMessageActionsEnter, - mcpClients, - pastedContents, - setPastedContents, - vimMode, - setVimMode, - showBashesDialog, - setShowBashesDialog, - onExit: onExit2, - getToolUseContext, - onSubmit: onSubmitProp, - onAgentSubmit, - isSearchingHistory, - setIsSearchingHistory, - onDismissSideQuestion, - isSideQuestionVisible, - helpOpen, - setHelpOpen, - hasSuppressedDialogs, - isLocalJSXCommandActive = false, - insertTextRef, - voiceInterimRange -}) { - const mainLoopModel = useMainLoopModel(); - const isModalOverlayActive = useIsModalOverlayActive() || isLocalJSXCommandActive; - const [isAutoUpdating, setIsAutoUpdating] = import_react260.useState(false); - const [exitMessage, setExitMessage] = import_react260.useState({ - show: false - }); - const [cursorOffset, setCursorOffset] = import_react260.useState(input.length); - const lastInternalInputRef = React141.useRef(input); - if (input !== lastInternalInputRef.current) { - setCursorOffset(input.length); - lastInternalInputRef.current = input; - } - const trackAndSetInput = React141.useCallback((value) => { - lastInternalInputRef.current = value; - onInputChange(value); - }, [onInputChange]); - if (insertTextRef) { - insertTextRef.current = { - cursorOffset, - insert: (text) => { - const needsSpace = cursorOffset === input.length && input.length > 0 && !/\s$/.test(input); - const insertText = needsSpace ? " " + text : text; - const newValue = input.slice(0, cursorOffset) + insertText + input.slice(cursorOffset); - lastInternalInputRef.current = newValue; - onInputChange(newValue); - setCursorOffset(cursorOffset + insertText.length); - }, - setInputWithCursor: (value, cursor) => { - lastInternalInputRef.current = value; - onInputChange(value); - setCursorOffset(cursor); - } - }; - } - const store = useAppStateStore(); - const setAppState = useSetAppState(); - const tasks2 = useAppState((s4) => s4.tasks); - const replBridgeConnected = useAppState((s4) => s4.replBridgeConnected); - const replBridgeExplicit = useAppState((s4) => s4.replBridgeExplicit); - const replBridgeReconnecting = useAppState((s4) => s4.replBridgeReconnecting); - const bridgeFooterVisible = replBridgeConnected && (replBridgeExplicit || replBridgeReconnecting); - const hasTungstenSession = useAppState((s4) => false); - const tmuxFooterVisible = false; - const bagelFooterVisible = useAppState((s4) => false); - const teamContext = useAppState((s4) => s4.teamContext); - const queuedCommands = useCommandQueue(); - const promptSuggestionState = useAppState((s4) => s4.promptSuggestion); - const speculation = useAppState((s4) => s4.speculation); - const speculationSessionTimeSavedMs = useAppState((s4) => s4.speculationSessionTimeSavedMs); - const viewingAgentTaskId = useAppState((s4) => s4.viewingAgentTaskId); - const viewSelectionMode = useAppState((s4) => s4.viewSelectionMode); - const showSpinnerTree = useAppState((s4) => s4.expandedView) === "teammates"; - const { - companion: _companion, - companionMuted - } = { - companion: undefined, - companionMuted: undefined - }; - const companionFooterVisible = !!_companion && !companionMuted; - const briefOwnsGap = false; - const mainLoopModel_ = useAppState((s4) => s4.mainLoopModel); - const mainLoopModelForSession = useAppState((s4) => s4.mainLoopModelForSession); - const thinkingEnabled = useAppState((s4) => s4.thinkingEnabled); - const isFastMode = useAppState((s4) => isFastModeEnabled() ? s4.fastMode : false); - const effortValue = useAppState((s4) => s4.effortValue); - const viewedTeammate = getViewedTeammateTask(store.getState()); - const viewingAgentName = viewedTeammate?.identity.agentName; - const viewingAgentColor = viewedTeammate?.identity.color && AGENT_COLORS.includes(viewedTeammate.identity.color) ? viewedTeammate.identity.color : undefined; - const inProcessTeammates = import_react260.useMemo(() => getRunningTeammatesSorted(tasks2), [tasks2]); - const isTeammateMode = inProcessTeammates.length > 0 || viewedTeammate !== undefined; - const effectiveToolPermissionContext = import_react260.useMemo(() => { - if (viewedTeammate) { - return { - ...toolPermissionContext, - mode: viewedTeammate.permissionMode - }; - } - return toolPermissionContext; - }, [viewedTeammate, toolPermissionContext]); - const { - historyQuery, - setHistoryQuery, - historyMatch, - historyFailedMatch - } = useHistorySearch((entry) => { - setPastedContents(entry.pastedContents); - onSubmit(entry.display); - }, input, trackAndSetInput, setCursorOffset, cursorOffset, onModeChange, mode, isSearchingHistory, setIsSearchingHistory, setPastedContents, pastedContents); - const nextPasteIdRef = import_react260.useRef(-1); - if (nextPasteIdRef.current === -1) { - nextPasteIdRef.current = getInitialPasteId(messages); - } - const pendingSpaceAfterPillRef = import_react260.useRef(false); - const [showTeamsDialog, setShowTeamsDialog] = import_react260.useState(false); - const [showBridgeDialog, setShowBridgeDialog] = import_react260.useState(false); - const [teammateFooterIndex, setTeammateFooterIndex] = import_react260.useState(0); - const coordinatorTaskIndex = useAppState((s4) => s4.coordinatorTaskIndex); - const setCoordinatorTaskIndex = import_react260.useCallback((v6) => setAppState((prev) => { - const next2 = typeof v6 === "function" ? v6(prev.coordinatorTaskIndex) : v6; - if (next2 === prev.coordinatorTaskIndex) - return prev; - return { - ...prev, - coordinatorTaskIndex: next2 - }; - }), [setAppState]); - const coordinatorTaskCount = useCoordinatorTaskCount(); - const hasBgTaskPill = import_react260.useMemo(() => Object.values(tasks2).some((t4) => isBackgroundTask(t4) && true), [tasks2]); - const minCoordinatorIndex = hasBgTaskPill ? -1 : 0; - import_react260.useEffect(() => { - if (coordinatorTaskIndex >= coordinatorTaskCount) { - setCoordinatorTaskIndex(Math.max(minCoordinatorIndex, coordinatorTaskCount - 1)); - } else if (coordinatorTaskIndex < minCoordinatorIndex) { - setCoordinatorTaskIndex(minCoordinatorIndex); - } - }, [coordinatorTaskCount, coordinatorTaskIndex, minCoordinatorIndex]); - const [isPasting, setIsPasting] = import_react260.useState(false); - const [isExternalEditorActive, setIsExternalEditorActive] = import_react260.useState(false); - const [showModelPicker, setShowModelPicker] = import_react260.useState(false); - const [showQuickOpen, setShowQuickOpen] = import_react260.useState(false); - const [showGlobalSearch, setShowGlobalSearch] = import_react260.useState(false); - const [showHistoryPicker, setShowHistoryPicker] = import_react260.useState(false); - const [showFastModePicker, setShowFastModePicker] = import_react260.useState(false); - const [showThinkingToggle, setShowThinkingToggle] = import_react260.useState(false); - const [showAutoModeOptIn, setShowAutoModeOptIn] = import_react260.useState(false); - const [previousModeBeforeAuto, setPreviousModeBeforeAuto] = import_react260.useState(null); - const autoModeOptInTimeoutRef = import_react260.useRef(null); - const isCursorOnFirstLine = import_react260.useMemo(() => { - const firstNewlineIndex = input.indexOf(` -`); - if (firstNewlineIndex === -1) { - return true; - } - return cursorOffset <= firstNewlineIndex; - }, [input, cursorOffset]); - const isCursorOnLastLine = import_react260.useMemo(() => { - const lastNewlineIndex = input.lastIndexOf(` -`); - if (lastNewlineIndex === -1) { - return true; - } - return cursorOffset > lastNewlineIndex; - }, [input, cursorOffset]); - const cachedTeams = import_react260.useMemo(() => { - if (!isAgentSwarmsEnabled()) - return []; - if (isInProcessEnabled()) - return []; - if (!teamContext) { - return []; - } - const teammateCount = count2(Object.values(teamContext.teammates), (t4) => t4.name !== "team-lead"); - return [{ - name: teamContext.teamName, - memberCount: teammateCount, - runningCount: 0, - idleCount: 0 - }]; - }, [teamContext]); - const runningTaskCount = import_react260.useMemo(() => count2(Object.values(tasks2), (t4) => t4.status === "running"), [tasks2]); - const tasksFooterVisible = (runningTaskCount > 0 || false) && !shouldHideTasksFooter(tasks2, showSpinnerTree); - const teamsFooterVisible = cachedTeams.length > 0; - const footerItems = import_react260.useMemo(() => [tasksFooterVisible && "tasks", tmuxFooterVisible && "tmux", bagelFooterVisible && "bagel", teamsFooterVisible && "teams", bridgeFooterVisible && "bridge", companionFooterVisible && "companion"].filter(Boolean), [tasksFooterVisible, tmuxFooterVisible, bagelFooterVisible, teamsFooterVisible, bridgeFooterVisible, companionFooterVisible]); - const rawFooterSelection = useAppState((s4) => s4.footerSelection); - const footerItemSelected = rawFooterSelection && footerItems.includes(rawFooterSelection) ? rawFooterSelection : null; - import_react260.useEffect(() => { - if (rawFooterSelection && !footerItemSelected) { - setAppState((prev) => prev.footerSelection === null ? prev : { - ...prev, - footerSelection: null - }); - } - }, [rawFooterSelection, footerItemSelected, setAppState]); - const tasksSelected = footerItemSelected === "tasks"; - const tmuxSelected = footerItemSelected === "tmux"; - const bagelSelected = footerItemSelected === "bagel"; - const teamsSelected = footerItemSelected === "teams"; - const bridgeSelected = footerItemSelected === "bridge"; - function selectFooterItem(item) { - setAppState((prev) => prev.footerSelection === item ? prev : { - ...prev, - footerSelection: item - }); - if (item === "tasks") { - setTeammateFooterIndex(0); - setCoordinatorTaskIndex(minCoordinatorIndex); - } - } - function navigateFooter(delta, exitAtStart = false) { - const idx = footerItemSelected ? footerItems.indexOf(footerItemSelected) : -1; - const next2 = footerItems[idx + delta]; - if (next2) { - selectFooterItem(next2); - return true; - } - if (delta < 0 && exitAtStart) { - selectFooterItem(null); - return true; - } - return false; - } - const { - suggestion: promptSuggestion, - markAccepted, - logOutcomeAtSubmission, - markShown - } = usePromptSuggestion({ - inputValue: input, - isAssistantResponding: isLoading - }); - const displayedValue = import_react260.useMemo(() => isSearchingHistory && historyMatch ? getValueFromInput(typeof historyMatch === "string" ? historyMatch : historyMatch.display) : input, [isSearchingHistory, historyMatch, input]); - const thinkTriggers = import_react260.useMemo(() => findThinkingTriggerPositions(displayedValue), [displayedValue]); - const ultraplanSessionUrl = useAppState((s4) => s4.ultraplanSessionUrl); - const ultraplanLaunching = useAppState((s4) => s4.ultraplanLaunching); - const ultraplanTriggers = import_react260.useMemo(() => [], [displayedValue, ultraplanSessionUrl, ultraplanLaunching]); - const ultrareviewTriggers = import_react260.useMemo(() => isUltrareviewEnabled() ? findUltrareviewTriggerPositions(displayedValue) : [], [displayedValue]); - const btwTriggers = import_react260.useMemo(() => findBtwTriggerPositions(displayedValue), [displayedValue]); - const buddyTriggers = import_react260.useMemo(() => findBuddyTriggerPositions(displayedValue), [displayedValue]); - const slashCommandTriggers = import_react260.useMemo(() => { - const positions = findSlashCommandPositions(displayedValue); - return positions.filter((pos) => { - const commandName = displayedValue.slice(pos.start + 1, pos.end); - return hasCommand(commandName, commands7); - }); - }, [displayedValue, commands7]); - const tokenBudgetTriggers = import_react260.useMemo(() => [], [displayedValue]); - const knownChannelsVersion2 = import_react260.useSyncExternalStore(subscribeKnownChannels, getKnownChannelsVersion); - const slackChannelTriggers = import_react260.useMemo(() => hasSlackMcpServer(store.getState().mcp.clients) ? findSlackChannelPositions(displayedValue) : [], [displayedValue, knownChannelsVersion2]); - const memberMentionHighlights = import_react260.useMemo(() => { - if (!isAgentSwarmsEnabled()) - return []; - if (!teamContext?.teammates) - return []; - const highlights = []; - const members = teamContext.teammates; - if (!members) - return highlights; - const regex2 = /(^|\s)@([\w-]+)/g; - const memberValues = Object.values(members); - let match; - while ((match = regex2.exec(displayedValue)) !== null) { - const leadingSpace = match[1] ?? ""; - const nameStart = match.index + leadingSpace.length; - const fullMatch = match[0].trimStart(); - const name3 = match[2]; - const member = memberValues.find((t4) => t4.name === name3); - if (member?.color) { - const themeColor = AGENT_COLOR_TO_THEME_COLOR[member.color]; - if (themeColor) { - highlights.push({ - start: nameStart, - end: nameStart + fullMatch.length, - themeColor - }); - } - } - } - return highlights; - }, [displayedValue, teamContext]); - const imageRefPositions = import_react260.useMemo(() => parseReferences(displayedValue).filter((r4) => r4.match.startsWith("[Image")).map((r4) => ({ - start: r4.index, - end: r4.index + r4.match.length - })), [displayedValue]); - const cursorAtImageChip = imageRefPositions.some((r4) => r4.start === cursorOffset); - import_react260.useEffect(() => { - const inside = imageRefPositions.find((r4) => cursorOffset > r4.start && cursorOffset < r4.end); - if (inside) { - const mid = (inside.start + inside.end) / 2; - setCursorOffset(cursorOffset < mid ? inside.start : inside.end); - } - }, [cursorOffset, imageRefPositions, setCursorOffset]); - const combinedHighlights = import_react260.useMemo(() => { - const highlights = []; - for (const ref of imageRefPositions) { - if (cursorOffset === ref.start) { - highlights.push({ - start: ref.start, - end: ref.end, - color: undefined, - inverse: true, - priority: 8 - }); - } - } - if (isSearchingHistory && historyMatch && !historyFailedMatch) { - highlights.push({ - start: cursorOffset, - end: cursorOffset + historyQuery.length, - color: "warning", - priority: 20 - }); - } - for (const trigger of btwTriggers) { - highlights.push({ - start: trigger.start, - end: trigger.end, - color: "warning", - priority: 15 - }); - } - for (const trigger of slashCommandTriggers) { - highlights.push({ - start: trigger.start, - end: trigger.end, - color: "suggestion", - priority: 5 - }); - } - for (const trigger of tokenBudgetTriggers) { - highlights.push({ - start: trigger.start, - end: trigger.end, - color: "suggestion", - priority: 5 - }); - } - for (const trigger of slackChannelTriggers) { - highlights.push({ - start: trigger.start, - end: trigger.end, - color: "suggestion", - priority: 5 - }); - } - for (const mention of memberMentionHighlights) { - highlights.push({ - start: mention.start, - end: mention.end, - color: mention.themeColor, - priority: 5 - }); - } - if (voiceInterimRange) { - highlights.push({ - start: voiceInterimRange.start, - end: voiceInterimRange.end, - color: undefined, - dimColor: true, - priority: 1 - }); - } - if (isUltrathinkEnabled()) { - for (const trigger of thinkTriggers) { - for (let i6 = trigger.start;i6 < trigger.end; i6++) { - highlights.push({ - start: i6, - end: i6 + 1, - color: getRainbowColor(i6 - trigger.start), - shimmerColor: getRainbowColor(i6 - trigger.start, true), - priority: 10 - }); - } - } - } - if (false) {} - for (const trigger of ultrareviewTriggers) { - for (let i6 = trigger.start;i6 < trigger.end; i6++) { - highlights.push({ - start: i6, - end: i6 + 1, - color: getRainbowColor(i6 - trigger.start), - shimmerColor: getRainbowColor(i6 - trigger.start, true), - priority: 10 - }); - } - } - for (const trigger of buddyTriggers) { - for (let i6 = trigger.start;i6 < trigger.end; i6++) { - highlights.push({ - start: i6, - end: i6 + 1, - color: getRainbowColor(i6 - trigger.start), - shimmerColor: getRainbowColor(i6 - trigger.start, true), - priority: 10 - }); - } - } - return highlights; - }, [isSearchingHistory, historyQuery, historyMatch, historyFailedMatch, cursorOffset, btwTriggers, imageRefPositions, memberMentionHighlights, slashCommandTriggers, tokenBudgetTriggers, slackChannelTriggers, displayedValue, voiceInterimRange, thinkTriggers, ultraplanTriggers, ultrareviewTriggers, buddyTriggers]); - const { - addNotification, - removeNotification - } = useNotifications(); - import_react260.useEffect(() => { - if (thinkTriggers.length && isUltrathinkEnabled()) { - addNotification({ - key: "ultrathink-active", - text: "Effort set to high for this turn", - priority: "immediate", - timeoutMs: 5000 - }); - } else { - removeNotification("ultrathink-active"); - } - }, [addNotification, removeNotification, thinkTriggers.length]); - import_react260.useEffect(() => { - if (false) {} else { - removeNotification("ultraplan-active"); - } - }, [addNotification, removeNotification, ultraplanTriggers.length]); - import_react260.useEffect(() => { - if (isUltrareviewEnabled() && ultrareviewTriggers.length) { - addNotification({ - key: "ultrareview-active", - text: "Run /ultrareview after Claude finishes to review these changes in the cloud", - priority: "immediate", - timeoutMs: 5000 - }); - } - }, [addNotification, ultrareviewTriggers.length]); - const prevInputLengthRef = import_react260.useRef(input.length); - const peakInputLengthRef = import_react260.useRef(input.length); - const dismissStashHint = import_react260.useCallback(() => { - removeNotification("stash-hint"); - }, [removeNotification]); - import_react260.useEffect(() => { - const prevLength = prevInputLengthRef.current; - const peakLength = peakInputLengthRef.current; - const currentLength = input.length; - prevInputLengthRef.current = currentLength; - if (currentLength > peakLength) { - peakInputLengthRef.current = currentLength; - return; - } - if (currentLength === 0) { - peakInputLengthRef.current = 0; - return; - } - const clearedSubstantialInput = peakLength >= 20 && currentLength <= 5; - const wasRapidClear = prevLength >= 20 && currentLength <= 5; - if (clearedSubstantialInput && !wasRapidClear) { - const config10 = getGlobalConfig(); - if (!config10.hasUsedStash) { - addNotification({ - key: "stash-hint", - jsx: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Tip:", - " ", - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ConfigurableShortcutHint, { - action: "chat:stash", - context: "Chat", - fallback: "ctrl+s", - description: "stash" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "immediate", - timeoutMs: FOOTER_TEMPORARY_STATUS_TIMEOUT - }); - } - peakInputLengthRef.current = currentLength; - } - }, [input.length, addNotification]); - const { - pushToBuffer, - undo, - canUndo, - clearBuffer - } = useInputBuffer({ - maxBufferSize: 50, - debounceMs: 1000 - }); - useMaybeTruncateInput({ - input, - pastedContents, - onInputChange: trackAndSetInput, - setCursorOffset, - setPastedContents - }); - const defaultPlaceholder = usePromptInputPlaceholder({ - input, - submitCount, - viewingAgentName - }); - const onChange = import_react260.useCallback((value) => { - if (value === "?") { - logEvent("tengu_help_toggled", {}); - setHelpOpen((v6) => !v6); - return; - } - setHelpOpen(false); - dismissStashHint(); - abortPromptSuggestion(); - abortSpeculation(setAppState); - const isSingleCharInsertion = value.length === input.length + 1; - const insertedAtStart = cursorOffset === 0; - const mode2 = getModeFromInput(value); - if (insertedAtStart && mode2 !== "prompt") { - if (isSingleCharInsertion) { - onModeChange(mode2); - return; - } - if (input.length === 0) { - onModeChange(mode2); - const valueWithoutMode = getValueFromInput(value).replaceAll("\t", " "); - pushToBuffer(input, cursorOffset, pastedContents); - trackAndSetInput(valueWithoutMode); - setCursorOffset(valueWithoutMode.length); - return; - } - } - const processedValue = value.replaceAll("\t", " "); - if (input !== processedValue) { - pushToBuffer(input, cursorOffset, pastedContents); - } - setAppState((prev) => prev.footerSelection === null ? prev : { - ...prev, - footerSelection: null - }); - trackAndSetInput(processedValue); - }, [trackAndSetInput, onModeChange, input, cursorOffset, pushToBuffer, pastedContents, dismissStashHint, setAppState]); - const { - resetHistory, - onHistoryUp, - onHistoryDown, - dismissSearchHint, - historyIndex - } = useArrowKeyHistory((value, historyMode, pastedContents2) => { - onChange(value); - onModeChange(historyMode); - setPastedContents(pastedContents2); - }, input, pastedContents, setCursorOffset, mode); - import_react260.useEffect(() => { - if (isSearchingHistory) { - dismissSearchHint(); - } - }, [isSearchingHistory, dismissSearchHint]); - function handleHistoryUp() { - if (suggestions.length > 1) { - return; - } - if (!isCursorOnFirstLine) { - return; - } - const hasEditableCommand = queuedCommands.some(isQueuedCommandEditable); - if (hasEditableCommand) { - popAllCommandsFromQueue(); - return; - } - onHistoryUp(); - } - function handleHistoryDown() { - if (suggestions.length > 1) { - return; - } - if (!isCursorOnLastLine) { - return; - } - if (onHistoryDown() && footerItems.length > 0) { - const first = footerItems[0]; - selectFooterItem(first); - if (first === "tasks" && !getGlobalConfig().hasSeenTasksHint) { - saveGlobalConfig((c9) => c9.hasSeenTasksHint ? c9 : { - ...c9, - hasSeenTasksHint: true - }); - } - } - } - const [suggestionsState, setSuggestionsStateRaw] = import_react260.useState({ - suggestions: [], - selectedSuggestion: -1, - commandArgumentHint: undefined - }); - const setSuggestionsState = import_react260.useCallback((updater) => { - setSuggestionsStateRaw((prev) => typeof updater === "function" ? updater(prev) : updater); - }, []); - const onSubmit = import_react260.useCallback(async (inputParam, isSubmittingSlashCommand = false) => { - inputParam = inputParam.trimEnd(); - const state4 = store.getState(); - if (state4.footerSelection && footerItems.includes(state4.footerSelection)) { - return; - } - if (state4.viewSelectionMode === "selecting-agent") { - return; - } - const hasImages = Object.values(pastedContents).some((c9) => c9.type === "image"); - const suggestionText = promptSuggestionState.text; - const inputMatchesSuggestion = inputParam.trim() === "" || inputParam === suggestionText; - if (inputMatchesSuggestion && suggestionText && !hasImages && !state4.viewingAgentTaskId) { - if (speculation.status === "active") { - markAccepted(); - logOutcomeAtSubmission(suggestionText, { - skipReset: true - }); - onSubmitProp(suggestionText, { - setCursorOffset, - clearBuffer, - resetHistory - }, { - state: speculation, - speculationSessionTimeSavedMs, - setAppState - }); - return; - } - if (promptSuggestionState.shownAt > 0) { - markAccepted(); - inputParam = suggestionText; - } - } - if (isAgentSwarmsEnabled()) { - const directMessage = parseDirectMemberMessage(inputParam); - if (directMessage) { - const result = await sendDirectMemberMessage(directMessage.recipientName, directMessage.message, teamContext, writeToMailbox); - if (result.success) { - addNotification({ - key: "direct-message-sent", - text: `Sent to @${result.recipientName}`, - priority: "immediate", - timeoutMs: 3000 - }); - trackAndSetInput(""); - setCursorOffset(0); - clearBuffer(); - resetHistory(); - return; - } else if (result.error === "no_team_context") {} else {} - } - } - if (inputParam.trim() === "" && !hasImages) { - return; - } - const hasDirectorySuggestions = suggestionsState.suggestions.length > 0 && suggestionsState.suggestions.every((s4) => s4.description === "directory"); - if (suggestionsState.suggestions.length > 0 && !isSubmittingSlashCommand && !hasDirectorySuggestions) { - logForDebugging(`[onSubmit] early return: suggestions showing (count=${suggestionsState.suggestions.length})`); - return; - } - if (promptSuggestionState.text && promptSuggestionState.shownAt > 0) { - logOutcomeAtSubmission(inputParam); - } - removeNotification("stash-hint"); - const activeAgent = getActiveAgentForInput(store.getState()); - if (activeAgent.type !== "leader" && onAgentSubmit) { - logEvent("tengu_transcript_input_to_teammate", {}); - await onAgentSubmit(inputParam, activeAgent.task, { - setCursorOffset, - clearBuffer, - resetHistory - }); - return; - } - await onSubmitProp(inputParam, { - setCursorOffset, - clearBuffer, - resetHistory - }); - }, [promptSuggestionState, speculation, speculationSessionTimeSavedMs, teamContext, store, footerItems, suggestionsState.suggestions, onSubmitProp, onAgentSubmit, clearBuffer, resetHistory, logOutcomeAtSubmission, setAppState, markAccepted, pastedContents, removeNotification]); - const { - suggestions, - selectedSuggestion, - commandArgumentHint, - inlineGhostText, - maxColumnWidth - } = useTypeahead({ - commands: commands7, - onInputChange: trackAndSetInput, - onSubmit, - setCursorOffset, - input, - cursorOffset, - mode, - agents: agents2, - setSuggestionsState, - suggestionsState, - suppressSuggestions: isSearchingHistory || historyIndex > 0, - markAccepted, - onModeChange - }); - const showPromptSuggestion = mode === "prompt" && suggestions.length === 0 && promptSuggestion && !viewingAgentTaskId; - if (showPromptSuggestion) { - markShown(); - } - if (promptSuggestionState.text && !promptSuggestion && promptSuggestionState.shownAt === 0 && !viewingAgentTaskId) { - logSuggestionSuppressed("timing", promptSuggestionState.text); - setAppState((prev) => ({ - ...prev, - promptSuggestion: { - text: null, - promptId: null, - shownAt: 0, - acceptedAt: 0, - generationRequestId: null - } - })); - } - function onImagePaste(image, mediaType, filename, dimensions, sourcePath) { - logEvent("tengu_paste_image", {}); - onModeChange("prompt"); - const pasteId = nextPasteIdRef.current++; - const newContent = { - id: pasteId, - type: "image", - content: image, - mediaType: mediaType || "image/png", - filename: filename || "Pasted image", - dimensions, - sourcePath - }; - cacheImagePath(newContent); - storeImage(newContent); - setPastedContents((prev) => ({ - ...prev, - [pasteId]: newContent - })); - const prefix = pendingSpaceAfterPillRef.current ? " " : ""; - insertTextAtCursor(prefix + formatImageRef(pasteId)); - pendingSpaceAfterPillRef.current = true; - } - import_react260.useEffect(() => { - const referencedIds = new Set(parseReferences(input).map((r4) => r4.id)); - setPastedContents((prev) => { - const orphaned = Object.values(prev).filter((c9) => c9.type === "image" && !referencedIds.has(c9.id)); - if (orphaned.length === 0) - return prev; - const next2 = { - ...prev - }; - for (const img of orphaned) - delete next2[img.id]; - return next2; - }); - }, [input, setPastedContents]); - function onTextPaste(rawText) { - pendingSpaceAfterPillRef.current = false; - let text = stripAnsi(rawText).replace(/\r/g, ` -`).replaceAll("\t", " "); - if (input.length === 0) { - const pastedMode = getModeFromInput(text); - if (pastedMode !== "prompt") { - onModeChange(pastedMode); - text = getValueFromInput(text); - } - } - const numLines = getPastedTextRefNumLines(text); - const maxLines = Math.min(rows - 10, 2); - if (text.length > PASTE_THRESHOLD || numLines > maxLines) { - const pasteId = nextPasteIdRef.current++; - const newContent = { - id: pasteId, - type: "text", - content: text - }; - setPastedContents((prev) => ({ - ...prev, - [pasteId]: newContent - })); - insertTextAtCursor(formatPastedTextRef(pasteId, numLines)); - } else { - insertTextAtCursor(text); - } - } - const lazySpaceInputFilter = import_react260.useCallback((input2, key2) => { - if (!pendingSpaceAfterPillRef.current) - return input2; - pendingSpaceAfterPillRef.current = false; - if (isNonSpacePrintable(input2, key2)) - return " " + input2; - return input2; - }, []); - function insertTextAtCursor(text) { - pushToBuffer(input, cursorOffset, pastedContents); - const newInput = input.slice(0, cursorOffset) + text + input.slice(cursorOffset); - trackAndSetInput(newInput); - setCursorOffset(cursorOffset + text.length); - } - const doublePressEscFromEmpty = useDoublePress(() => {}, () => onShowMessageSelector()); - const popAllCommandsFromQueue = import_react260.useCallback(() => { - const result = popAllEditable(input, cursorOffset); - if (!result) { - return false; - } - trackAndSetInput(result.text); - onModeChange("prompt"); - setCursorOffset(result.cursorOffset); - if (result.images.length > 0) { - setPastedContents((prev) => { - const newContents = { - ...prev - }; - for (const image of result.images) { - newContents[image.id] = image; - } - return newContents; - }); - } - return true; - }, [trackAndSetInput, onModeChange, input, cursorOffset, setPastedContents]); - const onIdeAtMentioned = function(atMentioned) { - logEvent("tengu_ext_at_mentioned", {}); - let atMentionedText; - const relativePath2 = path26.relative(getCwd(), atMentioned.filePath); - if (atMentioned.lineStart && atMentioned.lineEnd) { - atMentionedText = atMentioned.lineStart === atMentioned.lineEnd ? `@${relativePath2}#L${atMentioned.lineStart} ` : `@${relativePath2}#L${atMentioned.lineStart}-${atMentioned.lineEnd} `; - } else { - atMentionedText = `@${relativePath2} `; - } - const cursorChar = input[cursorOffset - 1] ?? " "; - if (!/\s/.test(cursorChar)) { - atMentionedText = ` ${atMentionedText}`; - } - insertTextAtCursor(atMentionedText); - }; - useIdeAtMentioned(mcpClients, onIdeAtMentioned); - const handleUndo = import_react260.useCallback(() => { - if (canUndo) { - const previousState = undo(); - if (previousState) { - trackAndSetInput(previousState.text); - setCursorOffset(previousState.cursorOffset); - setPastedContents(previousState.pastedContents); - } - } - }, [canUndo, undo, trackAndSetInput, setPastedContents]); - const handleNewline = import_react260.useCallback(() => { - pushToBuffer(input, cursorOffset, pastedContents); - const newInput = input.slice(0, cursorOffset) + ` -` + input.slice(cursorOffset); - trackAndSetInput(newInput); - setCursorOffset(cursorOffset + 1); - }, [input, cursorOffset, trackAndSetInput, setCursorOffset, pushToBuffer, pastedContents]); - const handleExternalEditor = import_react260.useCallback(async () => { - logEvent("tengu_external_editor_used", {}); - setIsExternalEditorActive(true); - try { - const result = await editPromptInEditor(input, pastedContents); - if (result.error) { - addNotification({ - key: "external-editor-error", - text: result.error, - color: "warning", - priority: "high" - }); - } - if (result.content !== null && result.content !== input) { - pushToBuffer(input, cursorOffset, pastedContents); - trackAndSetInput(result.content); - setCursorOffset(result.content.length); - } - } catch (err2) { - if (err2 instanceof Error) { - logError2(err2); - } - addNotification({ - key: "external-editor-error", - text: `External editor failed: ${errorMessage(err2)}`, - color: "warning", - priority: "high" - }); - } finally { - setIsExternalEditorActive(false); - } - }, [input, cursorOffset, pastedContents, pushToBuffer, trackAndSetInput, addNotification]); - const handleStash = import_react260.useCallback(() => { - if (input.trim() === "" && stashedPrompt !== undefined) { - trackAndSetInput(stashedPrompt.text); - setCursorOffset(stashedPrompt.cursorOffset); - setPastedContents(stashedPrompt.pastedContents); - setStashedPrompt(undefined); - } else if (input.trim() !== "") { - setStashedPrompt({ - text: input, - cursorOffset, - pastedContents - }); - trackAndSetInput(""); - setCursorOffset(0); - setPastedContents({}); - saveGlobalConfig((c9) => { - if (c9.hasUsedStash) - return c9; - return { - ...c9, - hasUsedStash: true - }; - }); - } - }, [input, cursorOffset, stashedPrompt, trackAndSetInput, setStashedPrompt, pastedContents, setPastedContents]); - const handleModelPicker = import_react260.useCallback(() => { - setShowModelPicker((prev) => !prev); - if (helpOpen) { - setHelpOpen(false); - } - }, [helpOpen]); - const handleFastModePicker = import_react260.useCallback(() => { - setShowFastModePicker((prev) => !prev); - if (helpOpen) { - setHelpOpen(false); - } - }, [helpOpen]); - const handleThinkingToggle = import_react260.useCallback(() => { - setShowThinkingToggle((prev) => !prev); - if (helpOpen) { - setHelpOpen(false); - } - }, [helpOpen]); - const handleCycleMode = import_react260.useCallback(() => { - if (isAgentSwarmsEnabled() && viewedTeammate && viewingAgentTaskId) { - const teammateContext = { - ...toolPermissionContext, - mode: viewedTeammate.permissionMode - }; - const nextMode2 = getNextPermissionMode(teammateContext, undefined); - logEvent("tengu_mode_cycle", { - to: nextMode2 - }); - const teammateTaskId = viewingAgentTaskId; - setAppState((prev) => { - const task = prev.tasks[teammateTaskId]; - if (!task || task.type !== "in_process_teammate") { - return prev; - } - if (task.permissionMode === nextMode2) { - return prev; - } - return { - ...prev, - tasks: { - ...prev.tasks, - [teammateTaskId]: { - ...task, - permissionMode: nextMode2 - } - } - }; - }); - if (helpOpen) { - setHelpOpen(false); - } - return; - } - logForDebugging(`[auto-mode] handleCycleMode: currentMode=${toolPermissionContext.mode} isAutoModeAvailable=${toolPermissionContext.isAutoModeAvailable} showAutoModeOptIn=${showAutoModeOptIn} timeoutPending=${!!autoModeOptInTimeoutRef.current}`); - const nextMode = getNextPermissionMode(toolPermissionContext, teamContext); - let isEnteringAutoModeFirstTime = false; - if (false) {} - if (false) {} - if (false) {} - const { - context: preparedContext - } = cyclePermissionMode(toolPermissionContext, teamContext); - logEvent("tengu_mode_cycle", { - to: nextMode - }); - if (nextMode === "plan") { - saveGlobalConfig((current) => ({ - ...current, - lastPlanModeUse: Date.now() - })); - } - setAppState((prev) => ({ - ...prev, - toolPermissionContext: { - ...preparedContext, - mode: nextMode - } - })); - setToolPermissionContext({ - ...preparedContext, - mode: nextMode - }); - syncTeammateMode(nextMode, teamContext?.teamName); - if (helpOpen) { - setHelpOpen(false); - } - }, [toolPermissionContext, teamContext, viewingAgentTaskId, viewedTeammate, setAppState, setToolPermissionContext, helpOpen, showAutoModeOptIn]); - const handleAutoModeOptInAccept = import_react260.useCallback(() => { - if (false) {} - }, [helpOpen, setHelpOpen, previousModeBeforeAuto, toolPermissionContext, setAppState, setToolPermissionContext]); - const handleAutoModeOptInDecline = import_react260.useCallback(() => { - if (false) {} - }, [previousModeBeforeAuto, toolPermissionContext, setAppState, setToolPermissionContext]); - const handleImagePaste = import_react260.useCallback(() => { - getImageFromClipboard().then((imageData) => { - if (imageData) { - onImagePaste(imageData.base64, imageData.mediaType); - } else { - const shortcutDisplay = getShortcutDisplay("chat:imagePaste", "Chat", "ctrl+v"); - const message = env2.isSSH() ? "No image found in clipboard. You're SSH'd; try scp?" : `No image found in clipboard. Use ${shortcutDisplay} to paste images.`; - addNotification({ - key: "no-image-in-clipboard", - text: message, - priority: "immediate", - timeoutMs: 1000 - }); - } - }); - }, [addNotification, onImagePaste]); - const keybindingContext = useOptionalKeybindingContext(); - import_react260.useEffect(() => { - if (!keybindingContext || isModalOverlayActive) - return; - return keybindingContext.registerHandler({ - action: "chat:submit", - context: "Chat", - handler: () => { - onSubmit(input); - } - }); - }, [keybindingContext, isModalOverlayActive, onSubmit, input]); - const chatHandlers = import_react260.useMemo(() => ({ - "chat:undo": handleUndo, - "chat:newline": handleNewline, - "chat:externalEditor": handleExternalEditor, - "chat:stash": handleStash, - "chat:modelPicker": handleModelPicker, - "chat:thinkingToggle": handleThinkingToggle, - "chat:cycleMode": handleCycleMode, - "chat:imagePaste": handleImagePaste - }), [handleUndo, handleNewline, handleExternalEditor, handleStash, handleModelPicker, handleThinkingToggle, handleCycleMode, handleImagePaste]); - useKeybindings(chatHandlers, { - context: "Chat", - isActive: !isModalOverlayActive - }); - useKeybinding("chat:messageActions", () => onMessageActionsEnter?.(), { - context: "Chat", - isActive: !isModalOverlayActive && !isSearchingHistory - }); - useKeybinding("chat:fastMode", handleFastModePicker, { - context: "Chat", - isActive: !isModalOverlayActive && isFastModeEnabled() && isFastModeAvailable() - }); - useKeybinding("help:dismiss", () => { - setHelpOpen(false); - }, { - context: "Help", - isActive: helpOpen - }); - const quickSearchActive = false; - useKeybinding("app:quickOpen", () => { - if (false) {} - }, { - context: "Global", - isActive: quickSearchActive - }); - useKeybinding("app:globalSearch", () => { - if (false) {} - }, { - context: "Global", - isActive: quickSearchActive - }); - useKeybinding("history:search", () => { - if (false) {} - }, { - context: "Global", - isActive: false - }); - useKeybinding("app:interrupt", () => { - abortSpeculation(setAppState); - }, { - context: "Global", - isActive: !isLoading && speculation.status === "active" - }); - useKeybindings({ - "footer:up": () => { - if (tasksSelected && false) {} - navigateFooter(-1, true); - }, - "footer:down": () => { - if (tasksSelected && false) {} - if (tasksSelected && !isTeammateMode) { - setShowBashesDialog(true); - selectFooterItem(null); - return; - } - navigateFooter(1); - }, - "footer:next": () => { - if (tasksSelected && isTeammateMode) { - const totalAgents = 1 + inProcessTeammates.length; - setTeammateFooterIndex((prev) => (prev + 1) % totalAgents); - return; - } - navigateFooter(1); - }, - "footer:previous": () => { - if (tasksSelected && isTeammateMode) { - const totalAgents = 1 + inProcessTeammates.length; - setTeammateFooterIndex((prev) => (prev - 1 + totalAgents) % totalAgents); - return; - } - navigateFooter(-1); - }, - "footer:openSelected": () => { - if (viewSelectionMode === "selecting-agent") { - return; - } - switch (footerItemSelected) { - case "companion": - if (false) {} - break; - case "tasks": - if (isTeammateMode) { - if (teammateFooterIndex === 0) { - exitTeammateView(setAppState); - } else { - const teammate = inProcessTeammates[teammateFooterIndex - 1]; - if (teammate) - enterTeammateView(teammate.id, setAppState); - } - } else if (coordinatorTaskIndex === 0 && coordinatorTaskCount > 0) { - exitTeammateView(setAppState); - } else { - const selectedTaskId = getVisibleAgentTasks(tasks2)[coordinatorTaskIndex - 1]?.id; - if (selectedTaskId) { - enterTeammateView(selectedTaskId, setAppState); - } else { - setShowBashesDialog(true); - selectFooterItem(null); - } - } - break; - case "tmux": - if (false) {} - break; - case "bagel": - break; - case "teams": - setShowTeamsDialog(true); - selectFooterItem(null); - break; - case "bridge": - setShowBridgeDialog(true); - selectFooterItem(null); - break; - } - }, - "footer:clearSelection": () => { - selectFooterItem(null); - }, - "footer:close": () => { - if (tasksSelected && coordinatorTaskIndex >= 1) { - const task = getVisibleAgentTasks(tasks2)[coordinatorTaskIndex - 1]; - if (!task) - return false; - if (viewSelectionMode === "viewing-agent" && task.id === viewingAgentTaskId) { - onChange(input.slice(0, cursorOffset) + "x" + input.slice(cursorOffset)); - setCursorOffset(cursorOffset + 1); - return; - } - stopOrDismissAgent(task.id, setAppState); - if (task.status !== "running") { - setCoordinatorTaskIndex((i6) => Math.max(minCoordinatorIndex, i6 - 1)); - } - return; - } - return false; - } - }, { - context: "Footer", - isActive: !!footerItemSelected && !isModalOverlayActive - }); - use_input_default((char, key2) => { - if (showTeamsDialog || showQuickOpen || showGlobalSearch || showHistoryPicker) { - return; - } - if (getPlatform() === "macos" && isMacosOptionChar(char)) { - const shortcut = MACOS_OPTION_SPECIAL_CHARS[char]; - const terminalName = getNativeCSIuTerminalDisplayName(); - const jsx = terminalName ? /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "To enable ", - shortcut, - ", set ", - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - bold: true, - children: "Option as Meta" - }, undefined, false, undefined, this), - " in", - " ", - terminalName, - " preferences (\u2318,)" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "To enable ", - shortcut, - ", run /terminal-setup" - ] - }, undefined, true, undefined, this); - addNotification({ - key: "option-meta-hint", - jsx, - priority: "immediate", - timeoutMs: 5000 - }); - } - if (footerItemSelected && char && !key2.ctrl && !key2.meta && !key2.escape && !key2.return) { - onChange(input.slice(0, cursorOffset) + char + input.slice(cursorOffset)); - setCursorOffset(cursorOffset + char.length); - return; - } - if (cursorOffset === 0 && (key2.escape || key2.backspace || key2.delete || key2.ctrl && char === "u")) { - onModeChange("prompt"); - setHelpOpen(false); - } - if (helpOpen && input === "" && (key2.backspace || key2.delete)) { - setHelpOpen(false); - } - if (key2.escape) { - if (speculation.status === "active") { - abortSpeculation(setAppState); - return; - } - if (isSideQuestionVisible && onDismissSideQuestion) { - onDismissSideQuestion(); - return; - } - if (helpOpen) { - setHelpOpen(false); - return; - } - if (footerItemSelected) { - return; - } - const hasEditableCommand = queuedCommands.some(isQueuedCommandEditable); - if (hasEditableCommand) { - popAllCommandsFromQueue(); - return; - } - if (messages.length > 0 && !input && !isLoading) { - doublePressEscFromEmpty(); - } - } - if (key2.return && helpOpen) { - setHelpOpen(false); - } - }); - const swarmBanner = useSwarmBanner(); - const fastModeCooldown = isFastModeEnabled() ? isFastModeCooldown() : false; - const showFastIcon = isFastModeEnabled() ? isFastMode && (isFastModeAvailable() || fastModeCooldown) : false; - const showFastIconHint = useShowFastIconHint(showFastIcon ?? false); - const effortNotificationText = briefOwnsGap ? undefined : getEffortNotificationText(effortValue, mainLoopModel); - import_react260.useEffect(() => { - if (!effortNotificationText) { - removeNotification("effort-level"); - return; - } - addNotification({ - key: "effort-level", - text: effortNotificationText, - priority: "high", - timeoutMs: 12000 - }); - }, [effortNotificationText, addNotification, removeNotification]); - useBuddyNotification(); - const companionSpeaking = false; - const { - columns, - rows - } = useTerminalSize(); - const textInputColumns = columns - 3 - companionReservedColumns(columns, companionSpeaking); - const maxVisibleLines = isFullscreenEnvEnabled() ? Math.max(MIN_INPUT_VIEWPORT_LINES, Math.floor(rows / 2) - PROMPT_FOOTER_LINES) : undefined; - const handleInputClick = import_react260.useCallback((e4) => { - if (!input || isSearchingHistory) - return; - const c9 = Cursor.fromText(input, textInputColumns, cursorOffset); - const viewportStart = c9.getViewportStartLine(maxVisibleLines); - const offset = c9.measuredText.getOffsetFromPosition({ - line: e4.localRow + viewportStart, - column: e4.localCol - }); - setCursorOffset(offset); - }, [input, textInputColumns, isSearchingHistory, cursorOffset, maxVisibleLines]); - const handleOpenTasksDialog = import_react260.useCallback((taskId) => setShowBashesDialog(taskId ?? true), [setShowBashesDialog]); - const placeholder = showPromptSuggestion && promptSuggestion ? promptSuggestion : defaultPlaceholder; - const isInputWrapped = import_react260.useMemo(() => input.includes(` -`), [input]); - const handleModelSelect = import_react260.useCallback((model, _effort) => { - let wasFastModeDisabled = false; - setAppState((prev) => { - wasFastModeDisabled = isFastModeEnabled() && !isFastModeSupportedByModel(model) && !!prev.fastMode; - return { - ...prev, - mainLoopModel: model, - mainLoopModelForSession: null, - ...wasFastModeDisabled && { - fastMode: false - } - }; - }); - setShowModelPicker(false); - const effectiveFastMode = (isFastMode ?? false) && !wasFastModeDisabled; - let message = `Model set to ${modelDisplayString(model)}`; - if (isBilledAsExtraUsage(model, effectiveFastMode, isOpus1mMergeEnabled())) { - message += " \xB7 Billed as extra usage"; - } - if (wasFastModeDisabled) { - message += " \xB7 Fast mode OFF"; - } - addNotification({ - key: "model-switched", - jsx: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - children: message - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 3000 - }); - logEvent("tengu_model_picker_hotkey", { - model - }); - }, [setAppState, addNotification, isFastMode]); - const handleModelCancel = import_react260.useCallback(() => { - setShowModelPicker(false); - }, []); - const modelPickerElement = import_react260.useMemo(() => { - if (!showModelPicker) - return null; - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ModelPicker, { - initial: mainLoopModel_, - sessionModel: mainLoopModelForSession, - onSelect: handleModelSelect, - onCancel: handleModelCancel, - isStandaloneCommand: true, - showFastModeNotice: isFastModeEnabled() && isFastMode && isFastModeSupportedByModel(mainLoopModel_) && isFastModeAvailable() - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - }, [showModelPicker, mainLoopModel_, mainLoopModelForSession, handleModelSelect, handleModelCancel]); - const handleFastModeSelect = import_react260.useCallback((result) => { - setShowFastModePicker(false); - if (result) { - addNotification({ - key: "fast-mode-toggled", - jsx: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - children: result - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 3000 - }); - } - }, [addNotification]); - const fastModePickerElement = import_react260.useMemo(() => { - if (!showFastModePicker) - return null; - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(FastModePicker, { - onDone: handleFastModeSelect, - unavailableReason: getFastModeUnavailableReason() - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - }, [showFastModePicker, handleFastModeSelect]); - const handleThinkingSelect = import_react260.useCallback((enabled2) => { - setAppState((prev) => ({ - ...prev, - thinkingEnabled: enabled2 - })); - setShowThinkingToggle(false); - logEvent("tengu_thinking_toggled_hotkey", { - enabled: enabled2 - }); - addNotification({ - key: "thinking-toggled-hotkey", - jsx: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - color: enabled2 ? "suggestion" : undefined, - dimColor: !enabled2, - children: [ - "Thinking ", - enabled2 ? "on" : "off" - ] - }, undefined, true, undefined, this), - priority: "immediate", - timeoutMs: 3000 - }); - }, [setAppState, addNotification]); - const handleThinkingCancel = import_react260.useCallback(() => { - setShowThinkingToggle(false); - }, []); - const thinkingToggleElement = import_react260.useMemo(() => { - if (!showThinkingToggle) - return null; - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThinkingToggle, { - currentValue: thinkingEnabled ?? true, - onSelect: handleThinkingSelect, - onCancel: handleThinkingCancel, - isMidConversation: messages.some((m4) => m4.type === "assistant") - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - }, [showThinkingToggle, thinkingEnabled, handleThinkingSelect, handleThinkingCancel, messages.length]); - const autoModeOptInDialog = import_react260.useMemo(() => null, [showAutoModeOptIn, handleAutoModeOptInAccept, handleAutoModeOptInDecline]); - useSetPromptOverlayDialog(isFullscreenEnvEnabled() ? autoModeOptInDialog : null); - if (showBashesDialog) { - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(BackgroundTasksDialog, { - onDone: () => setShowBashesDialog(false), - toolUseContext: getToolUseContext(messages, [], new AbortController, mainLoopModel), - initialDetailTaskId: typeof showBashesDialog === "string" ? showBashesDialog : undefined - }, undefined, false, undefined, this); - } - if (isAgentSwarmsEnabled() && showTeamsDialog) { - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(TeamsDialog, { - initialTeams: cachedTeams, - onDone: () => { - setShowTeamsDialog(false); - } - }, undefined, false, undefined, this); - } - if (false) {} - if (false) {} - if (modelPickerElement) { - return modelPickerElement; - } - if (fastModePickerElement) { - return fastModePickerElement; - } - if (thinkingToggleElement) { - return thinkingToggleElement; - } - if (showBridgeDialog) { - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(BridgeDialog, { - onDone: () => { - setShowBridgeDialog(false); - selectFooterItem(null); - } - }, undefined, false, undefined, this); - } - const baseProps = { - multiline: true, - onSubmit, - onChange, - value: historyMatch ? getValueFromInput(typeof historyMatch === "string" ? historyMatch : historyMatch.display) : input, - onHistoryUp: handleHistoryUp, - onHistoryDown: handleHistoryDown, - onHistoryReset: resetHistory, - placeholder, - onExit: onExit2, - onExitMessage: (show, key2) => setExitMessage({ - show, - key: key2 - }), - onImagePaste, - columns: textInputColumns, - maxVisibleLines, - disableCursorMovementForUpDownKeys: suggestions.length > 0 || !!footerItemSelected, - disableEscapeDoublePress: suggestions.length > 0, - cursorOffset, - onChangeCursorOffset: setCursorOffset, - onPaste: onTextPaste, - onIsPastingChange: setIsPasting, - focus: !isSearchingHistory && !isModalOverlayActive && !footerItemSelected, - showCursor: !footerItemSelected && !isSearchingHistory && !cursorAtImageChip, - argumentHint: commandArgumentHint, - onUndo: canUndo ? () => { - const previousState = undo(); - if (previousState) { - trackAndSetInput(previousState.text); - setCursorOffset(previousState.cursorOffset); - setPastedContents(previousState.pastedContents); - } - } : undefined, - highlights: combinedHighlights, - inlineGhostText, - inputFilter: lazySpaceInputFilter - }; - const getBorderColor = () => { - const modeColors = { - bash: "bashBorder" - }; - if (modeColors[mode]) { - return modeColors[mode]; - } - if (isInProcessTeammate()) { - return "promptBorder"; - } - const teammateColorName = getTeammateColor(); - if (teammateColorName && AGENT_COLORS.includes(teammateColorName)) { - return AGENT_COLOR_TO_THEME_COLOR[teammateColorName]; - } - return "promptBorder"; - }; - if (isExternalEditorActive) { - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "row", - alignItems: "center", - justifyContent: "center", - borderColor: getBorderColor(), - borderStyle: "round", - borderLeft: false, - borderRight: false, - borderBottom: true, - width: "100%", - children: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: "Save and close editor to continue..." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - } - const textInputElement = isVimModeEnabled() ? /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(VimTextInput, { - ...baseProps, - initialMode: vimMode, - onModeChange: setVimMode - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(TextInput, { - ...baseProps - }, undefined, false, undefined, this); - return /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: briefOwnsGap ? 0 : 1, - children: [ - !isFullscreenEnvEnabled() && /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(PromptInputQueuedCommands, {}, undefined, false, undefined, this), - hasSuppressedDialogs && /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - marginTop: 1, - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - dimColor: true, - children: "Waiting for permission\u2026" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(PromptInputStashNotice, { - hasStash: stashedPrompt !== undefined - }, undefined, false, undefined, this), - swarmBanner ? /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(jsx_dev_runtime436.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - color: swarmBanner.bgColor, - children: swarmBanner.text ? /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(jsx_dev_runtime436.Fragment, { - children: [ - "\u2500".repeat(Math.max(0, columns - stringWidth(swarmBanner.text) - 4)), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - backgroundColor: swarmBanner.bgColor, - color: "inverseText", - children: [ - " ", - swarmBanner.text, - " " - ] - }, undefined, true, undefined, this), - "\u2500\u2500" - ] - }, undefined, true, undefined, this) : "\u2500".repeat(columns) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "row", - width: "100%", - children: [ - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(PromptInputModeIndicator, { - mode, - isLoading, - viewingAgentName, - viewingAgentColor - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexGrow: 1, - flexShrink: 1, - onClick: handleInputClick, - children: textInputElement - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedText, { - color: swarmBanner.bgColor, - children: "\u2500".repeat(columns) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexDirection: "row", - alignItems: "flex-start", - justifyContent: "flex-start", - borderColor: getBorderColor(), - borderStyle: "round", - borderLeft: false, - borderRight: false, - borderBottom: true, - width: "100%", - borderText: buildBorderText(showFastIcon ?? false, showFastIconHint, fastModeCooldown), - children: [ - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(PromptInputModeIndicator, { - mode, - isLoading, - viewingAgentName, - viewingAgentColor - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - flexGrow: 1, - flexShrink: 1, - onClick: handleInputClick, - children: textInputElement - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(PromptInputFooter_default, { - apiKeyStatus, - debug: debug2, - exitMessage, - vimMode: isVimModeEnabled() ? vimMode : undefined, - mode, - autoUpdaterResult, - isAutoUpdating, - verbose, - onAutoUpdaterResult, - onChangeIsUpdating: setIsAutoUpdating, - suggestions, - selectedSuggestion, - maxColumnWidth, - toolPermissionContext: effectiveToolPermissionContext, - helpOpen, - suppressHint: input.length > 0, - isLoading, - tasksSelected, - teamsSelected, - bridgeSelected, - tmuxSelected, - teammateFooterIndex, - ideSelection, - mcpClients, - isPasting, - isInputWrapped, - messages, - isSearching: isSearchingHistory, - historyQuery, - setHistoryQuery, - historyFailedMatch, - onOpenTasksDialog: isFullscreenEnvEnabled() ? handleOpenTasksDialog : undefined - }, undefined, false, undefined, this), - isFullscreenEnvEnabled() ? null : autoModeOptInDialog, - isFullscreenEnvEnabled() ? /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(ThemedBox_default, { - position: "absolute", - marginTop: briefOwnsGap ? -2 : -1, - height: suggestions.length === 0 && !showAutoModeOptIn ? 1 : 0, - width: "100%", - paddingLeft: 2, - paddingRight: 1, - flexDirection: "column", - justifyContent: "flex-end", - overflow: "hidden", - children: /* @__PURE__ */ jsx_dev_runtime436.jsxDEV(Notifications, { - apiKeyStatus, - autoUpdaterResult, - debug: debug2, - isAutoUpdating, - verbose, - messages, - onAutoUpdaterResult, - onChangeIsUpdating: setIsAutoUpdating, - ideSelection, - mcpClients, - isInputWrapped - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : null - ] - }, undefined, true, undefined, this); -} -function getInitialPasteId(messages) { - let maxId = 0; - for (const message of messages) { - if (message.type === "user") { - if (message.imagePasteIds) { - for (const id of message.imagePasteIds) { - if (id > maxId) - maxId = id; - } - } - if (Array.isArray(message.message.content)) { - for (const block2 of message.message.content) { - if (block2.type === "text") { - const refs = parseReferences(block2.text); - for (const ref of refs) { - if (ref.id > maxId) - maxId = ref.id; - } - } - } - } - } - } - return maxId + 1; -} -function buildBorderText(showFastIcon, showFastIconHint, fastModeCooldown) { - if (!showFastIcon) - return; - const fastSeg = showFastIconHint ? `${getFastIconString(true, fastModeCooldown)} ${source_default.dim("/fast")}` : getFastIconString(true, fastModeCooldown); - return { - content: ` ${fastSeg} `, - position: "top", - align: "end", - offset: 0 - }; -} -var React141, import_react260, jsx_dev_runtime436, PROMPT_FOOTER_LINES = 5, MIN_INPUT_VIEWPORT_LINES = 3, PromptInput_default; -var init_PromptInput = __esm(() => { - init_source(); - init_notifications(); - init_useCommandQueue(); - init_useIdeAtMentioned(); - init_analytics(); - init_AppState(); - init_cwd(); - init_messageQueueManager(); - init_strip_ansi(); - init_CompanionSprite(); - init_useBuddyNotification(); - init_fast(); - init_ultrareviewEnabled(); - init_terminalSetup(); - init_commands5(); - init_overlayContext(); - init_promptOverlayContext(); - init_history(); - init_useArrowKeyHistory(); - init_useDoublePress(); - init_useHistorySearch(); - init_useInputBuffer(); - init_useMainLoopModel(); - init_usePromptSuggestion(); - init_useTerminalSize(); - init_useTypeahead(); - init_stringWidth(); - init_ink2(); - init_KeybindingContext(); - init_shortcutFormat(); - init_useKeybinding(); - init_promptSuggestion(); - init_speculation(); - init_selectors(); - init_teammateViewHelpers(); - init_InProcessTeammateTask(); - init_LocalAgentTask(); - init_agentColorManager(); - init_agentSwarmsEnabled(); - init_Cursor(); - init_config(); - init_debug(); - init_env(); - init_errors(); - init_extraUsage(); - init_fastMode(); - init_fullscreen(); - init_imagePaste(); - init_imageStore(); - init_keyboardShortcuts(); - init_log2(); - init_model(); - init_getNextPermissionMode(); - init_permissionSetup(); - init_platform2(); - init_promptEditor(); - init_settings2(); - init_sideQuestion(); - init_commandSuggestions(); - init_slackChannelSuggestions(); - init_registry(); - init_teamHelpers(); - init_teammate(); - init_teammateContext(); - init_teammateMailbox(); - init_thinking(); - init_tokenBudget(); - init_keyword(); - init_AutoModeOptInDialog(); - init_BridgeDialog(); - init_ConfigurableShortcutHint(); - init_CoordinatorAgentStatus(); - init_EffortIndicator(); - init_FastIcon(); - init_GlobalSearchDialog(); - init_HistorySearchDialog(); - init_ModelPicker(); - init_QuickOpenDialog(); - init_TextInput(); - init_ThinkingToggle(); - init_BackgroundTasksDialog(); - init_taskStatusUtils(); - init_TeamsDialog(); - init_VimTextInput(); - init_Notifications(); - init_PromptInputFooter(); - init_PromptInputModeIndicator(); - init_PromptInputQueuedCommands(); - init_PromptInputStashNotice(); - init_useMaybeTruncateInput(); - init_usePromptInputPlaceholder(); - init_useShowFastIconHint(); - init_useSwarmBanner(); - init_utils14(); - React141 = __toESM(require_react(), 1); - import_react260 = __toESM(require_react(), 1); - jsx_dev_runtime436 = __toESM(require_jsx_dev_runtime(), 1); - PromptInput_default = React141.memo(PromptInput); -}); - -// src/utils/controlMessageCompat.ts -function normalizeControlMessageKeys(obj) { - if (obj === null || typeof obj !== "object") - return obj; - const record3 = obj; - if ("requestId" in record3 && !("request_id" in record3)) { - record3.request_id = record3.requestId; - delete record3.requestId; - } - if ("response" in record3 && record3.response !== null && typeof record3.response === "object") { - const response7 = record3.response; - if ("requestId" in response7 && !("request_id" in response7)) { - response7.request_id = response7.requestId; - delete response7.requestId; - } - } - return obj; -} - -// src/bridge/bridgeMessaging.ts -import { randomUUID as randomUUID38 } from "crypto"; -function isSDKMessage(value) { - return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string"; -} -function isSDKControlResponse(value) { - return value !== null && typeof value === "object" && "type" in value && value.type === "control_response" && "response" in value; -} -function isSDKControlRequest(value) { - return value !== null && typeof value === "object" && "type" in value && value.type === "control_request" && "request_id" in value && "request" in value; -} -function isEligibleBridgeMessage(m4) { - if ((m4.type === "user" || m4.type === "assistant") && m4.isVirtual) { - return false; - } - return m4.type === "user" || m4.type === "assistant" || m4.type === "system" && m4.subtype === "local_command"; -} -function extractTitleText(m4) { - if (m4.type !== "user" || m4.isMeta || m4.toolUseResult || m4.isCompactSummary) - return; - if (m4.origin && m4.origin.kind !== "human") - return; - const content = m4.message.content; - let raw; - if (typeof content === "string") { - raw = content; - } else { - for (const block2 of content) { - if (block2.type === "text") { - raw = block2.text; - break; - } - } - } - if (!raw) - return; - const clean = stripDisplayTagsAllowEmpty(raw); - return clean || undefined; -} -function handleIngressMessage(data, recentPostedUUIDs, recentInboundUUIDs, onInboundMessage, onPermissionResponse, onControlRequest) { - try { - const parsed = normalizeControlMessageKeys(jsonParse(data)); - if (isSDKControlResponse(parsed)) { - logForDebugging("[bridge:repl] Ingress message type=control_response"); - onPermissionResponse?.(parsed); - return; - } - if (isSDKControlRequest(parsed)) { - logForDebugging(`[bridge:repl] Inbound control_request subtype=${parsed.request.subtype}`); - onControlRequest?.(parsed); - return; - } - if (!isSDKMessage(parsed)) - return; - const uuid8 = "uuid" in parsed && typeof parsed.uuid === "string" ? parsed.uuid : undefined; - if (uuid8 && recentPostedUUIDs.has(uuid8)) { - logForDebugging(`[bridge:repl] Ignoring echo: type=${parsed.type} uuid=${uuid8}`); - return; - } - if (uuid8 && recentInboundUUIDs.has(uuid8)) { - logForDebugging(`[bridge:repl] Ignoring re-delivered inbound: type=${parsed.type} uuid=${uuid8}`); - return; - } - logForDebugging(`[bridge:repl] Ingress message type=${parsed.type}${uuid8 ? ` uuid=${uuid8}` : ""}`); - if (parsed.type === "user") { - if (uuid8) - recentInboundUUIDs.add(uuid8); - logEvent("tengu_bridge_message_received", { - is_repl: true - }); - onInboundMessage?.(parsed); - } else { - logForDebugging(`[bridge:repl] Ignoring non-user inbound message: type=${parsed.type}`); - } - } catch (err2) { - logForDebugging(`[bridge:repl] Failed to parse ingress message: ${errorMessage(err2)}`); - } -} -function handleServerControlRequest(request2, handlers) { - const { - transport, - sessionId, - outboundOnly, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode - } = handlers; - if (!transport) { - logForDebugging("[bridge:repl] Cannot respond to control_request: transport not configured"); - return; - } - let response7; - if (outboundOnly && request2.request.subtype !== "initialize") { - response7 = { - type: "control_response", - response: { - subtype: "error", - request_id: request2.request_id, - error: OUTBOUND_ONLY_ERROR - } - }; - const event2 = { ...response7, session_id: sessionId }; - transport.write(event2); - logForDebugging(`[bridge:repl] Rejected ${request2.request.subtype} (outbound-only) request_id=${request2.request_id}`); - return; - } - switch (request2.request.subtype) { - case "initialize": - response7 = { - type: "control_response", - response: { - subtype: "success", - request_id: request2.request_id, - response: { - commands: [], - output_style: "normal", - available_output_styles: ["normal"], - models: [], - account: {}, - pid: process.pid - } - } - }; - break; - case "set_model": - onSetModel?.(request2.request.model); - response7 = { - type: "control_response", - response: { - subtype: "success", - request_id: request2.request_id - } - }; - break; - case "set_max_thinking_tokens": - onSetMaxThinkingTokens?.(request2.request.max_thinking_tokens); - response7 = { - type: "control_response", - response: { - subtype: "success", - request_id: request2.request_id - } - }; - break; - case "set_permission_mode": { - const verdict = onSetPermissionMode?.(request2.request.mode) ?? { - ok: false, - error: "set_permission_mode is not supported in this context (onSetPermissionMode callback not registered)" - }; - if (verdict.ok) { - response7 = { - type: "control_response", - response: { - subtype: "success", - request_id: request2.request_id - } - }; - } else { - response7 = { - type: "control_response", - response: { - subtype: "error", - request_id: request2.request_id, - error: verdict.error - } - }; - } - break; - } - case "interrupt": - onInterrupt?.(); - response7 = { - type: "control_response", - response: { - subtype: "success", - request_id: request2.request_id - } - }; - break; - default: - response7 = { - type: "control_response", - response: { - subtype: "error", - request_id: request2.request_id, - error: `REPL bridge does not handle control_request subtype: ${request2.request.subtype}` - } - }; - } - const event = { ...response7, session_id: sessionId }; - transport.write(event); - logForDebugging(`[bridge:repl] Sent control_response for ${request2.request.subtype} request_id=${request2.request_id} result=${response7.response.subtype}`); -} -function makeResultMessage(sessionId) { - return { - type: "result", - subtype: "success", - duration_ms: 0, - duration_api_ms: 0, - is_error: false, - num_turns: 0, - result: "", - stop_reason: null, - total_cost_usd: 0, - usage: { ...EMPTY_USAGE }, - modelUsage: {}, - permission_denials: [], - session_id: sessionId, - uuid: randomUUID38() - }; -} - -class BoundedUUIDSet { - capacity; - ring; - set = new Set; - writeIdx = 0; - constructor(capacity) { - this.capacity = capacity; - this.ring = new Array(capacity); - } - add(uuid8) { - if (this.set.has(uuid8)) - return; - const evicted = this.ring[this.writeIdx]; - if (evicted !== undefined) { - this.set.delete(evicted); - } - this.ring[this.writeIdx] = uuid8; - this.set.add(uuid8); - this.writeIdx = (this.writeIdx + 1) % this.capacity; - } - has(uuid8) { - return this.set.has(uuid8); - } - clear() { - this.set.clear(); - this.ring.fill(undefined); - this.writeIdx = 0; - } -} -var OUTBOUND_ONLY_ERROR = "This session is outbound-only. Enable Remote Control locally to allow inbound control."; -var init_bridgeMessaging = __esm(() => { - init_analytics(); - init_emptyUsage(); - init_debug(); - init_displayTags(); - init_errors(); - init_slowOperations(); -}); - -// src/remote/SessionsWebSocket.ts -import { randomUUID as randomUUID39 } from "crypto"; -function isSessionsMessage(value) { - if (typeof value !== "object" || value === null || !("type" in value)) { - return false; - } - return typeof value.type === "string"; -} - -class SessionsWebSocket { - sessionId; - orgUuid; - getAccessToken; - callbacks; - ws = null; - state = "closed"; - reconnectAttempts = 0; - sessionNotFoundRetries = 0; - pingInterval = null; - reconnectTimer = null; - constructor(sessionId, orgUuid, getAccessToken, callbacks) { - this.sessionId = sessionId; - this.orgUuid = orgUuid; - this.getAccessToken = getAccessToken; - this.callbacks = callbacks; - } - async connect() { - if (this.state === "connecting") { - logForDebugging("[SessionsWebSocket] Already connecting"); - return; - } - this.state = "connecting"; - const baseUrl = getOauthConfig().BASE_API_URL.replace("https://", "wss://"); - const url3 = `${baseUrl}/v1/sessions/ws/${this.sessionId}/subscribe?organization_uuid=${this.orgUuid}`; - logForDebugging(`[SessionsWebSocket] Connecting to ${url3}`); - const accessToken = this.getAccessToken(); - const headers = { - Authorization: `Bearer ${accessToken}`, - "anthropic-version": "2023-06-01" - }; - if (typeof Bun !== "undefined") { - const ws = new globalThis.WebSocket(url3, { - headers, - proxy: getWebSocketProxyUrl(url3), - tls: getWebSocketTLSOptions() || undefined - }); - this.ws = ws; - ws.addEventListener("open", () => { - logForDebugging("[SessionsWebSocket] Connection opened, authenticated via headers"); - this.state = "connected"; - this.reconnectAttempts = 0; - this.sessionNotFoundRetries = 0; - this.startPingInterval(); - this.callbacks.onConnected?.(); - }); - ws.addEventListener("message", (event) => { - const data = typeof event.data === "string" ? event.data : String(event.data); - this.handleMessage(data); - }); - ws.addEventListener("error", () => { - const err2 = new Error("[SessionsWebSocket] WebSocket error"); - logError2(err2); - this.callbacks.onError?.(err2); - }); - ws.addEventListener("close", (event) => { - logForDebugging(`[SessionsWebSocket] Closed: code=${event.code} reason=${event.reason}`); - this.handleClose(event.code); - }); - ws.addEventListener("pong", () => { - logForDebugging("[SessionsWebSocket] Pong received"); - }); - } else { - const { default: WS } = await import("ws"); - const ws = new WS(url3, { - headers, - agent: getWebSocketProxyAgent(url3), - ...getWebSocketTLSOptions() - }); - this.ws = ws; - ws.on("open", () => { - logForDebugging("[SessionsWebSocket] Connection opened, authenticated via headers"); - this.state = "connected"; - this.reconnectAttempts = 0; - this.sessionNotFoundRetries = 0; - this.startPingInterval(); - this.callbacks.onConnected?.(); - }); - ws.on("message", (data) => { - this.handleMessage(data.toString()); - }); - ws.on("error", (err2) => { - logError2(new Error(`[SessionsWebSocket] Error: ${err2.message}`)); - this.callbacks.onError?.(err2); - }); - ws.on("close", (code, reason) => { - logForDebugging(`[SessionsWebSocket] Closed: code=${code} reason=${reason.toString()}`); - this.handleClose(code); - }); - ws.on("pong", () => { - logForDebugging("[SessionsWebSocket] Pong received"); - }); - } - } - handleMessage(data) { - try { - const message = jsonParse(data); - if (isSessionsMessage(message)) { - this.callbacks.onMessage(message); - } else { - logForDebugging(`[SessionsWebSocket] Ignoring message type: ${typeof message === "object" && message !== null && "type" in message ? String(message.type) : "unknown"}`); - } - } catch (error46) { - logError2(new Error(`[SessionsWebSocket] Failed to parse message: ${errorMessage(error46)}`)); - } - } - handleClose(closeCode) { - this.stopPingInterval(); - if (this.state === "closed") { - return; - } - this.ws = null; - const previousState = this.state; - this.state = "closed"; - if (PERMANENT_CLOSE_CODES.has(closeCode)) { - logForDebugging(`[SessionsWebSocket] Permanent close code ${closeCode}, not reconnecting`); - this.callbacks.onClose?.(); - return; - } - if (closeCode === 4001) { - this.sessionNotFoundRetries++; - if (this.sessionNotFoundRetries > MAX_SESSION_NOT_FOUND_RETRIES) { - logForDebugging(`[SessionsWebSocket] 4001 retry budget exhausted (${MAX_SESSION_NOT_FOUND_RETRIES}), not reconnecting`); - this.callbacks.onClose?.(); - return; - } - this.scheduleReconnect(RECONNECT_DELAY_MS * this.sessionNotFoundRetries, `4001 attempt ${this.sessionNotFoundRetries}/${MAX_SESSION_NOT_FOUND_RETRIES}`); - return; - } - if (previousState === "connected" && this.reconnectAttempts < MAX_RECONNECT_ATTEMPTS2) { - this.reconnectAttempts++; - this.scheduleReconnect(RECONNECT_DELAY_MS, `attempt ${this.reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS2}`); - } else { - logForDebugging("[SessionsWebSocket] Not reconnecting"); - this.callbacks.onClose?.(); - } - } - scheduleReconnect(delay4, label) { - this.callbacks.onReconnecting?.(); - logForDebugging(`[SessionsWebSocket] Scheduling reconnect (${label}) in ${delay4}ms`); - this.reconnectTimer = setTimeout(() => { - this.reconnectTimer = null; - this.connect(); - }, delay4); - } - startPingInterval() { - this.stopPingInterval(); - this.pingInterval = setInterval(() => { - if (this.ws && this.state === "connected") { - try { - this.ws.ping?.(); - } catch {} - } - }, PING_INTERVAL_MS2); - } - stopPingInterval() { - if (this.pingInterval) { - clearInterval(this.pingInterval); - this.pingInterval = null; - } - } - sendControlResponse(response7) { - if (!this.ws || this.state !== "connected") { - logError2(new Error("[SessionsWebSocket] Cannot send: not connected")); - return; - } - logForDebugging("[SessionsWebSocket] Sending control response"); - this.ws.send(jsonStringify(response7)); - } - sendControlRequest(request2) { - if (!this.ws || this.state !== "connected") { - logError2(new Error("[SessionsWebSocket] Cannot send: not connected")); - return; - } - const controlRequest = { - type: "control_request", - request_id: randomUUID39(), - request: request2 - }; - logForDebugging(`[SessionsWebSocket] Sending control request: ${request2.subtype}`); - this.ws.send(jsonStringify(controlRequest)); - } - isConnected() { - return this.state === "connected"; - } - close() { - logForDebugging("[SessionsWebSocket] Closing connection"); - this.state = "closed"; - this.stopPingInterval(); - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - if (this.ws) { - this.ws.close(); - this.ws = null; - } - } - reconnect() { - logForDebugging("[SessionsWebSocket] Force reconnecting"); - this.reconnectAttempts = 0; - this.sessionNotFoundRetries = 0; - this.close(); - this.reconnectTimer = setTimeout(() => { - this.reconnectTimer = null; - this.connect(); - }, 500); - } -} -var RECONNECT_DELAY_MS = 2000, MAX_RECONNECT_ATTEMPTS2 = 5, PING_INTERVAL_MS2 = 30000, MAX_SESSION_NOT_FOUND_RETRIES = 3, PERMANENT_CLOSE_CODES; -var init_SessionsWebSocket = __esm(() => { - init_oauth(); - init_debug(); - init_errors(); - init_log2(); - init_mtls(); - init_proxy(); - init_slowOperations(); - PERMANENT_CLOSE_CODES = new Set([ - 4003 - ]); -}); - -// src/remote/RemoteSessionManager.ts -function isSDKMessage2(message) { - return message.type !== "control_request" && message.type !== "control_response" && message.type !== "control_cancel_request"; -} - -class RemoteSessionManager { - config; - callbacks; - websocket = null; - pendingPermissionRequests = new Map; - constructor(config10, callbacks) { - this.config = config10; - this.callbacks = callbacks; - } - connect() { - logForDebugging(`[RemoteSessionManager] Connecting to session ${this.config.sessionId}`); - const wsCallbacks = { - onMessage: (message) => this.handleMessage(message), - onConnected: () => { - logForDebugging("[RemoteSessionManager] Connected"); - this.callbacks.onConnected?.(); - }, - onClose: () => { - logForDebugging("[RemoteSessionManager] Disconnected"); - this.callbacks.onDisconnected?.(); - }, - onReconnecting: () => { - logForDebugging("[RemoteSessionManager] Reconnecting"); - this.callbacks.onReconnecting?.(); - }, - onError: (error46) => { - logError2(error46); - this.callbacks.onError?.(error46); - } - }; - this.websocket = new SessionsWebSocket(this.config.sessionId, this.config.orgUuid, this.config.getAccessToken, wsCallbacks); - this.websocket.connect(); - } - handleMessage(message) { - if (message.type === "control_request") { - this.handleControlRequest(message); - return; - } - if (message.type === "control_cancel_request") { - const { request_id } = message; - const pendingRequest = this.pendingPermissionRequests.get(request_id); - logForDebugging(`[RemoteSessionManager] Permission request cancelled: ${request_id}`); - this.pendingPermissionRequests.delete(request_id); - this.callbacks.onPermissionCancelled?.(request_id, pendingRequest?.tool_use_id); - return; - } - if (message.type === "control_response") { - logForDebugging("[RemoteSessionManager] Received control response"); - return; - } - if (isSDKMessage2(message)) { - this.callbacks.onMessage(message); - } - } - handleControlRequest(request2) { - const { request_id, request: inner } = request2; - if (inner.subtype === "can_use_tool") { - logForDebugging(`[RemoteSessionManager] Permission request for tool: ${inner.tool_name}`); - this.pendingPermissionRequests.set(request_id, inner); - this.callbacks.onPermissionRequest(inner, request_id); - } else { - logForDebugging(`[RemoteSessionManager] Unsupported control request subtype: ${inner.subtype}`); - const response7 = { - type: "control_response", - response: { - subtype: "error", - request_id, - error: `Unsupported control request subtype: ${inner.subtype}` - } - }; - this.websocket?.sendControlResponse(response7); - } - } - async sendMessage(content, opts) { - logForDebugging(`[RemoteSessionManager] Sending message to session ${this.config.sessionId}`); - const success2 = await sendEventToRemoteSession(this.config.sessionId, content, opts); - if (!success2) { - logError2(new Error(`[RemoteSessionManager] Failed to send message to session ${this.config.sessionId}`)); - } - return success2; - } - respondToPermissionRequest(requestId, result) { - const pendingRequest = this.pendingPermissionRequests.get(requestId); - if (!pendingRequest) { - logError2(new Error(`[RemoteSessionManager] No pending permission request with ID: ${requestId}`)); - return; - } - this.pendingPermissionRequests.delete(requestId); - const response7 = { - type: "control_response", - response: { - subtype: "success", - request_id: requestId, - response: { - behavior: result.behavior, - ...result.behavior === "allow" ? { updatedInput: result.updatedInput } : { message: result.message } - } - } - }; - logForDebugging(`[RemoteSessionManager] Sending permission response: ${result.behavior}`); - this.websocket?.sendControlResponse(response7); - } - isConnected() { - return this.websocket?.isConnected() ?? false; - } - cancelSession() { - logForDebugging("[RemoteSessionManager] Sending interrupt signal"); - this.websocket?.sendControlRequest({ subtype: "interrupt" }); - } - getSessionId() { - return this.config.sessionId; - } - disconnect() { - logForDebugging("[RemoteSessionManager] Disconnecting"); - this.websocket?.close(); - this.websocket = null; - this.pendingPermissionRequests.clear(); - } - reconnect() { - logForDebugging("[RemoteSessionManager] Reconnecting WebSocket"); - this.websocket?.reconnect(); - } -} -function createRemoteSessionConfig(sessionId, getAccessToken, orgUuid, hasInitialPrompt = false, viewerOnly = false) { - return { - sessionId, - getAccessToken, - orgUuid, - hasInitialPrompt, - viewerOnly - }; -} -var init_RemoteSessionManager = __esm(() => { - init_debug(); - init_log2(); - init_api2(); - init_SessionsWebSocket(); -}); - -// src/remote/remotePermissionBridge.ts -import { randomUUID as randomUUID40 } from "crypto"; -function createSyntheticAssistantMessage(request2, requestId) { - return { - type: "assistant", - uuid: randomUUID40(), - message: { - id: `remote-${requestId}`, - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: request2.tool_use_id, - name: request2.tool_name, - input: request2.input - } - ], - model: "", - stop_reason: null, - stop_sequence: null, - container: null, - context_management: null, - usage: { - input_tokens: 0, - output_tokens: 0, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0 - } - }, - requestId: undefined, - timestamp: new Date().toISOString() - }; -} -function createToolStub(toolName) { - return { - name: toolName, - inputSchema: {}, - isEnabled: () => true, - userFacingName: () => toolName, - renderToolUseMessage: (input) => { - const entries = Object.entries(input); - if (entries.length === 0) - return ""; - return entries.slice(0, 3).map(([key2, value]) => { - const valueStr = typeof value === "string" ? value : jsonStringify(value); - return `${key2}: ${valueStr}`; - }).join(", "); - }, - call: async () => ({ data: "" }), - description: async () => "", - prompt: () => "", - isReadOnly: () => false, - isMcp: false, - needsPermissions: () => true - }; -} -var init_remotePermissionBridge = __esm(() => { - init_slowOperations(); -}); - -// src/remote/sdkMessageAdapter.ts -function convertAssistantMessage(msg) { - return { - type: "assistant", - message: msg.message, - uuid: msg.uuid, - requestId: undefined, - timestamp: new Date().toISOString(), - error: msg.error - }; -} -function convertStreamEvent(msg) { - return { - type: "stream_event", - event: msg.event - }; -} -function convertResultMessage(msg) { - const isError3 = msg.subtype !== "success"; - const content = isError3 ? msg.errors?.join(", ") || "Unknown error" : "Session completed successfully"; - return { - type: "system", - subtype: "informational", - content, - level: isError3 ? "warning" : "info", - uuid: msg.uuid, - timestamp: new Date().toISOString() - }; -} -function convertInitMessage(msg) { - return { - type: "system", - subtype: "informational", - content: `Remote session initialized (model: ${msg.model})`, - level: "info", - uuid: msg.uuid, - timestamp: new Date().toISOString() - }; -} -function convertStatusMessage(msg) { - if (!msg.status) { - return null; - } - return { - type: "system", - subtype: "informational", - content: msg.status === "compacting" ? "Compacting conversation\u2026" : `Status: ${msg.status}`, - level: "info", - uuid: msg.uuid, - timestamp: new Date().toISOString() - }; -} -function convertToolProgressMessage(msg) { - return { - type: "system", - subtype: "informational", - content: `Tool ${msg.tool_name} running for ${msg.elapsed_time_seconds}s\u2026`, - level: "info", - uuid: msg.uuid, - timestamp: new Date().toISOString(), - toolUseID: msg.tool_use_id - }; -} -function convertCompactBoundaryMessage(msg) { - return { - type: "system", - subtype: "compact_boundary", - content: "Conversation compacted", - level: "info", - uuid: msg.uuid, - timestamp: new Date().toISOString(), - compactMetadata: fromSDKCompactMetadata(msg.compact_metadata) - }; -} -function convertSDKMessage(msg, opts) { - switch (msg.type) { - case "assistant": - return { type: "message", message: convertAssistantMessage(msg) }; - case "user": { - const content = msg.message?.content; - const isToolResult2 = Array.isArray(content) && content.some((b5) => b5.type === "tool_result"); - if (opts?.convertToolResults && isToolResult2) { - return { - type: "message", - message: createUserMessage({ - content, - toolUseResult: msg.tool_use_result, - uuid: msg.uuid, - timestamp: msg.timestamp - }) - }; - } - if (opts?.convertUserTextMessages && !isToolResult2) { - if (typeof content === "string" || Array.isArray(content)) { - return { - type: "message", - message: createUserMessage({ - content, - toolUseResult: msg.tool_use_result, - uuid: msg.uuid, - timestamp: msg.timestamp - }) - }; - } - } - return { type: "ignored" }; - } - case "stream_event": - return { type: "stream_event", event: convertStreamEvent(msg) }; - case "result": - if (msg.subtype !== "success") { - return { type: "message", message: convertResultMessage(msg) }; - } - return { type: "ignored" }; - case "system": - if (msg.subtype === "init") { - return { type: "message", message: convertInitMessage(msg) }; - } - if (msg.subtype === "status") { - const statusMsg = convertStatusMessage(msg); - return statusMsg ? { type: "message", message: statusMsg } : { type: "ignored" }; - } - if (msg.subtype === "compact_boundary") { - return { - type: "message", - message: convertCompactBoundaryMessage(msg) - }; - } - logForDebugging(`[sdkMessageAdapter] Ignoring system message subtype: ${msg.subtype}`); - return { type: "ignored" }; - case "tool_progress": - return { type: "message", message: convertToolProgressMessage(msg) }; - case "auth_status": - logForDebugging("[sdkMessageAdapter] Ignoring auth_status message"); - return { type: "ignored" }; - case "tool_use_summary": - logForDebugging("[sdkMessageAdapter] Ignoring tool_use_summary message"); - return { type: "ignored" }; - case "rate_limit_event": - logForDebugging("[sdkMessageAdapter] Ignoring rate_limit_event message"); - return { type: "ignored" }; - default: { - logForDebugging(`[sdkMessageAdapter] Unknown message type: ${msg.type}`); - return { type: "ignored" }; - } - } -} -function isSessionEndMessage(msg) { - return msg.type === "result"; -} -var init_sdkMessageAdapter = __esm(() => { - init_debug(); - init_mappers(); - init_messages9(); -}); - -// src/hooks/useRemoteSession.ts -function useRemoteSession({ - config: config10, - setMessages, - setIsLoading, - onInit, - setToolUseConfirmQueue, - tools, - setStreamingToolUses, - setStreamMode, - setInProgressToolUseIDs -}) { - const isRemoteMode = !!config10; - const setAppState = useSetAppState(); - const setConnStatus = import_react261.useCallback((s4) => setAppState((prev) => prev.remoteConnectionStatus === s4 ? prev : { ...prev, remoteConnectionStatus: s4 }), [setAppState]); - const runningTaskIdsRef = import_react261.useRef(new Set); - const writeTaskCount = import_react261.useCallback(() => { - const n6 = runningTaskIdsRef.current.size; - setAppState((prev) => prev.remoteBackgroundTaskCount === n6 ? prev : { ...prev, remoteBackgroundTaskCount: n6 }); - }, [setAppState]); - const responseTimeoutRef = import_react261.useRef(null); - const isCompactingRef = import_react261.useRef(false); - const managerRef = import_react261.useRef(null); - const hasUpdatedTitleRef = import_react261.useRef(false); - const sentUUIDsRef = import_react261.useRef(new BoundedUUIDSet(50)); - const toolsRef = import_react261.useRef(tools); - import_react261.useEffect(() => { - toolsRef.current = tools; - }, [tools]); - import_react261.useEffect(() => { - if (!config10) { - return; - } - logForDebugging(`[useRemoteSession] Initializing for session ${config10.sessionId}`); - const manager7 = new RemoteSessionManager(config10, { - onMessage: (sdkMessage) => { - const parts = [`type=${sdkMessage.type}`]; - if ("subtype" in sdkMessage) - parts.push(`subtype=${sdkMessage.subtype}`); - if (sdkMessage.type === "user") { - const c9 = sdkMessage.message?.content; - parts.push(`content=${Array.isArray(c9) ? c9.map((b5) => b5.type).join(",") : typeof c9}`); - } - logForDebugging(`[useRemoteSession] Received ${parts.join(" ")}`); - if (responseTimeoutRef.current) { - clearTimeout(responseTimeoutRef.current); - responseTimeoutRef.current = null; - } - if (sdkMessage.type === "user" && sdkMessage.uuid && sentUUIDsRef.current.has(sdkMessage.uuid)) { - logForDebugging(`[useRemoteSession] Dropping echoed user message ${sdkMessage.uuid}`); - return; - } - if (sdkMessage.type === "system" && sdkMessage.subtype === "init" && onInit) { - logForDebugging(`[useRemoteSession] Init received with ${sdkMessage.slash_commands.length} slash commands`); - onInit(sdkMessage.slash_commands); - } - if (sdkMessage.type === "system") { - if (sdkMessage.subtype === "task_started") { - runningTaskIdsRef.current.add(sdkMessage.task_id); - writeTaskCount(); - return; - } - if (sdkMessage.subtype === "task_notification") { - runningTaskIdsRef.current.delete(sdkMessage.task_id); - writeTaskCount(); - return; - } - if (sdkMessage.subtype === "task_progress") { - return; - } - if (sdkMessage.subtype === "status") { - const wasCompacting = isCompactingRef.current; - isCompactingRef.current = sdkMessage.status === "compacting"; - if (wasCompacting && isCompactingRef.current) { - return; - } - } - if (sdkMessage.subtype === "compact_boundary") { - isCompactingRef.current = false; - } - } - if (isSessionEndMessage(sdkMessage)) { - isCompactingRef.current = false; - setIsLoading(false); - } - if (setInProgressToolUseIDs && sdkMessage.type === "user") { - const content = sdkMessage.message?.content; - if (Array.isArray(content)) { - const resultIds = []; - for (const block2 of content) { - if (block2.type === "tool_result") { - resultIds.push(block2.tool_use_id); - } - } - if (resultIds.length > 0) { - setInProgressToolUseIDs((prev) => { - const next2 = new Set(prev); - for (const id of resultIds) - next2.delete(id); - return next2.size === prev.size ? prev : next2; - }); - } - } - } - const converted = convertSDKMessage(sdkMessage, config10.viewerOnly ? { convertToolResults: true, convertUserTextMessages: true } : undefined); - if (converted.type === "message") { - setStreamingToolUses?.((prev) => prev.length > 0 ? [] : prev); - if (setInProgressToolUseIDs && converted.message.type === "assistant") { - const toolUseIds = converted.message.message.content.filter((block2) => block2.type === "tool_use").map((block2) => block2.id); - if (toolUseIds.length > 0) { - setInProgressToolUseIDs((prev) => { - const next2 = new Set(prev); - for (const id of toolUseIds) { - next2.add(id); - } - return next2; - }); - } - } - setMessages((prev) => [...prev, converted.message]); - } else if (converted.type === "stream_event") { - if (setStreamingToolUses && setStreamMode) { - handleMessageFromStream(converted.event, (message) => setMessages((prev) => [...prev, message]), () => {}, setStreamMode, setStreamingToolUses); - } else { - logForDebugging(`[useRemoteSession] Stream event received but streaming callbacks not provided`); - } - } - }, - onPermissionRequest: (request2, requestId) => { - logForDebugging(`[useRemoteSession] Permission request for tool: ${request2.tool_name}`); - const tool = findToolByName(toolsRef.current, request2.tool_name) ?? createToolStub(request2.tool_name); - const syntheticMessage = createSyntheticAssistantMessage(request2, requestId); - const permissionResult = { - behavior: "ask", - message: request2.description ?? `${request2.tool_name} requires permission`, - suggestions: request2.permission_suggestions, - blockedPath: request2.blocked_path - }; - const toolUseConfirm = { - assistantMessage: syntheticMessage, - tool, - description: request2.description ?? `${request2.tool_name} requires permission`, - input: request2.input, - toolUseContext: {}, - toolUseID: request2.tool_use_id, - permissionResult, - permissionPromptStartTimeMs: Date.now(), - onUserInteraction() {}, - onAbort() { - const response7 = { - behavior: "deny", - message: "User aborted" - }; - manager7.respondToPermissionRequest(requestId, response7); - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== request2.tool_use_id)); - }, - onAllow(updatedInput, _permissionUpdates, _feedback) { - const response7 = { - behavior: "allow", - updatedInput - }; - manager7.respondToPermissionRequest(requestId, response7); - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== request2.tool_use_id)); - setIsLoading(true); - }, - onReject(feedback2) { - const response7 = { - behavior: "deny", - message: feedback2 ?? "User denied permission" - }; - manager7.respondToPermissionRequest(requestId, response7); - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== request2.tool_use_id)); - }, - async recheckPermission() {} - }; - setToolUseConfirmQueue((queue2) => [...queue2, toolUseConfirm]); - setIsLoading(false); - }, - onPermissionCancelled: (requestId, toolUseId) => { - logForDebugging(`[useRemoteSession] Permission request cancelled: ${requestId}`); - const idToRemove = toolUseId ?? requestId; - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== idToRemove)); - setIsLoading(true); - }, - onConnected: () => { - logForDebugging("[useRemoteSession] Connected"); - setConnStatus("connected"); - }, - onReconnecting: () => { - logForDebugging("[useRemoteSession] Reconnecting"); - setConnStatus("reconnecting"); - runningTaskIdsRef.current.clear(); - writeTaskCount(); - setInProgressToolUseIDs?.((prev) => prev.size > 0 ? new Set : prev); - }, - onDisconnected: () => { - logForDebugging("[useRemoteSession] Disconnected"); - setConnStatus("disconnected"); - setIsLoading(false); - runningTaskIdsRef.current.clear(); - writeTaskCount(); - setInProgressToolUseIDs?.((prev) => prev.size > 0 ? new Set : prev); - }, - onError: (error46) => { - logForDebugging(`[useRemoteSession] Error: ${error46.message}`); - } - }); - managerRef.current = manager7; - manager7.connect(); - return () => { - logForDebugging("[useRemoteSession] Cleanup - disconnecting"); - if (responseTimeoutRef.current) { - clearTimeout(responseTimeoutRef.current); - responseTimeoutRef.current = null; - } - manager7.disconnect(); - managerRef.current = null; - }; - }, [ - config10, - setMessages, - setIsLoading, - onInit, - setToolUseConfirmQueue, - setStreamingToolUses, - setStreamMode, - setInProgressToolUseIDs, - setConnStatus, - writeTaskCount - ]); - const sendMessage3 = import_react261.useCallback(async (content, opts) => { - const manager7 = managerRef.current; - if (!manager7) { - logForDebugging("[useRemoteSession] Cannot send - no manager"); - return false; - } - if (responseTimeoutRef.current) { - clearTimeout(responseTimeoutRef.current); - } - setIsLoading(true); - if (opts?.uuid) - sentUUIDsRef.current.add(opts.uuid); - const success2 = await manager7.sendMessage(content, opts); - if (!success2) { - setIsLoading(false); - return false; - } - if (!hasUpdatedTitleRef.current && config10 && !config10.hasInitialPrompt && !config10.viewerOnly) { - hasUpdatedTitleRef.current = true; - const sessionId = config10.sessionId; - const description = typeof content === "string" ? content : extractTextContent(content, " "); - if (description) { - generateSessionTitle(description, new AbortController().signal).then((title) => { - updateSessionTitle(sessionId, title ?? truncateToWidth(description, 75)); - }); - } - } - if (!config10?.viewerOnly) { - const timeoutMs = isCompactingRef.current ? COMPACTION_TIMEOUT_MS : RESPONSE_TIMEOUT_MS; - responseTimeoutRef.current = setTimeout((setMessages2, manager8) => { - logForDebugging("[useRemoteSession] Response timeout - attempting reconnect"); - const warningMessage = createSystemMessage("Remote session may be unresponsive. Attempting to reconnect\u2026", "warning"); - setMessages2((prev) => [...prev, warningMessage]); - manager8.reconnect(); - }, timeoutMs, setMessages, manager7); - } - return success2; - }, [config10, setIsLoading, setMessages]); - const cancelRequest = import_react261.useCallback(() => { - if (responseTimeoutRef.current) { - clearTimeout(responseTimeoutRef.current); - responseTimeoutRef.current = null; - } - if (!config10?.viewerOnly) { - managerRef.current?.cancelSession(); - } - setIsLoading(false); - }, [config10, setIsLoading]); - const disconnect2 = import_react261.useCallback(() => { - if (responseTimeoutRef.current) { - clearTimeout(responseTimeoutRef.current); - responseTimeoutRef.current = null; - } - managerRef.current?.disconnect(); - managerRef.current = null; - }, []); - return import_react261.useMemo(() => ({ isRemoteMode, sendMessage: sendMessage3, cancelRequest, disconnect: disconnect2 }), [isRemoteMode, sendMessage3, cancelRequest, disconnect2]); -} -var import_react261, RESPONSE_TIMEOUT_MS = 60000, COMPACTION_TIMEOUT_MS = 180000; -var init_useRemoteSession = __esm(() => { - init_bridgeMessaging(); - init_RemoteSessionManager(); - init_remotePermissionBridge(); - init_sdkMessageAdapter(); - init_AppState(); - init_Tool(); - init_debug(); - init_format(); - init_messages9(); - init_sessionTitle(); - init_api2(); - import_react261 = __toESM(require_react(), 1); -}); - -// src/server/directConnectManager.ts -function isStdoutMessage(value) { - return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string"; -} - -class DirectConnectSessionManager { - ws = null; - config; - callbacks; - constructor(config10, callbacks) { - this.config = config10; - this.callbacks = callbacks; - } - connect() { - const headers = {}; - if (this.config.authToken) { - headers["authorization"] = `Bearer ${this.config.authToken}`; - } - this.ws = new WebSocket(this.config.wsUrl, { - headers - }); - this.ws.addEventListener("open", () => { - this.callbacks.onConnected?.(); - }); - this.ws.addEventListener("message", (event) => { - const data = typeof event.data === "string" ? event.data : ""; - const lines2 = data.split(` -`).filter((l4) => l4.trim()); - for (const line of lines2) { - let raw; - try { - raw = jsonParse(line); - } catch { - continue; - } - if (!isStdoutMessage(raw)) { - continue; - } - const parsed = raw; - if (parsed.type === "control_request") { - if (parsed.request.subtype === "can_use_tool") { - this.callbacks.onPermissionRequest(parsed.request, parsed.request_id); - } else { - logForDebugging(`[DirectConnect] Unsupported control request subtype: ${parsed.request.subtype}`); - this.sendErrorResponse(parsed.request_id, `Unsupported control request subtype: ${parsed.request.subtype}`); - } - continue; - } - if (parsed.type !== "control_response" && parsed.type !== "keep_alive" && parsed.type !== "control_cancel_request" && parsed.type !== "streamlined_text" && parsed.type !== "streamlined_tool_use_summary" && !(parsed.type === "system" && parsed.subtype === "post_turn_summary")) { - this.callbacks.onMessage(parsed); - } - } - }); - this.ws.addEventListener("close", () => { - this.callbacks.onDisconnected?.(); - }); - this.ws.addEventListener("error", () => { - this.callbacks.onError?.(new Error("WebSocket connection error")); - }); - } - sendMessage(content) { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { - return false; - } - const message = jsonStringify({ - type: "user", - message: { - role: "user", - content - }, - parent_tool_use_id: null, - session_id: "" - }); - this.ws.send(message); - return true; - } - respondToPermissionRequest(requestId, result) { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { - return; - } - const response7 = jsonStringify({ - type: "control_response", - response: { - subtype: "success", - request_id: requestId, - response: { - behavior: result.behavior, - ...result.behavior === "allow" ? { updatedInput: result.updatedInput } : { message: result.message } - } - } - }); - this.ws.send(response7); - } - sendInterrupt() { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { - return; - } - const request2 = jsonStringify({ - type: "control_request", - request_id: crypto.randomUUID(), - request: { - subtype: "interrupt" - } - }); - this.ws.send(request2); - } - sendErrorResponse(requestId, error46) { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { - return; - } - const response7 = jsonStringify({ - type: "control_response", - response: { - subtype: "error", - request_id: requestId, - error: error46 - } - }); - this.ws.send(response7); - } - disconnect() { - if (this.ws) { - this.ws.close(); - this.ws = null; - } - } - isConnected() { - return this.ws?.readyState === WebSocket.OPEN; - } -} -var init_directConnectManager = __esm(() => { - init_debug(); - init_slowOperations(); -}); - -// src/hooks/useDirectConnect.ts -function useDirectConnect({ - config: config10, - setMessages, - setIsLoading, - setToolUseConfirmQueue, - tools -}) { - const isRemoteMode = !!config10; - const managerRef = import_react262.useRef(null); - const hasReceivedInitRef = import_react262.useRef(false); - const isConnectedRef = import_react262.useRef(false); - const toolsRef = import_react262.useRef(tools); - import_react262.useEffect(() => { - toolsRef.current = tools; - }, [tools]); - import_react262.useEffect(() => { - if (!config10) { - return; - } - hasReceivedInitRef.current = false; - logForDebugging(`[useDirectConnect] Connecting to ${config10.wsUrl}`); - const manager7 = new DirectConnectSessionManager(config10, { - onMessage: (sdkMessage) => { - if (isSessionEndMessage(sdkMessage)) { - setIsLoading(false); - } - if (sdkMessage.type === "system" && sdkMessage.subtype === "init") { - if (hasReceivedInitRef.current) { - return; - } - hasReceivedInitRef.current = true; - } - const converted = convertSDKMessage(sdkMessage, { - convertToolResults: true - }); - if (converted.type === "message") { - setMessages((prev) => [...prev, converted.message]); - } - }, - onPermissionRequest: (request2, requestId) => { - logForDebugging(`[useDirectConnect] Permission request for tool: ${request2.tool_name}`); - const tool = findToolByName(toolsRef.current, request2.tool_name) ?? createToolStub(request2.tool_name); - const syntheticMessage = createSyntheticAssistantMessage(request2, requestId); - const permissionResult = { - behavior: "ask", - message: request2.description ?? `${request2.tool_name} requires permission`, - suggestions: request2.permission_suggestions, - blockedPath: request2.blocked_path - }; - const toolUseConfirm = { - assistantMessage: syntheticMessage, - tool, - description: request2.description ?? `${request2.tool_name} requires permission`, - input: request2.input, - toolUseContext: {}, - toolUseID: request2.tool_use_id, - permissionResult, - permissionPromptStartTimeMs: Date.now(), - onUserInteraction() {}, - onAbort() { - const response7 = { - behavior: "deny", - message: "User aborted" - }; - manager7.respondToPermissionRequest(requestId, response7); - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== request2.tool_use_id)); - }, - onAllow(updatedInput, _permissionUpdates, _feedback) { - const response7 = { - behavior: "allow", - updatedInput - }; - manager7.respondToPermissionRequest(requestId, response7); - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== request2.tool_use_id)); - setIsLoading(true); - }, - onReject(feedback2) { - const response7 = { - behavior: "deny", - message: feedback2 ?? "User denied permission" - }; - manager7.respondToPermissionRequest(requestId, response7); - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== request2.tool_use_id)); - }, - async recheckPermission() {} - }; - setToolUseConfirmQueue((queue2) => [...queue2, toolUseConfirm]); - setIsLoading(false); - }, - onConnected: () => { - logForDebugging("[useDirectConnect] Connected"); - isConnectedRef.current = true; - }, - onDisconnected: () => { - logForDebugging("[useDirectConnect] Disconnected"); - if (!isConnectedRef.current) { - process.stderr.write(` -Failed to connect to server at ${config10.wsUrl} -`); - } else { - process.stderr.write(` -Server disconnected. -`); - } - isConnectedRef.current = false; - gracefulShutdown(1); - setIsLoading(false); - }, - onError: (error46) => { - logForDebugging(`[useDirectConnect] Error: ${error46.message}`); - } - }); - managerRef.current = manager7; - manager7.connect(); - return () => { - logForDebugging("[useDirectConnect] Cleanup - disconnecting"); - manager7.disconnect(); - managerRef.current = null; - }; - }, [config10, setMessages, setIsLoading, setToolUseConfirmQueue]); - const sendMessage3 = import_react262.useCallback(async (content) => { - const manager7 = managerRef.current; - if (!manager7) { - return false; - } - setIsLoading(true); - return manager7.sendMessage(content); - }, [setIsLoading]); - const cancelRequest = import_react262.useCallback(() => { - managerRef.current?.sendInterrupt(); - setIsLoading(false); - }, [setIsLoading]); - const disconnect2 = import_react262.useCallback(() => { - managerRef.current?.disconnect(); - managerRef.current = null; - isConnectedRef.current = false; - }, []); - return import_react262.useMemo(() => ({ isRemoteMode, sendMessage: sendMessage3, cancelRequest, disconnect: disconnect2 }), [isRemoteMode, sendMessage3, cancelRequest, disconnect2]); -} -var import_react262; -var init_useDirectConnect = __esm(() => { - init_remotePermissionBridge(); - init_sdkMessageAdapter(); - init_directConnectManager(); - init_Tool(); - init_debug(); - init_gracefulShutdown(); - import_react262 = __toESM(require_react(), 1); -}); - -// src/hooks/useSSHSession.ts -import { randomUUID as randomUUID41 } from "crypto"; -function useSSHSession({ - session: session2, - setMessages, - setIsLoading, - setToolUseConfirmQueue, - tools -}) { - const isRemoteMode = !!session2; - const managerRef = import_react263.useRef(null); - const hasReceivedInitRef = import_react263.useRef(false); - const isConnectedRef = import_react263.useRef(false); - const toolsRef = import_react263.useRef(tools); - import_react263.useEffect(() => { - toolsRef.current = tools; - }, [tools]); - import_react263.useEffect(() => { - if (!session2) - return; - hasReceivedInitRef.current = false; - logForDebugging("[useSSHSession] wiring SSH session manager"); - const manager7 = session2.createManager({ - onMessage: (sdkMessage) => { - if (isSessionEndMessage(sdkMessage)) { - setIsLoading(false); - } - if (sdkMessage.type === "system" && sdkMessage.subtype === "init") { - if (hasReceivedInitRef.current) - return; - hasReceivedInitRef.current = true; - } - const converted = convertSDKMessage(sdkMessage, { - convertToolResults: true - }); - if (converted.type === "message") { - setMessages((prev) => [...prev, converted.message]); - } - }, - onPermissionRequest: (request2, requestId) => { - logForDebugging(`[useSSHSession] permission request: ${request2.tool_name}`); - const tool = findToolByName(toolsRef.current, request2.tool_name) ?? createToolStub(request2.tool_name); - const syntheticMessage = createSyntheticAssistantMessage(request2, requestId); - const permissionResult = { - behavior: "ask", - message: request2.description ?? `${request2.tool_name} requires permission`, - suggestions: request2.permission_suggestions, - blockedPath: request2.blocked_path - }; - const toolUseConfirm = { - assistantMessage: syntheticMessage, - tool, - description: request2.description ?? `${request2.tool_name} requires permission`, - input: request2.input, - toolUseContext: {}, - toolUseID: request2.tool_use_id, - permissionResult, - permissionPromptStartTimeMs: Date.now(), - onUserInteraction() {}, - onAbort() { - manager7.respondToPermissionRequest(requestId, { - behavior: "deny", - message: "User aborted" - }); - setToolUseConfirmQueue((q4) => q4.filter((i6) => i6.toolUseID !== request2.tool_use_id)); - }, - onAllow(updatedInput) { - manager7.respondToPermissionRequest(requestId, { - behavior: "allow", - updatedInput - }); - setToolUseConfirmQueue((q4) => q4.filter((i6) => i6.toolUseID !== request2.tool_use_id)); - setIsLoading(true); - }, - onReject(feedback2) { - manager7.respondToPermissionRequest(requestId, { - behavior: "deny", - message: feedback2 ?? "User denied permission" - }); - setToolUseConfirmQueue((q4) => q4.filter((i6) => i6.toolUseID !== request2.tool_use_id)); - }, - async recheckPermission() {} - }; - setToolUseConfirmQueue((q4) => [...q4, toolUseConfirm]); - setIsLoading(false); - }, - onConnected: () => { - logForDebugging("[useSSHSession] connected"); - isConnectedRef.current = true; - }, - onReconnecting: (attempt, max2) => { - logForDebugging(`[useSSHSession] ssh dropped, reconnecting (${attempt}/${max2})`); - isConnectedRef.current = false; - setIsLoading(false); - const msg = { - type: "system", - subtype: "informational", - content: `SSH connection dropped \u2014 reconnecting (attempt ${attempt}/${max2})...`, - timestamp: new Date().toISOString(), - uuid: randomUUID41(), - level: "warning" - }; - setMessages((prev) => [...prev, msg]); - }, - onDisconnected: () => { - logForDebugging("[useSSHSession] ssh process exited (giving up)"); - const stderr = session2.getStderrTail().trim(); - const connected = isConnectedRef.current; - const exitCode = session2.proc.exitCode; - isConnectedRef.current = false; - setIsLoading(false); - let msg = connected ? "Remote session ended." : "SSH session failed before connecting."; - if (stderr && (!connected || exitCode !== 0)) { - msg += ` -Remote stderr (exit ${exitCode ?? "signal " + session2.proc.signalCode}): -${stderr}`; - } - gracefulShutdown(1, "other", { finalMessage: msg }); - }, - onError: (error46) => { - logForDebugging(`[useSSHSession] error: ${error46.message}`); - } - }); - managerRef.current = manager7; - manager7.connect(); - return () => { - logForDebugging("[useSSHSession] cleanup"); - manager7.disconnect(); - session2.proxy.stop(); - managerRef.current = null; - }; - }, [session2, setMessages, setIsLoading, setToolUseConfirmQueue]); - const sendMessage3 = import_react263.useCallback(async (content) => { - const m4 = managerRef.current; - if (!m4) - return false; - setIsLoading(true); - return m4.sendMessage(content); - }, [setIsLoading]); - const cancelRequest = import_react263.useCallback(() => { - managerRef.current?.sendInterrupt(); - setIsLoading(false); - }, [setIsLoading]); - const disconnect2 = import_react263.useCallback(() => { - managerRef.current?.disconnect(); - managerRef.current = null; - isConnectedRef.current = false; - }, []); - return import_react263.useMemo(() => ({ isRemoteMode, sendMessage: sendMessage3, cancelRequest, disconnect: disconnect2 }), [isRemoteMode, sendMessage3, cancelRequest, disconnect2]); -} -var import_react263; -var init_useSSHSession = __esm(() => { - init_remotePermissionBridge(); - init_sdkMessageAdapter(); - init_Tool(); - init_debug(); - init_gracefulShutdown(); - import_react263 = __toESM(require_react(), 1); -}); - -// src/assistant/sessionHistory.ts -var init_sessionHistory = __esm(() => { - init_oauth(); - init_debug(); - init_api2(); -}); - -// src/hooks/useAssistantHistory.ts -var import_react264; -var init_useAssistantHistory = __esm(() => { - init_sessionHistory(); - init_sdkMessageAdapter(); - init_debug(); - import_react264 = __toESM(require_react(), 1); -}); - -// src/components/FeedbackSurvey/useDebouncedDigitInput.ts -function useDebouncedDigitInput({ - inputValue, - setInputValue, - isValidDigit, - onDigit, - enabled: enabled2 = true, - once: once9 = false, - debounceMs = DEFAULT_DEBOUNCE_MS -}) { - const initialInputValue = import_react265.useRef(inputValue); - const hasTriggeredRef = import_react265.useRef(false); - const debounceRef = import_react265.useRef(null); - const callbacksRef = import_react265.useRef({ setInputValue, isValidDigit, onDigit }); - callbacksRef.current = { setInputValue, isValidDigit, onDigit }; - import_react265.useEffect(() => { - if (!enabled2 || once9 && hasTriggeredRef.current) { - return; - } - if (debounceRef.current !== null) { - clearTimeout(debounceRef.current); - debounceRef.current = null; - } - if (inputValue !== initialInputValue.current) { - const lastChar = normalizeFullWidthDigits(inputValue.slice(-1)); - if (callbacksRef.current.isValidDigit(lastChar)) { - const trimmed = inputValue.slice(0, -1); - debounceRef.current = setTimeout((debounceRef2, hasTriggeredRef2, callbacksRef2, trimmed2, lastChar2) => { - debounceRef2.current = null; - hasTriggeredRef2.current = true; - callbacksRef2.current.setInputValue(trimmed2); - callbacksRef2.current.onDigit(lastChar2); - }, debounceMs, debounceRef, hasTriggeredRef, callbacksRef, trimmed, lastChar); - } - } - return () => { - if (debounceRef.current !== null) { - clearTimeout(debounceRef.current); - debounceRef.current = null; - } - }; - }, [inputValue, enabled2, once9, debounceMs]); -} -var import_react265, DEFAULT_DEBOUNCE_MS = 400; -var init_useDebouncedDigitInput = __esm(() => { - init_stringUtils(); - import_react265 = __toESM(require_react(), 1); -}); - -// src/components/FeedbackSurvey/FeedbackSurveyView.tsx -function FeedbackSurveyView(t0) { - const $2 = import_compiler_runtime337.c(15); - const { - onSelect, - inputValue, - setInputValue, - message: t1 - } = t0; - const message = t1 === undefined ? DEFAULT_MESSAGE : t1; - let t22; - if ($2[0] !== onSelect) { - t22 = (digit) => onSelect(inputToResponse[digit]); - $2[0] = onSelect; - $2[1] = t22; - } else { - t22 = $2[1]; - } - let t32; - if ($2[2] !== inputValue || $2[3] !== setInputValue || $2[4] !== t22) { - t32 = { - inputValue, - setInputValue, - isValidDigit: isValidResponseInput, - onDigit: t22 - }; - $2[2] = inputValue; - $2[3] = setInputValue; - $2[4] = t22; - $2[5] = t32; - } else { - t32 = $2[5]; - } - useDebouncedDigitInput(t32); - let t4; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "\u25CF " - }, undefined, false, undefined, this); - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== message) { - t5 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - children: [ - t4, - /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - bold: true, - children: message - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[7] = message; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - width: 10, - children: /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "1" - }, undefined, false, undefined, this), - ": Bad" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - width: 10, - children: /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "2" - }, undefined, false, undefined, this), - ": Fine" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[10] = t7; - } else { - t7 = $2[10]; - } - let t8; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - width: 10, - children: /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "3" - }, undefined, false, undefined, this), - ": Good" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[11] = t8; - } else { - t8 = $2[11]; - } - let t9; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t9 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: [ - t6, - t7, - t8, - /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "0" - }, undefined, false, undefined, this), - ": Dismiss" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[12] = t9; - } else { - t9 = $2[12]; - } - let t10; - if ($2[13] !== t5) { - t10 = /* @__PURE__ */ jsx_dev_runtime437.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t5, - t9 - ] - }, undefined, true, undefined, this); - $2[13] = t5; - $2[14] = t10; - } else { - t10 = $2[14]; - } - return t10; -} -var import_compiler_runtime337, jsx_dev_runtime437, RESPONSE_INPUTS, inputToResponse, isValidResponseInput = (input) => RESPONSE_INPUTS.includes(input), DEFAULT_MESSAGE = "How is Claude doing this session? (optional)"; -var init_FeedbackSurveyView = __esm(() => { - init_ink2(); - init_useDebouncedDigitInput(); - import_compiler_runtime337 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime437 = __toESM(require_jsx_dev_runtime(), 1); - RESPONSE_INPUTS = ["0", "1", "2", "3"]; - inputToResponse = { - "0": "dismissed", - "1": "bad", - "2": "fine", - "3": "good" - }; -}); - -// src/components/SkillImprovementSurvey.tsx -var import_compiler_runtime338, import_react266, jsx_dev_runtime438; -var init_SkillImprovementSurvey = __esm(() => { - init_figures2(); - init_ink2(); - init_stringUtils(); - init_FeedbackSurveyView(); - import_compiler_runtime338 = __toESM(require_compiler_runtime(), 1); - import_react266 = __toESM(require_react(), 1); - jsx_dev_runtime438 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/hooks/apiQueryHookHelper.ts -var init_apiQueryHookHelper = __esm(() => { - init_claude(); - init_abortController(); - init_log2(); - init_errors(); - init_messages9(); -}); - -// src/utils/hooks/skillImprovement.ts -function initSkillImprovement() { - if (false) {} -} -async function applySkillImprovement(skillName, updates) { - if (!skillName) - return; - const { join: join144 } = await import("path"); - const fs13 = await import("fs/promises"); - const filePath = join144(getCwd(), ".claude", "skills", skillName, "SKILL.md"); - let currentContent; - try { - currentContent = await fs13.readFile(filePath, "utf-8"); - } catch { - logError2(new Error(`Failed to read skill file for improvement: ${filePath}`)); - return; - } - const updateList = updates.map((u5) => `- ${u5.section}: ${u5.change}`).join(` -`); - const response7 = await queryModelWithoutStreaming({ - messages: [ - createUserMessage({ - content: `You are editing a skill definition file. Apply the following improvements to the skill. - - -${currentContent} - - - -${updateList} - - -Rules: -- Integrate the improvements naturally into the existing structure -- Preserve frontmatter (--- block) exactly as-is -- Preserve the overall format and style -- Do not remove existing content unless an improvement explicitly replaces it -- Output the complete updated file inside tags` - }) - ], - systemPrompt: asSystemPrompt([ - "You edit skill definition files to incorporate user preferences. Output only the updated file content." - ]), - thinkingConfig: { type: "disabled" }, - tools: [], - signal: createAbortController().signal, - options: { - getToolPermissionContext: async () => getEmptyToolPermissionContext(), - model: getSmallFastModel(), - toolChoice: undefined, - isNonInteractiveSession: false, - hasAppendSystemPrompt: false, - temperatureOverride: 0, - agents: [], - querySource: "skill_improvement_apply", - mcpTools: [] - } - }); - const responseText = extractTextContent(response7.message.content).trim(); - const updatedContent = extractTag(responseText, "updated_file"); - if (!updatedContent) { - logError2(new Error("Skill improvement apply: no updated_file tag in response")); - return; - } - try { - await fs13.writeFile(filePath, updatedContent, "utf-8"); - } catch (e4) { - logError2(toError(e4)); - } -} -var init_skillImprovement = __esm(() => { - init_state(); - init_growthbook(); - init_analytics(); - init_claude(); - init_Tool(); - init_abortController(); - init_cwd(); - init_errors(); - init_log2(); - init_messages9(); - init_model(); - init_slowOperations(); - init_apiQueryHookHelper(); - init_postSamplingHooks(); -}); - -// src/hooks/useSkillImprovementSurvey.ts -function useSkillImprovementSurvey(setMessages) { - const suggestion = useAppState((s4) => s4.skillImprovement.suggestion); - const setAppState = useSetAppState(); - const [isOpen, setIsOpen] = import_react267.useState(false); - const lastSuggestionRef = import_react267.useRef(suggestion); - const loggedAppearanceRef = import_react267.useRef(false); - if (suggestion) { - lastSuggestionRef.current = suggestion; - } - if (suggestion && !isOpen) { - setIsOpen(true); - if (!loggedAppearanceRef.current) { - loggedAppearanceRef.current = true; - logEvent("tengu_skill_improvement_survey", { - event_type: "appeared", - _PROTO_skill_name: suggestion.skillName ?? "unknown" - }); - } - } - const handleSelect = import_react267.useCallback((selected) => { - const current = lastSuggestionRef.current; - if (!current) - return; - const applied = selected !== "dismissed"; - logEvent("tengu_skill_improvement_survey", { - event_type: "responded", - response: applied ? "applied" : "dismissed", - _PROTO_skill_name: current.skillName - }); - if (applied) { - applySkillImprovement(current.skillName, current.updates).then(() => { - setMessages((prev) => [ - ...prev, - createSystemMessage(`Skill "${current.skillName}" updated with improvements.`, "suggestion") - ]); - }); - } - setIsOpen(false); - loggedAppearanceRef.current = false; - setAppState((prev) => { - if (!prev.skillImprovement.suggestion) - return prev; - return { - ...prev, - skillImprovement: { suggestion: null } - }; - }); - }, [setAppState, setMessages]); - return { - isOpen, - suggestion: lastSuggestionRef.current, - handleSelect - }; -} -var import_react267; -var init_useSkillImprovementSurvey = __esm(() => { - init_analytics(); - init_AppState(); - init_skillImprovement(); - init_messages9(); - import_react267 = __toESM(require_react(), 1); -}); - -// src/moreright/useMoreRight.tsx -function useMoreRight(_args) { - return { - onBeforeQuery: async () => true, - onTurnComplete: async () => {}, - render: () => null - }; -} - -// src/utils/cleanup.ts -import * as fs13 from "fs/promises"; -import { homedir as homedir35 } from "os"; -import { join as join144 } from "path"; -function getCutoffDate() { - const settings = getSettings_DEPRECATED() || {}; - const cleanupPeriodDays = settings.cleanupPeriodDays ?? DEFAULT_CLEANUP_PERIOD_DAYS; - const cleanupPeriodMs = cleanupPeriodDays * 24 * 60 * 60 * 1000; - return new Date(Date.now() - cleanupPeriodMs); -} -function addCleanupResults(a5, b5) { - return { - messages: a5.messages + b5.messages, - errors: a5.errors + b5.errors - }; -} -function convertFileNameToDate(filename) { - const isoStr = filename.split(".")[0].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/, "T$1:$2:$3.$4Z"); - return new Date(isoStr); -} -async function cleanupOldFilesInDirectory(dirPath, cutoffDate, isMessagePath) { - const result = { messages: 0, errors: 0 }; - try { - const files3 = await getFsImplementation().readdir(dirPath); - for (const file2 of files3) { - try { - const timestamp = convertFileNameToDate(file2.name); - if (timestamp < cutoffDate) { - await getFsImplementation().unlink(join144(dirPath, file2.name)); - if (isMessagePath) { - result.messages++; - } else { - result.errors++; - } - } - } catch (error46) { - logError2(error46); - } - } - } catch (error46) { - if (error46 instanceof Error && "code" in error46 && error46.code !== "ENOENT") { - logError2(error46); - } - } - return result; -} -async function cleanupOldMessageFiles() { - const fsImpl = getFsImplementation(); - const cutoffDate = getCutoffDate(); - const errorPath = CACHE_PATHS.errors(); - const baseCachePath = CACHE_PATHS.baseLogs(); - let result = await cleanupOldFilesInDirectory(errorPath, cutoffDate, false); - try { - let dirents; - try { - dirents = await fsImpl.readdir(baseCachePath); - } catch { - return result; - } - const mcpLogDirs = dirents.filter((dirent) => dirent.isDirectory() && dirent.name.startsWith("mcp-logs-")).map((dirent) => join144(baseCachePath, dirent.name)); - for (const mcpLogDir of mcpLogDirs) { - result = addCleanupResults(result, await cleanupOldFilesInDirectory(mcpLogDir, cutoffDate, true)); - await tryRmdir(mcpLogDir, fsImpl); - } - } catch (error46) { - if (error46 instanceof Error && "code" in error46 && error46.code !== "ENOENT") { - logError2(error46); - } - } - return result; -} -async function unlinkIfOld(filePath, cutoffDate, fsImpl) { - const stats2 = await fsImpl.stat(filePath); - if (stats2.mtime < cutoffDate) { - await fsImpl.unlink(filePath); - return true; - } - return false; -} -async function tryRmdir(dirPath, fsImpl) { - try { - await fsImpl.rmdir(dirPath); - } catch {} -} -async function cleanupOldSessionFiles() { - const cutoffDate = getCutoffDate(); - const result = { messages: 0, errors: 0 }; - const projectsDir = getProjectsDir2(); - const fsImpl = getFsImplementation(); - let projectDirents; - try { - projectDirents = await fsImpl.readdir(projectsDir); - } catch { - return result; - } - for (const projectDirent of projectDirents) { - if (!projectDirent.isDirectory()) - continue; - const projectDir = join144(projectsDir, projectDirent.name); - let entries; - try { - entries = await fsImpl.readdir(projectDir); - } catch { - result.errors++; - continue; - } - for (const entry of entries) { - if (entry.isFile()) { - if (!entry.name.endsWith(".jsonl") && !entry.name.endsWith(".cast")) { - continue; - } - try { - if (await unlinkIfOld(join144(projectDir, entry.name), cutoffDate, fsImpl)) { - result.messages++; - } - } catch { - result.errors++; - } - } else if (entry.isDirectory()) { - const sessionDir = join144(projectDir, entry.name); - const toolResultsDir = join144(sessionDir, TOOL_RESULTS_SUBDIR); - let toolDirs; - try { - toolDirs = await fsImpl.readdir(toolResultsDir); - } catch { - await tryRmdir(sessionDir, fsImpl); - continue; - } - for (const toolEntry of toolDirs) { - if (toolEntry.isFile()) { - try { - if (await unlinkIfOld(join144(toolResultsDir, toolEntry.name), cutoffDate, fsImpl)) { - result.messages++; - } - } catch { - result.errors++; - } - } else if (toolEntry.isDirectory()) { - const toolDirPath = join144(toolResultsDir, toolEntry.name); - let toolFiles; - try { - toolFiles = await fsImpl.readdir(toolDirPath); - } catch { - continue; - } - for (const tf of toolFiles) { - if (!tf.isFile()) - continue; - try { - if (await unlinkIfOld(join144(toolDirPath, tf.name), cutoffDate, fsImpl)) { - result.messages++; - } - } catch { - result.errors++; - } - } - await tryRmdir(toolDirPath, fsImpl); - } - } - await tryRmdir(toolResultsDir, fsImpl); - await tryRmdir(sessionDir, fsImpl); - } - } - await tryRmdir(projectDir, fsImpl); - } - return result; -} -async function cleanupSingleDirectory(dirPath, extension, removeEmptyDir = true) { - const cutoffDate = getCutoffDate(); - const result = { messages: 0, errors: 0 }; - const fsImpl = getFsImplementation(); - let dirents; - try { - dirents = await fsImpl.readdir(dirPath); - } catch { - return result; - } - for (const dirent of dirents) { - if (!dirent.isFile() || !dirent.name.endsWith(extension)) - continue; - try { - if (await unlinkIfOld(join144(dirPath, dirent.name), cutoffDate, fsImpl)) { - result.messages++; - } - } catch { - result.errors++; - } - } - if (removeEmptyDir) { - await tryRmdir(dirPath, fsImpl); - } - return result; -} -function cleanupOldPlanFiles() { - const plansDir = join144(getClaudeConfigHomeDir(), "plans"); - return cleanupSingleDirectory(plansDir, ".md"); -} -async function cleanupOldFileHistoryBackups() { - const cutoffDate = getCutoffDate(); - const result = { messages: 0, errors: 0 }; - const fsImpl = getFsImplementation(); - try { - const configDir = getClaudeConfigHomeDir(); - const fileHistoryStorageDir = join144(configDir, "file-history"); - let dirents; - try { - dirents = await fsImpl.readdir(fileHistoryStorageDir); - } catch { - return result; - } - const fileHistorySessionsDirs = dirents.filter((dirent) => dirent.isDirectory()).map((dirent) => join144(fileHistoryStorageDir, dirent.name)); - await Promise.all(fileHistorySessionsDirs.map(async (fileHistorySessionDir) => { - try { - const stats2 = await fsImpl.stat(fileHistorySessionDir); - if (stats2.mtime < cutoffDate) { - await fsImpl.rm(fileHistorySessionDir, { - recursive: true, - force: true - }); - result.messages++; - } - } catch { - result.errors++; - } - })); - await tryRmdir(fileHistoryStorageDir, fsImpl); - } catch (error46) { - logError2(error46); - } - return result; -} -async function cleanupOldSessionEnvDirs() { - const cutoffDate = getCutoffDate(); - const result = { messages: 0, errors: 0 }; - const fsImpl = getFsImplementation(); - try { - const configDir = getClaudeConfigHomeDir(); - const sessionEnvBaseDir = join144(configDir, "session-env"); - let dirents; - try { - dirents = await fsImpl.readdir(sessionEnvBaseDir); - } catch { - return result; - } - const sessionEnvDirs = dirents.filter((dirent) => dirent.isDirectory()).map((dirent) => join144(sessionEnvBaseDir, dirent.name)); - for (const sessionEnvDir of sessionEnvDirs) { - try { - const stats2 = await fsImpl.stat(sessionEnvDir); - if (stats2.mtime < cutoffDate) { - await fsImpl.rm(sessionEnvDir, { recursive: true, force: true }); - result.messages++; - } - } catch { - result.errors++; - } - } - await tryRmdir(sessionEnvBaseDir, fsImpl); - } catch (error46) { - logError2(error46); - } - return result; -} -async function cleanupOldDebugLogs() { - const cutoffDate = getCutoffDate(); - const result = { messages: 0, errors: 0 }; - const fsImpl = getFsImplementation(); - const debugDir = join144(getClaudeConfigHomeDir(), "debug"); - let dirents; - try { - dirents = await fsImpl.readdir(debugDir); - } catch { - return result; - } - for (const dirent of dirents) { - if (!dirent.isFile() || !dirent.name.endsWith(".txt") || dirent.name === "latest") { - continue; - } - try { - if (await unlinkIfOld(join144(debugDir, dirent.name), cutoffDate, fsImpl)) { - result.messages++; - } - } catch { - result.errors++; - } - } - return result; -} -async function cleanupNpmCacheForAnthropicPackages() { - const markerPath = join144(getClaudeConfigHomeDir(), ".npm-cache-cleanup"); - try { - const stat46 = await fs13.stat(markerPath); - if (Date.now() - stat46.mtimeMs < ONE_DAY_MS) { - logForDebugging("npm cache cleanup: skipping, ran recently"); - return; - } - } catch {} - try { - await lock(markerPath, { retries: 0, realpath: false }); - } catch { - logForDebugging("npm cache cleanup: skipping, lock held"); - return; - } - logForDebugging("npm cache cleanup: starting"); - const npmCachePath = join144(homedir35(), ".npm", "_cacache"); - const NPM_CACHE_RETENTION_COUNT = 5; - const startTime = Date.now(); - try { - const cacache = await import("cacache"); - const cutoff = startTime - ONE_DAY_MS; - const stream10 = cacache.ls.stream(npmCachePath); - const anthropicEntries = []; - for await (const entry of stream10) { - if (entry.key.includes("@anthropic-ai/claude-")) { - anthropicEntries.push({ key: entry.key, time: entry.time }); - } - } - const byPackage = new Map; - for (const entry of anthropicEntries) { - const atVersionIdx = entry.key.lastIndexOf("@"); - const pkgName = atVersionIdx > 0 ? entry.key.slice(0, atVersionIdx) : entry.key; - const existing = byPackage.get(pkgName) ?? []; - existing.push(entry); - byPackage.set(pkgName, existing); - } - const keysToRemove = []; - for (const [, entries] of byPackage) { - entries.sort((a5, b5) => b5.time - a5.time); - for (let i6 = 0;i6 < entries.length; i6++) { - const entry = entries[i6]; - if (entry.time < cutoff || i6 >= NPM_CACHE_RETENTION_COUNT) { - keysToRemove.push(entry.key); - } - } - } - await Promise.all(keysToRemove.map((key2) => cacache.rm.entry(npmCachePath, key2))); - await fs13.writeFile(markerPath, new Date().toISOString()); - const durationMs = Date.now() - startTime; - if (keysToRemove.length > 0) { - logForDebugging(`npm cache cleanup: Removed ${keysToRemove.length} old @anthropic-ai entries in ${durationMs}ms`); - } else { - logForDebugging(`npm cache cleanup: completed in ${durationMs}ms`); - } - logEvent("tengu_npm_cache_cleanup", { - success: true, - durationMs, - entriesRemoved: keysToRemove.length - }); - } catch (error46) { - logError2(error46); - logEvent("tengu_npm_cache_cleanup", { - success: false, - durationMs: Date.now() - startTime - }); - } finally { - await unlock(markerPath, { realpath: false }).catch(() => {}); - } -} -async function cleanupOldVersionsThrottled() { - const markerPath = join144(getClaudeConfigHomeDir(), ".version-cleanup"); - try { - const stat46 = await fs13.stat(markerPath); - if (Date.now() - stat46.mtimeMs < ONE_DAY_MS) { - logForDebugging("version cleanup: skipping, ran recently"); - return; - } - } catch {} - try { - await lock(markerPath, { retries: 0, realpath: false }); - } catch { - logForDebugging("version cleanup: skipping, lock held"); - return; - } - logForDebugging("version cleanup: starting (throttled)"); - try { - await cleanupOldVersions(); - await fs13.writeFile(markerPath, new Date().toISOString()); - } catch (error46) { - logError2(error46); - } finally { - await unlock(markerPath, { realpath: false }).catch(() => {}); - } -} -async function cleanupOldMessageFilesInBackground() { - const { errors: errors8 } = getSettingsWithAllErrors(); - if (errors8.length > 0 && rawSettingsContainsKey("cleanupPeriodDays")) { - logForDebugging("Skipping cleanup: settings have validation errors but cleanupPeriodDays was explicitly set. Fix settings errors to enable cleanup."); - return; - } - await cleanupOldMessageFiles(); - await cleanupOldSessionFiles(); - await cleanupOldPlanFiles(); - await cleanupOldFileHistoryBackups(); - await cleanupOldSessionEnvDirs(); - await cleanupOldDebugLogs(); - await cleanupOldImageCaches(); - await cleanupOldPastes(getCutoffDate()); - const removedWorktrees = await cleanupStaleAgentWorktrees(getCutoffDate()); - if (removedWorktrees > 0) { - logEvent("tengu_worktree_cleanup", { removed: removedWorktrees }); - } - if (process.env.USER_TYPE === "ant") { - await cleanupNpmCacheForAnthropicPackages(); - } -} -var DEFAULT_CLEANUP_PERIOD_DAYS = 30, ONE_DAY_MS; -var init_cleanup2 = __esm(() => { - init_analytics(); - init_cachePaths(); - init_debug(); - init_envUtils(); - init_fsOperations(); - init_imageStore(); - init_log2(); - init_nativeInstaller(); - init_pasteStore(); - init_sessionStorage(); - init_allErrors(); - init_settings2(); - init_toolResultStorage(); - init_worktree(); - ONE_DAY_MS = 24 * 60 * 60 * 1000; -}); - -// src/utils/backgroundHousekeeping.ts -var exports_backgroundHousekeeping = {}; -__export(exports_backgroundHousekeeping, { - startBackgroundHousekeeping: () => startBackgroundHousekeeping -}); -function startBackgroundHousekeeping() { - initMagicDocs(); - initSkillImprovement(); - if (false) {} - initAutoDream(); - autoUpdateMarketplacesAndPluginsInBackground(); - if (false) {} - let needsCleanup = true; - async function runVerySlowOps() { - if (getIsInteractive() && getLastInteractionTime() > Date.now() - 1000 * 60) { - setTimeout(runVerySlowOps, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION).unref(); - return; - } - if (needsCleanup) { - needsCleanup = false; - await cleanupOldMessageFilesInBackground(); - } - if (getIsInteractive() && getLastInteractionTime() > Date.now() - 1000 * 60) { - setTimeout(runVerySlowOps, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION).unref(); - return; - } - await cleanupOldVersions(); - } - setTimeout(runVerySlowOps, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION).unref(); - if (process.env.USER_TYPE === "ant") { - const interval = setInterval(() => { - cleanupNpmCacheForAnthropicPackages(); - cleanupOldVersionsThrottled(); - }, RECURRING_CLEANUP_INTERVAL_MS); - interval.unref(); - } -} -var RECURRING_CLEANUP_INTERVAL_MS, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION; -var init_backgroundHousekeeping = __esm(() => { - init_autoDream(); - init_magicDocs(); - init_skillImprovement(); - init_state(); - init_cleanup2(); - init_nativeInstaller(); - init_pluginAutoupdate(); - RECURRING_CLEANUP_INTERVAL_MS = 24 * 60 * 60 * 1000; - DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION = 10 * 60 * 1000; -}); - -// src/costHook.ts -function useCostSummary(getFpsMetrics) { - import_react268.useEffect(() => { - const f4 = () => { - if (hasConsoleBillingAccess()) { - process.stdout.write(` -` + formatTotalCost() + ` -`); - } - saveCurrentSessionCosts(getFpsMetrics?.()); - }; - process.on("exit", f4); - return () => { - process.off("exit", f4); - }; - }, []); -} -var import_react268; -var init_costHook = __esm(() => { - init_cost_tracker(); - init_billing(); - import_react268 = __toESM(require_react(), 1); -}); - -// src/hooks/useAfterFirstRender.ts -function useAfterFirstRender() { - import_react269.useEffect(() => { - if (process.env.USER_TYPE === "ant" && isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER)) { - process.stderr.write(` -Startup time: ${Math.round(process.uptime() * 1000)}ms -`); - process.exit(0); - } - }, []); -} -var import_react269; -var init_useAfterFirstRender = __esm(() => { - init_envUtils(); - import_react269 = __toESM(require_react(), 1); -}); - -// src/hooks/useDeferredHookMessages.ts -function useDeferredHookMessages(pendingHookMessages, setMessages) { - const pendingRef = import_react270.useRef(pendingHookMessages ?? null); - const resolvedRef = import_react270.useRef(!pendingHookMessages); - import_react270.useEffect(() => { - const promise3 = pendingRef.current; - if (!promise3) - return; - let cancelled = false; - promise3.then((msgs) => { - if (cancelled) - return; - resolvedRef.current = true; - pendingRef.current = null; - if (msgs.length > 0) { - setMessages((prev) => [...msgs, ...prev]); - } - }); - return () => { - cancelled = true; - }; - }, [setMessages]); - return import_react270.useCallback(async () => { - if (resolvedRef.current || !pendingRef.current) - return; - const msgs = await pendingRef.current; - if (resolvedRef.current) - return; - resolvedRef.current = true; - pendingRef.current = null; - if (msgs.length > 0) { - setMessages((prev) => [...msgs, ...prev]); - } - }, [setMessages]); -} -var import_react270; -var init_useDeferredHookMessages = __esm(() => { - import_react270 = __toESM(require_react(), 1); -}); - -// src/hooks/useApiKeyVerification.ts -function useApiKeyVerification() { - const [status2, setStatus] = import_react271.useState(() => { - if (!isAnthropicAuthEnabled() || isClaudeAISubscriber()) { - return "valid"; - } - const { key: key2, source } = getAnthropicApiKeyWithSource({ - skipRetrievingKeyFromApiKeyHelper: true - }); - if (key2 || source === "apiKeyHelper") { - return "loading"; - } - return "missing"; - }); - const [error46, setError] = import_react271.useState(null); - const verify = import_react271.useCallback(async () => { - if (!isAnthropicAuthEnabled() || isClaudeAISubscriber()) { - setStatus("valid"); - return; - } - await getApiKeyFromApiKeyHelper(getIsNonInteractiveSession()); - const { key: apiKey, source } = getAnthropicApiKeyWithSource(); - if (!apiKey) { - if (source === "apiKeyHelper") { - setStatus("error"); - setError(new Error("API key helper did not return a valid key")); - return; - } - const newStatus = "missing"; - setStatus(newStatus); - return; - } - try { - const isValid2 = await verifyApiKey(apiKey, false); - const newStatus = isValid2 ? "valid" : "invalid"; - setStatus(newStatus); - return; - } catch (error47) { - setError(error47); - const newStatus = "error"; - setStatus(newStatus); - return; - } - }, []); - return { - status: status2, - reverify: verify, - error: error46 - }; -} -var import_react271; -var init_useApiKeyVerification = __esm(() => { - init_state(); - init_claude(); - init_auth14(); - import_react271 = __toESM(require_react(), 1); -}); - -// src/utils/terminalPanel.ts -var init_terminalPanel = __esm(() => { - init_state(); - init_instances(); - init_cleanupRegistry(); - init_cwd(); - init_debug(); -}); - -// src/hooks/useGlobalKeybindings.tsx -function GlobalKeybindingHandlers({ - screen, - setScreen, - showAllInTranscript, - setShowAllInTranscript, - messageCount, - onEnterTranscript, - onExitTranscript, - virtualScrollActive, - searchBarOpen = false -}) { - const expandedView = useAppState((s4) => s4.expandedView); - const setAppState = useSetAppState(); - const handleToggleTodos = import_react272.useCallback(() => { - logEvent("tengu_toggle_todos", { - is_expanded: expandedView === "tasks" - }); - setAppState((prev) => { - const { - getAllInProcessTeammateTasks: getAllInProcessTeammateTasks2 - } = (init_InProcessTeammateTask(), __toCommonJS(exports_InProcessTeammateTask)); - const hasTeammates = count2(getAllInProcessTeammateTasks2(prev.tasks), (t4) => t4.status === "running") > 0; - if (hasTeammates) { - switch (prev.expandedView) { - case "none": - return { - ...prev, - expandedView: "tasks" - }; - case "tasks": - return { - ...prev, - expandedView: "teammates" - }; - case "teammates": - return { - ...prev, - expandedView: "none" - }; - } - } - return { - ...prev, - expandedView: prev.expandedView === "tasks" ? "none" : "tasks" - }; - }); - }, [expandedView, setAppState]); - const isBriefOnly = false; - const handleToggleTranscript = import_react272.useCallback(() => { - if (false) {} - const isEnteringTranscript = screen !== "transcript"; - logEvent("tengu_toggle_transcript", { - is_entering: isEnteringTranscript, - show_all: showAllInTranscript, - message_count: messageCount - }); - setScreen((s_1) => s_1 === "transcript" ? "prompt" : "transcript"); - setShowAllInTranscript(false); - if (isEnteringTranscript && onEnterTranscript) { - onEnterTranscript(); - } - if (!isEnteringTranscript && onExitTranscript) { - onExitTranscript(); - } - }, [screen, setScreen, isBriefOnly, showAllInTranscript, setShowAllInTranscript, messageCount, setAppState, onEnterTranscript, onExitTranscript]); - const handleToggleShowAll = import_react272.useCallback(() => { - logEvent("tengu_transcript_toggle_show_all", { - is_expanding: !showAllInTranscript, - message_count: messageCount - }); - setShowAllInTranscript((prev_1) => !prev_1); - }, [showAllInTranscript, setShowAllInTranscript, messageCount]); - const handleExitTranscript = import_react272.useCallback(() => { - logEvent("tengu_transcript_exit", { - show_all: showAllInTranscript, - message_count: messageCount - }); - setScreen("prompt"); - setShowAllInTranscript(false); - if (onExitTranscript) { - onExitTranscript(); - } - }, [setScreen, showAllInTranscript, setShowAllInTranscript, messageCount, onExitTranscript]); - const handleToggleBrief = import_react272.useCallback(() => { - if (false) {} - }, [isBriefOnly, setAppState]); - useKeybinding("app:toggleTodos", handleToggleTodos, { - context: "Global" - }); - useKeybinding("app:toggleTranscript", handleToggleTranscript, { - context: "Global" - }); - if (false) {} - useKeybinding("app:toggleTeammatePreview", () => { - setAppState((prev_3) => ({ - ...prev_3, - showTeammateMessagePreview: !prev_3.showTeammateMessagePreview - })); - }, { - context: "Global" - }); - const handleToggleTerminal = import_react272.useCallback(() => { - if (false) {} - }, []); - useKeybinding("app:toggleTerminal", handleToggleTerminal, { - context: "Global" - }); - const handleRedraw = import_react272.useCallback(() => { - instances_default.get(process.stdout)?.forceRedraw(); - }, []); - useKeybinding("app:redraw", handleRedraw, { - context: "Global" - }); - const isInTranscript = screen === "transcript"; - useKeybinding("transcript:toggleShowAll", handleToggleShowAll, { - context: "Transcript", - isActive: isInTranscript && !virtualScrollActive - }); - useKeybinding("transcript:exit", handleExitTranscript, { - context: "Transcript", - isActive: isInTranscript && !searchBarOpen - }); - return null; -} -var import_react272; -var init_useGlobalKeybindings = __esm(() => { - init_instances(); - init_useKeybinding(); - init_growthbook(); - init_analytics(); - init_AppState(); - init_terminalPanel(); - import_react272 = __toESM(require_react(), 1); -}); - -// src/hooks/useCommandKeybindings.tsx -function CommandKeybindingHandlers(t0) { - const $2 = import_compiler_runtime339.c(8); - const { - onSubmit, - isActive: t1 - } = t0; - const isActive = t1 === undefined ? true : t1; - const keybindingContext = useOptionalKeybindingContext(); - const isModalOverlayActive = useIsModalOverlayActive(); - let t22; - bb0: { - if (!keybindingContext) { - let t33; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t33 = new Set; - $2[0] = t33; - } else { - t33 = $2[0]; - } - t22 = t33; - break bb0; - } - let actions; - if ($2[1] !== keybindingContext.bindings) { - actions = new Set; - for (const binding of keybindingContext.bindings) { - if (binding.action?.startsWith("command:")) { - actions.add(binding.action); - } - } - $2[1] = keybindingContext.bindings; - $2[2] = actions; - } else { - actions = $2[2]; - } - t22 = actions; - } - const commandActions = t22; - let map8; - if ($2[3] !== commandActions || $2[4] !== onSubmit) { - map8 = {}; - for (const action2 of commandActions) { - const commandName = action2.slice(8); - map8[action2] = () => { - onSubmit(`/${commandName}`, NOOP_HELPERS, undefined, { - fromKeybinding: true - }); - }; - } - $2[3] = commandActions; - $2[4] = onSubmit; - $2[5] = map8; - } else { - map8 = $2[5]; - } - const handlers = map8; - const t32 = isActive && !isModalOverlayActive; - let t4; - if ($2[6] !== t32) { - t4 = { - context: "Chat", - isActive: t32 - }; - $2[6] = t32; - $2[7] = t4; - } else { - t4 = $2[7]; - } - useKeybindings(handlers, t4); - return null; -} -var import_compiler_runtime339, NOOP_HELPERS; -var init_useCommandKeybindings = __esm(() => { - init_overlayContext(); - init_KeybindingContext(); - init_useKeybinding(); - import_compiler_runtime339 = __toESM(require_compiler_runtime(), 1); - NOOP_HELPERS = { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }; -}); - -// src/hooks/useCancelRequest.ts -function CancelRequestHandler(props) { - const { - setToolUseConfirmQueue, - onCancel, - onAgentsKilled, - isMessageSelectorVisible, - screen, - abortSignal, - popCommandFromQueue, - vimMode, - isLocalJSXCommand, - isSearchingHistory, - isHelpOpen, - inputMode, - inputValue, - streamMode - } = props; - const store = useAppStateStore(); - const setAppState = useSetAppState(); - const queuedCommandsLength = useCommandQueue().length; - const { addNotification, removeNotification } = useNotifications(); - const lastKillAgentsPressRef = import_react273.useRef(0); - const viewSelectionMode = useAppState((s4) => s4.viewSelectionMode); - const handleCancel = import_react273.useCallback(() => { - const cancelProps = { - source: "escape", - streamMode - }; - if (abortSignal !== undefined && !abortSignal.aborted) { - logEvent("tengu_cancel", cancelProps); - setToolUseConfirmQueue(() => []); - onCancel(); - return; - } - if (hasCommandsInQueue()) { - if (popCommandFromQueue) { - popCommandFromQueue(); - return; - } - } - logEvent("tengu_cancel", cancelProps); - setToolUseConfirmQueue(() => []); - onCancel(); - }, [ - abortSignal, - popCommandFromQueue, - setToolUseConfirmQueue, - onCancel, - streamMode - ]); - const isOverlayActive = useIsOverlayActive(); - const canCancelRunningTask = abortSignal !== undefined && !abortSignal.aborted; - const hasQueuedCommands = queuedCommandsLength > 0; - const isInSpecialModeWithEmptyInput = inputMode !== undefined && inputMode !== "prompt" && !inputValue; - const isViewingTeammate = viewSelectionMode === "viewing-agent"; - const isContextActive = screen !== "transcript" && !isSearchingHistory && !isMessageSelectorVisible && !isLocalJSXCommand && !isHelpOpen && !isOverlayActive && !(isVimModeEnabled() && vimMode === "INSERT"); - const isEscapeActive = isContextActive && (canCancelRunningTask || hasQueuedCommands) && !isInSpecialModeWithEmptyInput && !isViewingTeammate; - const isCtrlCActive = isContextActive && (canCancelRunningTask || hasQueuedCommands || isViewingTeammate); - useKeybinding("chat:cancel", handleCancel, { - context: "Chat", - isActive: isEscapeActive - }); - const killAllAgentsAndNotify = import_react273.useCallback(() => { - const tasks2 = store.getState().tasks; - const running = Object.entries(tasks2).filter(([, t4]) => t4.type === "local_agent" && t4.status === "running"); - if (running.length === 0) - return false; - killAllRunningAgentTasks(tasks2, setAppState); - const descriptions = []; - for (const [taskId, task] of running) { - markAgentsNotified(taskId, setAppState); - descriptions.push(task.description); - emitTaskTerminatedSdk(taskId, "stopped", { - toolUseId: task.toolUseId, - summary: task.description - }); - } - const summary = descriptions.length === 1 ? `Background agent "${descriptions[0]}" was stopped by the user.` : `${descriptions.length} background agents were stopped by the user: ${descriptions.map((d4) => `"${d4}"`).join(", ")}.`; - enqueuePendingNotification({ value: summary, mode: "task-notification" }); - onAgentsKilled(); - return true; - }, [store, setAppState, onAgentsKilled]); - const handleInterrupt = import_react273.useCallback(() => { - if (isViewingTeammate) { - killAllAgentsAndNotify(); - exitTeammateView(setAppState); - } - if (canCancelRunningTask || hasQueuedCommands) { - handleCancel(); - } - }, [ - isViewingTeammate, - killAllAgentsAndNotify, - setAppState, - canCancelRunningTask, - hasQueuedCommands, - handleCancel - ]); - useKeybinding("app:interrupt", handleInterrupt, { - context: "Global", - isActive: isCtrlCActive - }); - const handleKillAgents = import_react273.useCallback(() => { - const tasks2 = store.getState().tasks; - const hasRunningAgents = Object.values(tasks2).some((t4) => t4.type === "local_agent" && t4.status === "running"); - if (!hasRunningAgents) { - addNotification({ - key: "kill-agents-none", - text: "No background agents running", - priority: "immediate", - timeoutMs: 2000 - }); - return; - } - const now2 = Date.now(); - const elapsed = now2 - lastKillAgentsPressRef.current; - if (elapsed <= KILL_AGENTS_CONFIRM_WINDOW_MS) { - lastKillAgentsPressRef.current = 0; - removeNotification("kill-agents-confirm"); - logEvent("tengu_cancel", { - source: "kill_agents" - }); - clearCommandQueue(); - killAllAgentsAndNotify(); - return; - } - lastKillAgentsPressRef.current = now2; - const shortcut = getShortcutDisplay("chat:killAgents", "Chat", "ctrl+x ctrl+k"); - addNotification({ - key: "kill-agents-confirm", - text: `Press ${shortcut} again to stop background agents`, - priority: "immediate", - timeoutMs: KILL_AGENTS_CONFIRM_WINDOW_MS - }); - }, [store, addNotification, removeNotification, killAllAgentsAndNotify]); - useKeybinding("chat:killAgents", handleKillAgents, { - context: "Chat" - }); - return null; -} -var import_react273, KILL_AGENTS_CONFIRM_WINDOW_MS = 3000; -var init_useCancelRequest = __esm(() => { - init_analytics(); - init_AppState(); - init_utils14(); - init_notifications(); - init_overlayContext(); - init_useCommandQueue(); - init_shortcutFormat(); - init_useKeybinding(); - init_teammateViewHelpers(); - init_LocalAgentTask(); - init_messageQueueManager(); - init_sdkEventQueue(); - import_react273 = __toESM(require_react(), 1); -}); - -// src/hooks/useBackgroundTaskNavigation.ts -function stepTeammateSelection(delta, setAppState) { - setAppState((prev) => { - const currentCount = getRunningTeammatesSorted(prev.tasks).length; - if (currentCount === 0) - return prev; - if (prev.expandedView !== "teammates") { - return { - ...prev, - expandedView: "teammates", - viewSelectionMode: "selecting-agent", - selectedIPAgentIndex: -1 - }; - } - const maxIdx = currentCount; - const cur = prev.selectedIPAgentIndex; - const next2 = delta === 1 ? cur >= maxIdx ? -1 : cur + 1 : cur <= -1 ? maxIdx : cur - 1; - return { - ...prev, - selectedIPAgentIndex: next2, - viewSelectionMode: "selecting-agent" - }; - }); -} -function useBackgroundTaskNavigation(options2) { - const tasks2 = useAppState((s4) => s4.tasks); - const viewSelectionMode = useAppState((s4) => s4.viewSelectionMode); - const viewingAgentTaskId = useAppState((s4) => s4.viewingAgentTaskId); - const selectedIPAgentIndex = useAppState((s4) => s4.selectedIPAgentIndex); - const setAppState = useSetAppState(); - const teammateTasks = getRunningTeammatesSorted(tasks2); - const teammateCount = teammateTasks.length; - const hasNonTeammateBackgroundTasks = Object.values(tasks2).some((t4) => isBackgroundTask(t4) && t4.type !== "in_process_teammate"); - const prevTeammateCountRef = import_react274.useRef(teammateCount); - import_react274.useEffect(() => { - const prevCount = prevTeammateCountRef.current; - prevTeammateCountRef.current = teammateCount; - setAppState((prev) => { - const currentTeammates = getRunningTeammatesSorted(prev.tasks); - const currentCount = currentTeammates.length; - if (currentCount === 0 && prevCount > 0 && prev.selectedIPAgentIndex !== -1) { - if (prev.viewSelectionMode === "viewing-agent") { - return { - ...prev, - selectedIPAgentIndex: -1 - }; - } - return { - ...prev, - selectedIPAgentIndex: -1, - viewSelectionMode: "none" - }; - } - const maxIndex = prev.expandedView === "teammates" ? currentCount : currentCount - 1; - if (currentCount > 0 && prev.selectedIPAgentIndex > maxIndex) { - return { - ...prev, - selectedIPAgentIndex: maxIndex - }; - } - return prev; - }); - }, [teammateCount, setAppState]); - const getSelectedTeammate = () => { - if (teammateCount === 0) - return null; - const selectedIndex = selectedIPAgentIndex; - const task = teammateTasks[selectedIndex]; - if (!task) - return null; - return { taskId: task.id, task }; - }; - const handleKeyDown = (e4) => { - if (e4.key === "escape" && viewSelectionMode === "viewing-agent") { - e4.preventDefault(); - const taskId = viewingAgentTaskId; - if (taskId) { - const task = tasks2[taskId]; - if (isInProcessTeammateTask(task) && task.status === "running") { - task.currentWorkAbortController?.abort(); - return; - } - } - exitTeammateView(setAppState); - return; - } - if (e4.key === "escape" && viewSelectionMode === "selecting-agent") { - e4.preventDefault(); - setAppState((prev) => ({ - ...prev, - viewSelectionMode: "none", - selectedIPAgentIndex: -1 - })); - return; - } - if (e4.shift && (e4.key === "up" || e4.key === "down")) { - e4.preventDefault(); - if (teammateCount > 0) { - stepTeammateSelection(e4.key === "down" ? 1 : -1, setAppState); - } else if (hasNonTeammateBackgroundTasks) { - options2?.onOpenBackgroundTasks?.(); - } - return; - } - if (e4.key === "f" && viewSelectionMode === "selecting-agent" && teammateCount > 0) { - e4.preventDefault(); - const selected = getSelectedTeammate(); - if (selected) { - enterTeammateView(selected.taskId, setAppState); - } - return; - } - if (e4.key === "return" && viewSelectionMode === "selecting-agent") { - e4.preventDefault(); - if (selectedIPAgentIndex === -1) { - exitTeammateView(setAppState); - } else if (selectedIPAgentIndex >= teammateCount) { - setAppState((prev) => ({ - ...prev, - expandedView: "none", - viewSelectionMode: "none", - selectedIPAgentIndex: -1 - })); - } else { - const selected = getSelectedTeammate(); - if (selected) { - enterTeammateView(selected.taskId, setAppState); - } - } - return; - } - if (e4.key === "k" && viewSelectionMode === "selecting-agent" && selectedIPAgentIndex >= 0) { - e4.preventDefault(); - const selected = getSelectedTeammate(); - if (selected && selected.task.status === "running") { - InProcessTeammateTask.kill(selected.taskId, setAppState); - } - return; - } - }; - use_input_default((_input, _key, event) => { - handleKeyDown(new KeyboardEvent(event.keypress)); - }); - return { handleKeyDown }; -} -var import_react274; -var init_useBackgroundTaskNavigation = __esm(() => { - init_keyboard_event(); - init_ink2(); - init_AppState(); - init_teammateViewHelpers(); - init_InProcessTeammateTask(); - import_react274 = __toESM(require_react(), 1); -}); - -// src/utils/swarm/reconnection.ts -function computeInitialTeamContext() { - const context7 = getDynamicTeamContext(); - if (!context7?.teamName || !context7?.agentName) { - logForDebugging("[Reconnection] computeInitialTeamContext: No teammate context set (not a teammate)"); - return; - } - const { teamName, agentId, agentName } = context7; - const teamFile = readTeamFile(teamName); - if (!teamFile) { - logError2(new Error(`[computeInitialTeamContext] Could not read team file for ${teamName}`)); - return; - } - const teamFilePath = getTeamFilePath(teamName); - const isLeader = !agentId; - logForDebugging(`[Reconnection] Computed initial team context for ${isLeader ? "leader" : `teammate ${agentName}`} in team ${teamName}`); - return { - teamName, - teamFilePath, - leadAgentId: teamFile.leadAgentId, - selfAgentId: agentId, - selfAgentName: agentName, - isLeader, - teammates: {} - }; -} -function initializeTeammateContextFromSession(setAppState, teamName, agentName) { - const teamFile = readTeamFile(teamName); - if (!teamFile) { - logError2(new Error(`[initializeTeammateContextFromSession] Could not read team file for ${teamName} (agent: ${agentName})`)); - return; - } - const member = teamFile.members.find((m4) => m4.name === agentName); - if (!member) { - logForDebugging(`[Reconnection] Member ${agentName} not found in team ${teamName} - may have been removed`); - } - const agentId = member?.agentId; - const teamFilePath = getTeamFilePath(teamName); - setAppState((prev) => ({ - ...prev, - teamContext: { - teamName, - teamFilePath, - leadAgentId: teamFile.leadAgentId, - selfAgentId: agentId, - selfAgentName: agentName, - isLeader: false, - teammates: {} - } - })); - logForDebugging(`[Reconnection] Initialized agent context from session for ${agentName} in team ${teamName}`); -} -var init_reconnection = __esm(() => { - init_debug(); - init_log2(); - init_teammate(); - init_teamHelpers(); -}); - -// src/utils/swarm/teammateInit.ts -function initializeTeammateHooks(setAppState, sessionId, teamInfo) { - const { teamName, agentId, agentName } = teamInfo; - const teamFile = readTeamFile(teamName); - if (!teamFile) { - logForDebugging(`[TeammateInit] Team file not found for team: ${teamName}`); - return; - } - const leadAgentId = teamFile.leadAgentId; - if (teamFile.teamAllowedPaths && teamFile.teamAllowedPaths.length > 0) { - logForDebugging(`[TeammateInit] Found ${teamFile.teamAllowedPaths.length} team-wide allowed path(s)`); - for (const allowedPath of teamFile.teamAllowedPaths) { - const ruleContent = allowedPath.path.startsWith("/") ? `/${allowedPath.path}/**` : `${allowedPath.path}/**`; - logForDebugging(`[TeammateInit] Applying team permission: ${allowedPath.toolName} allowed in ${allowedPath.path} (rule: ${ruleContent})`); - setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdate(prev.toolPermissionContext, { - type: "addRules", - rules: [ - { - toolName: allowedPath.toolName, - ruleContent - } - ], - behavior: "allow", - destination: "session" - }) - })); - } - } - const leadMember = teamFile.members.find((m4) => m4.agentId === leadAgentId); - const leadAgentName = leadMember?.name || "team-lead"; - if (agentId === leadAgentId) { - logForDebugging("[TeammateInit] This agent is the team leader - skipping idle notification hook"); - return; - } - logForDebugging(`[TeammateInit] Registering Stop hook for teammate ${agentName} to notify leader ${leadAgentName}`); - addFunctionHook(setAppState, sessionId, "Stop", "", async (messages, _signal) => { - setMemberActive(teamName, agentName, false); - const notification = createIdleNotification(agentName, { - idleReason: "available", - summary: getLastPeerDmSummary(messages) - }); - await writeToMailbox(leadAgentName, { - from: agentName, - text: jsonStringify(notification), - timestamp: new Date().toISOString(), - color: getTeammateColor() - }); - logForDebugging(`[TeammateInit] Sent idle notification to leader ${leadAgentName}`); - return true; - }, "Failed to send idle notification to team leader", { - timeout: 1e4 - }); -} -var init_teammateInit = __esm(() => { - init_debug(); - init_sessionHooks(); - init_PermissionUpdate(); - init_slowOperations(); - init_teammate(); - init_teammateMailbox(); - init_teamHelpers(); -}); - -// src/hooks/useSwarmInitialization.ts -function useSwarmInitialization(setAppState, initialMessages, { enabled: enabled2 = true } = {}) { - import_react275.useEffect(() => { - if (!enabled2) - return; - if (isAgentSwarmsEnabled()) { - const firstMessage = initialMessages?.[0]; - const teamName = firstMessage && "teamName" in firstMessage ? firstMessage.teamName : undefined; - const agentName = firstMessage && "agentName" in firstMessage ? firstMessage.agentName : undefined; - if (teamName && agentName) { - initializeTeammateContextFromSession(setAppState, teamName, agentName); - const teamFile = readTeamFile(teamName); - const member = teamFile?.members.find((m4) => m4.name === agentName); - if (member) { - initializeTeammateHooks(setAppState, getSessionId(), { - teamName, - agentId: member.agentId, - agentName - }); - } - } else { - const context7 = getDynamicTeamContext?.(); - if (context7?.teamName && context7?.agentId && context7?.agentName) { - initializeTeammateHooks(setAppState, getSessionId(), { - teamName: context7.teamName, - agentId: context7.agentId, - agentName: context7.agentName - }); - } - } - } - }, [setAppState, initialMessages, enabled2]); -} -var import_react275; -var init_useSwarmInitialization = __esm(() => { - init_state(); - init_agentSwarmsEnabled(); - init_reconnection(); - init_teamHelpers(); - init_teammateInit(); - init_teammate(); - import_react275 = __toESM(require_react(), 1); -}); - -// src/hooks/useTeammateViewAutoExit.ts -function useTeammateViewAutoExit() { - const setAppState = useSetAppState(); - const viewingAgentTaskId = useAppState((s4) => s4.viewingAgentTaskId); - const task = useAppState((s4) => s4.viewingAgentTaskId ? s4.tasks[s4.viewingAgentTaskId] : undefined); - const viewedTask = task && isInProcessTeammateTask(task) ? task : undefined; - const viewedStatus = viewedTask?.status; - const viewedError = viewedTask?.error; - const taskExists = task !== undefined; - import_react276.useEffect(() => { - if (!viewingAgentTaskId) { - return; - } - if (!taskExists) { - exitTeammateView(setAppState); - return; - } - if (!viewedTask) - return; - if (viewedStatus === "killed" || viewedStatus === "failed" || viewedError || viewedStatus !== "running" && viewedStatus !== "completed" && viewedStatus !== "pending") { - exitTeammateView(setAppState); - return; - } - }, [ - viewingAgentTaskId, - taskExists, - viewedTask, - viewedStatus, - viewedError, - setAppState - ]); -} -var import_react276; -var init_useTeammateViewAutoExit = __esm(() => { - init_AppState(); - init_teammateViewHelpers(); - import_react276 = __toESM(require_react(), 1); -}); - -// src/hooks/toolPermission/handlers/coordinatorHandler.ts -async function handleCoordinatorPermission(params) { - const { ctx, updatedInput, suggestions, permissionMode } = params; - try { - const hookResult = await ctx.runHooks(permissionMode, suggestions, updatedInput); - if (hookResult) - return hookResult; - const classifierResult = null; - if (classifierResult) { - return classifierResult; - } - } catch (error46) { - if (error46 instanceof Error) { - logError2(error46); - } else { - logError2(new Error(`Automated permission check failed: ${String(error46)}`)); - } - } - return null; -} -var init_coordinatorHandler = __esm(() => { - init_log2(); -}); - -// src/hooks/toolPermission/PermissionContext.ts -function createResolveOnce(resolve42) { - let claimed = false; - let delivered = false; - return { - resolve(value) { - if (delivered) - return; - delivered = true; - claimed = true; - resolve42(value); - }, - isResolved() { - return claimed; - }, - claim() { - if (claimed) - return false; - claimed = true; - return true; - } - }; -} -function createPermissionContext(tool, input, toolUseContext, assistantMessage, toolUseID, setToolPermissionContext, queueOps) { - const messageId = assistantMessage.message.id; - const ctx = { - tool, - input, - toolUseContext, - assistantMessage, - messageId, - toolUseID, - logDecision(args, opts) { - logPermissionDecision({ - tool, - input: opts?.input ?? input, - toolUseContext, - messageId, - toolUseID - }, args, opts?.permissionPromptStartTimeMs); - }, - logCancelled() { - logEvent("tengu_tool_use_cancelled", { - messageID: messageId, - toolName: sanitizeToolNameForAnalytics(tool.name) - }); - }, - async persistPermissions(updates) { - if (updates.length === 0) - return false; - persistPermissionUpdates(updates); - const appState = toolUseContext.getAppState(); - setToolPermissionContext(applyPermissionUpdates(appState.toolPermissionContext, updates)); - return updates.some((update) => supportsPersistence(update.destination)); - }, - resolveIfAborted(resolve42) { - if (!toolUseContext.abortController.signal.aborted) - return false; - this.logCancelled(); - resolve42(this.cancelAndAbort(undefined, true)); - return true; - }, - cancelAndAbort(feedback2, isAbort, contentBlocks) { - const sub = !!toolUseContext.agentId; - const baseMessage = feedback2 ? `${sub ? SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX : REJECT_MESSAGE_WITH_REASON_PREFIX}${feedback2}` : sub ? SUBAGENT_REJECT_MESSAGE : REJECT_MESSAGE; - const message = sub ? baseMessage : withMemoryCorrectionHint(baseMessage); - if (isAbort || !feedback2 && !contentBlocks?.length && !sub) { - logForDebugging(`Aborting: tool=${tool.name} isAbort=${isAbort} hasFeedback=${!!feedback2} isSubagent=${sub}`); - toolUseContext.abortController.abort(); - } - return { behavior: "ask", message, contentBlocks }; - }, - ...{}, - async runHooks(permissionMode, suggestions, updatedInput, permissionPromptStartTimeMs) { - for await (const hookResult of executePermissionRequestHooks(tool.name, toolUseID, input, toolUseContext, permissionMode, suggestions, toolUseContext.abortController.signal)) { - if (hookResult.permissionRequestResult) { - const decision = hookResult.permissionRequestResult; - if (decision.behavior === "allow") { - const finalInput = decision.updatedInput ?? updatedInput ?? input; - return await this.handleHookAllow(finalInput, decision.updatedPermissions ?? [], permissionPromptStartTimeMs); - } else if (decision.behavior === "deny") { - this.logDecision({ decision: "reject", source: { type: "hook" } }, { permissionPromptStartTimeMs }); - if (decision.interrupt) { - logForDebugging(`Hook interrupt: tool=${tool.name} hookMessage=${decision.message}`); - toolUseContext.abortController.abort(); - } - return this.buildDeny(decision.message || "Permission denied by hook", { - type: "hook", - hookName: "PermissionRequest", - reason: decision.message - }); - } - } - } - return null; - }, - buildAllow(updatedInput, opts) { - return { - behavior: "allow", - updatedInput, - userModified: opts?.userModified ?? false, - ...opts?.decisionReason && { decisionReason: opts.decisionReason }, - ...opts?.acceptFeedback && { acceptFeedback: opts.acceptFeedback }, - ...opts?.contentBlocks && opts.contentBlocks.length > 0 && { - contentBlocks: opts.contentBlocks - } - }; - }, - buildDeny(message, decisionReason) { - return { behavior: "deny", message, decisionReason }; - }, - async handleUserAllow(updatedInput, permissionUpdates, feedback2, permissionPromptStartTimeMs, contentBlocks, decisionReason) { - const acceptedPermanentUpdates = await this.persistPermissions(permissionUpdates); - this.logDecision({ - decision: "accept", - source: { type: "user", permanent: acceptedPermanentUpdates } - }, { input: updatedInput, permissionPromptStartTimeMs }); - const userModified = tool.inputsEquivalent ? !tool.inputsEquivalent(input, updatedInput) : false; - const trimmedFeedback = feedback2?.trim(); - return this.buildAllow(updatedInput, { - userModified, - decisionReason, - acceptFeedback: trimmedFeedback || undefined, - contentBlocks - }); - }, - async handleHookAllow(finalInput, permissionUpdates, permissionPromptStartTimeMs) { - const acceptedPermanentUpdates = await this.persistPermissions(permissionUpdates); - this.logDecision({ - decision: "accept", - source: { type: "hook", permanent: acceptedPermanentUpdates } - }, { input: finalInput, permissionPromptStartTimeMs }); - return this.buildAllow(finalInput, { - decisionReason: { type: "hook", hookName: "PermissionRequest" } - }); - }, - pushToQueue(item) { - queueOps?.push(item); - }, - removeFromQueue() { - queueOps?.remove(toolUseID); - }, - updateQueueItem(patch2) { - queueOps?.update(toolUseID, patch2); - } - }; - return Object.freeze(ctx); -} -function createPermissionQueueOps(setToolUseConfirmQueue) { - return { - push(item) { - setToolUseConfirmQueue((queue2) => [...queue2, item]); - }, - remove(toolUseID) { - setToolUseConfirmQueue((queue2) => queue2.filter((item) => item.toolUseID !== toolUseID)); - }, - update(toolUseID, patch2) { - setToolUseConfirmQueue((queue2) => queue2.map((item) => item.toolUseID === toolUseID ? { ...item, ...patch2 } : item)); - } - }; -} -var init_PermissionContext = __esm(() => { - init_analytics(); - init_metadata(); - init_bashPermissions(); - init_classifierApprovals(); - init_debug(); - init_hooks3(); - init_messages9(); - init_PermissionUpdate(); - init_permissionLogging(); -}); - -// src/hooks/toolPermission/handlers/interactiveHandler.ts -import { randomUUID as randomUUID42 } from "crypto"; -function handleInteractivePermission(params, resolve42) { - const { - ctx, - description, - result, - awaitAutomatedChecksBeforeDialog, - bridgeCallbacks, - channelCallbacks - } = params; - const { resolve: resolveOnce, isResolved, claim } = createResolveOnce(resolve42); - let userInteracted = false; - let checkmarkTransitionTimer; - let checkmarkAbortHandler; - const bridgeRequestId = bridgeCallbacks ? randomUUID42() : undefined; - let channelUnsubscribe; - const permissionPromptStartTimeMs = Date.now(); - const displayInput = result.updatedInput ?? ctx.input; - function clearClassifierIndicator() { - if (false) {} - } - ctx.pushToQueue({ - assistantMessage: ctx.assistantMessage, - tool: ctx.tool, - description, - input: displayInput, - toolUseContext: ctx.toolUseContext, - toolUseID: ctx.toolUseID, - permissionResult: result, - permissionPromptStartTimeMs, - ...{}, - onUserInteraction() { - const GRACE_PERIOD_MS = 200; - if (Date.now() - permissionPromptStartTimeMs < GRACE_PERIOD_MS) { - return; - } - userInteracted = true; - clearClassifierChecking(ctx.toolUseID); - clearClassifierIndicator(); - }, - onDismissCheckmark() { - if (checkmarkTransitionTimer) { - clearTimeout(checkmarkTransitionTimer); - checkmarkTransitionTimer = undefined; - if (checkmarkAbortHandler) { - ctx.toolUseContext.abortController.signal.removeEventListener("abort", checkmarkAbortHandler); - checkmarkAbortHandler = undefined; - } - ctx.removeFromQueue(); - } - }, - onAbort() { - if (!claim()) - return; - if (bridgeCallbacks && bridgeRequestId) { - bridgeCallbacks.sendResponse(bridgeRequestId, { - behavior: "deny", - message: "User aborted" - }); - bridgeCallbacks.cancelRequest(bridgeRequestId); - } - channelUnsubscribe?.(); - ctx.logCancelled(); - ctx.logDecision({ decision: "reject", source: { type: "user_abort" } }, { permissionPromptStartTimeMs }); - resolveOnce(ctx.cancelAndAbort(undefined, true)); - }, - async onAllow(updatedInput, permissionUpdates, feedback2, contentBlocks) { - if (!claim()) - return; - if (bridgeCallbacks && bridgeRequestId) { - bridgeCallbacks.sendResponse(bridgeRequestId, { - behavior: "allow", - updatedInput, - updatedPermissions: permissionUpdates - }); - bridgeCallbacks.cancelRequest(bridgeRequestId); - } - channelUnsubscribe?.(); - resolveOnce(await ctx.handleUserAllow(updatedInput, permissionUpdates, feedback2, permissionPromptStartTimeMs, contentBlocks, result.decisionReason)); - }, - onReject(feedback2, contentBlocks) { - if (!claim()) - return; - if (bridgeCallbacks && bridgeRequestId) { - bridgeCallbacks.sendResponse(bridgeRequestId, { - behavior: "deny", - message: feedback2 ?? "User denied permission" - }); - bridgeCallbacks.cancelRequest(bridgeRequestId); - } - channelUnsubscribe?.(); - ctx.logDecision({ - decision: "reject", - source: { type: "user_reject", hasFeedback: !!feedback2 } - }, { permissionPromptStartTimeMs }); - resolveOnce(ctx.cancelAndAbort(feedback2, undefined, contentBlocks)); - }, - async recheckPermission() { - if (isResolved()) - return; - const freshResult = await hasPermissionsToUseTool(ctx.tool, ctx.input, ctx.toolUseContext, ctx.assistantMessage, ctx.toolUseID); - if (freshResult.behavior === "allow") { - if (!claim()) - return; - if (bridgeCallbacks && bridgeRequestId) { - bridgeCallbacks.cancelRequest(bridgeRequestId); - } - channelUnsubscribe?.(); - ctx.removeFromQueue(); - ctx.logDecision({ decision: "accept", source: "config" }); - resolveOnce(ctx.buildAllow(freshResult.updatedInput ?? ctx.input)); - } - } - }); - if (bridgeCallbacks && bridgeRequestId) { - bridgeCallbacks.sendRequest(bridgeRequestId, ctx.tool.name, displayInput, ctx.toolUseID, description, result.suggestions, result.blockedPath); - const signal = ctx.toolUseContext.abortController.signal; - const unsubscribe2 = bridgeCallbacks.onResponse(bridgeRequestId, (response7) => { - if (!claim()) - return; - signal.removeEventListener("abort", unsubscribe2); - clearClassifierChecking(ctx.toolUseID); - clearClassifierIndicator(); - ctx.removeFromQueue(); - channelUnsubscribe?.(); - if (response7.behavior === "allow") { - if (response7.updatedPermissions?.length) { - ctx.persistPermissions(response7.updatedPermissions); - } - ctx.logDecision({ - decision: "accept", - source: { - type: "user", - permanent: !!response7.updatedPermissions?.length - } - }, { permissionPromptStartTimeMs }); - resolveOnce(ctx.buildAllow(response7.updatedInput ?? displayInput)); - } else { - ctx.logDecision({ - decision: "reject", - source: { - type: "user_reject", - hasFeedback: !!response7.message - } - }, { permissionPromptStartTimeMs }); - resolveOnce(ctx.cancelAndAbort(response7.message)); - } - }); - signal.addEventListener("abort", unsubscribe2, { once: true }); - } - if (false) {} - if (!awaitAutomatedChecksBeforeDialog) { - (async () => { - if (isResolved()) - return; - const currentAppState = ctx.toolUseContext.getAppState(); - const hookDecision = await ctx.runHooks(currentAppState.toolPermissionContext.mode, result.suggestions, result.updatedInput, permissionPromptStartTimeMs); - if (!hookDecision || !claim()) - return; - if (bridgeCallbacks && bridgeRequestId) { - bridgeCallbacks.cancelRequest(bridgeRequestId); - } - channelUnsubscribe?.(); - ctx.removeFromQueue(); - resolveOnce(hookDecision); - })(); - } - if (false) {} -} -var init_interactiveHandler = __esm(() => { - init_debug(); - init_state(); - init_terminal_focus_state(); - init_channelNotification(); - init_channelPermissions(); - init_bashPermissions(); - init_classifierApprovals(); - init_errors(); - init_permissions2(); - init_PermissionContext(); -}); - -// src/hooks/toolPermission/handlers/swarmWorkerHandler.ts -async function handleSwarmWorkerPermission(params) { - if (!isAgentSwarmsEnabled() || !isSwarmWorker()) { - return null; - } - const { ctx, description, updatedInput, suggestions } = params; - const classifierResult = null; - if (classifierResult) { - return classifierResult; - } - try { - const clearPendingRequest = () => ctx.toolUseContext.setAppState((prev) => ({ - ...prev, - pendingWorkerRequest: null - })); - const decision = await new Promise((resolve42) => { - const { resolve: resolveOnce, claim } = createResolveOnce(resolve42); - const request2 = createPermissionRequest({ - toolName: ctx.tool.name, - toolUseId: ctx.toolUseID, - input: ctx.input, - description, - permissionSuggestions: suggestions - }); - registerPermissionCallback({ - requestId: request2.id, - toolUseId: ctx.toolUseID, - async onAllow(allowedInput, permissionUpdates, feedback2, contentBlocks) { - if (!claim()) - return; - clearPendingRequest(); - const finalInput = allowedInput && Object.keys(allowedInput).length > 0 ? allowedInput : ctx.input; - resolveOnce(await ctx.handleUserAllow(finalInput, permissionUpdates, feedback2, undefined, contentBlocks)); - }, - onReject(feedback2, contentBlocks) { - if (!claim()) - return; - clearPendingRequest(); - ctx.logDecision({ - decision: "reject", - source: { type: "user_reject", hasFeedback: !!feedback2 } - }); - resolveOnce(ctx.cancelAndAbort(feedback2, undefined, contentBlocks)); - } - }); - sendPermissionRequestViaMailbox(request2); - ctx.toolUseContext.setAppState((prev) => ({ - ...prev, - pendingWorkerRequest: { - toolName: ctx.tool.name, - toolUseId: ctx.toolUseID, - description - } - })); - ctx.toolUseContext.abortController.signal.addEventListener("abort", () => { - if (!claim()) - return; - clearPendingRequest(); - ctx.logCancelled(); - resolveOnce(ctx.cancelAndAbort(undefined, true)); - }, { once: true }); - }); - return decision; - } catch (error46) { - logError2(toError(error46)); - return null; - } -} -var init_swarmWorkerHandler = __esm(() => { - init_agentSwarmsEnabled(); - init_errors(); - init_log2(); - init_permissionSync(); - init_useSwarmPermissionPoller(); - init_PermissionContext(); -}); - -// src/hooks/useCanUseTool.tsx -function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) { - const $2 = import_compiler_runtime340.c(3); - let t0; - if ($2[0] !== setToolPermissionContext || $2[1] !== setToolUseConfirmQueue) { - t0 = async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => new Promise((resolve42) => { - const ctx = createPermissionContext(tool, input, toolUseContext, assistantMessage, toolUseID, setToolPermissionContext, createPermissionQueueOps(setToolUseConfirmQueue)); - if (ctx.resolveIfAborted(resolve42)) { - return; - } - const decisionPromise = forceDecision !== undefined ? Promise.resolve(forceDecision) : hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseID); - return decisionPromise.then(async (result) => { - if (result.behavior === "allow") { - if (ctx.resolveIfAborted(resolve42)) { - return; - } - if (false) {} - ctx.logDecision({ - decision: "accept", - source: "config" - }); - resolve42(ctx.buildAllow(result.updatedInput ?? input, { - decisionReason: result.decisionReason - })); - return; - } - const appState = toolUseContext.getAppState(); - const description = await tool.description(input, { - isNonInteractiveSession: toolUseContext.options.isNonInteractiveSession, - toolPermissionContext: appState.toolPermissionContext, - tools: toolUseContext.options.tools - }); - if (ctx.resolveIfAborted(resolve42)) { - return; - } - switch (result.behavior) { - case "deny": { - logPermissionDecision({ - tool, - input, - toolUseContext, - messageId: ctx.messageId, - toolUseID - }, { - decision: "reject", - source: "config" - }); - if (false) {} - resolve42(result); - return; - } - case "ask": { - if (appState.toolPermissionContext.awaitAutomatedChecksBeforeDialog) { - const coordinatorDecision = await handleCoordinatorPermission({ - ctx, - ...{}, - updatedInput: result.updatedInput, - suggestions: result.suggestions, - permissionMode: appState.toolPermissionContext.mode - }); - if (coordinatorDecision) { - resolve42(coordinatorDecision); - return; - } - } - if (ctx.resolveIfAborted(resolve42)) { - return; - } - const swarmDecision = await handleSwarmWorkerPermission({ - ctx, - description, - ...{}, - updatedInput: result.updatedInput, - suggestions: result.suggestions - }); - if (swarmDecision) { - resolve42(swarmDecision); - return; - } - if (false) {} - handleInteractivePermission({ - ctx, - description, - result, - awaitAutomatedChecksBeforeDialog: appState.toolPermissionContext.awaitAutomatedChecksBeforeDialog, - bridgeCallbacks: undefined, - channelCallbacks: undefined - }, resolve42); - return; - } - } - }).catch((error46) => { - if (error46 instanceof AbortError || error46 instanceof APIUserAbortError) { - logForDebugging(`Permission check threw ${error46.constructor.name} for tool=${tool.name}: ${error46.message}`); - ctx.logCancelled(); - resolve42(ctx.cancelAndAbort(undefined, true)); - } else { - logError2(error46); - resolve42(ctx.cancelAndAbort(undefined, true)); - } - }).finally(() => { - clearClassifierChecking(toolUseID); - }); - }); - $2[0] = setToolPermissionContext; - $2[1] = setToolUseConfirmQueue; - $2[2] = t0; - } else { - t0 = $2[2]; - } - return t0; -} -var import_compiler_runtime340, jsx_dev_runtime439, useCanUseTool_default; -var init_useCanUseTool = __esm(() => { - init_sdk(); - init_ink2(); - init_bashPermissions(); - init_autoModeDenials(); - init_classifierApprovals(); - init_debug(); - init_errors(); - init_log2(); - init_permissions2(); - init_coordinatorHandler(); - init_interactiveHandler(); - init_swarmWorkerHandler(); - init_PermissionContext(); - init_permissionLogging(); - import_compiler_runtime340 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime439 = __toESM(require_jsx_dev_runtime(), 1); - useCanUseTool_default = useCanUseTool; -}); - -// src/utils/userPromptKeywords.ts -function matchesNegativeKeyword(input) { - const lowerInput = input.toLowerCase(); - const negativePattern = /\b(wtf|wth|ffs|omfg|shit(ty|tiest)?|dumbass|horrible|awful|piss(ed|ing)? off|piece of (shit|crap|junk)|what the (fuck|hell)|fucking? (broken|useless|terrible|awful|horrible)|fuck you|screw (this|you)|so frustrating|this sucks|damn it)\b/; - return negativePattern.test(lowerInput); -} -function matchesKeepGoingKeyword(input) { - const lowerInput = input.toLowerCase().trim(); - if (lowerInput === "continue") { - return true; - } - const keepGoingPattern = /\b(keep going|go on)\b/; - return keepGoingPattern.test(lowerInput); -} - -// src/utils/processUserInput/processTextPrompt.ts -import { randomUUID as randomUUID43 } from "crypto"; -function processTextPrompt(input, imageContentBlocks, imagePasteIds, attachmentMessages, uuid8, permissionMode, isMeta) { - const promptId = randomUUID43(); - setPromptId(promptId); - const userPromptText = typeof input === "string" ? input : input.find((block2) => block2.type === "text")?.text || ""; - startInteractionSpan(userPromptText); - const otelPromptText = typeof input === "string" ? input : input.findLast((block2) => block2.type === "text")?.text || ""; - if (otelPromptText) { - logOTelEvent("user_prompt", { - prompt_length: String(otelPromptText.length), - prompt: redactIfDisabled(otelPromptText), - "prompt.id": promptId - }); - } - const isNegative = matchesNegativeKeyword(userPromptText); - const isKeepGoing = matchesKeepGoingKeyword(userPromptText); - logEvent("tengu_input_prompt", { - is_negative: isNegative, - is_keep_going: isKeepGoing - }); - if (imageContentBlocks.length > 0) { - const textContent = typeof input === "string" ? input.trim() ? [{ type: "text", text: input }] : [] : input; - const userMessage2 = createUserMessage({ - content: [...textContent, ...imageContentBlocks], - uuid: uuid8, - imagePasteIds: imagePasteIds.length > 0 ? imagePasteIds : undefined, - permissionMode, - isMeta: isMeta || undefined - }); - return { - messages: [userMessage2, ...attachmentMessages], - shouldQuery: true - }; - } - const userMessage = createUserMessage({ - content: input, - uuid: uuid8, - permissionMode, - isMeta: isMeta || undefined - }); - return { - messages: [userMessage, ...attachmentMessages], - shouldQuery: true - }; -} -var init_processTextPrompt = __esm(() => { - init_state(); - init_analytics(); - init_messages9(); - init_events(); - init_sessionTracing(); -}); - -// src/components/BashModeProgress.tsx -function BashModeProgress(t0) { - const $2 = import_compiler_runtime341.c(8); - const { - input, - progress, - verbose - } = t0; - const t1 = `${input}`; - let t22; - if ($2[0] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime440.jsxDEV(UserBashInputMessage, { - addMargin: false, - param: { - text: t1, - type: "text" - } - }, undefined, false, undefined, this); - $2[0] = t1; - $2[1] = t22; - } else { - t22 = $2[1]; - } - let t32; - if ($2[2] !== progress || $2[3] !== verbose) { - t32 = progress ? /* @__PURE__ */ jsx_dev_runtime440.jsxDEV(ShellProgressMessage, { - fullOutput: progress.fullOutput, - output: progress.output, - elapsedTimeSeconds: progress.elapsedTimeSeconds, - totalLines: progress.totalLines, - verbose - }, undefined, false, undefined, this) : BashTool.renderToolUseProgressMessage?.([], { - verbose, - tools: [], - terminalSize: undefined - }); - $2[2] = progress; - $2[3] = verbose; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] !== t22 || $2[6] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime440.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t22, - t32 - ] - }, undefined, true, undefined, this); - $2[5] = t22; - $2[6] = t32; - $2[7] = t4; - } else { - t4 = $2[7]; - } - return t4; -} -var import_compiler_runtime341, jsx_dev_runtime440; -var init_BashModeProgress = __esm(() => { - init_ink2(); - init_BashTool(); - init_UserBashInputMessage(); - init_ShellProgressMessage(); - import_compiler_runtime341 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime440 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/shell/resolveDefaultShell.ts -function resolveDefaultShell() { - return getInitialSettings().defaultShell ?? "bash"; -} -var init_resolveDefaultShell = __esm(() => { - init_settings2(); -}); - -// src/utils/processUserInput/processBashCommand.tsx -var exports_processBashCommand = {}; -__export(exports_processBashCommand, { - processBashCommand: () => processBashCommand -}); -import { randomUUID as randomUUID44 } from "crypto"; -async function processBashCommand(inputString, precedingInputBlocks, attachmentMessages, context7, setToolJSX) { - const usePowerShell = isPowerShellToolEnabled() && resolveDefaultShell() === "powershell"; - logEvent("tengu_input_bash", { - powershell: usePowerShell - }); - const userMessage = createUserMessage({ - content: prepareUserContent({ - inputString: `${inputString}`, - precedingInputBlocks - }) - }); - let jsx; - setToolJSX({ - jsx: /* @__PURE__ */ jsx_dev_runtime441.jsxDEV(BashModeProgress, { - input: inputString, - progress: null, - verbose: context7.options.verbose - }, undefined, false, undefined, this), - shouldHidePromptInput: false - }); - try { - const bashModeContext = { - ...context7, - setToolJSX: (_) => { - jsx = _?.jsx; - } - }; - const onProgress = (progress) => { - setToolJSX({ - jsx: /* @__PURE__ */ jsx_dev_runtime441.jsxDEV(jsx_dev_runtime441.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime441.jsxDEV(BashModeProgress, { - input: inputString, - progress: progress.data, - verbose: context7.options.verbose - }, undefined, false, undefined, this), - jsx - ] - }, undefined, true, undefined, this), - shouldHidePromptInput: false, - showSpinner: false - }); - }; - let PowerShellTool2 = null; - if (usePowerShell) { - PowerShellTool2 = (init_PowerShellTool(), __toCommonJS(exports_PowerShellTool)).PowerShellTool; - } - const shellTool = PowerShellTool2 ?? BashTool; - const response7 = PowerShellTool2 ? await PowerShellTool2.call({ - command: inputString, - dangerouslyDisableSandbox: true - }, bashModeContext, undefined, undefined, onProgress) : await BashTool.call({ - command: inputString, - dangerouslyDisableSandbox: true - }, bashModeContext, undefined, undefined, onProgress); - const data = response7.data; - if (!data) { - throw new Error("No result received from shell command"); - } - const stderr = data.stderr; - const mapped = await processToolResultBlock(shellTool, { - ...data, - stderr: "" - }, randomUUID44()); - const stdout = typeof mapped.content === "string" ? mapped.content : escapeXml(data.stdout); - return { - messages: [createSyntheticUserCaveatMessage(), userMessage, ...attachmentMessages, createUserMessage({ - content: `${stdout}${escapeXml(stderr)}` - })], - shouldQuery: false - }; - } catch (e4) { - if (e4 instanceof ShellError) { - if (e4.interrupted) { - return { - messages: [createSyntheticUserCaveatMessage(), userMessage, createUserInterruptionMessage({ - toolUse: false - }), ...attachmentMessages], - shouldQuery: false - }; - } - return { - messages: [createSyntheticUserCaveatMessage(), userMessage, ...attachmentMessages, createUserMessage({ - content: `${escapeXml(e4.stdout)}${escapeXml(e4.stderr)}` - })], - shouldQuery: false - }; - } - return { - messages: [createSyntheticUserCaveatMessage(), userMessage, ...attachmentMessages, createUserMessage({ - content: `Command failed: ${escapeXml(errorMessage(e4))}` - })], - shouldQuery: false - }; - } finally { - setToolJSX(null); - } -} -var jsx_dev_runtime441; -var init_processBashCommand = __esm(() => { - init_BashModeProgress(); - init_BashTool(); - init_analytics(); - init_errors(); - init_messages9(); - init_resolveDefaultShell(); - init_shellToolUtils(); - init_toolResultStorage(); - jsx_dev_runtime441 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/processUserInput/processUserInput.ts -import { randomUUID as randomUUID45 } from "crypto"; -async function processUserInput({ - input, - preExpansionInput, - mode, - setToolJSX, - context: context7, - pastedContents, - ideSelection, - messages, - setUserInputOnProcessing, - uuid: uuid8, - isAlreadyProcessing, - querySource, - canUseTool, - skipSlashCommands, - bridgeOrigin, - isMeta, - skipAttachments -}) { - const inputString = typeof input === "string" ? input : null; - if (mode === "prompt" && inputString !== null && !isMeta) { - setUserInputOnProcessing?.(inputString); - } - queryCheckpoint("query_process_user_input_base_start"); - const appState = context7.getAppState(); - const result = await processUserInputBase(input, mode, setToolJSX, context7, pastedContents, ideSelection, messages, uuid8, isAlreadyProcessing, querySource, canUseTool, appState.toolPermissionContext.mode, skipSlashCommands, bridgeOrigin, isMeta, skipAttachments, preExpansionInput); - queryCheckpoint("query_process_user_input_base_end"); - if (!result.shouldQuery) { - return result; - } - queryCheckpoint("query_hooks_start"); - const inputMessage = getContentText(input) || ""; - for await (const hookResult of executeUserPromptSubmitHooks(inputMessage, appState.toolPermissionContext.mode, context7, context7.requestPrompt)) { - if (hookResult.message?.type === "progress") { - continue; - } - if (hookResult.blockingError) { - const blockingMessage = getUserPromptSubmitHookBlockingMessage(hookResult.blockingError); - return { - messages: [ - createSystemMessage(`${blockingMessage} - -Original prompt: ${input}`, "warning") - ], - shouldQuery: false, - allowedTools: result.allowedTools - }; - } - if (hookResult.preventContinuation) { - const message = hookResult.stopReason ? `Operation stopped by hook: ${hookResult.stopReason}` : "Operation stopped by hook"; - result.messages.push(createUserMessage({ - content: message - })); - result.shouldQuery = false; - return result; - } - if (hookResult.additionalContexts && hookResult.additionalContexts.length > 0) { - result.messages.push(createAttachmentMessage({ - type: "hook_additional_context", - content: hookResult.additionalContexts.map(applyTruncation), - hookName: "UserPromptSubmit", - toolUseID: `hook-${randomUUID45()}`, - hookEvent: "UserPromptSubmit" - })); - } - if (hookResult.message) { - switch (hookResult.message.attachment.type) { - case "hook_success": - if (!hookResult.message.attachment.content) { - break; - } - result.messages.push({ - ...hookResult.message, - attachment: { - ...hookResult.message.attachment, - content: applyTruncation(hookResult.message.attachment.content) - } - }); - break; - default: - result.messages.push(hookResult.message); - break; - } - } - } - queryCheckpoint("query_hooks_end"); - return result; -} -function applyTruncation(content) { - if (content.length > MAX_HOOK_OUTPUT_LENGTH) { - return `${content.substring(0, MAX_HOOK_OUTPUT_LENGTH)}\u2026 [output truncated - exceeded ${MAX_HOOK_OUTPUT_LENGTH} characters]`; - } - return content; -} -async function processUserInputBase(input, mode, setToolJSX, context7, pastedContents, ideSelection, messages, uuid8, isAlreadyProcessing, querySource, canUseTool, permissionMode, skipSlashCommands, bridgeOrigin, isMeta, skipAttachments, preExpansionInput) { - let inputString = null; - let precedingInputBlocks = []; - const imageMetadataTexts = []; - let normalizedInput = input; - if (typeof input === "string") { - inputString = input; - } else if (input.length > 0) { - queryCheckpoint("query_image_processing_start"); - const processedBlocks = []; - for (const block2 of input) { - if (block2.type === "image") { - const resized = await maybeResizeAndDownsampleImageBlock(block2); - if (resized.dimensions) { - const metadataText = createImageMetadataText(resized.dimensions); - if (metadataText) { - imageMetadataTexts.push(metadataText); - } - } - processedBlocks.push(resized.block); - } else { - processedBlocks.push(block2); - } - } - normalizedInput = processedBlocks; - queryCheckpoint("query_image_processing_end"); - const lastBlock = processedBlocks[processedBlocks.length - 1]; - if (lastBlock?.type === "text") { - inputString = lastBlock.text; - precedingInputBlocks = processedBlocks.slice(0, -1); - } else { - precedingInputBlocks = processedBlocks; - } - } - if (inputString === null && mode !== "prompt") { - throw new Error(`Mode: ${mode} requires a string input.`); - } - const imageContents = pastedContents ? Object.values(pastedContents).filter(isValidImagePaste) : []; - const imagePasteIds = imageContents.map((img) => img.id); - const storedImagePaths2 = pastedContents ? await storeImages(pastedContents) : new Map; - queryCheckpoint("query_pasted_image_processing_start"); - const imageProcessingResults = await Promise.all(imageContents.map(async (pastedImage) => { - const imageBlock = { - type: "image", - source: { - type: "base64", - media_type: pastedImage.mediaType || "image/png", - data: pastedImage.content - } - }; - logEvent("tengu_pasted_image_resize_attempt", { - original_size_bytes: pastedImage.content.length - }); - const resized = await maybeResizeAndDownsampleImageBlock(imageBlock); - return { - resized, - originalDimensions: pastedImage.dimensions, - sourcePath: pastedImage.sourcePath ?? storedImagePaths2.get(pastedImage.id) - }; - })); - const imageContentBlocks = []; - for (const { - resized, - originalDimensions, - sourcePath - } of imageProcessingResults) { - if (resized.dimensions) { - const metadataText = createImageMetadataText(resized.dimensions, sourcePath); - if (metadataText) { - imageMetadataTexts.push(metadataText); - } - } else if (originalDimensions) { - const metadataText = createImageMetadataText(originalDimensions, sourcePath); - if (metadataText) { - imageMetadataTexts.push(metadataText); - } - } else if (sourcePath) { - imageMetadataTexts.push(`[Image source: ${sourcePath}]`); - } - imageContentBlocks.push(resized.block); - } - queryCheckpoint("query_pasted_image_processing_end"); - let effectiveSkipSlash = skipSlashCommands; - if (bridgeOrigin && inputString !== null && inputString.startsWith("/")) { - const parsed = parseSlashCommand(inputString); - const cmd = parsed ? findCommand(parsed.commandName, context7.options.commands) : undefined; - if (cmd) { - if (isBridgeSafeCommand(cmd)) { - effectiveSkipSlash = false; - } else { - const msg = `/${getCommandName(cmd)} isn't available over Remote Control.`; - return { - messages: [ - createUserMessage({ content: inputString, uuid: uuid8 }), - createCommandInputMessage(`${msg}`) - ], - shouldQuery: false, - resultText: msg - }; - } - } - } - if (false) {} - const shouldExtractAttachments = !skipAttachments && inputString !== null && (mode !== "prompt" || effectiveSkipSlash || !inputString.startsWith("/")); - queryCheckpoint("query_attachment_loading_start"); - const attachmentMessages = shouldExtractAttachments ? await toArray2(getAttachmentMessages(inputString, context7, ideSelection ?? null, [], messages, querySource)) : []; - queryCheckpoint("query_attachment_loading_end"); - if (inputString !== null && mode === "bash") { - const { processBashCommand: processBashCommand2 } = await Promise.resolve().then(() => (init_processBashCommand(), exports_processBashCommand)); - return addImageMetadataMessage(await processBashCommand2(inputString, precedingInputBlocks, attachmentMessages, context7, setToolJSX), imageMetadataTexts); - } - if (inputString !== null && !effectiveSkipSlash && inputString.startsWith("/")) { - const { processSlashCommand: processSlashCommand2 } = await Promise.resolve().then(() => (init_processSlashCommand(), exports_processSlashCommand)); - const slashResult = await processSlashCommand2(inputString, precedingInputBlocks, imageContentBlocks, attachmentMessages, context7, setToolJSX, uuid8, isAlreadyProcessing, canUseTool); - return addImageMetadataMessage(slashResult, imageMetadataTexts); - } - if (inputString !== null && mode === "prompt") { - const trimmedInput = inputString.trim(); - const agentMention = attachmentMessages.find((m4) => m4.attachment.type === "agent_mention"); - if (agentMention) { - const agentMentionString = `@agent-${agentMention.attachment.agentType}`; - const isSubagentOnly = trimmedInput === agentMentionString; - const isPrefix = trimmedInput.startsWith(agentMentionString) && !isSubagentOnly; - logEvent("tengu_subagent_at_mention", { - is_subagent_only: isSubagentOnly, - is_prefix: isPrefix - }); - } - } - return addImageMetadataMessage(processTextPrompt(normalizedInput, imageContentBlocks, imagePasteIds, attachmentMessages, uuid8, permissionMode, isMeta), imageMetadataTexts); -} -function addImageMetadataMessage(result, imageMetadataTexts) { - if (imageMetadataTexts.length > 0) { - result.messages.push(createUserMessage({ - content: imageMetadataTexts.map((text) => ({ type: "text", text })), - isMeta: true - })); - } - return result; -} -var MAX_HOOK_OUTPUT_LENGTH = 1e4; -var init_processUserInput = __esm(() => { - init_analytics(); - init_messages9(); - init_commands5(); - init_attachments(); - init_generators(); - init_hooks3(); - init_imageResizer(); - init_imageStore(); - init_messages9(); - init_queryProfiler(); - init_keyword(); - init_processTextPrompt(); -}); - -// src/utils/handlePromptSubmit.ts -function exit2() { - gracefulShutdownSync(0); -} -async function handlePromptSubmit(params) { - const { - helpers: helpers3, - queryGuard, - isExternalLoading = false, - commands: commands7, - onInputChange, - setPastedContents, - setToolJSX, - getToolUseContext, - messages, - mainLoopModel, - ideSelection, - setUserInputOnProcessing, - setAbortController, - onQuery, - setAppState, - onBeforeQuery, - canUseTool, - queuedCommands, - uuid: uuid8, - skipSlashCommands - } = params; - const { setCursorOffset, clearBuffer, resetHistory } = helpers3; - if (queuedCommands?.length) { - startQueryProfile(); - await executeUserInput({ - queuedCommands, - messages, - mainLoopModel, - ideSelection, - querySource: params.querySource, - commands: commands7, - queryGuard, - setToolJSX, - getToolUseContext, - setUserInputOnProcessing, - setAbortController, - onQuery, - setAppState, - onBeforeQuery, - resetHistory, - canUseTool, - onInputChange - }); - return; - } - const input = params.input ?? ""; - const mode = params.mode ?? "prompt"; - const rawPastedContents = params.pastedContents ?? {}; - const referencedIds = new Set(parseReferences(input).map((r4) => r4.id)); - const pastedContents = Object.fromEntries(Object.entries(rawPastedContents).filter(([, c9]) => c9.type !== "image" || referencedIds.has(c9.id))); - const hasImages = Object.values(pastedContents).some(isValidImagePaste); - if (input.trim() === "") { - return; - } - if (!skipSlashCommands && ["exit", "quit", ":q", ":q!", ":wq", ":wq!"].includes(input.trim())) { - const exitCommand = commands7.find((cmd2) => cmd2.name === "exit"); - if (exitCommand) { - handlePromptSubmit({ - ...params, - input: "/exit" - }); - } else { - exit2(); - } - return; - } - const finalInput = expandPastedTextRefs(input, pastedContents); - const pastedTextRefs = parseReferences(input).filter((r4) => pastedContents[r4.id]?.type === "text"); - const pastedTextCount = pastedTextRefs.length; - const pastedTextBytes = pastedTextRefs.reduce((sum, r4) => sum + (pastedContents[r4.id]?.content.length ?? 0), 0); - logEvent("tengu_paste_text", { pastedTextCount, pastedTextBytes }); - if (!skipSlashCommands && finalInput.trim().startsWith("/")) { - const trimmedInput = finalInput.trim(); - const spaceIndex = trimmedInput.indexOf(" "); - const commandName = spaceIndex === -1 ? trimmedInput.slice(1) : trimmedInput.slice(1, spaceIndex); - const commandArgs = spaceIndex === -1 ? "" : trimmedInput.slice(spaceIndex + 1).trim(); - const immediateCommand = commands7.find((cmd2) => cmd2.immediate && isCommandEnabled(cmd2) && (cmd2.name === commandName || cmd2.aliases?.includes(commandName) || getCommandName(cmd2) === commandName)); - if (immediateCommand && immediateCommand.type === "local-jsx" && (queryGuard.isActive || isExternalLoading)) { - logEvent("tengu_immediate_command_executed", { - commandName: immediateCommand.name - }); - onInputChange(""); - setCursorOffset(0); - setPastedContents({}); - clearBuffer(); - const context7 = getToolUseContext(messages, [], createAbortController(), mainLoopModel); - let doneWasCalled = false; - const onDone = (result, options2) => { - doneWasCalled = true; - setToolJSX({ - jsx: null, - shouldHidePromptInput: false, - clearLocalJSX: true - }); - if (result && options2?.display !== "skip" && params.addNotification) { - params.addNotification({ - key: `immediate-${immediateCommand.name}`, - text: result, - priority: "immediate" - }); - } - if (options2?.nextInput) { - if (options2.submitNextInput) { - enqueue({ value: options2.nextInput, mode: "prompt" }); - } else { - onInputChange(options2.nextInput); - } - } - }; - const impl = await immediateCommand.load(); - const jsx = await impl.call(onDone, context7, commandArgs); - if (jsx && !doneWasCalled) { - setToolJSX({ - jsx, - shouldHidePromptInput: false, - isLocalJSXCommand: true, - isImmediate: true - }); - } - return; - } - } - if (queryGuard.isActive || isExternalLoading) { - if (mode !== "prompt" && mode !== "bash") { - return; - } - if (params.hasInterruptibleToolInProgress) { - logForDebugging(`[interrupt] Aborting current turn: streamMode=${params.streamMode}`); - logEvent("tengu_cancel", { - source: "interrupt_on_submit", - streamMode: params.streamMode - }); - params.abortController?.abort("interrupt"); - } - enqueue({ - value: finalInput.trim(), - preExpansionValue: input.trim(), - mode, - pastedContents: hasImages ? pastedContents : undefined, - skipSlashCommands, - uuid: uuid8 - }); - onInputChange(""); - setCursorOffset(0); - setPastedContents({}); - resetHistory(); - clearBuffer(); - return; - } - startQueryProfile(); - const cmd = { - value: finalInput, - preExpansionValue: input, - mode, - pastedContents: hasImages ? pastedContents : undefined, - skipSlashCommands, - uuid: uuid8 - }; - await executeUserInput({ - queuedCommands: [cmd], - messages, - mainLoopModel, - ideSelection, - querySource: params.querySource, - commands: commands7, - queryGuard, - setToolJSX, - getToolUseContext, - setUserInputOnProcessing, - setAbortController, - onQuery, - setAppState, - onBeforeQuery, - resetHistory, - canUseTool, - onInputChange - }); -} -async function executeUserInput(params) { - const { - messages, - mainLoopModel, - ideSelection, - querySource, - queryGuard, - setToolJSX, - getToolUseContext, - setUserInputOnProcessing, - setAbortController, - onQuery, - setAppState, - onBeforeQuery, - resetHistory, - canUseTool, - queuedCommands - } = params; - const abortController = createAbortController(); - setAbortController(abortController); - function makeContext() { - return getToolUseContext(messages, [], abortController, mainLoopModel); - } - try { - queryGuard.reserve(); - queryCheckpoint("query_process_user_input_start"); - const newMessages = []; - let shouldQuery = false; - let allowedTools; - let model; - let effort; - let nextInput; - let submitNextInput; - const commands7 = queuedCommands ?? []; - const firstWorkload = commands7[0]?.workload; - const turnWorkload = firstWorkload !== undefined && commands7.every((c9) => c9.workload === firstWorkload) ? firstWorkload : undefined; - await runWithWorkload(turnWorkload, async () => { - for (let i6 = 0;i6 < commands7.length; i6++) { - const cmd = commands7[i6]; - const isFirst = i6 === 0; - const result = await processUserInput({ - input: cmd.value, - preExpansionInput: cmd.preExpansionValue, - mode: cmd.mode, - setToolJSX, - context: makeContext(), - pastedContents: isFirst ? cmd.pastedContents : undefined, - messages, - setUserInputOnProcessing: isFirst ? setUserInputOnProcessing : undefined, - isAlreadyProcessing: !isFirst, - querySource, - canUseTool, - uuid: cmd.uuid, - ideSelection: isFirst ? ideSelection : undefined, - skipSlashCommands: cmd.skipSlashCommands, - bridgeOrigin: cmd.bridgeOrigin, - isMeta: cmd.isMeta, - skipAttachments: !isFirst - }); - const origin2 = cmd.origin ?? (cmd.mode === "task-notification" ? { kind: "task-notification" } : undefined); - if (origin2) { - for (const m4 of result.messages) { - if (m4.type === "user") - m4.origin = origin2; - } - } - newMessages.push(...result.messages); - if (isFirst) { - shouldQuery = result.shouldQuery; - allowedTools = result.allowedTools; - model = result.model; - effort = result.effort; - nextInput = result.nextInput; - submitNextInput = result.submitNextInput; - } - } - queryCheckpoint("query_process_user_input_end"); - if (fileHistoryEnabled()) { - queryCheckpoint("query_file_history_snapshot_start"); - newMessages.filter(selectableUserMessagesFilter).forEach((message) => { - fileHistoryMakeSnapshot((updater) => { - setAppState((prev) => ({ - ...prev, - fileHistory: updater(prev.fileHistory) - })); - }, message.uuid); - }); - queryCheckpoint("query_file_history_snapshot_end"); - } - if (newMessages.length) { - resetHistory(); - setToolJSX({ - jsx: null, - shouldHidePromptInput: false, - clearLocalJSX: true - }); - const primaryCmd = commands7[0]; - const primaryMode = primaryCmd?.mode ?? "prompt"; - const primaryInput = primaryCmd && typeof primaryCmd.value === "string" ? primaryCmd.value : undefined; - const shouldCallBeforeQuery = primaryMode === "prompt"; - await onQuery(newMessages, abortController, shouldQuery, allowedTools ?? [], model ? resolveSkillModelOverride(model, mainLoopModel) : mainLoopModel, shouldCallBeforeQuery ? onBeforeQuery : undefined, primaryInput, effort); - } else { - queryGuard.cancelReservation(); - setToolJSX({ - jsx: null, - shouldHidePromptInput: false, - clearLocalJSX: true - }); - resetHistory(); - setAbortController(null); - } - if (nextInput) { - if (submitNextInput) { - enqueue({ value: nextInput, mode: "prompt" }); - } else { - params.onInputChange(nextInput); - } - } - }); - } finally { - queryGuard.cancelReservation(); - setUserInputOnProcessing(undefined); - } -} -var init_handlePromptSubmit = __esm(() => { - init_analytics(); - init_commands5(); - init_MessageSelector(); - init_history(); - init_abortController(); - init_debug(); - init_fileHistory(); - init_gracefulShutdown(); - init_messageQueueManager(); - init_model(); - init_processUserInput(); - init_queryProfiler(); - init_workloadContext(); -}); - -// src/utils/queueProcessor.ts -function isSlashCommand2(cmd) { - if (typeof cmd.value === "string") { - return cmd.value.trim().startsWith("/"); - } - for (const block2 of cmd.value) { - if (block2.type === "text") { - return block2.text.trim().startsWith("/"); - } - } - return false; -} -function processQueueIfReady({ - executeInput -}) { - const isMainThread = (cmd) => cmd.agentId === undefined; - const next2 = peek(isMainThread); - if (!next2) { - return { processed: false }; - } - if (isSlashCommand2(next2) || next2.mode === "bash") { - const cmd = dequeue(isMainThread); - executeInput([cmd]); - return { processed: true }; - } - const targetMode = next2.mode; - const commands7 = dequeueAllMatching((cmd) => isMainThread(cmd) && !isSlashCommand2(cmd) && cmd.mode === targetMode); - if (commands7.length === 0) { - return { processed: false }; - } - executeInput(commands7); - return { processed: true }; -} -var init_queueProcessor = __esm(() => { - init_messageQueueManager(); -}); - -// src/hooks/useQueueProcessor.ts -function useQueueProcessor({ - executeQueuedInput, - hasActiveLocalJsxUI, - queryGuard -}) { - const isQueryActive = import_react277.useSyncExternalStore(queryGuard.subscribe, queryGuard.getSnapshot); - const queueSnapshot = import_react277.useSyncExternalStore(subscribeToCommandQueue, getCommandQueueSnapshot); - import_react277.useEffect(() => { - if (isQueryActive) - return; - if (hasActiveLocalJsxUI) - return; - if (queueSnapshot.length === 0) - return; - processQueueIfReady({ executeInput: executeQueuedInput }); - }, [ - queueSnapshot, - isQueryActive, - executeQueuedInput, - hasActiveLocalJsxUI, - queryGuard - ]); -} -var import_react277; -var init_useQueueProcessor = __esm(() => { - init_messageQueueManager(); - init_queueProcessor(); - import_react277 = __toESM(require_react(), 1); -}); - -// src/hooks/useMailboxBridge.ts -function useMailboxBridge({ isLoading, onSubmitMessage }) { - const mailbox = useMailbox(); - const subscribe3 = import_react278.useMemo(() => mailbox.subscribe.bind(mailbox), [mailbox]); - const getSnapshot = import_react278.useCallback(() => mailbox.revision, [mailbox]); - const revision = import_react278.useSyncExternalStore(subscribe3, getSnapshot); - import_react278.useEffect(() => { - if (isLoading) - return; - const msg = mailbox.poll(); - if (msg) - onSubmitMessage(msg.content); - }, [isLoading, revision, mailbox, onSubmitMessage]); -} -var import_react278; -var init_useMailboxBridge = __esm(() => { - init_mailbox2(); - import_react278 = __toESM(require_react(), 1); -}); - -// src/hooks/useMergedClients.ts -function mergeClients(initialClients, mcpClients) { - if (initialClients && mcpClients && mcpClients.length > 0) { - return uniqBy_default([...initialClients, ...mcpClients], "name"); - } - return initialClients || []; -} -function useMergedClients(initialClients, mcpClients) { - return import_react279.useMemo(() => mergeClients(initialClients, mcpClients), [initialClients, mcpClients]); -} -var import_react279; -var init_useMergedClients = __esm(() => { - init_uniqBy(); - import_react279 = __toESM(require_react(), 1); -}); - -// src/hooks/useMergedCommands.ts -function useMergedCommands(initialCommands, mcpCommands) { - return import_react280.useMemo(() => { - if (mcpCommands.length > 0) { - return uniqBy_default([...initialCommands, ...mcpCommands], "name"); - } - return initialCommands; - }, [initialCommands, mcpCommands]); -} -var import_react280; -var init_useMergedCommands = __esm(() => { - init_uniqBy(); - import_react280 = __toESM(require_react(), 1); -}); - -// src/utils/skills/skillChangeDetector.ts -import * as platformPath2 from "path"; -async function initialize3() { - if (initialized4 || disposed3) - return; - initialized4 = true; - if (!dynamicSkillsCallbackRegistered) { - dynamicSkillsCallbackRegistered = true; - onDynamicSkillsLoaded(() => { - clearCommandMemoizationCaches(); - skillsChanged.emit(); - }); - } - const paths2 = await getWatchablePaths(); - if (paths2.length === 0) - return; - logForDebugging(`Watching for changes in skill/command directories: ${paths2.join(", ")}...`); - watcher4 = esm_default5.watch(paths2, { - persistent: true, - ignoreInitial: true, - depth: 2, - awaitWriteFinish: { - stabilityThreshold: testOverrides2?.stabilityThreshold ?? FILE_STABILITY_THRESHOLD_MS3, - pollInterval: testOverrides2?.pollInterval ?? FILE_STABILITY_POLL_INTERVAL_MS3 - }, - ignored: (path27, stats2) => { - if (stats2 && !stats2.isFile() && !stats2.isDirectory()) - return true; - return path27.split(platformPath2.sep).some((dir) => dir === ".git"); - }, - ignorePermissionErrors: true, - usePolling: USE_POLLING, - interval: testOverrides2?.chokidarInterval ?? POLLING_INTERVAL_MS3, - atomic: true - }); - watcher4.on("add", handleChange4); - watcher4.on("change", handleChange4); - watcher4.on("unlink", handleChange4); - unregisterCleanup = registerCleanup(async () => { - await dispose3(); - }); -} -function dispose3() { - disposed3 = true; - if (unregisterCleanup) { - unregisterCleanup(); - unregisterCleanup = null; - } - let closePromise = Promise.resolve(); - if (watcher4) { - closePromise = watcher4.close(); - watcher4 = null; - } - if (reloadTimer) { - clearTimeout(reloadTimer); - reloadTimer = null; - } - pendingChangedPaths.clear(); - skillsChanged.clear(); - return closePromise; -} -async function getWatchablePaths() { - const fs14 = getFsImplementation(); - const paths2 = []; - const userSkillsPath = getSkillsPath("userSettings", "skills"); - if (userSkillsPath) { - try { - await fs14.stat(userSkillsPath); - paths2.push(userSkillsPath); - } catch {} - } - const userCommandsPath = getSkillsPath("userSettings", "commands"); - if (userCommandsPath) { - try { - await fs14.stat(userCommandsPath); - paths2.push(userCommandsPath); - } catch {} - } - const projectSkillsPath = getSkillsPath("projectSettings", "skills"); - if (projectSkillsPath) { - try { - const absolutePath = platformPath2.resolve(projectSkillsPath); - await fs14.stat(absolutePath); - paths2.push(absolutePath); - } catch {} - } - const projectCommandsPath = getSkillsPath("projectSettings", "commands"); - if (projectCommandsPath) { - try { - const absolutePath = platformPath2.resolve(projectCommandsPath); - await fs14.stat(absolutePath); - paths2.push(absolutePath); - } catch {} - } - for (const dir of getAdditionalDirectoriesForClaudeMd()) { - const additionalSkillsPath = platformPath2.join(dir, ".claude", "skills"); - try { - await fs14.stat(additionalSkillsPath); - paths2.push(additionalSkillsPath); - } catch {} - } - return paths2; -} -function handleChange4(path27) { - logForDebugging(`Detected skill change: ${path27}`); - logEvent("tengu_skill_file_changed", { - source: "chokidar" - }); - scheduleReload(path27); -} -function scheduleReload(changedPath) { - pendingChangedPaths.add(changedPath); - if (reloadTimer) - clearTimeout(reloadTimer); - reloadTimer = setTimeout(async () => { - reloadTimer = null; - const paths2 = [...pendingChangedPaths]; - pendingChangedPaths.clear(); - const results = await executeConfigChangeHooks("skills", paths2[0]); - if (hasBlockingResult(results)) { - logForDebugging(`ConfigChange hook blocked skill reload (${paths2.length} paths)`); - return; - } - clearSkillCaches(); - clearCommandsCache(); - resetSentSkillNames(); - skillsChanged.emit(); - }, testOverrides2?.reloadDebounce ?? RELOAD_DEBOUNCE_MS); -} -async function resetForTesting2(overrides) { - if (watcher4) { - await watcher4.close(); - watcher4 = null; - } - if (reloadTimer) { - clearTimeout(reloadTimer); - reloadTimer = null; - } - pendingChangedPaths.clear(); - skillsChanged.clear(); - initialized4 = false; - disposed3 = false; - testOverrides2 = overrides ?? null; -} -var FILE_STABILITY_THRESHOLD_MS3 = 1000, FILE_STABILITY_POLL_INTERVAL_MS3 = 500, RELOAD_DEBOUNCE_MS = 300, POLLING_INTERVAL_MS3 = 2000, USE_POLLING, watcher4 = null, reloadTimer = null, pendingChangedPaths, initialized4 = false, disposed3 = false, dynamicSkillsCallbackRegistered = false, unregisterCleanup = null, skillsChanged, testOverrides2 = null, subscribe3, skillChangeDetector; -var init_skillChangeDetector = __esm(() => { - init_esm20(); - init_state(); - init_commands5(); - init_analytics(); - init_loadSkillsDir(); - init_attachments(); - init_cleanupRegistry(); - init_debug(); - init_fsOperations(); - init_hooks3(); - USE_POLLING = typeof Bun !== "undefined"; - pendingChangedPaths = new Set; - skillsChanged = createSignal(); - subscribe3 = skillsChanged.subscribe; - skillChangeDetector = { - initialize: initialize3, - dispose: dispose3, - subscribe: subscribe3, - resetForTesting: resetForTesting2 - }; -}); - -// src/hooks/useSkillsChange.ts -function useSkillsChange(cwd2, onCommandsChange) { - const handleChange5 = import_react281.useCallback(async () => { - if (!cwd2) - return; - try { - clearCommandsCache(); - const commands7 = await getCommands(cwd2); - onCommandsChange(commands7); - } catch (error46) { - if (error46 instanceof Error) { - logError2(error46); - } - } - }, [cwd2, onCommandsChange]); - import_react281.useEffect(() => skillChangeDetector.subscribe(handleChange5), [handleChange5]); - const handleGrowthBookRefresh = import_react281.useCallback(async () => { - if (!cwd2) - return; - try { - clearCommandMemoizationCaches(); - const commands7 = await getCommands(cwd2); - onCommandsChange(commands7); - } catch (error46) { - if (error46 instanceof Error) { - logError2(error46); - } - } - }, [cwd2, onCommandsChange]); - import_react281.useEffect(() => onGrowthBookRefresh(handleGrowthBookRefresh), [handleGrowthBookRefresh]); -} -var import_react281; -var init_useSkillsChange = __esm(() => { - init_commands5(); - init_growthbook(); - init_log2(); - init_skillChangeDetector(); - import_react281 = __toESM(require_react(), 1); -}); - -// src/utils/plugins/pluginBlocklist.ts -function detectDelistedPlugins(installedPlugins, marketplace, marketplaceName) { - const marketplacePluginNames = new Set(marketplace.plugins.map((p4) => p4.name)); - const suffix = `@${marketplaceName}`; - const delisted = []; - for (const pluginId of Object.keys(installedPlugins.plugins)) { - if (!pluginId.endsWith(suffix)) - continue; - const pluginName = pluginId.slice(0, -suffix.length); - if (!marketplacePluginNames.has(pluginName)) { - delisted.push(pluginId); - } - } - return delisted; -} -async function detectAndUninstallDelistedPlugins() { - await loadFlaggedPlugins(); - const installedPlugins = loadInstalledPluginsV2(); - const alreadyFlagged = getFlaggedPlugins(); - const knownMarketplaces = await loadKnownMarketplacesConfigSafe(); - const newlyFlagged = []; - for (const marketplaceName of Object.keys(knownMarketplaces)) { - try { - const marketplace = await getMarketplace(marketplaceName); - if (!marketplace.forceRemoveDeletedPlugins) - continue; - const delisted = detectDelistedPlugins(installedPlugins, marketplace, marketplaceName); - for (const pluginId of delisted) { - if (pluginId in alreadyFlagged) - continue; - const installations = installedPlugins.plugins[pluginId] ?? []; - const hasUserInstall = installations.some((i6) => i6.scope === "user" || i6.scope === "project" || i6.scope === "local"); - if (!hasUserInstall) - continue; - for (const installation of installations) { - const { scope } = installation; - if (scope !== "user" && scope !== "project" && scope !== "local") { - continue; - } - try { - await uninstallPluginOp(pluginId, scope); - } catch (error46) { - logForDebugging(`Failed to auto-uninstall delisted plugin ${pluginId} from ${scope}: ${errorMessage(error46)}`, { level: "error" }); - } - } - await addFlaggedPlugin(pluginId); - newlyFlagged.push(pluginId); - } - } catch (error46) { - logForDebugging(`Failed to check for delisted plugins in "${marketplaceName}": ${errorMessage(error46)}`, { level: "warn" }); - } - } - return newlyFlagged; -} -var init_pluginBlocklist = __esm(() => { - init_pluginOperations(); - init_debug(); - init_errors(); - init_installedPluginsManager(); - init_marketplaceManager(); - init_pluginFlagging(); -}); - -// src/hooks/useManagePlugins.ts -function useManagePlugins({ - enabled: enabled2 = true -} = {}) { - const setAppState = useSetAppState(); - const needsRefresh = useAppState((s4) => s4.plugins.needsRefresh); - const { addNotification } = useNotifications(); - const initialPluginLoad = import_react282.useCallback(async () => { - try { - const { enabled: enabled3, disabled, errors: errors8 } = await loadAllPlugins(); - await detectAndUninstallDelistedPlugins(); - const flagged = getFlaggedPlugins(); - if (Object.keys(flagged).length > 0) { - addNotification({ - key: "plugin-delisted-flagged", - text: "Plugins flagged. Check /plugins", - color: "warning", - priority: "high" - }); - } - let commands7 = []; - let agents2 = []; - try { - commands7 = await getPluginCommands(); - } catch (error46) { - const errorMessage4 = error46 instanceof Error ? error46.message : String(error46); - errors8.push({ - type: "generic-error", - source: "plugin-commands", - error: `Failed to load plugin commands: ${errorMessage4}` - }); - } - try { - agents2 = await loadPluginAgents(); - } catch (error46) { - const errorMessage4 = error46 instanceof Error ? error46.message : String(error46); - errors8.push({ - type: "generic-error", - source: "plugin-agents", - error: `Failed to load plugin agents: ${errorMessage4}` - }); - } - try { - await loadPluginHooks2(); - } catch (error46) { - const errorMessage4 = error46 instanceof Error ? error46.message : String(error46); - errors8.push({ - type: "generic-error", - source: "plugin-hooks", - error: `Failed to load plugin hooks: ${errorMessage4}` - }); - } - const mcpServerCounts = await Promise.all(enabled3.map(async (p4) => { - if (p4.mcpServers) - return Object.keys(p4.mcpServers).length; - const servers = await loadPluginMcpServers(p4, errors8); - if (servers) - p4.mcpServers = servers; - return servers ? Object.keys(servers).length : 0; - })); - const mcp_count = mcpServerCounts.reduce((sum, n6) => sum + n6, 0); - const lspServerCounts = await Promise.all(enabled3.map(async (p4) => { - if (p4.lspServers) - return Object.keys(p4.lspServers).length; - const servers = await loadPluginLspServers(p4, errors8); - if (servers) - p4.lspServers = servers; - return servers ? Object.keys(servers).length : 0; - })); - const lsp_count = lspServerCounts.reduce((sum, n6) => sum + n6, 0); - reinitializeLspServerManager(); - setAppState((prevState) => { - const existingLspErrors = prevState.plugins.errors.filter((e4) => e4.source === "lsp-manager" || e4.source.startsWith("plugin:")); - const newErrorKeys = new Set(errors8.map((e4) => e4.type === "generic-error" ? `generic-error:${e4.source}:${e4.error}` : `${e4.type}:${e4.source}`)); - const filteredExisting = existingLspErrors.filter((e4) => { - const key2 = e4.type === "generic-error" ? `generic-error:${e4.source}:${e4.error}` : `${e4.type}:${e4.source}`; - return !newErrorKeys.has(key2); - }); - const mergedErrors = [...filteredExisting, ...errors8]; - return { - ...prevState, - plugins: { - ...prevState.plugins, - enabled: enabled3, - disabled, - commands: commands7, - errors: mergedErrors - } - }; - }); - logForDebugging(`Loaded plugins - Enabled: ${enabled3.length}, Disabled: ${disabled.length}, Commands: ${commands7.length}, Agents: ${agents2.length}, Errors: ${errors8.length}`); - const hook_count = enabled3.reduce((sum, p4) => { - if (!p4.hooksConfig) - return sum; - return sum + Object.values(p4.hooksConfig).reduce((s4, matchers) => s4 + (matchers?.reduce((h5, m4) => h5 + m4.hooks.length, 0) ?? 0), 0); - }, 0); - return { - enabled_count: enabled3.length, - disabled_count: disabled.length, - inline_count: count2(enabled3, (p4) => p4.source.endsWith("@inline")), - marketplace_count: count2(enabled3, (p4) => !p4.source.endsWith("@inline")), - error_count: errors8.length, - skill_count: commands7.length, - agent_count: agents2.length, - hook_count, - mcp_count, - lsp_count, - ant_enabled_names: process.env.USER_TYPE === "ant" && enabled3.length > 0 ? enabled3.map((p4) => p4.name).sort().join(",") : undefined - }; - } catch (error46) { - const errorObj = toError(error46); - logError2(errorObj); - logForDebugging(`Error loading plugins: ${error46}`); - setAppState((prevState) => { - const existingLspErrors = prevState.plugins.errors.filter((e4) => e4.source === "lsp-manager" || e4.source.startsWith("plugin:")); - const newError = { - type: "generic-error", - source: "plugin-system", - error: errorObj.message - }; - return { - ...prevState, - plugins: { - ...prevState.plugins, - enabled: [], - disabled: [], - commands: [], - errors: [...existingLspErrors, newError] - } - }; - }); - return { - enabled_count: 0, - disabled_count: 0, - inline_count: 0, - marketplace_count: 0, - error_count: 1, - skill_count: 0, - agent_count: 0, - hook_count: 0, - mcp_count: 0, - lsp_count: 0, - load_failed: true, - ant_enabled_names: undefined - }; - } - }, [setAppState, addNotification]); - import_react282.useEffect(() => { - if (!enabled2) - return; - initialPluginLoad().then((metrics) => { - const { ant_enabled_names, ...baseMetrics } = metrics; - const allMetrics = { - ...baseMetrics, - has_custom_plugin_cache_dir: !!process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR - }; - logEvent("tengu_plugins_loaded", { - ...allMetrics, - ...ant_enabled_names !== undefined && { - enabled_names: ant_enabled_names - } - }); - logForDiagnosticsNoPII("info", "tengu_plugins_loaded", allMetrics); - }); - }, [initialPluginLoad, enabled2]); - import_react282.useEffect(() => { - if (!enabled2 || !needsRefresh) - return; - addNotification({ - key: "plugin-reload-pending", - text: "Plugins changed. Run /reload-plugins to activate.", - color: "suggestion", - priority: "low" - }); - }, [enabled2, needsRefresh, addNotification]); -} -var import_react282; -var init_useManagePlugins = __esm(() => { - init_notifications(); - init_analytics(); - init_manager7(); - init_AppState(); - init_debug(); - init_diagLogs(); - init_errors(); - init_log2(); - init_loadPluginAgents(); - init_loadPluginCommands(); - init_loadPluginHooks(); - init_lspPluginIntegration(); - init_mcpPluginIntegration(); - init_pluginBlocklist(); - init_pluginFlagging(); - init_pluginLoader(); - import_react282 = __toESM(require_react(), 1); -}); - -// src/components/TeammateViewHeader.tsx -function TeammateViewHeader() { - const $2 = import_compiler_runtime342.c(14); - const viewedTeammate = useAppState(_temp200); - if (!viewedTeammate) { - return null; - } - let t0; - if ($2[0] !== viewedTeammate.identity.color) { - t0 = toInkColor(viewedTeammate.identity.color); - $2[0] = viewedTeammate.identity.color; - $2[1] = t0; - } else { - t0 = $2[1]; - } - const nameColor = t0; - let t1; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(ThemedText, { - children: "Viewing " - }, undefined, false, undefined, this); - $2[2] = t1; - } else { - t1 = $2[2]; - } - let t22; - if ($2[3] !== nameColor || $2[4] !== viewedTeammate.identity.agentName) { - t22 = /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(ThemedText, { - color: nameColor, - bold: true, - children: [ - "@", - viewedTeammate.identity.agentName - ] - }, undefined, true, undefined, this); - $2[3] = nameColor; - $2[4] = viewedTeammate.identity.agentName; - $2[5] = t22; - } else { - t22 = $2[5]; - } - let t32; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " \xB7 ", - /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(KeyboardShortcutHint, { - shortcut: "esc", - action: "return" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] !== t22) { - t4 = /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(ThemedBox_default, { - children: [ - t1, - t22, - t32 - ] - }, undefined, true, undefined, this); - $2[7] = t22; - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] !== viewedTeammate.prompt) { - t5 = /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(ThemedText, { - dimColor: true, - children: viewedTeammate.prompt - }, undefined, false, undefined, this); - $2[9] = viewedTeammate.prompt; - $2[10] = t5; - } else { - t5 = $2[10]; - } - let t6; - if ($2[11] !== t4 || $2[12] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(OffscreenFreeze, { - children: /* @__PURE__ */ jsx_dev_runtime442.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginBottom: 1, - children: [ - t4, - t5 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[11] = t4; - $2[12] = t5; - $2[13] = t6; - } else { - t6 = $2[13]; - } - return t6; -} -function _temp200(s4) { - return getViewedTeammateTask(s4); -} -var import_compiler_runtime342, jsx_dev_runtime442; -var init_TeammateViewHeader = __esm(() => { - init_ink2(); - init_AppState(); - init_selectors(); - init_ink3(); - init_KeyboardShortcutHint(); - init_OffscreenFreeze(); - import_compiler_runtime342 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime442 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useIdeSelection.ts -function useIdeSelection(mcpClients, onSelect) { - const handlersRegistered = import_react283.useRef(false); - const currentIDERef = import_react283.useRef(null); - import_react283.useEffect(() => { - const ideClient = getConnectedIdeClient(mcpClients); - if (currentIDERef.current !== (ideClient ?? null)) { - handlersRegistered.current = false; - currentIDERef.current = ideClient || null; - onSelect({ - lineCount: 0, - lineStart: undefined, - text: undefined, - filePath: undefined - }); - } - if (handlersRegistered.current || !ideClient) { - return; - } - const selectionChangeHandler = (data) => { - if (data.selection?.start && data.selection?.end) { - const { start, end } = data.selection; - let lineCount = end.line - start.line + 1; - if (end.character === 0) { - lineCount--; - } - const selection = { - lineCount, - lineStart: start.line, - text: data.text, - filePath: data.filePath - }; - onSelect(selection); - } - }; - ideClient.client.setNotificationHandler(SelectionChangedSchema(), (notification) => { - if (currentIDERef.current !== ideClient) { - return; - } - try { - const selectionData = notification.params; - if (selectionData.selection && selectionData.selection.start && selectionData.selection.end) { - selectionChangeHandler(selectionData); - } else if (selectionData.text !== undefined) { - selectionChangeHandler({ - selection: null, - text: selectionData.text, - filePath: selectionData.filePath - }); - } - } catch (error46) { - logError2(error46); - } - }); - handlersRegistered.current = true; - }, [mcpClients, onSelect]); -} -var import_react283, SelectionChangedSchema; -var init_useIdeSelection = __esm(() => { - init_log2(); - init_v4(); - init_ide(); - import_react283 = __toESM(require_react(), 1); - SelectionChangedSchema = lazySchema(() => exports_external.object({ - method: exports_external.literal("selection_changed"), - params: exports_external.object({ - selection: exports_external.object({ - start: exports_external.object({ - line: exports_external.number(), - character: exports_external.number() - }), - end: exports_external.object({ - line: exports_external.number(), - character: exports_external.number() - }) - }).nullable().optional(), - text: exports_external.string().optional(), - filePath: exports_external.string().optional() - }) - })); -}); - -// src/utils/asciicast.ts -var exports_asciicast = {}; -__export(exports_asciicast, { - renameRecordingForSession: () => renameRecordingForSession, - installAsciicastRecorder: () => installAsciicastRecorder, - getSessionRecordingPaths: () => getSessionRecordingPaths, - getRecordFilePath: () => getRecordFilePath, - flushAsciicastRecorder: () => flushAsciicastRecorder, - _resetRecordingStateForTesting: () => _resetRecordingStateForTesting -}); -import { appendFile as appendFile6, rename as rename10 } from "fs/promises"; -import { basename as basename56, dirname as dirname57, join as join146 } from "path"; -function getRecordFilePath() { - if (recordingState.filePath !== null) { - return recordingState.filePath; - } - if (process.env.USER_TYPE !== "ant") { - return null; - } - if (!isEnvTruthy(process.env.CLAUDE_CODE_TERMINAL_RECORDING)) { - return null; - } - const projectsDir = join146(getClaudeConfigHomeDir(), "projects"); - const projectDir = join146(projectsDir, sanitizePath2(getOriginalCwd())); - recordingState.timestamp = Date.now(); - recordingState.filePath = join146(projectDir, `${getSessionId()}-${recordingState.timestamp}.cast`); - return recordingState.filePath; -} -function _resetRecordingStateForTesting() { - recordingState.filePath = null; - recordingState.timestamp = 0; -} -function getSessionRecordingPaths() { - const sessionId = getSessionId(); - const projectsDir = join146(getClaudeConfigHomeDir(), "projects"); - const projectDir = join146(projectsDir, sanitizePath2(getOriginalCwd())); - try { - const entries = getFsImplementation().readdirSync(projectDir); - const names = typeof entries[0] === "string" ? entries : entries.map((e4) => e4.name); - const files3 = names.filter((f4) => f4.startsWith(sessionId) && f4.endsWith(".cast")).sort(); - return files3.map((f4) => join146(projectDir, f4)); - } catch { - return []; - } -} -async function renameRecordingForSession() { - const oldPath = recordingState.filePath; - if (!oldPath || recordingState.timestamp === 0) { - return; - } - const projectsDir = join146(getClaudeConfigHomeDir(), "projects"); - const projectDir = join146(projectsDir, sanitizePath2(getOriginalCwd())); - const newPath = join146(projectDir, `${getSessionId()}-${recordingState.timestamp}.cast`); - if (oldPath === newPath) { - return; - } - await recorder?.flush(); - const oldName = basename56(oldPath); - const newName = basename56(newPath); - try { - await rename10(oldPath, newPath); - recordingState.filePath = newPath; - logForDebugging(`[asciicast] Renamed recording: ${oldName} \u2192 ${newName}`); - } catch { - logForDebugging(`[asciicast] Failed to rename recording from ${oldName} to ${newName}`); - } -} -function getTerminalSize() { - const cols = process.stdout.columns || 80; - const rows = process.stdout.rows || 24; - return { cols, rows }; -} -async function flushAsciicastRecorder() { - await recorder?.flush(); -} -function installAsciicastRecorder() { - const filePath = getRecordFilePath(); - if (!filePath) { - return; - } - const { cols, rows } = getTerminalSize(); - const startTime = performance.now(); - const header = jsonStringify({ - version: 2, - width: cols, - height: rows, - timestamp: Math.floor(Date.now() / 1000), - env: { - SHELL: process.env.SHELL || "", - TERM: process.env.TERM || "" - } - }); - try { - getFsImplementation().mkdirSync(dirname57(filePath)); - } catch {} - getFsImplementation().appendFileSync(filePath, header + ` -`, { mode: 384 }); - let pendingWrite2 = Promise.resolve(); - const writer = createBufferedWriter({ - writeFn(content) { - const currentPath = recordingState.filePath; - if (!currentPath) { - return; - } - pendingWrite2 = pendingWrite2.then(() => appendFile6(currentPath, content)).catch(() => {}); - }, - flushIntervalMs: 500, - maxBufferSize: 50, - maxBufferBytes: 10 * 1024 * 1024 - }); - const originalWrite = process.stdout.write.bind(process.stdout); - process.stdout.write = function(chunk2, encodingOrCb, cb) { - const elapsed = (performance.now() - startTime) / 1000; - const text = typeof chunk2 === "string" ? chunk2 : Buffer.from(chunk2).toString("utf-8"); - writer.write(jsonStringify([elapsed, "o", text]) + ` -`); - if (typeof encodingOrCb === "function") { - return originalWrite(chunk2, encodingOrCb); - } - return originalWrite(chunk2, encodingOrCb, cb); - }; - function onResize() { - const elapsed = (performance.now() - startTime) / 1000; - const { cols: newCols, rows: newRows } = getTerminalSize(); - writer.write(jsonStringify([elapsed, "r", `${newCols}x${newRows}`]) + ` -`); - } - process.stdout.on("resize", onResize); - recorder = { - async flush() { - writer.flush(); - await pendingWrite2; - }, - async dispose() { - writer.dispose(); - await pendingWrite2; - process.stdout.removeListener("resize", onResize); - process.stdout.write = originalWrite; - } - }; - registerCleanup(async () => { - await recorder?.dispose(); - recorder = null; - }); - logForDebugging(`[asciicast] Recording to ${filePath}`); -} -var recordingState, recorder = null; -var init_asciicast = __esm(() => { - init_state(); - init_cleanupRegistry(); - init_debug(); - init_envUtils(); - init_fsOperations(); - init_path(); - init_slowOperations(); - recordingState = { - filePath: null, - timestamp: 0 - }; -}); - -// src/utils/sessionRestore.ts -import { dirname as dirname58 } from "path"; -function extractTodosFromTranscript(messages) { - for (let i6 = messages.length - 1;i6 >= 0; i6--) { - const msg = messages[i6]; - if (msg?.type !== "assistant") - continue; - const toolUse = msg.message.content.find((block2) => block2.type === "tool_use" && block2.name === TODO_WRITE_TOOL_NAME); - if (!toolUse || toolUse.type !== "tool_use") - continue; - const input = toolUse.input; - if (input === null || typeof input !== "object") - return []; - const parsed = TodoListSchema().safeParse(input.todos); - return parsed.success ? parsed.data : []; - } - return []; -} -function restoreSessionStateFromLog(result, setAppState) { - if (result.fileHistorySnapshots && result.fileHistorySnapshots.length > 0) { - fileHistoryRestoreStateFromLog(result.fileHistorySnapshots, (newState) => { - setAppState((prev) => ({ ...prev, fileHistory: newState })); - }); - } - if (false) {} - if (false) {} - if (!isTodoV2Enabled() && result.messages && result.messages.length > 0) { - const todos = extractTodosFromTranscript(result.messages); - if (todos.length > 0) { - const agentId = getSessionId(); - setAppState((prev) => ({ - ...prev, - todos: { ...prev.todos, [agentId]: todos } - })); - } - } -} -function computeRestoredAttributionState(result) { - if (false) {} - return; -} -function computeStandaloneAgentContext(agentName, agentColor) { - if (!agentName && !agentColor) { - return; - } - return { - name: agentName ?? "", - color: agentColor === "default" ? undefined : agentColor - }; -} -function restoreAgentFromSession(agentSetting, currentAgentDefinition, agentDefinitions) { - if (currentAgentDefinition) { - return { agentDefinition: currentAgentDefinition, agentType: undefined }; - } - if (!agentSetting) { - setMainThreadAgentType(undefined); - return { agentDefinition: undefined, agentType: undefined }; - } - const resumedAgent = agentDefinitions.activeAgents.find((agent) => agent.agentType === agentSetting); - if (!resumedAgent) { - logForDebugging(`Resumed session had agent "${agentSetting}" but it is no longer available. Using default behavior.`); - setMainThreadAgentType(undefined); - return { agentDefinition: undefined, agentType: undefined }; - } - setMainThreadAgentType(resumedAgent.agentType); - if (!getMainLoopModelOverride() && resumedAgent.model && resumedAgent.model !== "inherit") { - setMainLoopModelOverride(parseUserSpecifiedModel(resumedAgent.model)); - } - return { agentDefinition: resumedAgent, agentType: resumedAgent.agentType }; -} -async function refreshAgentDefinitionsForModeSwitch(modeWasSwitched, currentCwd2, cliAgents, currentAgentDefinitions) { - if (true) { - return currentAgentDefinitions; - } - getAgentDefinitionsWithOverrides.cache.clear?.(); - const freshAgentDefs = await getAgentDefinitionsWithOverrides(currentCwd2); - const freshAllAgents = [...freshAgentDefs.allAgents, ...cliAgents]; - return { - ...freshAgentDefs, - allAgents: freshAllAgents, - activeAgents: getActiveAgentsFromList(freshAllAgents) - }; -} -function restoreWorktreeForResume(worktreeSession) { - const fresh = getCurrentWorktreeSession(); - if (fresh) { - saveWorktreeState(fresh); - return; - } - if (!worktreeSession) - return; - try { - process.chdir(worktreeSession.worktreePath); - } catch { - saveWorktreeState(null); - return; - } - setCwd(worktreeSession.worktreePath); - setOriginalCwd(getCwd()); - restoreWorktreeSession(worktreeSession); - clearMemoryFileCaches(); - clearSystemPromptSections(); - getPlansDirectory.cache.clear?.(); -} -function exitRestoredWorktree() { - const current = getCurrentWorktreeSession(); - if (!current) - return; - restoreWorktreeSession(null); - clearMemoryFileCaches(); - clearSystemPromptSections(); - getPlansDirectory.cache.clear?.(); - try { - process.chdir(current.originalCwd); - } catch { - return; - } - setCwd(current.originalCwd); - setOriginalCwd(getCwd()); -} -async function processResumedConversation(result, opts, context7) { - let modeWarning; - if (false) {} - if (!opts.forkSession) { - const sid = opts.sessionIdOverride ?? result.sessionId; - if (sid) { - switchSession(asSessionId(sid), opts.transcriptPath ? dirname58(opts.transcriptPath) : null); - await renameRecordingForSession(); - await resetSessionFilePointer(); - restoreCostStateForSession(sid); - } - } else if (result.contentReplacements?.length) { - await recordContentReplacement(result.contentReplacements); - } - restoreSessionMetadata(opts.forkSession ? { ...result, worktreeSession: undefined } : result); - if (!opts.forkSession) { - restoreWorktreeForResume(result.worktreeSession); - adoptResumedSessionFile(); - } - if (false) {} - const { agentDefinition: restoredAgent, agentType: resumedAgentType } = restoreAgentFromSession(result.agentSetting, context7.mainThreadAgentDefinition, context7.agentDefinitions); - if (false) {} - const restoredAttribution = opts.includeAttribution ? computeRestoredAttributionState(result) : undefined; - const standaloneAgentContext = computeStandaloneAgentContext(result.agentName, result.agentColor); - updateSessionName(result.agentName); - const refreshedAgentDefs = await refreshAgentDefinitionsForModeSwitch(!!modeWarning, context7.currentCwd, context7.cliAgents, context7.agentDefinitions); - return { - messages: result.messages, - fileHistorySnapshots: result.fileHistorySnapshots, - contentReplacements: result.contentReplacements, - agentName: result.agentName, - agentColor: result.agentColor === "default" ? undefined : result.agentColor, - restoredAgentDef: restoredAgent, - initialState: { - ...context7.initialState, - ...resumedAgentType && { agent: resumedAgentType }, - ...restoredAttribution && { attribution: restoredAttribution }, - ...standaloneAgentContext && { standaloneAgentContext }, - agentDefinitions: refreshedAgentDefs - } - }; -} -var init_sessionRestore = __esm(() => { - init_state(); - init_systemPromptSections(); - init_cost_tracker(); - init_loadAgentsDir(); - init_ids(); - init_asciicast(); - init_claudemd(); - init_commitAttribution(); - init_concurrentSessions(); - init_cwd(); - init_debug(); - init_fileHistory(); - init_messages9(); - init_model(); - init_plans(); - init_Shell(); - init_sessionStorage(); - init_tasks(); - init_types22(); - init_worktree(); -}); - -// src/hooks/useInboxPoller.ts -import { randomUUID as randomUUID46 } from "crypto"; -function getAgentNameToPoll(appState) { - if (isInProcessTeammate()) { - return; - } - if (isTeammate()) { - return getAgentName(); - } - if (isTeamLead(appState.teamContext)) { - const leadAgentId = appState.teamContext.leadAgentId; - const leadName = appState.teamContext.teammates[leadAgentId]?.name; - return leadName || "team-lead"; - } - return; -} -function useInboxPoller({ - enabled: enabled2, - isLoading, - focusedInputDialog, - onSubmitMessage -}) { - const onSubmitTeammateMessage = onSubmitMessage; - const store = useAppStateStore(); - const setAppState = useSetAppState(); - const inboxMessageCount = useAppState((s4) => s4.inbox.messages.length); - const terminal = useTerminalNotification(); - const poll = import_react284.useCallback(async () => { - if (!enabled2) - return; - const currentAppState = store.getState(); - const agentName = getAgentNameToPoll(currentAppState); - if (!agentName) - return; - const unread = await readUnreadMessages(agentName, currentAppState.teamContext?.teamName); - if (unread.length === 0) - return; - logForDebugging(`[InboxPoller] Found ${unread.length} unread message(s)`); - if (isTeammate() && isPlanModeRequired()) { - for (const msg of unread) { - const approvalResponse = isPlanApprovalResponse(msg.text); - if (approvalResponse && msg.from === "team-lead") { - logForDebugging(`[InboxPoller] Received plan approval response from team-lead: approved=${approvalResponse.approved}`); - if (approvalResponse.approved) { - const targetMode = approvalResponse.permissionMode ?? "default"; - setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdate(prev.toolPermissionContext, { - type: "setMode", - mode: toExternalPermissionMode(targetMode), - destination: "session" - }) - })); - logForDebugging(`[InboxPoller] Plan approved by team lead, exited plan mode to ${targetMode}`); - } else { - logForDebugging(`[InboxPoller] Plan rejected by team lead: ${approvalResponse.feedback || "No feedback provided"}`); - } - } else if (approvalResponse) { - logForDebugging(`[InboxPoller] Ignoring plan approval response from non-team-lead: ${msg.from}`); - } - } - } - const markRead = () => { - markMessagesAsRead(agentName, currentAppState.teamContext?.teamName); - }; - const permissionRequests = []; - const permissionResponses = []; - const sandboxPermissionRequests = []; - const sandboxPermissionResponses = []; - const shutdownRequests = []; - const shutdownApprovals = []; - const teamPermissionUpdates = []; - const modeSetRequests = []; - const planApprovalRequests = []; - const regularMessages = []; - for (const m4 of unread) { - const permReq = isPermissionRequest(m4.text); - const permResp = isPermissionResponse(m4.text); - const sandboxReq = isSandboxPermissionRequest(m4.text); - const sandboxResp = isSandboxPermissionResponse(m4.text); - const shutdownReq = isShutdownRequest(m4.text); - const shutdownApproval = isShutdownApproved(m4.text); - const teamPermUpdate = isTeamPermissionUpdate(m4.text); - const modeSetReq = isModeSetRequest(m4.text); - const planApprovalReq = isPlanApprovalRequest(m4.text); - if (permReq) { - permissionRequests.push(m4); - } else if (permResp) { - permissionResponses.push(m4); - } else if (sandboxReq) { - sandboxPermissionRequests.push(m4); - } else if (sandboxResp) { - sandboxPermissionResponses.push(m4); - } else if (shutdownReq) { - shutdownRequests.push(m4); - } else if (shutdownApproval) { - shutdownApprovals.push(m4); - } else if (teamPermUpdate) { - teamPermissionUpdates.push(m4); - } else if (modeSetReq) { - modeSetRequests.push(m4); - } else if (planApprovalReq) { - planApprovalRequests.push(m4); - } else { - regularMessages.push(m4); - } - } - if (permissionRequests.length > 0 && isTeamLead(currentAppState.teamContext)) { - logForDebugging(`[InboxPoller] Found ${permissionRequests.length} permission request(s)`); - const setToolUseConfirmQueue = getLeaderToolUseConfirmQueue(); - const teamName = currentAppState.teamContext?.teamName; - for (const m4 of permissionRequests) { - const parsed = isPermissionRequest(m4.text); - if (!parsed) - continue; - if (setToolUseConfirmQueue) { - const tool = findToolByName(getAllBaseTools(), parsed.tool_name); - if (!tool) { - logForDebugging(`[InboxPoller] Unknown tool ${parsed.tool_name}, skipping permission request`); - continue; - } - const entry = { - assistantMessage: createAssistantMessage({ content: "" }), - tool, - description: parsed.description, - input: parsed.input, - toolUseContext: {}, - toolUseID: parsed.tool_use_id, - permissionResult: { - behavior: "ask", - message: parsed.description - }, - permissionPromptStartTimeMs: Date.now(), - workerBadge: { - name: parsed.agent_id, - color: "cyan" - }, - onUserInteraction() {}, - onAbort() { - sendPermissionResponseViaMailbox(parsed.agent_id, { decision: "rejected", resolvedBy: "leader" }, parsed.request_id, teamName); - }, - onAllow(updatedInput, permissionUpdates) { - sendPermissionResponseViaMailbox(parsed.agent_id, { - decision: "approved", - resolvedBy: "leader", - updatedInput, - permissionUpdates - }, parsed.request_id, teamName); - }, - onReject(feedback2) { - sendPermissionResponseViaMailbox(parsed.agent_id, { - decision: "rejected", - resolvedBy: "leader", - feedback: feedback2 - }, parsed.request_id, teamName); - }, - async recheckPermission() {} - }; - setToolUseConfirmQueue((queue2) => { - if (queue2.some((q4) => q4.toolUseID === parsed.tool_use_id)) { - return queue2; - } - return [...queue2, entry]; - }); - } else { - logForDebugging(`[InboxPoller] ToolUseConfirmQueue unavailable, dropping permission request from ${parsed.agent_id}`); - } - } - const firstParsed = isPermissionRequest(permissionRequests[0]?.text ?? ""); - if (firstParsed && !isLoading && !focusedInputDialog) { - sendNotification({ - message: `${firstParsed.agent_id} needs permission for ${firstParsed.tool_name}`, - notificationType: "worker_permission_prompt" - }, terminal); - } - } - if (permissionResponses.length > 0 && isTeammate()) { - logForDebugging(`[InboxPoller] Found ${permissionResponses.length} permission response(s)`); - for (const m4 of permissionResponses) { - const parsed = isPermissionResponse(m4.text); - if (!parsed) - continue; - if (hasPermissionCallback(parsed.request_id)) { - logForDebugging(`[InboxPoller] Processing permission response for ${parsed.request_id}: ${parsed.subtype}`); - if (parsed.subtype === "success") { - processMailboxPermissionResponse({ - requestId: parsed.request_id, - decision: "approved", - updatedInput: parsed.response?.updated_input, - permissionUpdates: parsed.response?.permission_updates - }); - } else { - processMailboxPermissionResponse({ - requestId: parsed.request_id, - decision: "rejected", - feedback: parsed.error - }); - } - } - } - } - if (sandboxPermissionRequests.length > 0 && isTeamLead(currentAppState.teamContext)) { - logForDebugging(`[InboxPoller] Found ${sandboxPermissionRequests.length} sandbox permission request(s)`); - const newSandboxRequests = []; - for (const m4 of sandboxPermissionRequests) { - const parsed = isSandboxPermissionRequest(m4.text); - if (!parsed) - continue; - if (!parsed.hostPattern?.host) { - logForDebugging(`[InboxPoller] Invalid sandbox permission request: missing hostPattern.host`); - continue; - } - newSandboxRequests.push({ - requestId: parsed.requestId, - workerId: parsed.workerId, - workerName: parsed.workerName, - workerColor: parsed.workerColor, - host: parsed.hostPattern.host, - createdAt: parsed.createdAt - }); - } - if (newSandboxRequests.length > 0) { - setAppState((prev) => ({ - ...prev, - workerSandboxPermissions: { - ...prev.workerSandboxPermissions, - queue: [ - ...prev.workerSandboxPermissions.queue, - ...newSandboxRequests - ] - } - })); - const firstRequest = newSandboxRequests[0]; - if (firstRequest && !isLoading && !focusedInputDialog) { - sendNotification({ - message: `${firstRequest.workerName} needs network access to ${firstRequest.host}`, - notificationType: "worker_permission_prompt" - }, terminal); - } - } - } - if (sandboxPermissionResponses.length > 0 && isTeammate()) { - logForDebugging(`[InboxPoller] Found ${sandboxPermissionResponses.length} sandbox permission response(s)`); - for (const m4 of sandboxPermissionResponses) { - const parsed = isSandboxPermissionResponse(m4.text); - if (!parsed) - continue; - if (hasSandboxPermissionCallback(parsed.requestId)) { - logForDebugging(`[InboxPoller] Processing sandbox permission response for ${parsed.requestId}: allow=${parsed.allow}`); - processSandboxPermissionResponse({ - requestId: parsed.requestId, - host: parsed.host, - allow: parsed.allow - }); - setAppState((prev) => ({ - ...prev, - pendingSandboxRequest: null - })); - } - } - } - if (teamPermissionUpdates.length > 0 && isTeammate()) { - logForDebugging(`[InboxPoller] Found ${teamPermissionUpdates.length} team permission update(s)`); - for (const m4 of teamPermissionUpdates) { - const parsed = isTeamPermissionUpdate(m4.text); - if (!parsed) { - logForDebugging(`[InboxPoller] Failed to parse team permission update: ${m4.text.substring(0, 100)}`); - continue; - } - if (!parsed.permissionUpdate?.rules || !parsed.permissionUpdate?.behavior) { - logForDebugging(`[InboxPoller] Invalid team permission update: missing permissionUpdate.rules or permissionUpdate.behavior`); - continue; - } - logForDebugging(`[InboxPoller] Applying team permission update: ${parsed.toolName} allowed in ${parsed.directoryPath}`); - logForDebugging(`[InboxPoller] Permission update rules: ${jsonStringify(parsed.permissionUpdate.rules)}`); - setAppState((prev) => { - const updated = applyPermissionUpdate(prev.toolPermissionContext, { - type: "addRules", - rules: parsed.permissionUpdate.rules, - behavior: parsed.permissionUpdate.behavior, - destination: "session" - }); - logForDebugging(`[InboxPoller] Updated session allow rules: ${jsonStringify(updated.alwaysAllowRules.session)}`); - return { - ...prev, - toolPermissionContext: updated - }; - }); - } - } - if (modeSetRequests.length > 0 && isTeammate()) { - logForDebugging(`[InboxPoller] Found ${modeSetRequests.length} mode set request(s)`); - for (const m4 of modeSetRequests) { - if (m4.from !== "team-lead") { - logForDebugging(`[InboxPoller] Ignoring mode set request from non-team-lead: ${m4.from}`); - continue; - } - const parsed = isModeSetRequest(m4.text); - if (!parsed) { - logForDebugging(`[InboxPoller] Failed to parse mode set request: ${m4.text.substring(0, 100)}`); - continue; - } - const targetMode = permissionModeFromString(parsed.mode); - logForDebugging(`[InboxPoller] Applying mode change from team-lead: ${targetMode}`); - setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdate(prev.toolPermissionContext, { - type: "setMode", - mode: toExternalPermissionMode(targetMode), - destination: "session" - }) - })); - const teamName = currentAppState.teamContext?.teamName; - const agentName2 = getAgentName(); - if (teamName && agentName2) { - setMemberMode(teamName, agentName2, targetMode); - } - } - } - if (planApprovalRequests.length > 0 && isTeamLead(currentAppState.teamContext)) { - logForDebugging(`[InboxPoller] Found ${planApprovalRequests.length} plan approval request(s), auto-approving`); - const teamName = currentAppState.teamContext?.teamName; - const leaderExternalMode = toExternalPermissionMode(currentAppState.toolPermissionContext.mode); - const modeToInherit = leaderExternalMode === "plan" ? "default" : leaderExternalMode; - for (const m4 of planApprovalRequests) { - const parsed = isPlanApprovalRequest(m4.text); - if (!parsed) - continue; - const approvalResponse = { - type: "plan_approval_response", - requestId: parsed.requestId, - approved: true, - timestamp: new Date().toISOString(), - permissionMode: modeToInherit - }; - writeToMailbox(m4.from, { - from: TEAM_LEAD_NAME, - text: jsonStringify(approvalResponse), - timestamp: new Date().toISOString() - }, teamName); - const taskId = findInProcessTeammateTaskId(m4.from, currentAppState); - if (taskId) { - handlePlanApprovalResponse(taskId, { - type: "plan_approval_response", - requestId: parsed.requestId, - approved: true, - timestamp: new Date().toISOString(), - permissionMode: modeToInherit - }, setAppState); - } - logForDebugging(`[InboxPoller] Auto-approved plan from ${m4.from} (request ${parsed.requestId})`); - regularMessages.push(m4); - } - } - if (shutdownRequests.length > 0 && isTeammate()) { - logForDebugging(`[InboxPoller] Found ${shutdownRequests.length} shutdown request(s)`); - for (const m4 of shutdownRequests) { - regularMessages.push(m4); - } - } - if (shutdownApprovals.length > 0 && isTeamLead(currentAppState.teamContext)) { - logForDebugging(`[InboxPoller] Found ${shutdownApprovals.length} shutdown approval(s)`); - for (const m4 of shutdownApprovals) { - const parsed = isShutdownApproved(m4.text); - if (!parsed) - continue; - if (parsed.paneId && parsed.backendType) { - (async () => { - try { - await ensureBackendsRegistered(); - const insideTmux = await isInsideTmux(); - const backend = getBackendByType(parsed.backendType); - const success2 = await backend?.killPane(parsed.paneId, !insideTmux); - logForDebugging(`[InboxPoller] Killed pane ${parsed.paneId} for ${parsed.from}: ${success2}`); - } catch (error46) { - logForDebugging(`[InboxPoller] Failed to kill pane for ${parsed.from}: ${error46}`); - } - })(); - } - const teammateToRemove = parsed.from; - if (teammateToRemove && currentAppState.teamContext?.teammates) { - const teammateId = Object.entries(currentAppState.teamContext.teammates).find(([, t4]) => t4.name === teammateToRemove)?.[0]; - if (teammateId) { - const teamName = currentAppState.teamContext?.teamName; - if (teamName) { - removeTeammateFromTeamFile(teamName, { - agentId: teammateId, - name: teammateToRemove - }); - } - const { notificationMessage } = teamName ? await unassignTeammateTasks(teamName, teammateId, teammateToRemove, "shutdown") : { notificationMessage: `${teammateToRemove} has shut down.` }; - setAppState((prev) => { - if (!prev.teamContext?.teammates) - return prev; - if (!(teammateId in prev.teamContext.teammates)) - return prev; - const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates; - const updatedTasks = { ...prev.tasks }; - for (const [tid, task] of Object.entries(updatedTasks)) { - if (isInProcessTeammateTask(task) && task.identity.agentId === teammateId) { - updatedTasks[tid] = { - ...task, - status: "completed", - endTime: Date.now() - }; - } - } - return { - ...prev, - tasks: updatedTasks, - teamContext: { - ...prev.teamContext, - teammates: remainingTeammates - }, - inbox: { - messages: [ - ...prev.inbox.messages, - { - id: randomUUID46(), - from: "system", - text: jsonStringify({ - type: "teammate_terminated", - message: notificationMessage - }), - timestamp: new Date().toISOString(), - status: "pending" - } - ] - } - }; - }); - logForDebugging(`[InboxPoller] Removed ${teammateToRemove} (${teammateId}) from teamContext`); - } - } - regularMessages.push(m4); - } - } - if (regularMessages.length === 0) { - markRead(); - return; - } - const formatted = regularMessages.map((m4) => { - const colorAttr = m4.color ? ` color="${m4.color}"` : ""; - const summaryAttr = m4.summary ? ` summary="${m4.summary}"` : ""; - const messageContent = m4.text; - return `<${TEAMMATE_MESSAGE_TAG} teammate_id="${m4.from}"${colorAttr}${summaryAttr}> -${messageContent} -`; - }).join(` - -`); - const queueMessages = () => { - setAppState((prev) => ({ - ...prev, - inbox: { - messages: [ - ...prev.inbox.messages, - ...regularMessages.map((m4) => ({ - id: randomUUID46(), - from: m4.from, - text: m4.text, - timestamp: m4.timestamp, - status: "pending", - color: m4.color, - summary: m4.summary - })) - ] - } - })); - }; - if (!isLoading && !focusedInputDialog) { - logForDebugging(`[InboxPoller] Session idle, submitting immediately`); - const submitted = onSubmitTeammateMessage(formatted); - if (!submitted) { - logForDebugging(`[InboxPoller] Submission rejected, queuing for later delivery`); - queueMessages(); - } - } else { - logForDebugging(`[InboxPoller] Session busy, queuing for later delivery`); - queueMessages(); - } - markRead(); - }, [ - enabled2, - isLoading, - focusedInputDialog, - onSubmitTeammateMessage, - setAppState, - terminal, - store - ]); - import_react284.useEffect(() => { - if (!enabled2) - return; - if (isLoading || focusedInputDialog) { - return; - } - const currentAppState = store.getState(); - const agentName = getAgentNameToPoll(currentAppState); - if (!agentName) - return; - const pendingMessages = currentAppState.inbox.messages.filter((m4) => m4.status === "pending"); - const processedMessages = currentAppState.inbox.messages.filter((m4) => m4.status === "processed"); - if (processedMessages.length > 0) { - logForDebugging(`[InboxPoller] Cleaning up ${processedMessages.length} processed message(s) that were delivered mid-turn`); - const processedIds = new Set(processedMessages.map((m4) => m4.id)); - setAppState((prev) => ({ - ...prev, - inbox: { - messages: prev.inbox.messages.filter((m4) => !processedIds.has(m4.id)) - } - })); - } - if (pendingMessages.length === 0) - return; - logForDebugging(`[InboxPoller] Session idle, delivering ${pendingMessages.length} pending message(s)`); - const formatted = pendingMessages.map((m4) => { - const colorAttr = m4.color ? ` color="${m4.color}"` : ""; - const summaryAttr = m4.summary ? ` summary="${m4.summary}"` : ""; - return `<${TEAMMATE_MESSAGE_TAG} teammate_id="${m4.from}"${colorAttr}${summaryAttr}> -${m4.text} -`; - }).join(` - -`); - const submitted = onSubmitTeammateMessage(formatted); - if (submitted) { - const submittedIds = new Set(pendingMessages.map((m4) => m4.id)); - setAppState((prev) => ({ - ...prev, - inbox: { - messages: prev.inbox.messages.filter((m4) => !submittedIds.has(m4.id)) - } - })); - } else { - logForDebugging(`[InboxPoller] Submission rejected, keeping messages queued`); - } - }, [ - enabled2, - isLoading, - focusedInputDialog, - onSubmitTeammateMessage, - setAppState, - inboxMessageCount, - store - ]); - const shouldPoll = enabled2 && !!getAgentNameToPoll(store.getState()); - useInterval(() => void poll(), shouldPoll ? INBOX_POLL_INTERVAL_MS : null); - const hasDoneInitialPollRef = import_react284.useRef(false); - import_react284.useEffect(() => { - if (!enabled2) - return; - if (hasDoneInitialPollRef.current) - return; - if (getAgentNameToPoll(store.getState())) { - hasDoneInitialPollRef.current = true; - poll(); - } - }, [enabled2, poll, store]); -} -var import_react284, INBOX_POLL_INTERVAL_MS = 1000; -var init_useInboxPoller = __esm(() => { - init_dist4(); - init_xml(); - init_useTerminalNotification(); - init_notifier(); - init_AppState(); - init_Tool(); - init_tools2(); - init_debug(); - init_inProcessTeammateHelpers(); - init_messages9(); - init_PermissionMode(); - init_PermissionUpdate(); - init_slowOperations(); - init_detection(); - init_registry(); - init_permissionSync(); - init_teamHelpers(); - init_tasks(); - init_teammate(); - init_teammateContext(); - init_teammateMailbox(); - init_useSwarmPermissionPoller(); - import_react284 = __toESM(require_react(), 1); -}); - -// src/hooks/useTaskListWatcher.ts -var import_react285; -var init_useTaskListWatcher = __esm(() => { - init_debug(); - init_tasks(); - import_react285 = __toESM(require_react(), 1); -}); - -// src/hooks/useIDEIntegration.tsx -function useIDEIntegration(t0) { - const $2 = import_compiler_runtime343.c(7); - const { - autoConnectIdeFlag, - ideToInstallExtension, - setDynamicMcpConfig, - setShowIdeOnboarding, - setIDEInstallationState - } = t0; - let t1; - let t22; - if ($2[0] !== autoConnectIdeFlag || $2[1] !== ideToInstallExtension || $2[2] !== setDynamicMcpConfig || $2[3] !== setIDEInstallationState || $2[4] !== setShowIdeOnboarding) { - t1 = () => { - const addIde = function addIde2(ide2) { - if (!ide2) { - return; - } - const globalConfig2 = getGlobalConfig(); - const autoConnectEnabled = (globalConfig2.autoConnectIde || autoConnectIdeFlag || isSupportedTerminal() || process.env.CLAUDE_CODE_SSE_PORT || ideToInstallExtension || isEnvTruthy(process.env.CLAUDE_CODE_AUTO_CONNECT_IDE)) && !isEnvDefinedFalsy(process.env.CLAUDE_CODE_AUTO_CONNECT_IDE); - if (!autoConnectEnabled) { - return; - } - setDynamicMcpConfig((prev) => { - if (prev?.ide) { - return prev; - } - return { - ...prev, - ide: { - type: ide2.url.startsWith("ws:") ? "ws-ide" : "sse-ide", - url: ide2.url, - ideName: ide2.name, - authToken: ide2.authToken, - ideRunningInWindows: ide2.ideRunningInWindows, - scope: "dynamic" - } - }; - }); - }; - initializeIdeIntegration(addIde, ideToInstallExtension, () => setShowIdeOnboarding(true), (status2) => setIDEInstallationState(status2)); - }; - t22 = [autoConnectIdeFlag, ideToInstallExtension, setDynamicMcpConfig, setShowIdeOnboarding, setIDEInstallationState]; - $2[0] = autoConnectIdeFlag; - $2[1] = ideToInstallExtension; - $2[2] = setDynamicMcpConfig; - $2[3] = setIDEInstallationState; - $2[4] = setShowIdeOnboarding; - $2[5] = t1; - $2[6] = t22; - } else { - t1 = $2[5]; - t22 = $2[6]; - } - import_react286.useEffect(t1, t22); -} -var import_compiler_runtime343, import_react286; -var init_useIDEIntegration = __esm(() => { - init_config(); - init_envUtils(); - init_ide(); - import_compiler_runtime343 = __toESM(require_compiler_runtime(), 1); - import_react286 = __toESM(require_react(), 1); -}); - -// src/components/SessionBackgroundHint.tsx -function SessionBackgroundHint(t0) { - const $2 = import_compiler_runtime344.c(10); - const { - onBackgroundSession, - isLoading - } = t0; - const setAppState = useSetAppState(); - const appStateStore = useAppStateStore(); - const [showSessionHint, setShowSessionHint] = import_react287.useState(false); - const handleDoublePress = useDoublePress(setShowSessionHint, onBackgroundSession, _temp201); - let t1; - if ($2[0] !== appStateStore || $2[1] !== handleDoublePress || $2[2] !== isLoading || $2[3] !== setAppState) { - t1 = () => { - if (isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS)) { - return; - } - const state4 = appStateStore.getState(); - if (hasForegroundTasks(state4)) { - backgroundAll(() => appStateStore.getState(), setAppState); - if (!getGlobalConfig().hasUsedBackgroundTask) { - saveGlobalConfig(_temp283); - } - } else { - if (isEnvTruthy("false") && isLoading) { - handleDoublePress(); - } - } - }; - $2[0] = appStateStore; - $2[1] = handleDoublePress; - $2[2] = isLoading; - $2[3] = setAppState; - $2[4] = t1; - } else { - t1 = $2[4]; - } - const handleBackground = t1; - const hasForeground = useAppState(hasForegroundTasks); - let t22; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t22 = isEnvTruthy("false"); - $2[5] = t22; - } else { - t22 = $2[5]; - } - const sessionBgEnabled = t22; - const t32 = hasForeground || sessionBgEnabled && isLoading; - let t4; - if ($2[6] !== t32) { - t4 = { - context: "Task", - isActive: t32 - }; - $2[6] = t32; - $2[7] = t4; - } else { - t4 = $2[7]; - } - useKeybinding("task:background", handleBackground, t4); - const baseShortcut = useShortcutDisplay("task:background", "Task", "ctrl+b"); - const shortcut = env2.terminal === "tmux" && baseShortcut === "ctrl+b" ? "ctrl+b ctrl+b" : baseShortcut; - if (!isLoading || !showSessionHint) { - return null; - } - let t5; - if ($2[8] !== shortcut) { - t5 = /* @__PURE__ */ jsx_dev_runtime443.jsxDEV(ThemedBox_default, { - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime443.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime443.jsxDEV(KeyboardShortcutHint, { - shortcut, - action: "background" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[8] = shortcut; - $2[9] = t5; - } else { - t5 = $2[9]; - } - return t5; -} -function _temp283(c9) { - return c9.hasUsedBackgroundTask ? c9 : { - ...c9, - hasUsedBackgroundTask: true - }; -} -function _temp201() {} -var import_compiler_runtime344, import_react287, jsx_dev_runtime443; -var init_SessionBackgroundHint = __esm(() => { - init_useDoublePress(); - init_ink2(); - init_useKeybinding(); - init_useShortcutDisplay(); - init_AppState(); - init_LocalShellTask(); - init_config(); - init_env(); - init_envUtils(); - init_KeyboardShortcutHint(); - import_compiler_runtime344 = __toESM(require_compiler_runtime(), 1); - import_react287 = __toESM(require_react(), 1); - jsx_dev_runtime443 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useSessionBackgrounding.ts -function useSessionBackgrounding({ - setMessages, - setIsLoading, - resetLoadingState, - setAbortController, - onBackgroundQuery -}) { - const foregroundedTaskId = useAppState((s4) => s4.foregroundedTaskId); - const foregroundedTask = useAppState((s4) => s4.foregroundedTaskId ? s4.tasks[s4.foregroundedTaskId] : undefined); - const setAppState = useSetAppState(); - const lastSyncedMessagesLengthRef = import_react288.useRef(0); - const handleBackgroundSession = import_react288.useCallback(() => { - if (foregroundedTaskId) { - setAppState((prev) => { - const taskId = prev.foregroundedTaskId; - if (!taskId) - return prev; - const task = prev.tasks[taskId]; - if (!task) { - return { ...prev, foregroundedTaskId: undefined }; - } - return { - ...prev, - foregroundedTaskId: undefined, - tasks: { - ...prev.tasks, - [taskId]: { ...task, isBackgrounded: true } - } - }; - }); - setMessages([]); - resetLoadingState(); - setAbortController(null); - return; - } - onBackgroundQuery(); - }, [ - foregroundedTaskId, - setAppState, - setMessages, - resetLoadingState, - setAbortController, - onBackgroundQuery - ]); - import_react288.useEffect(() => { - if (!foregroundedTaskId) { - lastSyncedMessagesLengthRef.current = 0; - return; - } - if (!foregroundedTask || foregroundedTask.type !== "local_agent") { - setAppState((prev) => ({ ...prev, foregroundedTaskId: undefined })); - resetLoadingState(); - lastSyncedMessagesLengthRef.current = 0; - return; - } - const taskMessages = foregroundedTask.messages ?? []; - if (taskMessages.length !== lastSyncedMessagesLengthRef.current) { - lastSyncedMessagesLengthRef.current = taskMessages.length; - setMessages([...taskMessages]); - } - if (foregroundedTask.status === "running") { - const taskAbortController = foregroundedTask.abortController; - if (taskAbortController?.signal.aborted) { - setAppState((prev) => { - if (!prev.foregroundedTaskId) - return prev; - const task = prev.tasks[prev.foregroundedTaskId]; - if (!task) - return { ...prev, foregroundedTaskId: undefined }; - return { - ...prev, - foregroundedTaskId: undefined, - tasks: { - ...prev.tasks, - [prev.foregroundedTaskId]: { ...task, isBackgrounded: true } - } - }; - }); - resetLoadingState(); - setAbortController(null); - lastSyncedMessagesLengthRef.current = 0; - return; - } - setIsLoading(true); - if (taskAbortController) { - setAbortController(taskAbortController); - } - } else { - setAppState((prev) => { - const taskId = prev.foregroundedTaskId; - if (!taskId) - return prev; - const task = prev.tasks[taskId]; - if (!task) - return { ...prev, foregroundedTaskId: undefined }; - return { - ...prev, - foregroundedTaskId: undefined, - tasks: { ...prev.tasks, [taskId]: { ...task, isBackgrounded: true } } - }; - }); - resetLoadingState(); - setAbortController(null); - lastSyncedMessagesLengthRef.current = 0; - } - }, [ - foregroundedTaskId, - foregroundedTask, - setAppState, - setMessages, - setIsLoading, - resetLoadingState, - setAbortController - ]); - return { - handleBackgroundSession - }; -} -var import_react288; -var init_useSessionBackgrounding = __esm(() => { - init_AppState(); - import_react288 = __toESM(require_react(), 1); -}); - -// src/components/EffortCallout.tsx -function EffortCallout(t0) { - const $2 = import_compiler_runtime345.c(18); - const { - model, - onDone - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getOpusDefaultEffortConfig(); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const defaultEffortConfig = t1; - const onDoneRef = import_react289.useRef(onDone); - let t22; - if ($2[1] !== onDone) { - t22 = () => { - onDoneRef.current = onDone; - }; - $2[1] = onDone; - $2[2] = t22; - } else { - t22 = $2[2]; - } - import_react289.useEffect(t22); - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = () => { - onDoneRef.current("dismiss"); - }; - $2[3] = t32; - } else { - t32 = $2[3]; - } - const handleCancel = t32; - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = []; - $2[4] = t4; - } else { - t4 = $2[4]; - } - import_react289.useEffect(_temp202, t4); - let t5; - let t6; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t5 = () => { - const timeoutId = setTimeout(handleCancel, AUTO_DISMISS_MS); - return () => clearTimeout(timeoutId); - }; - t6 = [handleCancel]; - $2[5] = t5; - $2[6] = t6; - } else { - t5 = $2[5]; - t6 = $2[6]; - } - import_react289.useEffect(t5, t6); - let t7; - if ($2[7] !== model) { - const defaultEffort = getDefaultEffortForModel(model); - t7 = defaultEffort ? convertEffortValueToLevel(defaultEffort) : "high"; - $2[7] = model; - $2[8] = t7; - } else { - t7 = $2[8]; - } - const defaultLevel = t7; - let t8; - if ($2[9] !== defaultLevel) { - t8 = (value) => { - const effortLevel = value === defaultLevel ? undefined : value; - updateSettingsForSource("userSettings", { - effortLevel: toPersistableEffort(effortLevel) - }); - onDoneRef.current(value); - }; - $2[9] = defaultLevel; - $2[10] = t8; - } else { - t8 = $2[10]; - } - const handleSelect = t8; - let t9; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t9 = [{ - label: /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortOptionLabel, { - level: "medium", - text: "Medium (recommended)" - }, undefined, false, undefined, this), - value: "medium" - }, { - label: /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortOptionLabel, { - level: "high", - text: "High" - }, undefined, false, undefined, this), - value: "high" - }, { - label: /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortOptionLabel, { - level: "low", - text: "Low" - }, undefined, false, undefined, this), - value: "low" - }]; - $2[11] = t9; - } else { - t9 = $2[11]; - } - const options2 = t9; - let t10; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(ThemedText, { - children: defaultEffortConfig.dialogDescription - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[12] = t10; - } else { - t10 = $2[12]; - } - let t11; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t11 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortIndicatorSymbol, { - level: "low" - }, undefined, false, undefined, this); - $2[13] = t11; - } else { - t11 = $2[13]; - } - let t12; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortIndicatorSymbol, { - level: "medium" - }, undefined, false, undefined, this); - $2[14] = t12; - } else { - t12 = $2[14]; - } - let t13; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t13 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(ThemedText, { - dimColor: true, - children: [ - t11, - " low ", - "\xB7", - " ", - t12, - " medium ", - "\xB7", - " ", - /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortIndicatorSymbol, { - level: "high" - }, undefined, false, undefined, this), - " high" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[15] = t13; - } else { - t13 = $2[15]; - } - let t14; - if ($2[16] !== handleSelect) { - t14 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(PermissionDialog, { - title: defaultEffortConfig.dialogTitle, - children: /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - t10, - t13, - /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - onCancel: handleCancel - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[16] = handleSelect; - $2[17] = t14; - } else { - t14 = $2[17]; - } - return t14; -} -function _temp202() { - markV2Dismissed(); -} -function EffortIndicatorSymbol(t0) { - const $2 = import_compiler_runtime345.c(4); - const { - level - } = t0; - let t1; - if ($2[0] !== level) { - t1 = effortLevelToSymbol(level); - $2[0] = level; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(ThemedText, { - color: "suggestion", - children: t1 - }, undefined, false, undefined, this); - $2[2] = t1; - $2[3] = t22; - } else { - t22 = $2[3]; - } - return t22; -} -function EffortOptionLabel(t0) { - const $2 = import_compiler_runtime345.c(5); - const { - level, - text - } = t0; - let t1; - if ($2[0] !== level) { - t1 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(EffortIndicatorSymbol, { - level - }, undefined, false, undefined, this); - $2[0] = level; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== t1 || $2[3] !== text) { - t22 = /* @__PURE__ */ jsx_dev_runtime444.jsxDEV(jsx_dev_runtime444.Fragment, { - children: [ - t1, - " ", - text - ] - }, undefined, true, undefined, this); - $2[2] = t1; - $2[3] = text; - $2[4] = t22; - } else { - t22 = $2[4]; - } - return t22; -} -function shouldShowEffortCallout(model) { - const parsed = parseUserSpecifiedModel(model); - if (!parsed.toLowerCase().includes("opus-4-6")) { - return false; - } - const config10 = getGlobalConfig(); - if (config10.effortCalloutV2Dismissed) - return false; - if (config10.numStartups <= 1) { - markV2Dismissed(); - return false; - } - if (isProSubscriber()) { - if (config10.effortCalloutDismissed) { - markV2Dismissed(); - return false; - } - return getOpusDefaultEffortConfig().enabled; - } - if (isMaxSubscriber() || isTeamSubscriber()) { - return getOpusDefaultEffortConfig().enabled; - } - markV2Dismissed(); - return false; -} -function markV2Dismissed() { - saveGlobalConfig((current) => { - if (current.effortCalloutV2Dismissed) - return current; - return { - ...current, - effortCalloutV2Dismissed: true - }; - }); -} -var import_compiler_runtime345, import_react289, jsx_dev_runtime444, AUTO_DISMISS_MS = 30000; -var init_EffortCallout = __esm(() => { - init_ink2(); - init_auth14(); - init_config(); - init_effort(); - init_model(); - init_settings2(); - init_select(); - init_EffortIndicator(); - init_PermissionDialog(); - import_compiler_runtime345 = __toESM(require_compiler_runtime(), 1); - import_react289 = __toESM(require_react(), 1); - jsx_dev_runtime444 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/RemoteCallout.tsx -function RemoteCallout({ - onDone -}) { - const onDoneRef = import_react290.useRef(onDone); - onDoneRef.current = onDone; - const handleCancel = import_react290.useCallback(() => { - onDoneRef.current("dismiss"); - }, []); - import_react290.useEffect(() => { - saveGlobalConfig((current) => { - if (current.remoteDialogSeen) - return current; - return { - ...current, - remoteDialogSeen: true - }; - }); - }, []); - const handleSelect = import_react290.useCallback((value) => { - onDoneRef.current(value); - }, []); - const options2 = [{ - label: "Enable Remote Control for this session", - description: "Opens a secure connection to claude.ai.", - value: "enable" - }, { - label: "Never mind", - description: "You can always enable it later with /remote-control.", - value: "dismiss" - }]; - return /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(PermissionDialog, { - title: "Remote Control", - children: /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(ThemedBox_default, { - marginBottom: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(ThemedText, { - children: "Remote Control lets you access this CLI session from the web (claude.ai/code) or the Claude app, so you can pick up where you left off on any device." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(ThemedText, { - children: "You can disconnect remote access anytime by running /remote-control again." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime445.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - onCancel: handleCancel - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var import_react290, jsx_dev_runtime445; -var init_RemoteCallout = __esm(() => { - init_bridgeEnabled(); - init_ink2(); - init_auth14(); - init_config(); - init_select(); - init_PermissionDialog(); - import_react290 = __toESM(require_react(), 1); - jsx_dev_runtime445 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useDynamicConfig.ts -function useDynamicConfig(configName, defaultValue) { - const [configValue, setConfigValue] = import_react291.default.useState(defaultValue); - import_react291.default.useEffect(() => { - if (false) {} - getDynamicConfig_BLOCKS_ON_INIT(configName, defaultValue).then(setConfigValue); - }, [configName, defaultValue]); - return configValue; -} -var import_react291; -var init_useDynamicConfig = __esm(() => { - init_growthbook(); - import_react291 = __toESM(require_react(), 1); -}); - -// src/components/FeedbackSurvey/submitTranscriptShare.ts -import { readFile as readFile55, stat as stat46 } from "fs/promises"; -async function submitTranscriptShare(messages, trigger, appearanceId) { - try { - logForDebugging("Collecting transcript for sharing", { level: "info" }); - const transcript = normalizeMessagesForAPI(messages); - const agentIds = extractAgentIdsFromMessages(messages); - const subagentTranscripts = await loadSubagentTranscripts(agentIds); - let rawTranscriptJsonl; - try { - const transcriptPath = getTranscriptPath(); - const { size } = await stat46(transcriptPath); - if (size <= MAX_TRANSCRIPT_READ_BYTES) { - rawTranscriptJsonl = await readFile55(transcriptPath, "utf-8"); - } else { - logForDebugging(`Skipping raw transcript read: file too large (${size} bytes)`, { level: "warn" }); - } - } catch {} - const data = { - trigger, - version: MACRO.VERSION, - platform: process.platform, - transcript, - subagentTranscripts: Object.keys(subagentTranscripts).length > 0 ? subagentTranscripts : undefined, - rawTranscriptJsonl - }; - const content = redactSensitiveInfo(jsonStringify(data)); - await checkAndRefreshOAuthTokenIfNeeded(); - const authResult = getAuthHeaders2(); - if (authResult.error) { - return { success: false }; - } - const headers = { - "Content-Type": "application/json", - "User-Agent": getUserAgent(), - ...authResult.headers - }; - const response7 = await axios_default.post("https://api.anthropic.com/api/claude_code_shared_session_transcripts", { content, appearance_id: appearanceId }, { - headers, - timeout: 30000 - }); - if (response7.status === 200 || response7.status === 201) { - const result = response7.data; - logForDebugging("Transcript shared successfully", { level: "info" }); - return { - success: true, - transcriptId: result?.transcript_id - }; - } - return { success: false }; - } catch (err2) { - logForDebugging(errorMessage(err2), { - level: "error" - }); - return { success: false }; - } -} -var init_submitTranscriptShare = __esm(() => { - init_axios2(); - init_auth14(); - init_debug(); - init_errors(); - init_http8(); - init_messages9(); - init_sessionStorage(); - init_slowOperations(); - init_Feedback(); -}); - -// src/components/FeedbackSurvey/useSurveyState.tsx -import { randomUUID as randomUUID47 } from "crypto"; -function useSurveyState({ - hideThanksAfterMs, - onOpen, - onSelect, - shouldShowTranscriptPrompt, - onTranscriptPromptShown, - onTranscriptSelect -}) { - const [state4, setState] = import_react292.useState("closed"); - const [lastResponse, setLastResponse] = import_react292.useState(null); - const appearanceId = import_react292.useRef(randomUUID47()); - const lastResponseRef = import_react292.useRef(null); - const showThanksThenClose = import_react292.useCallback(() => { - setState("thanks"); - setTimeout((setState_0, setLastResponse_0) => { - setState_0("closed"); - setLastResponse_0(null); - }, hideThanksAfterMs, setState, setLastResponse); - }, [hideThanksAfterMs]); - const showSubmittedThenClose = import_react292.useCallback(() => { - setState("submitted"); - setTimeout(setState, hideThanksAfterMs, "closed"); - }, [hideThanksAfterMs]); - const open18 = import_react292.useCallback(() => { - if (state4 !== "closed") { - return; - } - setState("open"); - appearanceId.current = randomUUID47(); - onOpen(appearanceId.current); - }, [state4, onOpen]); - const handleSelect = import_react292.useCallback((selected) => { - setLastResponse(selected); - lastResponseRef.current = selected; - onSelect(appearanceId.current, selected); - if (selected === "dismissed") { - setState("closed"); - setLastResponse(null); - } else if (shouldShowTranscriptPrompt?.(selected)) { - setState("transcript_prompt"); - onTranscriptPromptShown?.(appearanceId.current, selected); - return true; - } else { - showThanksThenClose(); - } - return false; - }, [showThanksThenClose, onSelect, shouldShowTranscriptPrompt, onTranscriptPromptShown]); - const handleTranscriptSelect = import_react292.useCallback((selected_0) => { - switch (selected_0) { - case "yes": - setState("submitting"); - (async () => { - try { - const success2 = await onTranscriptSelect?.(appearanceId.current, selected_0, lastResponseRef.current); - if (success2) { - showSubmittedThenClose(); - } else { - showThanksThenClose(); - } - } catch { - showThanksThenClose(); - } - })(); - break; - case "no": - case "dont_ask_again": - onTranscriptSelect?.(appearanceId.current, selected_0, lastResponseRef.current); - showThanksThenClose(); - break; - } - }, [showThanksThenClose, showSubmittedThenClose, onTranscriptSelect]); - return { - state: state4, - lastResponse, - open: open18, - handleSelect, - handleTranscriptSelect - }; -} -var import_react292; -var init_useSurveyState = __esm(() => { - import_react292 = __toESM(require_react(), 1); -}); - -// src/components/FeedbackSurvey/useFeedbackSurvey.tsx -function useFeedbackSurvey(messages, isLoading, submitCount, surveyType = "session", hasActivePrompt = false) { - const lastAssistantMessageIdRef = import_react293.useRef("unknown"); - lastAssistantMessageIdRef.current = getLastAssistantMessage(messages)?.message?.id || "unknown"; - const [feedbackSurvey, setFeedbackSurvey] = import_react293.useState(() => ({ - timeLastShown: null, - submitCountAtLastAppearance: null - })); - const config10 = useDynamicConfig("tengu_feedback_survey_config", DEFAULT_FEEDBACK_SURVEY_CONFIG); - const badTranscriptAskConfig = useDynamicConfig("tengu_bad_survey_transcript_ask_config", DEFAULT_TRANSCRIPT_ASK_CONFIG); - const goodTranscriptAskConfig = useDynamicConfig("tengu_good_survey_transcript_ask_config", DEFAULT_TRANSCRIPT_ASK_CONFIG); - const settingsRate = getInitialSettings().feedbackSurveyRate; - const sessionStartTime = import_react293.useRef(Date.now()); - const submitCountAtSessionStart = import_react293.useRef(submitCount); - const submitCountRef = import_react293.useRef(submitCount); - submitCountRef.current = submitCount; - const messagesRef = import_react293.useRef(messages); - messagesRef.current = messages; - const probabilityPassedRef = import_react293.useRef(false); - const lastEligibleSubmitCountRef = import_react293.useRef(null); - const updateLastShownTime = import_react293.useCallback((timestamp, submitCountValue) => { - setFeedbackSurvey((prev) => { - if (prev.timeLastShown === timestamp && prev.submitCountAtLastAppearance === submitCountValue) { - return prev; - } - return { - timeLastShown: timestamp, - submitCountAtLastAppearance: submitCountValue - }; - }); - if (getGlobalConfig().feedbackSurveyState?.lastShownTime !== timestamp) { - saveGlobalConfig((current) => ({ - ...current, - feedbackSurveyState: { - lastShownTime: timestamp - } - })); - } - }, []); - const onOpen = import_react293.useCallback((appearanceId) => { - updateLastShownTime(Date.now(), submitCountRef.current); - logEvent("tengu_feedback_survey_event", { - event_type: "appeared", - appearance_id: appearanceId, - last_assistant_message_id: lastAssistantMessageIdRef.current, - survey_type: surveyType - }); - logOTelEvent("feedback_survey", { - event_type: "appeared", - appearance_id: appearanceId, - survey_type: surveyType - }); - }, [updateLastShownTime, surveyType]); - const onSelect = import_react293.useCallback((appearanceId_0, selected) => { - updateLastShownTime(Date.now(), submitCountRef.current); - logEvent("tengu_feedback_survey_event", { - event_type: "responded", - appearance_id: appearanceId_0, - response: selected, - last_assistant_message_id: lastAssistantMessageIdRef.current, - survey_type: surveyType - }); - logOTelEvent("feedback_survey", { - event_type: "responded", - appearance_id: appearanceId_0, - response: selected, - survey_type: surveyType - }); - }, [updateLastShownTime, surveyType]); - const shouldShowTranscriptPrompt = import_react293.useCallback((selected_0) => { - if (selected_0 !== "bad" && selected_0 !== "good") { - return false; - } - if (getGlobalConfig().transcriptShareDismissed) { - return false; - } - if (!isPolicyAllowed("allow_product_feedback")) { - return false; - } - const probability = selected_0 === "bad" ? badTranscriptAskConfig.probability : goodTranscriptAskConfig.probability; - return Math.random() <= probability; - }, [badTranscriptAskConfig.probability, goodTranscriptAskConfig.probability]); - const onTranscriptPromptShown = import_react293.useCallback((appearanceId_1, surveyResponse) => { - const trigger = surveyResponse === "good" ? "good_feedback_survey" : "bad_feedback_survey"; - logEvent("tengu_feedback_survey_event", { - event_type: "transcript_prompt_appeared", - appearance_id: appearanceId_1, - last_assistant_message_id: lastAssistantMessageIdRef.current, - survey_type: surveyType, - trigger - }); - logOTelEvent("feedback_survey", { - event_type: "transcript_prompt_appeared", - appearance_id: appearanceId_1, - survey_type: surveyType - }); - }, [surveyType]); - const onTranscriptSelect = import_react293.useCallback(async (appearanceId_2, selected_1, surveyResponse_0) => { - const trigger_0 = surveyResponse_0 === "good" ? "good_feedback_survey" : "bad_feedback_survey"; - logEvent("tengu_feedback_survey_event", { - event_type: `transcript_share_${selected_1}`, - appearance_id: appearanceId_2, - last_assistant_message_id: lastAssistantMessageIdRef.current, - survey_type: surveyType, - trigger: trigger_0 - }); - if (selected_1 === "dont_ask_again") { - saveGlobalConfig((current_0) => ({ - ...current_0, - transcriptShareDismissed: true - })); - } - if (selected_1 === "yes") { - const result = await submitTranscriptShare(messagesRef.current, trigger_0, appearanceId_2); - logEvent("tengu_feedback_survey_event", { - event_type: result.success ? "transcript_share_submitted" : "transcript_share_failed", - appearance_id: appearanceId_2, - trigger: trigger_0 - }); - return result.success; - } - return false; - }, [surveyType]); - const { - state: state4, - lastResponse, - open: open18, - handleSelect, - handleTranscriptSelect - } = useSurveyState({ - hideThanksAfterMs: config10.hideThanksAfterMs, - onOpen, - onSelect, - shouldShowTranscriptPrompt, - onTranscriptPromptShown, - onTranscriptSelect - }); - const currentModel = getMainLoopModel(); - const isModelAllowed2 = import_react293.useMemo(() => { - if (config10.onForModels.length === 0) { - return false; - } - if (config10.onForModels.includes("*")) { - return true; - } - return config10.onForModels.includes(currentModel); - }, [config10.onForModels, currentModel]); - const shouldOpen = import_react293.useMemo(() => { - if (state4 !== "closed") { - return false; - } - if (isLoading) { - return false; - } - if (hasActivePrompt) { - return false; - } - if (process.env.CLAUDE_FORCE_DISPLAY_SURVEY && !feedbackSurvey.timeLastShown) { - return true; - } - if (!isModelAllowed2) { - return false; - } - if (isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY)) { - return false; - } - if (isFeedbackSurveyDisabled()) { - return false; - } - if (!isPolicyAllowed("allow_product_feedback")) { - return false; - } - if (feedbackSurvey.timeLastShown) { - const timeSinceLastShown = Date.now() - feedbackSurvey.timeLastShown; - if (timeSinceLastShown < config10.minTimeBetweenFeedbackMs) { - return false; - } - if (feedbackSurvey.submitCountAtLastAppearance !== null && submitCount < feedbackSurvey.submitCountAtLastAppearance + config10.minUserTurnsBetweenFeedback) { - return false; - } - } else { - const timeSinceSessionStart = Date.now() - sessionStartTime.current; - if (timeSinceSessionStart < config10.minTimeBeforeFeedbackMs) { - return false; - } - if (submitCount < submitCountAtSessionStart.current + config10.minUserTurnsBeforeFeedback) { - return false; - } - } - if (lastEligibleSubmitCountRef.current !== submitCount) { - lastEligibleSubmitCountRef.current = submitCount; - probabilityPassedRef.current = Math.random() <= (settingsRate ?? config10.probability); - } - if (!probabilityPassedRef.current) { - return false; - } - const globalFeedbackState = getGlobalConfig().feedbackSurveyState; - if (globalFeedbackState?.lastShownTime) { - const timeSinceGlobalLastShown = Date.now() - globalFeedbackState.lastShownTime; - if (timeSinceGlobalLastShown < config10.minTimeBetweenGlobalFeedbackMs) { - return false; - } - } - return true; - }, [state4, isLoading, hasActivePrompt, isModelAllowed2, feedbackSurvey.timeLastShown, feedbackSurvey.submitCountAtLastAppearance, submitCount, config10.minTimeBetweenFeedbackMs, config10.minTimeBetweenGlobalFeedbackMs, config10.minUserTurnsBetweenFeedback, config10.minTimeBeforeFeedbackMs, config10.minUserTurnsBeforeFeedback, config10.probability, settingsRate]); - import_react293.useEffect(() => { - if (shouldOpen) { - open18(); - } - }, [shouldOpen, open18]); - return { - state: state4, - lastResponse, - handleSelect, - handleTranscriptSelect - }; -} -var import_react293, DEFAULT_FEEDBACK_SURVEY_CONFIG, DEFAULT_TRANSCRIPT_ASK_CONFIG; -var init_useFeedbackSurvey = __esm(() => { - init_useDynamicConfig(); - init_config8(); - init_analytics(); - init_policyLimits(); - init_config(); - init_envUtils(); - init_messages9(); - init_model(); - init_settings2(); - init_events(); - init_submitTranscriptShare(); - init_useSurveyState(); - import_react293 = __toESM(require_react(), 1); - DEFAULT_FEEDBACK_SURVEY_CONFIG = { - minTimeBeforeFeedbackMs: 600000, - minTimeBetweenFeedbackMs: 3600000, - minTimeBetweenGlobalFeedbackMs: 1e8, - minUserTurnsBeforeFeedback: 5, - minUserTurnsBetweenFeedback: 10, - hideThanksAfterMs: 3000, - onForModels: ["*"], - probability: 0.005 - }; - DEFAULT_TRANSCRIPT_ASK_CONFIG = { - probability: 0 - }; -}); - -// src/components/FeedbackSurvey/useMemorySurvey.tsx -function hasMemoryFileRead(messages) { - 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" || block2.name !== FILE_READ_TOOL_NAME) { - continue; - } - const input = block2.input; - if (typeof input.file_path === "string" && isAutoManagedMemoryFile(input.file_path)) { - return true; - } - } - } - return false; -} -function useMemorySurvey(messages, isLoading, hasActivePrompt = false, { - enabled: enabled2 = true -} = {}) { - const seenAssistantUuids = import_react294.useRef(new Set); - const memoryReadSeen = import_react294.useRef(false); - const messagesRef = import_react294.useRef(messages); - messagesRef.current = messages; - const onOpen = import_react294.useCallback((appearanceId) => { - logEvent(MEMORY_SURVEY_EVENT, { - event_type: "appeared", - appearance_id: appearanceId - }); - logOTelEvent("feedback_survey", { - event_type: "appeared", - appearance_id: appearanceId, - survey_type: "memory" - }); - }, []); - const onSelect = import_react294.useCallback((appearanceId_0, selected) => { - logEvent(MEMORY_SURVEY_EVENT, { - event_type: "responded", - appearance_id: appearanceId_0, - response: selected - }); - logOTelEvent("feedback_survey", { - event_type: "responded", - appearance_id: appearanceId_0, - response: selected, - survey_type: "memory" - }); - }, []); - const shouldShowTranscriptPrompt = import_react294.useCallback((selected_0) => { - if (true) { - return false; - } - if (selected_0 !== "bad" && selected_0 !== "good") { - return false; - } - if (getGlobalConfig().transcriptShareDismissed) { - return false; - } - if (!isPolicyAllowed("allow_product_feedback")) { - return false; - } - return true; - }, []); - const onTranscriptPromptShown = import_react294.useCallback((appearanceId_1) => { - logEvent(MEMORY_SURVEY_EVENT, { - event_type: "transcript_prompt_appeared", - appearance_id: appearanceId_1, - trigger: TRANSCRIPT_SHARE_TRIGGER - }); - logOTelEvent("feedback_survey", { - event_type: "transcript_prompt_appeared", - appearance_id: appearanceId_1, - survey_type: "memory" - }); - }, []); - const onTranscriptSelect = import_react294.useCallback(async (appearanceId_2, selected_1) => { - logEvent(MEMORY_SURVEY_EVENT, { - event_type: `transcript_share_${selected_1}`, - appearance_id: appearanceId_2, - trigger: TRANSCRIPT_SHARE_TRIGGER - }); - if (selected_1 === "dont_ask_again") { - saveGlobalConfig((current) => ({ - ...current, - transcriptShareDismissed: true - })); - } - if (selected_1 === "yes") { - const result = await submitTranscriptShare(messagesRef.current, TRANSCRIPT_SHARE_TRIGGER, appearanceId_2); - logEvent(MEMORY_SURVEY_EVENT, { - event_type: result.success ? "transcript_share_submitted" : "transcript_share_failed", - appearance_id: appearanceId_2, - trigger: TRANSCRIPT_SHARE_TRIGGER - }); - return result.success; - } - return false; - }, []); - const { - state: state4, - lastResponse, - open: open18, - handleSelect, - handleTranscriptSelect - } = useSurveyState({ - hideThanksAfterMs: HIDE_THANKS_AFTER_MS, - onOpen, - onSelect, - shouldShowTranscriptPrompt, - onTranscriptPromptShown, - onTranscriptSelect - }); - const lastAssistant = import_react294.useMemo(() => getLastAssistantMessage(messages), [messages]); - import_react294.useEffect(() => { - if (!enabled2) - return; - if (messages.length === 0) { - memoryReadSeen.current = false; - seenAssistantUuids.current.clear(); - return; - } - if (state4 !== "closed" || isLoading || hasActivePrompt) { - return; - } - if (!getFeatureValue_CACHED_MAY_BE_STALE(MEMORY_SURVEY_GATE, false)) { - return; - } - if (!isAutoMemoryEnabled()) { - return; - } - if (isFeedbackSurveyDisabled()) { - return; - } - if (!isPolicyAllowed("allow_product_feedback")) { - return; - } - if (isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY)) { - return; - } - if (!lastAssistant || seenAssistantUuids.current.has(lastAssistant.uuid)) { - return; - } - const text = extractTextContent(lastAssistant.message.content, " "); - if (!MEMORY_WORD_RE.test(text)) { - return; - } - seenAssistantUuids.current.add(lastAssistant.uuid); - if (!memoryReadSeen.current) { - memoryReadSeen.current = hasMemoryFileRead(messages); - } - if (!memoryReadSeen.current) { - return; - } - if (Math.random() < SURVEY_PROBABILITY) { - open18(); - } - }, [enabled2, state4, isLoading, hasActivePrompt, lastAssistant, messages, open18]); - return { - state: state4, - lastResponse, - handleSelect, - handleTranscriptSelect - }; -} -var import_react294, HIDE_THANKS_AFTER_MS = 3000, MEMORY_SURVEY_GATE = "tengu_dunwich_bell", MEMORY_SURVEY_EVENT = "tengu_memory_survey_event", SURVEY_PROBABILITY = 0.2, TRANSCRIPT_SHARE_TRIGGER = "memory_survey", MEMORY_WORD_RE; -var init_useMemorySurvey = __esm(() => { - init_config8(); - init_growthbook(); - init_analytics(); - init_paths(); - init_policyLimits(); - init_prompt2(); - init_config(); - init_envUtils(); - init_memoryFileDetection(); - init_messages9(); - init_events(); - init_submitTranscriptShare(); - init_useSurveyState(); - import_react294 = __toESM(require_react(), 1); - MEMORY_WORD_RE = /\bmemor(?:y|ies)\b/i; -}); - -// src/components/FeedbackSurvey/usePostCompactSurvey.tsx -function hasMessageAfterBoundary(messages, boundaryUuid) { - const boundaryIndex = messages.findIndex((msg) => msg.uuid === boundaryUuid); - if (boundaryIndex === -1) { - return false; - } - for (let i6 = boundaryIndex + 1;i6 < messages.length; i6++) { - const msg = messages[i6]; - if (msg && (msg.type === "user" || msg.type === "assistant")) { - return true; - } - } - return false; -} -function usePostCompactSurvey(messages, isLoading, t0, t1) { - const $2 = import_compiler_runtime346.c(23); - const hasActivePrompt = t0 === undefined ? false : t0; - let t22; - if ($2[0] !== t1) { - t22 = t1 === undefined ? {} : t1; - $2[0] = t1; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const { - enabled: t32 - } = t22; - const enabled2 = t32 === undefined ? true : t32; - const [gateEnabled, setGateEnabled] = import_react295.useState(null); - let t4; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t4 = new Set; - $2[2] = t4; - } else { - t4 = $2[2]; - } - const seenCompactBoundaries = import_react295.useRef(t4); - const pendingCompactBoundaryUuid = import_react295.useRef(null); - const onOpen = _temp203; - const onSelect = _temp284; - let t5; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t5 = { - hideThanksAfterMs: HIDE_THANKS_AFTER_MS2, - onOpen, - onSelect - }; - $2[3] = t5; - } else { - t5 = $2[3]; - } - const { - state: state4, - lastResponse, - open: open18, - handleSelect - } = useSurveyState(t5); - let t6; - let t7; - if ($2[4] !== enabled2) { - t6 = () => { - if (!enabled2) { - return; - } - setGateEnabled(checkStatsigFeatureGate_CACHED_MAY_BE_STALE(POST_COMPACT_SURVEY_GATE)); - }; - t7 = [enabled2]; - $2[4] = enabled2; - $2[5] = t6; - $2[6] = t7; - } else { - t6 = $2[5]; - t7 = $2[6]; - } - import_react295.useEffect(t6, t7); - let t8; - if ($2[7] !== messages) { - t8 = new Set(messages.filter(_temp354).map(_temp440)); - $2[7] = messages; - $2[8] = t8; - } else { - t8 = $2[8]; - } - const currentCompactBoundaries = t8; - let t10; - let t9; - if ($2[9] !== currentCompactBoundaries || $2[10] !== enabled2 || $2[11] !== gateEnabled || $2[12] !== hasActivePrompt || $2[13] !== isLoading || $2[14] !== messages || $2[15] !== open18 || $2[16] !== state4) { - t9 = () => { - if (!enabled2) { - return; - } - if (state4 !== "closed" || isLoading) { - return; - } - if (hasActivePrompt) { - return; - } - if (gateEnabled !== true) { - return; - } - if (isFeedbackSurveyDisabled()) { - return; - } - if (isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY)) { - return; - } - if (pendingCompactBoundaryUuid.current !== null) { - if (hasMessageAfterBoundary(messages, pendingCompactBoundaryUuid.current)) { - pendingCompactBoundaryUuid.current = null; - if (Math.random() < SURVEY_PROBABILITY2) { - open18(); - } - return; - } - } - const newBoundaries = Array.from(currentCompactBoundaries).filter((uuid8) => !seenCompactBoundaries.current.has(uuid8)); - if (newBoundaries.length > 0) { - seenCompactBoundaries.current = new Set(currentCompactBoundaries); - pendingCompactBoundaryUuid.current = newBoundaries[newBoundaries.length - 1]; - } - }; - t10 = [enabled2, currentCompactBoundaries, state4, isLoading, hasActivePrompt, gateEnabled, messages, open18]; - $2[9] = currentCompactBoundaries; - $2[10] = enabled2; - $2[11] = gateEnabled; - $2[12] = hasActivePrompt; - $2[13] = isLoading; - $2[14] = messages; - $2[15] = open18; - $2[16] = state4; - $2[17] = t10; - $2[18] = t9; - } else { - t10 = $2[17]; - t9 = $2[18]; - } - import_react295.useEffect(t9, t10); - let t11; - if ($2[19] !== handleSelect || $2[20] !== lastResponse || $2[21] !== state4) { - t11 = { - state: state4, - lastResponse, - handleSelect - }; - $2[19] = handleSelect; - $2[20] = lastResponse; - $2[21] = state4; - $2[22] = t11; - } else { - t11 = $2[22]; - } - return t11; -} -function _temp440(msg_0) { - return msg_0.uuid; -} -function _temp354(msg) { - return isCompactBoundaryMessage(msg); -} -function _temp284(appearanceId_0, selected) { - const smCompactionEnabled_0 = shouldUseSessionMemoryCompaction(); - logEvent("tengu_post_compact_survey_event", { - event_type: "responded", - appearance_id: appearanceId_0, - response: selected, - session_memory_compaction_enabled: smCompactionEnabled_0 - }); - logOTelEvent("feedback_survey", { - event_type: "responded", - appearance_id: appearanceId_0, - response: selected, - survey_type: "post_compact" - }); -} -function _temp203(appearanceId) { - const smCompactionEnabled = shouldUseSessionMemoryCompaction(); - logEvent("tengu_post_compact_survey_event", { - event_type: "appeared", - appearance_id: appearanceId, - session_memory_compaction_enabled: smCompactionEnabled - }); - logOTelEvent("feedback_survey", { - event_type: "appeared", - appearance_id: appearanceId, - survey_type: "post_compact" - }); -} -var import_compiler_runtime346, import_react295, HIDE_THANKS_AFTER_MS2 = 3000, POST_COMPACT_SURVEY_GATE = "tengu_post_compact_survey", SURVEY_PROBABILITY2 = 0.2; -var init_usePostCompactSurvey = __esm(() => { - init_config8(); - init_growthbook(); - init_analytics(); - init_sessionMemoryCompact(); - init_envUtils(); - init_messages9(); - init_events(); - init_useSurveyState(); - import_compiler_runtime346 = __toESM(require_compiler_runtime(), 1); - import_react295 = __toESM(require_react(), 1); -}); - -// src/components/FeedbackSurvey/TranscriptSharePrompt.tsx -function TranscriptSharePrompt(t0) { - const $2 = import_compiler_runtime347.c(11); - const { - onSelect, - inputValue, - setInputValue - } = t0; - let t1; - if ($2[0] !== onSelect) { - t1 = (digit) => onSelect(inputToResponse2[digit]); - $2[0] = onSelect; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== inputValue || $2[3] !== setInputValue || $2[4] !== t1) { - t22 = { - inputValue, - setInputValue, - isValidDigit: isValidResponseInput2, - onDigit: t1 - }; - $2[2] = inputValue; - $2[3] = setInputValue; - $2[4] = t1; - $2[5] = t22; - } else { - t22 = $2[5]; - } - useDebouncedDigitInput(t22); - let t32; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: [ - BLACK_CIRCLE, - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - bold: true, - children: "Can Anthropic look at your session transcript to help us improve Claude Code?" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = t32; - } else { - t32 = $2[6]; - } - let t4; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - dimColor: true, - children: "Learn more: https://code.claude.com/docs/en/data-usage#session-quality-surveys" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - width: 10, - children: /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "1" - }, undefined, false, undefined, this), - ": Yes" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - width: 10, - children: /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "2" - }, undefined, false, undefined, this), - ": No" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t32, - t4, - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: [ - t5, - t6, - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime446.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "3" - }, undefined, false, undefined, this), - ": Don't ask again" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[10] = t7; - } else { - t7 = $2[10]; - } - return t7; -} -var import_compiler_runtime347, jsx_dev_runtime446, RESPONSE_INPUTS2, inputToResponse2, isValidResponseInput2 = (input) => RESPONSE_INPUTS2.includes(input); -var init_TranscriptSharePrompt = __esm(() => { - init_figures2(); - init_ink2(); - init_useDebouncedDigitInput(); - import_compiler_runtime347 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime446 = __toESM(require_jsx_dev_runtime(), 1); - RESPONSE_INPUTS2 = ["1", "2", "3"]; - inputToResponse2 = { - "1": "yes", - "2": "no", - "3": "dont_ask_again" - }; -}); - -// src/components/FeedbackSurvey/FeedbackSurvey.tsx -function FeedbackSurvey(t0) { - const $2 = import_compiler_runtime348.c(16); - const { - state: state4, - lastResponse, - handleSelect, - handleTranscriptSelect, - inputValue, - setInputValue, - onRequestFeedback, - message - } = t0; - if (state4 === "closed") { - return null; - } - if (state4 === "thanks") { - let t12; - if ($2[0] !== inputValue || $2[1] !== lastResponse || $2[2] !== onRequestFeedback || $2[3] !== setInputValue) { - t12 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(FeedbackSurveyThanks, { - lastResponse, - inputValue, - setInputValue, - onRequestFeedback - }, undefined, false, undefined, this); - $2[0] = inputValue; - $2[1] = lastResponse; - $2[2] = onRequestFeedback; - $2[3] = setInputValue; - $2[4] = t12; - } else { - t12 = $2[4]; - } - return t12; - } - if (state4 === "submitted") { - let t12; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - color: "success", - children: [ - "\u2713", - " Thanks for sharing your transcript!" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[5] = t12; - } else { - t12 = $2[5]; - } - return t12; - } - if (state4 === "submitting") { - let t12; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Sharing transcript", - "\u2026" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[6] = t12; - } else { - t12 = $2[6]; - } - return t12; - } - if (state4 === "transcript_prompt") { - if (!handleTranscriptSelect) { - return null; - } - if (inputValue && !["1", "2", "3"].includes(inputValue)) { - return null; - } - let t12; - if ($2[7] !== handleTranscriptSelect || $2[8] !== inputValue || $2[9] !== setInputValue) { - t12 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(TranscriptSharePrompt, { - onSelect: handleTranscriptSelect, - inputValue, - setInputValue - }, undefined, false, undefined, this); - $2[7] = handleTranscriptSelect; - $2[8] = inputValue; - $2[9] = setInputValue; - $2[10] = t12; - } else { - t12 = $2[10]; - } - return t12; - } - if (inputValue && !isValidResponseInput(inputValue)) { - return null; - } - let t1; - if ($2[11] !== handleSelect || $2[12] !== inputValue || $2[13] !== message || $2[14] !== setInputValue) { - t1 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(FeedbackSurveyView, { - onSelect: handleSelect, - inputValue, - setInputValue, - message - }, undefined, false, undefined, this); - $2[11] = handleSelect; - $2[12] = inputValue; - $2[13] = message; - $2[14] = setInputValue; - $2[15] = t1; - } else { - t1 = $2[15]; - } - return t1; -} -function FeedbackSurveyThanks(t0) { - const $2 = import_compiler_runtime348.c(12); - const { - lastResponse, - inputValue, - setInputValue, - onRequestFeedback - } = t0; - const showFollowUp = onRequestFeedback && lastResponse === "good"; - const t1 = Boolean(showFollowUp); - let t22; - if ($2[0] !== lastResponse || $2[1] !== onRequestFeedback) { - t22 = () => { - logEvent("tengu_feedback_survey_event", { - event_type: "followup_accepted", - response: lastResponse - }); - onRequestFeedback?.(); - }; - $2[0] = lastResponse; - $2[1] = onRequestFeedback; - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== inputValue || $2[4] !== setInputValue || $2[5] !== t1 || $2[6] !== t22) { - t32 = { - inputValue, - setInputValue, - isValidDigit: isFollowUpDigit, - enabled: t1, - once: true, - onDigit: t22 - }; - $2[3] = inputValue; - $2[4] = setInputValue; - $2[5] = t1; - $2[6] = t22; - $2[7] = t32; - } else { - t32 = $2[7]; - } - useDebouncedDigitInput(t32); - const feedbackCommand = "/feedback"; - let t4; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - color: "success", - children: "Thanks for the feedback!" - }, undefined, false, undefined, this); - $2[8] = t4; - } else { - t4 = $2[8]; - } - let t5; - if ($2[9] !== lastResponse || $2[10] !== showFollowUp) { - t5 = /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedBox_default, { - marginTop: 1, - flexDirection: "column", - children: [ - t4, - showFollowUp ? /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "(Optional) Press [", - /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - color: "ansi:cyan", - children: "1" - }, undefined, false, undefined, this), - "] to tell us what went well ", - " \xB7 ", - feedbackCommand - ] - }, undefined, true, undefined, this) : lastResponse === "bad" ? /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - dimColor: true, - children: "Use /issue to report model behavior issues." - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime447.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Use ", - feedbackCommand, - " to share detailed feedback anytime." - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[9] = lastResponse; - $2[10] = showFollowUp; - $2[11] = t5; - } else { - t5 = $2[11]; - } - return t5; -} -var import_compiler_runtime348, jsx_dev_runtime447, isFollowUpDigit = (char) => char === "1"; -var init_FeedbackSurvey = __esm(() => { - init_analytics(); - init_ink2(); - init_FeedbackSurveyView(); - init_TranscriptSharePrompt(); - init_useDebouncedDigitInput(); - import_compiler_runtime348 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime447 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/notifs/useStartupNotification.ts -function useStartupNotification(compute) { - const { addNotification } = useNotifications(); - const hasRunRef = import_react296.useRef(false); - const computeRef = import_react296.useRef(compute); - computeRef.current = compute; - import_react296.useEffect(() => { - if (getIsRemoteMode() || hasRunRef.current) - return; - hasRunRef.current = true; - Promise.resolve().then(() => computeRef.current()).then((result) => { - if (!result) - return; - for (const n6 of Array.isArray(result) ? result : [result]) { - addNotification(n6); - } - }).catch(logError2); - }, [addNotification]); -} -var import_react296; -var init_useStartupNotification = __esm(() => { - init_state(); - init_notifications(); - init_log2(); - import_react296 = __toESM(require_react(), 1); -}); - -// src/hooks/notifs/useInstallMessages.tsx -function useInstallMessages() { - useStartupNotification(_temp285); -} -async function _temp285() { - const messages = await checkInstall(); - return messages.map(_temp204); -} -function _temp204(message, index2) { - let priority = "low"; - if (message.type === "error" || message.userActionRequired) { - priority = "high"; - } else { - if (message.type === "path" || message.type === "alias") { - priority = "medium"; - } - } - return { - key: `install-message-${index2}-${message.type}`, - text: message.message, - priority, - color: message.type === "error" ? "error" : "warning" - }; -} -var init_useInstallMessages = __esm(() => { - init_nativeInstaller(); - init_useStartupNotification(); -}); - -// src/services/awaySummary.ts -var init_awaySummary = __esm(() => { - init_Tool(); - init_debug(); - init_messages9(); - init_model(); - init_claude(); - init_sessionMemoryUtils(); -}); - -// src/hooks/useAwaySummary.ts -var import_react297, BLUR_DELAY_MS; -var init_useAwaySummary = __esm(() => { - init_terminal_focus_state(); - init_growthbook(); - init_awaySummary(); - init_messages9(); - import_react297 = __toESM(require_react(), 1); - BLUR_DELAY_MS = 5 * 60000; -}); - -// src/hooks/useChromeExtensionNotification.tsx -function getChromeFlag() { - if (process.argv.includes("--chrome")) { - return true; - } - if (process.argv.includes("--no-chrome")) { - return false; - } - return; -} -function useChromeExtensionNotification() { - useStartupNotification(_temp205); -} -async function _temp205() { - const chromeFlag = getChromeFlag(); - if (!shouldEnableClaudeInChrome(chromeFlag)) { - return null; - } - if (!isClaudeAISubscriber()) { - return { - key: "chrome-requires-subscription", - jsx: /* @__PURE__ */ jsx_dev_runtime448.jsxDEV(ThemedText, { - color: "error", - children: "Claude in Chrome requires a claude.ai subscription" - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 5000 - }; - } - const installed = await isChromeExtensionInstalled(); - if (!installed && !isRunningOnHomespace()) { - return { - key: "chrome-extension-not-detected", - jsx: /* @__PURE__ */ jsx_dev_runtime448.jsxDEV(ThemedText, { - color: "warning", - children: "Chrome extension not detected \xB7 https://claude.ai/chrome to install" - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 3000 - }; - } - if (chromeFlag === undefined) { - return { - key: "claude-in-chrome-default-enabled", - text: "Claude in Chrome enabled \xB7 /chrome", - priority: "low" - }; - } - return null; -} -var jsx_dev_runtime448; -var init_useChromeExtensionNotification = __esm(() => { - init_ink2(); - init_auth14(); - init_setup2(); - init_envUtils(); - init_useStartupNotification(); - jsx_dev_runtime448 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/plugins/officialMarketplaceStartupCheck.ts -import { join as join147 } from "path"; -function isOfficialMarketplaceAutoInstallDisabled() { - return isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL); -} -function calculateNextRetryDelay(retryCount) { - const delay4 = RETRY_CONFIG.INITIAL_DELAY_MS * Math.pow(RETRY_CONFIG.BACKOFF_MULTIPLIER, retryCount); - return Math.min(delay4, RETRY_CONFIG.MAX_DELAY_MS); -} -function shouldRetryInstallation(config10) { - if (!config10.officialMarketplaceAutoInstallAttempted) { - return true; - } - if (config10.officialMarketplaceAutoInstalled) { - return false; - } - const failReason = config10.officialMarketplaceAutoInstallFailReason; - const retryCount = config10.officialMarketplaceAutoInstallRetryCount || 0; - const nextRetryTime = config10.officialMarketplaceAutoInstallNextRetryTime; - const now2 = Date.now(); - if (retryCount >= RETRY_CONFIG.MAX_ATTEMPTS) { - return false; - } - if (failReason === "policy_blocked") { - return false; - } - if (nextRetryTime && now2 < nextRetryTime) { - return false; - } - return failReason === "unknown" || failReason === "git_unavailable" || failReason === "gcs_unavailable" || failReason === undefined; -} -async function checkAndInstallOfficialMarketplace() { - const config10 = getGlobalConfig(); - if (!shouldRetryInstallation(config10)) { - const reason = config10.officialMarketplaceAutoInstallFailReason ?? "already_attempted"; - logForDebugging(`Official marketplace auto-install skipped: ${reason}`); - return { - installed: false, - skipped: true, - reason - }; - } - try { - if (isOfficialMarketplaceAutoInstallDisabled()) { - logForDebugging("Official marketplace auto-install disabled via env var, skipping"); - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: false, - officialMarketplaceAutoInstallFailReason: "policy_blocked" - })); - logEvent("tengu_official_marketplace_auto_install", { - installed: false, - skipped: true, - policy_blocked: true - }); - return { installed: false, skipped: true, reason: "policy_blocked" }; - } - const knownMarketplaces = await loadKnownMarketplacesConfig(); - if (knownMarketplaces[OFFICIAL_MARKETPLACE_NAME]) { - logForDebugging(`Official marketplace '${OFFICIAL_MARKETPLACE_NAME}' already installed, skipping`); - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: true - })); - return { installed: false, skipped: true, reason: "already_installed" }; - } - if (!isSourceAllowedByPolicy(OFFICIAL_MARKETPLACE_SOURCE)) { - logForDebugging("Official marketplace blocked by enterprise policy, skipping"); - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: false, - officialMarketplaceAutoInstallFailReason: "policy_blocked" - })); - logEvent("tengu_official_marketplace_auto_install", { - installed: false, - skipped: true, - policy_blocked: true - }); - return { installed: false, skipped: true, reason: "policy_blocked" }; - } - const cacheDir = getMarketplacesCacheDir(); - const installLocation = join147(cacheDir, OFFICIAL_MARKETPLACE_NAME); - const gcsSha = await fetchOfficialMarketplaceFromGcs(installLocation, cacheDir); - if (gcsSha !== null) { - const known = await loadKnownMarketplacesConfig(); - known[OFFICIAL_MARKETPLACE_NAME] = { - source: OFFICIAL_MARKETPLACE_SOURCE, - installLocation, - lastUpdated: new Date().toISOString() - }; - await saveKnownMarketplacesConfig(known); - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: true, - officialMarketplaceAutoInstallFailReason: undefined, - officialMarketplaceAutoInstallRetryCount: undefined, - officialMarketplaceAutoInstallLastAttemptTime: undefined, - officialMarketplaceAutoInstallNextRetryTime: undefined - })); - logEvent("tengu_official_marketplace_auto_install", { - installed: true, - skipped: false, - via_gcs: true - }); - return { installed: true, skipped: false }; - } - if (!getFeatureValue_CACHED_MAY_BE_STALE("tengu_plugin_official_mkt_git_fallback", true)) { - logForDebugging("Official marketplace GCS failed; git fallback disabled by flag \u2014 skipping install"); - const retryCount = (config10.officialMarketplaceAutoInstallRetryCount || 0) + 1; - const now2 = Date.now(); - const nextRetryTime = now2 + calculateNextRetryDelay(retryCount); - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: false, - officialMarketplaceAutoInstallFailReason: "gcs_unavailable", - officialMarketplaceAutoInstallRetryCount: retryCount, - officialMarketplaceAutoInstallLastAttemptTime: now2, - officialMarketplaceAutoInstallNextRetryTime: nextRetryTime - })); - logEvent("tengu_official_marketplace_auto_install", { - installed: false, - skipped: true, - gcs_unavailable: true, - retry_count: retryCount - }); - return { installed: false, skipped: true, reason: "gcs_unavailable" }; - } - const gitAvailable = await checkGitAvailable(); - if (!gitAvailable) { - logForDebugging("Git not available, skipping official marketplace auto-install"); - const retryCount = (config10.officialMarketplaceAutoInstallRetryCount || 0) + 1; - const now2 = Date.now(); - const nextRetryDelay = calculateNextRetryDelay(retryCount); - const nextRetryTime = now2 + nextRetryDelay; - let configSaveFailed = false; - try { - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: false, - officialMarketplaceAutoInstallFailReason: "git_unavailable", - officialMarketplaceAutoInstallRetryCount: retryCount, - officialMarketplaceAutoInstallLastAttemptTime: now2, - officialMarketplaceAutoInstallNextRetryTime: nextRetryTime - })); - } catch (saveError) { - configSaveFailed = true; - const configError = toError(saveError); - logError2(configError); - logForDebugging(`Failed to save marketplace auto-install git_unavailable state: ${saveError}`, { level: "error" }); - } - logEvent("tengu_official_marketplace_auto_install", { - installed: false, - skipped: true, - git_unavailable: true, - retry_count: retryCount - }); - return { - installed: false, - skipped: true, - reason: "git_unavailable", - configSaveFailed - }; - } - logForDebugging("Attempting to auto-install official marketplace"); - await addMarketplaceSource(OFFICIAL_MARKETPLACE_SOURCE); - logForDebugging("Successfully auto-installed official marketplace"); - const previousRetryCount = config10.officialMarketplaceAutoInstallRetryCount || 0; - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: true, - officialMarketplaceAutoInstallFailReason: undefined, - officialMarketplaceAutoInstallRetryCount: undefined, - officialMarketplaceAutoInstallLastAttemptTime: undefined, - officialMarketplaceAutoInstallNextRetryTime: undefined - })); - logEvent("tengu_official_marketplace_auto_install", { - installed: true, - skipped: false, - retry_count: previousRetryCount - }); - return { installed: true, skipped: false }; - } catch (error46) { - const errorMessage4 = error46 instanceof Error ? error46.message : String(error46); - if (errorMessage4.includes("xcrun: error:")) { - markGitUnavailable(); - logForDebugging("Official marketplace auto-install: git is a non-functional macOS xcrun shim, treating as git_unavailable"); - logEvent("tengu_official_marketplace_auto_install", { - installed: false, - skipped: true, - git_unavailable: true, - macos_xcrun_shim: true - }); - return { - installed: false, - skipped: true, - reason: "git_unavailable" - }; - } - logForDebugging(`Failed to auto-install official marketplace: ${errorMessage4}`, { level: "error" }); - logError2(toError(error46)); - const retryCount = (config10.officialMarketplaceAutoInstallRetryCount || 0) + 1; - const now2 = Date.now(); - const nextRetryDelay = calculateNextRetryDelay(retryCount); - const nextRetryTime = now2 + nextRetryDelay; - let configSaveFailed = false; - try { - saveGlobalConfig((current) => ({ - ...current, - officialMarketplaceAutoInstallAttempted: true, - officialMarketplaceAutoInstalled: false, - officialMarketplaceAutoInstallFailReason: "unknown", - officialMarketplaceAutoInstallRetryCount: retryCount, - officialMarketplaceAutoInstallLastAttemptTime: now2, - officialMarketplaceAutoInstallNextRetryTime: nextRetryTime - })); - } catch (saveError) { - configSaveFailed = true; - const configError = toError(saveError); - logError2(configError); - logForDebugging(`Failed to save marketplace auto-install failure state: ${saveError}`, { level: "error" }); - } - logEvent("tengu_official_marketplace_auto_install", { - installed: false, - skipped: true, - failed: true, - retry_count: retryCount - }); - return { - installed: false, - skipped: true, - reason: "unknown", - configSaveFailed - }; - } -} -var RETRY_CONFIG; -var init_officialMarketplaceStartupCheck = __esm(() => { - init_growthbook(); - init_analytics(); - init_config(); - init_debug(); - init_envUtils(); - init_errors(); - init_log2(); - init_gitAvailability(); - init_marketplaceHelpers(); - init_marketplaceManager(); - init_officialMarketplace(); - init_officialMarketplaceGcs(); - RETRY_CONFIG = { - MAX_ATTEMPTS: 10, - INITIAL_DELAY_MS: 60 * 60 * 1000, - BACKOFF_MULTIPLIER: 2, - MAX_DELAY_MS: 7 * 24 * 60 * 60 * 1000 - }; -}); - -// src/hooks/useOfficialMarketplaceNotification.tsx -function useOfficialMarketplaceNotification() { - useStartupNotification(_temp206); -} -async function _temp206() { - const result = await checkAndInstallOfficialMarketplace(); - const notifs = []; - if (result.configSaveFailed) { - logForDebugging("Showing marketplace config save failure notification"); - notifs.push({ - key: "marketplace-config-save-failed", - jsx: /* @__PURE__ */ jsx_dev_runtime449.jsxDEV(ThemedText, { - color: "error", - children: "Failed to save marketplace retry info \xB7 Check ~/.claude.json permissions" - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 1e4 - }); - } - if (result.installed) { - logForDebugging("Showing marketplace installation success notification"); - notifs.push({ - key: "marketplace-installed", - jsx: /* @__PURE__ */ jsx_dev_runtime449.jsxDEV(ThemedText, { - color: "success", - children: "\u2713 Anthropic marketplace installed \xB7 /plugin to see available plugins" - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 7000 - }); - } else { - if (result.skipped && result.reason === "unknown") { - logForDebugging("Showing marketplace installation failure notification"); - notifs.push({ - key: "marketplace-install-failed", - jsx: /* @__PURE__ */ jsx_dev_runtime449.jsxDEV(ThemedText, { - color: "warning", - children: "Failed to install Anthropic marketplace \xB7 Will retry on next startup" - }, undefined, false, undefined, this), - priority: "immediate", - timeoutMs: 8000 - }); - } - } - return notifs; -} -var jsx_dev_runtime449; -var init_useOfficialMarketplaceNotification = __esm(() => { - init_ink2(); - init_debug(); - init_officialMarketplaceStartupCheck(); - init_useStartupNotification(); - jsx_dev_runtime449 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/usePromptsFromClaudeInChrome.tsx -function usePromptsFromClaudeInChrome(mcpClients, toolPermissionMode) { - const $2 = import_compiler_runtime349.c(6); - import_react298.useRef(undefined); - let t0; - if ($2[0] !== mcpClients) { - t0 = [mcpClients]; - $2[0] = mcpClients; - $2[1] = t0; - } else { - t0 = $2[1]; - } - import_react298.useEffect(_temp207, t0); - let t1; - let t22; - if ($2[2] !== mcpClients || $2[3] !== toolPermissionMode) { - t1 = () => { - const chromeClient = findChromeClient(mcpClients); - if (!chromeClient) { - return; - } - const chromeMode = toolPermissionMode === "bypassPermissions" ? "skip_all_permission_checks" : "ask"; - callIdeRpc("set_permission_mode", { - mode: chromeMode - }, chromeClient); - }; - t22 = [mcpClients, toolPermissionMode]; - $2[2] = mcpClients; - $2[3] = toolPermissionMode; - $2[4] = t1; - $2[5] = t22; - } else { - t1 = $2[4]; - t22 = $2[5]; - } - import_react298.useEffect(t1, t22); -} -function _temp207() {} -function findChromeClient(clients) { - return clients.find((client16) => client16.type === "connected" && client16.name === CLAUDE_IN_CHROME_MCP_SERVER_NAME); -} -var import_compiler_runtime349, import_react298, ClaudeInChromePromptNotificationSchema; -var init_usePromptsFromClaudeInChrome = __esm(() => { - init_v4(); - init_client22(); - init_common3(); - import_compiler_runtime349 = __toESM(require_compiler_runtime(), 1); - import_react298 = __toESM(require_react(), 1); - ClaudeInChromePromptNotificationSchema = lazySchema(() => exports_external.object({ - method: exports_external.literal("notifications/message"), - params: exports_external.object({ - prompt: exports_external.string(), - image: exports_external.object({ - type: exports_external.literal("base64"), - media_type: exports_external.enum(["image/jpeg", "image/png", "image/gif", "image/webp"]), - data: exports_external.string() - }).optional(), - tabId: exports_external.number().optional() - }) - })); -}); - -// src/services/tips/tipHistory.ts -function recordTipShown(tipId) { - const numStartups = getGlobalConfig().numStartups; - saveGlobalConfig((c9) => { - const history = c9.tipsHistory ?? {}; - if (history[tipId] === numStartups) - return c9; - return { ...c9, tipsHistory: { ...history, [tipId]: numStartups } }; - }); -} -function getSessionsSinceLastShown(tipId) { - const config10 = getGlobalConfig(); - const lastShown = config10.tipsHistory?.[tipId]; - if (!lastShown) - return Infinity; - return config10.numStartups - lastShown; -} -var init_tipHistory = __esm(() => { - init_config(); -}); - -// src/components/DesktopUpsell/DesktopUpsellStartup.tsx -function getDesktopUpsellConfig() { - return getDynamicConfig_CACHED_MAY_BE_STALE("tengu_desktop_upsell", DESKTOP_UPSELL_DEFAULT); -} -function isSupportedPlatform3() { - return process.platform === "darwin" || process.platform === "win32" && process.arch === "x64"; -} -function shouldShowDesktopUpsellStartup() { - if (!isSupportedPlatform3()) - return false; - if (!getDesktopUpsellConfig().enable_startup_dialog) - return false; - const config10 = getGlobalConfig(); - if (config10.desktopUpsellDismissed) - return false; - if ((config10.desktopUpsellSeenCount ?? 0) >= 3) - return false; - return true; -} -function DesktopUpsellStartup(t0) { - const $2 = import_compiler_runtime350.c(14); - const { - onDone - } = t0; - const [showHandoff, setShowHandoff] = import_react299.useState(false); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = []; - $2[0] = t1; - } else { - t1 = $2[0]; - } - import_react299.useEffect(_temp208, t1); - if (showHandoff) { - let t23; - if ($2[1] !== onDone) { - t23 = /* @__PURE__ */ jsx_dev_runtime450.jsxDEV(DesktopHandoff, { - onDone: () => onDone() - }, undefined, false, undefined, this); - $2[1] = onDone; - $2[2] = t23; - } else { - t23 = $2[2]; - } - return t23; - } - let t22; - if ($2[3] !== onDone) { - t22 = function handleSelect2(value) { - switch (value) { - case "try": { - setShowHandoff(true); - return; - } - case "never": { - saveGlobalConfig(_temp286); - onDone(); - return; - } - case "not-now": { - onDone(); - return; - } - } - }; - $2[3] = onDone; - $2[4] = t22; - } else { - t22 = $2[4]; - } - const handleSelect = t22; - let t32; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t32 = { - label: "Open in Claude Code Desktop", - value: "try" - }; - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t4 = { - label: "Not now", - value: "not-now" - }; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t5 = [t32, t4, { - label: "Don't ask again", - value: "never" - }]; - $2[7] = t5; - } else { - t5 = $2[7]; - } - const options2 = t5; - let t6; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t6 = /* @__PURE__ */ jsx_dev_runtime450.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime450.jsxDEV(ThemedText, { - children: "Same Claude Code with visual diffs, live app preview, parallel sessions, and more." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[8] = t6; - } else { - t6 = $2[8]; - } - let t7; - if ($2[9] !== handleSelect) { - t7 = () => handleSelect("not-now"); - $2[9] = handleSelect; - $2[10] = t7; - } else { - t7 = $2[10]; - } - let t8; - if ($2[11] !== handleSelect || $2[12] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime450.jsxDEV(PermissionDialog, { - title: "Try Claude Code Desktop", - children: /* @__PURE__ */ jsx_dev_runtime450.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - t6, - /* @__PURE__ */ jsx_dev_runtime450.jsxDEV(Select, { - options: options2, - onChange: handleSelect, - onCancel: t7 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[11] = handleSelect; - $2[12] = t7; - $2[13] = t8; - } else { - t8 = $2[13]; - } - return t8; -} -function _temp286(prev_0) { - if (prev_0.desktopUpsellDismissed) { - return prev_0; - } - return { - ...prev_0, - desktopUpsellDismissed: true - }; -} -function _temp208() { - const newCount = (getGlobalConfig().desktopUpsellSeenCount ?? 0) + 1; - saveGlobalConfig((prev) => { - if ((prev.desktopUpsellSeenCount ?? 0) >= newCount) { - return prev; - } - return { - ...prev, - desktopUpsellSeenCount: newCount - }; - }); - logEvent("tengu_desktop_upsell_shown", { - seen_count: newCount - }); -} -var import_compiler_runtime350, import_react299, jsx_dev_runtime450, DESKTOP_UPSELL_DEFAULT; -var init_DesktopUpsellStartup = __esm(() => { - init_ink2(); - init_growthbook(); - init_analytics(); - init_config(); - init_select(); - init_DesktopHandoff(); - init_PermissionDialog(); - import_compiler_runtime350 = __toESM(require_compiler_runtime(), 1); - import_react299 = __toESM(require_react(), 1); - jsx_dev_runtime450 = __toESM(require_jsx_dev_runtime(), 1); - DESKTOP_UPSELL_DEFAULT = { - enable_shortcut_tip: false, - enable_startup_dialog: false - }; -}); - -// src/services/tips/tipRegistry.ts -async function isOfficialMarketplaceInstalled() { - if (_isOfficialMarketplaceInstalledCache !== undefined) { - return _isOfficialMarketplaceInstalledCache; - } - const config10 = await loadKnownMarketplacesConfigSafe(); - _isOfficialMarketplaceInstalledCache = OFFICIAL_MARKETPLACE_NAME in config10; - return _isOfficialMarketplaceInstalledCache; -} -async function isMarketplacePluginRelevant(pluginName, context7, signals2) { - if (!await isOfficialMarketplaceInstalled()) { - return false; - } - if (isPluginInstalled(`${pluginName}@${OFFICIAL_MARKETPLACE_NAME}`)) { - return false; - } - const { bashTools } = context7 ?? {}; - if (signals2.cli && bashTools?.size) { - if (signals2.cli.some((cmd) => bashTools.has(cmd))) { - return true; - } - } - if (signals2.filePath && context7?.readFileState) { - const readFiles = cacheKeys(context7.readFileState); - if (readFiles.some((fp) => signals2.filePath.test(fp))) { - return true; - } - } - return false; -} -function getCustomTips() { - const settings = getInitialSettings(); - const override = settings.spinnerTipsOverride; - if (!override?.tips?.length) - return []; - return override.tips.map((content, i6) => ({ - id: `custom-tip-${i6}`, - content: async () => content, - cooldownSessions: 0, - isRelevant: async () => true - })); -} -async function getRelevantTips(context7) { - const settings = getInitialSettings(); - const override = settings.spinnerTipsOverride; - const customTips = getCustomTips(); - if (override?.excludeDefault && customTips.length > 0) { - return customTips; - } - const tips = [...externalTips, ...internalOnlyTips]; - const isRelevant = await Promise.all(tips.map((_) => _.isRelevant(context7))); - const filtered = tips.filter((_, index2) => isRelevant[index2]).filter((_) => getSessionsSinceLastShown(_.id) >= _.cooldownSessions); - return [...filtered, ...customTips]; -} -var _isOfficialMarketplaceInstalledCache, externalTips, internalOnlyTips; -var init_tipRegistry = __esm(() => { - init_source(); - init_debug(); - init_fileHistory(); - init_settings2(); - init_terminalSetup(); - init_DesktopUpsellStartup(); - init_color(); - init_OverageCreditUpsell(); - init_shortcutFormat(); - init_prompt8(); - init_auth14(); - init_concurrentSessions(); - init_config(); - init_effort(); - init_env(); - init_fileStateCache(); - init_git(); - init_ide(); - init_model(); - init_platform2(); - init_installedPluginsManager(); - init_marketplaceManager(); - init_officialMarketplace(); - init_sessionStorage(); - init_growthbook(); - init_overageCreditGrant(); - init_referral(); - init_tipHistory(); - externalTips = [ - { - id: "new-user-warmup", - content: async () => `Start with small features or bug fixes, tell Claude to propose a plan, and verify its suggested edits`, - cooldownSessions: 3, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.numStartups < 10; - } - }, - { - id: "plan-mode-for-complex-tasks", - content: async () => `Use Plan Mode to prepare for a complex request before making changes. Press ${getShortcutDisplay("chat:cycleMode", "Chat", "shift+tab")} twice to enable.`, - cooldownSessions: 5, - isRelevant: async () => { - if (process.env.USER_TYPE === "ant") - return false; - const config10 = getGlobalConfig(); - const daysSinceLastUse = config10.lastPlanModeUse ? (Date.now() - config10.lastPlanModeUse) / (1000 * 60 * 60 * 24) : Infinity; - return daysSinceLastUse > 7; - } - }, - { - id: "default-permission-mode-config", - content: async () => `Use /config to change your default permission mode (including Plan Mode)`, - cooldownSessions: 10, - isRelevant: async () => { - try { - const config10 = getGlobalConfig(); - const settings = getSettings_DEPRECATED(); - const hasUsedPlanMode = Boolean(config10.lastPlanModeUse); - const hasDefaultMode = Boolean(settings?.permissions?.defaultMode); - return hasUsedPlanMode && !hasDefaultMode; - } catch (error46) { - logForDebugging(`Failed to check default-permission-mode-config tip relevance: ${error46}`, { level: "warn" }); - return false; - } - } - }, - { - id: "git-worktrees", - content: async () => "Use git worktrees to run multiple Claude sessions in parallel.", - cooldownSessions: 10, - isRelevant: async () => { - try { - const config10 = getGlobalConfig(); - const worktreeCount = await getWorktreeCount(); - return worktreeCount <= 1 && config10.numStartups > 50; - } catch (_) { - return false; - } - } - }, - { - id: "color-when-multi-clauding", - content: async () => "Running multiple Claude sessions? Use /color and /rename to tell them apart at a glance.", - cooldownSessions: 10, - isRelevant: async () => { - if (getCurrentSessionAgentColor()) - return false; - const count4 = await countConcurrentSessions(); - return count4 >= 2; - } - }, - { - id: "terminal-setup", - content: async () => env2.terminal === "Apple_Terminal" ? "Run /terminal-setup to enable convenient terminal integration like Option + Enter for new line and more" : "Run /terminal-setup to enable convenient terminal integration like Shift + Enter for new line and more", - cooldownSessions: 10, - async isRelevant() { - const config10 = getGlobalConfig(); - if (env2.terminal === "Apple_Terminal") { - return !config10.optionAsMetaKeyInstalled; - } - return !config10.shiftEnterKeyBindingInstalled; - } - }, - { - id: "shift-enter", - content: async () => env2.terminal === "Apple_Terminal" ? "Press Option+Enter to send a multi-line message" : "Press Shift+Enter to send a multi-line message", - cooldownSessions: 10, - async isRelevant() { - const config10 = getGlobalConfig(); - return Boolean((env2.terminal === "Apple_Terminal" ? config10.optionAsMetaKeyInstalled : config10.shiftEnterKeyBindingInstalled) && config10.numStartups > 3); - } - }, - { - id: "shift-enter-setup", - content: async () => env2.terminal === "Apple_Terminal" ? "Run /terminal-setup to enable Option+Enter for new lines" : "Run /terminal-setup to enable Shift+Enter for new lines", - cooldownSessions: 10, - async isRelevant() { - if (!shouldOfferTerminalSetup()) { - return false; - } - const config10 = getGlobalConfig(); - return !(env2.terminal === "Apple_Terminal" ? config10.optionAsMetaKeyInstalled : config10.shiftEnterKeyBindingInstalled); - } - }, - { - id: "memory-command", - content: async () => "Use /memory to view and manage Claude memory", - cooldownSessions: 15, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.memoryUsageCount <= 0; - } - }, - { - id: "theme-command", - content: async () => "Use /theme to change the color theme", - cooldownSessions: 20, - isRelevant: async () => true - }, - { - id: "colorterm-truecolor", - content: async () => "Try setting environment variable COLORTERM=truecolor for richer colors", - cooldownSessions: 30, - isRelevant: async () => !process.env.COLORTERM && source_default.level < 3 - }, - { - id: "powershell-tool-env", - content: async () => "Set CLAUDE_CODE_USE_POWERSHELL_TOOL=1 to enable the PowerShell tool (preview)", - cooldownSessions: 10, - isRelevant: async () => getPlatform() === "windows" && process.env.CLAUDE_CODE_USE_POWERSHELL_TOOL === undefined - }, - { - id: "status-line", - content: async () => "Use /statusline to set up a custom status line that will display beneath the input box", - cooldownSessions: 25, - isRelevant: async () => getSettings_DEPRECATED().statusLine === undefined - }, - { - id: "prompt-queue", - content: async () => "Hit Enter to queue up additional messages while Claude is working.", - cooldownSessions: 5, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.promptQueueUseCount <= 3; - } - }, - { - id: "enter-to-steer-in-relatime", - content: async () => "Send messages to Claude while it works to steer Claude in real-time", - cooldownSessions: 20, - isRelevant: async () => true - }, - { - id: "todo-list", - content: async () => "Ask Claude to create a todo list when working on complex tasks to track progress and remain on track", - cooldownSessions: 20, - isRelevant: async () => true - }, - { - id: "vscode-command-install", - content: async () => `Open the Command Palette (Cmd+Shift+P) and run "Shell Command: Install '${env2.terminal === "vscode" ? "code" : env2.terminal}' command in PATH" to enable IDE integration`, - cooldownSessions: 0, - async isRelevant() { - if (!isSupportedVSCodeTerminal()) { - return false; - } - if (getPlatform() !== "macos") { - return false; - } - switch (env2.terminal) { - case "vscode": - return !await isVSCodeInstalled(); - case "cursor": - return !await isCursorInstalled(); - case "windsurf": - return !await isWindsurfInstalled(); - default: - return false; - } - } - }, - { - id: "ide-upsell-external-terminal", - content: async () => "Connect Claude to your IDE \xB7 /ide", - cooldownSessions: 4, - async isRelevant() { - if (isSupportedTerminal()) { - return false; - } - const lockfiles = await getSortedIdeLockfiles(); - if (lockfiles.length !== 0) { - return false; - } - const runningIDEs = await detectRunningIDEsCached(); - return runningIDEs.length > 0; - } - }, - { - id: "install-github-app", - content: async () => "Run /install-github-app to tag @claude right from your Github issues and PRs", - cooldownSessions: 10, - isRelevant: async () => !getGlobalConfig().githubActionSetupCount - }, - { - id: "install-slack-app", - content: async () => "Run /install-slack-app to use Claude in Slack", - cooldownSessions: 10, - isRelevant: async () => !getGlobalConfig().slackAppInstallCount - }, - { - id: "permissions", - content: async () => "Use /permissions to pre-approve and pre-deny bash, edit, and MCP tools", - cooldownSessions: 10, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.numStartups > 10; - } - }, - { - id: "drag-and-drop-images", - content: async () => "Did you know you can drag and drop image files into your terminal?", - cooldownSessions: 10, - isRelevant: async () => !env2.isSSH() - }, - { - id: "paste-images-mac", - content: async () => "Paste images into Claude Code using control+v (not cmd+v!)", - cooldownSessions: 10, - isRelevant: async () => getPlatform() === "macos" - }, - { - id: "double-esc", - content: async () => "Double-tap esc to rewind the conversation to a previous point in time", - cooldownSessions: 10, - isRelevant: async () => !fileHistoryEnabled() - }, - { - id: "double-esc-code-restore", - content: async () => "Double-tap esc to rewind the code and/or conversation to a previous point in time", - cooldownSessions: 10, - isRelevant: async () => fileHistoryEnabled() - }, - { - id: "continue", - content: async () => "Run claude --continue or claude --resume to resume a conversation", - cooldownSessions: 10, - isRelevant: async () => true - }, - { - id: "rename-conversation", - content: async () => "Name your conversations with /rename to find them easily in /resume later", - cooldownSessions: 15, - isRelevant: async () => isCustomTitleEnabled() && getGlobalConfig().numStartups > 10 - }, - { - id: "custom-commands", - content: async () => "Create skills by adding .md files to .claude/skills/ in your project or ~/.claude/skills/ for skills that work in any project", - cooldownSessions: 15, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.numStartups > 10; - } - }, - { - id: "shift-tab", - content: async () => process.env.USER_TYPE === "ant" ? `Hit ${getShortcutDisplay("chat:cycleMode", "Chat", "shift+tab")} to cycle between default mode and auto mode` : `Hit ${getShortcutDisplay("chat:cycleMode", "Chat", "shift+tab")} to cycle between default mode, auto-accept edit mode, and plan mode`, - cooldownSessions: 10, - isRelevant: async () => true - }, - { - id: "image-paste", - content: async () => `Use ${getShortcutDisplay("chat:imagePaste", "Chat", "ctrl+v")} to paste images from your clipboard`, - cooldownSessions: 20, - isRelevant: async () => true - }, - { - id: "custom-agents", - content: async () => "Use /agents to optimize specific tasks. Eg. Software Architect, Code Writer, Code Reviewer", - cooldownSessions: 15, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.numStartups > 5; - } - }, - { - id: "agent-flag", - content: async () => "Use --agent to directly start a conversation with a subagent", - cooldownSessions: 15, - async isRelevant() { - const config10 = getGlobalConfig(); - return config10.numStartups > 5; - } - }, - { - id: "desktop-app", - content: async () => "Run Claude Code locally or remotely using the Claude desktop app: clau.de/desktop", - cooldownSessions: 15, - isRelevant: async () => getPlatform() !== "linux" - }, - { - id: "desktop-shortcut", - content: async (ctx) => { - const blue2 = color("suggestion", ctx.theme); - return `Continue your session in Claude Code Desktop with ${blue2("/desktop")}`; - }, - cooldownSessions: 15, - isRelevant: async () => { - if (!getDesktopUpsellConfig().enable_shortcut_tip) - return false; - return process.platform === "darwin" || process.platform === "win32" && process.arch === "x64"; - } - }, - { - id: "web-app", - content: async () => "Run tasks in the cloud while you keep coding locally \xB7 clau.de/web", - cooldownSessions: 15, - isRelevant: async () => true - }, - { - id: "mobile-app", - content: async () => "/mobile to use Claude Code from the Claude app on your phone", - cooldownSessions: 15, - isRelevant: async () => true - }, - { - id: "opusplan-mode-reminder", - content: async () => `Your default model setting is Opus Plan Mode. Press ${getShortcutDisplay("chat:cycleMode", "Chat", "shift+tab")} twice to activate Plan Mode and plan with Claude Opus.`, - cooldownSessions: 2, - async isRelevant() { - if (process.env.USER_TYPE === "ant") - return false; - const config10 = getGlobalConfig(); - const modelSetting = getUserSpecifiedModelSetting(); - const hasOpusPlanMode = modelSetting === "opusplan"; - const daysSinceLastUse = config10.lastPlanModeUse ? (Date.now() - config10.lastPlanModeUse) / (1000 * 60 * 60 * 24) : Infinity; - return hasOpusPlanMode && daysSinceLastUse > 3; - } - }, - { - id: "frontend-design-plugin", - content: async (ctx) => { - const blue2 = color("suggestion", ctx.theme); - return `Working with HTML/CSS? Install the frontend-design plugin: -${blue2(`/plugin install frontend-design@${OFFICIAL_MARKETPLACE_NAME}`)}`; - }, - cooldownSessions: 3, - isRelevant: async (context7) => isMarketplacePluginRelevant("frontend-design", context7, { - filePath: /\.(html|css|htm)$/i - }) - }, - { - id: "vercel-plugin", - content: async (ctx) => { - const blue2 = color("suggestion", ctx.theme); - return `Working with Vercel? Install the vercel plugin: -${blue2(`/plugin install vercel@${OFFICIAL_MARKETPLACE_NAME}`)}`; - }, - cooldownSessions: 3, - isRelevant: async (context7) => isMarketplacePluginRelevant("vercel", context7, { - filePath: /(?:^|[/\\])vercel\.json$/i, - cli: ["vercel"] - }) - }, - { - id: "effort-high-nudge", - content: async (ctx) => { - const blue2 = color("suggestion", ctx.theme); - const cmd = blue2("/effort high"); - const variant = getFeatureValue_CACHED_MAY_BE_STALE("tengu_tide_elm", "off"); - return variant === "copy_b" ? `Use ${cmd} for better one-shot answers. Claude thinks it through first.` : `Working on something tricky? ${cmd} gives better first answers`; - }, - cooldownSessions: 3, - isRelevant: async () => { - if (!is1PApiCustomer()) - return false; - if (!modelSupportsEffort(getMainLoopModel())) - return false; - if (getSettingsForSource("policySettings")?.effortLevel !== undefined) { - return false; - } - if (getEffortEnvOverride() !== undefined) - return false; - const persisted = getInitialSettings().effortLevel; - if (persisted === "high" || persisted === "max") - return false; - return getFeatureValue_CACHED_MAY_BE_STALE("tengu_tide_elm", "off") !== "off"; - } - }, - { - id: "subagent-fanout-nudge", - content: async (ctx) => { - const blue2 = color("suggestion", ctx.theme); - const variant = getFeatureValue_CACHED_MAY_BE_STALE("tengu_tern_alloy", "off"); - return variant === "copy_b" ? `For big tasks, tell Claude to ${blue2("use subagents")}. They work in parallel and keep your main thread clean.` : `Say ${blue2('"fan out subagents"')} and Claude sends a team. Each one digs deep so nothing gets missed.`; - }, - cooldownSessions: 3, - isRelevant: async () => { - if (!is1PApiCustomer()) - return false; - return getFeatureValue_CACHED_MAY_BE_STALE("tengu_tern_alloy", "off") !== "off"; - } - }, - { - id: "loop-command-nudge", - content: async (ctx) => { - const blue2 = color("suggestion", ctx.theme); - const variant = getFeatureValue_CACHED_MAY_BE_STALE("tengu_timber_lark", "off"); - return variant === "copy_b" ? `Use ${blue2("/loop 5m check the deploy")} to run any prompt on a schedule. Set it and forget it.` : `${blue2("/loop")} runs any prompt on a recurring schedule. Great for monitoring deploys, babysitting PRs, or polling status.`; - }, - cooldownSessions: 3, - isRelevant: async () => { - if (!is1PApiCustomer()) - return false; - if (!isKairosCronEnabled()) - return false; - return getFeatureValue_CACHED_MAY_BE_STALE("tengu_timber_lark", "off") !== "off"; - } - }, - { - id: "guest-passes", - content: async (ctx) => { - const claude = color("claude", ctx.theme); - const reward = getCachedReferrerReward(); - return reward ? `Share Claude Code and earn ${claude(formatCreditAmount(reward))} of extra usage \xB7 ${claude("/passes")}` : `You have free guest passes to share \xB7 ${claude("/passes")}`; - }, - cooldownSessions: 3, - isRelevant: async () => { - const config10 = getGlobalConfig(); - if (config10.hasVisitedPasses) { - return false; - } - const { eligible: eligible2 } = checkCachedPassesEligibility(); - return eligible2; - } - }, - { - id: "overage-credit", - content: async (ctx) => { - const claude = color("claude", ctx.theme); - const info = getCachedOverageCreditGrant(); - const amount = info ? formatGrantAmount(info) : null; - if (!amount) - return ""; - return `${claude(`${amount} in extra usage, on us`)} \xB7 third-party apps \xB7 ${claude("/extra-usage")}`; - }, - cooldownSessions: 3, - isRelevant: async () => shouldShowOverageCreditUpsell() - }, - { - id: "feedback-command", - content: async () => "Use /feedback to help us improve!", - cooldownSessions: 15, - async isRelevant() { - if (process.env.USER_TYPE === "ant") { - return false; - } - const config10 = getGlobalConfig(); - return config10.numStartups > 5; - } - } - ]; - internalOnlyTips = process.env.USER_TYPE === "ant" ? [ - { - id: "important-claudemd", - content: async () => '[ANT-ONLY] Use "IMPORTANT:" prefix for must-follow CLAUDE.md rules', - cooldownSessions: 30, - isRelevant: async () => true - }, - { - id: "skillify", - content: async () => "[ANT-ONLY] Use /skillify at the end of a workflow to turn it into a reusable skill", - cooldownSessions: 15, - isRelevant: async () => true - } - ] : []; -}); - -// src/services/tips/tipScheduler.ts -function selectTipWithLongestTimeSinceShown(availableTips) { - if (availableTips.length === 0) { - return; - } - if (availableTips.length === 1) { - return availableTips[0]; - } - const tipsWithSessions = availableTips.map((tip) => ({ - tip, - sessions: getSessionsSinceLastShown(tip.id) - })); - tipsWithSessions.sort((a5, b5) => b5.sessions - a5.sessions); - return tipsWithSessions[0]?.tip; -} -async function getTipToShowOnSpinner(context7) { - if (getSettings_DEPRECATED().spinnerTipsEnabled === false) { - return; - } - const tips = await getRelevantTips(context7); - if (tips.length === 0) { - return; - } - return selectTipWithLongestTimeSinceShown(tips); -} -function recordShownTip(tip) { - recordTipShown(tip.id); - logEvent("tengu_tip_shown", { - tipIdLength: tip.id, - cooldownSessions: tip.cooldownSessions - }); -} -var init_tipScheduler = __esm(() => { - init_settings2(); - init_analytics(); - init_tipHistory(); - init_tipRegistry(); -}); - -// src/entrypoints/sdk/controlSchemas.ts -var JSONRPCMessagePlaceholder, SDKHookCallbackMatcherSchema, SDKControlInitializeRequestSchema, SDKControlInitializeResponseSchema, SDKControlInterruptRequestSchema, SDKControlPermissionRequestSchema, SDKControlSetPermissionModeRequestSchema, SDKControlSetModelRequestSchema, SDKControlSetMaxThinkingTokensRequestSchema, SDKControlMcpStatusRequestSchema, SDKControlMcpStatusResponseSchema, SDKControlGetContextUsageRequestSchema, ContextCategorySchema, ContextGridSquareSchema, SDKControlGetContextUsageResponseSchema, SDKControlRewindFilesRequestSchema, SDKControlRewindFilesResponseSchema, SDKControlCancelAsyncMessageRequestSchema, SDKControlCancelAsyncMessageResponseSchema, SDKControlSeedReadStateRequestSchema, SDKHookCallbackRequestSchema, SDKControlMcpMessageRequestSchema, SDKControlMcpSetServersRequestSchema, SDKControlMcpSetServersResponseSchema, SDKControlReloadPluginsRequestSchema, SDKControlReloadPluginsResponseSchema, SDKControlMcpReconnectRequestSchema, SDKControlMcpToggleRequestSchema, SDKControlStopTaskRequestSchema, SDKControlApplyFlagSettingsRequestSchema, SDKControlGetSettingsRequestSchema, SDKControlGetSettingsResponseSchema, SDKControlElicitationRequestSchema, SDKControlElicitationResponseSchema, SDKControlRequestInnerSchema, SDKControlRequestSchema, ControlResponseSchema, ControlErrorResponseSchema, SDKControlResponseSchema, SDKControlCancelRequestSchema, SDKKeepAliveMessageSchema, SDKUpdateEnvironmentVariablesMessageSchema, StdoutMessageSchema, StdinMessageSchema; -var init_controlSchemas = __esm(() => { - init_v4(); - init_coreSchemas(); - JSONRPCMessagePlaceholder = lazySchema(() => exports_external.unknown()); - SDKHookCallbackMatcherSchema = lazySchema(() => exports_external.object({ - matcher: exports_external.string().optional(), - hookCallbackIds: exports_external.array(exports_external.string()), - timeout: exports_external.number().optional() - }).describe("Configuration for matching and routing hook callbacks.")); - SDKControlInitializeRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("initialize"), - hooks: exports_external.record(HookEventSchema(), exports_external.array(SDKHookCallbackMatcherSchema())).optional(), - sdkMcpServers: exports_external.array(exports_external.string()).optional(), - jsonSchema: exports_external.record(exports_external.string(), exports_external.unknown()).optional(), - systemPrompt: exports_external.string().optional(), - appendSystemPrompt: exports_external.string().optional(), - agents: exports_external.record(exports_external.string(), AgentDefinitionSchema()).optional(), - promptSuggestions: exports_external.boolean().optional(), - agentProgressSummaries: exports_external.boolean().optional() - }).describe("Initializes the SDK session with hooks, MCP servers, and agent configuration.")); - SDKControlInitializeResponseSchema = lazySchema(() => exports_external.object({ - commands: exports_external.array(SlashCommandSchema()), - agents: exports_external.array(AgentInfoSchema()), - output_style: exports_external.string(), - available_output_styles: exports_external.array(exports_external.string()), - models: exports_external.array(ModelInfoSchema()), - account: AccountInfoSchema(), - pid: exports_external.number().optional().describe("@internal CLI process PID for tmux socket isolation"), - fast_mode_state: FastModeStateSchema().optional() - }).describe("Response from session initialization with available commands, models, and account info.")); - SDKControlInterruptRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("interrupt") - }).describe("Interrupts the currently running conversation turn.")); - SDKControlPermissionRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("can_use_tool"), - tool_name: exports_external.string(), - input: exports_external.record(exports_external.string(), exports_external.unknown()), - permission_suggestions: exports_external.array(PermissionUpdateSchema()).optional(), - blocked_path: exports_external.string().optional(), - decision_reason: exports_external.string().optional(), - title: exports_external.string().optional(), - display_name: exports_external.string().optional(), - tool_use_id: exports_external.string(), - agent_id: exports_external.string().optional(), - description: exports_external.string().optional() - }).describe("Requests permission to use a tool with the given input.")); - SDKControlSetPermissionModeRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("set_permission_mode"), - mode: PermissionModeSchema(), - ultraplan: exports_external.boolean().optional().describe("@internal CCR ultraplan session marker.") - }).describe("Sets the permission mode for tool execution handling.")); - SDKControlSetModelRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("set_model"), - model: exports_external.string().optional() - }).describe("Sets the model to use for subsequent conversation turns.")); - SDKControlSetMaxThinkingTokensRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("set_max_thinking_tokens"), - max_thinking_tokens: exports_external.number().nullable() - }).describe("Sets the maximum number of thinking tokens for extended thinking.")); - SDKControlMcpStatusRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("mcp_status") - }).describe("Requests the current status of all MCP server connections.")); - SDKControlMcpStatusResponseSchema = lazySchema(() => exports_external.object({ - mcpServers: exports_external.array(McpServerStatusSchema()) - }).describe("Response containing the current status of all MCP server connections.")); - SDKControlGetContextUsageRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("get_context_usage") - }).describe("Requests a breakdown of current context window usage by category.")); - ContextCategorySchema = lazySchema(() => exports_external.object({ - name: exports_external.string(), - tokens: exports_external.number(), - color: exports_external.string(), - isDeferred: exports_external.boolean().optional() - })); - ContextGridSquareSchema = lazySchema(() => exports_external.object({ - color: exports_external.string(), - isFilled: exports_external.boolean(), - categoryName: exports_external.string(), - tokens: exports_external.number(), - percentage: exports_external.number(), - squareFullness: exports_external.number() - })); - SDKControlGetContextUsageResponseSchema = lazySchema(() => exports_external.object({ - categories: exports_external.array(ContextCategorySchema()), - totalTokens: exports_external.number(), - maxTokens: exports_external.number(), - rawMaxTokens: exports_external.number(), - percentage: exports_external.number(), - gridRows: exports_external.array(exports_external.array(ContextGridSquareSchema())), - model: exports_external.string(), - memoryFiles: exports_external.array(exports_external.object({ - path: exports_external.string(), - type: exports_external.string(), - tokens: exports_external.number() - })), - mcpTools: exports_external.array(exports_external.object({ - name: exports_external.string(), - serverName: exports_external.string(), - tokens: exports_external.number(), - isLoaded: exports_external.boolean().optional() - })), - deferredBuiltinTools: exports_external.array(exports_external.object({ - name: exports_external.string(), - tokens: exports_external.number(), - isLoaded: exports_external.boolean() - })).optional(), - systemTools: exports_external.array(exports_external.object({ name: exports_external.string(), tokens: exports_external.number() })).optional(), - systemPromptSections: exports_external.array(exports_external.object({ name: exports_external.string(), tokens: exports_external.number() })).optional(), - agents: exports_external.array(exports_external.object({ - agentType: exports_external.string(), - source: exports_external.string(), - tokens: exports_external.number() - })), - slashCommands: exports_external.object({ - totalCommands: exports_external.number(), - includedCommands: exports_external.number(), - tokens: exports_external.number() - }).optional(), - skills: exports_external.object({ - totalSkills: exports_external.number(), - includedSkills: exports_external.number(), - tokens: exports_external.number(), - skillFrontmatter: exports_external.array(exports_external.object({ - name: exports_external.string(), - source: exports_external.string(), - tokens: exports_external.number() - })) - }).optional(), - autoCompactThreshold: exports_external.number().optional(), - isAutoCompactEnabled: exports_external.boolean(), - messageBreakdown: exports_external.object({ - toolCallTokens: exports_external.number(), - toolResultTokens: exports_external.number(), - attachmentTokens: exports_external.number(), - assistantMessageTokens: exports_external.number(), - userMessageTokens: exports_external.number(), - toolCallsByType: exports_external.array(exports_external.object({ - name: exports_external.string(), - callTokens: exports_external.number(), - resultTokens: exports_external.number() - })), - attachmentsByType: exports_external.array(exports_external.object({ name: exports_external.string(), tokens: exports_external.number() })) - }).optional(), - apiUsage: exports_external.object({ - input_tokens: exports_external.number(), - output_tokens: exports_external.number(), - cache_creation_input_tokens: exports_external.number(), - cache_read_input_tokens: exports_external.number() - }).nullable() - }).describe("Breakdown of current context window usage by category (system prompt, tools, messages, etc.).")); - SDKControlRewindFilesRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("rewind_files"), - user_message_id: exports_external.string(), - dry_run: exports_external.boolean().optional() - }).describe("Rewinds file changes made since a specific user message.")); - SDKControlRewindFilesResponseSchema = lazySchema(() => exports_external.object({ - canRewind: exports_external.boolean(), - error: exports_external.string().optional(), - filesChanged: exports_external.array(exports_external.string()).optional(), - insertions: exports_external.number().optional(), - deletions: exports_external.number().optional() - }).describe("Result of a rewindFiles operation.")); - SDKControlCancelAsyncMessageRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("cancel_async_message"), - message_uuid: exports_external.string() - }).describe("Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.")); - SDKControlCancelAsyncMessageResponseSchema = lazySchema(() => exports_external.object({ - cancelled: exports_external.boolean() - }).describe("Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).")); - SDKControlSeedReadStateRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("seed_read_state"), - path: exports_external.string(), - mtime: exports_external.number() - }).describe("Seeds the readFileState cache with a path+mtime entry. Use when a prior Read was removed from context (e.g. by snip) so Edit validation would fail despite the client having observed the Read. The mtime lets the CLI detect if the file changed since the seeded Read \u2014 same staleness check as the normal path.")); - SDKHookCallbackRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("hook_callback"), - callback_id: exports_external.string(), - input: HookInputSchema(), - tool_use_id: exports_external.string().optional() - }).describe("Delivers a hook callback with its input data.")); - SDKControlMcpMessageRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("mcp_message"), - server_name: exports_external.string(), - message: JSONRPCMessagePlaceholder() - }).describe("Sends a JSON-RPC message to a specific MCP server.")); - SDKControlMcpSetServersRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("mcp_set_servers"), - servers: exports_external.record(exports_external.string(), McpServerConfigForProcessTransportSchema()) - }).describe("Replaces the set of dynamically managed MCP servers.")); - SDKControlMcpSetServersResponseSchema = lazySchema(() => exports_external.object({ - added: exports_external.array(exports_external.string()), - removed: exports_external.array(exports_external.string()), - errors: exports_external.record(exports_external.string(), exports_external.string()) - }).describe("Result of replacing the set of dynamically managed MCP servers.")); - SDKControlReloadPluginsRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("reload_plugins") - }).describe("Reloads plugins from disk and returns the refreshed session components.")); - SDKControlReloadPluginsResponseSchema = lazySchema(() => exports_external.object({ - commands: exports_external.array(SlashCommandSchema()), - agents: exports_external.array(AgentInfoSchema()), - plugins: exports_external.array(exports_external.object({ - name: exports_external.string(), - path: exports_external.string(), - source: exports_external.string().optional() - })), - mcpServers: exports_external.array(McpServerStatusSchema()), - error_count: exports_external.number() - }).describe("Refreshed commands, agents, plugins, and MCP server status after reload.")); - SDKControlMcpReconnectRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("mcp_reconnect"), - serverName: exports_external.string() - }).describe("Reconnects a disconnected or failed MCP server.")); - SDKControlMcpToggleRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("mcp_toggle"), - serverName: exports_external.string(), - enabled: exports_external.boolean() - }).describe("Enables or disables an MCP server.")); - SDKControlStopTaskRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("stop_task"), - task_id: exports_external.string() - }).describe("Stops a running task.")); - SDKControlApplyFlagSettingsRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("apply_flag_settings"), - settings: exports_external.record(exports_external.string(), exports_external.unknown()) - }).describe("Merges the provided settings into the flag settings layer, updating the active configuration.")); - SDKControlGetSettingsRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("get_settings") - }).describe("Returns the effective merged settings and the raw per-source settings.")); - SDKControlGetSettingsResponseSchema = lazySchema(() => exports_external.object({ - effective: exports_external.record(exports_external.string(), exports_external.unknown()), - sources: exports_external.array(exports_external.object({ - source: exports_external.enum([ - "userSettings", - "projectSettings", - "localSettings", - "flagSettings", - "policySettings" - ]), - settings: exports_external.record(exports_external.string(), exports_external.unknown()) - })).describe("Ordered low-to-high priority \u2014 later entries override earlier ones."), - applied: exports_external.object({ - model: exports_external.string(), - effort: exports_external.enum(["low", "medium", "high", "max"]).nullable() - }).optional().describe("Runtime-resolved values after env overrides, session state, and model-specific defaults are applied. Unlike `effective` (disk merge), these reflect what will actually be sent to the API.") - }).describe("Effective merged settings plus raw per-source settings in merge order.")); - SDKControlElicitationRequestSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("elicitation"), - mcp_server_name: exports_external.string(), - message: exports_external.string(), - mode: exports_external.enum(["form", "url"]).optional(), - url: exports_external.string().optional(), - elicitation_id: exports_external.string().optional(), - requested_schema: exports_external.record(exports_external.string(), exports_external.unknown()).optional() - }).describe("Requests the SDK consumer to handle an MCP elicitation (user input request).")); - SDKControlElicitationResponseSchema = lazySchema(() => exports_external.object({ - action: exports_external.enum(["accept", "decline", "cancel"]), - content: exports_external.record(exports_external.string(), exports_external.unknown()).optional() - }).describe("Response from the SDK consumer for an elicitation request.")); - SDKControlRequestInnerSchema = lazySchema(() => exports_external.union([ - SDKControlInterruptRequestSchema(), - SDKControlPermissionRequestSchema(), - SDKControlInitializeRequestSchema(), - SDKControlSetPermissionModeRequestSchema(), - SDKControlSetModelRequestSchema(), - SDKControlSetMaxThinkingTokensRequestSchema(), - SDKControlMcpStatusRequestSchema(), - SDKControlGetContextUsageRequestSchema(), - SDKHookCallbackRequestSchema(), - SDKControlMcpMessageRequestSchema(), - SDKControlRewindFilesRequestSchema(), - SDKControlCancelAsyncMessageRequestSchema(), - SDKControlSeedReadStateRequestSchema(), - SDKControlMcpSetServersRequestSchema(), - SDKControlReloadPluginsRequestSchema(), - SDKControlMcpReconnectRequestSchema(), - SDKControlMcpToggleRequestSchema(), - SDKControlStopTaskRequestSchema(), - SDKControlApplyFlagSettingsRequestSchema(), - SDKControlGetSettingsRequestSchema(), - SDKControlElicitationRequestSchema() - ])); - SDKControlRequestSchema = lazySchema(() => exports_external.object({ - type: exports_external.literal("control_request"), - request_id: exports_external.string(), - request: SDKControlRequestInnerSchema() - })); - ControlResponseSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("success"), - request_id: exports_external.string(), - response: exports_external.record(exports_external.string(), exports_external.unknown()).optional() - })); - ControlErrorResponseSchema = lazySchema(() => exports_external.object({ - subtype: exports_external.literal("error"), - request_id: exports_external.string(), - error: exports_external.string(), - pending_permission_requests: exports_external.array(exports_external.lazy(() => SDKControlRequestSchema())).optional() - })); - SDKControlResponseSchema = lazySchema(() => exports_external.object({ - type: exports_external.literal("control_response"), - response: exports_external.union([ControlResponseSchema(), ControlErrorResponseSchema()]) - })); - SDKControlCancelRequestSchema = lazySchema(() => exports_external.object({ - type: exports_external.literal("control_cancel_request"), - request_id: exports_external.string() - }).describe("Cancels a currently open control request.")); - SDKKeepAliveMessageSchema = lazySchema(() => exports_external.object({ - type: exports_external.literal("keep_alive") - }).describe("Keep-alive message to maintain WebSocket connection.")); - SDKUpdateEnvironmentVariablesMessageSchema = lazySchema(() => exports_external.object({ - type: exports_external.literal("update_environment_variables"), - variables: exports_external.record(exports_external.string(), exports_external.string()) - }).describe("Updates environment variables at runtime.")); - StdoutMessageSchema = lazySchema(() => exports_external.union([ - SDKMessageSchema(), - SDKStreamlinedTextMessageSchema(), - SDKStreamlinedToolUseSummaryMessageSchema(), - SDKPostTurnSummaryMessageSchema(), - SDKControlResponseSchema(), - SDKControlRequestSchema(), - SDKControlCancelRequestSchema(), - SDKKeepAliveMessageSchema() - ])); - StdinMessageSchema = lazySchema(() => exports_external.union([ - SDKUserMessageSchema(), - SDKControlRequestSchema(), - SDKControlResponseSchema(), - SDKKeepAliveMessageSchema(), - SDKUpdateEnvironmentVariablesMessageSchema() - ])); -}); - -// src/utils/permissions/PermissionPromptToolResultSchema.ts -function permissionPromptToolResultToPermissionDecision(result, tool, input, toolUseContext) { - const decisionReason = { - type: "permissionPromptTool", - permissionPromptToolName: tool.name, - toolResult: result - }; - if (result.behavior === "allow") { - const updatedPermissions = result.updatedPermissions; - if (updatedPermissions) { - toolUseContext.setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdates(prev.toolPermissionContext, updatedPermissions) - })); - persistPermissionUpdates(updatedPermissions); - } - const updatedInput = Object.keys(result.updatedInput).length > 0 ? result.updatedInput : input; - return { - ...result, - updatedInput, - decisionReason - }; - } else if (result.behavior === "deny" && result.interrupt) { - logForDebugging(`SDK permission prompt deny+interrupt: tool=${tool.name} message=${result.message}`); - toolUseContext.abortController.abort(); - } - return { - ...result, - decisionReason - }; -} -var inputSchema39, decisionClassificationField, PermissionAllowResultSchema, PermissionDenyResultSchema, outputSchema32; -var init_PermissionPromptToolResultSchema = __esm(() => { - init_v4(); - init_debug(); - init_PermissionUpdate(); - init_PermissionUpdateSchema(); - inputSchema39 = lazySchema(() => v4_default.object({ - tool_name: v4_default.string().describe("The name of the tool requesting permission"), - input: v4_default.record(v4_default.string(), v4_default.unknown()).describe("The input for the tool"), - tool_use_id: v4_default.string().optional().describe("The unique tool use request ID") - })); - decisionClassificationField = lazySchema(() => v4_default.enum(["user_temporary", "user_permanent", "user_reject"]).optional().catch(undefined)); - PermissionAllowResultSchema = lazySchema(() => v4_default.object({ - behavior: v4_default.literal("allow"), - updatedInput: v4_default.record(v4_default.string(), v4_default.unknown()), - updatedPermissions: v4_default.array(permissionUpdateSchema()).optional().catch((ctx) => { - logForDebugging(`Malformed updatedPermissions from SDK host ignored: ${ctx.error.issues[0]?.message ?? "unknown"}`, { level: "warn" }); - return; - }), - toolUseID: v4_default.string().optional(), - decisionClassification: decisionClassificationField() - })); - PermissionDenyResultSchema = lazySchema(() => v4_default.object({ - behavior: v4_default.literal("deny"), - message: v4_default.string(), - interrupt: v4_default.boolean().optional(), - toolUseID: v4_default.string().optional(), - decisionClassification: decisionClassificationField() - })); - outputSchema32 = lazySchema(() => v4_default.union([PermissionAllowResultSchema(), PermissionDenyResultSchema()])); -}); - -// src/cli/ndjsonSafeStringify.ts -function escapeJsLineTerminators(json2) { - return json2.replace(JS_LINE_TERMINATORS, (c9) => c9 === "\u2028" ? "\\u2028" : "\\u2029"); -} -function ndjsonSafeStringify(value) { - return escapeJsLineTerminators(jsonStringify(value)); -} -var JS_LINE_TERMINATORS; -var init_ndjsonSafeStringify = __esm(() => { - init_slowOperations(); - JS_LINE_TERMINATORS = /\u2028|\u2029/g; -}); - -// src/cli/structuredIO.ts -import { randomUUID as randomUUID48 } from "crypto"; -function serializeDecisionReason(reason) { - if (!reason) { - return; - } - if (false) {} - switch (reason.type) { - case "rule": - case "mode": - case "subcommandResults": - case "permissionPromptTool": - return; - case "hook": - case "asyncAgent": - case "sandboxOverride": - case "workingDir": - case "safetyCheck": - case "other": - return reason.reason; - } -} -function buildRequiresActionDetails(tool, input, toolUseID, requestId) { - let description; - try { - description = tool.getActivityDescription?.(input) ?? tool.getToolUseSummary?.(input) ?? tool.userFacingName(input); - } catch { - description = tool.name; - } - return { - tool_name: tool.name, - action_description: description, - tool_use_id: toolUseID, - request_id: requestId, - input - }; -} - -class StructuredIO { - input; - replayUserMessages; - structuredInput; - pendingRequests = new Map; - restoredWorkerState = Promise.resolve(null); - inputClosed = false; - unexpectedResponseCallback; - resolvedToolUseIds = new Set; - prependedLines = []; - onControlRequestSent; - onControlRequestResolved; - outbound = new Stream7; - constructor(input, replayUserMessages) { - this.input = input; - this.replayUserMessages = replayUserMessages; - this.input = input; - this.structuredInput = this.read(); - } - trackResolvedToolUseId(request2) { - if (request2.request.subtype === "can_use_tool") { - this.resolvedToolUseIds.add(request2.request.tool_use_id); - if (this.resolvedToolUseIds.size > MAX_RESOLVED_TOOL_USE_IDS) { - const first = this.resolvedToolUseIds.values().next().value; - if (first !== undefined) { - this.resolvedToolUseIds.delete(first); - } - } - } - } - flushInternalEvents() { - return Promise.resolve(); - } - get internalEventsPending() { - return 0; - } - prependUserMessage(content) { - this.prependedLines.push(jsonStringify({ - type: "user", - session_id: "", - message: { role: "user", content }, - parent_tool_use_id: null - }) + ` -`); - } - async* read() { - let content = ""; - const splitAndProcess = async function* () { - for (;; ) { - if (this.prependedLines.length > 0) { - content = this.prependedLines.join("") + content; - this.prependedLines = []; - } - const newline2 = content.indexOf(` -`); - if (newline2 === -1) - break; - const line = content.slice(0, newline2); - content = content.slice(newline2 + 1); - const message = await this.processLine(line); - if (message) { - logForDiagnosticsNoPII("info", "cli_stdin_message_parsed", { - type: message.type - }); - yield message; - } - } - }.bind(this); - yield* splitAndProcess(); - for await (const block2 of this.input) { - content += block2; - yield* splitAndProcess(); - } - if (content) { - const message = await this.processLine(content); - if (message) { - yield message; - } - } - this.inputClosed = true; - for (const request2 of this.pendingRequests.values()) { - request2.reject(new Error("Tool permission stream closed before response received")); - } - } - getPendingPermissionRequests() { - return Array.from(this.pendingRequests.values()).map((entry) => entry.request).filter((pr) => pr.request.subtype === "can_use_tool"); - } - setUnexpectedResponseCallback(callback) { - this.unexpectedResponseCallback = callback; - } - injectControlResponse(response7) { - const requestId = response7.response?.request_id; - if (!requestId) - return; - const request2 = this.pendingRequests.get(requestId); - if (!request2) - return; - this.trackResolvedToolUseId(request2.request); - this.pendingRequests.delete(requestId); - this.write({ - type: "control_cancel_request", - request_id: requestId - }); - if (response7.response.subtype === "error") { - request2.reject(new Error(response7.response.error)); - } else { - const result = response7.response.response; - if (request2.schema) { - try { - request2.resolve(request2.schema.parse(result)); - } catch (error46) { - request2.reject(error46); - } - } else { - request2.resolve({}); - } - } - } - setOnControlRequestSent(callback) { - this.onControlRequestSent = callback; - } - setOnControlRequestResolved(callback) { - this.onControlRequestResolved = callback; - } - async processLine(line) { - if (!line) { - return; - } - try { - const message = normalizeControlMessageKeys(jsonParse(line)); - if (message.type === "keep_alive") { - return; - } - if (message.type === "update_environment_variables") { - const keys2 = Object.keys(message.variables); - for (const [key2, value] of Object.entries(message.variables)) { - process.env[key2] = value; - } - logForDebugging(`[structuredIO] applied update_environment_variables: ${keys2.join(", ")}`); - return; - } - if (message.type === "control_response") { - const uuid8 = "uuid" in message && typeof message.uuid === "string" ? message.uuid : undefined; - if (uuid8) { - notifyCommandLifecycle(uuid8, "completed"); - } - const request2 = this.pendingRequests.get(message.response.request_id); - if (!request2) { - const responsePayload = message.response.subtype === "success" ? message.response.response : undefined; - const toolUseID = responsePayload?.toolUseID; - if (typeof toolUseID === "string" && this.resolvedToolUseIds.has(toolUseID)) { - logForDebugging(`Ignoring duplicate control_response for already-resolved toolUseID=${toolUseID} request_id=${message.response.request_id}`); - return; - } - if (this.unexpectedResponseCallback) { - await this.unexpectedResponseCallback(message); - } - return; - } - this.trackResolvedToolUseId(request2.request); - this.pendingRequests.delete(message.response.request_id); - if (request2.request.request.subtype === "can_use_tool" && this.onControlRequestResolved) { - this.onControlRequestResolved(message.response.request_id); - } - if (message.response.subtype === "error") { - request2.reject(new Error(message.response.error)); - return; - } - const result = message.response.response; - if (request2.schema) { - try { - request2.resolve(request2.schema.parse(result)); - } catch (error46) { - request2.reject(error46); - } - } else { - request2.resolve({}); - } - if (this.replayUserMessages) { - return message; - } - return; - } - if (message.type !== "user" && message.type !== "control_request" && message.type !== "assistant" && message.type !== "system") { - logForDebugging(`Ignoring unknown message type: ${message.type}`, { - level: "warn" - }); - return; - } - if (message.type === "control_request") { - if (!message.request) { - exitWithMessage(`Error: Missing request on control_request`); - } - return message; - } - if (message.type === "assistant" || message.type === "system") { - return message; - } - if (message.message.role !== "user") { - exitWithMessage(`Error: Expected message role 'user', got '${message.message.role}'`); - } - return message; - } catch (error46) { - console.error(`Error parsing streaming input line: ${line}: ${error46}`); - process.exit(1); - } - } - async write(message) { - writeToStdout(ndjsonSafeStringify(message) + ` -`); - } - async sendRequest(request2, schema5, signal, requestId = randomUUID48()) { - const message = { - type: "control_request", - request_id: requestId, - request: request2 - }; - if (this.inputClosed) { - throw new Error("Stream closed"); - } - if (signal?.aborted) { - throw new Error("Request aborted"); - } - this.outbound.enqueue(message); - if (request2.subtype === "can_use_tool" && this.onControlRequestSent) { - this.onControlRequestSent(message); - } - const aborted3 = () => { - this.outbound.enqueue({ - type: "control_cancel_request", - request_id: requestId - }); - const request3 = this.pendingRequests.get(requestId); - if (request3) { - this.trackResolvedToolUseId(request3.request); - request3.reject(new AbortError); - } - }; - if (signal) { - signal.addEventListener("abort", aborted3, { - once: true - }); - } - try { - return await new Promise((resolve43, reject2) => { - this.pendingRequests.set(requestId, { - request: { - type: "control_request", - request_id: requestId, - request: request2 - }, - resolve: (result) => { - resolve43(result); - }, - reject: reject2, - schema: schema5 - }); - }); - } finally { - if (signal) { - signal.removeEventListener("abort", aborted3); - } - this.pendingRequests.delete(requestId); - } - } - createCanUseTool(onPermissionPrompt) { - return async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => { - const mainPermissionResult = forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseID); - if (mainPermissionResult.behavior === "allow" || mainPermissionResult.behavior === "deny") { - return mainPermissionResult; - } - const hookAbortController = new AbortController; - const parentSignal = toolUseContext.abortController.signal; - const onParentAbort = () => hookAbortController.abort(); - parentSignal.addEventListener("abort", onParentAbort, { once: true }); - try { - const hookPromise = executePermissionRequestHooksForSDK(tool.name, toolUseID, input, toolUseContext, mainPermissionResult.suggestions).then((decision) => ({ source: "hook", decision })); - const requestId = randomUUID48(); - onPermissionPrompt?.(buildRequiresActionDetails(tool, input, toolUseID, requestId)); - const sdkPromise = this.sendRequest({ - subtype: "can_use_tool", - tool_name: tool.name, - input, - permission_suggestions: mainPermissionResult.suggestions, - blocked_path: mainPermissionResult.blockedPath, - decision_reason: serializeDecisionReason(mainPermissionResult.decisionReason), - tool_use_id: toolUseID, - agent_id: toolUseContext.agentId - }, outputSchema32(), hookAbortController.signal, requestId).then((result) => ({ source: "sdk", result })); - const winner = await Promise.race([hookPromise, sdkPromise]); - if (winner.source === "hook") { - if (winner.decision) { - sdkPromise.catch(() => {}); - hookAbortController.abort(); - return winner.decision; - } - const sdkResult = await sdkPromise; - return permissionPromptToolResultToPermissionDecision(sdkResult.result, tool, input, toolUseContext); - } - return permissionPromptToolResultToPermissionDecision(winner.result, tool, input, toolUseContext); - } catch (error46) { - return permissionPromptToolResultToPermissionDecision({ - behavior: "deny", - message: `Tool permission request failed: ${error46}`, - toolUseID - }, tool, input, toolUseContext); - } finally { - if (this.getPendingPermissionRequests().length === 0) { - notifySessionStateChanged("running"); - } - parentSignal.removeEventListener("abort", onParentAbort); - } - }; - } - createHookCallback(callbackId, timeout2) { - return { - type: "callback", - timeout: timeout2, - callback: async (input, toolUseID, abort7) => { - try { - const result = await this.sendRequest({ - subtype: "hook_callback", - callback_id: callbackId, - input, - tool_use_id: toolUseID || undefined - }, hookJSONOutputSchema(), abort7); - return result; - } catch (error46) { - console.error(`Error in hook callback ${callbackId}:`, error46); - return {}; - } - } - }; - } - async handleElicitation(serverName, message, requestedSchema, signal, mode, url3, elicitationId) { - try { - const result = await this.sendRequest({ - subtype: "elicitation", - mcp_server_name: serverName, - message, - mode, - url: url3, - elicitation_id: elicitationId, - requested_schema: requestedSchema - }, SDKControlElicitationResponseSchema(), signal); - return result; - } catch { - return { action: "cancel" }; - } - } - createSandboxAskCallback() { - return async (hostPattern) => { - try { - const result = await this.sendRequest({ - subtype: "can_use_tool", - tool_name: SANDBOX_NETWORK_ACCESS_TOOL_NAME, - input: { host: hostPattern.host }, - tool_use_id: randomUUID48(), - description: `Allow network connection to ${hostPattern.host}?` - }, outputSchema32()); - return result.behavior === "allow"; - } catch { - return false; - } - }; - } - async sendMcpMessage(serverName, message) { - const response7 = await this.sendRequest({ - subtype: "mcp_message", - server_name: serverName, - message - }, exports_external.object({ - mcp_response: exports_external.any() - })); - return response7.mcp_response; - } -} -function exitWithMessage(message) { - console.error(message); - process.exit(1); -} -async function executePermissionRequestHooksForSDK(toolName, toolUseID, input, toolUseContext, suggestions) { - const appState = toolUseContext.getAppState(); - const permissionMode = appState.toolPermissionContext.mode; - const hookGenerator = executePermissionRequestHooks(toolName, toolUseID, input, toolUseContext, permissionMode, suggestions, toolUseContext.abortController.signal); - for await (const hookResult of hookGenerator) { - if (hookResult.permissionRequestResult && (hookResult.permissionRequestResult.behavior === "allow" || hookResult.permissionRequestResult.behavior === "deny")) { - const decision = hookResult.permissionRequestResult; - if (decision.behavior === "allow") { - const finalInput = decision.updatedInput || input; - const permissionUpdates = decision.updatedPermissions ?? []; - if (permissionUpdates.length > 0) { - persistPermissionUpdates(permissionUpdates); - const currentAppState = toolUseContext.getAppState(); - const updatedContext = applyPermissionUpdates(currentAppState.toolPermissionContext, permissionUpdates); - toolUseContext.setAppState((prev) => { - if (prev.toolPermissionContext === updatedContext) - return prev; - return { ...prev, toolPermissionContext: updatedContext }; - }); - } - return { - behavior: "allow", - updatedInput: finalInput, - userModified: false, - decisionReason: { - type: "hook", - hookName: "PermissionRequest" - } - }; - } else { - return { - behavior: "deny", - message: decision.message || "Permission denied by PermissionRequest hook", - decisionReason: { - type: "hook", - hookName: "PermissionRequest" - } - }; - } - } - } - return; -} -var SANDBOX_NETWORK_ACCESS_TOOL_NAME = "SandboxNetworkAccess", MAX_RESOLVED_TOOL_USE_IDS = 1000; -var init_structuredIO = __esm(() => { - init_controlSchemas(); - init_hooks2(); - init_debug(); - init_diagLogs(); - init_errors(); - init_PermissionPromptToolResultSchema(); - init_permissions2(); - init_slowOperations(); - init_v4(); - init_hooks3(); - init_PermissionUpdate(); - init_sessionState(); - init_slowOperations(); - init_stream9(); - init_ndjsonSafeStringify(); -}); - -// src/hooks/useFileHistorySnapshotInit.ts -function useFileHistorySnapshotInit(initialFileHistorySnapshots, fileHistoryState, onUpdateState) { - const initialized5 = import_react300.useRef(false); - import_react300.useEffect(() => { - if (!fileHistoryEnabled() || initialized5.current) { - return; - } - initialized5.current = true; - if (initialFileHistorySnapshots) { - fileHistoryRestoreStateFromLog(initialFileHistorySnapshots, onUpdateState); - } - }, [fileHistoryState, initialFileHistorySnapshots, onUpdateState]); -} -var import_react300; -var init_useFileHistorySnapshotInit = __esm(() => { - init_fileHistory(); - import_react300 = __toESM(require_react(), 1); -}); - -// src/components/permissions/SandboxPermissionRequest.tsx -function SandboxPermissionRequest(t0) { - const $2 = import_compiler_runtime351.c(22); - const { - hostPattern: t1, - onUserResponse - } = t0; - const { - host - } = t1; - let t22; - if ($2[0] !== onUserResponse) { - t22 = function onSelect2(value) { - bb4: - switch (value) { - case "yes": { - onUserResponse({ - allow: true, - persistToSettings: false - }); - break bb4; - } - case "yes-dont-ask-again": { - onUserResponse({ - allow: true, - persistToSettings: true - }); - break bb4; - } - case "no": { - onUserResponse({ - allow: false, - persistToSettings: false - }); - } - } - }; - $2[0] = onUserResponse; - $2[1] = t22; - } else { - t22 = $2[1]; - } - const onSelect = t22; - let t32; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t32 = shouldAllowManagedSandboxDomainsOnly(); - $2[2] = t32; - } else { - t32 = $2[2]; - } - const managedDomainsOnly = t32; - let t4; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t4 = { - label: "Yes", - value: "yes" - }; - $2[3] = t4; - } else { - t4 = $2[3]; - } - let t5; - if ($2[4] !== host) { - t5 = !managedDomainsOnly ? [{ - label: /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - children: [ - "Yes, and don't ask again for ", - /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - bold: true, - children: host - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "yes-dont-ask-again" - }] : []; - $2[4] = host; - $2[5] = t5; - } else { - t5 = $2[5]; - } - let t6; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t6 = { - label: /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - children: [ - "No, and tell Claude what to do differently ", - /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - bold: true, - children: "(esc)" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "no" - }; - $2[6] = t6; - } else { - t6 = $2[6]; - } - let t7; - if ($2[7] !== t5) { - t7 = [t4, ...t5, t6]; - $2[7] = t5; - $2[8] = t7; - } else { - t7 = $2[8]; - } - const options2 = t7; - let t8; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - dimColor: true, - children: "Host:" - }, undefined, false, undefined, this); - $2[9] = t8; - } else { - t8 = $2[9]; - } - let t9; - if ($2[10] !== host) { - t9 = /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedBox_default, { - children: [ - t8, - /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - children: [ - " ", - host - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[10] = host; - $2[11] = t9; - } else { - t9 = $2[11]; - } - let t10; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedText, { - children: "Do you want to allow this connection?" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[12] = t10; - } else { - t10 = $2[12]; - } - let t11; - if ($2[13] !== onUserResponse) { - t11 = () => { - onUserResponse({ - allow: false, - persistToSettings: false - }); - }; - $2[13] = onUserResponse; - $2[14] = t11; - } else { - t11 = $2[14]; - } - let t12; - if ($2[15] !== onSelect || $2[16] !== options2 || $2[17] !== t11) { - t12 = /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(Select, { - options: options2, - onChange: onSelect, - onCancel: t11 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[15] = onSelect; - $2[16] = options2; - $2[17] = t11; - $2[18] = t12; - } else { - t12 = $2[18]; - } - let t13; - if ($2[19] !== t12 || $2[20] !== t9) { - t13 = /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(PermissionDialog, { - title: "Network request outside of sandbox", - children: /* @__PURE__ */ jsx_dev_runtime451.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - t9, - t10, - t12 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[19] = t12; - $2[20] = t9; - $2[21] = t13; - } else { - t13 = $2[21]; - } - return t13; -} -var import_compiler_runtime351, jsx_dev_runtime451; -var init_SandboxPermissionRequest = __esm(() => { - init_ink2(); - init_sandbox_adapter(); - init_select(); - init_PermissionDialog(); - import_compiler_runtime351 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime451 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/SandboxViolationExpandedView.tsx -function formatTime(date6) { - const h5 = date6.getHours() % 12 || 12; - const m4 = String(date6.getMinutes()).padStart(2, "0"); - const s4 = String(date6.getSeconds()).padStart(2, "0"); - const ampm = date6.getHours() < 12 ? "am" : "pm"; - return `${h5}:${m4}:${s4}${ampm}`; -} -function SandboxViolationExpandedView() { - const $2 = import_compiler_runtime352.c(15); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = []; - $2[0] = t0; - } else { - t0 = $2[0]; - } - const [violations, setViolations] = import_react301.useState(t0); - const [totalCount, setTotalCount] = import_react301.useState(0); - let t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - const store = SandboxManager.getSandboxViolationStore(); - const unsubscribe2 = store.subscribe((allViolations) => { - setViolations(allViolations.slice(-10)); - setTotalCount(store.getTotalCount()); - }); - return unsubscribe2; - }; - t22 = []; - $2[1] = t1; - $2[2] = t22; - } else { - t1 = $2[1]; - t22 = $2[2]; - } - import_react301.useEffect(t1, t22); - if (!SandboxManager.isSandboxingEnabled() || getPlatform() === "linux") { - return null; - } - if (totalCount === 0) { - return null; - } - const t32 = totalCount === 1 ? "operation" : "operations"; - let t4; - if ($2[3] !== t32 || $2[4] !== totalCount) { - t4 = /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedBox_default, { - marginLeft: 0, - children: /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedText, { - color: "permission", - children: [ - "\u29C8 Sandbox blocked ", - totalCount, - " total", - " ", - t32 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[3] = t32; - $2[4] = totalCount; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== violations) { - t5 = violations.map(_temp209); - $2[6] = violations; - $2[7] = t5; - } else { - t5 = $2[7]; - } - const t6 = Math.min(10, violations.length); - let t7; - if ($2[8] !== t6 || $2[9] !== totalCount) { - t7 = /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedBox_default, { - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "\u2026 showing last ", - t6, - " of ", - totalCount - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[8] = t6; - $2[9] = totalCount; - $2[10] = t7; - } else { - t7 = $2[10]; - } - let t8; - if ($2[11] !== t4 || $2[12] !== t5 || $2[13] !== t7) { - t8 = /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t4, - t5, - t7 - ] - }, undefined, true, undefined, this); - $2[11] = t4; - $2[12] = t5; - $2[13] = t7; - $2[14] = t8; - } else { - t8 = $2[14]; - } - return t8; -} -function _temp209(v6, i6) { - return /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedBox_default, { - paddingLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime452.jsxDEV(ThemedText, { - dimColor: true, - children: [ - formatTime(v6.timestamp), - v6.command ? ` ${v6.command}:` : "", - " ", - v6.line - ] - }, undefined, true, undefined, this) - }, `${v6.timestamp.getTime()}-${i6}`, false, undefined, this); -} -var import_compiler_runtime352, import_react301, jsx_dev_runtime452; -var init_SandboxViolationExpandedView = __esm(() => { - init_ink2(); - init_sandbox_adapter(); - init_platform2(); - import_compiler_runtime352 = __toESM(require_compiler_runtime(), 1); - import_react301 = __toESM(require_react(), 1); - jsx_dev_runtime452 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/notifs/useMcpConnectivityStatus.tsx -function useMcpConnectivityStatus(t0) { - const $2 = import_compiler_runtime353.c(4); - const { - mcpClients: t1 - } = t0; - const mcpClients = t1 === undefined ? EMPTY_MCP_CLIENTS : t1; - const { - addNotification - } = useNotifications(); - let t22; - let t32; - if ($2[0] !== addNotification || $2[1] !== mcpClients) { - t22 = () => { - if (getIsRemoteMode()) { - return; - } - const failedLocalClients = mcpClients.filter(_temp224); - const failedClaudeAiClients = mcpClients.filter(_temp287); - const needsAuthLocalServers = mcpClients.filter(_temp355); - const needsAuthClaudeAiServers = mcpClients.filter(_temp441); - if (failedLocalClients.length === 0 && failedClaudeAiClients.length === 0 && needsAuthLocalServers.length === 0 && needsAuthClaudeAiServers.length === 0) { - return; - } - if (failedLocalClients.length > 0) { - addNotification({ - key: "mcp-failed", - jsx: /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(jsx_dev_runtime453.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - color: "error", - children: [ - failedLocalClients.length, - " MCP", - " ", - failedLocalClients.length === 1 ? "server" : "servers", - " failed" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /mcp" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium" - }); - } - if (failedClaudeAiClients.length > 0) { - addNotification({ - key: "mcp-claudeai-failed", - jsx: /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(jsx_dev_runtime453.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - color: "error", - children: [ - failedClaudeAiClients.length, - " claude.ai", - " ", - failedClaudeAiClients.length === 1 ? "connector" : "connectors", - " ", - "unavailable" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /mcp" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium" - }); - } - if (needsAuthLocalServers.length > 0) { - addNotification({ - key: "mcp-needs-auth", - jsx: /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(jsx_dev_runtime453.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - color: "warning", - children: [ - needsAuthLocalServers.length, - " MCP", - " ", - needsAuthLocalServers.length === 1 ? "server needs" : "servers need", - " ", - "auth" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /mcp" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium" - }); - } - if (needsAuthClaudeAiServers.length > 0) { - addNotification({ - key: "mcp-claudeai-needs-auth", - jsx: /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(jsx_dev_runtime453.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - color: "warning", - children: [ - needsAuthClaudeAiServers.length, - " claude.ai", - " ", - needsAuthClaudeAiServers.length === 1 ? "connector needs" : "connectors need", - " ", - "auth" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime453.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /mcp" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium" - }); - } - }; - t32 = [addNotification, mcpClients]; - $2[0] = addNotification; - $2[1] = mcpClients; - $2[2] = t22; - $2[3] = t32; - } else { - t22 = $2[2]; - t32 = $2[3]; - } - import_react302.useEffect(t22, t32); -} -function _temp441(client_2) { - return client_2.type === "needs-auth" && client_2.config.type === "claudeai-proxy" && hasClaudeAiMcpEverConnected(client_2.name); -} -function _temp355(client_1) { - return client_1.type === "needs-auth" && client_1.config.type !== "claudeai-proxy"; -} -function _temp287(client_0) { - return client_0.type === "failed" && client_0.config.type === "claudeai-proxy" && hasClaudeAiMcpEverConnected(client_0.name); -} -function _temp224(client16) { - return client16.type === "failed" && client16.config.type !== "sse-ide" && client16.config.type !== "ws-ide" && client16.config.type !== "claudeai-proxy"; -} -var import_compiler_runtime353, import_react302, jsx_dev_runtime453, EMPTY_MCP_CLIENTS; -var init_useMcpConnectivityStatus = __esm(() => { - init_notifications(); - init_state(); - init_ink2(); - init_claudeai(); - import_compiler_runtime353 = __toESM(require_compiler_runtime(), 1); - import_react302 = __toESM(require_react(), 1); - jsx_dev_runtime453 = __toESM(require_jsx_dev_runtime(), 1); - EMPTY_MCP_CLIENTS = []; -}); - -// src/hooks/notifs/useAutoModeUnavailableNotification.ts -function useAutoModeUnavailableNotification() { - const { addNotification } = useNotifications(); - const mode = useAppState((s4) => s4.toolPermissionContext.mode); - const isAutoModeAvailable = useAppState((s4) => s4.toolPermissionContext.isAutoModeAvailable); - const shownRef = import_react303.useRef(false); - const prevModeRef = import_react303.useRef(mode); - import_react303.useEffect(() => { - const prevMode = prevModeRef.current; - prevModeRef.current = mode; - if (true) - return; - if (getIsRemoteMode()) - return; - if (shownRef.current) - return; - const wrappedPastAutoSlot = mode === "default" && prevMode !== "default" && prevMode !== "auto" && !isAutoModeAvailable && hasAutoModeOptIn(); - if (!wrappedPastAutoSlot) - return; - const reason = getAutoModeUnavailableReason(); - if (!reason) - return; - shownRef.current = true; - addNotification({ - key: "auto-mode-unavailable", - text: getAutoModeUnavailableNotification(reason), - color: "warning", - priority: "medium" - }); - }, [mode, isAutoModeAvailable, addNotification]); -} -var import_react303; -var init_useAutoModeUnavailableNotification = __esm(() => { - init_notifications(); - init_state(); - init_AppState(); - init_permissionSetup(); - init_settings2(); - import_react303 = __toESM(require_react(), 1); -}); - -// src/hooks/notifs/useLspInitializationNotification.tsx -function useLspInitializationNotification() { - const $2 = import_compiler_runtime354.c(10); - const { - addNotification - } = useNotifications(); - const setAppState = useSetAppState(); - const [shouldPoll, setShouldPoll] = React146.useState(_temp234); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = new Set; - $2[0] = t0; - } else { - t0 = $2[0]; - } - const notifiedErrorsRef = React146.useRef(t0); - let t1; - if ($2[1] !== addNotification || $2[2] !== setAppState) { - t1 = (source, errorMessage4) => { - const errorKey2 = `${source}:${errorMessage4}`; - if (notifiedErrorsRef.current.has(errorKey2)) { - return; - } - notifiedErrorsRef.current.add(errorKey2); - logForDebugging(`LSP error: ${source} - ${errorMessage4}`); - setAppState((prev) => { - const existingKeys = new Set(prev.plugins.errors.map(_temp288)); - const stateErrorKey = `generic-error:${source}:${errorMessage4}`; - if (existingKeys.has(stateErrorKey)) { - return prev; - } - return { - ...prev, - plugins: { - ...prev.plugins, - errors: [...prev.plugins.errors, { - type: "generic-error", - source, - error: errorMessage4 - }] - } - }; - }); - const displayName = source.startsWith("plugin:") ? source.split(":")[1] ?? source : source; - addNotification({ - key: `lsp-error-${source}`, - jsx: /* @__PURE__ */ jsx_dev_runtime454.jsxDEV(jsx_dev_runtime454.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime454.jsxDEV(ThemedText, { - color: "error", - children: [ - "LSP for ", - displayName, - " failed" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime454.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /plugin for details" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium", - timeoutMs: 8000 - }); - }; - $2[1] = addNotification; - $2[2] = setAppState; - $2[3] = t1; - } else { - t1 = $2[3]; - } - const addError = t1; - let t22; - if ($2[4] !== addError) { - t22 = () => { - if (getIsRemoteMode()) { - return; - } - if (getIsScrollDraining()) { - return; - } - const status2 = getInitializationStatus(); - if (status2.status === "failed") { - addError("lsp-manager", status2.error.message); - setShouldPoll(false); - return; - } - if (status2.status === "pending" || status2.status === "not-started") { - return; - } - const manager7 = getLspServerManager(); - if (manager7) { - const servers = manager7.getAllServers(); - for (const [serverName, server] of servers) { - if (server.state === "error" && server.lastError) { - addError(serverName, server.lastError.message); - } - } - } - }; - $2[4] = addError; - $2[5] = t22; - } else { - t22 = $2[5]; - } - const poll = t22; - useInterval(poll, shouldPoll ? LSP_POLL_INTERVAL_MS : null); - let t32; - let t4; - if ($2[6] !== poll || $2[7] !== shouldPoll) { - t32 = () => { - if (getIsRemoteMode() || !shouldPoll) { - return; - } - poll(); - }; - t4 = [poll, shouldPoll]; - $2[6] = poll; - $2[7] = shouldPoll; - $2[8] = t32; - $2[9] = t4; - } else { - t32 = $2[8]; - t4 = $2[9]; - } - React146.useEffect(t32, t4); -} -function _temp288(e4) { - if (e4.type === "generic-error") { - return `generic-error:${e4.source}:${e4.error}`; - } - return `${e4.type}:${e4.source}`; -} -function _temp234() { - return isEnvTruthy("true"); -} -var import_compiler_runtime354, React146, jsx_dev_runtime454, LSP_POLL_INTERVAL_MS = 5000; -var init_useLspInitializationNotification = __esm(() => { - init_dist4(); - init_state(); - init_notifications(); - init_ink2(); - init_manager7(); - init_AppState(); - init_debug(); - init_envUtils(); - import_compiler_runtime354 = __toESM(require_compiler_runtime(), 1); - React146 = __toESM(require_react(), 1); - jsx_dev_runtime454 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/binaryCheck.ts -async function isBinaryInstalled(command19) { - if (!command19 || !command19.trim()) { - logForDebugging("[binaryCheck] Empty command provided, returning false"); - return false; - } - const trimmedCommand = command19.trim(); - const cached3 = binaryCache.get(trimmedCommand); - if (cached3 !== undefined) { - logForDebugging(`[binaryCheck] Cache hit for '${trimmedCommand}': ${cached3}`); - return cached3; - } - let exists = false; - if (await which(trimmedCommand).catch(() => null)) { - exists = true; - } - binaryCache.set(trimmedCommand, exists); - logForDebugging(`[binaryCheck] Binary '${trimmedCommand}' ${exists ? "found" : "not found"}`); - return exists; -} -var binaryCache; -var init_binaryCheck = __esm(() => { - init_debug(); - init_which(); - binaryCache = new Map; -}); - -// src/utils/plugins/lspRecommendation.ts -import { extname as extname14 } from "path"; -function isOfficialMarketplace(name3) { - return ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(name3.toLowerCase()); -} -function extractLspInfoFromManifest(lspServers) { - if (!lspServers) { - return null; - } - if (typeof lspServers === "string") { - logForDebugging("[lspRecommendation] Skipping string path lspServers (not readable from marketplace)"); - return null; - } - if (Array.isArray(lspServers)) { - for (const item of lspServers) { - if (typeof item === "string") { - continue; - } - const info = extractFromServerConfigRecord(item); - if (info) { - return info; - } - } - return null; - } - return extractFromServerConfigRecord(lspServers); -} -function isRecord2(value) { - return typeof value === "object" && value !== null; -} -function extractFromServerConfigRecord(serverConfigs) { - const extensions20 = new Set; - let command19 = null; - for (const [_serverName, config10] of Object.entries(serverConfigs)) { - if (!isRecord2(config10)) { - continue; - } - if (!command19 && typeof config10.command === "string") { - command19 = config10.command; - } - const extMapping = config10.extensionToLanguage; - if (isRecord2(extMapping)) { - for (const ext of Object.keys(extMapping)) { - extensions20.add(ext.toLowerCase()); - } - } - } - if (!command19 || extensions20.size === 0) { - return null; - } - return { extensions: extensions20, command: command19 }; -} -async function getLspPluginsFromMarketplaces() { - const result = new Map; - try { - const config10 = await loadKnownMarketplacesConfig(); - for (const marketplaceName of Object.keys(config10)) { - try { - const marketplace = await getMarketplace(marketplaceName); - const isOfficial = isOfficialMarketplace(marketplaceName); - for (const entry of marketplace.plugins) { - if (!entry.lspServers) { - continue; - } - const lspInfo = extractLspInfoFromManifest(entry.lspServers); - if (!lspInfo) { - continue; - } - const pluginId = `${entry.name}@${marketplaceName}`; - result.set(pluginId, { - entry, - marketplaceName, - extensions: lspInfo.extensions, - command: lspInfo.command, - isOfficial - }); - } - } catch (error46) { - logForDebugging(`[lspRecommendation] Failed to load marketplace ${marketplaceName}: ${error46}`); - } - } - } catch (error46) { - logForDebugging(`[lspRecommendation] Failed to load marketplaces config: ${error46}`); - } - return result; -} -async function getMatchingLspPlugins(filePath) { - if (isLspRecommendationsDisabled()) { - logForDebugging("[lspRecommendation] Recommendations are disabled"); - return []; - } - const ext = extname14(filePath).toLowerCase(); - if (!ext) { - logForDebugging("[lspRecommendation] No file extension found"); - return []; - } - logForDebugging(`[lspRecommendation] Looking for LSP plugins for ${ext}`); - const allLspPlugins = await getLspPluginsFromMarketplaces(); - const config10 = getGlobalConfig(); - const neverPlugins = config10.lspRecommendationNeverPlugins ?? []; - const matchingPlugins = []; - for (const [pluginId, info] of allLspPlugins) { - if (!info.extensions.has(ext)) { - continue; - } - if (neverPlugins.includes(pluginId)) { - logForDebugging(`[lspRecommendation] Skipping ${pluginId} (in never suggest list)`); - continue; - } - if (isPluginInstalled(pluginId)) { - logForDebugging(`[lspRecommendation] Skipping ${pluginId} (already installed)`); - continue; - } - matchingPlugins.push({ info, pluginId }); - } - const pluginsWithBinary = []; - for (const { info, pluginId } of matchingPlugins) { - const binaryExists = await isBinaryInstalled(info.command); - if (binaryExists) { - pluginsWithBinary.push({ info, pluginId }); - logForDebugging(`[lspRecommendation] Binary '${info.command}' found for ${pluginId}`); - } else { - logForDebugging(`[lspRecommendation] Skipping ${pluginId} (binary '${info.command}' not found)`); - } - } - pluginsWithBinary.sort((a5, b5) => { - if (a5.info.isOfficial && !b5.info.isOfficial) - return -1; - if (!a5.info.isOfficial && b5.info.isOfficial) - return 1; - return 0; - }); - return pluginsWithBinary.map(({ info, pluginId }) => ({ - pluginId, - pluginName: info.entry.name, - marketplaceName: info.marketplaceName, - description: info.entry.description, - isOfficial: info.isOfficial, - extensions: Array.from(info.extensions), - command: info.command - })); -} -function addToNeverSuggest(pluginId) { - saveGlobalConfig((currentConfig) => { - const current = currentConfig.lspRecommendationNeverPlugins ?? []; - if (current.includes(pluginId)) { - return currentConfig; - } - return { - ...currentConfig, - lspRecommendationNeverPlugins: [...current, pluginId] - }; - }); - logForDebugging(`[lspRecommendation] Added ${pluginId} to never suggest`); -} -function incrementIgnoredCount() { - saveGlobalConfig((currentConfig) => { - const newCount = (currentConfig.lspRecommendationIgnoredCount ?? 0) + 1; - return { - ...currentConfig, - lspRecommendationIgnoredCount: newCount - }; - }); - logForDebugging("[lspRecommendation] Incremented ignored count"); -} -function isLspRecommendationsDisabled() { - const config10 = getGlobalConfig(); - return config10.lspRecommendationDisabled === true || (config10.lspRecommendationIgnoredCount ?? 0) >= MAX_IGNORED_COUNT; -} -var MAX_IGNORED_COUNT = 5; -var init_lspRecommendation = __esm(() => { - init_binaryCheck(); - init_config(); - init_debug(); - init_installedPluginsManager(); - init_marketplaceManager(); - init_schemas3(); -}); - -// src/hooks/usePluginRecommendationBase.tsx -function usePluginRecommendationBase() { - const $2 = import_compiler_runtime355.c(6); - const [recommendation, setRecommendation] = React147.useState(null); - const isCheckingRef = React147.useRef(false); - let t0; - if ($2[0] !== recommendation) { - t0 = (resolve43) => { - if (getIsRemoteMode()) { - return; - } - if (recommendation) { - return; - } - if (isCheckingRef.current) { - return; - } - isCheckingRef.current = true; - resolve43().then((rec) => { - if (rec) { - setRecommendation(rec); - } - }).catch(logError2).finally(() => { - isCheckingRef.current = false; - }); - }; - $2[0] = recommendation; - $2[1] = t0; - } else { - t0 = $2[1]; - } - const tryResolve = t0; - let t1; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => setRecommendation(null); - $2[2] = t1; - } else { - t1 = $2[2]; - } - const clearRecommendation = t1; - let t22; - if ($2[3] !== recommendation || $2[4] !== tryResolve) { - t22 = { - recommendation, - clearRecommendation, - tryResolve - }; - $2[3] = recommendation; - $2[4] = tryResolve; - $2[5] = t22; - } else { - t22 = $2[5]; - } - return t22; -} -async function installPluginAndNotify(pluginId, pluginName, keyPrefix, addNotification, install) { - try { - const pluginData = await getPluginById(pluginId); - if (!pluginData) { - throw new Error(`Plugin ${pluginId} not found in marketplace`); - } - await install(pluginData); - addNotification({ - key: `${keyPrefix}-installed`, - jsx: /* @__PURE__ */ jsx_dev_runtime455.jsxDEV(ThemedText, { - color: "success", - children: [ - figures_default.tick, - " ", - pluginName, - " installed \xB7 restart to apply" - ] - }, undefined, true, undefined, this), - priority: "immediate", - timeoutMs: 5000 - }); - } catch (error46) { - logError2(error46); - addNotification({ - key: `${keyPrefix}-install-failed`, - jsx: /* @__PURE__ */ jsx_dev_runtime455.jsxDEV(ThemedText, { - color: "error", - children: [ - "Failed to install ", - pluginName - ] - }, undefined, true, undefined, this), - priority: "immediate", - timeoutMs: 5000 - }); - } -} -var import_compiler_runtime355, React147, jsx_dev_runtime455; -var init_usePluginRecommendationBase = __esm(() => { - init_figures(); - init_state(); - init_ink2(); - init_log2(); - init_marketplaceManager(); - import_compiler_runtime355 = __toESM(require_compiler_runtime(), 1); - React147 = __toESM(require_react(), 1); - jsx_dev_runtime455 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useLspPluginRecommendation.tsx -import { extname as extname15, join as join148 } from "path"; -function useLspPluginRecommendation() { - const $2 = import_compiler_runtime356.c(12); - const trackedFiles = useAppState(_temp244); - const { - addNotification - } = useNotifications(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = new Set; - $2[0] = t0; - } else { - t0 = $2[0]; - } - const checkedFilesRef = React148.useRef(t0); - const { - recommendation, - clearRecommendation, - tryResolve - } = usePluginRecommendationBase(); - let t1; - let t22; - if ($2[1] !== trackedFiles || $2[2] !== tryResolve) { - t1 = () => { - tryResolve(async () => { - if (hasShownLspRecommendationThisSession()) { - return null; - } - const newFiles = []; - for (const file2 of trackedFiles) { - if (!checkedFilesRef.current.has(file2)) { - checkedFilesRef.current.add(file2); - newFiles.push(file2); - } - } - for (const filePath of newFiles) { - try { - const matches = await getMatchingLspPlugins(filePath); - const match = matches[0]; - if (match) { - logForDebugging(`[useLspPluginRecommendation] Found match: ${match.pluginName} for ${filePath}`); - setLspRecommendationShownThisSession(true); - return { - pluginId: match.pluginId, - pluginName: match.pluginName, - pluginDescription: match.description, - fileExtension: extname15(filePath), - shownAt: Date.now() - }; - } - } catch (t33) { - const error46 = t33; - logError2(error46); - } - } - return null; - }); - }; - t22 = [trackedFiles, tryResolve]; - $2[1] = trackedFiles; - $2[2] = tryResolve; - $2[3] = t1; - $2[4] = t22; - } else { - t1 = $2[3]; - t22 = $2[4]; - } - React148.useEffect(t1, t22); - let t32; - if ($2[5] !== addNotification || $2[6] !== clearRecommendation || $2[7] !== recommendation) { - t32 = (response7) => { - if (!recommendation) { - return; - } - const { - pluginId, - pluginName, - shownAt - } = recommendation; - logForDebugging(`[useLspPluginRecommendation] User response: ${response7} for ${pluginName}`); - bb60: - switch (response7) { - case "yes": { - installPluginAndNotify(pluginId, pluginName, "lsp-plugin", addNotification, async (pluginData) => { - logForDebugging(`[useLspPluginRecommendation] Installing plugin: ${pluginId}`); - const localSourcePath = typeof pluginData.entry.source === "string" ? join148(pluginData.marketplaceInstallLocation, pluginData.entry.source) : undefined; - await cacheAndRegisterPlugin(pluginId, pluginData.entry, "user", undefined, localSourcePath); - const settings = getSettingsForSource("userSettings"); - updateSettingsForSource("userSettings", { - enabledPlugins: { - ...settings?.enabledPlugins, - [pluginId]: true - } - }); - logForDebugging(`[useLspPluginRecommendation] Plugin installed: ${pluginId}`); - }); - break bb60; - } - case "no": { - const elapsed = Date.now() - shownAt; - if (elapsed >= TIMEOUT_THRESHOLD_MS) { - logForDebugging(`[useLspPluginRecommendation] Timeout detected (${elapsed}ms), incrementing ignored count`); - incrementIgnoredCount(); - } - break bb60; - } - case "never": { - addToNeverSuggest(pluginId); - break bb60; - } - case "disable": { - saveGlobalConfig(_temp289); - } - } - clearRecommendation(); - }; - $2[5] = addNotification; - $2[6] = clearRecommendation; - $2[7] = recommendation; - $2[8] = t32; - } else { - t32 = $2[8]; - } - const handleResponse = t32; - let t4; - if ($2[9] !== handleResponse || $2[10] !== recommendation) { - t4 = { - recommendation, - handleResponse - }; - $2[9] = handleResponse; - $2[10] = recommendation; - $2[11] = t4; - } else { - t4 = $2[11]; - } - return t4; -} -function _temp289(current) { - if (current.lspRecommendationDisabled) { - return current; - } - return { - ...current, - lspRecommendationDisabled: true - }; -} -function _temp244(s4) { - return s4.fileHistory.trackedFiles; -} -var import_compiler_runtime356, React148, TIMEOUT_THRESHOLD_MS = 28000; -var init_useLspPluginRecommendation = __esm(() => { - init_state(); - init_notifications(); - init_AppState(); - init_config(); - init_debug(); - init_log2(); - init_lspRecommendation(); - init_pluginInstallationHelpers(); - init_settings2(); - init_usePluginRecommendationBase(); - import_compiler_runtime356 = __toESM(require_compiler_runtime(), 1); - React148 = __toESM(require_react(), 1); -}); - -// src/components/LspRecommendation/LspRecommendationMenu.tsx -function LspRecommendationMenu({ - pluginName, - pluginDescription, - fileExtension: fileExtension3, - onResponse -}) { - const onResponseRef = React149.useRef(onResponse); - onResponseRef.current = onResponse; - React149.useEffect(() => { - const timeoutId = setTimeout((ref) => ref.current("no"), AUTO_DISMISS_MS2, onResponseRef); - return () => clearTimeout(timeoutId); - }, []); - function onSelect(value) { - switch (value) { - case "yes": - onResponse("yes"); - break; - case "no": - onResponse("no"); - break; - case "never": - onResponse("never"); - break; - case "disable": - onResponse("disable"); - break; - } - } - const options2 = [{ - label: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - children: [ - "Yes, install ", - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - bold: true, - children: pluginName - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "yes" - }, { - label: "No, not now", - value: "no" - }, { - label: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - children: [ - "Never for ", - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - bold: true, - children: pluginName - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "never" - }, { - label: "Disable all LSP recommendations", - value: "disable" - }]; - return /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(PermissionDialog, { - title: "LSP Plugin Recommendation", - children: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - dimColor: true, - children: "LSP provides code intelligence like go-to-definition and error checking" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - dimColor: true, - children: "Plugin:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - children: [ - " ", - pluginName - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - pluginDescription && /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - dimColor: true, - children: pluginDescription - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - dimColor: true, - children: "Triggered by:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - children: [ - " ", - fileExtension3, - " files" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedText, { - children: "Would you like to install this LSP plugin?" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime456.jsxDEV(Select, { - options: options2, - onChange: onSelect, - onCancel: () => onResponse("no") - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var React149, jsx_dev_runtime456, AUTO_DISMISS_MS2 = 30000; -var init_LspRecommendationMenu = __esm(() => { - init_ink2(); - init_select(); - init_PermissionDialog(); - React149 = __toESM(require_react(), 1); - jsx_dev_runtime456 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useClaudeCodeHintRecommendation.tsx -function useClaudeCodeHintRecommendation() { - const $2 = import_compiler_runtime357.c(11); - const pendingHint2 = React150.useSyncExternalStore(subscribeToPendingHint, getPendingHintSnapshot); - const { - addNotification - } = useNotifications(); - const { - recommendation, - clearRecommendation, - tryResolve - } = usePluginRecommendationBase(); - let t0; - let t1; - if ($2[0] !== pendingHint2 || $2[1] !== tryResolve) { - t0 = () => { - if (!pendingHint2) { - return; - } - tryResolve(async () => { - const resolved = await resolvePluginHint(pendingHint2); - if (resolved) { - logForDebugging(`[useClaudeCodeHintRecommendation] surfacing ${resolved.pluginId} from ${resolved.sourceCommand}`); - markShownThisSession(); - } - if (getPendingHintSnapshot() === pendingHint2) { - clearPendingHint(); - } - return resolved; - }); - }; - t1 = [pendingHint2, tryResolve]; - $2[0] = pendingHint2; - $2[1] = tryResolve; - $2[2] = t0; - $2[3] = t1; - } else { - t0 = $2[2]; - t1 = $2[3]; - } - React150.useEffect(t0, t1); - let t22; - if ($2[4] !== addNotification || $2[5] !== clearRecommendation || $2[6] !== recommendation) { - t22 = (response7) => { - if (!recommendation) { - return; - } - markHintPluginShown(recommendation.pluginId); - logEvent("tengu_plugin_hint_response", { - _PROTO_plugin_name: recommendation.pluginName, - _PROTO_marketplace_name: recommendation.marketplaceName, - response: response7 - }); - bb15: - switch (response7) { - case "yes": { - const { - pluginId, - pluginName, - marketplaceName - } = recommendation; - installPluginAndNotify(pluginId, pluginName, "hint-plugin", addNotification, async (pluginData) => { - const result = await installPluginFromMarketplace({ - pluginId, - entry: pluginData.entry, - marketplaceName, - scope: "user", - trigger: "hint" - }); - if (!result.success) { - throw new Error(result.error); - } - }); - break bb15; - } - case "disable": { - disableHintRecommendations(); - break bb15; - } - case "no": - } - clearRecommendation(); - }; - $2[4] = addNotification; - $2[5] = clearRecommendation; - $2[6] = recommendation; - $2[7] = t22; - } else { - t22 = $2[7]; - } - const handleResponse = t22; - let t32; - if ($2[8] !== handleResponse || $2[9] !== recommendation) { - t32 = { - recommendation, - handleResponse - }; - $2[8] = handleResponse; - $2[9] = recommendation; - $2[10] = t32; - } else { - t32 = $2[10]; - } - return t32; -} -var import_compiler_runtime357, React150; -var init_useClaudeCodeHintRecommendation = __esm(() => { - init_notifications(); - init_analytics(); - init_claudeCodeHints(); - init_debug(); - init_hintRecommendation(); - init_pluginInstallationHelpers(); - init_usePluginRecommendationBase(); - import_compiler_runtime357 = __toESM(require_compiler_runtime(), 1); - React150 = __toESM(require_react(), 1); -}); - -// src/components/ClaudeCodeHint/PluginHintMenu.tsx -function PluginHintMenu({ - pluginName, - pluginDescription, - marketplaceName, - sourceCommand, - onResponse -}) { - const onResponseRef = React151.useRef(onResponse); - onResponseRef.current = onResponse; - React151.useEffect(() => { - const timeoutId = setTimeout((ref) => ref.current("no"), AUTO_DISMISS_MS3, onResponseRef); - return () => clearTimeout(timeoutId); - }, []); - function onSelect(value) { - switch (value) { - case "yes": - onResponse("yes"); - break; - case "disable": - onResponse("disable"); - break; - default: - onResponse("no"); - } - } - const options2 = [{ - label: /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - children: [ - "Yes, install ", - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - bold: true, - children: pluginName - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: "yes" - }, { - label: "No", - value: "no" - }, { - label: "No, and don't show plugin installation hints again", - value: "disable" - }]; - return /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(PermissionDialog, { - title: "Plugin Recommendation", - children: /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "The ", - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - bold: true, - children: sourceCommand - }, undefined, false, undefined, this), - " command suggests installing a plugin." - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - dimColor: true, - children: "Plugin:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - children: [ - " ", - pluginName - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - dimColor: true, - children: "Marketplace:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - children: [ - " ", - marketplaceName - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - pluginDescription && /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - dimColor: true, - children: pluginDescription - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedText, { - children: "Would you like to install it?" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime457.jsxDEV(Select, { - options: options2, - onChange: onSelect, - onCancel: () => onResponse("no") - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); -} -var React151, jsx_dev_runtime457, AUTO_DISMISS_MS3 = 30000; -var init_PluginHintMenu = __esm(() => { - init_ink2(); - init_select(); - init_PermissionDialog(); - React151 = __toESM(require_react(), 1); - jsx_dev_runtime457 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/notifs/usePluginInstallationStatus.tsx -function usePluginInstallationStatus() { - const $2 = import_compiler_runtime358.c(20); - const { - addNotification - } = useNotifications(); - const installationStatus = useAppState(_temp254); - let t0; - bb0: { - if (!installationStatus) { - let t13; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t13 = { - totalFailed: 0, - failedMarketplacesCount: 0, - failedPluginsCount: 0 - }; - $2[0] = t13; - } else { - t13 = $2[0]; - } - t0 = t13; - break bb0; - } - let t12; - if ($2[1] !== installationStatus.marketplaces) { - t12 = installationStatus.marketplaces.filter(_temp290); - $2[1] = installationStatus.marketplaces; - $2[2] = t12; - } else { - t12 = $2[2]; - } - const failedMarketplaces = t12; - let t23; - if ($2[3] !== installationStatus.plugins) { - t23 = installationStatus.plugins.filter(_temp356); - $2[3] = installationStatus.plugins; - $2[4] = t23; - } else { - t23 = $2[4]; - } - const failedPlugins = t23; - const t32 = failedMarketplaces.length + failedPlugins.length; - let t4; - if ($2[5] !== failedMarketplaces.length || $2[6] !== failedPlugins.length || $2[7] !== t32) { - t4 = { - totalFailed: t32, - failedMarketplacesCount: failedMarketplaces.length, - failedPluginsCount: failedPlugins.length - }; - $2[5] = failedMarketplaces.length; - $2[6] = failedPlugins.length; - $2[7] = t32; - $2[8] = t4; - } else { - t4 = $2[8]; - } - t0 = t4; - } - const { - totalFailed, - failedMarketplacesCount, - failedPluginsCount - } = t0; - let t1; - if ($2[9] !== addNotification || $2[10] !== failedMarketplacesCount || $2[11] !== failedPluginsCount || $2[12] !== installationStatus || $2[13] !== totalFailed) { - t1 = () => { - if (getIsRemoteMode()) { - return; - } - if (!installationStatus) { - logForDebugging("No installation status to monitor"); - return; - } - if (totalFailed === 0) { - return; - } - logForDebugging(`Plugin installation status: ${failedMarketplacesCount} failed marketplaces, ${failedPluginsCount} failed plugins`); - if (totalFailed === 0) { - return; - } - logForDebugging(`Adding notification for ${totalFailed} failed installations`); - addNotification({ - key: "plugin-install-failed", - jsx: /* @__PURE__ */ jsx_dev_runtime458.jsxDEV(jsx_dev_runtime458.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime458.jsxDEV(ThemedText, { - color: "error", - children: [ - totalFailed, - " ", - plural(totalFailed, "plugin"), - " failed to install" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime458.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /plugin for details" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium" - }); - }; - $2[9] = addNotification; - $2[10] = failedMarketplacesCount; - $2[11] = failedPluginsCount; - $2[12] = installationStatus; - $2[13] = totalFailed; - $2[14] = t1; - } else { - t1 = $2[14]; - } - let t22; - if ($2[15] !== addNotification || $2[16] !== failedMarketplacesCount || $2[17] !== failedPluginsCount || $2[18] !== totalFailed) { - t22 = [addNotification, totalFailed, failedMarketplacesCount, failedPluginsCount]; - $2[15] = addNotification; - $2[16] = failedMarketplacesCount; - $2[17] = failedPluginsCount; - $2[18] = totalFailed; - $2[19] = t22; - } else { - t22 = $2[19]; - } - import_react304.useEffect(t1, t22); -} -function _temp356(p4) { - return p4.status === "failed"; -} -function _temp290(m4) { - return m4.status === "failed"; -} -function _temp254(s4) { - return s4.plugins.installationStatus; -} -var import_compiler_runtime358, import_react304, jsx_dev_runtime458; -var init_usePluginInstallationStatus = __esm(() => { - init_state(); - init_notifications(); - init_ink2(); - init_AppState(); - init_debug(); - init_stringUtils(); - import_compiler_runtime358 = __toESM(require_compiler_runtime(), 1); - import_react304 = __toESM(require_react(), 1); - jsx_dev_runtime458 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/notifs/usePluginAutoupdateNotification.tsx -function usePluginAutoupdateNotification() { - const $2 = import_compiler_runtime359.c(7); - const { - addNotification - } = useNotifications(); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = []; - $2[0] = t0; - } else { - t0 = $2[0]; - } - const [updatedPlugins, setUpdatedPlugins] = import_react305.useState(t0); - let t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - if (getIsRemoteMode()) { - return; - } - const unsubscribe2 = onPluginsAutoUpdated((plugins) => { - logForDebugging(`Plugin autoupdate notification: ${plugins.length} plugin(s) updated`); - setUpdatedPlugins(plugins); - }); - return unsubscribe2; - }; - t22 = []; - $2[1] = t1; - $2[2] = t22; - } else { - t1 = $2[1]; - t22 = $2[2]; - } - import_react305.useEffect(t1, t22); - let t32; - let t4; - if ($2[3] !== addNotification || $2[4] !== updatedPlugins) { - t32 = () => { - if (getIsRemoteMode()) { - return; - } - if (updatedPlugins.length === 0) { - return; - } - const pluginNames = updatedPlugins.map(_temp291); - const displayNames = pluginNames.length <= 2 ? pluginNames.join(" and ") : `${pluginNames.length} plugins`; - addNotification({ - key: "plugin-autoupdate-restart", - jsx: /* @__PURE__ */ jsx_dev_runtime459.jsxDEV(jsx_dev_runtime459.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime459.jsxDEV(ThemedText, { - color: "success", - children: [ - pluginNames.length === 1 ? "Plugin" : "Plugins", - " updated:", - " ", - displayNames - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime459.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 Run /reload-plugins to apply" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "low", - timeoutMs: 1e4 - }); - logForDebugging(`Showing plugin autoupdate notification for: ${pluginNames.join(", ")}`); - }; - t4 = [updatedPlugins, addNotification]; - $2[3] = addNotification; - $2[4] = updatedPlugins; - $2[5] = t32; - $2[6] = t4; - } else { - t32 = $2[5]; - t4 = $2[6]; - } - import_react305.useEffect(t32, t4); -} -function _temp291(id) { - const atIndex = id.indexOf("@"); - return atIndex > 0 ? id.substring(0, atIndex) : id; -} -var import_compiler_runtime359, import_react305, jsx_dev_runtime459; -var init_usePluginAutoupdateNotification = __esm(() => { - init_state(); - init_notifications(); - init_ink2(); - init_debug(); - init_pluginAutoupdate(); - import_compiler_runtime359 = __toESM(require_compiler_runtime(), 1); - import_react305 = __toESM(require_react(), 1); - jsx_dev_runtime459 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/plugins/reconciler.ts -import { isAbsolute as isAbsolute26, resolve as resolve43 } from "path"; -function diffMarketplaces(declared, materialized, opts) { - const missing = []; - const sourceChanged = []; - const upToDate = []; - for (const [name3, intent] of Object.entries(declared)) { - const state4 = materialized[name3]; - const normalizedIntent = normalizeSource(intent.source, opts?.projectRoot); - if (!state4) { - missing.push(name3); - } else if (intent.sourceIsFallback) { - upToDate.push(name3); - } else if (!isEqual_default(normalizedIntent, state4.source)) { - sourceChanged.push({ - name: name3, - declaredSource: normalizedIntent, - materializedSource: state4.source - }); - } else { - upToDate.push(name3); - } - } - return { missing, sourceChanged, upToDate }; -} -async function reconcileMarketplaces(opts) { - const declared = getDeclaredMarketplaces(); - if (Object.keys(declared).length === 0) { - return { installed: [], updated: [], failed: [], upToDate: [], skipped: [] }; - } - let materialized; - try { - materialized = await loadKnownMarketplacesConfig(); - } catch (e4) { - logError2(e4); - materialized = {}; - } - const diff3 = diffMarketplaces(declared, materialized, { - projectRoot: getOriginalCwd() - }); - const work = [ - ...diff3.missing.map((name3) => ({ - name: name3, - source: normalizeSource(declared[name3].source), - action: "install" - })), - ...diff3.sourceChanged.map(({ name: name3, declaredSource }) => ({ - name: name3, - source: declaredSource, - action: "update" - })) - ]; - const skipped = []; - const toProcess = []; - for (const item of work) { - if (opts?.skip?.(item.name, item.source)) { - skipped.push(item.name); - continue; - } - if (item.action === "update" && isLocalMarketplaceSource(item.source) && !await pathExists(item.source.path)) { - logForDebugging(`[reconcile] '${item.name}' declared path does not exist; keeping materialized entry`); - skipped.push(item.name); - continue; - } - toProcess.push(item); - } - if (toProcess.length === 0) { - return { - installed: [], - updated: [], - failed: [], - upToDate: diff3.upToDate, - skipped - }; - } - logForDebugging(`[reconcile] ${toProcess.length} marketplace(s): ${toProcess.map((w2) => `${w2.name}(${w2.action})`).join(", ")}`); - const installed = []; - const updated = []; - const failed = []; - for (let i6 = 0;i6 < toProcess.length; i6++) { - const { name: name3, source, action: action2 } = toProcess[i6]; - opts?.onProgress?.({ - type: "installing", - name: name3, - action: action2, - index: i6 + 1, - total: toProcess.length - }); - try { - const result = await addMarketplaceSource(source); - if (action2 === "install") - installed.push(name3); - else - updated.push(name3); - opts?.onProgress?.({ - type: "installed", - name: name3, - alreadyMaterialized: result.alreadyMaterialized - }); - } catch (e4) { - const error46 = errorMessage(e4); - failed.push({ name: name3, error: error46 }); - opts?.onProgress?.({ type: "failed", name: name3, error: error46 }); - logError2(e4); - } - } - return { installed, updated, failed, upToDate: diff3.upToDate, skipped }; -} -function normalizeSource(source, projectRoot) { - if ((source.source === "directory" || source.source === "file") && !isAbsolute26(source.path)) { - const base2 = projectRoot ?? getOriginalCwd(); - const canonicalRoot = findCanonicalGitRoot(base2); - return { - ...source, - path: resolve43(canonicalRoot ?? base2, source.path) - }; - } - return source; -} -var init_reconciler2 = __esm(() => { - init_isEqual(); - init_state(); - init_debug(); - init_errors(); - init_file(); - init_git(); - init_log2(); - init_marketplaceManager(); - init_schemas3(); -}); - -// src/services/plugins/PluginInstallationManager.ts -function updateMarketplaceStatus(setAppState, name3, status2, error46) { - setAppState((prevState) => ({ - ...prevState, - plugins: { - ...prevState.plugins, - installationStatus: { - ...prevState.plugins.installationStatus, - marketplaces: prevState.plugins.installationStatus.marketplaces.map((m4) => m4.name === name3 ? { ...m4, status: status2, error: error46 } : m4) - } - } - })); -} -async function performBackgroundPluginInstallations(setAppState) { - logForDebugging("performBackgroundPluginInstallations called"); - try { - const declared = getDeclaredMarketplaces(); - const materialized = await loadKnownMarketplacesConfig().catch(() => ({})); - const diff3 = diffMarketplaces(declared, materialized); - const pendingNames = [ - ...diff3.missing, - ...diff3.sourceChanged.map((c9) => c9.name) - ]; - setAppState((prev) => ({ - ...prev, - plugins: { - ...prev.plugins, - installationStatus: { - marketplaces: pendingNames.map((name3) => ({ - name: name3, - status: "pending" - })), - plugins: [] - } - } - })); - if (pendingNames.length === 0) { - return; - } - logForDebugging(`Installing ${pendingNames.length} marketplace(s) in background`); - const result = await reconcileMarketplaces({ - onProgress: (event) => { - switch (event.type) { - case "installing": - updateMarketplaceStatus(setAppState, event.name, "installing"); - break; - case "installed": - updateMarketplaceStatus(setAppState, event.name, "installed"); - break; - case "failed": - updateMarketplaceStatus(setAppState, event.name, "failed", event.error); - break; - } - } - }); - const metrics = { - installed_count: result.installed.length, - updated_count: result.updated.length, - failed_count: result.failed.length, - up_to_date_count: result.upToDate.length - }; - logEvent("tengu_marketplace_background_install", metrics); - logForDiagnosticsNoPII("info", "tengu_marketplace_background_install", metrics); - if (result.installed.length > 0) { - clearMarketplacesCache(); - logForDebugging(`Auto-refreshing plugins after ${result.installed.length} new marketplace(s) installed`); - try { - await refreshActivePlugins(setAppState); - } catch (refreshError) { - logError2(refreshError); - logForDebugging(`Auto-refresh failed, falling back to needsRefresh: ${refreshError}`, { level: "warn" }); - clearPluginCache("performBackgroundPluginInstallations: auto-refresh failed"); - setAppState((prev) => { - if (prev.plugins.needsRefresh) - return prev; - return { - ...prev, - plugins: { ...prev.plugins, needsRefresh: true } - }; - }); - } - } else if (result.updated.length > 0) { - clearMarketplacesCache(); - clearPluginCache("performBackgroundPluginInstallations: marketplaces reconciled"); - setAppState((prev) => { - if (prev.plugins.needsRefresh) - return prev; - return { - ...prev, - plugins: { ...prev.plugins, needsRefresh: true } - }; - }); - } - } catch (error46) { - logError2(error46); - } -} -var init_PluginInstallationManager = __esm(() => { - init_debug(); - init_diagLogs(); - init_log2(); - init_marketplaceManager(); - init_pluginLoader(); - init_reconciler2(); - init_refresh(); - init_analytics(); -}); - -// src/utils/plugins/performStartupChecks.tsx -async function performStartupChecks(setAppState) { - logForDebugging("performStartupChecks called"); - if (!checkHasTrustDialogAccepted()) { - logForDebugging("Trust not accepted for current directory - skipping plugin installations"); - return; - } - try { - logForDebugging("Starting background plugin installations"); - const seedChanged = await registerSeedMarketplaces(); - if (seedChanged) { - clearMarketplacesCache(); - clearPluginCache("performStartupChecks: seed marketplaces changed"); - setAppState((prev) => { - if (prev.plugins.needsRefresh) - return prev; - return { - ...prev, - plugins: { - ...prev.plugins, - needsRefresh: true - } - }; - }); - } - await performBackgroundPluginInstallations(setAppState); - } catch (error46) { - logForDebugging(`Error initiating background plugin installations: ${error46}`); - } -} -var init_performStartupChecks = __esm(() => { - init_PluginInstallationManager(); - init_config(); - init_debug(); - init_marketplaceManager(); - init_pluginLoader(); -}); - -// src/components/AwsAuthStatusBox.tsx -function AwsAuthStatusBox() { - const $2 = import_compiler_runtime360.c(11); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = AwsAuthStatusManager.getInstance().getStatus(); - $2[0] = t0; - } else { - t0 = $2[0]; - } - const [status2, setStatus] = import_react306.useState(t0); - let t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - const unsubscribe2 = AwsAuthStatusManager.getInstance().subscribe(setStatus); - return unsubscribe2; - }; - t22 = []; - $2[1] = t1; - $2[2] = t22; - } else { - t1 = $2[1]; - t22 = $2[2]; - } - import_react306.useEffect(t1, t22); - if (!status2.isAuthenticating && !status2.error && status2.output.length === 0) { - return null; - } - if (!status2.isAuthenticating && !status2.error) { - return null; - } - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedText, { - bold: true, - color: "permission", - children: "Cloud Authentication" - }, undefined, false, undefined, this); - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] !== status2.output) { - t4 = status2.output.length > 0 && /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: status2.output.slice(-5).map(_temp293) - }, undefined, false, undefined, this); - $2[4] = status2.output; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== status2.error) { - t5 = status2.error && /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedText, { - color: "error", - children: status2.error - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[6] = status2.error; - $2[7] = t5; - } else { - t5 = $2[7]; - } - let t6; - if ($2[8] !== t4 || $2[9] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedBox_default, { - flexDirection: "column", - borderStyle: "round", - borderColor: "permission", - paddingX: 1, - marginY: 1, - children: [ - t32, - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[8] = t4; - $2[9] = t5; - $2[10] = t6; - } else { - t6 = $2[10]; - } - return t6; -} -function _temp293(line, index2) { - const m4 = line.match(URL_RE); - if (!m4) { - return /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedText, { - dimColor: true, - children: line - }, index2, false, undefined, this); - } - const url3 = m4[0]; - const start = m4.index ?? 0; - const before = line.slice(0, start); - const after = line.slice(start + url3.length); - return /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(ThemedText, { - dimColor: true, - children: [ - before, - /* @__PURE__ */ jsx_dev_runtime460.jsxDEV(Link, { - url: url3, - children: url3 - }, undefined, false, undefined, this), - after - ] - }, index2, true, undefined, this); -} -var import_compiler_runtime360, import_react306, jsx_dev_runtime460, URL_RE; -var init_AwsAuthStatusBox = __esm(() => { - init_ink2(); - init_awsAuthStatusManager(); - import_compiler_runtime360 = __toESM(require_compiler_runtime(), 1); - import_react306 = __toESM(require_react(), 1); - jsx_dev_runtime460 = __toESM(require_jsx_dev_runtime(), 1); - URL_RE = /https?:\/\/\S+/; -}); - -// src/hooks/notifs/useRateLimitWarningNotification.tsx -function useRateLimitWarningNotification(model) { - const $2 = import_compiler_runtime361.c(17); - const { - addNotification - } = useNotifications(); - const claudeAiLimits = useClaudeAiLimits(); - let t0; - if ($2[0] !== claudeAiLimits || $2[1] !== model) { - t0 = getRateLimitWarning(claudeAiLimits, model); - $2[0] = claudeAiLimits; - $2[1] = model; - $2[2] = t0; - } else { - t0 = $2[2]; - } - const rateLimitWarning = t0; - let t1; - if ($2[3] !== claudeAiLimits) { - t1 = getUsingOverageText(claudeAiLimits); - $2[3] = claudeAiLimits; - $2[4] = t1; - } else { - t1 = $2[4]; - } - const usingOverageText = t1; - const shownWarningRef = import_react307.useRef(null); - let t22; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t22 = getSubscriptionType(); - $2[5] = t22; - } else { - t22 = $2[5]; - } - const subscriptionType = t22; - let t32; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t32 = hasClaudeAiBillingAccess(); - $2[6] = t32; - } else { - t32 = $2[6]; - } - const hasBillingAccess = t32; - const isTeamOrEnterprise = subscriptionType === "team" || subscriptionType === "enterprise"; - const [hasShownOverageNotification, setHasShownOverageNotification] = import_react307.useState(false); - let t4; - let t5; - if ($2[7] !== addNotification || $2[8] !== claudeAiLimits.isUsingOverage || $2[9] !== hasShownOverageNotification || $2[10] !== usingOverageText) { - t4 = () => { - if (getIsRemoteMode()) { - return; - } - if (claudeAiLimits.isUsingOverage && !hasShownOverageNotification && (!isTeamOrEnterprise || hasBillingAccess)) { - addNotification({ - key: "limit-reached", - text: usingOverageText, - priority: "immediate" - }); - setHasShownOverageNotification(true); - } else { - if (!claudeAiLimits.isUsingOverage && hasShownOverageNotification) { - setHasShownOverageNotification(false); - } - } - }; - t5 = [claudeAiLimits.isUsingOverage, usingOverageText, hasShownOverageNotification, addNotification, hasBillingAccess, isTeamOrEnterprise]; - $2[7] = addNotification; - $2[8] = claudeAiLimits.isUsingOverage; - $2[9] = hasShownOverageNotification; - $2[10] = usingOverageText; - $2[11] = t4; - $2[12] = t5; - } else { - t4 = $2[11]; - t5 = $2[12]; - } - import_react307.useEffect(t4, t5); - let t6; - let t7; - if ($2[13] !== addNotification || $2[14] !== rateLimitWarning) { - t6 = () => { - if (getIsRemoteMode()) { - return; - } - if (rateLimitWarning && rateLimitWarning !== shownWarningRef.current) { - shownWarningRef.current = rateLimitWarning; - addNotification({ - key: "rate-limit-warning", - jsx: /* @__PURE__ */ jsx_dev_runtime461.jsxDEV(ThemedText, { - children: /* @__PURE__ */ jsx_dev_runtime461.jsxDEV(ThemedText, { - color: "warning", - children: rateLimitWarning - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - priority: "high" - }); - } - }; - t7 = [rateLimitWarning, addNotification]; - $2[13] = addNotification; - $2[14] = rateLimitWarning; - $2[15] = t6; - $2[16] = t7; - } else { - t6 = $2[15]; - t7 = $2[16]; - } - import_react307.useEffect(t6, t7); -} -var import_compiler_runtime361, import_react307, jsx_dev_runtime461; -var init_useRateLimitWarningNotification = __esm(() => { - init_notifications(); - init_ink2(); - init_claudeAiLimits(); - init_claudeAiLimitsHook(); - init_auth14(); - init_billing(); - init_state(); - import_compiler_runtime361 = __toESM(require_compiler_runtime(), 1); - import_react307 = __toESM(require_react(), 1); - jsx_dev_runtime461 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/utils/model/deprecation.ts -function getDeprecatedModelInfo(modelId) { - const lowercaseModelId = modelId.toLowerCase(); - const provider5 = getAPIProvider(); - for (const [key2, value] of Object.entries(DEPRECATED_MODELS9)) { - const retirementDate = value.retirementDates[provider5]; - if (!lowercaseModelId.includes(key2) || !retirementDate) { - continue; - } - return { - isDeprecated: true, - modelName: value.modelName, - retirementDate - }; - } - return { isDeprecated: false }; -} -function getModelDeprecationWarning(modelId) { - if (!modelId) { - return null; - } - const info = getDeprecatedModelInfo(modelId); - if (!info.isDeprecated) { - return null; - } - return `\u26A0 ${info.modelName} will be retired on ${info.retirementDate}. Consider switching to a newer model.`; -} -var DEPRECATED_MODELS9; -var init_deprecation = __esm(() => { - init_providers(); - DEPRECATED_MODELS9 = { - "claude-3-opus": { - modelName: "Claude 3 Opus", - retirementDates: { - firstParty: "January 5, 2026", - bedrock: "January 15, 2026", - vertex: "January 5, 2026", - foundry: "January 5, 2026" - } - }, - "claude-3-7-sonnet": { - modelName: "Claude 3.7 Sonnet", - retirementDates: { - firstParty: "February 19, 2026", - bedrock: "April 28, 2026", - vertex: "May 11, 2026", - foundry: "February 19, 2026" - } - }, - "claude-3-5-haiku": { - modelName: "Claude 3.5 Haiku", - retirementDates: { - firstParty: "February 19, 2026", - bedrock: null, - vertex: null, - foundry: null - } - } - }; -}); - -// src/hooks/notifs/useDeprecationWarningNotification.tsx -function useDeprecationWarningNotification(model) { - const $2 = import_compiler_runtime362.c(4); - const { - addNotification - } = useNotifications(); - const lastWarningRef = import_react308.useRef(null); - let t0; - let t1; - if ($2[0] !== addNotification || $2[1] !== model) { - t0 = () => { - if (getIsRemoteMode()) { - return; - } - const deprecationWarning = getModelDeprecationWarning(model); - if (deprecationWarning && deprecationWarning !== lastWarningRef.current) { - lastWarningRef.current = deprecationWarning; - addNotification({ - key: "model-deprecation-warning", - text: deprecationWarning, - color: "warning", - priority: "high" - }); - } - if (!deprecationWarning) { - lastWarningRef.current = null; - } - }; - t1 = [model, addNotification]; - $2[0] = addNotification; - $2[1] = model; - $2[2] = t0; - $2[3] = t1; - } else { - t0 = $2[2]; - t1 = $2[3]; - } - import_react308.useEffect(t0, t1); -} -var import_compiler_runtime362, import_react308; -var init_useDeprecationWarningNotification = __esm(() => { - init_notifications(); - init_deprecation(); - init_state(); - import_compiler_runtime362 = __toESM(require_compiler_runtime(), 1); - import_react308 = __toESM(require_react(), 1); -}); - -// src/hooks/notifs/useNpmDeprecationNotification.tsx -function useNpmDeprecationNotification() { - useStartupNotification(_temp294); -} -async function _temp294() { - if (isInBundledMode() || isEnvTruthy(process.env.DISABLE_INSTALLATION_CHECKS)) { - return null; - } - const installationType = await getCurrentInstallationType(); - if (installationType === "development") { - return null; - } - return { - timeoutMs: 15000, - key: "npm-deprecation-warning", - text: NPM_DEPRECATION_MESSAGE, - color: "warning", - priority: "high" - }; -} -var NPM_DEPRECATION_MESSAGE = "Claude Code has switched from npm to native installer. Run `claude install` or see https://docs.anthropic.com/en/docs/claude-code/getting-started for more options."; -var init_useNpmDeprecationNotification = __esm(() => { - init_doctorDiagnostic(); - init_envUtils(); - init_useStartupNotification(); -}); - -// src/hooks/notifs/useIDEStatusIndicator.tsx -function useIDEStatusIndicator(t0) { - const $2 = import_compiler_runtime363.c(26); - const { - ideSelection, - mcpClients, - ideInstallationStatus - } = t0; - const { - addNotification, - removeNotification - } = useNotifications(); - const { - status: ideStatus, - ideName - } = useIdeConnectionStatus(mcpClients); - const hasShownHintRef = import_react309.useRef(false); - let t1; - if ($2[0] !== ideInstallationStatus) { - t1 = ideInstallationStatus ? isJetBrainsIde(ideInstallationStatus?.ideType) : false; - $2[0] = ideInstallationStatus; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const isJetBrains = t1; - const showIDEInstallErrorOrJetBrainsInfo = ideInstallationStatus?.error || isJetBrains; - const shouldShowIdeSelection = ideStatus === "connected" && (ideSelection?.filePath || ideSelection?.text && ideSelection.lineCount > 0); - const shouldShowConnected = ideStatus === "connected" && !shouldShowIdeSelection; - const showIDEInstallError = showIDEInstallErrorOrJetBrainsInfo && !isJetBrains && !shouldShowConnected && !shouldShowIdeSelection; - const showJetBrainsInfo = showIDEInstallErrorOrJetBrainsInfo && isJetBrains && !shouldShowConnected && !shouldShowIdeSelection; - let t22; - let t32; - if ($2[2] !== addNotification || $2[3] !== ideStatus || $2[4] !== removeNotification || $2[5] !== showJetBrainsInfo) { - t22 = () => { - if (getIsRemoteMode()) { - return; - } - if (isSupportedTerminal() || ideStatus !== null || showJetBrainsInfo) { - removeNotification("ide-status-hint"); - return; - } - if (hasShownHintRef.current || (getGlobalConfig().ideHintShownCount ?? 0) >= MAX_IDE_HINT_SHOW_COUNT) { - return; - } - const timeoutId = setTimeout(_temp292, 3000, hasShownHintRef, addNotification); - return () => clearTimeout(timeoutId); - }; - t32 = [addNotification, removeNotification, ideStatus, showJetBrainsInfo]; - $2[2] = addNotification; - $2[3] = ideStatus; - $2[4] = removeNotification; - $2[5] = showJetBrainsInfo; - $2[6] = t22; - $2[7] = t32; - } else { - t22 = $2[6]; - t32 = $2[7]; - } - import_react309.useEffect(t22, t32); - let t4; - let t5; - if ($2[8] !== addNotification || $2[9] !== ideName || $2[10] !== ideStatus || $2[11] !== removeNotification || $2[12] !== showIDEInstallError || $2[13] !== showJetBrainsInfo) { - t4 = () => { - if (getIsRemoteMode()) { - return; - } - if (showIDEInstallError || showJetBrainsInfo || ideStatus !== "disconnected" || !ideName) { - removeNotification("ide-status-disconnected"); - return; - } - addNotification({ - key: "ide-status-disconnected", - text: `${ideName} disconnected`, - color: "error", - priority: "medium" - }); - }; - t5 = [addNotification, removeNotification, ideStatus, ideName, showIDEInstallError, showJetBrainsInfo]; - $2[8] = addNotification; - $2[9] = ideName; - $2[10] = ideStatus; - $2[11] = removeNotification; - $2[12] = showIDEInstallError; - $2[13] = showJetBrainsInfo; - $2[14] = t4; - $2[15] = t5; - } else { - t4 = $2[14]; - t5 = $2[15]; - } - import_react309.useEffect(t4, t5); - let t6; - let t7; - if ($2[16] !== addNotification || $2[17] !== removeNotification || $2[18] !== showJetBrainsInfo) { - t6 = () => { - if (getIsRemoteMode()) { - return; - } - if (!showJetBrainsInfo) { - removeNotification("ide-status-jetbrains-disconnected"); - return; - } - addNotification({ - key: "ide-status-jetbrains-disconnected", - text: "IDE plugin not connected \xB7 /status for info", - priority: "medium" - }); - }; - t7 = [addNotification, removeNotification, showJetBrainsInfo]; - $2[16] = addNotification; - $2[17] = removeNotification; - $2[18] = showJetBrainsInfo; - $2[19] = t6; - $2[20] = t7; - } else { - t6 = $2[19]; - t7 = $2[20]; - } - import_react309.useEffect(t6, t7); - let t8; - let t9; - if ($2[21] !== addNotification || $2[22] !== removeNotification || $2[23] !== showIDEInstallError) { - t8 = () => { - if (getIsRemoteMode()) { - return; - } - if (!showIDEInstallError) { - removeNotification("ide-status-install-error"); - return; - } - addNotification({ - key: "ide-status-install-error", - text: "IDE extension install failed (see /status for info)", - color: "error", - priority: "medium" - }); - }; - t9 = [addNotification, removeNotification, showIDEInstallError]; - $2[21] = addNotification; - $2[22] = removeNotification; - $2[23] = showIDEInstallError; - $2[24] = t8; - $2[25] = t9; - } else { - t8 = $2[24]; - t9 = $2[25]; - } - import_react309.useEffect(t8, t9); -} -function _temp292(hasShownHintRef_0, addNotification_0) { - detectIDEs(true).then((infos) => { - const ideName_0 = infos[0]?.name; - if (ideName_0 && !hasShownHintRef_0.current) { - hasShownHintRef_0.current = true; - saveGlobalConfig(_temp295); - addNotification_0({ - key: "ide-status-hint", - jsx: /* @__PURE__ */ jsx_dev_runtime462.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "/ide for ", - /* @__PURE__ */ jsx_dev_runtime462.jsxDEV(ThemedText, { - color: "ide", - children: ideName_0 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "low" - }); - } - }); -} -function _temp295(current) { - return { - ...current, - ideHintShownCount: (current.ideHintShownCount ?? 0) + 1 - }; -} -var import_compiler_runtime363, import_react309, jsx_dev_runtime462, MAX_IDE_HINT_SHOW_COUNT = 5; -var init_useIDEStatusIndicator = __esm(() => { - init_notifications(); - init_ink2(); - init_config(); - init_ide(); - init_state(); - init_useIdeConnectionStatus(); - import_compiler_runtime363 = __toESM(require_compiler_runtime(), 1); - import_react309 = __toESM(require_react(), 1); - jsx_dev_runtime462 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/notifs/useModelMigrationNotifications.tsx -function useModelMigrationNotifications() { - useStartupNotification(_temp296); -} -function _temp296() { - const config10 = getGlobalConfig(); - const notifs = []; - for (const migration of MIGRATIONS) { - const notif = migration(config10); - if (notif) { - notifs.push(notif); - } - } - return notifs.length > 0 ? notifs : null; -} -function recent(ts) { - return ts !== undefined && Date.now() - ts < 3000; -} -var MIGRATIONS; -var init_useModelMigrationNotifications = __esm(() => { - init_config(); - init_useStartupNotification(); - MIGRATIONS = [ - (c9) => { - if (!recent(c9.sonnet45To46MigrationTimestamp)) - return; - return { - key: "sonnet-46-update", - text: "Model updated to Sonnet 4.6", - color: "suggestion", - priority: "high", - timeoutMs: 3000 - }; - }, - (c9) => { - const isLegacyRemap = Boolean(c9.legacyOpusMigrationTimestamp); - const ts = c9.legacyOpusMigrationTimestamp ?? c9.opusProMigrationTimestamp; - if (!recent(ts)) - return; - return { - key: "opus-pro-update", - text: isLegacyRemap ? "Model updated to Opus 4.6 \xB7 Set CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP=1 to opt out" : "Model updated to Opus 4.6", - color: "suggestion", - priority: "high", - timeoutMs: isLegacyRemap ? 8000 : 3000 - }; - } - ]; -}); - -// src/hooks/notifs/useCanSwitchToExistingSubscription.tsx -function useCanSwitchToExistingSubscription() { - useStartupNotification(_temp297); -} -async function _temp297() { - if ((getGlobalConfig().subscriptionNoticeCount ?? 0) >= MAX_SHOW_COUNT2) { - return null; - } - const subscriptionType = await getExistingClaudeSubscription(); - if (subscriptionType === null) { - return null; - } - saveGlobalConfig(_temp298); - logEvent("tengu_switch_to_subscription_notice_shown", {}); - return { - key: "switch-to-subscription", - jsx: /* @__PURE__ */ jsx_dev_runtime463.jsxDEV(ThemedText, { - color: "suggestion", - children: [ - "Use your existing Claude ", - subscriptionType, - " plan with Claude Code", - /* @__PURE__ */ jsx_dev_runtime463.jsxDEV(ThemedText, { - color: "text", - dimColor: true, - children: [ - " ", - "\xB7 /login to activate" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "low" - }; -} -function _temp298(current) { - return { - ...current, - subscriptionNoticeCount: (current.subscriptionNoticeCount ?? 0) + 1 - }; -} -async function getExistingClaudeSubscription() { - if (isClaudeAISubscriber()) { - return null; - } - const profile7 = await getOauthProfileFromApiKey(); - if (!profile7) { - return null; - } - if (profile7.account.has_claude_max) { - return "Max"; - } - if (profile7.account.has_claude_pro) { - return "Pro"; - } - return null; -} -var jsx_dev_runtime463, MAX_SHOW_COUNT2 = 3; -var init_useCanSwitchToExistingSubscription = __esm(() => { - init_getOauthProfile(); - init_auth14(); - init_ink2(); - init_analytics(); - init_config(); - init_useStartupNotification(); - jsx_dev_runtime463 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/notifs/useTeammateShutdownNotification.ts -function parseCount(notif) { - if (!("text" in notif)) { - return 1; - } - const match = notif.text.match(/^(\d+)/); - return match?.[1] ? parseInt(match[1], 10) : 1; -} -function foldSpawn(acc, _incoming) { - return makeSpawnNotif(parseCount(acc) + 1); -} -function makeSpawnNotif(count4) { - return { - key: "teammate-spawn", - text: count4 === 1 ? "1 agent spawned" : `${count4} agents spawned`, - priority: "low", - timeoutMs: 5000, - fold: foldSpawn - }; -} -function foldShutdown(acc, _incoming) { - return makeShutdownNotif(parseCount(acc) + 1); -} -function makeShutdownNotif(count4) { - return { - key: "teammate-shutdown", - text: count4 === 1 ? "1 agent shut down" : `${count4} agents shut down`, - priority: "low", - timeoutMs: 5000, - fold: foldShutdown - }; -} -function useTeammateLifecycleNotification() { - const tasks2 = useAppState((s4) => s4.tasks); - const { addNotification } = useNotifications(); - const seenRunningRef = import_react310.useRef(new Set); - const seenCompletedRef = import_react310.useRef(new Set); - import_react310.useEffect(() => { - if (getIsRemoteMode()) - return; - for (const [id, task] of Object.entries(tasks2)) { - if (!isInProcessTeammateTask(task)) { - continue; - } - if (task.status === "running" && !seenRunningRef.current.has(id)) { - seenRunningRef.current.add(id); - addNotification(makeSpawnNotif(1)); - } - if (task.status === "completed" && !seenCompletedRef.current.has(id)) { - seenCompletedRef.current.add(id); - addNotification(makeShutdownNotif(1)); - } - } - }, [tasks2, addNotification]); -} -var import_react310; -var init_useTeammateShutdownNotification = __esm(() => { - init_state(); - init_notifications(); - init_AppState(); - import_react310 = __toESM(require_react(), 1); -}); - -// src/hooks/notifs/useFastModeNotification.tsx -function useFastModeNotification() { - const $2 = import_compiler_runtime364.c(13); - const { - addNotification - } = useNotifications(); - const isFastMode = useAppState(_temp300); - const setAppState = useSetAppState(); - let t0; - let t1; - if ($2[0] !== addNotification || $2[1] !== isFastMode || $2[2] !== setAppState) { - t0 = () => { - if (getIsRemoteMode()) { - return; - } - if (!isFastModeEnabled()) { - return; - } - return onOrgFastModeChanged((orgEnabled) => { - if (orgEnabled) { - addNotification({ - key: ORG_CHANGED_KEY, - color: "fastMode", - priority: "immediate", - text: "Fast mode is now available \xB7 /fast to turn on" - }); - } else { - if (isFastMode) { - setAppState(_temp299); - addNotification({ - key: ORG_CHANGED_KEY, - color: "warning", - priority: "immediate", - text: "Fast mode has been disabled by your organization" - }); - } - } - }); - }; - t1 = [addNotification, isFastMode, setAppState]; - $2[0] = addNotification; - $2[1] = isFastMode; - $2[2] = setAppState; - $2[3] = t0; - $2[4] = t1; - } else { - t0 = $2[3]; - t1 = $2[4]; - } - import_react311.useEffect(t0, t1); - let t22; - let t32; - if ($2[5] !== addNotification || $2[6] !== setAppState) { - t22 = () => { - if (getIsRemoteMode()) { - return; - } - if (!isFastModeEnabled()) { - return; - } - return onFastModeOverageRejection((message) => { - setAppState(_temp357); - addNotification({ - key: OVERAGE_REJECTED_KEY, - color: "warning", - priority: "immediate", - text: message - }); - }); - }; - t32 = [addNotification, setAppState]; - $2[5] = addNotification; - $2[6] = setAppState; - $2[7] = t22; - $2[8] = t32; - } else { - t22 = $2[7]; - t32 = $2[8]; - } - import_react311.useEffect(t22, t32); - let t4; - let t5; - if ($2[9] !== addNotification || $2[10] !== isFastMode) { - t4 = () => { - if (getIsRemoteMode()) { - return; - } - if (!isFastMode) { - return; - } - const unsubTriggered = onCooldownTriggered((resetAt, reason) => { - const resetIn = formatDuration(resetAt - Date.now(), { - hideTrailingZeros: true - }); - const message_0 = getCooldownMessage(reason, resetIn); - addNotification({ - key: COOLDOWN_STARTED_KEY, - invalidates: [COOLDOWN_EXPIRED_KEY], - text: message_0, - color: "warning", - priority: "immediate" - }); - }); - const unsubExpired = onCooldownExpired(() => { - addNotification({ - key: COOLDOWN_EXPIRED_KEY, - invalidates: [COOLDOWN_STARTED_KEY], - color: "fastMode", - text: "Fast limit reset \xB7 now using fast mode", - priority: "immediate" - }); - }); - return () => { - unsubTriggered(); - unsubExpired(); - }; - }; - t5 = [addNotification, isFastMode]; - $2[9] = addNotification; - $2[10] = isFastMode; - $2[11] = t4; - $2[12] = t5; - } else { - t4 = $2[11]; - t5 = $2[12]; - } - import_react311.useEffect(t4, t5); -} -function _temp357(prev_0) { - return { - ...prev_0, - fastMode: false - }; -} -function _temp299(prev) { - return { - ...prev, - fastMode: false - }; -} -function _temp300(s4) { - return s4.fastMode; -} -function getCooldownMessage(reason, resetIn) { - switch (reason) { - case "overloaded": - return `Fast mode overloaded and is temporarily unavailable \xB7 resets in ${resetIn}`; - case "rate_limit": - return `Fast limit reached and temporarily disabled \xB7 resets in ${resetIn}`; - } -} -var import_compiler_runtime364, import_react311, COOLDOWN_STARTED_KEY = "fast-mode-cooldown-started", COOLDOWN_EXPIRED_KEY = "fast-mode-cooldown-expired", ORG_CHANGED_KEY = "fast-mode-org-changed", OVERAGE_REJECTED_KEY = "fast-mode-overage-rejected"; -var init_useFastModeNotification = __esm(() => { - init_notifications(); - init_AppState(); - init_fastMode(); - init_format(); - init_state(); - import_compiler_runtime364 = __toESM(require_compiler_runtime(), 1); - import_react311 = __toESM(require_react(), 1); -}); - -// src/utils/autoRunIssue.tsx -function AutoRunIssueNotification(t0) { - const $2 = import_compiler_runtime365.c(8); - const { - onRun, - onCancel, - reason - } = t0; - const hasRunRef = import_react312.useRef(false); - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = { - context: "Confirmation" - }; - $2[0] = t1; - } else { - t1 = $2[0]; - } - useKeybinding("confirm:no", onCancel, t1); - let t22; - let t32; - if ($2[1] !== onRun) { - t22 = () => { - if (!hasRunRef.current) { - hasRunRef.current = true; - onRun(); - } - }; - t32 = [onRun]; - $2[1] = onRun; - $2[2] = t22; - $2[3] = t32; - } else { - t22 = $2[2]; - t32 = $2[3]; - } - import_react312.useEffect(t22, t32); - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedText, { - bold: true, - children: "Running feedback capture..." - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(KeyboardShortcutHint, { - shortcut: "Esc", - action: "cancel" - }, undefined, false, undefined, this), - " anytime" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[5] = t5; - } else { - t5 = $2[5]; - } - let t6; - if ($2[6] !== reason) { - t6 = /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - t4, - t5, - /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime464.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Reason: ", - reason - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = reason; - $2[7] = t6; - } else { - t6 = $2[7]; - } - return t6; -} -function shouldAutoRunIssue(reason) { - if (true) { - return false; - } - switch (reason) { - case "feedback_survey_bad": - return false; - case "feedback_survey_good": - return false; - default: - return false; - } -} -function getAutoRunCommand(reason) { - if (false) {} - return "/issue"; -} -function getAutoRunIssueReasonText(reason) { - switch (reason) { - case "feedback_survey_bad": - return 'You responded "Bad" to the feedback survey'; - case "feedback_survey_good": - return 'You responded "Good" to the feedback survey'; - default: - return "Unknown reason"; - } -} -var import_compiler_runtime365, import_react312, jsx_dev_runtime464; -var init_autoRunIssue = __esm(() => { - init_KeyboardShortcutHint(); - init_ink2(); - init_useKeybinding(); - import_compiler_runtime365 = __toESM(require_compiler_runtime(), 1); - import_react312 = __toESM(require_react(), 1); - jsx_dev_runtime464 = __toESM(require_jsx_dev_runtime(), 1); -}); -// src/components/PromptInput/IssueFlagBanner.tsx -function IssueFlagBanner() { - return null; -} - -// src/hooks/useIssueFlagBanner.ts -function isSessionContainerCompatible(messages) { - for (const msg of messages) { - if (msg.type !== "assistant") { - continue; - } - const content = msg.message.content; - if (!Array.isArray(content)) { - continue; - } - for (const block2 of content) { - if (block2.type !== "tool_use" || !("name" in block2)) { - continue; - } - const toolName = block2.name; - if (toolName.startsWith("mcp__")) { - return false; - } - if (toolName === BASH_TOOL_NAME) { - const input = block2.input; - const command19 = input?.command || ""; - if (EXTERNAL_COMMAND_PATTERNS.some((p4) => p4.test(command19))) { - return false; - } - } - } - } - return true; -} -function hasFrictionSignal(messages) { - for (let i6 = messages.length - 1;i6 >= 0; i6--) { - const msg = messages[i6]; - if (msg.type !== "user") { - continue; - } - const text = getUserMessageText(msg); - if (!text) { - continue; - } - return FRICTION_PATTERNS.some((p4) => p4.test(text)); - } - return false; -} -function useIssueFlagBanner(messages, submitCount) { - if (process.env.USER_TYPE !== "ant") { - return false; - } - const lastTriggeredAtRef = import_react313.useRef(0); - const activeForSubmitRef = import_react313.useRef(-1); - const shouldTrigger = import_react313.useMemo(() => isSessionContainerCompatible(messages) && hasFrictionSignal(messages), [messages]); - if (activeForSubmitRef.current === submitCount) { - return true; - } - if (Date.now() - lastTriggeredAtRef.current < COOLDOWN_MS) { - return false; - } - if (submitCount < MIN_SUBMIT_COUNT) { - return false; - } - if (!shouldTrigger) { - return false; - } - lastTriggeredAtRef.current = Date.now(); - activeForSubmitRef.current = submitCount; - return true; -} -var import_react313, EXTERNAL_COMMAND_PATTERNS, FRICTION_PATTERNS, MIN_SUBMIT_COUNT = 3, COOLDOWN_MS; -var init_useIssueFlagBanner = __esm(() => { - init_messages9(); - import_react313 = __toESM(require_react(), 1); - EXTERNAL_COMMAND_PATTERNS = [ - /\bcurl\b/, - /\bwget\b/, - /\bssh\b/, - /\bkubectl\b/, - /\bsrun\b/, - /\bdocker\b/, - /\bbq\b/, - /\bgsutil\b/, - /\bgcloud\b/, - /\baws\b/, - /\bgit\s+push\b/, - /\bgit\s+pull\b/, - /\bgit\s+fetch\b/, - /\bgh\s+(pr|issue)\b/, - /\bnc\b/, - /\bncat\b/, - /\btelnet\b/, - /\bftp\b/ - ]; - FRICTION_PATTERNS = [ - /^no[,!]\s/i, - /\bthat'?s (wrong|incorrect|not (what|right|correct))\b/i, - /\bnot what I (asked|wanted|meant|said)\b/i, - /\bI (said|asked|wanted|told you|already said)\b/i, - /\bwhy did you\b/i, - /\byou should(n'?t| not)? have\b/i, - /\byou were supposed to\b/i, - /\btry again\b/i, - /\b(undo|revert) (that|this|it|what you)\b/i - ]; - COOLDOWN_MS = 30 * 60 * 1000; -}); - -// src/components/DevBar.tsx -var import_compiler_runtime366, import_react314, jsx_dev_runtime465; -var init_DevBar = __esm(() => { - init_state(); - init_ink2(); - import_compiler_runtime366 = __toESM(require_compiler_runtime(), 1); - import_react314 = __toESM(require_react(), 1); - jsx_dev_runtime465 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/ink/components/AlternateScreen.tsx -function AlternateScreen(t0) { - const $2 = import_compiler_runtime367.c(7); - const { - children, - mouseTracking: t1 - } = t0; - const mouseTracking = t1 === undefined ? true : t1; - const size = import_react315.useContext(TerminalSizeContext); - const writeRaw = import_react315.useContext(TerminalWriteContext); - let t22; - let t32; - if ($2[0] !== mouseTracking || $2[1] !== writeRaw) { - t22 = () => { - const ink = instances_default.get(process.stdout); - if (!writeRaw) { - return; - } - writeRaw(ENTER_ALT_SCREEN + "\x1B[2J\x1B[H" + (mouseTracking ? ENABLE_MOUSE_TRACKING : "")); - ink?.setAltScreenActive(true, mouseTracking); - return () => { - ink?.setAltScreenActive(false); - ink?.clearTextSelection(); - writeRaw((mouseTracking ? DISABLE_MOUSE_TRACKING : "") + EXIT_ALT_SCREEN); - }; - }; - t32 = [writeRaw, mouseTracking]; - $2[0] = mouseTracking; - $2[1] = writeRaw; - $2[2] = t22; - $2[3] = t32; - } else { - t22 = $2[2]; - t32 = $2[3]; - } - import_react315.useInsertionEffect(t22, t32); - const t4 = size?.rows ?? 24; - let t5; - if ($2[4] !== children || $2[5] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime466.jsxDEV(Box_default, { - flexDirection: "column", - height: t4, - width: "100%", - flexShrink: 0, - children - }, undefined, false, undefined, this); - $2[4] = children; - $2[5] = t4; - $2[6] = t5; - } else { - t5 = $2[6]; - } - return t5; -} -var import_compiler_runtime367, import_react315, jsx_dev_runtime466; -var init_AlternateScreen = __esm(() => { - init_instances(); - init_dec(); - init_useTerminalNotification(); - init_Box(); - init_TerminalSizeContext(); - import_compiler_runtime367 = __toESM(require_compiler_runtime(), 1); - import_react315 = __toESM(require_react(), 1); - jsx_dev_runtime466 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useCopyOnSelect.ts -function useCopyOnSelect(selection, isActive, onCopied) { - const copiedRef = import_react316.useRef(false); - const onCopiedRef = import_react316.useRef(onCopied); - onCopiedRef.current = onCopied; - import_react316.useEffect(() => { - if (!isActive) - return; - const unsubscribe2 = selection.subscribe(() => { - const sel = selection.getState(); - const has2 = selection.hasSelection(); - if (sel?.isDragging) { - copiedRef.current = false; - return; - } - if (!has2) { - copiedRef.current = false; - return; - } - if (copiedRef.current) - return; - const enabled2 = getGlobalConfig().copyOnSelect ?? true; - if (!enabled2) - return; - const text = selection.copySelectionNoClear(); - if (!text || !text.trim()) { - copiedRef.current = true; - return; - } - copiedRef.current = true; - onCopiedRef.current?.(text); - }); - return unsubscribe2; - }, [isActive, selection]); -} -function useSelectionBgColor(selection) { - const [themeName] = useTheme(); - import_react316.useEffect(() => { - selection.setSelectionBgColor(getTheme(themeName).selectionBg); - }, [selection, themeName]); -} -var import_react316; -var init_useCopyOnSelect = __esm(() => { - init_ThemeProvider(); - init_config(); - init_theme(); - import_react316 = __toESM(require_react(), 1); -}); - -// src/components/ScrollKeybindingHandler.tsx -function shouldClearSelectionOnKey(key2) { - if (key2.wheelUp || key2.wheelDown) - return false; - const isNav = key2.leftArrow || key2.rightArrow || key2.upArrow || key2.downArrow || key2.home || key2.end || key2.pageUp || key2.pageDown; - if (isNav && (key2.shift || key2.meta || key2.super)) - return false; - return true; -} -function selectionFocusMoveForKey(key2) { - if (!key2.shift || key2.meta) - return null; - if (key2.leftArrow) - return "left"; - if (key2.rightArrow) - return "right"; - if (key2.upArrow) - return "up"; - if (key2.downArrow) - return "down"; - if (key2.home) - return "lineStart"; - if (key2.end) - return "lineEnd"; - return null; -} -function computeWheelStep(state4, dir, now2) { - if (!state4.xtermJs) { - if (state4.wheelMode && now2 - state4.time > WHEEL_MODE_IDLE_DISENGAGE_MS) { - state4.wheelMode = false; - state4.burstCount = 0; - state4.mult = state4.base; - } - if (state4.pendingFlip) { - state4.pendingFlip = false; - if (dir !== state4.dir || now2 - state4.time > WHEEL_BOUNCE_GAP_MAX_MS) { - state4.dir = dir; - state4.time = now2; - state4.mult = state4.base; - return Math.floor(state4.mult); - } - state4.wheelMode = true; - } - const gap2 = now2 - state4.time; - if (dir !== state4.dir && state4.dir !== 0) { - state4.pendingFlip = true; - state4.time = now2; - return 0; - } - state4.dir = dir; - state4.time = now2; - if (state4.wheelMode) { - if (gap2 < WHEEL_BURST_MS) { - if (++state4.burstCount >= 5) { - state4.wheelMode = false; - state4.burstCount = 0; - state4.mult = state4.base; - } else { - return 1; - } - } else { - state4.burstCount = 0; - } - } - if (state4.wheelMode) { - const m4 = Math.pow(0.5, gap2 / WHEEL_DECAY_HALFLIFE_MS); - const cap = Math.max(WHEEL_MODE_CAP, state4.base * 2); - const next2 = 1 + (state4.mult - 1) * m4 + WHEEL_MODE_STEP * m4; - state4.mult = Math.min(cap, next2, state4.mult + WHEEL_MODE_RAMP); - return Math.floor(state4.mult); - } - if (gap2 > WHEEL_ACCEL_WINDOW_MS) { - state4.mult = state4.base; - } else { - const cap = Math.max(WHEEL_ACCEL_MAX, state4.base * 2); - state4.mult = Math.min(cap, state4.mult + WHEEL_ACCEL_STEP); - } - return Math.floor(state4.mult); - } - const gap = now2 - state4.time; - const sameDir = dir === state4.dir; - state4.time = now2; - state4.dir = dir; - if (sameDir && gap < WHEEL_BURST_MS) - return 1; - if (!sameDir || gap > WHEEL_DECAY_IDLE_MS) { - state4.mult = 2; - state4.frac = 0; - } else { - const m4 = Math.pow(0.5, gap / WHEEL_DECAY_HALFLIFE_MS); - const cap = gap >= WHEEL_DECAY_GAP_MS ? WHEEL_DECAY_CAP_SLOW : WHEEL_DECAY_CAP_FAST; - state4.mult = Math.min(cap, 1 + (state4.mult - 1) * m4 + WHEEL_DECAY_STEP * m4); - } - const total = state4.mult + state4.frac; - const rows = Math.floor(total); - state4.frac = total - rows; - return rows; -} -function readScrollSpeedBase() { - const raw = process.env.CLAUDE_CODE_SCROLL_SPEED; - if (!raw) - return 1; - const n6 = parseFloat(raw); - return Number.isNaN(n6) || n6 <= 0 ? 1 : Math.min(n6, 20); -} -function initWheelAccel(xtermJs = false, base2 = 1) { - return { - time: 0, - mult: base2, - dir: 0, - xtermJs, - frac: 0, - base: base2, - pendingFlip: false, - wheelMode: false, - burstCount: 0 - }; -} -function initAndLogWheelAccel() { - const xtermJs = isXtermJs(); - const base2 = readScrollSpeedBase(); - logForDebugging(`wheel accel: ${xtermJs ? "decay (xterm.js)" : "window (native)"} \xB7 base=${base2} \xB7 TERM_PROGRAM=${process.env.TERM_PROGRAM ?? "unset"}`); - return initWheelAccel(xtermJs, base2); -} -function ScrollKeybindingHandler({ - scrollRef, - isActive, - onScroll, - isModal = false -}) { - const selection = useSelection(); - const { - addNotification - } = useNotifications(); - const wheelAccel = import_react317.useRef(null); - function showCopiedToast(text) { - const path27 = getClipboardPath(); - const n6 = text.length; - let msg; - switch (path27) { - case "native": - msg = `copied ${n6} chars to clipboard`; - break; - case "tmux-buffer": - msg = `copied ${n6} chars to tmux buffer \xB7 paste with prefix + ]`; - break; - case "osc52": - msg = `sent ${n6} chars via OSC 52 \xB7 check terminal clipboard settings if paste fails`; - break; - } - addNotification({ - key: "selection-copied", - text: msg, - color: "suggestion", - priority: "immediate", - timeoutMs: path27 === "native" ? 2000 : 4000 - }); - } - function copyAndToast() { - const text_0 = selection.copySelection(); - if (text_0) - showCopiedToast(text_0); - } - function translateSelectionForJump(s4, delta) { - const sel = selection.getState(); - if (!sel?.anchor || !sel.focus) - return; - const top = s4.getViewportTop(); - const bottom = top + s4.getViewportHeight() - 1; - if (sel.anchor.row < top || sel.anchor.row > bottom) - return; - if (sel.focus.row < top || sel.focus.row > bottom) - return; - const max2 = Math.max(0, s4.getScrollHeight() - s4.getViewportHeight()); - const cur = s4.getScrollTop() + s4.getPendingDelta(); - const actual = Math.max(0, Math.min(max2, cur + delta)) - cur; - if (actual === 0) - return; - if (actual > 0) { - selection.captureScrolledRows(top, top + actual - 1, "above"); - selection.shiftSelection(-actual, top, bottom); - } else { - const a5 = -actual; - selection.captureScrolledRows(bottom - a5 + 1, bottom, "below"); - selection.shiftSelection(a5, top, bottom); - } - } - useKeybindings({ - "scroll:pageUp": () => { - const s_0 = scrollRef.current; - if (!s_0) - return; - const d4 = -Math.max(1, Math.floor(s_0.getViewportHeight() / 2)); - translateSelectionForJump(s_0, d4); - const sticky = jumpBy(s_0, d4); - onScroll?.(sticky, s_0); - }, - "scroll:pageDown": () => { - const s_1 = scrollRef.current; - if (!s_1) - return; - const d_0 = Math.max(1, Math.floor(s_1.getViewportHeight() / 2)); - translateSelectionForJump(s_1, d_0); - const sticky_0 = jumpBy(s_1, d_0); - onScroll?.(sticky_0, s_1); - }, - "scroll:lineUp": () => { - selection.clearSelection(); - const s_2 = scrollRef.current; - if (!s_2 || s_2.getScrollHeight() <= s_2.getViewportHeight()) - return false; - wheelAccel.current ??= initAndLogWheelAccel(); - scrollUp2(s_2, computeWheelStep(wheelAccel.current, -1, performance.now())); - onScroll?.(false, s_2); - }, - "scroll:lineDown": () => { - selection.clearSelection(); - const s_3 = scrollRef.current; - if (!s_3 || s_3.getScrollHeight() <= s_3.getViewportHeight()) - return false; - wheelAccel.current ??= initAndLogWheelAccel(); - const step = computeWheelStep(wheelAccel.current, 1, performance.now()); - const reachedBottom = scrollDown2(s_3, step); - onScroll?.(reachedBottom, s_3); - }, - "scroll:top": () => { - const s_4 = scrollRef.current; - if (!s_4) - return; - translateSelectionForJump(s_4, -(s_4.getScrollTop() + s_4.getPendingDelta())); - s_4.scrollTo(0); - onScroll?.(false, s_4); - }, - "scroll:bottom": () => { - const s_5 = scrollRef.current; - if (!s_5) - return; - const max_0 = Math.max(0, s_5.getScrollHeight() - s_5.getViewportHeight()); - translateSelectionForJump(s_5, max_0 - (s_5.getScrollTop() + s_5.getPendingDelta())); - s_5.scrollTo(max_0); - s_5.scrollToBottom(); - onScroll?.(true, s_5); - }, - "selection:copy": copyAndToast - }, { - context: "Scroll", - isActive - }); - useKeybindings({ - "scroll:halfPageUp": () => { - const s_6 = scrollRef.current; - if (!s_6) - return; - const d_1 = -Math.max(1, Math.floor(s_6.getViewportHeight() / 2)); - translateSelectionForJump(s_6, d_1); - const sticky_1 = jumpBy(s_6, d_1); - onScroll?.(sticky_1, s_6); - }, - "scroll:halfPageDown": () => { - const s_7 = scrollRef.current; - if (!s_7) - return; - const d_2 = Math.max(1, Math.floor(s_7.getViewportHeight() / 2)); - translateSelectionForJump(s_7, d_2); - const sticky_2 = jumpBy(s_7, d_2); - onScroll?.(sticky_2, s_7); - }, - "scroll:fullPageUp": () => { - const s_8 = scrollRef.current; - if (!s_8) - return; - const d_3 = -Math.max(1, s_8.getViewportHeight()); - translateSelectionForJump(s_8, d_3); - const sticky_3 = jumpBy(s_8, d_3); - onScroll?.(sticky_3, s_8); - }, - "scroll:fullPageDown": () => { - const s_9 = scrollRef.current; - if (!s_9) - return; - const d_4 = Math.max(1, s_9.getViewportHeight()); - translateSelectionForJump(s_9, d_4); - const sticky_4 = jumpBy(s_9, d_4); - onScroll?.(sticky_4, s_9); - } - }, { - context: "Scroll", - isActive - }); - use_input_default((input, key2, event) => { - const s_10 = scrollRef.current; - if (!s_10) - return; - const sticky_5 = applyModalPagerAction(s_10, modalPagerAction(input, key2), (d_5) => translateSelectionForJump(s_10, d_5)); - if (sticky_5 === null) - return; - onScroll?.(sticky_5, s_10); - event.stopImmediatePropagation(); - }, { - isActive: isActive && isModal - }); - use_input_default((input_0, key_0, event_0) => { - if (!selection.hasSelection()) - return; - if (key_0.escape) { - selection.clearSelection(); - event_0.stopImmediatePropagation(); - return; - } - if (key_0.ctrl && !key_0.shift && !key_0.meta && input_0 === "c") { - copyAndToast(); - event_0.stopImmediatePropagation(); - return; - } - const move = selectionFocusMoveForKey(key_0); - if (move) { - selection.moveFocus(move); - event_0.stopImmediatePropagation(); - return; - } - if (shouldClearSelectionOnKey(key_0)) { - selection.clearSelection(); - } - }, { - isActive - }); - useDragToScroll(scrollRef, selection, isActive, onScroll); - useCopyOnSelect(selection, isActive, showCopiedToast); - useSelectionBgColor(selection); - return null; -} -function useDragToScroll(scrollRef, selection, isActive, onScroll) { - const timerRef = import_react317.useRef(null); - const dirRef = import_react317.useRef(0); - const lastScrolledDirRef = import_react317.useRef(0); - const ticksRef = import_react317.useRef(0); - const onScrollRef = import_react317.useRef(onScroll); - onScrollRef.current = onScroll; - import_react317.useEffect(() => { - if (!isActive) - return; - function stop() { - dirRef.current = 0; - if (timerRef.current) { - clearInterval(timerRef.current); - timerRef.current = null; - } - } - function tick() { - const sel = selection.getState(); - const s4 = scrollRef.current; - const dir = dirRef.current; - if (!sel?.isDragging || !sel.focus || !s4 || dir === 0 || ++ticksRef.current > AUTOSCROLL_MAX_TICKS) { - stop(); - return; - } - if (s4.getPendingDelta() !== 0) - return; - const top = s4.getViewportTop(); - const bottom = top + s4.getViewportHeight() - 1; - if (dir < 0) { - if (s4.getScrollTop() <= 0) { - stop(); - return; - } - const actual = Math.min(AUTOSCROLL_LINES, s4.getScrollTop()); - selection.captureScrolledRows(bottom - actual + 1, bottom, "below"); - selection.shiftAnchor(actual, 0, bottom); - s4.scrollBy(-AUTOSCROLL_LINES); - } else { - const max2 = Math.max(0, s4.getScrollHeight() - s4.getViewportHeight()); - if (s4.getScrollTop() >= max2) { - stop(); - return; - } - const actual_0 = Math.min(AUTOSCROLL_LINES, max2 - s4.getScrollTop()); - selection.captureScrolledRows(top, top + actual_0 - 1, "above"); - selection.shiftAnchor(-actual_0, top, bottom); - s4.scrollBy(AUTOSCROLL_LINES); - } - onScrollRef.current?.(false, s4); - } - function start(dir_0) { - lastScrolledDirRef.current = dir_0; - if (dirRef.current === dir_0) - return; - stop(); - dirRef.current = dir_0; - ticksRef.current = 0; - tick(); - if (dirRef.current === dir_0) { - timerRef.current = setInterval(tick, AUTOSCROLL_INTERVAL_MS); - } - } - function check3() { - const s_0 = scrollRef.current; - if (!s_0) { - stop(); - return; - } - const top_0 = s_0.getViewportTop(); - const bottom_0 = top_0 + s_0.getViewportHeight() - 1; - const sel_0 = selection.getState(); - if (!sel_0?.isDragging || sel_0.scrolledOffAbove.length === 0 && sel_0.scrolledOffBelow.length === 0) { - lastScrolledDirRef.current = 0; - } - const dir_1 = dragScrollDirection(sel_0, top_0, bottom_0, lastScrolledDirRef.current); - if (dir_1 === 0) { - if (lastScrolledDirRef.current !== 0 && sel_0?.focus) { - const want = sel_0.focus.row < top_0 ? -1 : sel_0.focus.row > bottom_0 ? 1 : 0; - if (want !== 0 && want !== lastScrolledDirRef.current) { - sel_0.scrolledOffAbove = []; - sel_0.scrolledOffBelow = []; - sel_0.scrolledOffAboveSW = []; - sel_0.scrolledOffBelowSW = []; - lastScrolledDirRef.current = 0; - } - } - stop(); - } else - start(dir_1); - } - const unsubscribe2 = selection.subscribe(check3); - return () => { - unsubscribe2(); - stop(); - lastScrolledDirRef.current = 0; - }; - }, [isActive, scrollRef, selection]); -} -function dragScrollDirection(sel, top, bottom, alreadyScrollingDir = 0) { - if (!sel?.isDragging || !sel.anchor || !sel.focus) - return 0; - const row = sel.focus.row; - const want = row < top ? -1 : row > bottom ? 1 : 0; - if (alreadyScrollingDir !== 0) { - return want === alreadyScrollingDir ? want : 0; - } - if (sel.anchor.row < top || sel.anchor.row > bottom) - return 0; - return want; -} -function jumpBy(s4, delta) { - const max2 = Math.max(0, s4.getScrollHeight() - s4.getViewportHeight()); - const target = s4.getScrollTop() + s4.getPendingDelta() + delta; - if (target >= max2) { - s4.scrollTo(max2); - s4.scrollToBottom(); - return true; - } - s4.scrollTo(Math.max(0, target)); - return false; -} -function scrollDown2(s4, amount) { - const max2 = Math.max(0, s4.getScrollHeight() - s4.getViewportHeight()); - const effectiveTop = s4.getScrollTop() + s4.getPendingDelta(); - if (effectiveTop + amount >= max2) { - s4.scrollToBottom(); - return true; - } - s4.scrollBy(amount); - return false; -} -function scrollUp2(s4, amount) { - const effectiveTop = s4.getScrollTop() + s4.getPendingDelta(); - if (effectiveTop - amount <= 0) { - s4.scrollTo(0); - return; - } - s4.scrollBy(-amount); -} -function modalPagerAction(input, key2) { - if (key2.meta) - return null; - if (!key2.ctrl && !key2.shift) { - if (key2.upArrow) - return "lineUp"; - if (key2.downArrow) - return "lineDown"; - if (key2.home) - return "top"; - if (key2.end) - return "bottom"; - } - if (key2.ctrl) { - if (key2.shift) - return null; - switch (input) { - case "u": - return "halfPageUp"; - case "d": - return "halfPageDown"; - case "b": - return "fullPageUp"; - case "f": - return "fullPageDown"; - case "n": - return "lineDown"; - case "p": - return "lineUp"; - default: - return null; - } - } - const c9 = input[0]; - if (!c9 || input !== c9.repeat(input.length)) - return null; - if (c9 === "G" || c9 === "g" && key2.shift) - return "bottom"; - if (key2.shift) - return null; - switch (c9) { - case "g": - return "top"; - case "j": - return "lineDown"; - case "k": - return "lineUp"; - case " ": - return "fullPageDown"; - case "b": - return "fullPageUp"; - default: - return null; - } -} -function applyModalPagerAction(s4, act, onBeforeJump) { - switch (act) { - case null: - return null; - case "lineUp": - case "lineDown": { - const d4 = act === "lineDown" ? 1 : -1; - onBeforeJump(d4); - return jumpBy(s4, d4); - } - case "halfPageUp": - case "halfPageDown": { - const half = Math.max(1, Math.floor(s4.getViewportHeight() / 2)); - const d4 = act === "halfPageDown" ? half : -half; - onBeforeJump(d4); - return jumpBy(s4, d4); - } - case "fullPageUp": - case "fullPageDown": { - const page = Math.max(1, s4.getViewportHeight()); - const d4 = act === "fullPageDown" ? page : -page; - onBeforeJump(d4); - return jumpBy(s4, d4); - } - case "top": - onBeforeJump(-(s4.getScrollTop() + s4.getPendingDelta())); - s4.scrollTo(0); - return false; - case "bottom": { - const max2 = Math.max(0, s4.getScrollHeight() - s4.getViewportHeight()); - onBeforeJump(max2 - (s4.getScrollTop() + s4.getPendingDelta())); - s4.scrollTo(max2); - s4.scrollToBottom(); - return true; - } - } -} -var import_react317, WHEEL_ACCEL_WINDOW_MS = 40, WHEEL_ACCEL_STEP = 0.3, WHEEL_ACCEL_MAX = 6, WHEEL_BOUNCE_GAP_MAX_MS = 200, WHEEL_MODE_STEP = 15, WHEEL_MODE_CAP = 15, WHEEL_MODE_RAMP = 3, WHEEL_MODE_IDLE_DISENGAGE_MS = 1500, WHEEL_DECAY_HALFLIFE_MS = 150, WHEEL_DECAY_STEP = 5, WHEEL_BURST_MS = 5, WHEEL_DECAY_GAP_MS = 80, WHEEL_DECAY_CAP_SLOW = 3, WHEEL_DECAY_CAP_FAST = 6, WHEEL_DECAY_IDLE_MS = 500, AUTOSCROLL_LINES = 2, AUTOSCROLL_INTERVAL_MS = 50, AUTOSCROLL_MAX_TICKS = 200; -var init_ScrollKeybindingHandler = __esm(() => { - init_notifications(); - init_useCopyOnSelect(); - init_use_selection(); - init_terminal(); - init_osc(); - init_ink2(); - init_useKeybinding(); - init_debug(); - import_react317 = __toESM(require_react(), 1); -}); - -// src/screens/REPL.tsx -var exports_REPL = {}; -__export(exports_REPL, { - REPL: () => REPL -}); -import { dirname as dirname59, join as join149 } from "path"; -import { tmpdir as tmpdir13 } from "os"; -import { writeFile as writeFile47 } from "fs/promises"; -import { randomUUID as randomUUID49 } from "crypto"; -function TranscriptModeFooter(t0) { - const $2 = import_compiler_runtime368.c(9); - const { - showAllInTranscript, - virtualScroll, - searchBadge, - suppressShowAll: t1, - status: status2 - } = t0; - const suppressShowAll = t1 === undefined ? false : t1; - const toggleShortcut = useShortcutDisplay("app:toggleTranscript", "Global", "ctrl+o"); - const showAllShortcut = useShortcutDisplay("transcript:toggleShowAll", "Transcript", "ctrl+e"); - const t22 = searchBadge ? " \xB7 n/N to navigate" : virtualScroll ? ` \xB7 ${figures_default.arrowUp}${figures_default.arrowDown} scroll \xB7 home/end top/bottom` : suppressShowAll ? "" : ` \xB7 ${showAllShortcut} to ${showAllInTranscript ? "collapse" : "show all"}`; - let t32; - if ($2[0] !== t22 || $2[1] !== toggleShortcut) { - t32 = /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Showing detailed transcript \xB7 ", - toggleShortcut, - " to toggle", - t22 - ] - }, undefined, true, undefined, this); - $2[0] = t22; - $2[1] = toggleShortcut; - $2[2] = t32; - } else { - t32 = $2[2]; - } - let t4; - if ($2[3] !== searchBadge || $2[4] !== status2) { - t4 = status2 ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexGrow: 1 - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - children: [ - status2, - " " - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) : searchBadge ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexGrow: 1 - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: [ - searchBadge.current, - "/", - searchBadge.count, - " " - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) : null; - $2[3] = searchBadge; - $2[4] = status2; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== t32 || $2[7] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - noSelect: true, - alignItems: "center", - alignSelf: "center", - borderTopDimColor: true, - borderBottom: false, - borderLeft: false, - borderRight: false, - borderStyle: "single", - marginTop: 1, - paddingLeft: 2, - width: "100%", - children: [ - t32, - t4 - ] - }, undefined, true, undefined, this); - $2[6] = t32; - $2[7] = t4; - $2[8] = t5; - } else { - t5 = $2[8]; - } - return t5; -} -function TranscriptSearchBar({ - jumpRef, - count: count4, - current, - onClose, - onCancel, - setHighlight, - initialQuery -}) { - const { - query: query2, - cursorOffset - } = useSearchInput({ - isActive: true, - initialQuery, - onExit: () => onClose(query2), - onCancel - }); - const [indexStatus, setIndexStatus] = React156.useState("building"); - React156.useEffect(() => { - let alive = true; - const warm = jumpRef.current?.warmSearchIndex; - if (!warm) { - setIndexStatus(null); - return; - } - setIndexStatus("building"); - warm().then((ms) => { - if (!alive) - return; - if (ms < 20) { - setIndexStatus(null); - } else { - setIndexStatus({ - ms - }); - setTimeout(() => alive && setIndexStatus(null), 2000); - } - }); - return () => { - alive = false; - }; - }, []); - const warmDone = indexStatus !== "building"; - import_react318.useEffect(() => { - if (!warmDone) - return; - jumpRef.current?.setSearchQuery(query2); - setHighlight(query2); - }, [query2, warmDone]); - const off = cursorOffset; - const cursorChar = off < query2.length ? query2[off] : " "; - return /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - borderTopDimColor: true, - borderBottom: false, - borderLeft: false, - borderRight: false, - borderStyle: "single", - marginTop: 1, - paddingLeft: 2, - width: "100%", - noSelect: true, - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - children: "/" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - children: query2.slice(0, off) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - inverse: true, - children: cursorChar - }, undefined, false, undefined, this), - off < query2.length && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - children: query2.slice(off + 1) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexGrow: 1 - }, undefined, false, undefined, this), - indexStatus === "building" ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: "indexing\u2026 " - }, undefined, false, undefined, this) : indexStatus ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "indexed in ", - indexStatus.ms, - "ms " - ] - }, undefined, true, undefined, this) : count4 === 0 && query2 ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - color: "error", - children: "no matches " - }, undefined, false, undefined, this) : count4 > 0 ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: [ - current, - "/", - count4, - " " - ] - }, undefined, true, undefined, this) : null - ] - }, undefined, true, undefined, this); -} -function AnimatedTerminalTitle(t0) { - const $2 = import_compiler_runtime368.c(6); - const { - isAnimating, - title, - disabled, - noPrefix - } = t0; - const terminalFocused = useTerminalFocus(); - const [frame, setFrame] = import_react318.useState(0); - let t1; - let t22; - if ($2[0] !== disabled || $2[1] !== isAnimating || $2[2] !== noPrefix || $2[3] !== terminalFocused) { - t1 = () => { - if (disabled || noPrefix || !isAnimating || !terminalFocused) { - return; - } - const interval = setInterval(_temp2100, TITLE_ANIMATION_INTERVAL_MS, setFrame); - return () => clearInterval(interval); - }; - t22 = [disabled, noPrefix, isAnimating, terminalFocused]; - $2[0] = disabled; - $2[1] = isAnimating; - $2[2] = noPrefix; - $2[3] = terminalFocused; - $2[4] = t1; - $2[5] = t22; - } else { - t1 = $2[4]; - t22 = $2[5]; - } - import_react318.useEffect(t1, t22); - const prefix = isAnimating ? TITLE_ANIMATION_FRAMES[frame] ?? TITLE_STATIC_PREFIX : TITLE_STATIC_PREFIX; - useTerminalTitle(disabled ? null : noPrefix ? title : `${prefix} ${title}`); - return null; -} -function _temp2100(setFrame_0) { - return setFrame_0(_temp301); -} -function _temp301(f4) { - return (f4 + 1) % TITLE_ANIMATION_FRAMES.length; -} -function REPL({ - commands: initialCommands, - debug: debug2, - initialTools, - initialMessages, - pendingHookMessages, - initialFileHistorySnapshots, - initialContentReplacements, - initialAgentName, - initialAgentColor, - mcpClients: initialMcpClients, - dynamicMcpConfig: initialDynamicMcpConfig, - autoConnectIdeFlag, - strictMcpConfig = false, - systemPrompt: customSystemPrompt, - appendSystemPrompt, - onBeforeQuery, - onTurnComplete, - disabled = false, - mainThreadAgentDefinition: initialMainThreadAgentDefinition, - disableSlashCommands = false, - taskListId, - remoteSessionConfig, - directConnectConfig, - sshSession, - thinkingConfig -}) { - const isRemoteSession = !!remoteSessionConfig; - const titleDisabled = import_react318.useMemo(() => isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE), []); - const moreRightEnabled = import_react318.useMemo(() => false, []); - const disableVirtualScroll = import_react318.useMemo(() => isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL), []); - const disableMessageActions = false; - import_react318.useEffect(() => { - logForDebugging(`[REPL:mount] REPL mounted, disabled=${disabled}`); - return () => logForDebugging(`[REPL:unmount] REPL unmounting`); - }, [disabled]); - const [mainThreadAgentDefinition, setMainThreadAgentDefinition] = import_react318.useState(initialMainThreadAgentDefinition); - const toolPermissionContext = useAppState((s4) => s4.toolPermissionContext); - const verbose = useAppState((s4) => s4.verbose); - const mcp2 = useAppState((s4) => s4.mcp); - const plugins = useAppState((s4) => s4.plugins); - const agentDefinitions = useAppState((s4) => s4.agentDefinitions); - const fileHistory = useAppState((s4) => s4.fileHistory); - const initialMessage = useAppState((s4) => s4.initialMessage); - const queuedCommands = useCommandQueue(); - const spinnerTip = useAppState((s4) => s4.spinnerTip); - const showExpandedTodos = useAppState((s4) => s4.expandedView) === "tasks"; - const pendingWorkerRequest = useAppState((s4) => s4.pendingWorkerRequest); - const pendingSandboxRequest = useAppState((s4) => s4.pendingSandboxRequest); - const teamContext = useAppState((s4) => s4.teamContext); - const tasks2 = useAppState((s4) => s4.tasks); - const workerSandboxPermissions = useAppState((s4) => s4.workerSandboxPermissions); - const elicitation = useAppState((s4) => s4.elicitation); - const ultraplanPendingChoice = useAppState((s4) => s4.ultraplanPendingChoice); - const ultraplanLaunchPending = useAppState((s4) => s4.ultraplanLaunchPending); - const viewingAgentTaskId = useAppState((s4) => s4.viewingAgentTaskId); - const setAppState = useSetAppState(); - const viewedLocalAgent = viewingAgentTaskId ? tasks2[viewingAgentTaskId] : undefined; - const needsBootstrap = isLocalAgentTask(viewedLocalAgent) && viewedLocalAgent.retain && !viewedLocalAgent.diskLoaded; - import_react318.useEffect(() => { - if (!viewingAgentTaskId || !needsBootstrap) - return; - const taskId = viewingAgentTaskId; - getAgentTranscript(asAgentId(taskId)).then((result) => { - setAppState((prev) => { - const t4 = prev.tasks[taskId]; - if (!isLocalAgentTask(t4) || t4.diskLoaded || !t4.retain) - return prev; - const live = t4.messages ?? []; - const liveUuids = new Set(live.map((m4) => m4.uuid)); - const diskOnly = result ? result.messages.filter((m4) => !liveUuids.has(m4.uuid)) : []; - return { - ...prev, - tasks: { - ...prev.tasks, - [taskId]: { - ...t4, - messages: [...diskOnly, ...live], - diskLoaded: true - } - } - }; - }); - }); - }, [viewingAgentTaskId, needsBootstrap, setAppState]); - const store = useAppStateStore(); - const terminal = useTerminalNotification(); - const mainLoopModel = useMainLoopModel(); - const [localCommands, setLocalCommands] = import_react318.useState(initialCommands); - useSkillsChange(isRemoteSession ? undefined : getProjectRoot(), setLocalCommands); - const proactiveActive = React156.useSyncExternalStore(proactiveModule5?.subscribeToProactiveChanges ?? PROACTIVE_NO_OP_SUBSCRIBE, proactiveModule5?.isProactiveActive ?? PROACTIVE_FALSE); - const isBriefOnly = useAppState((s4) => s4.isBriefOnly); - const localTools = import_react318.useMemo(() => getTools(toolPermissionContext), [toolPermissionContext, proactiveActive, isBriefOnly]); - useKickOffCheckAndDisableBypassPermissionsIfNeeded(); - useKickOffCheckAndDisableAutoModeIfNeeded(); - const [dynamicMcpConfig, setDynamicMcpConfig] = import_react318.useState(initialDynamicMcpConfig); - const onChangeDynamicMcpConfig = import_react318.useCallback((config10) => { - setDynamicMcpConfig(config10); - }, [setDynamicMcpConfig]); - const [screen, setScreen] = import_react318.useState("prompt"); - const [showAllInTranscript, setShowAllInTranscript] = import_react318.useState(false); - const [dumpMode, setDumpMode] = import_react318.useState(false); - const [editorStatus, setEditorStatus] = import_react318.useState(""); - const editorGenRef = import_react318.useRef(0); - const editorTimerRef = import_react318.useRef(undefined); - const editorRenderingRef = import_react318.useRef(false); - const { - addNotification, - removeNotification - } = useNotifications(); - let trySuggestBgPRIntercept = SUGGEST_BG_PR_NOOP; - const mcpClients = useMergedClients(initialMcpClients, mcp2.clients); - const [ideSelection, setIDESelection] = import_react318.useState(undefined); - const [ideToInstallExtension, setIDEToInstallExtension] = import_react318.useState(null); - const [ideInstallationStatus, setIDEInstallationStatus] = import_react318.useState(null); - const [showIdeOnboarding, setShowIdeOnboarding] = import_react318.useState(false); - const [showModelSwitchCallout, setShowModelSwitchCallout] = import_react318.useState(() => { - if (false) {} - return false; - }); - const [showEffortCallout, setShowEffortCallout] = import_react318.useState(() => shouldShowEffortCallout(mainLoopModel)); - const showRemoteCallout = useAppState((s4) => s4.showRemoteCallout); - const [showDesktopUpsellStartup, setShowDesktopUpsellStartup] = import_react318.useState(() => shouldShowDesktopUpsellStartup()); - useModelMigrationNotifications(); - useCanSwitchToExistingSubscription(); - useIDEStatusIndicator({ - ideSelection, - mcpClients, - ideInstallationStatus - }); - useMcpConnectivityStatus({ - mcpClients - }); - useAutoModeUnavailableNotification(); - usePluginInstallationStatus(); - usePluginAutoupdateNotification(); - useSettingsErrors(); - useRateLimitWarningNotification(mainLoopModel); - useFastModeNotification(); - useDeprecationWarningNotification(mainLoopModel); - useNpmDeprecationNotification(); - useAntOrgWarningNotification(); - useInstallMessages(); - useChromeExtensionNotification(); - useOfficialMarketplaceNotification(); - useLspInitializationNotification(); - useTeammateLifecycleNotification(); - const { - recommendation: lspRecommendation, - handleResponse: handleLspResponse - } = useLspPluginRecommendation(); - const { - recommendation: hintRecommendation, - handleResponse: handleHintResponse - } = useClaudeCodeHintRecommendation(); - const combinedInitialTools = import_react318.useMemo(() => { - return [...localTools, ...initialTools]; - }, [localTools, initialTools]); - useManagePlugins({ - enabled: !isRemoteSession - }); - const tasksV2 = useTasksV2WithCollapseEffect(); - import_react318.useEffect(() => { - if (isRemoteSession) - return; - performStartupChecks(setAppState); - }, [setAppState, isRemoteSession]); - usePromptsFromClaudeInChrome(isRemoteSession ? EMPTY_MCP_CLIENTS2 : mcpClients, toolPermissionContext.mode); - useSwarmInitialization(setAppState, initialMessages, { - enabled: !isRemoteSession - }); - const mergedTools = useMergedTools(combinedInitialTools, mcp2.tools, toolPermissionContext); - const { - tools, - allowedAgentTypes - } = import_react318.useMemo(() => { - if (!mainThreadAgentDefinition) { - return { - tools: mergedTools, - allowedAgentTypes: undefined - }; - } - const resolved = resolveAgentTools(mainThreadAgentDefinition, mergedTools, false, true); - return { - tools: resolved.resolvedTools, - allowedAgentTypes: resolved.allowedAgentTypes - }; - }, [mainThreadAgentDefinition, mergedTools]); - const commandsWithPlugins = useMergedCommands(localCommands, plugins.commands); - const mergedCommands = useMergedCommands(commandsWithPlugins, mcp2.commands); - const commands7 = import_react318.useMemo(() => disableSlashCommands ? [] : mergedCommands, [disableSlashCommands, mergedCommands]); - useIdeLogging(isRemoteSession ? EMPTY_MCP_CLIENTS2 : mcp2.clients); - useIdeSelection(isRemoteSession ? EMPTY_MCP_CLIENTS2 : mcp2.clients, setIDESelection); - const [streamMode, setStreamMode] = import_react318.useState("responding"); - const streamModeRef = import_react318.useRef(streamMode); - streamModeRef.current = streamMode; - const [streamingToolUses, setStreamingToolUses] = import_react318.useState([]); - const [streamingThinking, setStreamingThinking] = import_react318.useState(null); - import_react318.useEffect(() => { - if (streamingThinking && !streamingThinking.isStreaming && streamingThinking.streamingEndedAt) { - const elapsed = Date.now() - streamingThinking.streamingEndedAt; - const remaining = 30000 - elapsed; - if (remaining > 0) { - const timer = setTimeout(setStreamingThinking, remaining, null); - return () => clearTimeout(timer); - } else { - setStreamingThinking(null); - } - } - }, [streamingThinking]); - const [abortController, setAbortController] = import_react318.useState(null); - const abortControllerRef = import_react318.useRef(null); - abortControllerRef.current = abortController; - const sendBridgeResultRef = import_react318.useRef(() => {}); - const restoreMessageSyncRef = import_react318.useRef(() => {}); - const scrollRef = import_react318.useRef(null); - const modalScrollRef = import_react318.useRef(null); - const lastUserScrollTsRef = import_react318.useRef(0); - const queryGuard = React156.useRef(new QueryGuard).current; - const isQueryActive = React156.useSyncExternalStore(queryGuard.subscribe, queryGuard.getSnapshot); - const [isExternalLoading, setIsExternalLoadingRaw] = React156.useState(remoteSessionConfig?.hasInitialPrompt ?? false); - const isLoading = isQueryActive || isExternalLoading; - const [userInputOnProcessing, setUserInputOnProcessingRaw] = React156.useState(undefined); - const userInputBaselineRef = React156.useRef(0); - const userMessagePendingRef = React156.useRef(false); - const loadingStartTimeRef = React156.useRef(0); - const totalPausedMsRef = React156.useRef(0); - const pauseStartTimeRef = React156.useRef(null); - const resetTimingRefs = React156.useCallback(() => { - loadingStartTimeRef.current = Date.now(); - totalPausedMsRef.current = 0; - pauseStartTimeRef.current = null; - }, []); - const wasQueryActiveRef = React156.useRef(false); - if (isQueryActive && !wasQueryActiveRef.current) { - resetTimingRefs(); - } - wasQueryActiveRef.current = isQueryActive; - const setIsExternalLoading = React156.useCallback((value) => { - setIsExternalLoadingRaw(value); - if (value) - resetTimingRefs(); - }, [resetTimingRefs]); - const swarmStartTimeRef = React156.useRef(null); - const swarmBudgetInfoRef = React156.useRef(undefined); - const focusedInputDialogRef = React156.useRef(undefined); - const PROMPT_SUPPRESSION_MS = 1500; - const [isPromptInputActive, setIsPromptInputActive] = React156.useState(false); - const [autoUpdaterResult, setAutoUpdaterResult] = import_react318.useState(null); - import_react318.useEffect(() => { - if (autoUpdaterResult?.notifications) { - autoUpdaterResult.notifications.forEach((notification) => { - addNotification({ - key: "auto-updater-notification", - text: notification, - priority: "low" - }); - }); - } - }, [autoUpdaterResult, addNotification]); - import_react318.useEffect(() => { - if (isFullscreenEnvEnabled()) { - maybeGetTmuxMouseHint().then((hint) => { - if (hint) { - addNotification({ - key: "tmux-mouse-hint", - text: hint, - priority: "low" - }); - } - }); - } - }, []); - const [showUndercoverCallout, setShowUndercoverCallout] = import_react318.useState(false); - import_react318.useEffect(() => { - if (false) {} - }, []); - const [toolJSX, setToolJSXInternal] = import_react318.useState(null); - const localJSXCommandRef = import_react318.useRef(null); - const setToolJSX = import_react318.useCallback((args) => { - if (args?.isLocalJSXCommand) { - const { - clearLocalJSX: _, - ...rest - } = args; - localJSXCommandRef.current = { - ...rest, - isLocalJSXCommand: true - }; - setToolJSXInternal(rest); - return; - } - if (localJSXCommandRef.current) { - if (args?.clearLocalJSX) { - localJSXCommandRef.current = null; - setToolJSXInternal(null); - return; - } - return; - } - if (args?.clearLocalJSX) { - setToolJSXInternal(null); - return; - } - setToolJSXInternal(args); - }, []); - const [toolUseConfirmQueue, setToolUseConfirmQueue] = import_react318.useState([]); - const [permissionStickyFooter, setPermissionStickyFooter] = import_react318.useState(null); - const [sandboxPermissionRequestQueue, setSandboxPermissionRequestQueue] = import_react318.useState([]); - const [promptQueue, setPromptQueue] = import_react318.useState([]); - const sandboxBridgeCleanupRef = import_react318.useRef(new Map); - const terminalTitleFromRename = useAppState((s4) => s4.settings.terminalTitleFromRename) !== false; - const sessionTitle = terminalTitleFromRename ? getCurrentSessionTitle(getSessionId()) : undefined; - const [haikuTitle, setHaikuTitle] = import_react318.useState(); - const haikuTitleAttemptedRef = import_react318.useRef((initialMessages?.length ?? 0) > 0); - const agentTitle = mainThreadAgentDefinition?.agentType; - const terminalTitle = sessionTitle ?? agentTitle ?? haikuTitle ?? "Claude Code"; - const isWaitingForApproval = toolUseConfirmQueue.length > 0 || promptQueue.length > 0 || pendingWorkerRequest || pendingSandboxRequest; - const isShowingLocalJSXCommand = toolJSX?.isLocalJSXCommand === true && toolJSX?.jsx != null; - const titleIsAnimating = isLoading && !isWaitingForApproval && !isShowingLocalJSXCommand; - import_react318.useEffect(() => { - if (isLoading && !isWaitingForApproval && !isShowingLocalJSXCommand) { - startPreventSleep(); - return () => stopPreventSleep(); - } - }, [isLoading, isWaitingForApproval, isShowingLocalJSXCommand]); - const sessionStatus = isWaitingForApproval || isShowingLocalJSXCommand ? "waiting" : isLoading ? "busy" : "idle"; - const waitingFor = sessionStatus !== "waiting" ? undefined : toolUseConfirmQueue.length > 0 ? `approve ${toolUseConfirmQueue[0].tool.name}` : pendingWorkerRequest ? "worker request" : pendingSandboxRequest ? "sandbox request" : isShowingLocalJSXCommand ? "dialog open" : "input needed"; - import_react318.useEffect(() => { - if (false) {} - }, [sessionStatus, waitingFor]); - const tabStatusGateEnabled = getFeatureValue_CACHED_MAY_BE_STALE("tengu_terminal_sidebar", false); - const showStatusInTerminalTab = tabStatusGateEnabled && (getGlobalConfig().showStatusInTerminalTab ?? false); - useTabStatus(titleDisabled || !showStatusInTerminalTab ? null : sessionStatus); - import_react318.useEffect(() => { - registerLeaderToolUseConfirmQueue(setToolUseConfirmQueue); - return () => unregisterLeaderToolUseConfirmQueue(); - }, [setToolUseConfirmQueue]); - const [messages, rawSetMessages] = import_react318.useState(initialMessages ?? []); - const messagesRef = import_react318.useRef(messages); - const idleHintShownRef = import_react318.useRef(false); - const setMessages = import_react318.useCallback((action2) => { - const prev = messagesRef.current; - const next2 = typeof action2 === "function" ? action2(messagesRef.current) : action2; - messagesRef.current = next2; - if (next2.length < userInputBaselineRef.current) { - userInputBaselineRef.current = 0; - } else if (next2.length > prev.length && userMessagePendingRef.current) { - const delta = next2.length - prev.length; - const added = prev.length === 0 || next2[0] === prev[0] ? next2.slice(-delta) : next2.slice(0, delta); - if (added.some(isHumanTurn)) { - userMessagePendingRef.current = false; - } else { - userInputBaselineRef.current = next2.length; - } - } - rawSetMessages(next2); - }, []); - const setUserInputOnProcessing = import_react318.useCallback((input) => { - if (input !== undefined) { - userInputBaselineRef.current = messagesRef.current.length; - userMessagePendingRef.current = true; - } else { - userMessagePendingRef.current = false; - } - setUserInputOnProcessingRaw(input); - }, []); - const { - dividerIndex, - dividerYRef, - onScrollAway, - onRepin, - jumpToNew, - shiftDivider - } = useUnseenDivider(messages.length); - if (false) {} - const [cursor, setCursor] = import_react318.useState(null); - const cursorNavRef = import_react318.useRef(null); - const unseenDivider = import_react318.useMemo(() => computeUnseenDivider(messages, dividerIndex), [dividerIndex, messages.length]); - const repinScroll = import_react318.useCallback(() => { - scrollRef.current?.scrollToBottom(); - onRepin(); - setCursor(null); - }, [onRepin, setCursor]); - const lastMsg = messages.at(-1); - const lastMsgIsHuman = lastMsg != null && isHumanTurn(lastMsg); - import_react318.useEffect(() => { - if (lastMsgIsHuman) { - repinScroll(); - } - }, [lastMsgIsHuman, lastMsg, repinScroll]); - const { - maybeLoadOlder - } = HISTORY_STUB; - const composedOnScroll = import_react318.useCallback((sticky, handle) => { - lastUserScrollTsRef.current = Date.now(); - if (sticky) { - onRepin(); - } else { - onScrollAway(handle); - if (false) - ; - if (false) {} - } - }, [onRepin, onScrollAway, maybeLoadOlder, setAppState]); - const awaitPendingHooks = useDeferredHookMessages(pendingHookMessages, setMessages); - const deferredMessages = import_react318.useDeferredValue(messages); - const deferredBehind = messages.length - deferredMessages.length; - if (deferredBehind > 0) { - logForDebugging(`[useDeferredValue] Messages deferred by ${deferredBehind} (${deferredMessages.length}\u2192${messages.length})`); - } - const [frozenTranscriptState, setFrozenTranscriptState] = import_react318.useState(null); - const [inputValue, setInputValueRaw] = import_react318.useState(() => consumeEarlyInput()); - const inputValueRef = import_react318.useRef(inputValue); - inputValueRef.current = inputValue; - const insertTextRef = import_react318.useRef(null); - const setInputValue = import_react318.useCallback((value) => { - if (trySuggestBgPRIntercept(inputValueRef.current, value)) - return; - if (inputValueRef.current === "" && value !== "" && Date.now() - lastUserScrollTsRef.current >= RECENT_SCROLL_REPIN_WINDOW_MS) { - repinScroll(); - } - inputValueRef.current = value; - setInputValueRaw(value); - setIsPromptInputActive(value.trim().length > 0); - }, [setIsPromptInputActive, repinScroll, trySuggestBgPRIntercept]); - import_react318.useEffect(() => { - if (inputValue.trim().length === 0) - return; - const timer = setTimeout(setIsPromptInputActive, PROMPT_SUPPRESSION_MS, false); - return () => clearTimeout(timer); - }, [inputValue]); - const [inputMode, setInputMode] = import_react318.useState("prompt"); - const [stashedPrompt, setStashedPrompt] = import_react318.useState(); - const handleRemoteInit = import_react318.useCallback((remoteSlashCommands) => { - const remoteCommandSet = new Set(remoteSlashCommands); - setLocalCommands((prev) => prev.filter((cmd) => remoteCommandSet.has(cmd.name) || REMOTE_SAFE_COMMANDS.has(cmd))); - }, [setLocalCommands]); - const [inProgressToolUseIDs, setInProgressToolUseIDs] = import_react318.useState(new Set); - const hasInterruptibleToolInProgressRef = import_react318.useRef(false); - const remoteSession = useRemoteSession({ - config: remoteSessionConfig, - setMessages, - setIsLoading: setIsExternalLoading, - onInit: handleRemoteInit, - setToolUseConfirmQueue, - tools: combinedInitialTools, - setStreamingToolUses, - setStreamMode, - setInProgressToolUseIDs - }); - const directConnect = useDirectConnect({ - config: directConnectConfig, - setMessages, - setIsLoading: setIsExternalLoading, - setToolUseConfirmQueue, - tools: combinedInitialTools - }); - const sshRemote = useSSHSession({ - session: sshSession, - setMessages, - setIsLoading: setIsExternalLoading, - setToolUseConfirmQueue, - tools: combinedInitialTools - }); - const activeRemote = sshRemote.isRemoteMode ? sshRemote : directConnect.isRemoteMode ? directConnect : remoteSession; - const [pastedContents, setPastedContents] = import_react318.useState({}); - const [submitCount, setSubmitCount] = import_react318.useState(0); - const responseLengthRef = import_react318.useRef(0); - const apiMetricsRef2 = import_react318.useRef([]); - const setResponseLength = import_react318.useCallback((f4) => { - const prev = responseLengthRef.current; - responseLengthRef.current = f4(prev); - if (responseLengthRef.current > prev) { - const entries = apiMetricsRef2.current; - if (entries.length > 0) { - const lastEntry = entries.at(-1); - lastEntry.lastTokenTime = Date.now(); - lastEntry.endResponseLength = responseLengthRef.current; - } - } - }, []); - const [streamingText, setStreamingText] = import_react318.useState(null); - const reducedMotion = useAppState((s4) => s4.settings.prefersReducedMotion) ?? false; - const showStreamingText = !reducedMotion && !hasCursorUpViewportYankBug(); - const onStreamingText = import_react318.useCallback((f4) => { - if (!showStreamingText) - return; - setStreamingText(f4); - }, [showStreamingText]); - const visibleStreamingText = streamingText && showStreamingText ? streamingText.substring(0, streamingText.lastIndexOf(` -`) + 1) || null : null; - const [lastQueryCompletionTime, setLastQueryCompletionTime] = import_react318.useState(0); - const [spinnerMessage, setSpinnerMessage] = import_react318.useState(null); - const [spinnerColor, setSpinnerColor] = import_react318.useState(null); - const [spinnerShimmerColor, setSpinnerShimmerColor] = import_react318.useState(null); - const [isMessageSelectorVisible, setIsMessageSelectorVisible] = import_react318.useState(false); - const [messageSelectorPreselect, setMessageSelectorPreselect] = import_react318.useState(undefined); - const [showCostDialog, setShowCostDialog] = import_react318.useState(false); - const [conversationId, setConversationId] = import_react318.useState(randomUUID49()); - const [idleReturnPending, setIdleReturnPending] = import_react318.useState(null); - const skipIdleCheckRef = import_react318.useRef(false); - const lastQueryCompletionTimeRef = import_react318.useRef(lastQueryCompletionTime); - lastQueryCompletionTimeRef.current = lastQueryCompletionTime; - const [contentReplacementStateRef] = import_react318.useState(() => ({ - current: provisionContentReplacementState(initialMessages, initialContentReplacements) - })); - const [haveShownCostDialog, setHaveShownCostDialog] = import_react318.useState(getGlobalConfig().hasAcknowledgedCostThreshold); - const [vimMode, setVimMode] = import_react318.useState("INSERT"); - const [showBashesDialog, setShowBashesDialog] = import_react318.useState(false); - const [isSearchingHistory, setIsSearchingHistory] = import_react318.useState(false); - const [isHelpOpen, setIsHelpOpen] = import_react318.useState(false); - import_react318.useEffect(() => { - if (ultraplanPendingChoice && showBashesDialog) { - setShowBashesDialog(false); - } - }, [ultraplanPendingChoice, showBashesDialog]); - const isTerminalFocused = useTerminalFocus(); - const terminalFocusRef = import_react318.useRef(isTerminalFocused); - terminalFocusRef.current = isTerminalFocused; - const [theme2] = useTheme(); - const tipPickedThisTurnRef = React156.useRef(false); - const pickNewSpinnerTip = import_react318.useCallback(() => { - if (tipPickedThisTurnRef.current) - return; - tipPickedThisTurnRef.current = true; - const newMessages = messagesRef.current.slice(bashToolsProcessedIdx.current); - for (const tool of extractBashToolsFromMessages(newMessages)) { - bashTools.current.add(tool); - } - bashToolsProcessedIdx.current = messagesRef.current.length; - getTipToShowOnSpinner({ - theme: theme2, - readFileState: readFileState.current, - bashTools: bashTools.current - }).then(async (tip) => { - if (tip) { - const content = await tip.content({ - theme: theme2 - }); - setAppState((prev) => ({ - ...prev, - spinnerTip: content - })); - recordShownTip(tip); - } else { - setAppState((prev) => { - if (prev.spinnerTip === undefined) - return prev; - return { - ...prev, - spinnerTip: undefined - }; - }); - } - }); - }, [setAppState, theme2]); - const resetLoadingState = import_react318.useCallback(() => { - setIsExternalLoading(false); - setUserInputOnProcessing(undefined); - responseLengthRef.current = 0; - apiMetricsRef2.current = []; - setStreamingText(null); - setStreamingToolUses([]); - setSpinnerMessage(null); - setSpinnerColor(null); - setSpinnerShimmerColor(null); - pickNewSpinnerTip(); - endInteractionSpan(); - clearSpeculativeChecks(); - }, [pickNewSpinnerTip]); - const hasRunningTeammates = import_react318.useMemo(() => getAllInProcessTeammateTasks(tasks2).some((t4) => t4.status === "running"), [tasks2]); - import_react318.useEffect(() => { - if (!hasRunningTeammates && swarmStartTimeRef.current !== null) { - const totalMs = Date.now() - swarmStartTimeRef.current; - const deferredBudget = swarmBudgetInfoRef.current; - swarmStartTimeRef.current = null; - swarmBudgetInfoRef.current = undefined; - setMessages((prev) => [...prev, createTurnDurationMessage(totalMs, deferredBudget, count2(prev, isLoggableMessage))]); - } - }, [hasRunningTeammates, setMessages]); - const safeYoloMessageShownRef = import_react318.useRef(false); - import_react318.useEffect(() => { - if (false) {} - }, [toolPermissionContext.mode, setMessages]); - const worktreeTipShownRef = import_react318.useRef(false); - import_react318.useEffect(() => { - if (worktreeTipShownRef.current) - return; - const wt = getCurrentWorktreeSession(); - if (!wt?.creationDurationMs || wt.usedSparsePaths) - return; - if (wt.creationDurationMs < 15000) - return; - worktreeTipShownRef.current = true; - const secs = Math.round(wt.creationDurationMs / 1000); - setMessages((prev) => [...prev, createSystemMessage(`Worktree creation took ${secs}s. For large repos, set \`worktree.sparsePaths\` in .claude/settings.json to check out only the directories you need \u2014 e.g. \`{"worktree": {"sparsePaths": ["src", "packages/foo"]}}\`.`, "info")]); - }, [setMessages]); - const onlySleepToolActive = import_react318.useMemo(() => { - const lastAssistant = messages.findLast((m4) => m4.type === "assistant"); - if (lastAssistant?.type !== "assistant") - return false; - const inProgressToolUses = lastAssistant.message.content.filter((b5) => b5.type === "tool_use" && inProgressToolUseIDs.has(b5.id)); - return inProgressToolUses.length > 0 && inProgressToolUses.every((b5) => b5.type === "tool_use" && b5.name === SLEEP_TOOL_NAME); - }, [messages, inProgressToolUseIDs]); - const { - onBeforeQuery: mrOnBeforeQuery, - onTurnComplete: mrOnTurnComplete, - render: mrRender - } = useMoreRight({ - enabled: moreRightEnabled, - setMessages, - inputValue, - setInputValue, - setToolJSX - }); - const showSpinner = (!toolJSX || toolJSX.showSpinner === true) && toolUseConfirmQueue.length === 0 && promptQueue.length === 0 && (isLoading || userInputOnProcessing || hasRunningTeammates || getCommandQueueLength() > 0) && !pendingWorkerRequest && !onlySleepToolActive && (!visibleStreamingText || isBriefOnly); - const hasActivePrompt = toolUseConfirmQueue.length > 0 || promptQueue.length > 0 || sandboxPermissionRequestQueue.length > 0 || elicitation.queue.length > 0 || workerSandboxPermissions.queue.length > 0; - const feedbackSurveyOriginal = useFeedbackSurvey(messages, isLoading, submitCount, "session", hasActivePrompt); - const skillImprovementSurvey = useSkillImprovementSurvey(setMessages); - const showIssueFlagBanner = useIssueFlagBanner(messages, submitCount); - const feedbackSurvey = import_react318.useMemo(() => ({ - ...feedbackSurveyOriginal, - handleSelect: (selected) => { - didAutoRunIssueRef.current = false; - const showedTranscriptPrompt = feedbackSurveyOriginal.handleSelect(selected); - if (selected === "bad" && !showedTranscriptPrompt && shouldAutoRunIssue("feedback_survey_bad")) { - setAutoRunIssueReason("feedback_survey_bad"); - didAutoRunIssueRef.current = true; - } - } - }), [feedbackSurveyOriginal]); - const postCompactSurvey = usePostCompactSurvey(messages, isLoading, hasActivePrompt, { - enabled: !isRemoteSession - }); - const memorySurvey = useMemorySurvey(messages, isLoading, hasActivePrompt, { - enabled: !isRemoteSession - }); - const frustrationDetection = useFrustrationDetection(messages, isLoading, hasActivePrompt, feedbackSurvey.state !== "closed" || postCompactSurvey.state !== "closed" || memorySurvey.state !== "closed"); - useIDEIntegration({ - autoConnectIdeFlag, - ideToInstallExtension, - setDynamicMcpConfig, - setShowIdeOnboarding, - setIDEInstallationState: setIDEInstallationStatus - }); - useFileHistorySnapshotInit(initialFileHistorySnapshots, fileHistory, (fileHistoryState) => setAppState((prev) => ({ - ...prev, - fileHistory: fileHistoryState - }))); - const resume2 = import_react318.useCallback(async (sessionId, log3, entrypoint) => { - const resumeStart = performance.now(); - try { - const messages2 = deserializeMessages(log3.messages); - if (false) {} - const sessionEndTimeoutMs = getSessionEndHookTimeoutMs(); - await executeSessionEndHooks("resume", { - getAppState: () => store.getState(), - setAppState, - signal: AbortSignal.timeout(sessionEndTimeoutMs), - timeoutMs: sessionEndTimeoutMs - }); - const hookMessages = await processSessionStartHooks("resume", { - sessionId, - agentType: mainThreadAgentDefinition?.agentType, - model: mainLoopModel - }); - messages2.push(...hookMessages); - if (entrypoint === "fork") { - copyPlanForFork(log3, asSessionId(sessionId)); - } else { - copyPlanForResume(log3, asSessionId(sessionId)); - } - restoreSessionStateFromLog(log3, setAppState); - if (log3.fileHistorySnapshots) { - copyFileHistoryForResume(log3); - } - const { - agentDefinition: restoredAgent - } = restoreAgentFromSession(log3.agentSetting, initialMainThreadAgentDefinition, agentDefinitions); - setMainThreadAgentDefinition(restoredAgent); - setAppState((prev) => ({ - ...prev, - agent: restoredAgent?.agentType - })); - setAppState((prev) => ({ - ...prev, - standaloneAgentContext: computeStandaloneAgentContext(log3.agentName, log3.agentColor) - })); - updateSessionName(log3.agentName); - restoreReadFileState(messages2, log3.projectPath ?? getOriginalCwd()); - resetLoadingState(); - setAbortController(null); - setConversationId(sessionId); - const targetSessionCosts = getStoredSessionCosts(sessionId); - saveCurrentSessionCosts(); - resetCostState(); - switchSession(asSessionId(sessionId), log3.fullPath ? dirname59(log3.fullPath) : null); - const { - renameRecordingForSession: renameRecordingForSession2 - } = await Promise.resolve().then(() => (init_asciicast(), exports_asciicast)); - await renameRecordingForSession2(); - await resetSessionFilePointer(); - clearSessionMetadata(); - restoreSessionMetadata(log3); - haikuTitleAttemptedRef.current = true; - setHaikuTitle(undefined); - if (entrypoint !== "fork") { - exitRestoredWorktree(); - restoreWorktreeForResume(log3.worktreeSession); - adoptResumedSessionFile(); - restoreRemoteAgentTasks({ - abortController: new AbortController, - getAppState: () => store.getState(), - setAppState - }); - } else { - const ws = getCurrentWorktreeSession(); - if (ws) - saveWorktreeState(ws); - } - if (false) {} - if (targetSessionCosts) { - setCostStateForRestore(targetSessionCosts); - } - if (contentReplacementStateRef.current && entrypoint !== "fork") { - contentReplacementStateRef.current = reconstructContentReplacementState(messages2, log3.contentReplacements ?? []); - } - setMessages(() => messages2); - setToolJSX(null); - setInputValue(""); - logEvent("tengu_session_resumed", { - entrypoint, - success: true, - resume_duration_ms: Math.round(performance.now() - resumeStart) - }); - } catch (error46) { - logEvent("tengu_session_resumed", { - entrypoint, - success: false - }); - throw error46; - } - }, [resetLoadingState, setAppState]); - const [initialReadFileState] = import_react318.useState(() => createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE)); - const readFileState = import_react318.useRef(initialReadFileState); - const bashTools = import_react318.useRef(new Set); - const bashToolsProcessedIdx = import_react318.useRef(0); - const discoveredSkillNamesRef = import_react318.useRef(new Set); - const loadedNestedMemoryPathsRef = import_react318.useRef(new Set); - const restoreReadFileState = import_react318.useCallback((messages2, cwd2) => { - const extracted = extractReadFilesFromMessages(messages2, cwd2, READ_FILE_STATE_CACHE_SIZE); - readFileState.current = mergeFileStateCaches(readFileState.current, extracted); - for (const tool of extractBashToolsFromMessages(messages2)) { - bashTools.current.add(tool); - } - }, []); - import_react318.useEffect(() => { - if (initialMessages && initialMessages.length > 0) { - restoreReadFileState(initialMessages, getOriginalCwd()); - restoreRemoteAgentTasks({ - abortController: new AbortController, - getAppState: () => store.getState(), - setAppState - }); - } - }, []); - const { - status: apiKeyStatus, - reverify - } = useApiKeyVerification(); - const [autoRunIssueReason, setAutoRunIssueReason] = import_react318.useState(null); - const didAutoRunIssueRef = import_react318.useRef(false); - const [exitFlow, setExitFlow] = import_react318.useState(null); - const [isExiting, setIsExiting] = import_react318.useState(false); - const showingCostDialog = !isLoading && showCostDialog; - function getFocusedInputDialog() { - if (isExiting || exitFlow) - return; - if (isMessageSelectorVisible) - return "message-selector"; - if (isPromptInputActive) - return; - if (sandboxPermissionRequestQueue[0]) - return "sandbox-permission"; - const allowDialogsWithAnimation = !toolJSX || toolJSX.shouldContinueAnimation; - if (allowDialogsWithAnimation && toolUseConfirmQueue[0]) - return "tool-permission"; - if (allowDialogsWithAnimation && promptQueue[0]) - return "prompt"; - if (allowDialogsWithAnimation && workerSandboxPermissions.queue[0]) - return "worker-sandbox-permission"; - if (allowDialogsWithAnimation && elicitation.queue[0]) - return "elicitation"; - if (allowDialogsWithAnimation && showingCostDialog) - return "cost"; - if (allowDialogsWithAnimation && idleReturnPending) - return "idle-return"; - if (false) - ; - if (false) - ; - if (allowDialogsWithAnimation && showIdeOnboarding) - return "ide-onboarding"; - if (false) - ; - if (false) - ; - if (allowDialogsWithAnimation && showEffortCallout) - return "effort-callout"; - if (allowDialogsWithAnimation && showRemoteCallout) - return "remote-callout"; - if (allowDialogsWithAnimation && lspRecommendation) - return "lsp-recommendation"; - if (allowDialogsWithAnimation && hintRecommendation) - return "plugin-hint"; - if (allowDialogsWithAnimation && showDesktopUpsellStartup) - return "desktop-upsell"; - return; - } - const focusedInputDialog = getFocusedInputDialog(); - const hasSuppressedDialogs = isPromptInputActive && (sandboxPermissionRequestQueue[0] || toolUseConfirmQueue[0] || promptQueue[0] || workerSandboxPermissions.queue[0] || elicitation.queue[0] || showingCostDialog); - focusedInputDialogRef.current = focusedInputDialog; - import_react318.useEffect(() => { - if (!isLoading) - return; - const isPaused = focusedInputDialog === "tool-permission"; - const now2 = Date.now(); - if (isPaused && pauseStartTimeRef.current === null) { - pauseStartTimeRef.current = now2; - } else if (!isPaused && pauseStartTimeRef.current !== null) { - totalPausedMsRef.current += now2 - pauseStartTimeRef.current; - pauseStartTimeRef.current = null; - } - }, [focusedInputDialog, isLoading]); - const prevDialogRef = import_react318.useRef(focusedInputDialog); - import_react318.useLayoutEffect(() => { - const was = prevDialogRef.current === "tool-permission"; - const now2 = focusedInputDialog === "tool-permission"; - if (was !== now2) - repinScroll(); - prevDialogRef.current = focusedInputDialog; - }, [focusedInputDialog, repinScroll]); - function onCancel() { - if (focusedInputDialog === "elicitation") { - return; - } - logForDebugging(`[onCancel] focusedInputDialog=${focusedInputDialog} streamMode=${streamMode}`); - if (false) {} - queryGuard.forceEnd(); - skipIdleCheckRef.current = false; - if (streamingText?.trim()) { - setMessages((prev) => [...prev, createAssistantMessage({ - content: streamingText - })]); - } - resetLoadingState(); - if (false) {} - if (focusedInputDialog === "tool-permission") { - toolUseConfirmQueue[0]?.onAbort(); - setToolUseConfirmQueue([]); - } else if (focusedInputDialog === "prompt") { - for (const item of promptQueue) { - item.reject(new Error("Prompt cancelled by user")); - } - setPromptQueue([]); - abortController?.abort("user-cancel"); - } else if (activeRemote.isRemoteMode) { - activeRemote.cancelRequest(); - } else { - abortController?.abort("user-cancel"); - } - setAbortController(null); - mrOnTurnComplete(messagesRef.current, true); - } - const handleQueuedCommandOnCancel = import_react318.useCallback(() => { - const result = popAllEditable(inputValue, 0); - if (!result) - return; - setInputValue(result.text); - setInputMode("prompt"); - if (result.images.length > 0) { - setPastedContents((prev) => { - const newContents = { - ...prev - }; - for (const image of result.images) { - newContents[image.id] = image; - } - return newContents; - }); - } - }, [setInputValue, setInputMode, inputValue, setPastedContents]); - const cancelRequestProps = { - setToolUseConfirmQueue, - onCancel, - onAgentsKilled: () => setMessages((prev) => [...prev, createAgentsKilledMessage()]), - isMessageSelectorVisible: isMessageSelectorVisible || !!showBashesDialog, - screen, - abortSignal: abortController?.signal, - popCommandFromQueue: handleQueuedCommandOnCancel, - vimMode, - isLocalJSXCommand: toolJSX?.isLocalJSXCommand, - isSearchingHistory, - isHelpOpen, - inputMode, - inputValue, - streamMode - }; - import_react318.useEffect(() => { - const totalCost = getTotalCostUSD(); - if (totalCost >= 5 && !showCostDialog && !haveShownCostDialog) { - logEvent("tengu_cost_threshold_reached", {}); - setHaveShownCostDialog(true); - if (hasConsoleBillingAccess()) { - setShowCostDialog(true); - } - } - }, [messages, showCostDialog, haveShownCostDialog]); - const sandboxAskCallback = import_react318.useCallback(async (hostPattern) => { - if (isAgentSwarmsEnabled() && isSwarmWorker()) { - const requestId = generateSandboxRequestId(); - const sent = await sendSandboxPermissionRequestViaMailbox(hostPattern.host, requestId); - return new Promise((resolveShouldAllowHost) => { - if (!sent) { - setSandboxPermissionRequestQueue((prev) => [...prev, { - hostPattern, - resolvePromise: resolveShouldAllowHost - }]); - return; - } - registerSandboxPermissionCallback({ - requestId, - host: hostPattern.host, - resolve: resolveShouldAllowHost - }); - setAppState((prev) => ({ - ...prev, - pendingSandboxRequest: { - requestId, - host: hostPattern.host - } - })); - }); - } - return new Promise((resolveShouldAllowHost) => { - let resolved = false; - function resolveOnce(allow) { - if (resolved) - return; - resolved = true; - resolveShouldAllowHost(allow); - } - setSandboxPermissionRequestQueue((prev) => [...prev, { - hostPattern, - resolvePromise: resolveOnce - }]); - if (false) {} - }); - }, [setAppState, store]); - import_react318.useEffect(() => { - const reason = SandboxManager.getSandboxUnavailableReason(); - if (!reason) - return; - if (SandboxManager.isSandboxRequired()) { - process.stderr.write(` -Error: sandbox required but unavailable: ${reason} -` + ` sandbox.failIfUnavailable is set \u2014 refusing to start without a working sandbox. - -`); - gracefulShutdownSync(1, "other"); - return; - } - logForDebugging(`sandbox disabled: ${reason}`, { - level: "warn" - }); - addNotification({ - key: "sandbox-unavailable", - jsx: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - color: "warning", - children: "sandbox disabled" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: " \xB7 /sandbox" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - priority: "medium" - }); - }, [addNotification]); - if (SandboxManager.isSandboxingEnabled()) { - SandboxManager.initialize(sandboxAskCallback).catch((err2) => { - process.stderr.write(` -\u274C Sandbox Error: ${errorMessage(err2)} -`); - gracefulShutdownSync(1, "other"); - }); - } - const setToolPermissionContext = import_react318.useCallback((context7, options2) => { - setAppState((prev) => ({ - ...prev, - toolPermissionContext: { - ...context7, - mode: options2?.preserveMode ? prev.toolPermissionContext.mode : context7.mode - } - })); - setImmediate((setToolUseConfirmQueue2) => { - setToolUseConfirmQueue2((currentQueue) => { - currentQueue.forEach((item) => { - item.recheckPermission(); - }); - return currentQueue; - }); - }, setToolUseConfirmQueue); - }, [setAppState, setToolUseConfirmQueue]); - import_react318.useEffect(() => { - registerLeaderSetToolPermissionContext(setToolPermissionContext); - return () => unregisterLeaderSetToolPermissionContext(); - }, [setToolPermissionContext]); - const canUseTool = useCanUseTool_default(setToolUseConfirmQueue, setToolPermissionContext); - const requestPrompt = import_react318.useCallback((title, toolInputSummary) => (request2) => new Promise((resolve44, reject2) => { - setPromptQueue((prev) => [...prev, { - request: request2, - title, - toolInputSummary, - resolve: resolve44, - reject: reject2 - }]); - }), []); - const getToolUseContext = import_react318.useCallback((messages2, newMessages, abortController2, mainLoopModel2) => { - const s4 = store.getState(); - const computeTools = () => { - const state4 = store.getState(); - const assembled = assembleToolPool(state4.toolPermissionContext, state4.mcp.tools); - const merged = mergeAndFilterTools(combinedInitialTools, assembled, state4.toolPermissionContext.mode); - if (!mainThreadAgentDefinition) - return merged; - return resolveAgentTools(mainThreadAgentDefinition, merged, false, true).resolvedTools; - }; - return { - abortController: abortController2, - options: { - commands: commands7, - tools: computeTools(), - debug: debug2, - verbose: s4.verbose, - mainLoopModel: mainLoopModel2, - thinkingConfig: s4.thinkingEnabled !== false ? thinkingConfig : { - type: "disabled" - }, - mcpClients: mergeClients(initialMcpClients, s4.mcp.clients), - mcpResources: s4.mcp.resources, - ideInstallationStatus, - isNonInteractiveSession: false, - dynamicMcpConfig, - theme: theme2, - agentDefinitions: allowedAgentTypes ? { - ...s4.agentDefinitions, - allowedAgentTypes - } : s4.agentDefinitions, - customSystemPrompt, - appendSystemPrompt, - refreshTools: computeTools - }, - getAppState: () => store.getState(), - setAppState, - messages: messages2, - setMessages, - updateFileHistoryState(updater) { - setAppState((prev) => { - const updated = updater(prev.fileHistory); - if (updated === prev.fileHistory) - return prev; - return { - ...prev, - fileHistory: updated - }; - }); - }, - updateAttributionState(updater) { - setAppState((prev) => { - const updated = updater(prev.attribution); - if (updated === prev.attribution) - return prev; - return { - ...prev, - attribution: updated - }; - }); - }, - openMessageSelector: () => { - if (!disabled) { - setIsMessageSelectorVisible(true); - } - }, - onChangeAPIKey: reverify, - readFileState: readFileState.current, - setToolJSX, - addNotification, - appendSystemMessage: (msg) => setMessages((prev) => [...prev, msg]), - sendOSNotification: (opts) => { - sendNotification(opts, terminal); - }, - onChangeDynamicMcpConfig, - onInstallIDEExtension: setIDEToInstallExtension, - nestedMemoryAttachmentTriggers: new Set, - loadedNestedMemoryPaths: loadedNestedMemoryPathsRef.current, - dynamicSkillDirTriggers: new Set, - discoveredSkillNames: discoveredSkillNamesRef.current, - setResponseLength, - pushApiMetricsEntry: undefined, - setStreamMode, - onCompactProgress: (event) => { - switch (event.type) { - case "hooks_start": - setSpinnerColor("claudeBlue_FOR_SYSTEM_SPINNER"); - setSpinnerShimmerColor("claudeBlueShimmer_FOR_SYSTEM_SPINNER"); - setSpinnerMessage(event.hookType === "pre_compact" ? "Running PreCompact hooks\u2026" : event.hookType === "post_compact" ? "Running PostCompact hooks\u2026" : "Running SessionStart hooks\u2026"); - break; - case "compact_start": - setSpinnerMessage("Compacting conversation"); - break; - case "compact_end": - setSpinnerMessage(null); - setSpinnerColor(null); - setSpinnerShimmerColor(null); - break; - } - }, - setInProgressToolUseIDs, - setHasInterruptibleToolInProgress: (v6) => { - hasInterruptibleToolInProgressRef.current = v6; - }, - resume: resume2, - setConversationId, - requestPrompt: undefined, - contentReplacementState: contentReplacementStateRef.current - }; - }, [commands7, combinedInitialTools, mainThreadAgentDefinition, debug2, initialMcpClients, ideInstallationStatus, dynamicMcpConfig, theme2, allowedAgentTypes, store, setAppState, reverify, addNotification, setMessages, onChangeDynamicMcpConfig, resume2, requestPrompt, disabled, customSystemPrompt, appendSystemPrompt, setConversationId]); - const handleBackgroundQuery = import_react318.useCallback(() => { - abortController?.abort("background"); - const removedNotifications = removeByFilter((cmd) => cmd.mode === "task-notification"); - (async () => { - const toolUseContext = getToolUseContext(messagesRef.current, [], new AbortController, mainLoopModel); - const [defaultSystemPrompt, userContext, systemContext] = await Promise.all([getSystemPrompt(toolUseContext.options.tools, mainLoopModel, Array.from(toolPermissionContext.additionalWorkingDirectories.keys()), toolUseContext.options.mcpClients), getUserContext(), getSystemContext()]); - const systemPrompt = buildEffectiveSystemPrompt({ - mainThreadAgentDefinition, - toolUseContext, - customSystemPrompt, - defaultSystemPrompt, - appendSystemPrompt - }); - toolUseContext.renderedSystemPrompt = systemPrompt; - const notificationAttachments = await getQueuedCommandAttachments(removedNotifications).catch(() => []); - const notificationMessages = notificationAttachments.map(createAttachmentMessage); - const existingPrompts = new Set; - for (const m4 of messagesRef.current) { - if (m4.type === "attachment" && m4.attachment.type === "queued_command" && m4.attachment.commandMode === "task-notification" && typeof m4.attachment.prompt === "string") { - existingPrompts.add(m4.attachment.prompt); - } - } - const uniqueNotifications = notificationMessages.filter((m4) => m4.attachment.type === "queued_command" && (typeof m4.attachment.prompt !== "string" || !existingPrompts.has(m4.attachment.prompt))); - startBackgroundSession({ - messages: [...messagesRef.current, ...uniqueNotifications], - queryParams: { - systemPrompt, - userContext, - systemContext, - canUseTool, - toolUseContext, - querySource: getQuerySourceForREPL() - }, - description: terminalTitle, - setAppState, - agentDefinition: mainThreadAgentDefinition - }); - })(); - }, [abortController, mainLoopModel, toolPermissionContext, mainThreadAgentDefinition, getToolUseContext, customSystemPrompt, appendSystemPrompt, canUseTool, setAppState]); - const { - handleBackgroundSession - } = useSessionBackgrounding({ - setMessages, - setIsLoading: setIsExternalLoading, - resetLoadingState, - setAbortController, - onBackgroundQuery: handleBackgroundQuery - }); - const onQueryEvent = import_react318.useCallback((event) => { - handleMessageFromStream(event, (newMessage) => { - if (isCompactBoundaryMessage(newMessage)) { - if (isFullscreenEnvEnabled()) { - setMessages((old) => [...getMessagesAfterCompactBoundary(old, { - includeSnipped: true - }), newMessage]); - } else { - setMessages(() => [newMessage]); - } - setConversationId(randomUUID49()); - if (false) {} - } else if (newMessage.type === "progress" && isEphemeralToolProgress(newMessage.data.type)) { - setMessages((oldMessages) => { - const last2 = oldMessages.at(-1); - if (last2?.type === "progress" && last2.parentToolUseID === newMessage.parentToolUseID && last2.data.type === newMessage.data.type) { - const copy2 = oldMessages.slice(); - copy2[copy2.length - 1] = newMessage; - return copy2; - } - return [...oldMessages, newMessage]; - }); - } else { - setMessages((oldMessages) => [...oldMessages, newMessage]); - } - if (false) {} - }, (newContent) => { - setResponseLength((length) => length + newContent.length); - }, setStreamMode, setStreamingToolUses, (tombstonedMessage) => { - setMessages((oldMessages) => oldMessages.filter((m4) => m4 !== tombstonedMessage)); - removeTranscriptMessage(tombstonedMessage.uuid); - }, setStreamingThinking, (metrics) => { - const now2 = Date.now(); - const baseline = responseLengthRef.current; - apiMetricsRef2.current.push({ - ...metrics, - firstTokenTime: now2, - lastTokenTime: now2, - responseLengthBaseline: baseline, - endResponseLength: baseline - }); - }, onStreamingText); - }, [setMessages, setResponseLength, setStreamMode, setStreamingToolUses, setStreamingThinking, onStreamingText]); - const onQueryImpl = import_react318.useCallback(async (messagesIncludingNewMessages, newMessages, abortController2, shouldQuery, additionalAllowedTools, mainLoopModelParam, effort) => { - if (shouldQuery) { - const freshClients = mergeClients(initialMcpClients, store.getState().mcp.clients); - diagnosticTracker.handleQueryStart(freshClients); - const ideClient = getConnectedIdeClient(freshClients); - if (ideClient) { - closeOpenDiffs(ideClient); - } - } - maybeMarkProjectOnboardingComplete(); - if (!titleDisabled && !sessionTitle && !agentTitle && !haikuTitleAttemptedRef.current) { - const firstUserMessage = newMessages.find((m4) => m4.type === "user" && !m4.isMeta); - const text = firstUserMessage?.type === "user" ? getContentText(firstUserMessage.message.content) : null; - if (text && !text.startsWith(`<${LOCAL_COMMAND_STDOUT_TAG}>`) && !text.startsWith(`<${COMMAND_MESSAGE_TAG}>`) && !text.startsWith(`<${COMMAND_NAME_TAG}>`) && !text.startsWith(`<${BASH_INPUT_TAG}>`)) { - haikuTitleAttemptedRef.current = true; - generateSessionTitle(text, new AbortController().signal).then((title) => { - if (title) - setHaikuTitle(title); - else - haikuTitleAttemptedRef.current = false; - }, () => { - haikuTitleAttemptedRef.current = false; - }); - } - } - store.setState((prev) => { - const cur = prev.toolPermissionContext.alwaysAllowRules.command; - if (cur === additionalAllowedTools || cur?.length === additionalAllowedTools.length && cur.every((v6, i6) => v6 === additionalAllowedTools[i6])) { - return prev; - } - return { - ...prev, - toolPermissionContext: { - ...prev.toolPermissionContext, - alwaysAllowRules: { - ...prev.toolPermissionContext.alwaysAllowRules, - command: additionalAllowedTools - } - } - }; - }); - if (!shouldQuery) { - if (newMessages.some(isCompactBoundaryMessage)) { - setConversationId(randomUUID49()); - if (false) {} - } - resetLoadingState(); - setAbortController(null); - return; - } - const toolUseContext = getToolUseContext(messagesIncludingNewMessages, newMessages, abortController2, mainLoopModelParam); - const { - tools: freshTools, - mcpClients: freshMcpClients - } = toolUseContext.options; - if (effort !== undefined) { - const previousGetAppState = toolUseContext.getAppState; - toolUseContext.getAppState = () => ({ - ...previousGetAppState(), - effortValue: effort - }); - } - queryCheckpoint("query_context_loading_start"); - const [, , defaultSystemPrompt, baseUserContext, systemContext] = await Promise.all([ - checkAndDisableBypassPermissionsIfNeeded(toolPermissionContext, setAppState), - undefined, - getSystemPrompt(freshTools, mainLoopModelParam, Array.from(toolPermissionContext.additionalWorkingDirectories.keys()), freshMcpClients), - getUserContext(), - getSystemContext() - ]); - const userContext = { - ...baseUserContext, - ...getCoordinatorUserContext(freshMcpClients, isScratchpadEnabled() ? getScratchpadDir() : undefined), - ...{} - }; - queryCheckpoint("query_context_loading_end"); - const systemPrompt = buildEffectiveSystemPrompt({ - mainThreadAgentDefinition, - toolUseContext, - customSystemPrompt, - defaultSystemPrompt, - appendSystemPrompt - }); - toolUseContext.renderedSystemPrompt = systemPrompt; - queryCheckpoint("query_query_start"); - resetTurnHookDuration(); - resetTurnToolDuration(); - resetTurnClassifierDuration(); - for await (const event of query({ - messages: messagesIncludingNewMessages, - systemPrompt, - userContext, - systemContext, - canUseTool, - toolUseContext, - querySource: getQuerySourceForREPL() - })) { - onQueryEvent(event); - } - if (false) {} - queryCheckpoint("query_end"); - if (false) {} - resetLoadingState(); - logQueryProfileReport(); - await onTurnComplete?.(messagesRef.current); - }, [initialMcpClients, resetLoadingState, getToolUseContext, toolPermissionContext, setAppState, customSystemPrompt, onTurnComplete, appendSystemPrompt, canUseTool, mainThreadAgentDefinition, onQueryEvent, sessionTitle, titleDisabled]); - const onQuery = import_react318.useCallback(async (newMessages, abortController2, shouldQuery, additionalAllowedTools, mainLoopModelParam, onBeforeQueryCallback, input, effort) => { - if (isAgentSwarmsEnabled()) { - const teamName = getTeamName(); - const agentName = getAgentName(); - if (teamName && agentName) { - setMemberActive(teamName, agentName, true); - } - } - const thisGeneration = queryGuard.tryStart(); - if (thisGeneration === null) { - logEvent("tengu_concurrent_onquery_detected", {}); - newMessages.filter((m4) => m4.type === "user" && !m4.isMeta).map((_) => getContentText(_.message.content)).filter((_) => _ !== null).forEach((msg, i6) => { - enqueue({ - value: msg, - mode: "prompt" - }); - if (i6 === 0) { - logEvent("tengu_concurrent_onquery_enqueued", {}); - } - }); - return; - } - try { - resetTimingRefs(); - setMessages((oldMessages) => [...oldMessages, ...newMessages]); - responseLengthRef.current = 0; - if (false) {} - apiMetricsRef2.current = []; - setStreamingToolUses([]); - setStreamingText(null); - const latestMessages = messagesRef.current; - if (input) { - await mrOnBeforeQuery(input, latestMessages, newMessages.length); - } - if (onBeforeQueryCallback && input) { - const shouldProceed = await onBeforeQueryCallback(input, latestMessages); - if (!shouldProceed) { - return; - } - } - await onQueryImpl(latestMessages, newMessages, abortController2, shouldQuery, additionalAllowedTools, mainLoopModelParam, effort); - } finally { - if (queryGuard.end(thisGeneration)) { - setLastQueryCompletionTime(Date.now()); - skipIdleCheckRef.current = false; - resetLoadingState(); - await mrOnTurnComplete(messagesRef.current, abortController2.signal.aborted); - sendBridgeResultRef.current(); - if (false) {} - let budgetInfo; - if (false) {} - const turnDurationMs = Date.now() - loadingStartTimeRef.current - totalPausedMsRef.current; - if ((turnDurationMs > 30000 || budgetInfo !== undefined) && !abortController2.signal.aborted && !proactiveActive) { - const hasRunningSwarmAgents = getAllInProcessTeammateTasks(store.getState().tasks).some((t4) => t4.status === "running"); - if (hasRunningSwarmAgents) { - if (swarmStartTimeRef.current === null) { - swarmStartTimeRef.current = loadingStartTimeRef.current; - } - if (budgetInfo) { - swarmBudgetInfoRef.current = budgetInfo; - } - } else { - setMessages((prev) => [...prev, createTurnDurationMessage(turnDurationMs, budgetInfo, count2(prev, isLoggableMessage))]); - } - } - setAbortController(null); - } - if (abortController2.signal.reason === "user-cancel" && !queryGuard.isActive && inputValueRef.current === "" && getCommandQueueLength() === 0 && !store.getState().viewingAgentTaskId) { - const msgs = messagesRef.current; - const lastUserMsg = msgs.findLast(selectableUserMessagesFilter); - if (lastUserMsg) { - const idx = msgs.lastIndexOf(lastUserMsg); - if (messagesAfterAreOnlySynthetic(msgs, idx)) { - removeLastFromHistory(); - restoreMessageSyncRef.current(lastUserMsg); - } - } - } - } - }, [onQueryImpl, setAppState, resetLoadingState, queryGuard, mrOnBeforeQuery, mrOnTurnComplete]); - const initialMessageRef = import_react318.useRef(false); - import_react318.useEffect(() => { - const pending = initialMessage; - if (!pending || isLoading || initialMessageRef.current) - return; - initialMessageRef.current = true; - async function processInitialMessage(initialMsg) { - if (initialMsg.clearContext) { - const oldPlanSlug = initialMsg.message.planContent ? getPlanSlug() : undefined; - const { - clearConversation: clearConversation2 - } = await Promise.resolve().then(() => (init_conversation(), exports_conversation)); - await clearConversation2({ - setMessages, - readFileState: readFileState.current, - discoveredSkillNames: discoveredSkillNamesRef.current, - loadedNestedMemoryPaths: loadedNestedMemoryPathsRef.current, - getAppState: () => store.getState(), - setAppState, - setConversationId - }); - haikuTitleAttemptedRef.current = false; - setHaikuTitle(undefined); - bashTools.current.clear(); - bashToolsProcessedIdx.current = 0; - if (oldPlanSlug) { - setPlanSlug(getSessionId(), oldPlanSlug); - } - } - const shouldStorePlanForVerification = initialMsg.message.planContent && false; - setAppState((prev) => { - let updatedToolPermissionContext = initialMsg.mode ? applyPermissionUpdates(prev.toolPermissionContext, buildPermissionUpdates(initialMsg.mode, initialMsg.allowedPrompts)) : prev.toolPermissionContext; - if (false) {} - return { - ...prev, - initialMessage: null, - toolPermissionContext: updatedToolPermissionContext, - ...shouldStorePlanForVerification && { - pendingPlanVerification: { - plan: initialMsg.message.planContent, - verificationStarted: false, - verificationCompleted: false - } - } - }; - }); - if (fileHistoryEnabled()) { - fileHistoryMakeSnapshot((updater) => { - setAppState((prev) => ({ - ...prev, - fileHistory: updater(prev.fileHistory) - })); - }, initialMsg.message.uuid); - } - await awaitPendingHooks(); - const content = initialMsg.message.message.content; - if (typeof content === "string" && !initialMsg.message.planContent) { - onSubmit(content, { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }); - } else { - const newAbortController = createAbortController(); - setAbortController(newAbortController); - onQuery([initialMsg.message], newAbortController, true, [], mainLoopModel); - } - setTimeout((ref) => { - ref.current = false; - }, 100, initialMessageRef); - } - processInitialMessage(pending); - }, [initialMessage, isLoading, setMessages, setAppState, onQuery, mainLoopModel, tools]); - const onSubmit = import_react318.useCallback(async (input, helpers3, speculationAccept, options2) => { - repinScroll(); - if (false) {} - if (!speculationAccept && input.trim().startsWith("/")) { - const trimmedInput = expandPastedTextRefs(input, pastedContents).trim(); - const spaceIndex = trimmedInput.indexOf(" "); - const commandName = spaceIndex === -1 ? trimmedInput.slice(1) : trimmedInput.slice(1, spaceIndex); - const commandArgs = spaceIndex === -1 ? "" : trimmedInput.slice(spaceIndex + 1).trim(); - const matchingCommand = commands7.find((cmd) => isCommandEnabled(cmd) && (cmd.name === commandName || cmd.aliases?.includes(commandName) || getCommandName(cmd) === commandName)); - if (matchingCommand?.name === "clear" && idleHintShownRef.current) { - logEvent("tengu_idle_return_action", { - action: "hint_converted", - variant: idleHintShownRef.current, - idleMinutes: Math.round((Date.now() - lastQueryCompletionTimeRef.current) / 60000), - messageCount: messagesRef.current.length, - totalInputTokens: getTotalInputTokens() - }); - idleHintShownRef.current = false; - } - const shouldTreatAsImmediate = queryGuard.isActive && (matchingCommand?.immediate || options2?.fromKeybinding); - if (matchingCommand && shouldTreatAsImmediate && matchingCommand.type === "local-jsx") { - if (input.trim() === inputValueRef.current.trim()) { - setInputValue(""); - helpers3.setCursorOffset(0); - helpers3.clearBuffer(); - setPastedContents({}); - } - const pastedTextRefs = parseReferences(input).filter((r4) => pastedContents[r4.id]?.type === "text"); - const pastedTextCount = pastedTextRefs.length; - const pastedTextBytes = pastedTextRefs.reduce((sum, r4) => sum + (pastedContents[r4.id]?.content.length ?? 0), 0); - logEvent("tengu_paste_text", { - pastedTextCount, - pastedTextBytes - }); - logEvent("tengu_immediate_command_executed", { - commandName: matchingCommand.name, - fromKeybinding: options2?.fromKeybinding ?? false - }); - const executeImmediateCommand = async () => { - let doneWasCalled = false; - const onDone = (result, doneOptions) => { - doneWasCalled = true; - setToolJSX({ - jsx: null, - shouldHidePromptInput: false, - clearLocalJSX: true - }); - const newMessages = []; - if (result && doneOptions?.display !== "skip") { - addNotification({ - key: `immediate-${matchingCommand.name}`, - text: result, - priority: "immediate" - }); - if (!isFullscreenEnvEnabled()) { - newMessages.push(createCommandInputMessage(formatCommandInputTags(getCommandName(matchingCommand), commandArgs)), createCommandInputMessage(`<${LOCAL_COMMAND_STDOUT_TAG}>${escapeXml(result)}`)); - } - } - if (doneOptions?.metaMessages?.length) { - newMessages.push(...doneOptions.metaMessages.map((content) => createUserMessage({ - content, - isMeta: true - }))); - } - if (newMessages.length) { - setMessages((prev) => [...prev, ...newMessages]); - } - if (stashedPrompt !== undefined) { - setInputValue(stashedPrompt.text); - helpers3.setCursorOffset(stashedPrompt.cursorOffset); - setPastedContents(stashedPrompt.pastedContents); - setStashedPrompt(undefined); - } - }; - const context7 = getToolUseContext(messagesRef.current, [], createAbortController(), mainLoopModel); - const mod2 = await matchingCommand.load(); - const jsx = await mod2.call(onDone, context7, commandArgs); - if (jsx && !doneWasCalled) { - setToolJSX({ - jsx, - shouldHidePromptInput: false, - isLocalJSXCommand: true - }); - } - }; - executeImmediateCommand(); - return; - } - } - if (activeRemote.isRemoteMode && !input.trim()) { - return; - } - { - const willowMode = getFeatureValue_CACHED_MAY_BE_STALE("tengu_willow_mode", "off"); - const idleThresholdMin = Number(process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES ?? 75); - const tokenThreshold = Number(process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD ?? 1e5); - if (willowMode !== "off" && !getGlobalConfig().idleReturnDismissed && !skipIdleCheckRef.current && !speculationAccept && !input.trim().startsWith("/") && lastQueryCompletionTimeRef.current > 0 && getTotalInputTokens() >= tokenThreshold) { - const idleMs = Date.now() - lastQueryCompletionTimeRef.current; - const idleMinutes = idleMs / 60000; - if (idleMinutes >= idleThresholdMin && willowMode === "dialog") { - setIdleReturnPending({ - input, - idleMinutes - }); - setInputValue(""); - helpers3.setCursorOffset(0); - helpers3.clearBuffer(); - return; - } - } - } - if (!options2?.fromKeybinding) { - addToHistory({ - display: speculationAccept ? input : prependModeCharacterToInput(input, inputMode), - pastedContents: speculationAccept ? {} : pastedContents - }); - if (inputMode === "bash") { - prependToShellHistoryCache(input.trim()); - } - } - const isSlashCommand3 = !speculationAccept && input.trim().startsWith("/"); - const submitsNow = !isLoading || speculationAccept || activeRemote.isRemoteMode; - if (stashedPrompt !== undefined && !isSlashCommand3 && submitsNow) { - setInputValue(stashedPrompt.text); - helpers3.setCursorOffset(stashedPrompt.cursorOffset); - setPastedContents(stashedPrompt.pastedContents); - setStashedPrompt(undefined); - } else if (submitsNow) { - if (!options2?.fromKeybinding) { - setInputValue(""); - helpers3.setCursorOffset(0); - } - setPastedContents({}); - } - if (submitsNow) { - setInputMode("prompt"); - setIDESelection(undefined); - setSubmitCount((_) => _ + 1); - helpers3.clearBuffer(); - tipPickedThisTurnRef.current = false; - if (!isSlashCommand3 && inputMode === "prompt" && !speculationAccept && !activeRemote.isRemoteMode) { - setUserInputOnProcessing(input); - resetTimingRefs(); - } - if (false) {} - } - if (speculationAccept) { - const { - queryRequired - } = await handleSpeculationAccept(speculationAccept.state, speculationAccept.speculationSessionTimeSavedMs, speculationAccept.setAppState, input, { - setMessages, - readFileState, - cwd: getOriginalCwd() - }); - if (queryRequired) { - const newAbortController = createAbortController(); - setAbortController(newAbortController); - onQuery([], newAbortController, true, [], mainLoopModel); - } - return; - } - if (activeRemote.isRemoteMode && !(isSlashCommand3 && commands7.find((c9) => { - const name3 = input.trim().slice(1).split(/\s/)[0]; - return isCommandEnabled(c9) && (c9.name === name3 || c9.aliases?.includes(name3) || getCommandName(c9) === name3); - })?.type === "local-jsx")) { - const pastedValues = Object.values(pastedContents); - const imageContents = pastedValues.filter((c9) => c9.type === "image"); - const imagePasteIds = imageContents.length > 0 ? imageContents.map((c9) => c9.id) : undefined; - let messageContent = input.trim(); - let remoteContent = input.trim(); - if (pastedValues.length > 0) { - const contentBlocks = []; - const remoteBlocks = []; - const trimmedInput = input.trim(); - if (trimmedInput) { - contentBlocks.push({ - type: "text", - text: trimmedInput - }); - remoteBlocks.push({ - type: "text", - text: trimmedInput - }); - } - for (const pasted of pastedValues) { - if (pasted.type === "image") { - const source = { - type: "base64", - media_type: pasted.mediaType ?? "image/png", - data: pasted.content - }; - contentBlocks.push({ - type: "image", - source - }); - remoteBlocks.push({ - type: "image", - source - }); - } else { - contentBlocks.push({ - type: "text", - text: pasted.content - }); - remoteBlocks.push({ - type: "text", - text: pasted.content - }); - } - } - messageContent = contentBlocks; - remoteContent = remoteBlocks; - } - const userMessage = createUserMessage({ - content: messageContent, - imagePasteIds - }); - setMessages((prev) => [...prev, userMessage]); - await activeRemote.sendMessage(remoteContent, { - uuid: userMessage.uuid - }); - return; - } - await awaitPendingHooks(); - await handlePromptSubmit({ - input, - helpers: helpers3, - queryGuard, - isExternalLoading, - mode: inputMode, - commands: commands7, - onInputChange: setInputValue, - setPastedContents, - setToolJSX, - getToolUseContext, - messages: messagesRef.current, - mainLoopModel, - pastedContents, - ideSelection, - setUserInputOnProcessing, - setAbortController, - abortController, - onQuery, - setAppState, - querySource: getQuerySourceForREPL(), - onBeforeQuery, - canUseTool, - addNotification, - setMessages, - streamMode: streamModeRef.current, - hasInterruptibleToolInProgress: hasInterruptibleToolInProgressRef.current - }); - if ((isSlashCommand3 || isLoading) && stashedPrompt !== undefined) { - setInputValue(stashedPrompt.text); - helpers3.setCursorOffset(stashedPrompt.cursorOffset); - setPastedContents(stashedPrompt.pastedContents); - setStashedPrompt(undefined); - } - }, [ - queryGuard, - isLoading, - isExternalLoading, - inputMode, - commands7, - setInputValue, - setInputMode, - setPastedContents, - setSubmitCount, - setIDESelection, - setToolJSX, - getToolUseContext, - mainLoopModel, - pastedContents, - ideSelection, - setUserInputOnProcessing, - setAbortController, - addNotification, - onQuery, - stashedPrompt, - setStashedPrompt, - setAppState, - onBeforeQuery, - canUseTool, - remoteSession, - setMessages, - awaitPendingHooks, - repinScroll - ]); - const onAgentSubmit = import_react318.useCallback(async (input, task, helpers3) => { - if (isLocalAgentTask(task)) { - appendMessageToLocalAgent(task.id, createUserMessage({ - content: input - }), setAppState); - if (task.status === "running") { - queuePendingMessage(task.id, input, setAppState); - } else { - resumeAgentBackground({ - agentId: task.id, - prompt: input, - toolUseContext: getToolUseContext(messagesRef.current, [], new AbortController, mainLoopModel), - canUseTool - }).catch((err2) => { - logForDebugging(`resumeAgentBackground failed: ${errorMessage(err2)}`); - addNotification({ - key: `resume-agent-failed-${task.id}`, - jsx: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - color: "error", - children: [ - "Failed to resume agent: ", - errorMessage(err2) - ] - }, undefined, true, undefined, this), - priority: "low" - }); - }); - } - } else { - injectUserMessageToTeammate(task.id, input, setAppState); - } - setInputValue(""); - helpers3.setCursorOffset(0); - helpers3.clearBuffer(); - }, [setAppState, setInputValue, getToolUseContext, canUseTool, mainLoopModel, addNotification]); - const handleAutoRunIssue = import_react318.useCallback(() => { - const command19 = autoRunIssueReason ? getAutoRunCommand(autoRunIssueReason) : "/issue"; - setAutoRunIssueReason(null); - onSubmit(command19, { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }).catch((err2) => { - logForDebugging(`Auto-run ${command19} failed: ${errorMessage(err2)}`); - }); - }, [onSubmit, autoRunIssueReason]); - const handleCancelAutoRunIssue = import_react318.useCallback(() => { - setAutoRunIssueReason(null); - }, []); - const handleSurveyRequestFeedback = import_react318.useCallback(() => { - const command19 = "/feedback"; - onSubmit(command19, { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }).catch((err2) => { - logForDebugging(`Survey feedback request failed: ${err2 instanceof Error ? err2.message : String(err2)}`); - }); - }, [onSubmit]); - const onSubmitRef = import_react318.useRef(onSubmit); - onSubmitRef.current = onSubmit; - const handleOpenRateLimitOptions = import_react318.useCallback(() => { - onSubmitRef.current("/rate-limit-options", { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }); - }, []); - const handleExit = import_react318.useCallback(async () => { - setIsExiting(true); - if (false) {} - const showWorktree = getCurrentWorktreeSession() !== null; - if (showWorktree) { - setExitFlow(/* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ExitFlow, { - showWorktree: true, - onDone: () => {}, - onCancel: () => { - setExitFlow(null); - setIsExiting(false); - } - }, undefined, false, undefined, this)); - return; - } - const exitMod = await exit_default.load(); - const exitFlowResult = await exitMod.call(() => {}); - setExitFlow(exitFlowResult); - if (exitFlowResult === null) { - setIsExiting(false); - } - }, []); - const handleShowMessageSelector = import_react318.useCallback(() => { - setIsMessageSelectorVisible((prev) => !prev); - }, []); - const rewindConversationTo = import_react318.useCallback((message) => { - const prev = messagesRef.current; - const messageIndex = prev.lastIndexOf(message); - if (messageIndex === -1) - return; - logEvent("tengu_conversation_rewind", { - preRewindMessageCount: prev.length, - postRewindMessageCount: messageIndex, - messagesRemoved: prev.length - messageIndex, - rewindToMessageIndex: messageIndex - }); - setMessages(prev.slice(0, messageIndex)); - setConversationId(randomUUID49()); - resetMicrocompactState(); - if (false) {} - setAppState((prev2) => ({ - ...prev2, - toolPermissionContext: message.permissionMode && prev2.toolPermissionContext.mode !== message.permissionMode ? { - ...prev2.toolPermissionContext, - mode: message.permissionMode - } : prev2.toolPermissionContext, - promptSuggestion: { - text: null, - promptId: null, - shownAt: 0, - acceptedAt: 0, - generationRequestId: null - } - })); - }, [setMessages, setAppState]); - const restoreMessageSync = import_react318.useCallback((message) => { - rewindConversationTo(message); - const r4 = textForResubmit(message); - if (r4) { - setInputValue(r4.text); - setInputMode(r4.mode); - } - if (Array.isArray(message.message.content) && message.message.content.some((block2) => block2.type === "image")) { - const imageBlocks = message.message.content.filter((block2) => block2.type === "image"); - if (imageBlocks.length > 0) { - const newPastedContents = {}; - imageBlocks.forEach((block2, index2) => { - if (block2.source.type === "base64") { - const id = message.imagePasteIds?.[index2] ?? index2 + 1; - newPastedContents[id] = { - id, - type: "image", - content: block2.source.data, - mediaType: block2.source.media_type - }; - } - }); - setPastedContents(newPastedContents); - } - } - }, [rewindConversationTo, setInputValue]); - restoreMessageSyncRef.current = restoreMessageSync; - const handleRestoreMessage = import_react318.useCallback(async (message) => { - setImmediate((restore, message2) => restore(message2), restoreMessageSync, message); - }, [restoreMessageSync]); - const findRawIndex = (uuid8) => { - const prefix = uuid8.slice(0, 24); - return messages.findIndex((m4) => m4.uuid.slice(0, 24) === prefix); - }; - const messageActionCaps = { - copy: (text) => void setClipboard(text).then((raw) => { - if (raw) - process.stdout.write(raw); - addNotification({ - key: "selection-copied", - text: "copied", - color: "success", - priority: "immediate", - timeoutMs: 2000 - }); - }), - edit: async (msg) => { - const rawIdx = findRawIndex(msg.uuid); - const raw = rawIdx >= 0 ? messages[rawIdx] : undefined; - if (!raw || !selectableUserMessagesFilter(raw)) - return; - const noFileChanges = !await fileHistoryHasAnyChanges(fileHistory, raw.uuid); - const onlySynthetic = messagesAfterAreOnlySynthetic(messages, rawIdx); - if (noFileChanges && onlySynthetic) { - onCancel(); - handleRestoreMessage(raw); - } else { - setMessageSelectorPreselect(raw); - setIsMessageSelectorVisible(true); - } - } - }; - const { - enter: enterMessageActions, - handlers: messageActionHandlers - } = useMessageActions(cursor, setCursor, cursorNavRef, messageActionCaps); - async function onInit() { - reverify(); - const memoryFiles = await getMemoryFiles(); - if (memoryFiles.length > 0) { - const fileList = memoryFiles.map((f4) => ` [${f4.type}] ${f4.path} (${f4.content.length} chars)${f4.parent ? ` (included by ${f4.parent})` : ""}`).join(` -`); - logForDebugging(`Loaded ${memoryFiles.length} CLAUDE.md/rules files: -${fileList}`); - } else { - logForDebugging("No CLAUDE.md/rules files found"); - } - for (const file2 of memoryFiles) { - readFileState.current.set(file2.path, { - content: file2.contentDiffersFromDisk ? file2.rawContent ?? file2.content : file2.content, - timestamp: Date.now(), - offset: undefined, - limit: undefined, - isPartialView: file2.contentDiffersFromDisk - }); - } - } - useCostSummary(useFpsMetrics()); - useLogMessages(messages, messages.length === initialMessages?.length); - const { - sendBridgeResult - } = useReplBridge(messages, setMessages, abortControllerRef, commands7, mainLoopModel); - sendBridgeResultRef.current = sendBridgeResult; - useAfterFirstRender(); - const hasCountedQueueUseRef = import_react318.useRef(false); - import_react318.useEffect(() => { - if (queuedCommands.length < 1) { - hasCountedQueueUseRef.current = false; - return; - } - if (hasCountedQueueUseRef.current) - return; - hasCountedQueueUseRef.current = true; - saveGlobalConfig((current) => ({ - ...current, - promptQueueUseCount: (current.promptQueueUseCount ?? 0) + 1 - })); - }, [queuedCommands.length]); - const executeQueuedInput = import_react318.useCallback(async (queuedCommands2) => { - await handlePromptSubmit({ - helpers: { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }, - queryGuard, - commands: commands7, - onInputChange: () => {}, - setPastedContents: () => {}, - setToolJSX, - getToolUseContext, - messages, - mainLoopModel, - ideSelection, - setUserInputOnProcessing, - setAbortController, - onQuery, - setAppState, - querySource: getQuerySourceForREPL(), - onBeforeQuery, - canUseTool, - addNotification, - setMessages, - queuedCommands: queuedCommands2 - }); - }, [queryGuard, commands7, setToolJSX, getToolUseContext, messages, mainLoopModel, ideSelection, setUserInputOnProcessing, canUseTool, setAbortController, onQuery, addNotification, setAppState, onBeforeQuery]); - useQueueProcessor({ - executeQueuedInput, - hasActiveLocalJsxUI: isShowingLocalJSXCommand, - queryGuard - }); - import_react318.useEffect(() => { - activityManager.recordUserActivity(); - updateLastInteractionTime(true); - }, [inputValue, submitCount]); - import_react318.useEffect(() => { - if (submitCount === 1) { - startBackgroundHousekeeping(); - } - }, [submitCount]); - import_react318.useEffect(() => { - if (isLoading) - return; - if (submitCount === 0) - return; - if (lastQueryCompletionTime === 0) - return; - const timer = setTimeout((lastQueryCompletionTime2, isLoading2, toolJSX2, focusedInputDialogRef2, terminal2) => { - const lastUserInteraction = getLastInteractionTime(); - if (lastUserInteraction > lastQueryCompletionTime2) { - return; - } - const idleTimeSinceResponse = Date.now() - lastQueryCompletionTime2; - if (!isLoading2 && !toolJSX2 && focusedInputDialogRef2.current === undefined && idleTimeSinceResponse >= getGlobalConfig().messageIdleNotifThresholdMs) { - sendNotification({ - message: "Claude is waiting for your input", - notificationType: "idle_prompt" - }, terminal2); - } - }, getGlobalConfig().messageIdleNotifThresholdMs, lastQueryCompletionTime, isLoading, toolJSX, focusedInputDialogRef, terminal); - return () => clearTimeout(timer); - }, [isLoading, toolJSX, submitCount, lastQueryCompletionTime, terminal]); - import_react318.useEffect(() => { - if (lastQueryCompletionTime === 0) - return; - if (isLoading) - return; - const willowMode = getFeatureValue_CACHED_MAY_BE_STALE("tengu_willow_mode", "off"); - if (willowMode !== "hint" && willowMode !== "hint_v2") - return; - if (getGlobalConfig().idleReturnDismissed) - return; - const tokenThreshold = Number(process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD ?? 1e5); - if (getTotalInputTokens() < tokenThreshold) - return; - const idleThresholdMs = Number(process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES ?? 75) * 60000; - const elapsed = Date.now() - lastQueryCompletionTime; - const remaining = idleThresholdMs - elapsed; - const timer = setTimeout((lqct, addNotif, msgsRef, mode, hintRef) => { - if (msgsRef.current.length === 0) - return; - const totalTokens = getTotalInputTokens(); - const formattedTokens = formatTokens(totalTokens); - const idleMinutes = (Date.now() - lqct) / 60000; - addNotif({ - key: "idle-return-hint", - jsx: mode === "hint_v2" ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: "new task? " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - color: "suggestion", - children: "/clear" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - dimColor: true, - children: " to save " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - color: "suggestion", - children: [ - formattedTokens, - " tokens" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedText, { - color: "warning", - children: [ - "new task? /clear to save ", - formattedTokens, - " tokens" - ] - }, undefined, true, undefined, this), - priority: "medium", - timeoutMs: 2147483647 - }); - hintRef.current = mode; - logEvent("tengu_idle_return_action", { - action: "hint_shown", - variant: mode, - idleMinutes: Math.round(idleMinutes), - messageCount: msgsRef.current.length, - totalInputTokens: totalTokens - }); - }, Math.max(0, remaining), lastQueryCompletionTime, addNotification, messagesRef, willowMode, idleHintShownRef); - return () => { - clearTimeout(timer); - removeNotification("idle-return-hint"); - idleHintShownRef.current = false; - }; - }, [lastQueryCompletionTime, isLoading, addNotification, removeNotification]); - const handleIncomingPrompt = import_react318.useCallback((content, options2) => { - if (queryGuard.isActive) - return false; - if (getCommandQueue().some((cmd) => cmd.mode === "prompt" || cmd.mode === "bash")) { - return false; - } - const newAbortController = createAbortController(); - setAbortController(newAbortController); - const userMessage = createUserMessage({ - content, - isMeta: options2?.isMeta ? true : undefined - }); - onQuery([userMessage], newAbortController, true, [], mainLoopModel); - return true; - }, [onQuery, mainLoopModel, store]); - const voice = { - stripTrailing: () => 0, - handleKeyEvent: () => {}, - resetAnchor: () => {}, - interimRange: null - }; - useInboxPoller({ - enabled: isAgentSwarmsEnabled(), - isLoading, - focusedInputDialog, - onSubmitMessage: handleIncomingPrompt - }); - useMailboxBridge({ - isLoading, - onSubmitMessage: handleIncomingPrompt - }); - if (false) {} - if (false) {} - import_react318.useEffect(() => { - if (queuedCommands.some((cmd) => cmd.priority === "now")) { - abortControllerRef.current?.abort("interrupt"); - } - }, [queuedCommands]); - import_react318.useEffect(() => { - onInit(); - return () => { - diagnosticTracker.shutdown(); - }; - }, []); - const { - internal_eventEmitter - } = use_stdin_default(); - const [remountKey, setRemountKey] = import_react318.useState(0); - import_react318.useEffect(() => { - const handleSuspend = () => { - process.stdout.write(` -Claude Code has been suspended. Run \`fg\` to bring Claude Code back. -Note: ctrl + z now suspends Claude Code, ctrl + _ undoes input. -`); - }; - const handleResume = () => { - setRemountKey((prev) => prev + 1); - }; - internal_eventEmitter?.on("suspend", handleSuspend); - internal_eventEmitter?.on("resume", handleResume); - return () => { - internal_eventEmitter?.off("suspend", handleSuspend); - internal_eventEmitter?.off("resume", handleResume); - }; - }, [internal_eventEmitter]); - const stopHookSpinnerSuffix = import_react318.useMemo(() => { - if (!isLoading) - return null; - const progressMsgs = messages.filter((m4) => m4.type === "progress" && m4.data.type === "hook_progress" && (m4.data.hookEvent === "Stop" || m4.data.hookEvent === "SubagentStop")); - if (progressMsgs.length === 0) - return null; - const currentToolUseID = progressMsgs.at(-1)?.toolUseID; - if (!currentToolUseID) - return null; - const hasSummaryForCurrentExecution = messages.some((m4) => m4.type === "system" && m4.subtype === "stop_hook_summary" && m4.toolUseID === currentToolUseID); - if (hasSummaryForCurrentExecution) - return null; - const currentHooks = progressMsgs.filter((p4) => p4.toolUseID === currentToolUseID); - const total = currentHooks.length; - const completedCount = count2(messages, (m4) => { - if (m4.type !== "attachment") - return false; - const attachment = m4.attachment; - return "hookEvent" in attachment && (attachment.hookEvent === "Stop" || attachment.hookEvent === "SubagentStop") && "toolUseID" in attachment && attachment.toolUseID === currentToolUseID; - }); - const customMessage = currentHooks.find((p4) => p4.data.statusMessage)?.data.statusMessage; - if (customMessage) { - return total === 1 ? `${customMessage}\u2026` : `${customMessage}\u2026 ${completedCount}/${total}`; - } - const hookType = currentHooks[0]?.data.hookEvent === "SubagentStop" ? "subagent stop" : "stop"; - if (false) {} - return total === 1 ? `running ${hookType} hook` : `running stop hooks\u2026 ${completedCount}/${total}`; - }, [messages, isLoading]); - const handleEnterTranscript = import_react318.useCallback(() => { - setFrozenTranscriptState({ - messagesLength: messages.length, - streamingToolUsesLength: streamingToolUses.length - }); - }, [messages.length, streamingToolUses.length]); - const handleExitTranscript = import_react318.useCallback(() => { - setFrozenTranscriptState(null); - }, []); - const virtualScrollActive = isFullscreenEnvEnabled() && !disableVirtualScroll; - const jumpRef = import_react318.useRef(null); - const [searchOpen, setSearchOpen] = import_react318.useState(false); - const [searchQuery, setSearchQuery] = import_react318.useState(""); - const [searchCount, setSearchCount] = import_react318.useState(0); - const [searchCurrent, setSearchCurrent] = import_react318.useState(0); - const onSearchMatchesChange = import_react318.useCallback((count4, current) => { - setSearchCount(count4); - setSearchCurrent(current); - }, []); - use_input_default((input, key2, event) => { - if (key2.ctrl || key2.meta) - return; - if (input === "/") { - jumpRef.current?.setAnchor(); - setSearchOpen(true); - event.stopImmediatePropagation(); - return; - } - const c9 = input[0]; - if ((c9 === "n" || c9 === "N") && input === c9.repeat(input.length) && searchCount > 0) { - const fn = c9 === "n" ? jumpRef.current?.nextMatch : jumpRef.current?.prevMatch; - if (fn) - for (let i6 = 0;i6 < input.length; i6++) - fn(); - event.stopImmediatePropagation(); - } - }, { - isActive: screen === "transcript" && virtualScrollActive && !searchOpen && !dumpMode - }); - const { - setQuery: setHighlight, - scanElement, - setPositions - } = useSearchHighlight(); - const transcriptCols = useTerminalSize().columns; - const prevColsRef = React156.useRef(transcriptCols); - React156.useEffect(() => { - if (prevColsRef.current !== transcriptCols) { - prevColsRef.current = transcriptCols; - if (searchQuery || searchOpen) { - setSearchOpen(false); - setSearchQuery(""); - setSearchCount(0); - setSearchCurrent(0); - jumpRef.current?.disarmSearch(); - setHighlight(""); - } - } - }, [transcriptCols, searchQuery, searchOpen, setHighlight]); - use_input_default((input, key2, event) => { - if (key2.ctrl || key2.meta) - return; - if (input === "q") { - handleExitTranscript(); - event.stopImmediatePropagation(); - return; - } - if (input === "[" && !dumpMode) { - setDumpMode(true); - setShowAllInTranscript(true); - event.stopImmediatePropagation(); - } else if (input === "v") { - event.stopImmediatePropagation(); - if (editorRenderingRef.current) - return; - editorRenderingRef.current = true; - const gen = editorGenRef.current; - const setStatus = (s4) => { - if (gen !== editorGenRef.current) - return; - clearTimeout(editorTimerRef.current); - setEditorStatus(s4); - }; - setStatus(`rendering ${deferredMessages.length} messages\u2026`); - (async () => { - try { - const w2 = Math.max(80, (process.stdout.columns ?? 80) - 6); - const raw = await renderMessagesToPlainText(deferredMessages, tools, w2); - const text = raw.replace(/[ \t]+$/gm, ""); - const path27 = join149(tmpdir13(), `cc-transcript-${Date.now()}.txt`); - await writeFile47(path27, text); - const opened = openFileInExternalEditor(path27); - setStatus(opened ? `opening ${path27}` : `wrote ${path27} \xB7 no $VISUAL/$EDITOR set`); - } catch (e4) { - setStatus(`render failed: ${e4 instanceof Error ? e4.message : String(e4)}`); - } - editorRenderingRef.current = false; - if (gen !== editorGenRef.current) - return; - editorTimerRef.current = setTimeout((s4) => s4(""), 4000, setEditorStatus); - })(); - } - }, { - isActive: screen === "transcript" && virtualScrollActive && !searchOpen - }); - const inTranscript = screen === "transcript" && virtualScrollActive; - import_react318.useEffect(() => { - if (!inTranscript) { - setSearchQuery(""); - setSearchCount(0); - setSearchCurrent(0); - setSearchOpen(false); - editorGenRef.current++; - clearTimeout(editorTimerRef.current); - setDumpMode(false); - setEditorStatus(""); - } - }, [inTranscript]); - import_react318.useEffect(() => { - setHighlight(inTranscript ? searchQuery : ""); - if (!inTranscript) - setPositions(null); - }, [inTranscript, searchQuery, setHighlight, setPositions]); - const globalKeybindingProps = { - screen, - setScreen, - showAllInTranscript, - setShowAllInTranscript, - messageCount: messages.length, - onEnterTranscript: handleEnterTranscript, - onExitTranscript: handleExitTranscript, - virtualScrollActive, - searchBarOpen: searchOpen - }; - const transcriptMessages = frozenTranscriptState ? deferredMessages.slice(0, frozenTranscriptState.messagesLength) : deferredMessages; - const transcriptStreamingToolUses = frozenTranscriptState ? streamingToolUses.slice(0, frozenTranscriptState.streamingToolUsesLength) : streamingToolUses; - useBackgroundTaskNavigation({ - onOpenBackgroundTasks: isShowingLocalJSXCommand ? undefined : () => setShowBashesDialog(true) - }); - useTeammateViewAutoExit(); - if (screen === "transcript") { - const transcriptScrollRef = isFullscreenEnvEnabled() && !disableVirtualScroll && !dumpMode ? scrollRef : undefined; - const transcriptMessagesElement = /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(Messages10, { - messages: transcriptMessages, - tools, - commands: commands7, - verbose: true, - toolJSX: null, - toolUseConfirmQueue: [], - inProgressToolUseIDs, - isMessageSelectorVisible: false, - conversationId, - screen, - agentDefinitions, - streamingToolUses: transcriptStreamingToolUses, - showAllInTranscript, - onOpenRateLimitOptions: handleOpenRateLimitOptions, - isLoading, - hidePastThinking: true, - streamingThinking, - scrollRef: transcriptScrollRef, - jumpRef, - onSearchMatchesChange, - scanElement, - setPositions, - disableRenderCap: dumpMode - }, undefined, false, undefined, this); - const transcriptToolJSX = toolJSX && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: "100%", - children: toolJSX.jsx - }, undefined, false, undefined, this); - const transcriptReturn = /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(KeybindingSetup, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(AnimatedTerminalTitle, { - isAnimating: titleIsAnimating, - title: terminalTitle, - disabled: titleDisabled, - noPrefix: showStatusInTerminalTab - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(GlobalKeybindingHandlers, { - ...globalKeybindingProps - }, undefined, false, undefined, this), - null, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(CommandKeybindingHandlers, { - onSubmit, - isActive: !toolJSX?.isLocalJSXCommand - }, undefined, false, undefined, this), - transcriptScrollRef ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ScrollKeybindingHandler, { - scrollRef, - isActive: focusedInputDialog !== "ultraplan-choice", - isModal: !searchOpen, - onScroll: () => jumpRef.current?.disarmSearch() - }, undefined, false, undefined, this) : null, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(CancelRequestHandler, { - ...cancelRequestProps - }, undefined, false, undefined, this), - transcriptScrollRef ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(FullscreenLayout, { - scrollRef, - scrollable: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - transcriptMessagesElement, - transcriptToolJSX, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(SandboxViolationExpandedView, {}, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - bottom: searchOpen ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(TranscriptSearchBar, { - jumpRef, - initialQuery: "", - count: searchCount, - current: searchCurrent, - onClose: (q4) => { - setSearchQuery(searchCount > 0 ? q4 : ""); - setSearchOpen(false); - if (!q4) { - setSearchCount(0); - setSearchCurrent(0); - jumpRef.current?.setSearchQuery(""); - } - }, - onCancel: () => { - setSearchOpen(false); - jumpRef.current?.setSearchQuery(""); - jumpRef.current?.setSearchQuery(searchQuery); - setHighlight(searchQuery); - }, - setHighlight - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(TranscriptModeFooter, { - showAllInTranscript, - virtualScroll: true, - status: editorStatus || undefined, - searchBadge: searchQuery && searchCount > 0 ? { - current: searchCurrent, - count: searchCount - } : undefined - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - transcriptMessagesElement, - transcriptToolJSX, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(SandboxViolationExpandedView, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(TranscriptModeFooter, { - showAllInTranscript, - virtualScroll: false, - suppressShowAll: dumpMode, - status: editorStatus || undefined - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - if (transcriptScrollRef) { - return /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(AlternateScreen, { - mouseTracking: isMouseTrackingEnabled(), - children: transcriptReturn - }, undefined, false, undefined, this); - } - return transcriptReturn; - } - const viewedTask = viewingAgentTaskId ? tasks2[viewingAgentTaskId] : undefined; - const viewedTeammateTask = viewedTask && isInProcessTeammateTask(viewedTask) ? viewedTask : undefined; - const viewedAgentTask = viewedTeammateTask ?? (viewedTask && isLocalAgentTask(viewedTask) ? viewedTask : undefined); - const usesSyncMessages = showStreamingText || !isLoading; - const displayedMessages = viewedAgentTask ? viewedAgentTask.messages ?? [] : usesSyncMessages ? messages : deferredMessages; - const placeholderText = userInputOnProcessing && !viewedAgentTask && displayedMessages.length <= userInputBaselineRef.current ? userInputOnProcessing : undefined; - const toolPermissionOverlay = focusedInputDialog === "tool-permission" ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(PermissionRequest, { - onDone: () => setToolUseConfirmQueue(([_, ...tail]) => tail), - onReject: handleQueuedCommandOnCancel, - toolUseConfirm: toolUseConfirmQueue[0], - toolUseContext: getToolUseContext(messages, messages, abortController ?? createAbortController(), mainLoopModel), - verbose, - workerBadge: toolUseConfirmQueue[0]?.workerBadge, - setStickyFooter: isFullscreenEnvEnabled() ? setPermissionStickyFooter : undefined - }, toolUseConfirmQueue[0]?.toolUseID, false, undefined, this) : null; - const companionNarrow = transcriptCols < MIN_COLS_FOR_FULL_SPRITE; - const companionVisible = !toolJSX?.shouldHidePromptInput && !focusedInputDialog && !showBashesDialog; - const toolJsxCentered = isFullscreenEnvEnabled() && toolJSX?.isLocalJSXCommand === true; - const centeredModal = toolJsxCentered ? toolJSX.jsx : null; - const mainReturn = /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(KeybindingSetup, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(AnimatedTerminalTitle, { - isAnimating: titleIsAnimating, - title: terminalTitle, - disabled: titleDisabled, - noPrefix: showStatusInTerminalTab - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(GlobalKeybindingHandlers, { - ...globalKeybindingProps - }, undefined, false, undefined, this), - null, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(CommandKeybindingHandlers, { - onSubmit, - isActive: !toolJSX?.isLocalJSXCommand - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ScrollKeybindingHandler, { - scrollRef, - isActive: isFullscreenEnvEnabled() && (centeredModal != null || !focusedInputDialog || focusedInputDialog === "tool-permission"), - onScroll: centeredModal || toolPermissionOverlay || viewedAgentTask ? undefined : composedOnScroll - }, undefined, false, undefined, this), - null, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(CancelRequestHandler, { - ...cancelRequestProps - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(MCPConnectionManager, { - dynamicMcpConfig, - isStrictMcpConfig: strictMcpConfig, - children: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(FullscreenLayout, { - scrollRef, - overlay: toolPermissionOverlay, - bottomFloat: undefined, - modal: centeredModal, - modalScrollRef, - dividerYRef, - hidePill: !!viewedAgentTask, - hideSticky: !!viewedTeammateTask, - newMessageCount: unseenDivider?.count ?? 0, - onPillClick: () => { - setCursor(null); - jumpToNew(scrollRef.current); - }, - scrollable: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(TeammateViewHeader, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(Messages10, { - messages: displayedMessages, - tools, - commands: commands7, - verbose, - toolJSX, - toolUseConfirmQueue, - inProgressToolUseIDs: viewedTeammateTask ? viewedTeammateTask.inProgressToolUseIDs ?? new Set : inProgressToolUseIDs, - isMessageSelectorVisible, - conversationId, - screen, - streamingToolUses, - showAllInTranscript, - agentDefinitions, - onOpenRateLimitOptions: handleOpenRateLimitOptions, - isLoading, - streamingText: isLoading && !viewedAgentTask ? visibleStreamingText : null, - isBriefOnly: viewedAgentTask ? false : isBriefOnly, - unseenDivider: viewedAgentTask ? undefined : unseenDivider, - scrollRef: isFullscreenEnvEnabled() ? scrollRef : undefined, - trackStickyPrompt: isFullscreenEnvEnabled() ? true : undefined, - cursor, - setCursor, - cursorNavRef - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(AwsAuthStatusBox, {}, undefined, false, undefined, this), - !disabled && placeholderText && !centeredModal && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(UserTextMessage, { - param: { - text: placeholderText, - type: "text" - }, - addMargin: true, - verbose - }, undefined, false, undefined, this), - toolJSX && !(toolJSX.isLocalJSXCommand && toolJSX.isImmediate) && !toolJsxCentered && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: "100%", - children: toolJSX.jsx - }, undefined, false, undefined, this), - false, - null, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexGrow: 1 - }, undefined, false, undefined, this), - showSpinner && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(SpinnerWithVerb, { - mode: streamMode, - spinnerTip, - responseLengthRef, - apiMetricsRef: apiMetricsRef2, - overrideMessage: spinnerMessage, - spinnerSuffix: stopHookSpinnerSuffix, - verbose, - loadingStartTimeRef, - totalPausedMsRef, - pauseStartTimeRef, - overrideColor: spinnerColor, - overrideShimmerColor: spinnerShimmerColor, - hasActiveTools: inProgressToolUseIDs.size > 0, - leaderIsIdle: !isLoading - }, undefined, false, undefined, this), - !showSpinner && !isLoading && !userInputOnProcessing && !hasRunningTeammates && isBriefOnly && !viewedAgentTask && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(BriefIdleStatus, {}, undefined, false, undefined, this), - isFullscreenEnvEnabled() && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(PromptInputQueuedCommands, {}, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - bottom: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexDirection: "row", - width: "100%", - alignItems: "flex-end", - children: [ - null, - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexDirection: "column", - flexGrow: 1, - children: [ - permissionStickyFooter, - toolJSX?.isLocalJSXCommand && toolJSX.isImmediate && !toolJsxCentered && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: "100%", - children: toolJSX.jsx - }, undefined, false, undefined, this), - !showSpinner && !toolJSX?.isLocalJSXCommand && showExpandedTodos && tasksV2 && tasksV2.length > 0 && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ThemedBox_default, { - width: "100%", - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(TaskListV2, { - tasks: tasksV2, - isStandalone: true - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - focusedInputDialog === "sandbox-permission" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(SandboxPermissionRequest, { - hostPattern: sandboxPermissionRequestQueue[0].hostPattern, - onUserResponse: (response7) => { - const { - allow, - persistToSettings - } = response7; - const currentRequest = sandboxPermissionRequestQueue[0]; - if (!currentRequest) - return; - const approvedHost = currentRequest.hostPattern.host; - if (persistToSettings) { - const update = { - type: "addRules", - rules: [{ - toolName: WEB_FETCH_TOOL_NAME, - ruleContent: `domain:${approvedHost}` - }], - behavior: allow ? "allow" : "deny", - destination: "localSettings" - }; - setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdate(prev.toolPermissionContext, update) - })); - persistPermissionUpdate(update); - SandboxManager.refreshConfig(); - } - setSandboxPermissionRequestQueue((queue2) => { - queue2.filter((item) => item.hostPattern.host === approvedHost).forEach((item) => item.resolvePromise(allow)); - return queue2.filter((item) => item.hostPattern.host !== approvedHost); - }); - const cleanups = sandboxBridgeCleanupRef.current.get(approvedHost); - if (cleanups) { - for (const fn of cleanups) { - fn(); - } - sandboxBridgeCleanupRef.current.delete(approvedHost); - } - } - }, sandboxPermissionRequestQueue[0].hostPattern.host, false, undefined, this), - focusedInputDialog === "prompt" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(PromptDialog, { - title: promptQueue[0].title, - toolInputSummary: promptQueue[0].toolInputSummary, - request: promptQueue[0].request, - onRespond: (selectedKey) => { - const item = promptQueue[0]; - if (!item) - return; - item.resolve({ - prompt_response: item.request.prompt, - selected: selectedKey - }); - setPromptQueue(([, ...tail]) => tail); - }, - onAbort: () => { - const item = promptQueue[0]; - if (!item) - return; - item.reject(new Error("Prompt cancelled by user")); - setPromptQueue(([, ...tail]) => tail); - } - }, promptQueue[0].request.prompt, false, undefined, this), - pendingWorkerRequest && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(WorkerPendingPermission, { - toolName: pendingWorkerRequest.toolName, - description: pendingWorkerRequest.description - }, undefined, false, undefined, this), - pendingSandboxRequest && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(WorkerPendingPermission, { - toolName: "Network Access", - description: `Waiting for leader to approve network access to ${pendingSandboxRequest.host}` - }, undefined, false, undefined, this), - focusedInputDialog === "worker-sandbox-permission" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(SandboxPermissionRequest, { - hostPattern: { - host: workerSandboxPermissions.queue[0].host, - port: undefined - }, - onUserResponse: (response7) => { - const { - allow, - persistToSettings - } = response7; - const currentRequest = workerSandboxPermissions.queue[0]; - if (!currentRequest) - return; - const approvedHost = currentRequest.host; - sendSandboxPermissionResponseViaMailbox(currentRequest.workerName, currentRequest.requestId, approvedHost, allow, teamContext?.teamName); - if (persistToSettings && allow) { - const update = { - type: "addRules", - rules: [{ - toolName: WEB_FETCH_TOOL_NAME, - ruleContent: `domain:${approvedHost}` - }], - behavior: "allow", - destination: "localSettings" - }; - setAppState((prev) => ({ - ...prev, - toolPermissionContext: applyPermissionUpdate(prev.toolPermissionContext, update) - })); - persistPermissionUpdate(update); - SandboxManager.refreshConfig(); - } - setAppState((prev) => ({ - ...prev, - workerSandboxPermissions: { - ...prev.workerSandboxPermissions, - queue: prev.workerSandboxPermissions.queue.slice(1) - } - })); - } - }, workerSandboxPermissions.queue[0].requestId, false, undefined, this), - focusedInputDialog === "elicitation" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(ElicitationDialog, { - event: elicitation.queue[0], - onResponse: (action2, content) => { - const currentRequest = elicitation.queue[0]; - if (!currentRequest) - return; - currentRequest.respond({ - action: action2, - content - }); - const isUrlAccept = currentRequest.params.mode === "url" && action2 === "accept"; - if (!isUrlAccept) { - setAppState((prev) => ({ - ...prev, - elicitation: { - queue: prev.elicitation.queue.slice(1) - } - })); - } - }, - onWaitingDismiss: (action2) => { - const currentRequest = elicitation.queue[0]; - setAppState((prev) => ({ - ...prev, - elicitation: { - queue: prev.elicitation.queue.slice(1) - } - })); - currentRequest?.onWaitingDismiss?.(action2); - } - }, elicitation.queue[0].serverName + ":" + String(elicitation.queue[0].requestId), false, undefined, this), - focusedInputDialog === "cost" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(CostThresholdDialog, { - onDone: () => { - setShowCostDialog(false); - setHaveShownCostDialog(true); - saveGlobalConfig((current) => ({ - ...current, - hasAcknowledgedCostThreshold: true - })); - logEvent("tengu_cost_threshold_acknowledged", {}); - } - }, undefined, false, undefined, this), - focusedInputDialog === "idle-return" && idleReturnPending && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(IdleReturnDialog, { - idleMinutes: idleReturnPending.idleMinutes, - totalInputTokens: getTotalInputTokens(), - onDone: async (action2) => { - const pending = idleReturnPending; - setIdleReturnPending(null); - logEvent("tengu_idle_return_action", { - action: action2, - idleMinutes: Math.round(pending.idleMinutes), - messageCount: messagesRef.current.length, - totalInputTokens: getTotalInputTokens() - }); - if (action2 === "dismiss") { - setInputValue(pending.input); - return; - } - if (action2 === "never") { - saveGlobalConfig((current) => { - if (current.idleReturnDismissed) - return current; - return { - ...current, - idleReturnDismissed: true - }; - }); - } - if (action2 === "clear") { - const { - clearConversation: clearConversation2 - } = await Promise.resolve().then(() => (init_conversation(), exports_conversation)); - await clearConversation2({ - setMessages, - readFileState: readFileState.current, - discoveredSkillNames: discoveredSkillNamesRef.current, - loadedNestedMemoryPaths: loadedNestedMemoryPathsRef.current, - getAppState: () => store.getState(), - setAppState, - setConversationId - }); - haikuTitleAttemptedRef.current = false; - setHaikuTitle(undefined); - bashTools.current.clear(); - bashToolsProcessedIdx.current = 0; - } - skipIdleCheckRef.current = true; - onSubmitRef.current(pending.input, { - setCursorOffset: () => {}, - clearBuffer: () => {}, - resetHistory: () => {} - }); - } - }, undefined, false, undefined, this), - focusedInputDialog === "ide-onboarding" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(IdeOnboardingDialog, { - onDone: () => setShowIdeOnboarding(false), - installationStatus: ideInstallationStatus - }, undefined, false, undefined, this), - false, - false, - focusedInputDialog === "effort-callout" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(EffortCallout, { - model: mainLoopModel, - onDone: (selection) => { - setShowEffortCallout(false); - if (selection !== "dismiss") { - setAppState((prev) => ({ - ...prev, - effortValue: selection - })); - } - } - }, undefined, false, undefined, this), - focusedInputDialog === "remote-callout" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(RemoteCallout, { - onDone: (selection) => { - setAppState((prev) => { - if (!prev.showRemoteCallout) - return prev; - return { - ...prev, - showRemoteCallout: false, - ...selection === "enable" && { - replBridgeEnabled: true, - replBridgeExplicit: true, - replBridgeOutboundOnly: false - } - }; - }); - } - }, undefined, false, undefined, this), - exitFlow, - focusedInputDialog === "plugin-hint" && hintRecommendation && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(PluginHintMenu, { - pluginName: hintRecommendation.pluginName, - pluginDescription: hintRecommendation.pluginDescription, - marketplaceName: hintRecommendation.marketplaceName, - sourceCommand: hintRecommendation.sourceCommand, - onResponse: handleHintResponse - }, undefined, false, undefined, this), - focusedInputDialog === "lsp-recommendation" && lspRecommendation && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(LspRecommendationMenu, { - pluginName: lspRecommendation.pluginName, - pluginDescription: lspRecommendation.pluginDescription, - fileExtension: lspRecommendation.fileExtension, - onResponse: handleLspResponse - }, undefined, false, undefined, this), - focusedInputDialog === "desktop-upsell" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(DesktopUpsellStartup, { - onDone: () => setShowDesktopUpsellStartup(false) - }, undefined, false, undefined, this), - null, - null, - mrRender(), - !toolJSX?.shouldHidePromptInput && !focusedInputDialog && !isExiting && !disabled && !cursor && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(jsx_dev_runtime467.Fragment, { - children: [ - autoRunIssueReason && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(AutoRunIssueNotification, { - onRun: handleAutoRunIssue, - onCancel: handleCancelAutoRunIssue, - reason: getAutoRunIssueReasonText(autoRunIssueReason) - }, undefined, false, undefined, this), - postCompactSurvey.state !== "closed" ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(FeedbackSurvey, { - state: postCompactSurvey.state, - lastResponse: postCompactSurvey.lastResponse, - handleSelect: postCompactSurvey.handleSelect, - inputValue, - setInputValue, - onRequestFeedback: handleSurveyRequestFeedback - }, undefined, false, undefined, this) : memorySurvey.state !== "closed" ? /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(FeedbackSurvey, { - state: memorySurvey.state, - lastResponse: memorySurvey.lastResponse, - handleSelect: memorySurvey.handleSelect, - handleTranscriptSelect: memorySurvey.handleTranscriptSelect, - inputValue, - setInputValue, - onRequestFeedback: handleSurveyRequestFeedback, - message: "How well did Claude use its memory? (optional)" - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(FeedbackSurvey, { - state: feedbackSurvey.state, - lastResponse: feedbackSurvey.lastResponse, - handleSelect: feedbackSurvey.handleSelect, - handleTranscriptSelect: feedbackSurvey.handleTranscriptSelect, - inputValue, - setInputValue, - onRequestFeedback: didAutoRunIssueRef.current ? undefined : handleSurveyRequestFeedback - }, undefined, false, undefined, this), - frustrationDetection.state !== "closed" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(FeedbackSurvey, { - state: frustrationDetection.state, - lastResponse: null, - handleSelect: () => {}, - handleTranscriptSelect: frustrationDetection.handleTranscriptSelect, - inputValue, - setInputValue - }, undefined, false, undefined, this), - false, - showIssueFlagBanner && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(IssueFlagBanner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(PromptInput_default, { - debug: debug2, - ideSelection, - hasSuppressedDialogs: !!hasSuppressedDialogs, - isLocalJSXCommandActive: isShowingLocalJSXCommand, - getToolUseContext, - toolPermissionContext, - setToolPermissionContext, - apiKeyStatus, - commands: commands7, - agents: agentDefinitions.activeAgents, - isLoading, - onExit: handleExit, - verbose, - messages, - onAutoUpdaterResult: setAutoUpdaterResult, - autoUpdaterResult, - input: inputValue, - onInputChange: setInputValue, - mode: inputMode, - onModeChange: setInputMode, - stashedPrompt, - setStashedPrompt, - submitCount, - onShowMessageSelector: handleShowMessageSelector, - onMessageActionsEnter: undefined, - mcpClients, - pastedContents, - setPastedContents, - vimMode, - setVimMode, - showBashesDialog, - setShowBashesDialog, - onSubmit, - onAgentSubmit, - isSearchingHistory, - setIsSearchingHistory, - helpOpen: isHelpOpen, - setHelpOpen: setIsHelpOpen, - insertTextRef: undefined, - voiceInterimRange: voice.interimRange - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(SessionBackgroundHint, { - onBackgroundSession: handleBackgroundSession, - isLoading - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - cursor && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(MessageActionsBar, { - cursor - }, undefined, false, undefined, this), - focusedInputDialog === "message-selector" && /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(MessageSelector, { - messages, - preselectedMessage: messageSelectorPreselect, - onPreRestore: onCancel, - onRestoreCode: async (message) => { - await fileHistoryRewind((updater) => { - setAppState((prev) => ({ - ...prev, - fileHistory: updater(prev.fileHistory) - })); - }, message.uuid); - }, - onSummarize: async (message, feedback2, direction = "from") => { - const compactMessages = getMessagesAfterCompactBoundary(messages); - const messageIndex = compactMessages.indexOf(message); - if (messageIndex === -1) { - setMessages((prev) => [...prev, createSystemMessage("That message is no longer in the active context (snipped or pre-compact). Choose a more recent message.", "warning")]); - return; - } - const newAbortController = createAbortController(); - const context7 = getToolUseContext(compactMessages, [], newAbortController, mainLoopModel); - const appState = context7.getAppState(); - const defaultSysPrompt = await getSystemPrompt(context7.options.tools, context7.options.mainLoopModel, Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys()), context7.options.mcpClients); - const systemPrompt = buildEffectiveSystemPrompt({ - mainThreadAgentDefinition: undefined, - toolUseContext: context7, - customSystemPrompt: context7.options.customSystemPrompt, - defaultSystemPrompt: defaultSysPrompt, - appendSystemPrompt: context7.options.appendSystemPrompt - }); - const [userContext, systemContext] = await Promise.all([getUserContext(), getSystemContext()]); - const result = await partialCompactConversation(compactMessages, messageIndex, context7, { - systemPrompt, - userContext, - systemContext, - toolUseContext: context7, - forkContextMessages: compactMessages - }, feedback2, direction); - const kept = result.messagesToKeep ?? []; - const ordered = direction === "up_to" ? [...result.summaryMessages, ...kept] : [...kept, ...result.summaryMessages]; - const postCompact = [result.boundaryMarker, ...ordered, ...result.attachments, ...result.hookResults]; - if (isFullscreenEnvEnabled() && direction === "from") { - setMessages((old) => { - const rawIdx = old.findIndex((m4) => m4.uuid === message.uuid); - return [...old.slice(0, rawIdx === -1 ? 0 : rawIdx), ...postCompact]; - }); - } else { - setMessages(postCompact); - } - if (false) {} - setConversationId(randomUUID49()); - runPostCompactCleanup(context7.options.querySource); - if (direction === "from") { - const r4 = textForResubmit(message); - if (r4) { - setInputValue(r4.text); - setInputMode(r4.mode); - } - } - const historyShortcut = getShortcutDisplay("app:toggleTranscript", "Global", "ctrl+o"); - addNotification({ - key: "summarize-ctrl-o-hint", - text: `Conversation summarized (${historyShortcut} for history)`, - priority: "medium", - timeoutMs: 8000 - }); - }, - onRestoreMessage: handleRestoreMessage, - onClose: () => { - setIsMessageSelectorVisible(false); - setMessageSelectorPreselect(undefined); - } - }, undefined, false, undefined, this), - false - ] - }, undefined, true, undefined, this), - null - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - }, remountKey, false, undefined, this) - ] - }, undefined, true, undefined, this); - if (isFullscreenEnvEnabled()) { - return /* @__PURE__ */ jsx_dev_runtime467.jsxDEV(AlternateScreen, { - mouseTracking: isMouseTrackingEnabled(), - children: mainReturn - }, undefined, false, undefined, this); - } - return mainReturn; -} -var import_compiler_runtime368, React156, import_react318, jsx_dev_runtime467, useFrustrationDetection = () => ({ - state: "closed", - handleTranscriptSelect: () => {} -}), useAntOrgWarningNotification = () => {}, getCoordinatorUserContext = () => ({}), proactiveModule5 = null, PROACTIVE_NO_OP_SUBSCRIBE = (_cb) => () => {}, PROACTIVE_FALSE = () => false, SUGGEST_BG_PR_NOOP = (_p3, _n3) => false, EMPTY_MCP_CLIENTS2, HISTORY_STUB, RECENT_SCROLL_REPIN_WINDOW_MS = 3000, TITLE_ANIMATION_FRAMES, TITLE_STATIC_PREFIX = "\u2733", TITLE_ANIMATION_INTERVAL_MS = 960; -var init_REPL = __esm(() => { - init_state(); - init_tokenBudget(); - init_figures(); - init_ink2(); - init_useSearchInput(); - init_useTerminalSize(); - init_use_search_highlight(); - init_exportRenderer(); - init_editor(); - init_ink2(); - init_CostThresholdDialog(); - init_IdleReturnDialog(); - init_notifications(); - init_notifier(); - init_preventSleep(); - init_useTerminalNotification(); - init_terminal(); - init_fileStateCache(); - init_state(); - init_ids(); - init_debug(); - init_QueryGuard(); - init_envUtils(); - init_format(); - init_earlyInput(); - init_teamHelpers(); - init_permissionSync(); - init_useSwarmPermissionPoller(); - init_teammate(); - init_WorkerPendingPermission(); - init_InProcessTeammateTask(); - init_LocalAgentTask(); - init_sessionTracing(); - init_useLogMessages(); - init_useReplBridge(); - init_commands5(); - init_MessageSelector(); - init_useIdeLogging(); - init_PermissionRequest(); - init_ElicitationDialog(); - init_PromptDialog(); - init_PromptInput(); - init_PromptInputQueuedCommands(); - init_useRemoteSession(); - init_useDirectConnect(); - init_useSSHSession(); - init_useAssistantHistory(); - init_SkillImprovementSurvey(); - init_useSkillImprovementSurvey(); - init_Spinner2(); - init_prompts3(); - init_systemPrompt(); - init_context4(); - init_claudemd(); - init_backgroundHousekeeping(); - init_cost_tracker(); - init_costHook(); - init_fpsMetrics(); - init_useAfterFirstRender(); - init_useDeferredHookMessages(); - init_history(); - init_shellHistoryCompletion(); - init_useApiKeyVerification(); - init_useGlobalKeybindings(); - init_useCommandKeybindings(); - init_KeybindingProviderSetup(); - init_useShortcutDisplay(); - init_shortcutFormat(); - init_useCancelRequest(); - init_useBackgroundTaskNavigation(); - init_useSwarmInitialization(); - init_useTeammateViewAutoExit(); - init_errors(); - init_log2(); - init_useCanUseTool(); - init_PermissionUpdate(); - init_ExitPlanModePermissionRequest(); - init_permissionSetup(); - init_filesystem(); - init_prompt16(); - init_bashPermissions(); - init_config(); - init_billing(); - init_analytics(); - init_growthbook(); - init_messages9(); - init_sessionTitle(); - init_xml(); - init_gracefulShutdown(); - init_handlePromptSubmit(); - init_useQueueProcessor(); - init_useMailboxBridge(); - init_queryProfiler(); - init_query4(); - init_useMergedClients(); - init_promptCategory(); - init_useMergedTools(); - init_toolPool(); - init_useMergedCommands(); - init_useSkillsChange(); - init_useManagePlugins(); - init_Messages(); - init_TaskListV2(); - init_TeammateViewHeader(); - init_useTasksV2(); - init_projectOnboardingState(); - init_sessionStart(); - init_hooks3(); - init_useIdeSelection(); - init_tools2(); - init_agentToolUtils(); - init_resumeAgent(); - init_useMainLoopModel(); - init_AppState(); - init_plans(); - init_sessionStorage(); - init_conversationRecovery(); - init_queryHelpers(); - init_microCompact(); - init_postCompactCleanup(); - init_toolResultStorage(); - init_compact(); - init_fileHistory(); - init_commitAttribution(); - init_sessionStorage(); - init_sessionRestore(); - init_concurrentSessions(); - init_RemoteAgentTask(); - init_useInboxPoller(); - init_agentSwarmsEnabled(); - init_useTaskListWatcher(); - init_ide(); - init_useIDEIntegration(); - init_exit2(); - init_ExitFlow(); - init_worktree(); - init_messageQueueManager(); - init_useCommandQueue(); - init_SessionBackgroundHint(); - init_LocalMainSessionTask(); - init_useSessionBackgrounding(); - init_diagnosticTracking(); - init_speculation(); - init_IdeOnboardingDialog(); - init_EffortCallout(); - init_RemoteCallout(); - init_activityManager(); - init_abortController(); - init_MCPConnectionManager(); - init_useFeedbackSurvey(); - init_useMemorySurvey(); - init_usePostCompactSurvey(); - init_FeedbackSurvey(); - init_useInstallMessages(); - init_useAwaySummary(); - init_useChromeExtensionNotification(); - init_useOfficialMarketplaceNotification(); - init_usePromptsFromClaudeInChrome(); - init_tipScheduler(); - init_bypassPermissionsKillswitch(); - init_sandbox_adapter(); - init_structuredIO(); - init_useFileHistorySnapshotInit(); - init_SandboxPermissionRequest(); - init_SandboxViolationExpandedView(); - init_useSettingsErrors(); - init_useMcpConnectivityStatus(); - init_useAutoModeUnavailableNotification(); - init_AutoModeOptInDialog(); - init_useLspInitializationNotification(); - init_useLspPluginRecommendation(); - init_LspRecommendationMenu(); - init_useClaudeCodeHintRecommendation(); - init_PluginHintMenu(); - init_DesktopUpsellStartup(); - init_usePluginInstallationStatus(); - init_usePluginAutoupdateNotification(); - init_performStartupChecks(); - init_UserTextMessage(); - init_AwsAuthStatusBox(); - init_useRateLimitWarningNotification(); - init_useDeprecationWarningNotification(); - init_useNpmDeprecationNotification(); - init_useIDEStatusIndicator(); - init_useModelMigrationNotifications(); - init_useCanSwitchToExistingSubscription(); - init_useTeammateShutdownNotification(); - init_useFastModeNotification(); - init_autoRunIssue(); - init_useIssueFlagBanner(); - init_CompanionSprite(); - init_DevBar(); - init_commands5(); - init_FullscreenLayout(); - init_fullscreen(); - init_AlternateScreen(); - init_ScrollKeybindingHandler(); - init_messageActions(); - init_osc(); - init_attachments(); - import_compiler_runtime368 = __toESM(require_compiler_runtime(), 1); - React156 = __toESM(require_react(), 1); - import_react318 = __toESM(require_react(), 1); - jsx_dev_runtime467 = __toESM(require_jsx_dev_runtime(), 1); - EMPTY_MCP_CLIENTS2 = []; - HISTORY_STUB = { - maybeLoadOlder: (_) => {} - }; - TITLE_ANIMATION_FRAMES = ["\u2802", "\u2810"]; -}); - -// src/utils/githubRepoPathMapping.ts -import { realpath as realpath12 } from "fs/promises"; -async function updateGithubRepoPathMapping() { - try { - const repo = await detectCurrentRepository(); - if (!repo) { - logForDebugging("Not in a GitHub repository, skipping path mapping update"); - return; - } - const cwd2 = getOriginalCwd(); - const gitRoot = findGitRoot(cwd2); - const basePath = gitRoot ?? cwd2; - let currentPath; - try { - currentPath = (await realpath12(basePath)).normalize("NFC"); - } catch { - currentPath = basePath; - } - const repoKey = repo.toLowerCase(); - const config10 = getGlobalConfig(); - const existingPaths = config10.githubRepoPaths?.[repoKey] ?? []; - if (existingPaths[0] === currentPath) { - logForDebugging(`Path ${currentPath} already tracked for repo ${repoKey}`); - return; - } - const withoutCurrent = existingPaths.filter((p4) => p4 !== currentPath); - const updatedPaths = [currentPath, ...withoutCurrent]; - saveGlobalConfig((current) => ({ - ...current, - githubRepoPaths: { - ...current.githubRepoPaths, - [repoKey]: updatedPaths - } - })); - logForDebugging(`Added ${currentPath} to tracked paths for repo ${repoKey}`); - } catch (error46) { - logForDebugging(`Error updating repo path mapping: ${error46}`); - } -} -function getKnownPathsForRepo(repo) { - const config10 = getGlobalConfig(); - const repoKey = repo.toLowerCase(); - return config10.githubRepoPaths?.[repoKey] ?? []; -} -async function filterExistingPaths(paths2) { - const results = await Promise.all(paths2.map(pathExists)); - return paths2.filter((_, i6) => results[i6]); -} -async function validateRepoAtPath(path27, expectedRepo) { - try { - const remoteUrl = await getRemoteUrlForDir(path27); - if (!remoteUrl) { - return false; - } - const actualRepo = parseGitHubRepository(remoteUrl); - if (!actualRepo) { - return false; - } - return actualRepo.toLowerCase() === expectedRepo.toLowerCase(); - } catch { - return false; - } -} -function removePathFromRepo(repo, pathToRemove) { - const config10 = getGlobalConfig(); - const repoKey = repo.toLowerCase(); - const existingPaths = config10.githubRepoPaths?.[repoKey] ?? []; - const updatedPaths = existingPaths.filter((path27) => path27 !== pathToRemove); - if (updatedPaths.length === existingPaths.length) { - return; - } - const updatedMapping = { ...config10.githubRepoPaths }; - if (updatedPaths.length === 0) { - delete updatedMapping[repoKey]; - } else { - updatedMapping[repoKey] = updatedPaths; - } - saveGlobalConfig((current) => ({ - ...current, - githubRepoPaths: updatedMapping - })); - logForDebugging(`Removed ${pathToRemove} from tracked paths for repo ${repoKey}`); -} -var init_githubRepoPathMapping = __esm(() => { - init_state(); - init_config(); - init_debug(); - init_detectRepository(); - init_file(); - init_gitFilesystem(); - init_git(); -}); - -// src/hooks/useTimeout.ts -function useTimeout(delay4, resetTrigger) { - const [isElapsed, setIsElapsed] = import_react319.useState(false); - import_react319.useEffect(() => { - setIsElapsed(false); - const timer = setTimeout(setIsElapsed, delay4, true); - return () => clearTimeout(timer); - }, [delay4, resetTrigger]); - return isElapsed; -} -var import_react319; -var init_useTimeout = __esm(() => { - import_react319 = __toESM(require_react(), 1); -}); - -// src/utils/preflightChecks.tsx -async function checkEndpoints() { - try { - const oauthConfig = getOauthConfig(); - const tokenUrl = new URL(oauthConfig.TOKEN_URL); - const endpoints7 = [`${oauthConfig.BASE_API_URL}/api/hello`, `${tokenUrl.origin}/v1/oauth/hello`]; - const checkEndpoint = async (url3) => { - try { - const response7 = await axios_default.get(url3, { - headers: { - "User-Agent": getUserAgent() - } - }); - if (response7.status !== 200) { - const hostname3 = new URL(url3).hostname; - return { - success: false, - error: `Failed to connect to ${hostname3}: Status ${response7.status}` - }; - } - return { - success: true - }; - } catch (error46) { - const hostname3 = new URL(url3).hostname; - const sslHint = getSSLErrorHint(error46); - return { - success: false, - error: `Failed to connect to ${hostname3}: ${error46 instanceof Error ? error46.code || error46.message : String(error46)}`, - sslHint: sslHint ?? undefined - }; - } - }; - const results = await Promise.all(endpoints7.map(checkEndpoint)); - const failedResult = results.find((result) => !result.success); - if (failedResult) { - logEvent("tengu_preflight_check_failed", { - isConnectivityError: false, - hasErrorMessage: !!failedResult.error, - isSSLError: !!failedResult.sslHint - }); - } - return failedResult || { - success: true - }; - } catch (error46) { - logError2(error46); - logEvent("tengu_preflight_check_failed", { - isConnectivityError: true - }); - return { - success: false, - error: `Connectivity check error: ${error46 instanceof Error ? error46.code || error46.message : String(error46)}` - }; - } -} -function PreflightStep(t0) { - const $2 = import_compiler_runtime372.c(12); - const { - onSuccess - } = t0; - const [result, setResult] = import_react320.useState(null); - const [isChecking, setIsChecking] = import_react320.useState(true); - const showSpinner = useTimeout(1000) && isChecking; - let t1; - let t22; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - const run = async function run2() { - const checkResult = await checkEndpoints(); - setResult(checkResult); - setIsChecking(false); - }; - run(); - }; - t22 = []; - $2[0] = t1; - $2[1] = t22; - } else { - t1 = $2[0]; - t22 = $2[1]; - } - import_react320.useEffect(t1, t22); - let t32; - let t4; - if ($2[2] !== onSuccess || $2[3] !== result) { - t32 = () => { - if (result?.success) { - onSuccess(); - } else { - if (result && !result.success) { - const timer = setTimeout(_temp303, 100); - return () => clearTimeout(timer); - } - } - }; - t4 = [result, onSuccess]; - $2[2] = onSuccess; - $2[3] = result; - $2[4] = t32; - $2[5] = t4; - } else { - t32 = $2[4]; - t4 = $2[5]; - } - import_react320.useEffect(t32, t4); - let t5; - if ($2[6] !== isChecking || $2[7] !== result || $2[8] !== showSpinner) { - t5 = isChecking && showSpinner ? /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedBox_default, { - paddingLeft: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - children: "Checking connectivity..." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : !result?.success && !isChecking && /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - color: "error", - children: "Unable to connect to Anthropic services" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - color: "error", - children: result?.error - }, undefined, false, undefined, this), - result?.sslHint ? /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - children: result.sslHint - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - color: "suggestion", - children: "See https://code.claude.com/docs/en/network-config" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - children: "Please check your internet connection and network settings." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - children: [ - "Note: Claude Code might not be available in your country. Check supported countries at", - " ", - /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedText, { - color: "suggestion", - children: "https://anthropic.com/supported-countries" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = isChecking; - $2[7] = result; - $2[8] = showSpinner; - $2[9] = t5; - } else { - t5 = $2[9]; - } - let t6; - if ($2[10] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime473.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - paddingLeft: 1, - children: t5 - }, undefined, false, undefined, this); - $2[10] = t5; - $2[11] = t6; - } else { - t6 = $2[11]; - } - return t6; -} -function _temp303() { - return process.exit(1); -} -var import_compiler_runtime372, import_react320, jsx_dev_runtime473; -var init_preflightChecks = __esm(() => { - init_axios2(); - init_analytics(); - init_Spinner2(); - init_oauth(); - init_useTimeout(); - init_ink2(); - init_errorUtils(); - init_http8(); - init_log2(); - import_compiler_runtime372 = __toESM(require_compiler_runtime(), 1); - import_react320 = __toESM(require_react(), 1); - jsx_dev_runtime473 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/ApproveApiKey.tsx -var exports_ApproveApiKey = {}; -__export(exports_ApproveApiKey, { - ApproveApiKey: () => ApproveApiKey -}); -function ApproveApiKey(t0) { - const $2 = import_compiler_runtime373.c(17); - const { - customApiKeyTruncated, - onDone - } = t0; - let t1; - if ($2[0] !== customApiKeyTruncated || $2[1] !== onDone) { - t1 = function onChange2(value) { - bb2: - switch (value) { - case "yes": { - saveGlobalConfig((current_0) => ({ - ...current_0, - customApiKeyResponses: { - ...current_0.customApiKeyResponses, - approved: [...current_0.customApiKeyResponses?.approved ?? [], customApiKeyTruncated] - } - })); - onDone(true); - break bb2; - } - case "no": { - saveGlobalConfig((current) => ({ - ...current, - customApiKeyResponses: { - ...current.customApiKeyResponses, - rejected: [...current.customApiKeyResponses?.rejected ?? [], customApiKeyTruncated] - } - })); - onDone(false); - } - } - }; - $2[0] = customApiKeyTruncated; - $2[1] = onDone; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const onChange = t1; - let t22; - if ($2[3] !== onChange) { - t22 = () => onChange("no"); - $2[3] = onChange; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(ThemedText, { - bold: true, - children: "ANTHROPIC_API_KEY" - }, undefined, false, undefined, this); - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] !== customApiKeyTruncated) { - t4 = /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(ThemedText, { - children: [ - t32, - /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(ThemedText, { - children: [ - ": sk-ant-...", - customApiKeyTruncated - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[6] = customApiKeyTruncated; - $2[7] = t4; - } else { - t4 = $2[7]; - } - let t5; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(ThemedText, { - children: "Do you want to use this API key?" - }, undefined, false, undefined, this); - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] === Symbol.for("react.memo_cache_sentinel")) { - t6 = { - label: "Yes", - value: "yes" - }; - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] === Symbol.for("react.memo_cache_sentinel")) { - t7 = [t6, { - label: /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(ThemedText, { - children: [ - "No (", - /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(ThemedText, { - bold: true, - children: "recommended" - }, undefined, false, undefined, this), - ")" - ] - }, undefined, true, undefined, this), - value: "no" - }]; - $2[10] = t7; - } else { - t7 = $2[10]; - } - let t8; - if ($2[11] !== onChange) { - t8 = /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(Select, { - defaultValue: "no", - defaultFocusValue: "no", - options: t7, - onChange: (value_0) => onChange(value_0), - onCancel: () => onChange("no") - }, undefined, false, undefined, this); - $2[11] = onChange; - $2[12] = t8; - } else { - t8 = $2[12]; - } - let t9; - if ($2[13] !== t22 || $2[14] !== t4 || $2[15] !== t8) { - t9 = /* @__PURE__ */ jsx_dev_runtime474.jsxDEV(Dialog, { - title: "Detected a custom API key in your environment", - color: "warning", - onCancel: t22, - children: [ - t4, - t5, - t8 - ] - }, undefined, true, undefined, this); - $2[13] = t22; - $2[14] = t4; - $2[15] = t8; - $2[16] = t9; - } else { - t9 = $2[16]; - } - return t9; -} -var import_compiler_runtime373, jsx_dev_runtime474; -var init_ApproveApiKey = __esm(() => { - init_ink2(); - init_config(); - init_CustomSelect(); - init_Dialog(); - import_compiler_runtime373 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime474 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/LogoV2/WelcomeV2.tsx -function WelcomeV2() { - const $2 = import_compiler_runtime374.c(35); - const [theme2] = useTheme(); - if (env2.terminal === "Apple_Terminal") { - let t02; - if ($2[0] !== theme2) { - t02 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(AppleTerminalWelcomeV2, { - theme: theme2, - welcomeMessage: "Welcome to Claude Code" - }, undefined, false, undefined, this); - $2[0] = theme2; - $2[1] = t02; - } else { - t02 = $2[1]; - } - return t02; - } - if (["light", "light-daltonized", "light-ansi"].includes(theme2)) { - let t02; - let t17; - let t23; - let t33; - let t42; - let t52; - let t62; - let t72; - let t82; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t02 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "claude", - children: [ - "Welcome to Claude Code", - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "v", - MACRO.VERSION, - " " - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - t17 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026" - }, undefined, false, undefined, this); - t23 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t33 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t42 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t52 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t62 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t72 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t82 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - $2[2] = t02; - $2[3] = t17; - $2[4] = t23; - $2[5] = t33; - $2[6] = t42; - $2[7] = t52; - $2[8] = t62; - $2[9] = t72; - $2[10] = t82; - } else { - t02 = $2[2]; - t17 = $2[3]; - t23 = $2[4]; - t33 = $2[5]; - t42 = $2[6]; - t52 = $2[7]; - t62 = $2[8]; - t72 = $2[9]; - t82 = $2[10]; - } - let t92; - if ($2[11] === Symbol.for("react.memo_cache_sentinel")) { - t92 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2588\u2588 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[11] = t92; - } else { - t92 = $2[11]; - } - let t102; - let t112; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t102 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2588\u2588\u2592\u2592\u2588\u2588 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - t112 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2592\u2592 \u2588\u2588 \u2592" - }, undefined, false, undefined, this); - $2[12] = t102; - $2[13] = t112; - } else { - t102 = $2[12]; - t112 = $2[13]; - } - let t122; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t122 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: " \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 " - }, undefined, false, undefined, this), - " \u2592\u2592\u2591\u2591\u2592\u2592 \u2592 \u2592\u2592" - ] - }, undefined, true, undefined, this); - $2[14] = t122; - } else { - t122 = $2[14]; - } - let t132; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t132 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - backgroundColor: "clawd_background", - children: "\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2588\u2588" - }, undefined, false, undefined, this), - " \u2592\u2592 \u2592\u2592 " - ] - }, undefined, true, undefined, this); - $2[15] = t132; - } else { - t132 = $2[15]; - } - let t142; - if ($2[16] === Symbol.for("react.memo_cache_sentinel")) { - t142 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: " \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 " - }, undefined, false, undefined, this), - " \u2591 \u2592 " - ] - }, undefined, true, undefined, this); - $2[16] = t142; - } else { - t142 = $2[16]; - } - let t152; - if ($2[17] === Symbol.for("react.memo_cache_sentinel")) { - t152 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedBox_default, { - width: WELCOME_V2_WIDTH, - children: /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - t02, - t17, - t23, - t33, - t42, - t52, - t62, - t72, - t82, - t92, - t102, - t112, - t122, - t132, - t142, - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2588 \u2588 \u2588 \u2588" - }, undefined, false, undefined, this), - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2591\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2592\u2026\u2026\u2026\u2026" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[17] = t152; - } else { - t152 = $2[17]; - } - return t152; - } - let t0; - let t1; - let t22; - let t32; - let t4; - let t5; - let t6; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t0 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "claude", - children: [ - "Welcome to Claude Code", - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "v", - MACRO.VERSION, - " " - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - t1 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026" - }, undefined, false, undefined, this); - t22 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t32 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " * \u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2591 " - }, undefined, false, undefined, this); - t4 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " * \u2588\u2588\u2588\u2593\u2591 \u2591\u2591 " - }, undefined, false, undefined, this); - t5 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591 \u2588\u2588\u2588\u2593\u2591 " - }, undefined, false, undefined, this); - t6 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2588\u2588\u2588\u2593\u2591 " - }, undefined, false, undefined, this); - $2[18] = t0; - $2[19] = t1; - $2[20] = t22; - $2[21] = t32; - $2[22] = t4; - $2[23] = t5; - $2[24] = t6; - } else { - t0 = $2[18]; - t1 = $2[19]; - t22 = $2[20]; - t32 = $2[21]; - t4 = $2[22]; - t5 = $2[23]; - t6 = $2[24]; - } - let t10; - let t11; - let t7; - let t8; - let t9; - if ($2[25] === Symbol.for("react.memo_cache_sentinel")) { - t7 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - bold: true, - children: "*" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2588\u2588\u2593\u2591\u2591 \u2593 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - t8 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2593\u2593\u2588\u2588\u2588\u2593\u2593\u2591 " - }, undefined, false, undefined, this); - t9 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " * \u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t10 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t11 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - $2[25] = t10; - $2[26] = t11; - $2[27] = t7; - $2[28] = t8; - $2[29] = t9; - } else { - t10 = $2[25]; - t11 = $2[26]; - t7 = $2[27]; - t8 = $2[28]; - t9 = $2[29]; - } - let t12; - if ($2[30] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: " \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 " - }, undefined, false, undefined, this); - $2[30] = t12; - } else { - t12 = $2[30]; - } - let t13; - if ($2[31] === Symbol.for("react.memo_cache_sentinel")) { - t13 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - t12, - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: "*" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[31] = t13; - } else { - t13 = $2[31]; - } - let t14; - if ($2[32] === Symbol.for("react.memo_cache_sentinel")) { - t14 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2588\u2588" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - bold: true, - children: "*" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[32] = t14; - } else { - t14 = $2[32]; - } - let t15; - if ($2[33] === Symbol.for("react.memo_cache_sentinel")) { - t15 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: " \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 " - }, undefined, false, undefined, this), - " * " - ] - }, undefined, true, undefined, this); - $2[33] = t15; - } else { - t15 = $2[33]; - } - let t16; - if ($2[34] === Symbol.for("react.memo_cache_sentinel")) { - t16 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedBox_default, { - width: WELCOME_V2_WIDTH, - children: /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - t0, - t1, - t22, - t32, - t4, - t5, - t6, - t7, - t8, - t9, - t10, - t11, - t13, - t14, - t15, - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2588 \u2588 \u2588 \u2588" - }, undefined, false, undefined, this), - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[34] = t16; - } else { - t16 = $2[34]; - } - return t16; -} -function AppleTerminalWelcomeV2(t0) { - const $2 = import_compiler_runtime374.c(44); - const { - theme: theme2, - welcomeMessage - } = t0; - const isLightTheme = ["light", "light-daltonized", "light-ansi"].includes(theme2); - if (isLightTheme) { - let t110; - if ($2[0] !== welcomeMessage) { - t110 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "claude", - children: [ - welcomeMessage, - " " - ] - }, undefined, true, undefined, this); - $2[0] = welcomeMessage; - $2[1] = t110; - } else { - t110 = $2[1]; - } - let t23; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t23 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "v", - MACRO.VERSION, - " " - ] - }, undefined, true, undefined, this); - $2[2] = t23; - } else { - t23 = $2[2]; - } - let t33; - if ($2[3] !== t110) { - t33 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - t110, - t23 - ] - }, undefined, true, undefined, this); - $2[3] = t110; - $2[4] = t33; - } else { - t33 = $2[4]; - } - let t102; - let t112; - let t42; - let t52; - let t62; - let t72; - let t82; - let t92; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t42 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026" - }, undefined, false, undefined, this); - t52 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t62 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t72 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t82 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t92 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t102 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t112 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - $2[5] = t102; - $2[6] = t112; - $2[7] = t42; - $2[8] = t52; - $2[9] = t62; - $2[10] = t72; - $2[11] = t82; - $2[12] = t92; - } else { - t102 = $2[5]; - t112 = $2[6]; - t42 = $2[7]; - t52 = $2[8]; - t62 = $2[9]; - t72 = $2[10]; - t82 = $2[11]; - t92 = $2[12]; - } - let t122; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t122 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2588\u2588 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[13] = t122; - } else { - t122 = $2[13]; - } - let t132; - let t142; - let t152; - if ($2[14] === Symbol.for("react.memo_cache_sentinel")) { - t132 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2588\u2588\u2592\u2592\u2588\u2588 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - t142 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2592\u2592 \u2588\u2588 \u2592" - }, undefined, false, undefined, this); - t152 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2592\u2592\u2591\u2591\u2592\u2592 \u2592 \u2592\u2592" - }, undefined, false, undefined, this); - $2[14] = t132; - $2[15] = t142; - $2[16] = t152; - } else { - t132 = $2[14]; - t142 = $2[15]; - t152 = $2[16]; - } - let t162; - if ($2[17] === Symbol.for("react.memo_cache_sentinel")) { - t162 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2597" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_background", - backgroundColor: "clawd_body", - children: [ - " ", - "\u2597", - " ", - "\u2596", - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2596" - }, undefined, false, undefined, this), - " \u2592\u2592 \u2592\u2592 " - ] - }, undefined, true, undefined, this); - $2[17] = t162; - } else { - t162 = $2[17]; - } - let t172; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t172 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " ".repeat(9) - }, undefined, false, undefined, this), - " \u2591 \u2592 " - ] - }, undefined, true, undefined, this); - $2[18] = t172; - } else { - t172 = $2[18]; - } - let t182; - if ($2[19] === Symbol.for("react.memo_cache_sentinel")) { - t182 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2591\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2592\u2026\u2026\u2026\u2026" - ] - }, undefined, true, undefined, this); - $2[19] = t182; - } else { - t182 = $2[19]; - } - let t192; - if ($2[20] !== t33) { - t192 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedBox_default, { - width: WELCOME_V2_WIDTH, - children: /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - t33, - t42, - t52, - t62, - t72, - t82, - t92, - t102, - t112, - t122, - t132, - t142, - t152, - t162, - t172, - t182 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[20] = t33; - $2[21] = t192; - } else { - t192 = $2[21]; - } - return t192; - } - let t1; - if ($2[22] !== welcomeMessage) { - t1 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "claude", - children: [ - welcomeMessage, - " " - ] - }, undefined, true, undefined, this); - $2[22] = welcomeMessage; - $2[23] = t1; - } else { - t1 = $2[23]; - } - let t22; - if ($2[24] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "v", - MACRO.VERSION, - " " - ] - }, undefined, true, undefined, this); - $2[24] = t22; - } else { - t22 = $2[24]; - } - let t32; - if ($2[25] !== t1) { - t32 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - t1, - t22 - ] - }, undefined, true, undefined, this); - $2[25] = t1; - $2[26] = t32; - } else { - t32 = $2[26]; - } - let t4; - let t5; - let t6; - let t7; - let t8; - let t9; - if ($2[27] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026" - }, undefined, false, undefined, this); - t5 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this); - t6 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " * \u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2591 " - }, undefined, false, undefined, this); - t7 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " * \u2588\u2588\u2588\u2593\u2591 \u2591\u2591 " - }, undefined, false, undefined, this); - t8 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591 \u2588\u2588\u2588\u2593\u2591 " - }, undefined, false, undefined, this); - t9 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2588\u2588\u2588\u2593\u2591 " - }, undefined, false, undefined, this); - $2[27] = t4; - $2[28] = t5; - $2[29] = t6; - $2[30] = t7; - $2[31] = t8; - $2[32] = t9; - } else { - t4 = $2[27]; - t5 = $2[28]; - t6 = $2[29]; - t7 = $2[30]; - t8 = $2[31]; - t9 = $2[32]; - } - let t10; - let t11; - let t12; - let t13; - let t14; - if ($2[33] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - bold: true, - children: "*" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2588\u2588\u2593\u2591\u2591 \u2593 " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - t11 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " \u2591\u2593\u2593\u2588\u2588\u2588\u2593\u2593\u2591 " - }, undefined, false, undefined, this); - t12 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " * \u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t13 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - t14 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: " \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 " - }, undefined, false, undefined, this); - $2[33] = t10; - $2[34] = t11; - $2[35] = t12; - $2[36] = t13; - $2[37] = t14; - } else { - t10 = $2[33]; - t11 = $2[34]; - t12 = $2[35]; - t13 = $2[36]; - t14 = $2[37]; - } - let t15; - if ($2[38] === Symbol.for("react.memo_cache_sentinel")) { - t15 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - dimColor: true, - children: "*" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[38] = t15; - } else { - t15 = $2[38]; - } - let t16; - if ($2[39] === Symbol.for("react.memo_cache_sentinel")) { - t16 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2597" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_background", - backgroundColor: "clawd_body", - children: [ - " ", - "\u2597", - " ", - "\u2596", - " " - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - color: "clawd_body", - children: "\u2596" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - bold: true, - children: "*" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[39] = t16; - } else { - t16 = $2[39]; - } - let t17; - if ($2[40] === Symbol.for("react.memo_cache_sentinel")) { - t17 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - " ", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " ".repeat(9) - }, undefined, false, undefined, this), - " * " - ] - }, undefined, true, undefined, this); - $2[40] = t17; - } else { - t17 = $2[40]; - } - let t18; - if ($2[41] === Symbol.for("react.memo_cache_sentinel")) { - t18 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026", - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: " " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - backgroundColor: "clawd_body", - children: " " - }, undefined, false, undefined, this), - "\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026" - ] - }, undefined, true, undefined, this); - $2[41] = t18; - } else { - t18 = $2[41]; - } - let t19; - if ($2[42] !== t32) { - t19 = /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedBox_default, { - width: WELCOME_V2_WIDTH, - children: /* @__PURE__ */ jsx_dev_runtime475.jsxDEV(ThemedText, { - children: [ - t32, - t4, - t5, - t6, - t7, - t8, - t9, - t10, - t11, - t12, - t13, - t14, - t15, - t16, - t17, - t18 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[42] = t32; - $2[43] = t19; - } else { - t19 = $2[43]; - } - return t19; -} -var import_compiler_runtime374, jsx_dev_runtime475, WELCOME_V2_WIDTH = 58; -var init_WelcomeV2 = __esm(() => { - init_ink2(); - init_env(); - import_compiler_runtime374 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime475 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/ui/OrderedListItem.tsx -function OrderedListItem(t0) { - const $2 = import_compiler_runtime375.c(7); - const { - children - } = t0; - const { - marker - } = import_react321.useContext(OrderedListItemContext); - let t1; - if ($2[0] !== marker) { - t1 = /* @__PURE__ */ jsx_dev_runtime476.jsxDEV(ThemedText, { - dimColor: true, - children: marker - }, undefined, false, undefined, this); - $2[0] = marker; - $2[1] = t1; - } else { - t1 = $2[1]; - } - let t22; - if ($2[2] !== children) { - t22 = /* @__PURE__ */ jsx_dev_runtime476.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children - }, undefined, false, undefined, this); - $2[2] = children; - $2[3] = t22; - } else { - t22 = $2[3]; - } - let t32; - if ($2[4] !== t1 || $2[5] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime476.jsxDEV(ThemedBox_default, { - gap: 1, - children: [ - t1, - t22 - ] - }, undefined, true, undefined, this); - $2[4] = t1; - $2[5] = t22; - $2[6] = t32; - } else { - t32 = $2[6]; - } - return t32; -} -var import_compiler_runtime375, import_react321, jsx_dev_runtime476, OrderedListItemContext; -var init_OrderedListItem = __esm(() => { - init_ink2(); - import_compiler_runtime375 = __toESM(require_compiler_runtime(), 1); - import_react321 = __toESM(require_react(), 1); - jsx_dev_runtime476 = __toESM(require_jsx_dev_runtime(), 1); - OrderedListItemContext = import_react321.createContext({ - marker: "" - }); -}); - -// src/components/ui/OrderedList.tsx -function OrderedListComponent(t0) { - const $2 = import_compiler_runtime376.c(9); - const { - children - } = t0; - const { - marker: parentMarker - } = import_react322.useContext(OrderedListContext); - let numberOfItems = 0; - for (const child of import_react322.default.Children.toArray(children)) { - if (!import_react322.isValidElement(child) || child.type !== OrderedListItem) { - continue; - } - numberOfItems++; - } - const maxMarkerWidth = String(numberOfItems).length; - let t1; - if ($2[0] !== children || $2[1] !== maxMarkerWidth || $2[2] !== parentMarker) { - let t23; - if ($2[4] !== maxMarkerWidth || $2[5] !== parentMarker) { - t23 = (child_0, index2) => { - if (!import_react322.isValidElement(child_0) || child_0.type !== OrderedListItem) { - return child_0; - } - const paddedMarker = `${String(index2 + 1).padStart(maxMarkerWidth)}.`; - const marker = `${parentMarker}${paddedMarker}`; - return /* @__PURE__ */ jsx_dev_runtime477.jsxDEV(OrderedListContext.Provider, { - value: { - marker - }, - children: /* @__PURE__ */ jsx_dev_runtime477.jsxDEV(OrderedListItemContext.Provider, { - value: { - marker - }, - children: child_0 - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - }; - $2[4] = maxMarkerWidth; - $2[5] = parentMarker; - $2[6] = t23; - } else { - t23 = $2[6]; - } - t1 = import_react322.default.Children.map(children, t23); - $2[0] = children; - $2[1] = maxMarkerWidth; - $2[2] = parentMarker; - $2[3] = t1; - } else { - t1 = $2[3]; - } - let t22; - if ($2[7] !== t1) { - t22 = /* @__PURE__ */ jsx_dev_runtime477.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: t1 - }, undefined, false, undefined, this); - $2[7] = t1; - $2[8] = t22; - } else { - t22 = $2[8]; - } - return t22; -} -var import_compiler_runtime376, import_react322, jsx_dev_runtime477, OrderedListContext, OrderedList; -var init_OrderedList = __esm(() => { - init_ink2(); - init_OrderedListItem(); - import_compiler_runtime376 = __toESM(require_compiler_runtime(), 1); - import_react322 = __toESM(require_react(), 1); - jsx_dev_runtime477 = __toESM(require_jsx_dev_runtime(), 1); - OrderedListContext = import_react322.createContext({ - marker: "" - }); - OrderedListComponent.Item = OrderedListItem; - OrderedList = OrderedListComponent; -}); - -// src/components/Onboarding.tsx -var exports_Onboarding = {}; -__export(exports_Onboarding, { - SkippableStep: () => SkippableStep, - Onboarding: () => Onboarding -}); -function Onboarding({ - onDone -}) { - const [currentStepIndex, setCurrentStepIndex] = import_react323.useState(0); - const [skipOAuth, setSkipOAuth] = import_react323.useState(false); - const [oauthEnabled] = import_react323.useState(() => isAnthropicAuthEnabled()); - const [theme2, setTheme] = useTheme(); - import_react323.useEffect(() => { - logEvent("tengu_began_setup", { - oauthEnabled - }); - }, [oauthEnabled]); - function goToNextStep() { - if (currentStepIndex < steps.length - 1) { - const nextIndex = currentStepIndex + 1; - setCurrentStepIndex(nextIndex); - logEvent("tengu_onboarding_step", { - oauthEnabled, - stepId: steps[nextIndex]?.id - }); - } else { - onDone(); - } - } - function handleThemeSelection(newTheme) { - setTheme(newTheme); - goToNextStep(); - } - const exitState = useExitOnCtrlCDWithKeybindings(); - const themeStep = /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - marginX: 1, - children: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemePicker, { - onThemeSelect: handleThemeSelection, - showIntroText: true, - helpText: "To change this later, run /theme", - hideEscToCancel: true, - skipExitHandling: true - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - const securityStep = /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - paddingLeft: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - bold: true, - children: "Security notes:" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 70, - children: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(OrderedList, { - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(OrderedList.Item, { - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - children: "Claude can make mistakes" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - dimColor: true, - wrap: "wrap", - children: [ - "You should always review Claude's responses, especially when", - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(Newline, {}, undefined, false, undefined, this), - "running code.", - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(Newline, {}, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(OrderedList.Item, { - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - children: "Due to prompt injection risks, only use it with code you trust" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - dimColor: true, - wrap: "wrap", - children: [ - "For more details see:", - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(Newline, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/security" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(PressEnterToContinue, {}, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - const preflightStep = /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(PreflightStep, { - onSuccess: goToNextStep - }, undefined, false, undefined, this); - const apiKeyNeedingApproval = import_react323.useMemo(() => { - if (!process.env.ANTHROPIC_API_KEY || isRunningOnHomespace()) { - return ""; - } - const customApiKeyTruncated = normalizeApiKeyForConfig(process.env.ANTHROPIC_API_KEY); - if (getCustomApiKeyStatus(customApiKeyTruncated) === "new") { - return customApiKeyTruncated; - } - }, []); - function handleApiKeyDone(approved) { - if (approved) { - setSkipOAuth(true); - } - goToNextStep(); - } - const steps = []; - if (oauthEnabled) { - steps.push({ - id: "preflight", - component: preflightStep - }); - } - steps.push({ - id: "theme", - component: themeStep - }); - if (apiKeyNeedingApproval) { - steps.push({ - id: "api-key", - component: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ApproveApiKey, { - customApiKeyTruncated: apiKeyNeedingApproval, - onDone: handleApiKeyDone - }, undefined, false, undefined, this) - }); - } - if (oauthEnabled) { - steps.push({ - id: "oauth", - component: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(SkippableStep, { - skip: skipOAuth, - onSkip: goToNextStep, - children: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ConsoleOAuthFlow, { - onDone: goToNextStep - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }); - } - steps.push({ - id: "security", - component: securityStep - }); - if (shouldOfferTerminalSetup()) { - steps.push({ - id: "terminal-setup", - component: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - paddingLeft: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - bold: true, - children: "Use Claude Code's terminal setup?" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - flexDirection: "column", - width: 70, - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - children: [ - "For the optimal coding experience, enable the recommended settings", - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(Newline, {}, undefined, false, undefined, this), - "for your terminal:", - " ", - env2.terminal === "Apple_Terminal" ? "Option+Enter for newlines and visual bell" : "Shift+Enter for newlines" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(Select, { - options: [{ - label: "Yes, use recommended settings", - value: "install" - }, { - label: "No, maybe later with /terminal-setup", - value: "no" - }], - onChange: (value) => { - if (value === "install") { - setupTerminal(theme2).catch(() => {}).finally(goToNextStep); - } else { - goToNextStep(); - } - }, - onCancel: () => goToNextStep() - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - dimColor: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(jsx_dev_runtime478.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(jsx_dev_runtime478.Fragment, { - children: "Enter to confirm \xB7 Esc to skip" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this) - }); - } - const currentStep = steps[currentStepIndex]; - const handleSecurityContinue = import_react323.useCallback(() => { - if (currentStepIndex === steps.length - 1) { - onDone(); - } else { - goToNextStep(); - } - }, [currentStepIndex, steps.length, oauthEnabled, onDone]); - const handleTerminalSetupSkip = import_react323.useCallback(() => { - goToNextStep(); - }, [currentStepIndex, steps.length, oauthEnabled, onDone]); - useKeybindings({ - "confirm:yes": handleSecurityContinue - }, { - context: "Confirmation", - isActive: currentStep?.id === "security" - }); - useKeybindings({ - "confirm:no": handleTerminalSetupSkip - }, { - context: "Confirmation", - isActive: currentStep?.id === "terminal-setup" - }); - return /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(WelcomeV2, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - currentStep?.component, - exitState.pending && /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedBox_default, { - padding: 1, - children: /* @__PURE__ */ jsx_dev_runtime478.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -function SkippableStep(t0) { - const $2 = import_compiler_runtime377.c(4); - const { - skip, - onSkip, - children - } = t0; - let t1; - let t22; - if ($2[0] !== onSkip || $2[1] !== skip) { - t1 = () => { - if (skip) { - onSkip(); - } - }; - t22 = [skip, onSkip]; - $2[0] = onSkip; - $2[1] = skip; - $2[2] = t1; - $2[3] = t22; - } else { - t1 = $2[2]; - t22 = $2[3]; - } - import_react323.useEffect(t1, t22); - if (skip) { - return null; - } - return children; -} -var import_compiler_runtime377, import_react323, jsx_dev_runtime478; -var init_Onboarding = __esm(() => { - init_analytics(); - init_terminalSetup(); - init_useExitOnCtrlCDWithKeybindings(); - init_ink2(); - init_useKeybinding(); - init_auth14(); - init_authPortable(); - init_config(); - init_env(); - init_envUtils(); - init_preflightChecks(); - init_ApproveApiKey(); - init_ConsoleOAuthFlow(); - init_select(); - init_WelcomeV2(); - init_PressEnterToContinue(); - init_ThemePicker(); - init_OrderedList(); - import_compiler_runtime377 = __toESM(require_compiler_runtime(), 1); - import_react323 = __toESM(require_react(), 1); - jsx_dev_runtime478 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/TrustDialog/utils.ts -function hasHooks(settings) { - if (settings === null || settings.disableAllHooks) { - return false; - } - if (settings.statusLine) { - return true; - } - if (settings.fileSuggestion) { - return true; - } - if (!settings.hooks) { - return false; - } - for (const hookConfig of Object.values(settings.hooks)) { - if (hookConfig.length > 0) { - return true; - } - } - return false; -} -function getHooksSources() { - const sources = []; - const projectSettings = getSettingsForSource("projectSettings"); - if (hasHooks(projectSettings)) { - sources.push(".claude/settings.json"); - } - const localSettings = getSettingsForSource("localSettings"); - if (hasHooks(localSettings)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -function hasBashPermission(rules2) { - return rules2.some((rule) => rule.ruleBehavior === "allow" && (rule.ruleValue.toolName === BASH_TOOL_NAME || rule.ruleValue.toolName.startsWith(BASH_TOOL_NAME + "("))); -} -function getBashPermissionSources() { - const sources = []; - const projectRules = getPermissionRulesForSource("projectSettings"); - if (hasBashPermission(projectRules)) { - sources.push(".claude/settings.json"); - } - const localRules = getPermissionRulesForSource("localSettings"); - if (hasBashPermission(localRules)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -function hasOtelHeadersHelper(settings) { - return !!settings?.otelHeadersHelper; -} -function getOtelHeadersHelperSources() { - const sources = []; - const projectSettings = getSettingsForSource("projectSettings"); - if (hasOtelHeadersHelper(projectSettings)) { - sources.push(".claude/settings.json"); - } - const localSettings = getSettingsForSource("localSettings"); - if (hasOtelHeadersHelper(localSettings)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -function hasApiKeyHelper(settings) { - return !!settings?.apiKeyHelper; -} -function getApiKeyHelperSources() { - const sources = []; - const projectSettings = getSettingsForSource("projectSettings"); - if (hasApiKeyHelper(projectSettings)) { - sources.push(".claude/settings.json"); - } - const localSettings = getSettingsForSource("localSettings"); - if (hasApiKeyHelper(localSettings)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -function hasAwsCommands(settings) { - return !!(settings?.awsAuthRefresh || settings?.awsCredentialExport); -} -function getAwsCommandsSources() { - const sources = []; - const projectSettings = getSettingsForSource("projectSettings"); - if (hasAwsCommands(projectSettings)) { - sources.push(".claude/settings.json"); - } - const localSettings = getSettingsForSource("localSettings"); - if (hasAwsCommands(localSettings)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -function hasGcpCommands(settings) { - return !!settings?.gcpAuthRefresh; -} -function getGcpCommandsSources() { - const sources = []; - const projectSettings = getSettingsForSource("projectSettings"); - if (hasGcpCommands(projectSettings)) { - sources.push(".claude/settings.json"); - } - const localSettings = getSettingsForSource("localSettings"); - if (hasGcpCommands(localSettings)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -function hasDangerousEnvVars(settings) { - if (!settings?.env) { - return false; - } - return Object.keys(settings.env).some((key2) => !SAFE_ENV_VARS2.has(key2.toUpperCase())); -} -function getDangerousEnvVarsSources() { - const sources = []; - const projectSettings = getSettingsForSource("projectSettings"); - if (hasDangerousEnvVars(projectSettings)) { - sources.push(".claude/settings.json"); - } - const localSettings = getSettingsForSource("localSettings"); - if (hasDangerousEnvVars(localSettings)) { - sources.push(".claude/settings.local.json"); - } - return sources; -} -var init_utils17 = __esm(() => { - init_settings2(); - init_managedEnvConstants(); - init_permissionsLoader(); -}); - -// src/components/TrustDialog/TrustDialog.tsx -var exports_TrustDialog = {}; -__export(exports_TrustDialog, { - TrustDialog: () => TrustDialog -}); -import { homedir as homedir36 } from "os"; -function TrustDialog(t0) { - const $2 = import_compiler_runtime378.c(33); - const { - onDone, - commands: commands7 - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = getMcpConfigsByScope("project"); - $2[0] = t1; - } else { - t1 = $2[0]; - } - const { - servers: projectServers - } = t1; - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = Object.keys(projectServers); - $2[1] = t22; - } else { - t22 = $2[1]; - } - const hasMcpServers = t22.length > 0; - let t32; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t32 = getHooksSources(); - $2[2] = t32; - } else { - t32 = $2[2]; - } - const hooksSettingSources = t32; - const hasHooks2 = hooksSettingSources.length > 0; - let t4; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t4 = getBashPermissionSources(); - $2[3] = t4; - } else { - t4 = $2[3]; - } - const bashSettingSources = t4; - let t5; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t5 = getApiKeyHelperSources(); - $2[4] = t5; - } else { - t5 = $2[4]; - } - const apiKeyHelperSources = t5; - const hasApiKeyHelper2 = apiKeyHelperSources.length > 0; - let t6; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t6 = getAwsCommandsSources(); - $2[5] = t6; - } else { - t6 = $2[5]; - } - const awsCommandsSources = t6; - const hasAwsCommands2 = awsCommandsSources.length > 0; - let t7; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t7 = getGcpCommandsSources(); - $2[6] = t7; - } else { - t7 = $2[6]; - } - const gcpCommandsSources = t7; - const hasGcpCommands2 = gcpCommandsSources.length > 0; - let t8; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t8 = getOtelHeadersHelperSources(); - $2[7] = t8; - } else { - t8 = $2[7]; - } - const otelHeadersHelperSources = t8; - const hasOtelHeadersHelper2 = otelHeadersHelperSources.length > 0; - let t9; - if ($2[8] === Symbol.for("react.memo_cache_sentinel")) { - t9 = getDangerousEnvVarsSources(); - $2[8] = t9; - } else { - t9 = $2[8]; - } - const dangerousEnvVarsSources = t9; - const hasDangerousEnvVars2 = dangerousEnvVarsSources.length > 0; - let t10; - if ($2[9] !== commands7) { - t10 = commands7?.some(_temp2101) ?? false; - $2[9] = commands7; - $2[10] = t10; - } else { - t10 = $2[10]; - } - const hasSlashCommandBash = t10; - let t11; - if ($2[11] !== commands7) { - t11 = commands7?.some(_temp442) ?? false; - $2[11] = commands7; - $2[12] = t11; - } else { - t11 = $2[12]; - } - const hasSkillsBash = t11; - const hasAnyBashExecution = bashSettingSources.length > 0 || hasSlashCommandBash || hasSkillsBash; - const hasTrustDialogAccepted = checkHasTrustDialogAccepted(); - let t12; - let t13; - if ($2[13] !== hasAnyBashExecution) { - t12 = () => { - const isHomeDir = homedir36() === getCwd(); - logEvent("tengu_trust_dialog_shown", { - isHomeDir, - hasMcpServers, - hasHooks: hasHooks2, - hasBashExecution: hasAnyBashExecution, - hasApiKeyHelper: hasApiKeyHelper2, - hasAwsCommands: hasAwsCommands2, - hasGcpCommands: hasGcpCommands2, - hasOtelHeadersHelper: hasOtelHeadersHelper2, - hasDangerousEnvVars: hasDangerousEnvVars2 - }); - }; - t13 = [hasMcpServers, hasHooks2, hasAnyBashExecution, hasApiKeyHelper2, hasAwsCommands2, hasGcpCommands2, hasOtelHeadersHelper2, hasDangerousEnvVars2]; - $2[13] = hasAnyBashExecution; - $2[14] = t12; - $2[15] = t13; - } else { - t12 = $2[14]; - t13 = $2[15]; - } - import_react324.default.useEffect(t12, t13); - let t14; - if ($2[16] !== hasAnyBashExecution || $2[17] !== onDone) { - t14 = function onChange2(value) { - if (value === "exit") { - gracefulShutdownSync(1); - return; - } - const isHomeDir_0 = homedir36() === getCwd(); - logEvent("tengu_trust_dialog_accept", { - isHomeDir: isHomeDir_0, - hasMcpServers, - hasHooks: hasHooks2, - hasBashExecution: hasAnyBashExecution, - hasApiKeyHelper: hasApiKeyHelper2, - hasAwsCommands: hasAwsCommands2, - hasGcpCommands: hasGcpCommands2, - hasOtelHeadersHelper: hasOtelHeadersHelper2, - hasDangerousEnvVars: hasDangerousEnvVars2 - }); - if (isHomeDir_0) { - setSessionTrustAccepted(true); - } else { - saveCurrentProjectConfig(_temp530); - } - onDone(); - }; - $2[16] = hasAnyBashExecution; - $2[17] = onDone; - $2[18] = t14; - } else { - t14 = $2[18]; - } - const onChange = t14; - const exitState = useExitOnCtrlCDWithKeybindings(_temp624); - let t15; - if ($2[19] === Symbol.for("react.memo_cache_sentinel")) { - t15 = { - context: "Confirmation" - }; - $2[19] = t15; - } else { - t15 = $2[19]; - } - useKeybinding("confirm:no", _temp721, t15); - if (hasTrustDialogAccepted) { - setTimeout(onDone); - return null; - } - let t16; - let t17; - let t18; - if ($2[20] === Symbol.for("react.memo_cache_sentinel")) { - t16 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(ThemedText, { - bold: true, - children: getFsImplementation().cwd() - }, undefined, false, undefined, this); - t17 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(ThemedText, { - children: [ - "Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what", - "'", - "s in this folder first." - ] - }, undefined, true, undefined, this); - t18 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(ThemedText, { - children: [ - "Claude Code", - "'", - "ll be able to read, edit, and execute files here." - ] - }, undefined, true, undefined, this); - $2[20] = t16; - $2[21] = t17; - $2[22] = t18; - } else { - t16 = $2[20]; - t17 = $2[21]; - t18 = $2[22]; - } - let t19; - if ($2[23] === Symbol.for("react.memo_cache_sentinel")) { - t19 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/security", - children: "Security guide" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[23] = t19; - } else { - t19 = $2[23]; - } - let t20; - if ($2[24] === Symbol.for("react.memo_cache_sentinel")) { - t20 = [{ - label: "Yes, I trust this folder", - value: "enable_all" - }, { - label: "No, exit", - value: "exit" - }]; - $2[24] = t20; - } else { - t20 = $2[24]; - } - let t21; - if ($2[25] !== onChange) { - t21 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(Select, { - options: t20, - onChange: (value_0) => onChange(value_0), - onCancel: () => onChange("exit") - }, undefined, false, undefined, this); - $2[25] = onChange; - $2[26] = t21; - } else { - t21 = $2[26]; - } - let t222; - if ($2[27] !== exitState.keyName || $2[28] !== exitState.pending) { - t222 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(ThemedText, { - dimColor: true, - children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(jsx_dev_runtime479.Fragment, { - children: [ - "Press ", - exitState.keyName, - " again to exit" - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(jsx_dev_runtime479.Fragment, { - children: "Enter to confirm \xB7 Esc to cancel" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[27] = exitState.keyName; - $2[28] = exitState.pending; - $2[29] = t222; - } else { - t222 = $2[29]; - } - let t23; - if ($2[30] !== t21 || $2[31] !== t222) { - t23 = /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(PermissionDialog, { - color: "warning", - titleColor: "warning", - title: "Accessing workspace:", - children: /* @__PURE__ */ jsx_dev_runtime479.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - paddingTop: 1, - children: [ - t16, - t17, - t18, - t19, - t21, - t222 - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[30] = t21; - $2[31] = t222; - $2[32] = t23; - } else { - t23 = $2[32]; - } - return t23; -} -function _temp721() { - gracefulShutdownSync(0); -} -function _temp624() { - return gracefulShutdownSync(1); -} -function _temp530(current) { - return { - ...current, - hasTrustDialogAccepted: true - }; -} -function _temp442(command_0) { - return command_0.type === "prompt" && (command_0.loadedFrom === "skills" || command_0.loadedFrom === "plugin") && (command_0.source === "projectSettings" || command_0.source === "localSettings" || command_0.source === "plugin") && command_0.allowedTools?.some(_temp358); -} -function _temp358(tool_0) { - return tool_0 === BASH_TOOL_NAME || tool_0.startsWith(BASH_TOOL_NAME + "("); -} -function _temp2101(command19) { - return command19.type === "prompt" && command19.loadedFrom === "commands_DEPRECATED" && (command19.source === "projectSettings" || command19.source === "localSettings") && command19.allowedTools?.some(_temp304); -} -function _temp304(tool) { - return tool === BASH_TOOL_NAME || tool.startsWith(BASH_TOOL_NAME + "("); -} -var import_compiler_runtime378, import_react324, jsx_dev_runtime479; -var init_TrustDialog = __esm(() => { - init_analytics(); - init_state(); - init_useExitOnCtrlCDWithKeybindings(); - init_ink2(); - init_useKeybinding(); - init_config9(); - init_config(); - init_cwd(); - init_fsOperations(); - init_gracefulShutdown(); - init_CustomSelect(); - init_PermissionDialog(); - init_utils17(); - import_compiler_runtime378 = __toESM(require_compiler_runtime(), 1); - import_react324 = __toESM(require_react(), 1); - jsx_dev_runtime479 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/BypassPermissionsModeDialog.tsx -var exports_BypassPermissionsModeDialog = {}; -__export(exports_BypassPermissionsModeDialog, { - BypassPermissionsModeDialog: () => BypassPermissionsModeDialog -}); -function BypassPermissionsModeDialog(t0) { - const $2 = import_compiler_runtime379.c(7); - const { - onAccept - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = []; - $2[0] = t1; - } else { - t1 = $2[0]; - } - import_react325.default.useEffect(_temp305, t1); - let t22; - if ($2[1] !== onAccept) { - t22 = function onChange2(value) { - bb3: - switch (value) { - case "accept": { - logEvent("tengu_bypass_permissions_mode_dialog_accept", {}); - updateSettingsForSource("userSettings", { - skipDangerousModePermissionPrompt: true - }); - onAccept(); - break bb3; - } - case "decline": { - gracefulShutdownSync(1); - } - } - }; - $2[1] = onAccept; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const onChange = t22; - const handleEscape = _temp2102; - let t32; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(ThemedText, { - children: [ - "In Bypass Permissions mode, Claude Code will not ask for your approval before running potentially dangerous commands.", - /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(Newline, {}, undefined, false, undefined, this), - "This mode should only be used in a sandboxed container/VM that has restricted internet access and can easily be restored if damaged." - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(ThemedText, { - children: "By proceeding, you accept all responsibility for actions taken while running in Bypass Permissions mode." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/security" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] === Symbol.for("react.memo_cache_sentinel")) { - t4 = [{ - label: "No, exit", - value: "decline" - }, { - label: "Yes, I accept", - value: "accept" - }]; - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] !== onChange) { - t5 = /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(Dialog, { - title: "WARNING: Claude Code running in Bypass Permissions mode", - color: "error", - onCancel: handleEscape, - children: [ - t32, - /* @__PURE__ */ jsx_dev_runtime480.jsxDEV(Select, { - options: t4, - onChange: (value_0) => onChange(value_0) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[5] = onChange; - $2[6] = t5; - } else { - t5 = $2[6]; - } - return t5; -} -function _temp2102() { - gracefulShutdownSync(0); -} -function _temp305() { - logEvent("tengu_bypass_permissions_mode_dialog_shown", {}); -} -var import_compiler_runtime379, import_react325, jsx_dev_runtime480; -var init_BypassPermissionsModeDialog = __esm(() => { - init_analytics(); - init_ink2(); - init_gracefulShutdown(); - init_settings2(); - init_CustomSelect(); - init_Dialog(); - import_compiler_runtime379 = __toESM(require_compiler_runtime(), 1); - import_react325 = __toESM(require_react(), 1); - jsx_dev_runtime480 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/ClaudeInChromeOnboarding.tsx -var exports_ClaudeInChromeOnboarding = {}; -__export(exports_ClaudeInChromeOnboarding, { - ClaudeInChromeOnboarding: () => ClaudeInChromeOnboarding -}); -function ClaudeInChromeOnboarding(t0) { - const $2 = import_compiler_runtime380.c(20); - const { - onDone - } = t0; - const [isExtensionInstalled, setIsExtensionInstalled] = import_react326.default.useState(false); - let t1; - let t22; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - logEvent("tengu_claude_in_chrome_onboarding_shown", {}); - isChromeExtensionInstalled().then(setIsExtensionInstalled); - saveGlobalConfig(_temp306); - }; - t22 = []; - $2[0] = t1; - $2[1] = t22; - } else { - t1 = $2[0]; - t22 = $2[1]; - } - import_react326.default.useEffect(t1, t22); - let t32; - if ($2[2] !== onDone) { - t32 = (_input, key2) => { - if (key2.return) { - onDone(); - } - }; - $2[2] = onDone; - $2[3] = t32; - } else { - t32 = $2[3]; - } - use_input_default(t32); - let t4; - if ($2[4] !== isExtensionInstalled) { - t4 = !isExtensionInstalled && /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(jsx_dev_runtime481.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(Newline, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(Newline, {}, undefined, false, undefined, this), - "Requires the Chrome extension. Get started at", - " ", - /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(Link, { - url: CHROME_EXTENSION_URL2 - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[4] = isExtensionInstalled; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== t4) { - t5 = /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(ThemedText, { - children: [ - "Claude in Chrome works with the Chrome extension to let you control your browser directly from Claude Code. You can navigate websites, fill forms, capture screenshots, record GIFs, and debug with console logs and network requests.", - t4 - ] - }, undefined, true, undefined, this); - $2[6] = t4; - $2[7] = t5; - } else { - t5 = $2[7]; - } - let t6; - if ($2[8] !== isExtensionInstalled) { - t6 = isExtensionInstalled && /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(jsx_dev_runtime481.Fragment, { - children: [ - " ", - "(", - /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(Link, { - url: CHROME_PERMISSIONS_URL2 - }, undefined, false, undefined, this), - ")" - ] - }, undefined, true, undefined, this); - $2[8] = isExtensionInstalled; - $2[9] = t6; - } else { - t6 = $2[9]; - } - let t7; - if ($2[10] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on", - t6, - "." - ] - }, undefined, true, undefined, this); - $2[10] = t6; - $2[11] = t7; - } else { - t7 = $2[11]; - } - let t8; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(ThemedText, { - bold: true, - color: "chromeYellow", - children: "/chrome" - }, undefined, false, undefined, this); - $2[12] = t8; - } else { - t8 = $2[12]; - } - let t9; - if ($2[13] === Symbol.for("react.memo_cache_sentinel")) { - t9 = /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "For more info, use", - " ", - t8, - " ", - "or visit ", - /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/chrome" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[13] = t9; - } else { - t9 = $2[13]; - } - let t10; - if ($2[14] !== t5 || $2[15] !== t7) { - t10 = /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t5, - t7, - t9 - ] - }, undefined, true, undefined, this); - $2[14] = t5; - $2[15] = t7; - $2[16] = t10; - } else { - t10 = $2[16]; - } - let t11; - if ($2[17] !== onDone || $2[18] !== t10) { - t11 = /* @__PURE__ */ jsx_dev_runtime481.jsxDEV(Dialog, { - title: "Claude in Chrome (Beta)", - onCancel: onDone, - color: "chromeYellow", - children: t10 - }, undefined, false, undefined, this); - $2[17] = onDone; - $2[18] = t10; - $2[19] = t11; - } else { - t11 = $2[19]; - } - return t11; -} -function _temp306(current) { - return { - ...current, - hasCompletedClaudeInChromeOnboarding: true - }; -} -var import_compiler_runtime380, import_react326, jsx_dev_runtime481, CHROME_EXTENSION_URL2 = "https://claude.ai/chrome", CHROME_PERMISSIONS_URL2 = "https://clau.de/chrome/permissions"; -var init_ClaudeInChromeOnboarding = __esm(() => { - init_analytics(); - init_ink2(); - init_setup2(); - init_config(); - init_Dialog(); - import_compiler_runtime380 = __toESM(require_compiler_runtime(), 1); - import_react326 = __toESM(require_react(), 1); - jsx_dev_runtime481 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/InvalidSettingsDialog.tsx -var exports_InvalidSettingsDialog = {}; -__export(exports_InvalidSettingsDialog, { - InvalidSettingsDialog: () => InvalidSettingsDialog -}); -function InvalidSettingsDialog(t0) { - const $2 = import_compiler_runtime381.c(13); - const { - settingsErrors, - onContinue, - onExit: onExit2 - } = t0; - let t1; - if ($2[0] !== onContinue || $2[1] !== onExit2) { - t1 = function handleSelect2(value) { - if (value === "exit") { - onExit2(); - } else { - onContinue(); - } - }; - $2[0] = onContinue; - $2[1] = onExit2; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const handleSelect = t1; - let t22; - if ($2[3] !== settingsErrors) { - t22 = /* @__PURE__ */ jsx_dev_runtime483.jsxDEV(ValidationErrorsList, { - errors: settingsErrors - }, undefined, false, undefined, this); - $2[3] = settingsErrors; - $2[4] = t22; - } else { - t22 = $2[4]; - } - let t32; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime483.jsxDEV(ThemedText, { - dimColor: true, - children: "Files with errors are skipped entirely, not just the invalid settings." - }, undefined, false, undefined, this); - $2[5] = t32; - } else { - t32 = $2[5]; - } - let t4; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t4 = [{ - label: "Exit and fix manually", - value: "exit" - }, { - label: "Continue without these settings", - value: "continue" - }]; - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== handleSelect) { - t5 = /* @__PURE__ */ jsx_dev_runtime483.jsxDEV(Select, { - options: t4, - onChange: handleSelect - }, undefined, false, undefined, this); - $2[7] = handleSelect; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== onExit2 || $2[10] !== t22 || $2[11] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime483.jsxDEV(Dialog, { - title: "Settings Error", - onCancel: onExit2, - color: "warning", - children: [ - t22, - t32, - t5 - ] - }, undefined, true, undefined, this); - $2[9] = onExit2; - $2[10] = t22; - $2[11] = t5; - $2[12] = t6; - } else { - t6 = $2[12]; - } - return t6; -} -var import_compiler_runtime381, jsx_dev_runtime483; -var init_InvalidSettingsDialog = __esm(() => { - init_ink2(); - init_CustomSelect(); - init_Dialog(); - init_ValidationErrorsList(); - import_compiler_runtime381 = __toESM(require_compiler_runtime(), 1); - jsx_dev_runtime483 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/hooks/useTeleportResume.tsx -function useTeleportResume(source) { - const $2 = import_compiler_runtime382.c(8); - const [isResuming, setIsResuming] = import_react327.useState(false); - const [error46, setError] = import_react327.useState(null); - const [selectedSession, setSelectedSession] = import_react327.useState(null); - let t0; - if ($2[0] !== source) { - t0 = async (session2) => { - setIsResuming(true); - setError(null); - setSelectedSession(session2); - logEvent("tengu_teleport_resume_session", { - source, - session_id: session2.id - }); - try { - const result = await teleportResumeCodeSession(session2.id); - setTeleportedSessionInfo({ - sessionId: session2.id - }); - setIsResuming(false); - return result; - } catch (t12) { - const err2 = t12; - const teleportError = { - message: err2 instanceof TeleportOperationError ? err2.message : errorMessage(err2), - formattedMessage: err2 instanceof TeleportOperationError ? err2.formattedMessage : undefined, - isOperationError: err2 instanceof TeleportOperationError - }; - setError(teleportError); - setIsResuming(false); - return null; - } - }; - $2[0] = source; - $2[1] = t0; - } else { - t0 = $2[1]; - } - const resumeSession = t0; - let t1; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t1 = () => { - setError(null); - }; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const clearError = t1; - let t22; - if ($2[3] !== error46 || $2[4] !== isResuming || $2[5] !== resumeSession || $2[6] !== selectedSession) { - t22 = { - resumeSession, - isResuming, - error: error46, - selectedSession, - clearError - }; - $2[3] = error46; - $2[4] = isResuming; - $2[5] = resumeSession; - $2[6] = selectedSession; - $2[7] = t22; - } else { - t22 = $2[7]; - } - return t22; -} -var import_compiler_runtime382, import_react327; -var init_useTeleportResume = __esm(() => { - init_state(); - init_analytics(); - init_errors(); - init_teleport(); - import_compiler_runtime382 = __toESM(require_compiler_runtime(), 1); - import_react327 = __toESM(require_react(), 1); -}); - -// src/components/ResumeTask.tsx -function ResumeTask({ - onSelect, - onCancel, - isEmbedded = false -}) { - const { - rows - } = useTerminalSize(); - const [sessions, setSessions] = import_react328.useState([]); - const [currentRepo, setCurrentRepo] = import_react328.useState(null); - const [loading, setLoading] = import_react328.useState(true); - const [loadErrorType, setLoadErrorType] = import_react328.useState(null); - const [retrying, setRetrying] = import_react328.useState(false); - const [hasCompletedTeleportErrorFlow, setHasCompletedTeleportErrorFlow] = import_react328.useState(false); - const [focusedIndex, setFocusedIndex] = import_react328.useState(1); - const escKey = useShortcutDisplay("confirm:no", "Confirmation", "Esc"); - const loadSessions = import_react328.useCallback(async () => { - try { - setLoading(true); - setLoadErrorType(null); - const detectedRepo = await detectCurrentRepository(); - setCurrentRepo(detectedRepo); - logForDebugging(`Current repository: ${detectedRepo || "not detected"}`); - const codeSessions = await fetchCodeSessionsFromSessionsAPI(); - let filteredSessions = codeSessions; - if (detectedRepo) { - filteredSessions = codeSessions.filter((session2) => { - if (!session2.repo) - return false; - const sessionRepo = `${session2.repo.owner.login}/${session2.repo.name}`; - return sessionRepo === detectedRepo; - }); - logForDebugging(`Filtered ${filteredSessions.length} sessions for repo ${detectedRepo} from ${codeSessions.length} total`); - } - const sortedSessions = [...filteredSessions].sort((a5, b5) => { - const dateA = new Date(a5.updated_at); - const dateB = new Date(b5.updated_at); - return dateB.getTime() - dateA.getTime(); - }); - setSessions(sortedSessions); - } catch (err2) { - const errorMessage4 = err2 instanceof Error ? err2.message : String(err2); - logForDebugging(`Error loading code sessions: ${errorMessage4}`); - setLoadErrorType(determineErrorType(errorMessage4)); - } finally { - setLoading(false); - setRetrying(false); - } - }, []); - const handleRetry = () => { - setRetrying(true); - loadSessions(); - }; - useKeybinding("confirm:no", onCancel, { - context: "Confirmation" - }); - use_input_default((input, key2) => { - if (key2.ctrl && input === "c") { - onCancel(); - return; - } - if (key2.ctrl && input === "r" && loadErrorType) { - handleRetry(); - return; - } - if (loadErrorType !== null && key2.return) { - onCancel(); - return; - } - }); - const handleErrorComplete = import_react328.useCallback(() => { - setHasCompletedTeleportErrorFlow(true); - loadSessions(); - }, [setHasCompletedTeleportErrorFlow, loadSessions]); - if (!hasCompletedTeleportErrorFlow) { - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(TeleportError, { - onComplete: handleErrorComplete - }, undefined, false, undefined, this); - } - if (loading) { - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "column", - padding: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: "Loading Claude Code sessions\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: retrying ? "Retrying\u2026" : "Fetching your Claude Code sessions\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - if (loadErrorType) { - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "column", - padding: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - color: "error", - children: "Error loading Claude Code sessions" - }, undefined, false, undefined, this), - renderErrorSpecificGuidance(loadErrorType), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: "Ctrl+R" - }, undefined, false, undefined, this), - " to retry \xB7 Press", - " ", - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: escKey - }, undefined, false, undefined, this), - " to cancel" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - } - if (sessions.length === 0) { - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "column", - padding: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: [ - "No Claude Code sessions found", - currentRepo && /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - children: [ - " for ", - currentRepo - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: escKey - }, undefined, false, undefined, this), - " to cancel" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - const sessionMetadata = sessions.map((session_0) => ({ - ...session_0, - timeString: formatRelativeTime(new Date(session_0.updated_at)) - })); - const maxTimeStringLength = Math.max(UPDATED_STRING.length, ...sessionMetadata.map((meta) => meta.timeString.length)); - const options2 = sessionMetadata.map(({ - timeString, - title, - id - }) => { - const paddedTime = timeString.padEnd(maxTimeStringLength, " "); - return { - label: `${paddedTime} ${title}`, - value: id - }; - }); - const layoutOverhead = 7; - const maxVisibleOptions = Math.max(1, isEmbedded ? Math.min(sessions.length, 5, rows - 6 - layoutOverhead) : Math.min(sessions.length, rows - 1 - layoutOverhead)); - const maxHeight = maxVisibleOptions + layoutOverhead; - const showScrollPosition = sessions.length > maxVisibleOptions; - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "column", - padding: 1, - height: maxHeight, - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: [ - "Select a session to resume", - showScrollPosition && /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " ", - "(", - focusedIndex, - " of ", - sessions.length, - ")" - ] - }, undefined, true, undefined, this), - currentRepo && /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: [ - " (", - currentRepo, - ")" - ] - }, undefined, true, undefined, this), - ":" - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - flexGrow: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: [ - UPDATED_STRING.padEnd(maxTimeStringLength, " "), - SPACE_BETWEEN_TABLE_COLUMNS, - "Session Title" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(Select, { - visibleOptionCount: maxVisibleOptions, - options: options2, - onChange: (value) => { - const session_1 = sessions.find((s4) => s4.id === value); - if (session_1) { - onSelect(session_1); - } - }, - onFocus: (value_0) => { - const index2 = options2.findIndex((o5) => o5.value === value_0); - if (index2 >= 0) { - setFocusedIndex(index2 + 1); - } - } - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(KeyboardShortcutHint, { - shortcut: "\u2191/\u2193", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "confirm" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); -} -function determineErrorType(errorMessage4) { - const message = errorMessage4.toLowerCase(); - if (message.includes("fetch") || message.includes("network") || message.includes("timeout")) { - return "network"; - } - if (message.includes("auth") || message.includes("token") || message.includes("permission") || message.includes("oauth") || message.includes("not authenticated") || message.includes("/login") || message.includes("console account") || message.includes("403")) { - return "auth"; - } - if (message.includes("api") || message.includes("rate limit") || message.includes("500") || message.includes("529")) { - return "api"; - } - return "other"; -} -function renderErrorSpecificGuidance(errorType) { - switch (errorType) { - case "network": - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - marginY: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: "Check your internet connection" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - case "auth": - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - marginY: 1, - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: "Teleport requires a Claude account" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Run ", - /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - bold: true, - children: "/login" - }, undefined, false, undefined, this), - ' and select "Claude account with subscription"' - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - case "api": - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - marginY: 1, - flexDirection: "column", - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: "Sorry, Claude encountered an error" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - case "other": - return /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedBox_default, { - marginY: 1, - flexDirection: "row", - children: /* @__PURE__ */ jsx_dev_runtime484.jsxDEV(ThemedText, { - dimColor: true, - children: "Sorry, Claude Code encountered an error" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - } -} -var import_react328, jsx_dev_runtime484, UPDATED_STRING = "Updated", SPACE_BETWEEN_TABLE_COLUMNS = " "; -var init_ResumeTask = __esm(() => { - init_useTerminalSize(); - init_api2(); - init_ink2(); - init_useKeybinding(); - init_useShortcutDisplay(); - init_debug(); - init_detectRepository(); - init_format(); - init_ConfigurableShortcutHint(); - init_CustomSelect(); - init_Byline(); - init_KeyboardShortcutHint(); - init_Spinner2(); - init_TeleportError(); - import_react328 = __toESM(require_react(), 1); - jsx_dev_runtime484 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/TeleportResumeWrapper.tsx -var exports_TeleportResumeWrapper = {}; -__export(exports_TeleportResumeWrapper, { - TeleportResumeWrapper: () => TeleportResumeWrapper -}); -function TeleportResumeWrapper(t0) { - const $2 = import_compiler_runtime383.c(25); - const { - onComplete, - onCancel, - onError, - isEmbedded: t1, - source - } = t0; - const isEmbedded = t1 === undefined ? false : t1; - const { - resumeSession, - isResuming, - error: error46, - selectedSession - } = useTeleportResume(source); - let t22; - let t32; - if ($2[0] !== source) { - t22 = () => { - logEvent("tengu_teleport_started", { - source - }); - }; - t32 = [source]; - $2[0] = source; - $2[1] = t22; - $2[2] = t32; - } else { - t22 = $2[1]; - t32 = $2[2]; - } - import_react329.useEffect(t22, t32); - let t4; - if ($2[3] !== error46 || $2[4] !== onComplete || $2[5] !== onError || $2[6] !== resumeSession) { - t4 = async (session2) => { - const result = await resumeSession(session2); - if (result) { - onComplete(result); - } else { - if (error46) { - if (onError) { - onError(error46.message, error46.formattedMessage); - } - } - } - }; - $2[3] = error46; - $2[4] = onComplete; - $2[5] = onError; - $2[6] = resumeSession; - $2[7] = t4; - } else { - t4 = $2[7]; - } - const handleSelect = t4; - let t5; - if ($2[8] !== onCancel) { - t5 = () => { - logEvent("tengu_teleport_cancelled", {}); - onCancel(); - }; - $2[8] = onCancel; - $2[9] = t5; - } else { - t5 = $2[9]; - } - const handleCancel = t5; - const t6 = !!error46 && !onError; - let t7; - if ($2[10] !== t6) { - t7 = { - context: "Global", - isActive: t6 - }; - $2[10] = t6; - $2[11] = t7; - } else { - t7 = $2[11]; - } - useKeybinding("app:interrupt", handleCancel, t7); - if (isResuming && selectedSession) { - let t82; - if ($2[12] === Symbol.for("react.memo_cache_sentinel")) { - t82 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedText, { - bold: true, - children: "Resuming session\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[12] = t82; - } else { - t82 = $2[12]; - } - let t9; - if ($2[13] !== selectedSession.title) { - t9 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedBox_default, { - flexDirection: "column", - padding: 1, - children: [ - t82, - /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedText, { - dimColor: true, - children: [ - 'Loading "', - selectedSession.title, - '"\u2026' - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[13] = selectedSession.title; - $2[14] = t9; - } else { - t9 = $2[14]; - } - return t9; - } - if (error46 && !onError) { - let t82; - if ($2[15] === Symbol.for("react.memo_cache_sentinel")) { - t82 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedText, { - bold: true, - color: "error", - children: "Failed to resume session" - }, undefined, false, undefined, this); - $2[15] = t82; - } else { - t82 = $2[15]; - } - let t9; - if ($2[16] !== error46.message) { - t9 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedText, { - dimColor: true, - children: error46.message - }, undefined, false, undefined, this); - $2[16] = error46.message; - $2[17] = t9; - } else { - t9 = $2[17]; - } - let t10; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t10 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Press ", - /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedText, { - bold: true, - children: "Esc" - }, undefined, false, undefined, this), - " to cancel" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[18] = t10; - } else { - t10 = $2[18]; - } - let t11; - if ($2[19] !== t9) { - t11 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ThemedBox_default, { - flexDirection: "column", - padding: 1, - children: [ - t82, - t9, - t10 - ] - }, undefined, true, undefined, this); - $2[19] = t9; - $2[20] = t11; - } else { - t11 = $2[20]; - } - return t11; - } - let t8; - if ($2[21] !== handleCancel || $2[22] !== handleSelect || $2[23] !== isEmbedded) { - t8 = /* @__PURE__ */ jsx_dev_runtime485.jsxDEV(ResumeTask, { - onSelect: handleSelect, - onCancel: handleCancel, - isEmbedded - }, undefined, false, undefined, this); - $2[21] = handleCancel; - $2[22] = handleSelect; - $2[23] = isEmbedded; - $2[24] = t8; - } else { - t8 = $2[24]; - } - return t8; -} -var import_compiler_runtime383, import_react329, jsx_dev_runtime485; -var init_TeleportResumeWrapper = __esm(() => { - init_analytics(); - init_useTeleportResume(); - init_ink2(); - init_useKeybinding(); - init_ResumeTask(); - init_Spinner2(); - import_compiler_runtime383 = __toESM(require_compiler_runtime(), 1); - import_react329 = __toESM(require_react(), 1); - jsx_dev_runtime485 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/components/TeleportRepoMismatchDialog.tsx -var exports_TeleportRepoMismatchDialog = {}; -__export(exports_TeleportRepoMismatchDialog, { - TeleportRepoMismatchDialog: () => TeleportRepoMismatchDialog -}); -function TeleportRepoMismatchDialog(t0) { - const $2 = import_compiler_runtime384.c(18); - const { - targetRepo, - initialPaths, - onSelectPath, - onCancel - } = t0; - const [availablePaths, setAvailablePaths] = import_react330.useState(initialPaths); - const [errorMessage4, setErrorMessage] = import_react330.useState(null); - const [validating, setValidating] = import_react330.useState(false); - let t1; - if ($2[0] !== availablePaths || $2[1] !== onCancel || $2[2] !== onSelectPath || $2[3] !== targetRepo) { - t1 = async (value) => { - if (value === "cancel") { - onCancel(); - return; - } - setValidating(true); - setErrorMessage(null); - const isValid2 = await validateRepoAtPath(value, targetRepo); - if (isValid2) { - onSelectPath(value); - return; - } - removePathFromRepo(targetRepo, value); - const updatedPaths = availablePaths.filter((p4) => p4 !== value); - setAvailablePaths(updatedPaths); - setValidating(false); - setErrorMessage(`${getDisplayPath(value)} no longer contains the correct repository. Select another path.`); - }; - $2[0] = availablePaths; - $2[1] = onCancel; - $2[2] = onSelectPath; - $2[3] = targetRepo; - $2[4] = t1; - } else { - t1 = $2[4]; - } - const handleChange5 = t1; - let t22; - if ($2[5] !== availablePaths) { - let t33; - if ($2[7] === Symbol.for("react.memo_cache_sentinel")) { - t33 = { - label: "Cancel", - value: "cancel" - }; - $2[7] = t33; - } else { - t33 = $2[7]; - } - t22 = [...availablePaths.map(_temp307), t33]; - $2[5] = availablePaths; - $2[6] = t22; - } else { - t22 = $2[6]; - } - const options2 = t22; - let t32; - if ($2[8] !== availablePaths.length || $2[9] !== errorMessage4 || $2[10] !== handleChange5 || $2[11] !== options2 || $2[12] !== targetRepo || $2[13] !== validating) { - t32 = availablePaths.length > 0 ? /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(jsx_dev_runtime486.Fragment, { - children: [ - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - errorMessage4 && /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - color: "error", - children: errorMessage4 - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - children: [ - "Open Claude Code in ", - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - bold: true, - children: targetRepo - }, undefined, false, undefined, this), - ":" - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - validating ? /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - children: " Validating repository\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(Select, { - options: options2, - onChange: (value_0) => void handleChange5(value_0) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - errorMessage4 && /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - color: "error", - children: errorMessage4 - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "Run claude --teleport from a checkout of ", - targetRepo - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[8] = availablePaths.length; - $2[9] = errorMessage4; - $2[10] = handleChange5; - $2[11] = options2; - $2[12] = targetRepo; - $2[13] = validating; - $2[14] = t32; - } else { - t32 = $2[14]; - } - let t4; - if ($2[15] !== onCancel || $2[16] !== t32) { - t4 = /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(Dialog, { - title: "Teleport to Repo", - onCancel, - color: "background", - children: t32 - }, undefined, false, undefined, this); - $2[15] = onCancel; - $2[16] = t32; - $2[17] = t4; - } else { - t4 = $2[17]; - } - return t4; -} -function _temp307(path27) { - return { - label: /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - children: [ - "Use ", - /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ThemedText, { - bold: true, - children: getDisplayPath(path27) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - value: path27 - }; -} -var import_compiler_runtime384, import_react330, jsx_dev_runtime486; -var init_TeleportRepoMismatchDialog = __esm(() => { - init_ink2(); - init_file(); - init_githubRepoPathMapping(); - init_CustomSelect(); - init_Dialog(); - init_Spinner2(); - import_compiler_runtime384 = __toESM(require_compiler_runtime(), 1); - import_react330 = __toESM(require_react(), 1); - jsx_dev_runtime486 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/screens/ResumeConversation.tsx -var exports_ResumeConversation = {}; -__export(exports_ResumeConversation, { - ResumeConversation: () => ResumeConversation -}); -import { dirname as dirname60 } from "path"; -function parsePrIdentifier(value) { - const directNumber = parseInt(value, 10); - if (!isNaN(directNumber) && directNumber > 0) { - return directNumber; - } - const urlMatch = value.match(/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/); - if (urlMatch?.[1]) { - return parseInt(urlMatch[1], 10); - } - return null; -} -function ResumeConversation({ - commands: commands7, - worktreePaths, - initialTools, - mcpClients, - dynamicMcpConfig, - debug: debug2, - mainThreadAgentDefinition, - autoConnectIdeFlag, - strictMcpConfig = false, - systemPrompt, - appendSystemPrompt, - initialSearchQuery, - disableSlashCommands = false, - forkSession, - taskListId, - filterByPr, - thinkingConfig, - onTurnComplete -}) { - const { - rows - } = useTerminalSize(); - const agentDefinitions = useAppState((s4) => s4.agentDefinitions); - const setAppState = useSetAppState(); - const [logs2, setLogs] = import_react331.default.useState([]); - const [loading, setLoading] = import_react331.default.useState(true); - const [resuming, setResuming] = import_react331.default.useState(false); - const [showAllProjects, setShowAllProjects] = import_react331.default.useState(false); - const [resumeData, setResumeData] = import_react331.default.useState(null); - const [crossProjectCommand, setCrossProjectCommand] = import_react331.default.useState(null); - const sessionLogResultRef = import_react331.default.useRef(null); - const logCountRef = import_react331.default.useRef(0); - const filteredLogs = import_react331.default.useMemo(() => { - let result = logs2.filter((l4) => !l4.isSidechain); - if (filterByPr !== undefined) { - if (filterByPr === true) { - result = result.filter((l_0) => l_0.prNumber !== undefined); - } else if (typeof filterByPr === "number") { - result = result.filter((l_1) => l_1.prNumber === filterByPr); - } else if (typeof filterByPr === "string") { - const prNumber = parsePrIdentifier(filterByPr); - if (prNumber !== null) { - result = result.filter((l_2) => l_2.prNumber === prNumber); - } - } - } - return result; - }, [logs2, filterByPr]); - const isResumeWithRenameEnabled = isCustomTitleEnabled(); - import_react331.default.useEffect(() => { - loadSameRepoMessageLogsProgressive(worktreePaths).then((result_0) => { - sessionLogResultRef.current = result_0; - logCountRef.current = result_0.logs.length; - setLogs(result_0.logs); - setLoading(false); - }).catch((error46) => { - logError2(error46); - setLoading(false); - }); - }, [worktreePaths]); - const loadMoreLogs = import_react331.default.useCallback((count4) => { - const ref = sessionLogResultRef.current; - if (!ref || ref.nextIndex >= ref.allStatLogs.length) - return; - enrichLogs(ref.allStatLogs, ref.nextIndex, count4).then((result_1) => { - ref.nextIndex = result_1.nextIndex; - if (result_1.logs.length > 0) { - const offset = logCountRef.current; - result_1.logs.forEach((log3, i6) => { - log3.value = offset + i6; - }); - setLogs((prev) => prev.concat(result_1.logs)); - logCountRef.current += result_1.logs.length; - } else if (ref.nextIndex < ref.allStatLogs.length) { - loadMoreLogs(count4); - } - }); - }, []); - const loadLogs = import_react331.default.useCallback((allProjects) => { - setLoading(true); - const promise3 = allProjects ? loadAllProjectsMessageLogsProgressive() : loadSameRepoMessageLogsProgressive(worktreePaths); - promise3.then((result_2) => { - sessionLogResultRef.current = result_2; - logCountRef.current = result_2.logs.length; - setLogs(result_2.logs); - }).catch((error_0) => { - logError2(error_0); - }).finally(() => { - setLoading(false); - }); - }, [worktreePaths]); - const handleToggleAllProjects = import_react331.default.useCallback(() => { - const newValue = !showAllProjects; - setShowAllProjects(newValue); - loadLogs(newValue); - }, [showAllProjects, loadLogs]); - function onCancel() { - process.exit(1); - } - async function onSelect(log_0) { - setResuming(true); - const resumeStart = performance.now(); - const crossProjectCheck = checkCrossProjectResume(log_0, showAllProjects, worktreePaths); - if (crossProjectCheck.isCrossProject) { - if (!crossProjectCheck.isSameRepoWorktree) { - const raw = await setClipboard(crossProjectCheck.command); - if (raw) - process.stdout.write(raw); - setCrossProjectCommand(crossProjectCheck.command); - return; - } - } - try { - const result_3 = await loadConversationForResume(log_0, undefined); - if (!result_3) { - throw new Error("Failed to load conversation"); - } - if (false) {} - if (result_3.sessionId && !forkSession) { - switchSession(asSessionId(result_3.sessionId), log_0.fullPath ? dirname60(log_0.fullPath) : null); - await renameRecordingForSession(); - await resetSessionFilePointer(); - restoreCostStateForSession(result_3.sessionId); - } else if (forkSession && result_3.contentReplacements?.length) { - await recordContentReplacement(result_3.contentReplacements); - } - const { - agentDefinition: resolvedAgentDef - } = restoreAgentFromSession(result_3.agentSetting, mainThreadAgentDefinition, agentDefinitions); - setAppState((prev_1) => ({ - ...prev_1, - agent: resolvedAgentDef?.agentType - })); - if (false) {} - const standaloneAgentContext = computeStandaloneAgentContext(result_3.agentName, result_3.agentColor); - if (standaloneAgentContext) { - setAppState((prev_2) => ({ - ...prev_2, - standaloneAgentContext - })); - } - updateSessionName(result_3.agentName); - restoreSessionMetadata(forkSession ? { - ...result_3, - worktreeSession: undefined - } : result_3); - if (!forkSession) { - restoreWorktreeForResume(result_3.worktreeSession); - if (result_3.sessionId) { - adoptResumedSessionFile(); - } - } - if (false) {} - logEvent("tengu_session_resumed", { - entrypoint: "picker", - success: true, - resume_duration_ms: Math.round(performance.now() - resumeStart) - }); - setLogs([]); - setResumeData({ - messages: result_3.messages, - fileHistorySnapshots: result_3.fileHistorySnapshots, - contentReplacements: result_3.contentReplacements, - agentName: result_3.agentName, - agentColor: result_3.agentColor === "default" ? undefined : result_3.agentColor, - mainThreadAgentDefinition: resolvedAgentDef - }); - } catch (e4) { - logEvent("tengu_session_resumed", { - entrypoint: "picker", - success: false - }); - logError2(e4); - throw e4; - } - } - if (crossProjectCommand) { - return /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(CrossProjectMessage, { - command: crossProjectCommand - }, undefined, false, undefined, this); - } - if (resumeData) { - return /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(REPL, { - debug: debug2, - commands: commands7, - initialTools, - initialMessages: resumeData.messages, - initialFileHistorySnapshots: resumeData.fileHistorySnapshots, - initialContentReplacements: resumeData.contentReplacements, - initialAgentName: resumeData.agentName, - initialAgentColor: resumeData.agentColor, - mcpClients, - dynamicMcpConfig, - strictMcpConfig, - systemPrompt, - appendSystemPrompt, - mainThreadAgentDefinition: resumeData.mainThreadAgentDefinition, - autoConnectIdeFlag, - disableSlashCommands, - taskListId, - thinkingConfig, - onTurnComplete - }, undefined, false, undefined, this); - } - if (loading) { - return /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - children: " Loading conversations\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - if (resuming) { - return /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(Spinner, {}, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - children: " Resuming conversation\u2026" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - } - if (filteredLogs.length === 0) { - return /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(NoConversationsMessage, {}, undefined, false, undefined, this); - } - return /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(LogSelector, { - logs: filteredLogs, - maxHeight: rows, - onCancel, - onSelect, - onLogsChanged: isResumeWithRenameEnabled ? () => loadLogs(showAllProjects) : undefined, - onLoadMore: loadMoreLogs, - initialSearchQuery, - showAllProjects, - onToggleAllProjects: handleToggleAllProjects, - onAgenticSearch: agenticSessionSearch - }, undefined, false, undefined, this); -} -function NoConversationsMessage() { - const $2 = import_compiler_runtime385.c(2); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = { - context: "Global" - }; - $2[0] = t0; - } else { - t0 = $2[0]; - } - useKeybinding("app:interrupt", _temp308, t0); - let t1; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - children: "No conversations found to resume." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - dimColor: true, - children: "Press Ctrl+C to exit and start a new conversation." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this); - $2[1] = t1; - } else { - t1 = $2[1]; - } - return t1; -} -function _temp308() { - process.exit(1); -} -function CrossProjectMessage(t0) { - const $2 = import_compiler_runtime385.c(8); - const { - command: command19 - } = t0; - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = []; - $2[0] = t1; - } else { - t1 = $2[0]; - } - import_react331.default.useEffect(_temp359, t1); - let t22; - if ($2[1] === Symbol.for("react.memo_cache_sentinel")) { - t22 = /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - children: "This conversation is from a different directory." - }, undefined, false, undefined, this); - $2[1] = t22; - } else { - t22 = $2[1]; - } - let t32; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t32 = /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - children: "To resume, run:" - }, undefined, false, undefined, this); - $2[2] = t32; - } else { - t32 = $2[2]; - } - let t4; - if ($2[3] !== command19) { - t4 = /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - t32, - /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - children: [ - " ", - command19 - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); - $2[3] = command19; - $2[4] = t4; - } else { - t4 = $2[4]; - } - let t5; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t5 = /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedText, { - dimColor: true, - children: "(Command copied to clipboard)" - }, undefined, false, undefined, this); - $2[5] = t5; - } else { - t5 = $2[5]; - } - let t6; - if ($2[6] !== t4) { - t6 = /* @__PURE__ */ jsx_dev_runtime487.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - t22, - t4, - t5 - ] - }, undefined, true, undefined, this); - $2[6] = t4; - $2[7] = t6; - } else { - t6 = $2[7]; - } - return t6; -} -function _temp359() { - const timeout2 = setTimeout(_temp2103, 100); - return () => clearTimeout(timeout2); -} -function _temp2103() { - process.exit(0); -} -var import_compiler_runtime385, import_react331, jsx_dev_runtime487; -var init_ResumeConversation = __esm(() => { - init_useTerminalSize(); - init_state(); - init_LogSelector(); - init_Spinner2(); - init_cost_tracker(); - init_osc(); - init_ink2(); - init_useKeybinding(); - init_analytics(); - init_AppState(); - init_ids(); - init_agenticSessionSearch(); - init_asciicast(); - init_concurrentSessions(); - init_conversationRecovery(); - init_crossProjectResume(); - init_log2(); - init_messages9(); - init_sessionRestore(); - init_sessionStorage(); - init_REPL(); - import_compiler_runtime385 = __toESM(require_compiler_runtime(), 1); - import_react331 = __toESM(require_react(), 1); - jsx_dev_runtime487 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/services/plugins/pluginCliCommands.ts -function handlePluginCommandError(error46, command19, plugin2) { - logError2(error46); - const operation = plugin2 ? `${command19} plugin "${plugin2}"` : command19 === "disable-all" ? "disable all plugins" : `${command19} plugins`; - console.error(`${figures_default.cross} Failed to ${operation}: ${errorMessage(error46)}`); - const telemetryFields = plugin2 ? (() => { - const { name: name3, marketplace } = parsePluginIdentifier(plugin2); - return { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - ...buildPluginTelemetryFields(name3, marketplace, getManagedPluginNames()) - }; - })() : {}; - logEvent("tengu_plugin_command_failed", { - command: command19, - error_category: classifyPluginCommandError(error46), - ...telemetryFields - }); - process.exit(1); -} -async function installPlugin(plugin2, scope = "user") { - try { - console.log(`Installing plugin "${plugin2}"...`); - const result = await installPluginOp(plugin2, scope); - if (!result.success) { - throw new Error(result.message); - } - console.log(`${figures_default.tick} ${result.message}`); - const { name: name3, marketplace } = parsePluginIdentifier(result.pluginId || plugin2); - logEvent("tengu_plugin_installed_cli", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope: result.scope || scope, - install_source: "cli-explicit", - ...buildPluginTelemetryFields(name3, marketplace, getManagedPluginNames()) - }); - process.exit(0); - } catch (error46) { - handlePluginCommandError(error46, "install", plugin2); - } -} -async function uninstallPlugin(plugin2, scope = "user", keepData = false) { - try { - const result = await uninstallPluginOp(plugin2, scope, !keepData); - if (!result.success) { - throw new Error(result.message); - } - console.log(`${figures_default.tick} ${result.message}`); - const { name: name3, marketplace } = parsePluginIdentifier(result.pluginId || plugin2); - logEvent("tengu_plugin_uninstalled_cli", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope: result.scope || scope, - ...buildPluginTelemetryFields(name3, marketplace, getManagedPluginNames()) - }); - process.exit(0); - } catch (error46) { - handlePluginCommandError(error46, "uninstall", plugin2); - } -} -async function enablePlugin(plugin2, scope) { - try { - const result = await enablePluginOp(plugin2, scope); - if (!result.success) { - throw new Error(result.message); - } - console.log(`${figures_default.tick} ${result.message}`); - const { name: name3, marketplace } = parsePluginIdentifier(result.pluginId || plugin2); - logEvent("tengu_plugin_enabled_cli", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope: result.scope, - ...buildPluginTelemetryFields(name3, marketplace, getManagedPluginNames()) - }); - process.exit(0); - } catch (error46) { - handlePluginCommandError(error46, "enable", plugin2); - } -} -async function disablePlugin(plugin2, scope) { - try { - const result = await disablePluginOp(plugin2, scope); - if (!result.success) { - throw new Error(result.message); - } - console.log(`${figures_default.tick} ${result.message}`); - const { name: name3, marketplace } = parsePluginIdentifier(result.pluginId || plugin2); - logEvent("tengu_plugin_disabled_cli", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope: result.scope, - ...buildPluginTelemetryFields(name3, marketplace, getManagedPluginNames()) - }); - process.exit(0); - } catch (error46) { - handlePluginCommandError(error46, "disable", plugin2); - } -} -async function disableAllPlugins() { - try { - const result = await disableAllPluginsOp(); - if (!result.success) { - throw new Error(result.message); - } - console.log(`${figures_default.tick} ${result.message}`); - logEvent("tengu_plugin_disabled_all_cli", {}); - process.exit(0); - } catch (error46) { - handlePluginCommandError(error46, "disable-all"); - } -} -async function updatePluginCli(plugin2, scope) { - try { - writeToStdout(`Checking for updates for plugin "${plugin2}" at ${scope} scope\u2026 -`); - const result = await updatePluginOp(plugin2, scope); - if (!result.success) { - throw new Error(result.message); - } - writeToStdout(`${figures_default.tick} ${result.message} -`); - if (!result.alreadyUpToDate) { - const { name: name3, marketplace } = parsePluginIdentifier(result.pluginId || plugin2); - logEvent("tengu_plugin_updated_cli", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - old_version: result.oldVersion || "unknown", - new_version: result.newVersion || "unknown", - ...buildPluginTelemetryFields(name3, marketplace, getManagedPluginNames()) - }); - } - await gracefulShutdown(0); - } catch (error46) { - handlePluginCommandError(error46, "update", plugin2); - } -} -var init_pluginCliCommands = __esm(() => { - init_figures(); - init_errors(); - init_gracefulShutdown(); - init_log2(); - init_managedPlugins(); - init_pluginIdentifier(); - init_pluginTelemetry(); - init_analytics(); - init_pluginOperations(); -}); - -// src/cli/exit.ts -function cliError(msg) { - if (msg) - console.error(msg); - process.exit(1); - return; -} -function cliOk(msg) { - if (msg) - process.stdout.write(msg + ` -`); - process.exit(0); - return; -} - -// src/utils/errorLogSink.ts -import { dirname as dirname61, join as join150 } from "path"; -function getErrorsPath() { - return join150(CACHE_PATHS.errors(), DATE + ".jsonl"); -} -function getMCPLogsPath(serverName) { - return join150(CACHE_PATHS.mcpLogs(serverName), DATE + ".jsonl"); -} -function createJsonlWriter(options2) { - const writer = createBufferedWriter(options2); - return { - write(obj) { - writer.write(jsonStringify(obj) + ` -`); - }, - flush: writer.flush, - dispose: writer.dispose - }; -} -function getLogWriter(path27) { - let writer = logWriters.get(path27); - if (!writer) { - const dir = dirname61(path27); - writer = createJsonlWriter({ - writeFn: (content) => { - try { - getFsImplementation().appendFileSync(path27, content); - } catch { - getFsImplementation().mkdirSync(dir); - getFsImplementation().appendFileSync(path27, content); - } - }, - flushIntervalMs: 1000, - maxBufferSize: 50 - }); - logWriters.set(path27, writer); - registerCleanup(async () => writer?.dispose()); - } - return writer; -} -function appendToLog(path27, message) { - if (process.env.USER_TYPE !== "ant") { - return; - } - const messageWithTimestamp = { - timestamp: new Date().toISOString(), - ...message, - cwd: getFsImplementation().cwd(), - userType: process.env.USER_TYPE, - sessionId: getSessionId(), - version: MACRO.VERSION - }; - getLogWriter(path27).write(messageWithTimestamp); -} -function extractServerMessage(data) { - if (typeof data === "string") { - return data; - } - if (data && typeof data === "object") { - const obj = data; - if (typeof obj.message === "string") { - return obj.message; - } - if (typeof obj.error === "object" && obj.error && "message" in obj.error && typeof obj.error.message === "string") { - return obj.error.message; - } - } - return; -} -function logErrorImpl(error46) { - const errorStr = error46.stack || error46.message; - let context7 = ""; - if (axios_default.isAxiosError(error46) && error46.config?.url) { - const parts = [`url=${error46.config.url}`]; - if (error46.response?.status !== undefined) { - parts.push(`status=${error46.response.status}`); - } - const serverMessage = extractServerMessage(error46.response?.data); - if (serverMessage) { - parts.push(`body=${serverMessage}`); - } - context7 = `[${parts.join(",")}] `; - } - logForDebugging(`${error46.name}: ${context7}${errorStr}`, { level: "error" }); - appendToLog(getErrorsPath(), { - error: `${context7}${errorStr}` - }); -} -function logMCPErrorImpl(serverName, error46) { - logForDebugging(`MCP server "${serverName}" ${error46}`, { level: "error" }); - const logFile = getMCPLogsPath(serverName); - const errorStr = error46 instanceof Error ? error46.stack || error46.message : String(error46); - const errorInfo = { - error: errorStr, - timestamp: new Date().toISOString(), - sessionId: getSessionId(), - cwd: getFsImplementation().cwd() - }; - getLogWriter(logFile).write(errorInfo); -} -function logMCPDebugImpl(serverName, message) { - logForDebugging(`MCP server "${serverName}": ${message}`); - const logFile = getMCPLogsPath(serverName); - const debugInfo = { - debug: message, - timestamp: new Date().toISOString(), - sessionId: getSessionId(), - cwd: getFsImplementation().cwd() - }; - getLogWriter(logFile).write(debugInfo); -} -function initializeErrorLogSink() { - attachErrorLogSink({ - logError: logErrorImpl, - logMCPError: logMCPErrorImpl, - logMCPDebug: logMCPDebugImpl, - getErrorsPath, - getMCPLogsPath - }); - logForDebugging("Error log sink initialized"); -} -var DATE, logWriters; -var init_errorLogSink = __esm(() => { - init_axios2(); - init_state(); - init_cachePaths(); - init_cleanupRegistry(); - init_debug(); - init_fsOperations(); - init_log2(); - init_slowOperations(); - DATE = dateToFilename(new Date); - logWriters = new Map; -}); - -// src/utils/sinks.ts -var exports_sinks = {}; -__export(exports_sinks, { - initSinks: () => initSinks -}); -function initSinks() { - initializeErrorLogSink(); - initializeAnalyticsSink(); -} -var init_sinks = __esm(() => { - init_sink(); - init_errorLogSink(); -}); - -// src/services/SessionMemory/sessionMemory.ts -import { writeFile as writeFile48 } from "fs/promises"; -function isSessionMemoryGateEnabled() { - return getFeatureValue_CACHED_MAY_BE_STALE("tengu_session_memory", false); -} -function getSessionMemoryRemoteConfig() { - return getDynamicConfig_CACHED_MAY_BE_STALE("tengu_sm_config", {}); -} -function countToolCallsSince(messages, sinceUuid) { - let toolCallCount = 0; - let foundStart = sinceUuid === null || sinceUuid === undefined; - for (const message of messages) { - if (!foundStart) { - if (message.uuid === sinceUuid) { - foundStart = true; - } - continue; - } - if (message.type === "assistant") { - const content = message.message.content; - if (Array.isArray(content)) { - toolCallCount += count2(content, (block2) => block2.type === "tool_use"); - } - } - } - return toolCallCount; -} -function shouldExtractMemory(messages) { - const currentTokenCount = tokenCountWithEstimation(messages); - if (!isSessionMemoryInitialized()) { - if (!hasMetInitializationThreshold(currentTokenCount)) { - return false; - } - markSessionMemoryInitialized(); - } - const hasMetTokenThreshold = hasMetUpdateThreshold(currentTokenCount); - const toolCallsSinceLastUpdate = countToolCallsSince(messages, lastMemoryMessageUuid); - const hasMetToolCallThreshold = toolCallsSinceLastUpdate >= getToolCallsBetweenUpdates(); - const hasToolCallsInLastTurn = hasToolCallsInLastAssistantTurn(messages); - const shouldExtract = hasMetTokenThreshold && hasMetToolCallThreshold || hasMetTokenThreshold && !hasToolCallsInLastTurn; - if (shouldExtract) { - const lastMessage = messages[messages.length - 1]; - if (lastMessage?.uuid) { - lastMemoryMessageUuid = lastMessage.uuid; - } - return true; - } - return false; -} -async function setupSessionMemoryFile(toolUseContext) { - const fs14 = getFsImplementation(); - const sessionMemoryDir = getSessionMemoryDir(); - await fs14.mkdir(sessionMemoryDir, { mode: 448 }); - const memoryPath = getSessionMemoryPath(); - try { - await writeFile48(memoryPath, "", { - encoding: "utf-8", - mode: 384, - flag: "wx" - }); - const template = await loadSessionMemoryTemplate(); - await writeFile48(memoryPath, template, { - encoding: "utf-8", - mode: 384 - }); - } catch (e4) { - const code = getErrnoCode(e4); - if (code !== "EEXIST") { - throw e4; - } - } - toolUseContext.readFileState.delete(memoryPath); - const result = await FileReadTool.call({ file_path: memoryPath }, toolUseContext); - let currentMemory = ""; - const output = result.data; - if (output.type === "text") { - currentMemory = output.file.content; - } - logEvent("tengu_session_memory_file_read", { - content_length: currentMemory.length - }); - return { memoryPath, currentMemory }; -} -function initSessionMemory() { - if (getIsRemoteMode()) - return; - const autoCompactEnabled = isAutoCompactEnabled(); - if (process.env.USER_TYPE === "ant") { - logEvent("tengu_session_memory_init", { - auto_compact_enabled: autoCompactEnabled - }); - } - if (!autoCompactEnabled) { - return; - } - registerPostSamplingHook(extractSessionMemory); -} -function createMemoryFileCanUseTool(memoryPath) { - return async (tool, input) => { - if (tool.name === FILE_EDIT_TOOL_NAME && typeof input === "object" && input !== null && "file_path" in input) { - const filePath = input.file_path; - if (typeof filePath === "string" && filePath === memoryPath) { - return { behavior: "allow", updatedInput: input }; - } - } - return { - behavior: "deny", - message: `only ${FILE_EDIT_TOOL_NAME} on ${memoryPath} is allowed`, - decisionReason: { - type: "other", - reason: `only ${FILE_EDIT_TOOL_NAME} on ${memoryPath} is allowed` - } - }; - }; -} -function updateLastSummarizedMessageIdIfSafe(messages) { - if (!hasToolCallsInLastAssistantTurn(messages)) { - const lastMessage = messages[messages.length - 1]; - if (lastMessage?.uuid) { - setLastSummarizedMessageId(lastMessage.uuid); - } - } -} -var lastMemoryMessageUuid, initSessionMemoryConfigIfNeeded, hasLoggedGateFailure = false, extractSessionMemory; -var init_sessionMemory = __esm(() => { - init_memoize(); - init_state(); - init_prompts3(); - init_context4(); - init_FileReadTool(); - init_forkedAgent(); - init_fsOperations(); - init_postSamplingHooks(); - init_messages9(); - init_filesystem(); - init_tokens(); - init_analytics(); - init_autoCompact(); - init_prompts(); - init_sessionMemoryUtils(); - init_errors(); - init_growthbook(); - initSessionMemoryConfigIfNeeded = memoize_default(() => { - const remoteConfig = getSessionMemoryRemoteConfig(); - const config10 = { - minimumMessageTokensToInit: remoteConfig.minimumMessageTokensToInit && remoteConfig.minimumMessageTokensToInit > 0 ? remoteConfig.minimumMessageTokensToInit : DEFAULT_SESSION_MEMORY_CONFIG.minimumMessageTokensToInit, - minimumTokensBetweenUpdate: remoteConfig.minimumTokensBetweenUpdate && remoteConfig.minimumTokensBetweenUpdate > 0 ? remoteConfig.minimumTokensBetweenUpdate : DEFAULT_SESSION_MEMORY_CONFIG.minimumTokensBetweenUpdate, - toolCallsBetweenUpdates: remoteConfig.toolCallsBetweenUpdates && remoteConfig.toolCallsBetweenUpdates > 0 ? remoteConfig.toolCallsBetweenUpdates : DEFAULT_SESSION_MEMORY_CONFIG.toolCallsBetweenUpdates - }; - setSessionMemoryConfig(config10); - }); - extractSessionMemory = sequential(async function(context7) { - const { messages, toolUseContext, querySource } = context7; - if (querySource !== "repl_main_thread") { - return; - } - if (!isSessionMemoryGateEnabled()) { - if (process.env.USER_TYPE === "ant" && !hasLoggedGateFailure) { - hasLoggedGateFailure = true; - logEvent("tengu_session_memory_gate_disabled", {}); - } - return; - } - initSessionMemoryConfigIfNeeded(); - if (!shouldExtractMemory(messages)) { - return; - } - markExtractionStarted(); - const setupContext = createSubagentContext(toolUseContext); - const { memoryPath, currentMemory } = await setupSessionMemoryFile(setupContext); - const userPrompt = await buildSessionMemoryUpdatePrompt(currentMemory, memoryPath); - await runForkedAgent({ - promptMessages: [createUserMessage({ content: userPrompt })], - cacheSafeParams: createCacheSafeParams(context7), - canUseTool: createMemoryFileCanUseTool(memoryPath), - querySource: "session_memory", - forkLabel: "session_memory", - overrides: { readFileState: setupContext.readFileState } - }); - const lastMessage = messages[messages.length - 1]; - const usage = lastMessage ? getTokenUsage(lastMessage) : undefined; - const config10 = getSessionMemoryConfig(); - logEvent("tengu_session_memory_extraction", { - input_tokens: usage?.input_tokens, - output_tokens: usage?.output_tokens, - cache_read_input_tokens: usage?.cache_read_input_tokens ?? undefined, - cache_creation_input_tokens: usage?.cache_creation_input_tokens ?? undefined, - config_min_message_tokens_to_init: config10.minimumMessageTokensToInit, - config_min_tokens_between_update: config10.minimumTokensBetweenUpdate, - config_tool_calls_between_updates: config10.toolCallsBetweenUpdates - }); - recordExtractionTokenCount(tokenCountWithEstimation(messages)); - updateLastSummarizedMessageIdIfSafe(messages); - markExtractionCompleted(); - }); -}); - -// src/utils/iTermBackup.ts -import { copyFile as copyFile12, stat as stat48 } from "fs/promises"; -import { homedir as homedir37 } from "os"; -import { join as join151 } from "path"; -function markITerm2SetupComplete() { - saveGlobalConfig((current) => ({ - ...current, - iterm2SetupInProgress: false - })); -} -function getIterm2RecoveryInfo() { - const config10 = getGlobalConfig(); - return { - inProgress: config10.iterm2SetupInProgress ?? false, - backupPath: config10.iterm2BackupPath || null - }; -} -function getITerm2PlistPath() { - return join151(homedir37(), "Library", "Preferences", "com.googlecode.iterm2.plist"); -} -async function checkAndRestoreITerm2Backup() { - const { inProgress, backupPath } = getIterm2RecoveryInfo(); - if (!inProgress) { - return { status: "no_backup" }; - } - if (!backupPath) { - markITerm2SetupComplete(); - return { status: "no_backup" }; - } - try { - await stat48(backupPath); - } catch { - markITerm2SetupComplete(); - return { status: "no_backup" }; - } - try { - await copyFile12(backupPath, getITerm2PlistPath()); - markITerm2SetupComplete(); - return { status: "restored" }; - } catch (restoreError) { - logError2(new Error(`Failed to restore iTerm2 settings with: ${restoreError}`)); - markITerm2SetupComplete(); - return { status: "failed", backupPath }; - } -} -var init_iTermBackup = __esm(() => { - init_config(); - init_log2(); -}); - -// src/setup.ts -var exports_setup = {}; -__export(exports_setup, { - setup: () => setup -}); -async function setup(cwd2, permissionMode, allowDangerouslySkipPermissions, worktreeEnabled, worktreeName, tmuxEnabled, customSessionId, worktreePRNumber, messagingSocketPath) { - logForDiagnosticsNoPII("info", "setup_started"); - const nodeVersion = process.version.match(/^v(\d+)\./)?.[1]; - if (!nodeVersion || parseInt(nodeVersion) < 18) { - console.error(source_default.bold.red("Error: Claude Code requires Node.js version 18 or higher.")); - process.exit(1); - } - if (customSessionId) { - switchSession(asSessionId(customSessionId)); - } - if (!isBareMode() || messagingSocketPath !== undefined) { - if (false) {} - } - if (!isBareMode() && isAgentSwarmsEnabled()) { - const { captureTeammateModeSnapshot: captureTeammateModeSnapshot2 } = await Promise.resolve().then(() => (init_teammateModeSnapshot(), exports_teammateModeSnapshot)); - captureTeammateModeSnapshot2(); - } - if (!getIsNonInteractiveSession()) { - if (isAgentSwarmsEnabled()) { - const restoredIterm2Backup = await checkAndRestoreITerm2Backup(); - if (restoredIterm2Backup.status === "restored") { - console.log(source_default.yellow("Detected an interrupted iTerm2 setup. Your original settings have been restored. You may need to restart iTerm2 for the changes to take effect.")); - } else if (restoredIterm2Backup.status === "failed") { - console.error(source_default.red(`Failed to restore iTerm2 settings. Please manually restore your original settings with: defaults import com.googlecode.iterm2 ${restoredIterm2Backup.backupPath}.`)); - } - } - try { - const restoredTerminalBackup = await checkAndRestoreTerminalBackup(); - if (restoredTerminalBackup.status === "restored") { - console.log(source_default.yellow("Detected an interrupted Terminal.app setup. Your original settings have been restored. You may need to restart Terminal.app for the changes to take effect.")); - } else if (restoredTerminalBackup.status === "failed") { - console.error(source_default.red(`Failed to restore Terminal.app settings. Please manually restore your original settings with: defaults import com.apple.Terminal ${restoredTerminalBackup.backupPath}.`)); - } - } catch (error46) { - logError2(error46); - } - } - setCwd(cwd2); - const hooksStart = Date.now(); - captureHooksConfigSnapshot(); - logForDiagnosticsNoPII("info", "setup_hooks_captured", { - duration_ms: Date.now() - hooksStart - }); - initializeFileChangedWatcher(cwd2); - if (worktreeEnabled) { - const hasHook = hasWorktreeCreateHook(); - const inGit = await getIsGit(); - if (!hasHook && !inGit) { - process.stderr.write(source_default.red(`Error: Can only use --worktree in a git repository, but ${source_default.bold(cwd2)} is not a git repository. Configure a WorktreeCreate hook in settings.json to use --worktree with other VCS systems. -`)); - process.exit(1); - } - const slug = worktreePRNumber ? `pr-${worktreePRNumber}` : worktreeName ?? getPlanSlug(); - let tmuxSessionName; - if (inGit) { - const mainRepoRoot = findCanonicalGitRoot(getCwd()); - if (!mainRepoRoot) { - process.stderr.write(source_default.red(`Error: Could not determine the main git repository root. -`)); - process.exit(1); - } - if (mainRepoRoot !== (findGitRoot(getCwd()) ?? getCwd())) { - logForDiagnosticsNoPII("info", "worktree_resolved_to_main_repo"); - process.chdir(mainRepoRoot); - setCwd(mainRepoRoot); - } - tmuxSessionName = tmuxEnabled ? generateTmuxSessionName(mainRepoRoot, worktreeBranchName(slug)) : undefined; - } else { - tmuxSessionName = tmuxEnabled ? generateTmuxSessionName(getCwd(), worktreeBranchName(slug)) : undefined; - } - let worktreeSession; - try { - worktreeSession = await createWorktreeForSession(getSessionId(), slug, tmuxSessionName, worktreePRNumber ? { prNumber: worktreePRNumber } : undefined); - } catch (error46) { - process.stderr.write(source_default.red(`Error creating worktree: ${errorMessage(error46)} -`)); - process.exit(1); - } - logEvent("tengu_worktree_created", { tmux_enabled: tmuxEnabled }); - if (tmuxEnabled && tmuxSessionName) { - const tmuxResult = await createTmuxSessionForWorktree(tmuxSessionName, worktreeSession.worktreePath); - if (tmuxResult.created) { - console.log(source_default.green(`Created tmux session: ${source_default.bold(tmuxSessionName)} -To attach: ${source_default.bold(`tmux attach -t ${tmuxSessionName}`)}`)); - } else { - console.error(source_default.yellow(`Warning: Failed to create tmux session: ${tmuxResult.error}`)); - } - } - process.chdir(worktreeSession.worktreePath); - setCwd(worktreeSession.worktreePath); - setOriginalCwd(getCwd()); - setProjectRoot(getCwd()); - saveWorktreeState(worktreeSession); - clearMemoryFileCaches(); - updateHooksConfigSnapshot(); - } - logForDiagnosticsNoPII("info", "setup_background_jobs_starting"); - if (!isBareMode()) { - initSessionMemory(); - if (false) {} - } - lockCurrentVersion(); - logForDiagnosticsNoPII("info", "setup_background_jobs_launched"); - profileCheckpoint("setup_before_prefetch"); - logForDiagnosticsNoPII("info", "setup_prefetch_starting"); - const skipPluginPrefetch = getIsNonInteractiveSession() && isEnvTruthy(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL) || isBareMode(); - if (!skipPluginPrefetch) { - getCommands(getProjectRoot()); - } - Promise.resolve().then(() => (init_loadPluginHooks(), exports_loadPluginHooks)).then((m4) => { - if (!skipPluginPrefetch) { - m4.loadPluginHooks(); - m4.setupPluginHookHotReload(); - } - }); - if (!isBareMode()) { - if (process.env.USER_TYPE === "ant") { - Promise.resolve().then(() => (init_commitAttribution(), exports_commitAttribution)).then(async (m4) => { - if (await m4.isInternalModelRepo()) { - const { clearSystemPromptSections: clearSystemPromptSections2 } = await Promise.resolve().then(() => (init_systemPromptSections(), exports_systemPromptSections)); - clearSystemPromptSections2(); - } - }); - } - if (false) {} - Promise.resolve().then(() => (init_sessionFileAccessHooks(), exports_sessionFileAccessHooks)).then((m4) => m4.registerSessionFileAccessHooks()); - if (false) {} - } - initSinks(); - logEvent("tengu_started", {}); - prefetchApiKeyFromApiKeyHelperIfSafe(getIsNonInteractiveSession()); - profileCheckpoint("setup_after_prefetch"); - if (!isBareMode()) { - const { hasReleaseNotes } = await checkForReleaseNotes(getGlobalConfig().lastReleaseNotesSeen); - if (hasReleaseNotes) { - await getRecentActivity(); - } - } - if (permissionMode === "bypassPermissions" || allowDangerouslySkipPermissions) { - if (process.platform !== "win32" && typeof process.getuid === "function" && process.getuid() === 0 && process.env.IS_SANDBOX !== "1" && !isEnvTruthy(process.env.CLAUDE_CODE_BUBBLEWRAP)) { - console.error(`--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons`); - process.exit(1); - } - if (process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_ENTRYPOINT !== "local-agent" && process.env.CLAUDE_CODE_ENTRYPOINT !== "claude-desktop") { - const [isDocker2, hasInternet] = await Promise.all([ - envDynamic.getIsDocker(), - env2.hasInternetAccess() - ]); - const isBubblewrap = envDynamic.getIsBubblewrapSandbox(); - const isSandbox = process.env.IS_SANDBOX === "1"; - const isSandboxed = isDocker2 || isBubblewrap || isSandbox; - if (!isSandboxed || hasInternet) { - console.error(`--dangerously-skip-permissions can only be used in Docker/sandbox containers with no internet access but got Docker: ${isDocker2}, Bubblewrap: ${isBubblewrap}, IS_SANDBOX: ${isSandbox}, hasInternet: ${hasInternet}`); - process.exit(1); - } - } - } - if (false) {} - const projectConfig = getCurrentProjectConfig(); - if (projectConfig.lastCost !== undefined && projectConfig.lastDuration !== undefined) { - logEvent("tengu_exit", { - last_session_cost: projectConfig.lastCost, - last_session_api_duration: projectConfig.lastAPIDuration, - last_session_tool_duration: projectConfig.lastToolDuration, - last_session_duration: projectConfig.lastDuration, - last_session_lines_added: projectConfig.lastLinesAdded, - last_session_lines_removed: projectConfig.lastLinesRemoved, - last_session_total_input_tokens: projectConfig.lastTotalInputTokens, - last_session_total_output_tokens: projectConfig.lastTotalOutputTokens, - last_session_total_cache_creation_input_tokens: projectConfig.lastTotalCacheCreationInputTokens, - last_session_total_cache_read_input_tokens: projectConfig.lastTotalCacheReadInputTokens, - last_session_fps_average: projectConfig.lastFpsAverage, - last_session_fps_low_1_pct: projectConfig.lastFpsLow1Pct, - last_session_id: projectConfig.lastSessionId, - ...projectConfig.lastSessionMetrics - }); - } -} -var init_setup3 = __esm(() => { - init_source(); - init_analytics(); - init_cwd(); - init_releaseNotes(); - init_Shell(); - init_sinks(); - init_state(); - init_commands5(); - init_sessionMemory(); - init_ids(); - init_agentSwarmsEnabled(); - init_appleTerminalBackup(); - init_auth14(); - init_claudemd(); - init_config(); - init_diagLogs(); - init_env(); - init_envDynamic(); - init_envUtils(); - init_errors(); - init_git(); - init_fileChangedWatcher(); - init_hooksConfigSnapshot(); - init_hooks3(); - init_iTermBackup(); - init_log2(); - init_logoV2Utils(); - init_nativeInstaller(); - init_plans(); - init_sessionStorage(); - init_startupProfiler(); - init_worktree(); -}); - -// src/bridge/pollConfigDefaults.ts -var POLL_INTERVAL_MS_NOT_AT_CAPACITY = 2000, POLL_INTERVAL_MS_AT_CAPACITY = 600000, MULTISESSION_POLL_INTERVAL_MS_NOT_AT_CAPACITY, MULTISESSION_POLL_INTERVAL_MS_PARTIAL_CAPACITY, MULTISESSION_POLL_INTERVAL_MS_AT_CAPACITY, DEFAULT_POLL_CONFIG; -var init_pollConfigDefaults = __esm(() => { - MULTISESSION_POLL_INTERVAL_MS_NOT_AT_CAPACITY = POLL_INTERVAL_MS_NOT_AT_CAPACITY; - MULTISESSION_POLL_INTERVAL_MS_PARTIAL_CAPACITY = POLL_INTERVAL_MS_NOT_AT_CAPACITY; - MULTISESSION_POLL_INTERVAL_MS_AT_CAPACITY = POLL_INTERVAL_MS_AT_CAPACITY; - DEFAULT_POLL_CONFIG = { - poll_interval_ms_not_at_capacity: POLL_INTERVAL_MS_NOT_AT_CAPACITY, - poll_interval_ms_at_capacity: POLL_INTERVAL_MS_AT_CAPACITY, - non_exclusive_heartbeat_interval_ms: 0, - multisession_poll_interval_ms_not_at_capacity: MULTISESSION_POLL_INTERVAL_MS_NOT_AT_CAPACITY, - multisession_poll_interval_ms_partial_capacity: MULTISESSION_POLL_INTERVAL_MS_PARTIAL_CAPACITY, - multisession_poll_interval_ms_at_capacity: MULTISESSION_POLL_INTERVAL_MS_AT_CAPACITY, - reclaim_older_than_ms: 5000, - session_keepalive_interval_v2_ms: 120000 - }; -}); - -// src/bridge/pollConfig.ts -function getPollIntervalConfig() { - const raw = getFeatureValue_CACHED_WITH_REFRESH("tengu_bridge_poll_interval_config", DEFAULT_POLL_CONFIG, 5 * 60 * 1000); - const parsed = pollIntervalConfigSchema().safeParse(raw); - return parsed.success ? parsed.data : DEFAULT_POLL_CONFIG; -} -var zeroOrAtLeast100, pollIntervalConfigSchema; -var init_pollConfig = __esm(() => { - init_v4(); - init_growthbook(); - init_pollConfigDefaults(); - zeroOrAtLeast100 = { - message: "must be 0 (disabled) or \u2265100ms" - }; - pollIntervalConfigSchema = lazySchema(() => exports_external.object({ - poll_interval_ms_not_at_capacity: exports_external.number().int().min(100), - poll_interval_ms_at_capacity: exports_external.number().int().refine((v6) => v6 === 0 || v6 >= 100, zeroOrAtLeast100), - non_exclusive_heartbeat_interval_ms: exports_external.number().int().min(0).default(0), - multisession_poll_interval_ms_not_at_capacity: exports_external.number().int().min(100).default(DEFAULT_POLL_CONFIG.multisession_poll_interval_ms_not_at_capacity), - multisession_poll_interval_ms_partial_capacity: exports_external.number().int().min(100).default(DEFAULT_POLL_CONFIG.multisession_poll_interval_ms_partial_capacity), - multisession_poll_interval_ms_at_capacity: exports_external.number().int().refine((v6) => v6 === 0 || v6 >= 100, zeroOrAtLeast100).default(DEFAULT_POLL_CONFIG.multisession_poll_interval_ms_at_capacity), - reclaim_older_than_ms: exports_external.number().int().min(1).default(5000), - session_keepalive_interval_v2_ms: exports_external.number().int().min(0).default(120000) - }).refine((cfg) => cfg.non_exclusive_heartbeat_interval_ms > 0 || cfg.poll_interval_ms_at_capacity > 0, { - message: "at-capacity liveness requires non_exclusive_heartbeat_interval_ms > 0 or poll_interval_ms_at_capacity > 0" - }).refine((cfg) => cfg.non_exclusive_heartbeat_interval_ms > 0 || cfg.multisession_poll_interval_ms_at_capacity > 0, { - message: "at-capacity liveness requires non_exclusive_heartbeat_interval_ms > 0 or multisession_poll_interval_ms_at_capacity > 0" - })); -}); - -// src/bridge/jwtUtils.ts -function formatDuration2(ms) { - if (ms < 60000) - return `${Math.round(ms / 1000)}s`; - const m4 = Math.floor(ms / 60000); - const s4 = Math.round(ms % 60000 / 1000); - return s4 > 0 ? `${m4}m ${s4}s` : `${m4}m`; -} -function decodeJwtPayload(token) { - const jwt3 = token.startsWith("sk-ant-si-") ? token.slice("sk-ant-si-".length) : token; - const parts = jwt3.split("."); - if (parts.length !== 3 || !parts[1]) - return null; - try { - return jsonParse(Buffer.from(parts[1], "base64url").toString("utf8")); - } catch { - return null; - } -} -function decodeJwtExpiry(token) { - const payload = decodeJwtPayload(token); - if (payload !== null && typeof payload === "object" && "exp" in payload && typeof payload.exp === "number") { - return payload.exp; - } - return null; -} -function createTokenRefreshScheduler({ - getAccessToken, - onRefresh, - label, - refreshBufferMs = TOKEN_REFRESH_BUFFER_MS -}) { - const timers = new Map; - const failureCounts = new Map; - const generations = new Map; - function nextGeneration(sessionId) { - const gen = (generations.get(sessionId) ?? 0) + 1; - generations.set(sessionId, gen); - return gen; - } - function schedule(sessionId, token) { - const expiry = decodeJwtExpiry(token); - if (!expiry) { - logForDebugging(`[${label}:token] Could not decode JWT expiry for sessionId=${sessionId}, token prefix=${token.slice(0, 15)}\u2026, keeping existing timer`); - return; - } - const existing = timers.get(sessionId); - if (existing) { - clearTimeout(existing); - } - const gen = nextGeneration(sessionId); - const expiryDate = new Date(expiry * 1000).toISOString(); - const delayMs = expiry * 1000 - Date.now() - refreshBufferMs; - if (delayMs <= 0) { - logForDebugging(`[${label}:token] Token for sessionId=${sessionId} expires=${expiryDate} (past or within buffer), refreshing immediately`); - doRefresh(sessionId, gen); - return; - } - logForDebugging(`[${label}:token] Scheduled token refresh for sessionId=${sessionId} in ${formatDuration2(delayMs)} (expires=${expiryDate}, buffer=${refreshBufferMs / 1000}s)`); - const timer = setTimeout(doRefresh, delayMs, sessionId, gen); - timers.set(sessionId, timer); - } - function scheduleFromExpiresIn(sessionId, expiresInSeconds) { - const existing = timers.get(sessionId); - if (existing) - clearTimeout(existing); - const gen = nextGeneration(sessionId); - const delayMs = Math.max(expiresInSeconds * 1000 - refreshBufferMs, 30000); - logForDebugging(`[${label}:token] Scheduled token refresh for sessionId=${sessionId} in ${formatDuration2(delayMs)} (expires_in=${expiresInSeconds}s, buffer=${refreshBufferMs / 1000}s)`); - const timer = setTimeout(doRefresh, delayMs, sessionId, gen); - timers.set(sessionId, timer); - } - async function doRefresh(sessionId, gen) { - let oauthToken; - try { - oauthToken = await getAccessToken(); - } catch (err2) { - logForDebugging(`[${label}:token] getAccessToken threw for sessionId=${sessionId}: ${errorMessage(err2)}`, { level: "error" }); - } - if (generations.get(sessionId) !== gen) { - logForDebugging(`[${label}:token] doRefresh for sessionId=${sessionId} stale (gen ${gen} vs ${generations.get(sessionId)}), skipping`); - return; - } - if (!oauthToken) { - const failures = (failureCounts.get(sessionId) ?? 0) + 1; - failureCounts.set(sessionId, failures); - logForDebugging(`[${label}:token] No OAuth token available for refresh, sessionId=${sessionId} (failure ${failures}/${MAX_REFRESH_FAILURES})`, { level: "error" }); - logForDiagnosticsNoPII("error", "bridge_token_refresh_no_oauth"); - if (failures < MAX_REFRESH_FAILURES) { - const retryTimer = setTimeout(doRefresh, REFRESH_RETRY_DELAY_MS, sessionId, gen); - timers.set(sessionId, retryTimer); - } - return; - } - failureCounts.delete(sessionId); - logForDebugging(`[${label}:token] Refreshing token for sessionId=${sessionId}: new token prefix=${oauthToken.slice(0, 15)}\u2026`); - logEvent("tengu_bridge_token_refreshed", {}); - onRefresh(sessionId, oauthToken); - const timer = setTimeout(doRefresh, FALLBACK_REFRESH_INTERVAL_MS, sessionId, gen); - timers.set(sessionId, timer); - logForDebugging(`[${label}:token] Scheduled follow-up refresh for sessionId=${sessionId} in ${formatDuration2(FALLBACK_REFRESH_INTERVAL_MS)}`); - } - function cancel(sessionId) { - nextGeneration(sessionId); - const timer = timers.get(sessionId); - if (timer) { - clearTimeout(timer); - timers.delete(sessionId); - } - failureCounts.delete(sessionId); - } - function cancelAll() { - for (const sessionId of generations.keys()) { - nextGeneration(sessionId); - } - for (const timer of timers.values()) { - clearTimeout(timer); - } - timers.clear(); - failureCounts.clear(); - } - return { schedule, scheduleFromExpiresIn, cancel, cancelAll }; -} -var TOKEN_REFRESH_BUFFER_MS, FALLBACK_REFRESH_INTERVAL_MS, MAX_REFRESH_FAILURES = 3, REFRESH_RETRY_DELAY_MS = 60000; -var init_jwtUtils = __esm(() => { - init_analytics(); - init_debug(); - init_diagLogs(); - init_errors(); - init_slowOperations(); - TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1000; - FALLBACK_REFRESH_INTERVAL_MS = 30 * 60 * 1000; -}); - -// src/cli/transports/SerialBatchEventUploader.ts -class SerialBatchEventUploader { - pending = []; - pendingAtClose = 0; - draining = false; - closed = false; - backpressureResolvers = []; - sleepResolve = null; - flushResolvers = []; - droppedBatches = 0; - config; - constructor(config10) { - this.config = config10; - } - get droppedBatchCount() { - return this.droppedBatches; - } - get pendingCount() { - return this.closed ? this.pendingAtClose : this.pending.length; - } - async enqueue(events2) { - if (this.closed) - return; - const items = Array.isArray(events2) ? events2 : [events2]; - if (items.length === 0) - return; - while (this.pending.length + items.length > this.config.maxQueueSize && !this.closed) { - await new Promise((resolve44) => { - this.backpressureResolvers.push(resolve44); - }); - } - if (this.closed) - return; - this.pending.push(...items); - this.drain(); - } - flush() { - if (this.pending.length === 0 && !this.draining) { - return Promise.resolve(); - } - this.drain(); - return new Promise((resolve44) => { - this.flushResolvers.push(resolve44); - }); - } - close() { - if (this.closed) - return; - this.closed = true; - this.pendingAtClose = this.pending.length; - this.pending = []; - this.sleepResolve?.(); - this.sleepResolve = null; - for (const resolve44 of this.backpressureResolvers) - resolve44(); - this.backpressureResolvers = []; - for (const resolve44 of this.flushResolvers) - resolve44(); - this.flushResolvers = []; - } - async drain() { - if (this.draining || this.closed) - return; - this.draining = true; - let failures = 0; - try { - while (this.pending.length > 0 && !this.closed) { - const batch = this.takeBatch(); - if (batch.length === 0) - continue; - try { - await this.config.send(batch); - failures = 0; - } catch (err2) { - failures++; - if (this.config.maxConsecutiveFailures !== undefined && failures >= this.config.maxConsecutiveFailures) { - this.droppedBatches++; - this.config.onBatchDropped?.(batch.length, failures); - failures = 0; - this.releaseBackpressure(); - continue; - } - this.pending = batch.concat(this.pending); - const retryAfterMs = err2 instanceof RetryableError ? err2.retryAfterMs : undefined; - await this.sleep(this.retryDelay(failures, retryAfterMs)); - continue; - } - this.releaseBackpressure(); - } - } finally { - this.draining = false; - if (this.pending.length === 0) { - for (const resolve44 of this.flushResolvers) - resolve44(); - this.flushResolvers = []; - } - } - } - takeBatch() { - const { maxBatchSize, maxBatchBytes } = this.config; - if (maxBatchBytes === undefined) { - return this.pending.splice(0, maxBatchSize); - } - let bytes = 0; - let count4 = 0; - while (count4 < this.pending.length && count4 < maxBatchSize) { - let itemBytes; - try { - itemBytes = Buffer.byteLength(jsonStringify(this.pending[count4])); - } catch { - this.pending.splice(count4, 1); - continue; - } - if (count4 > 0 && bytes + itemBytes > maxBatchBytes) - break; - bytes += itemBytes; - count4++; - } - return this.pending.splice(0, count4); - } - retryDelay(failures, retryAfterMs) { - const jitter = Math.random() * this.config.jitterMs; - if (retryAfterMs !== undefined) { - const clamped = Math.max(this.config.baseDelayMs, Math.min(retryAfterMs, this.config.maxDelayMs)); - return clamped + jitter; - } - const exponential = Math.min(this.config.baseDelayMs * 2 ** (failures - 1), this.config.maxDelayMs); - return exponential + jitter; - } - releaseBackpressure() { - const resolvers2 = this.backpressureResolvers; - this.backpressureResolvers = []; - for (const resolve44 of resolvers2) - resolve44(); - } - sleep(ms) { - return new Promise((resolve44) => { - this.sleepResolve = resolve44; - setTimeout((self2, resolve45) => { - self2.sleepResolve = null; - resolve45(); - }, ms, this, resolve44); - }); - } -} -var RetryableError; -var init_SerialBatchEventUploader = __esm(() => { - init_slowOperations(); - RetryableError = class RetryableError extends Error { - retryAfterMs; - constructor(message, retryAfterMs) { - super(message); - this.retryAfterMs = retryAfterMs; - } - }; -}); - -// src/cli/transports/WorkerStateUploader.ts -class WorkerStateUploader { - inflight = null; - pending = null; - closed = false; - config; - constructor(config10) { - this.config = config10; - } - enqueue(patch2) { - if (this.closed) - return; - this.pending = this.pending ? coalescePatches(this.pending, patch2) : patch2; - this.drain(); - } - close() { - this.closed = true; - this.pending = null; - } - async drain() { - if (this.inflight || this.closed) - return; - if (!this.pending) - return; - const payload = this.pending; - this.pending = null; - this.inflight = this.sendWithRetry(payload).then(() => { - this.inflight = null; - if (this.pending && !this.closed) { - this.drain(); - } - }); - } - async sendWithRetry(payload) { - let current = payload; - let failures = 0; - while (!this.closed) { - const ok = await this.config.send(current); - if (ok) - return; - failures++; - await sleep6(this.retryDelay(failures)); - if (this.pending && !this.closed) { - current = coalescePatches(current, this.pending); - this.pending = null; - } - } - } - retryDelay(failures) { - const exponential = Math.min(this.config.baseDelayMs * 2 ** (failures - 1), this.config.maxDelayMs); - const jitter = Math.random() * this.config.jitterMs; - return exponential + jitter; - } -} -function coalescePatches(base2, overlay) { - const merged = { ...base2 }; - for (const [key2, value] of Object.entries(overlay)) { - if ((key2 === "external_metadata" || key2 === "internal_metadata") && merged[key2] && typeof merged[key2] === "object" && typeof value === "object" && value !== null) { - merged[key2] = { - ...merged[key2], - ...value - }; - } else { - merged[key2] = value; - } - } - return merged; -} -var init_WorkerStateUploader = () => {}; - -// src/cli/transports/ccrClient.ts -import { randomUUID as randomUUID50 } from "crypto"; -function alwaysValidStatus() { - return true; -} -function createStreamAccumulator() { - return { byMessage: new Map, scopeToMessage: new Map }; -} -function scopeKey(m4) { - return `${m4.session_id}:${m4.parent_tool_use_id ?? ""}`; -} -function accumulateStreamEvents(buffer, state4) { - const out = []; - const touched = new Map; - for (const msg of buffer) { - switch (msg.event.type) { - case "message_start": { - const id = msg.event.message.id; - const prevId = state4.scopeToMessage.get(scopeKey(msg)); - if (prevId) - state4.byMessage.delete(prevId); - state4.scopeToMessage.set(scopeKey(msg), id); - state4.byMessage.set(id, []); - out.push(msg); - break; - } - case "content_block_delta": { - if (msg.event.delta.type !== "text_delta") { - out.push(msg); - break; - } - const messageId = state4.scopeToMessage.get(scopeKey(msg)); - const blocks = messageId ? state4.byMessage.get(messageId) : undefined; - if (!blocks) { - out.push(msg); - break; - } - const chunks = blocks[msg.event.index] ??= []; - chunks.push(msg.event.delta.text); - const existing = touched.get(chunks); - if (existing) { - existing.event.delta.text = chunks.join(""); - break; - } - const snapshot2 = { - type: "stream_event", - uuid: msg.uuid, - session_id: msg.session_id, - parent_tool_use_id: msg.parent_tool_use_id, - event: { - type: "content_block_delta", - index: msg.event.index, - delta: { type: "text_delta", text: chunks.join("") } - } - }; - touched.set(chunks, snapshot2); - out.push(snapshot2); - break; - } - default: - out.push(msg); - } - } - return out; -} -function clearStreamAccumulatorForMessage(state4, assistant) { - state4.byMessage.delete(assistant.message.id); - const scope = scopeKey(assistant); - if (state4.scopeToMessage.get(scope) === assistant.message.id) { - state4.scopeToMessage.delete(scope); - } -} - -class CCRClient { - workerEpoch = 0; - heartbeatIntervalMs; - heartbeatJitterFraction; - heartbeatTimer = null; - heartbeatInFlight = false; - closed = false; - consecutiveAuthFailures = 0; - currentState = null; - sessionBaseUrl; - sessionId; - http = createAxiosInstance({ keepAlive: true }); - streamEventBuffer = []; - streamEventTimer = null; - streamTextAccumulator = createStreamAccumulator(); - workerState; - eventUploader; - internalEventUploader; - deliveryUploader; - onEpochMismatch; - getAuthHeaders; - constructor(transport, sessionUrl, opts) { - this.onEpochMismatch = opts?.onEpochMismatch ?? (() => { - process.exit(1); - }); - this.heartbeatIntervalMs = opts?.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS; - this.heartbeatJitterFraction = opts?.heartbeatJitterFraction ?? 0; - this.getAuthHeaders = opts?.getAuthHeaders ?? getSessionIngressAuthHeaders; - if (sessionUrl.protocol !== "http:" && sessionUrl.protocol !== "https:") { - throw new Error(`CCRClient: Expected http(s) URL, got ${sessionUrl.protocol}`); - } - const pathname = sessionUrl.pathname.replace(/\/$/, ""); - this.sessionBaseUrl = `${sessionUrl.protocol}//${sessionUrl.host}${pathname}`; - this.sessionId = pathname.split("/").pop() || ""; - this.workerState = new WorkerStateUploader({ - send: (body) => this.request("put", "/worker", { worker_epoch: this.workerEpoch, ...body }, "PUT worker").then((r4) => r4.ok), - baseDelayMs: 500, - maxDelayMs: 30000, - jitterMs: 500 - }); - this.eventUploader = new SerialBatchEventUploader({ - maxBatchSize: 100, - maxBatchBytes: 10 * 1024 * 1024, - maxQueueSize: 1e5, - send: async (batch) => { - const result = await this.request("post", "/worker/events", { worker_epoch: this.workerEpoch, events: batch }, "client events"); - if (!result.ok) { - throw new RetryableError("client event POST failed", result.retryAfterMs); - } - }, - baseDelayMs: 500, - maxDelayMs: 30000, - jitterMs: 500 - }); - this.internalEventUploader = new SerialBatchEventUploader({ - maxBatchSize: 100, - maxBatchBytes: 10 * 1024 * 1024, - maxQueueSize: 200, - send: async (batch) => { - const result = await this.request("post", "/worker/internal-events", { worker_epoch: this.workerEpoch, events: batch }, "internal events"); - if (!result.ok) { - throw new RetryableError("internal event POST failed", result.retryAfterMs); - } - }, - baseDelayMs: 500, - maxDelayMs: 30000, - jitterMs: 500 - }); - this.deliveryUploader = new SerialBatchEventUploader({ - maxBatchSize: 64, - maxQueueSize: 64, - send: async (batch) => { - const result = await this.request("post", "/worker/events/delivery", { - worker_epoch: this.workerEpoch, - updates: batch.map((d4) => ({ - event_id: d4.eventId, - status: d4.status - })) - }, "delivery batch"); - if (!result.ok) { - throw new RetryableError("delivery POST failed", result.retryAfterMs); - } - }, - baseDelayMs: 500, - maxDelayMs: 30000, - jitterMs: 500 - }); - transport.setOnEvent((event) => { - this.reportDelivery(event.event_id, "received"); - }); - } - async initialize(epoch) { - const startMs = Date.now(); - if (Object.keys(this.getAuthHeaders()).length === 0) { - throw new CCRInitError("no_auth_headers"); - } - if (epoch === undefined) { - const rawEpoch = process.env.CLAUDE_CODE_WORKER_EPOCH; - epoch = rawEpoch ? parseInt(rawEpoch, 10) : NaN; - } - if (isNaN(epoch)) { - throw new CCRInitError("missing_epoch"); - } - this.workerEpoch = epoch; - const restoredPromise = this.getWorkerState(); - const result = await this.request("put", "/worker", { - worker_status: "idle", - worker_epoch: this.workerEpoch, - external_metadata: { - pending_action: null, - task_summary: null - } - }, "PUT worker (init)"); - if (!result.ok) { - throw new CCRInitError("worker_register_failed"); - } - this.currentState = "idle"; - this.startHeartbeat(); - registerSessionActivityCallback(() => { - this.writeEvent({ type: "keep_alive" }); - }); - logForDebugging(`CCRClient: initialized, epoch=${this.workerEpoch}`); - logForDiagnosticsNoPII("info", "cli_worker_lifecycle_initialized", { - epoch: this.workerEpoch, - duration_ms: Date.now() - startMs - }); - const { metadata, durationMs } = await restoredPromise; - if (!this.closed) { - logForDiagnosticsNoPII("info", "cli_worker_state_restored", { - duration_ms: durationMs, - had_state: metadata !== null - }); - } - return metadata; - } - async getWorkerState() { - const startMs = Date.now(); - const authHeaders = this.getAuthHeaders(); - if (Object.keys(authHeaders).length === 0) { - return { metadata: null, durationMs: 0 }; - } - const data = await this.getWithRetry(`${this.sessionBaseUrl}/worker`, authHeaders, "worker_state"); - return { - metadata: data?.worker?.external_metadata ?? null, - durationMs: Date.now() - startMs - }; - } - async request(method, path27, body, label, { timeout: timeout2 = 1e4 } = {}) { - const authHeaders = this.getAuthHeaders(); - if (Object.keys(authHeaders).length === 0) - return { ok: false }; - try { - const response7 = await this.http[method](`${this.sessionBaseUrl}${path27}`, body, { - headers: { - ...authHeaders, - "Content-Type": "application/json", - "anthropic-version": "2023-06-01", - "User-Agent": getClaudeCodeUserAgent() - }, - validateStatus: alwaysValidStatus, - timeout: timeout2 - }); - if (response7.status >= 200 && response7.status < 300) { - this.consecutiveAuthFailures = 0; - return { ok: true }; - } - if (response7.status === 409) { - this.handleEpochMismatch(); - } - if (response7.status === 401 || response7.status === 403) { - const tok = getSessionIngressAuthToken(); - const exp = tok ? decodeJwtExpiry(tok) : null; - if (exp !== null && exp * 1000 < Date.now()) { - logForDebugging(`CCRClient: session_token expired (exp=${new Date(exp * 1000).toISOString()}) \u2014 no refresh was delivered, exiting`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_worker_token_expired_no_refresh"); - this.onEpochMismatch(); - } - this.consecutiveAuthFailures++; - if (this.consecutiveAuthFailures >= MAX_CONSECUTIVE_AUTH_FAILURES) { - logForDebugging(`CCRClient: ${this.consecutiveAuthFailures} consecutive auth failures with a valid-looking token \u2014 server-side auth unrecoverable, exiting`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_worker_auth_failures_exhausted"); - this.onEpochMismatch(); - } - } - logForDebugging(`CCRClient: ${label} returned ${response7.status}`, { - level: "warn" - }); - logForDiagnosticsNoPII("warn", "cli_worker_request_failed", { - method, - path: path27, - status: response7.status - }); - if (response7.status === 429) { - const raw = response7.headers?.["retry-after"]; - const seconds = typeof raw === "string" ? parseInt(raw, 10) : NaN; - if (!isNaN(seconds) && seconds >= 0) { - return { ok: false, retryAfterMs: seconds * 1000 }; - } - } - return { ok: false }; - } catch (error46) { - logForDebugging(`CCRClient: ${label} failed: ${errorMessage(error46)}`, { - level: "warn" - }); - logForDiagnosticsNoPII("warn", "cli_worker_request_error", { - method, - path: path27, - error_code: getErrnoCode(error46) - }); - return { ok: false }; - } - } - reportState(state4, details) { - if (state4 === this.currentState && !details) - return; - this.currentState = state4; - this.workerState.enqueue({ - worker_status: state4, - requires_action_details: details ? { - tool_name: details.tool_name, - action_description: details.action_description, - request_id: details.request_id - } : null - }); - } - reportMetadata(metadata) { - this.workerState.enqueue({ external_metadata: metadata }); - } - handleEpochMismatch() { - logForDebugging("CCRClient: Epoch mismatch (409), shutting down", { - level: "error" - }); - logForDiagnosticsNoPII("error", "cli_worker_epoch_mismatch"); - this.onEpochMismatch(); - } - startHeartbeat() { - this.stopHeartbeat(); - const schedule = () => { - const jitter = this.heartbeatIntervalMs * this.heartbeatJitterFraction * (2 * Math.random() - 1); - this.heartbeatTimer = setTimeout(tick, this.heartbeatIntervalMs + jitter); - }; - const tick = () => { - this.sendHeartbeat(); - if (this.heartbeatTimer === null) - return; - schedule(); - }; - schedule(); - } - stopHeartbeat() { - if (this.heartbeatTimer) { - clearTimeout(this.heartbeatTimer); - this.heartbeatTimer = null; - } - } - async sendHeartbeat() { - if (this.heartbeatInFlight) - return; - this.heartbeatInFlight = true; - try { - const result = await this.request("post", "/worker/heartbeat", { session_id: this.sessionId, worker_epoch: this.workerEpoch }, "Heartbeat", { timeout: 5000 }); - if (result.ok) { - logForDebugging("CCRClient: Heartbeat sent"); - } - } finally { - this.heartbeatInFlight = false; - } - } - async writeEvent(message) { - if (message.type === "stream_event") { - this.streamEventBuffer.push(message); - if (!this.streamEventTimer) { - this.streamEventTimer = setTimeout(() => void this.flushStreamEventBuffer(), STREAM_EVENT_FLUSH_INTERVAL_MS); - } - return; - } - await this.flushStreamEventBuffer(); - if (message.type === "assistant") { - clearStreamAccumulatorForMessage(this.streamTextAccumulator, message); - } - await this.eventUploader.enqueue(this.toClientEvent(message)); - } - toClientEvent(message) { - const msg = message; - return { - payload: { - ...msg, - uuid: typeof msg.uuid === "string" ? msg.uuid : randomUUID50() - } - }; - } - async flushStreamEventBuffer() { - if (this.streamEventTimer) { - clearTimeout(this.streamEventTimer); - this.streamEventTimer = null; - } - if (this.streamEventBuffer.length === 0) - return; - const buffered = this.streamEventBuffer; - this.streamEventBuffer = []; - const payloads = accumulateStreamEvents(buffered, this.streamTextAccumulator); - await this.eventUploader.enqueue(payloads.map((payload) => ({ payload, ephemeral: true }))); - } - async writeInternalEvent(eventType, payload, { - isCompaction = false, - agentId - } = {}) { - const event = { - payload: { - type: eventType, - ...payload, - uuid: typeof payload.uuid === "string" ? payload.uuid : randomUUID50() - }, - ...isCompaction && { is_compaction: true }, - ...agentId && { agent_id: agentId } - }; - await this.internalEventUploader.enqueue(event); - } - flushInternalEvents() { - return this.internalEventUploader.flush(); - } - async flush() { - await this.flushStreamEventBuffer(); - return this.eventUploader.flush(); - } - async readInternalEvents() { - return this.paginatedGet("/worker/internal-events", {}, "internal_events"); - } - async readSubagentInternalEvents() { - return this.paginatedGet("/worker/internal-events", { subagents: "true" }, "subagent_events"); - } - async paginatedGet(path27, params, context7) { - const authHeaders = this.getAuthHeaders(); - if (Object.keys(authHeaders).length === 0) - return null; - const allEvents = []; - let cursor; - do { - const url3 = new URL(`${this.sessionBaseUrl}${path27}`); - for (const [k4, v6] of Object.entries(params)) { - url3.searchParams.set(k4, v6); - } - if (cursor) { - url3.searchParams.set("cursor", cursor); - } - const page = await this.getWithRetry(url3.toString(), authHeaders, context7); - if (!page) - return null; - allEvents.push(...page.data ?? []); - cursor = page.next_cursor; - } while (cursor); - logForDebugging(`CCRClient: Read ${allEvents.length} internal events from ${path27}${params.subagents ? " (subagents)" : ""}`); - return allEvents; - } - async getWithRetry(url3, authHeaders, context7) { - for (let attempt = 1;attempt <= 10; attempt++) { - let response7; - try { - response7 = await this.http.get(url3, { - headers: { - ...authHeaders, - "anthropic-version": "2023-06-01", - "User-Agent": getClaudeCodeUserAgent() - }, - validateStatus: alwaysValidStatus, - timeout: 30000 - }); - } catch (error46) { - logForDebugging(`CCRClient: GET ${url3} failed (attempt ${attempt}/10): ${errorMessage(error46)}`, { level: "warn" }); - if (attempt < 10) { - const delay4 = Math.min(500 * 2 ** (attempt - 1), 30000) + Math.random() * 500; - await sleep6(delay4); - } - continue; - } - if (response7.status >= 200 && response7.status < 300) { - return response7.data; - } - if (response7.status === 409) { - this.handleEpochMismatch(); - } - logForDebugging(`CCRClient: GET ${url3} returned ${response7.status} (attempt ${attempt}/10)`, { level: "warn" }); - if (attempt < 10) { - const delay4 = Math.min(500 * 2 ** (attempt - 1), 30000) + Math.random() * 500; - await sleep6(delay4); - } - } - logForDebugging("CCRClient: GET retries exhausted", { level: "error" }); - logForDiagnosticsNoPII("error", "cli_worker_get_retries_exhausted", { - context: context7 - }); - return null; - } - reportDelivery(eventId, status2) { - this.deliveryUploader.enqueue({ eventId, status: status2 }); - } - getWorkerEpoch() { - return this.workerEpoch; - } - get internalEventsPending() { - return this.internalEventUploader.pendingCount; - } - close() { - this.closed = true; - this.stopHeartbeat(); - unregisterSessionActivityCallback(); - if (this.streamEventTimer) { - clearTimeout(this.streamEventTimer); - this.streamEventTimer = null; - } - this.streamEventBuffer = []; - this.streamTextAccumulator.byMessage.clear(); - this.streamTextAccumulator.scopeToMessage.clear(); - this.workerState.close(); - this.eventUploader.close(); - this.internalEventUploader.close(); - this.deliveryUploader.close(); - } -} -var DEFAULT_HEARTBEAT_INTERVAL_MS = 20000, STREAM_EVENT_FLUSH_INTERVAL_MS = 100, CCRInitError, MAX_CONSECUTIVE_AUTH_FAILURES = 10; -var init_ccrClient = __esm(() => { - init_jwtUtils(); - init_debug(); - init_diagLogs(); - init_errors(); - init_proxy(); - init_sessionActivity(); - init_sessionIngressAuth(); - init_SerialBatchEventUploader(); - init_WorkerStateUploader(); - CCRInitError = class CCRInitError extends Error { - reason; - constructor(reason) { - super(`CCRClient init failed: ${reason}`); - this.reason = reason; - } - }; -}); - -// src/cli/transports/SSETransport.ts -function alwaysValidStatus2() { - return true; -} -function parseSSEFrames(buffer) { - const frames = []; - let pos = 0; - let idx; - while ((idx = buffer.indexOf(` - -`, pos)) !== -1) { - const rawFrame = buffer.slice(pos, idx); - pos = idx + 2; - if (!rawFrame.trim()) - continue; - const frame = {}; - let isComment = false; - for (const line of rawFrame.split(` -`)) { - if (line.startsWith(":")) { - isComment = true; - continue; - } - const colonIdx = line.indexOf(":"); - if (colonIdx === -1) - continue; - const field = line.slice(0, colonIdx); - const value = line[colonIdx + 1] === " " ? line.slice(colonIdx + 2) : line.slice(colonIdx + 1); - switch (field) { - case "event": - frame.event = value; - break; - case "id": - frame.id = value; - break; - case "data": - frame.data = frame.data ? frame.data + ` -` + value : value; - break; - } - } - if (frame.data || isComment) { - frames.push(frame); - } - } - return { frames, remaining: buffer.slice(pos) }; -} - -class SSETransport { - url; - state = "idle"; - onData; - onCloseCallback; - onEventCallback; - headers; - sessionId; - refreshHeaders; - getAuthHeaders; - abortController = null; - lastSequenceNum = 0; - seenSequenceNums = new Set; - reconnectAttempts = 0; - reconnectStartTime = null; - reconnectTimer = null; - livenessTimer = null; - postUrl; - constructor(url3, headers = {}, sessionId, refreshHeaders, initialSequenceNum, getAuthHeaders4) { - this.url = url3; - this.headers = headers; - this.sessionId = sessionId; - this.refreshHeaders = refreshHeaders; - this.getAuthHeaders = getAuthHeaders4 ?? getSessionIngressAuthHeaders; - this.postUrl = convertSSEUrlToPostUrl(url3); - if (initialSequenceNum !== undefined && initialSequenceNum > 0) { - this.lastSequenceNum = initialSequenceNum; - } - logForDebugging(`SSETransport: SSE URL = ${url3.href}`); - logForDebugging(`SSETransport: POST URL = ${this.postUrl}`); - logForDiagnosticsNoPII("info", "cli_sse_transport_initialized"); - } - getLastSequenceNum() { - return this.lastSequenceNum; - } - async connect() { - if (this.state !== "idle" && this.state !== "reconnecting") { - logForDebugging(`SSETransport: Cannot connect, current state is ${this.state}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_sse_connect_failed"); - return; - } - this.state = "reconnecting"; - const connectStartTime = Date.now(); - const sseUrl = new URL(this.url.href); - if (this.lastSequenceNum > 0) { - sseUrl.searchParams.set("from_sequence_num", String(this.lastSequenceNum)); - } - const authHeaders = this.getAuthHeaders(); - const headers = { - ...this.headers, - ...authHeaders, - Accept: "text/event-stream", - "anthropic-version": "2023-06-01", - "User-Agent": getClaudeCodeUserAgent() - }; - if (authHeaders["Cookie"]) { - delete headers["Authorization"]; - } - if (this.lastSequenceNum > 0) { - headers["Last-Event-ID"] = String(this.lastSequenceNum); - } - logForDebugging(`SSETransport: Opening ${sseUrl.href}`); - logForDiagnosticsNoPII("info", "cli_sse_connect_opening"); - this.abortController = new AbortController; - try { - const response7 = await fetch(sseUrl.href, { - headers, - signal: this.abortController.signal - }); - if (!response7.ok) { - const isPermanent = PERMANENT_HTTP_CODES.has(response7.status); - logForDebugging(`SSETransport: HTTP ${response7.status}${isPermanent ? " (permanent)" : ""}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_sse_connect_http_error", { - status: response7.status - }); - if (isPermanent) { - this.state = "closed"; - this.onCloseCallback?.(response7.status); - return; - } - this.handleConnectionError(); - return; - } - if (!response7.body) { - logForDebugging("SSETransport: No response body"); - this.handleConnectionError(); - return; - } - const connectDuration = Date.now() - connectStartTime; - logForDebugging("SSETransport: Connected"); - logForDiagnosticsNoPII("info", "cli_sse_connect_connected", { - duration_ms: connectDuration - }); - this.state = "connected"; - this.reconnectAttempts = 0; - this.reconnectStartTime = null; - this.resetLivenessTimer(); - await this.readStream(response7.body); - } catch (error46) { - if (this.abortController?.signal.aborted) { - return; - } - logForDebugging(`SSETransport: Connection error: ${errorMessage(error46)}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_sse_connect_error"); - this.handleConnectionError(); - } - } - async readStream(body) { - const reader = body.getReader(); - const decoder = new TextDecoder; - let buffer = ""; - try { - while (true) { - const { done, value } = await reader.read(); - if (done) - break; - buffer += decoder.decode(value, STREAM_DECODE_OPTS); - const { frames, remaining } = parseSSEFrames(buffer); - buffer = remaining; - for (const frame of frames) { - this.resetLivenessTimer(); - if (frame.id) { - const seqNum = parseInt(frame.id, 10); - if (!isNaN(seqNum)) { - if (this.seenSequenceNums.has(seqNum)) { - logForDebugging(`SSETransport: DUPLICATE frame seq=${seqNum} (lastSequenceNum=${this.lastSequenceNum}, seenCount=${this.seenSequenceNums.size})`, { level: "warn" }); - logForDiagnosticsNoPII("warn", "cli_sse_duplicate_sequence"); - } else { - this.seenSequenceNums.add(seqNum); - if (this.seenSequenceNums.size > 1000) { - const threshold = this.lastSequenceNum - 200; - for (const s4 of this.seenSequenceNums) { - if (s4 < threshold) { - this.seenSequenceNums.delete(s4); - } - } - } - } - if (seqNum > this.lastSequenceNum) { - this.lastSequenceNum = seqNum; - } - } - } - if (frame.event && frame.data) { - this.handleSSEFrame(frame.event, frame.data); - } else if (frame.data) { - logForDebugging("SSETransport: Frame has data: but no event: field \u2014 dropped", { level: "warn" }); - logForDiagnosticsNoPII("warn", "cli_sse_frame_missing_event_field"); - } - } - } - } catch (error46) { - if (this.abortController?.signal.aborted) - return; - logForDebugging(`SSETransport: Stream read error: ${errorMessage(error46)}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_sse_stream_read_error"); - } finally { - reader.releaseLock(); - } - if (this.state !== "closing" && this.state !== "closed") { - logForDebugging("SSETransport: Stream ended, reconnecting"); - this.handleConnectionError(); - } - } - handleSSEFrame(eventType, data) { - if (eventType !== "client_event") { - logForDebugging(`SSETransport: Unexpected SSE event type '${eventType}' on worker stream`, { level: "warn" }); - logForDiagnosticsNoPII("warn", "cli_sse_unexpected_event_type", { - event_type: eventType - }); - return; - } - let ev; - try { - ev = jsonParse(data); - } catch (error46) { - logForDebugging(`SSETransport: Failed to parse client_event data: ${errorMessage(error46)}`, { level: "error" }); - return; - } - const payload = ev.payload; - if (payload && typeof payload === "object" && "type" in payload) { - const sessionLabel = this.sessionId ? ` session=${this.sessionId}` : ""; - logForDebugging(`SSETransport: Event seq=${ev.sequence_num} event_id=${ev.event_id} event_type=${ev.event_type} payload_type=${String(payload.type)}${sessionLabel}`); - logForDiagnosticsNoPII("info", "cli_sse_message_received"); - this.onData?.(jsonStringify(payload) + ` -`); - } else { - logForDebugging(`SSETransport: Ignoring client_event with no type in payload: event_id=${ev.event_id}`); - } - this.onEventCallback?.(ev); - } - handleConnectionError() { - this.clearLivenessTimer(); - if (this.state === "closing" || this.state === "closed") - return; - this.abortController?.abort(); - this.abortController = null; - const now2 = Date.now(); - if (!this.reconnectStartTime) { - this.reconnectStartTime = now2; - } - const elapsed = now2 - this.reconnectStartTime; - if (elapsed < RECONNECT_GIVE_UP_MS) { - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - if (this.refreshHeaders) { - const freshHeaders = this.refreshHeaders(); - Object.assign(this.headers, freshHeaders); - logForDebugging("SSETransport: Refreshed headers for reconnect"); - } - this.state = "reconnecting"; - this.reconnectAttempts++; - const baseDelay = Math.min(RECONNECT_BASE_DELAY_MS * Math.pow(2, this.reconnectAttempts - 1), RECONNECT_MAX_DELAY_MS); - const delay4 = Math.max(0, baseDelay + baseDelay * 0.25 * (2 * Math.random() - 1)); - logForDebugging(`SSETransport: Reconnecting in ${Math.round(delay4)}ms (attempt ${this.reconnectAttempts}, ${Math.round(elapsed / 1000)}s elapsed)`); - logForDiagnosticsNoPII("error", "cli_sse_reconnect_attempt", { - reconnectAttempts: this.reconnectAttempts - }); - this.reconnectTimer = setTimeout(() => { - this.reconnectTimer = null; - this.connect(); - }, delay4); - } else { - logForDebugging(`SSETransport: Reconnection time budget exhausted after ${Math.round(elapsed / 1000)}s`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_sse_reconnect_exhausted", { - reconnectAttempts: this.reconnectAttempts, - elapsedMs: elapsed - }); - this.state = "closed"; - this.onCloseCallback?.(); - } - } - onLivenessTimeout = () => { - this.livenessTimer = null; - logForDebugging("SSETransport: Liveness timeout, reconnecting", { - level: "error" - }); - logForDiagnosticsNoPII("error", "cli_sse_liveness_timeout"); - this.abortController?.abort(); - this.handleConnectionError(); - }; - resetLivenessTimer() { - this.clearLivenessTimer(); - this.livenessTimer = setTimeout(this.onLivenessTimeout, LIVENESS_TIMEOUT_MS); - } - clearLivenessTimer() { - if (this.livenessTimer) { - clearTimeout(this.livenessTimer); - this.livenessTimer = null; - } - } - async write(message) { - const authHeaders = this.getAuthHeaders(); - if (Object.keys(authHeaders).length === 0) { - logForDebugging("SSETransport: No session token available for POST"); - logForDiagnosticsNoPII("warn", "cli_sse_post_no_token"); - return; - } - const headers = { - ...authHeaders, - "Content-Type": "application/json", - "anthropic-version": "2023-06-01", - "User-Agent": getClaudeCodeUserAgent() - }; - logForDebugging(`SSETransport: POST body keys=${Object.keys(message).join(",")}`); - for (let attempt = 1;attempt <= POST_MAX_RETRIES; attempt++) { - try { - const response7 = await axios_default.post(this.postUrl, message, { - headers, - validateStatus: alwaysValidStatus2 - }); - if (response7.status === 200 || response7.status === 201) { - logForDebugging(`SSETransport: POST success type=${message.type}`); - return; - } - logForDebugging(`SSETransport: POST ${response7.status} body=${jsonStringify(response7.data).slice(0, 200)}`); - if (response7.status >= 400 && response7.status < 500 && response7.status !== 429) { - logForDebugging(`SSETransport: POST returned ${response7.status} (client error), not retrying`); - logForDiagnosticsNoPII("warn", "cli_sse_post_client_error", { - status: response7.status - }); - return; - } - logForDebugging(`SSETransport: POST returned ${response7.status}, attempt ${attempt}/${POST_MAX_RETRIES}`); - logForDiagnosticsNoPII("warn", "cli_sse_post_retryable_error", { - status: response7.status, - attempt - }); - } catch (error46) { - const axiosError = error46; - logForDebugging(`SSETransport: POST error: ${axiosError.message}, attempt ${attempt}/${POST_MAX_RETRIES}`); - logForDiagnosticsNoPII("warn", "cli_sse_post_network_error", { - attempt - }); - } - if (attempt === POST_MAX_RETRIES) { - logForDebugging(`SSETransport: POST failed after ${POST_MAX_RETRIES} attempts, continuing`); - logForDiagnosticsNoPII("warn", "cli_sse_post_retries_exhausted"); - return; - } - const delayMs = Math.min(POST_BASE_DELAY_MS * Math.pow(2, attempt - 1), POST_MAX_DELAY_MS); - await sleep6(delayMs); - } - } - isConnectedStatus() { - return this.state === "connected"; - } - isClosedStatus() { - return this.state === "closed"; - } - setOnData(callback) { - this.onData = callback; - } - setOnClose(callback) { - this.onCloseCallback = callback; - } - setOnEvent(callback) { - this.onEventCallback = callback; - } - close() { - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - this.clearLivenessTimer(); - this.state = "closing"; - this.abortController?.abort(); - this.abortController = null; - } -} -function convertSSEUrlToPostUrl(sseUrl) { - let pathname = sseUrl.pathname; - if (pathname.endsWith("/stream")) { - pathname = pathname.slice(0, -"/stream".length); - } - return `${sseUrl.protocol}//${sseUrl.host}${pathname}`; -} -var RECONNECT_BASE_DELAY_MS = 1000, RECONNECT_MAX_DELAY_MS = 30000, RECONNECT_GIVE_UP_MS = 600000, LIVENESS_TIMEOUT_MS = 45000, PERMANENT_HTTP_CODES, POST_MAX_RETRIES = 10, POST_BASE_DELAY_MS = 500, POST_MAX_DELAY_MS = 8000, STREAM_DECODE_OPTS; -var init_SSETransport = __esm(() => { - init_axios2(); - init_debug(); - init_diagLogs(); - init_errors(); - init_sessionIngressAuth(); - init_slowOperations(); - PERMANENT_HTTP_CODES = new Set([401, 403, 404]); - STREAM_DECODE_OPTS = { stream: true }; -}); - -// src/cli/transports/WebSocketTransport.ts -class WebSocketTransport2 { - ws = null; - lastSentId = null; - url; - state = "idle"; - onData; - onCloseCallback; - onConnectCallback; - headers; - sessionId; - autoReconnect; - isBridge; - reconnectAttempts = 0; - reconnectStartTime = null; - reconnectTimer = null; - lastReconnectAttemptTime = null; - lastActivityTime = 0; - pingInterval = null; - pongReceived = true; - keepAliveInterval = null; - messageBuffer; - isBunWs = false; - connectStartTime = 0; - refreshHeaders; - constructor(url3, headers = {}, sessionId, refreshHeaders, options2) { - this.url = url3; - this.headers = headers; - this.sessionId = sessionId; - this.refreshHeaders = refreshHeaders; - this.autoReconnect = options2?.autoReconnect ?? true; - this.isBridge = options2?.isBridge ?? false; - this.messageBuffer = new CircularBuffer(DEFAULT_MAX_BUFFER_SIZE); - } - async connect() { - if (this.state !== "idle" && this.state !== "reconnecting") { - logForDebugging(`WebSocketTransport: Cannot connect, current state is ${this.state}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_connect_failed"); - return; - } - this.state = "reconnecting"; - this.connectStartTime = Date.now(); - logForDebugging(`WebSocketTransport: Opening ${this.url.href}`); - logForDiagnosticsNoPII("info", "cli_websocket_connect_opening"); - const headers = { ...this.headers }; - if (this.lastSentId) { - headers["X-Last-Request-Id"] = this.lastSentId; - logForDebugging(`WebSocketTransport: Adding X-Last-Request-Id header: ${this.lastSentId}`); - } - if (typeof Bun !== "undefined") { - const ws = new globalThis.WebSocket(this.url.href, { - headers, - proxy: getWebSocketProxyUrl(this.url.href), - tls: getWebSocketTLSOptions() || undefined - }); - this.ws = ws; - this.isBunWs = true; - ws.addEventListener("open", this.onBunOpen); - ws.addEventListener("message", this.onBunMessage); - ws.addEventListener("error", this.onBunError); - ws.addEventListener("close", this.onBunClose); - ws.addEventListener("pong", this.onPong); - } else { - const { default: WS } = await import("ws"); - const ws = new WS(this.url.href, { - headers, - agent: getWebSocketProxyAgent(this.url.href), - ...getWebSocketTLSOptions() - }); - this.ws = ws; - this.isBunWs = false; - ws.on("open", this.onNodeOpen); - ws.on("message", this.onNodeMessage); - ws.on("error", this.onNodeError); - ws.on("close", this.onNodeClose); - ws.on("pong", this.onPong); - } - } - onBunOpen = () => { - this.handleOpenEvent(); - if (this.lastSentId) { - this.replayBufferedMessages(""); - } - }; - onBunMessage = (event) => { - const message = typeof event.data === "string" ? event.data : String(event.data); - this.lastActivityTime = Date.now(); - logForDiagnosticsNoPII("info", "cli_websocket_message_received", { - length: message.length - }); - if (this.onData) { - this.onData(message); - } - }; - onBunError = () => { - logForDebugging("WebSocketTransport: Error", { - level: "error" - }); - logForDiagnosticsNoPII("error", "cli_websocket_connect_error"); - }; - onBunClose = (event) => { - const isClean = event.code === 1000 || event.code === 1001; - logForDebugging(`WebSocketTransport: Closed: ${event.code}`, isClean ? undefined : { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_connect_closed"); - this.handleConnectionError(event.code); - }; - onNodeOpen = () => { - const ws = this.ws; - this.handleOpenEvent(); - if (!ws) - return; - const nws = ws; - const upgradeResponse = nws.upgradeReq; - if (upgradeResponse?.headers?.["x-last-request-id"]) { - const serverLastId = upgradeResponse.headers["x-last-request-id"]; - this.replayBufferedMessages(serverLastId); - } - }; - onNodeMessage = (data) => { - const message = data.toString(); - this.lastActivityTime = Date.now(); - logForDiagnosticsNoPII("info", "cli_websocket_message_received", { - length: message.length - }); - if (this.onData) { - this.onData(message); - } - }; - onNodeError = (err2) => { - logForDebugging(`WebSocketTransport: Error: ${err2.message}`, { - level: "error" - }); - logForDiagnosticsNoPII("error", "cli_websocket_connect_error"); - }; - onNodeClose = (code, _reason) => { - const isClean = code === 1000 || code === 1001; - logForDebugging(`WebSocketTransport: Closed: ${code}`, isClean ? undefined : { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_connect_closed"); - this.handleConnectionError(code); - }; - onPong = () => { - this.pongReceived = true; - }; - handleOpenEvent() { - const connectDuration = Date.now() - this.connectStartTime; - logForDebugging("WebSocketTransport: Connected"); - logForDiagnosticsNoPII("info", "cli_websocket_connect_connected", { - duration_ms: connectDuration - }); - if (this.isBridge && this.reconnectStartTime !== null) { - logEvent("tengu_ws_transport_reconnected", { - attempts: this.reconnectAttempts, - downtimeMs: Date.now() - this.reconnectStartTime - }); - } - this.reconnectAttempts = 0; - this.reconnectStartTime = null; - this.lastReconnectAttemptTime = null; - this.lastActivityTime = Date.now(); - this.state = "connected"; - this.onConnectCallback?.(); - this.startPingInterval(); - this.startKeepaliveInterval(); - registerSessionActivityCallback(() => { - this.write({ type: "keep_alive" }); - }); - } - sendLine(line) { - if (!this.ws || this.state !== "connected") { - logForDebugging("WebSocketTransport: Not connected"); - logForDiagnosticsNoPII("info", "cli_websocket_send_not_connected"); - return false; - } - try { - this.ws.send(line); - this.lastActivityTime = Date.now(); - return true; - } catch (error46) { - logForDebugging(`WebSocketTransport: Failed to send: ${error46}`, { - level: "error" - }); - logForDiagnosticsNoPII("error", "cli_websocket_send_error"); - this.handleConnectionError(); - return false; - } - } - removeWsListeners(ws) { - if (this.isBunWs) { - const nws = ws; - nws.removeEventListener("open", this.onBunOpen); - nws.removeEventListener("message", this.onBunMessage); - nws.removeEventListener("error", this.onBunError); - nws.removeEventListener("close", this.onBunClose); - nws.removeEventListener("pong", this.onPong); - } else { - const nws = ws; - nws.off("open", this.onNodeOpen); - nws.off("message", this.onNodeMessage); - nws.off("error", this.onNodeError); - nws.off("close", this.onNodeClose); - nws.off("pong", this.onPong); - } - } - doDisconnect() { - this.stopPingInterval(); - this.stopKeepaliveInterval(); - unregisterSessionActivityCallback(); - if (this.ws) { - this.removeWsListeners(this.ws); - this.ws.close(); - this.ws = null; - } - } - handleConnectionError(closeCode) { - logForDebugging(`WebSocketTransport: Disconnected from ${this.url.href}` + (closeCode != null ? ` (code ${closeCode})` : "")); - logForDiagnosticsNoPII("info", "cli_websocket_disconnected"); - if (this.isBridge) { - logEvent("tengu_ws_transport_closed", { - closeCode, - msSinceLastActivity: this.lastActivityTime > 0 ? Date.now() - this.lastActivityTime : -1, - wasConnected: this.state === "connected", - reconnectAttempts: this.reconnectAttempts - }); - } - this.doDisconnect(); - if (this.state === "closing" || this.state === "closed") - return; - let headersRefreshed = false; - if (closeCode === 4003 && this.refreshHeaders) { - const freshHeaders = this.refreshHeaders(); - if (freshHeaders.Authorization !== this.headers.Authorization) { - Object.assign(this.headers, freshHeaders); - headersRefreshed = true; - logForDebugging("WebSocketTransport: 4003 received but headers refreshed, scheduling reconnect"); - logForDiagnosticsNoPII("info", "cli_websocket_4003_token_refreshed"); - } - } - if (closeCode != null && PERMANENT_CLOSE_CODES2.has(closeCode) && !headersRefreshed) { - logForDebugging(`WebSocketTransport: Permanent close code ${closeCode}, not reconnecting`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_permanent_close", { - closeCode - }); - this.state = "closed"; - this.onCloseCallback?.(closeCode); - return; - } - if (!this.autoReconnect) { - this.state = "closed"; - this.onCloseCallback?.(closeCode); - return; - } - const now2 = Date.now(); - if (!this.reconnectStartTime) { - this.reconnectStartTime = now2; - } - if (this.lastReconnectAttemptTime !== null && now2 - this.lastReconnectAttemptTime > SLEEP_DETECTION_THRESHOLD_MS) { - logForDebugging(`WebSocketTransport: Detected system sleep (${Math.round((now2 - this.lastReconnectAttemptTime) / 1000)}s gap), resetting reconnection budget`); - logForDiagnosticsNoPII("info", "cli_websocket_sleep_detected", { - gapMs: now2 - this.lastReconnectAttemptTime - }); - this.reconnectStartTime = now2; - this.reconnectAttempts = 0; - } - this.lastReconnectAttemptTime = now2; - const elapsed = now2 - this.reconnectStartTime; - if (elapsed < DEFAULT_RECONNECT_GIVE_UP_MS) { - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - if (!headersRefreshed && this.refreshHeaders) { - const freshHeaders = this.refreshHeaders(); - Object.assign(this.headers, freshHeaders); - logForDebugging("WebSocketTransport: Refreshed headers for reconnect"); - } - this.state = "reconnecting"; - this.reconnectAttempts++; - const baseDelay = Math.min(DEFAULT_BASE_RECONNECT_DELAY * Math.pow(2, this.reconnectAttempts - 1), DEFAULT_MAX_RECONNECT_DELAY); - const delay4 = Math.max(0, baseDelay + baseDelay * 0.25 * (2 * Math.random() - 1)); - logForDebugging(`WebSocketTransport: Reconnecting in ${Math.round(delay4)}ms (attempt ${this.reconnectAttempts}, ${Math.round(elapsed / 1000)}s elapsed)`); - logForDiagnosticsNoPII("error", "cli_websocket_reconnect_attempt", { - reconnectAttempts: this.reconnectAttempts - }); - if (this.isBridge) { - logEvent("tengu_ws_transport_reconnecting", { - attempt: this.reconnectAttempts, - elapsedMs: elapsed, - delayMs: Math.round(delay4) - }); - } - this.reconnectTimer = setTimeout(() => { - this.reconnectTimer = null; - this.connect(); - }, delay4); - } else { - logForDebugging(`WebSocketTransport: Reconnection time budget exhausted after ${Math.round(elapsed / 1000)}s for ${this.url.href}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_reconnect_exhausted", { - reconnectAttempts: this.reconnectAttempts, - elapsedMs: elapsed - }); - this.state = "closed"; - if (this.onCloseCallback) { - this.onCloseCallback(closeCode); - } - } - } - close() { - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - this.stopPingInterval(); - this.stopKeepaliveInterval(); - unregisterSessionActivityCallback(); - this.state = "closing"; - this.doDisconnect(); - } - replayBufferedMessages(lastId) { - const messages = this.messageBuffer.toArray(); - if (messages.length === 0) - return; - let startIndex = 0; - if (lastId) { - const lastConfirmedIndex = messages.findIndex((message) => ("uuid" in message) && message.uuid === lastId); - if (lastConfirmedIndex >= 0) { - startIndex = lastConfirmedIndex + 1; - const remaining = messages.slice(startIndex); - this.messageBuffer.clear(); - this.messageBuffer.addAll(remaining); - if (remaining.length === 0) { - this.lastSentId = null; - } - logForDebugging(`WebSocketTransport: Evicted ${startIndex} confirmed messages, ${remaining.length} remaining`); - logForDiagnosticsNoPII("info", "cli_websocket_evicted_confirmed_messages", { - evicted: startIndex, - remaining: remaining.length - }); - } - } - const messagesToReplay = messages.slice(startIndex); - if (messagesToReplay.length === 0) { - logForDebugging("WebSocketTransport: No new messages to replay"); - logForDiagnosticsNoPII("info", "cli_websocket_no_messages_to_replay"); - return; - } - logForDebugging(`WebSocketTransport: Replaying ${messagesToReplay.length} buffered messages`); - logForDiagnosticsNoPII("info", "cli_websocket_messages_to_replay", { - count: messagesToReplay.length - }); - for (const message of messagesToReplay) { - const line = jsonStringify(message) + ` -`; - const success2 = this.sendLine(line); - if (!success2) { - this.handleConnectionError(); - break; - } - } - } - isConnectedStatus() { - return this.state === "connected"; - } - isClosedStatus() { - return this.state === "closed"; - } - setOnData(callback) { - this.onData = callback; - } - setOnConnect(callback) { - this.onConnectCallback = callback; - } - setOnClose(callback) { - this.onCloseCallback = callback; - } - getStateLabel() { - return this.state; - } - async write(message) { - if ("uuid" in message && typeof message.uuid === "string") { - this.messageBuffer.add(message); - this.lastSentId = message.uuid; - } - const line = jsonStringify(message) + ` -`; - if (this.state !== "connected") { - return; - } - const sessionLabel = this.sessionId ? ` session=${this.sessionId}` : ""; - const detailLabel = this.getControlMessageDetailLabel(message); - logForDebugging(`WebSocketTransport: Sending message type=${message.type}${sessionLabel}${detailLabel}`); - this.sendLine(line); - } - getControlMessageDetailLabel(message) { - if (message.type === "control_request") { - const { request_id, request: request2 } = message; - const toolName = request2.subtype === "can_use_tool" ? request2.tool_name : ""; - return ` subtype=${request2.subtype} request_id=${request_id}${toolName ? ` tool=${toolName}` : ""}`; - } - if (message.type === "control_response") { - const { subtype, request_id } = message.response; - return ` subtype=${subtype} request_id=${request_id}`; - } - return ""; - } - startPingInterval() { - this.stopPingInterval(); - this.pongReceived = true; - let lastTickTime = Date.now(); - this.pingInterval = setInterval(() => { - if (this.state === "connected" && this.ws) { - const now2 = Date.now(); - const gap = now2 - lastTickTime; - lastTickTime = now2; - if (gap > SLEEP_DETECTION_THRESHOLD_MS) { - logForDebugging(`WebSocketTransport: ${Math.round(gap / 1000)}s tick gap detected \u2014 process was suspended, forcing reconnect`); - logForDiagnosticsNoPII("info", "cli_websocket_sleep_detected_on_ping", { gapMs: gap }); - this.handleConnectionError(); - return; - } - if (!this.pongReceived) { - logForDebugging("WebSocketTransport: No pong received, connection appears dead", { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_pong_timeout"); - this.handleConnectionError(); - return; - } - this.pongReceived = false; - try { - this.ws.ping?.(); - } catch (error46) { - logForDebugging(`WebSocketTransport: Ping failed: ${error46}`, { - level: "error" - }); - logForDiagnosticsNoPII("error", "cli_websocket_ping_failed"); - } - } - }, DEFAULT_PING_INTERVAL); - } - stopPingInterval() { - if (this.pingInterval) { - clearInterval(this.pingInterval); - this.pingInterval = null; - } - } - startKeepaliveInterval() { - this.stopKeepaliveInterval(); - if (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) { - return; - } - this.keepAliveInterval = setInterval(() => { - if (this.state === "connected" && this.ws) { - try { - this.ws.send(KEEP_ALIVE_FRAME); - this.lastActivityTime = Date.now(); - logForDebugging("WebSocketTransport: Sent periodic keep_alive data frame"); - } catch (error46) { - logForDebugging(`WebSocketTransport: Periodic keep_alive failed: ${error46}`, { level: "error" }); - logForDiagnosticsNoPII("error", "cli_websocket_keepalive_failed"); - } - } - }, DEFAULT_KEEPALIVE_INTERVAL); - } - stopKeepaliveInterval() { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - this.keepAliveInterval = null; - } - } -} -var KEEP_ALIVE_FRAME = `{"type":"keep_alive"} -`, DEFAULT_MAX_BUFFER_SIZE = 1000, DEFAULT_BASE_RECONNECT_DELAY = 1000, DEFAULT_MAX_RECONNECT_DELAY = 30000, DEFAULT_RECONNECT_GIVE_UP_MS = 600000, DEFAULT_PING_INTERVAL = 1e4, DEFAULT_KEEPALIVE_INTERVAL = 300000, SLEEP_DETECTION_THRESHOLD_MS, PERMANENT_CLOSE_CODES2; -var init_WebSocketTransport = __esm(() => { - init_analytics(); - init_debug(); - init_diagLogs(); - init_envUtils(); - init_mtls(); - init_proxy(); - init_sessionActivity(); - init_slowOperations(); - SLEEP_DETECTION_THRESHOLD_MS = DEFAULT_MAX_RECONNECT_DELAY * 2; - PERMANENT_CLOSE_CODES2 = new Set([ - 1002, - 4001, - 4003 - ]); -}); - -// src/cli/transports/HybridTransport.ts -function convertWsUrlToPostUrl(wsUrl) { - const protocol = wsUrl.protocol === "wss:" ? "https:" : "http:"; - let pathname = wsUrl.pathname; - pathname = pathname.replace("/ws/", "/session/"); - if (!pathname.endsWith("/events")) { - pathname = pathname.endsWith("/") ? pathname + "events" : pathname + "/events"; - } - return `${protocol}//${wsUrl.host}${pathname}${wsUrl.search}`; -} -var BATCH_FLUSH_INTERVAL_MS = 100, POST_TIMEOUT_MS = 15000, CLOSE_GRACE_MS = 3000, HybridTransport; -var init_HybridTransport = __esm(() => { - init_axios2(); - init_debug(); - init_diagLogs(); - init_sessionIngressAuth(); - init_SerialBatchEventUploader(); - init_WebSocketTransport(); - HybridTransport = class HybridTransport extends WebSocketTransport2 { - postUrl; - uploader; - streamEventBuffer = []; - streamEventTimer = null; - constructor(url3, headers = {}, sessionId, refreshHeaders, options2) { - super(url3, headers, sessionId, refreshHeaders, options2); - const { maxConsecutiveFailures, onBatchDropped } = options2 ?? {}; - this.postUrl = convertWsUrlToPostUrl(url3); - this.uploader = new SerialBatchEventUploader({ - maxBatchSize: 500, - maxQueueSize: 1e5, - baseDelayMs: 500, - maxDelayMs: 8000, - jitterMs: 1000, - maxConsecutiveFailures, - onBatchDropped: (batchSize, failures) => { - logForDiagnosticsNoPII("error", "cli_hybrid_batch_dropped_max_failures", { - batchSize, - failures - }); - onBatchDropped?.(batchSize, failures); - }, - send: (batch) => this.postOnce(batch) - }); - logForDebugging(`HybridTransport: POST URL = ${this.postUrl}`); - logForDiagnosticsNoPII("info", "cli_hybrid_transport_initialized"); - } - async write(message) { - if (message.type === "stream_event") { - this.streamEventBuffer.push(message); - if (!this.streamEventTimer) { - this.streamEventTimer = setTimeout(() => this.flushStreamEvents(), BATCH_FLUSH_INTERVAL_MS); - } - return; - } - await this.uploader.enqueue([...this.takeStreamEvents(), message]); - return this.uploader.flush(); - } - async writeBatch(messages) { - await this.uploader.enqueue([...this.takeStreamEvents(), ...messages]); - return this.uploader.flush(); - } - get droppedBatchCount() { - return this.uploader.droppedBatchCount; - } - flush() { - this.uploader.enqueue(this.takeStreamEvents()); - return this.uploader.flush(); - } - takeStreamEvents() { - if (this.streamEventTimer) { - clearTimeout(this.streamEventTimer); - this.streamEventTimer = null; - } - const buffered = this.streamEventBuffer; - this.streamEventBuffer = []; - return buffered; - } - flushStreamEvents() { - this.streamEventTimer = null; - this.uploader.enqueue(this.takeStreamEvents()); - } - close() { - if (this.streamEventTimer) { - clearTimeout(this.streamEventTimer); - this.streamEventTimer = null; - } - this.streamEventBuffer = []; - const uploader = this.uploader; - let graceTimer; - Promise.race([ - uploader.flush(), - new Promise((r4) => { - graceTimer = setTimeout(r4, CLOSE_GRACE_MS); - }) - ]).finally(() => { - clearTimeout(graceTimer); - uploader.close(); - }); - super.close(); - } - async postOnce(events2) { - const sessionToken = getSessionIngressAuthToken(); - if (!sessionToken) { - logForDebugging("HybridTransport: No session token available for POST"); - logForDiagnosticsNoPII("warn", "cli_hybrid_post_no_token"); - return; - } - const headers = { - Authorization: `Bearer ${sessionToken}`, - "Content-Type": "application/json" - }; - let response7; - try { - response7 = await axios_default.post(this.postUrl, { events: events2 }, { - headers, - validateStatus: () => true, - timeout: POST_TIMEOUT_MS - }); - } catch (error46) { - const axiosError = error46; - logForDebugging(`HybridTransport: POST error: ${axiosError.message}`); - logForDiagnosticsNoPII("warn", "cli_hybrid_post_network_error"); - throw error46; - } - if (response7.status >= 200 && response7.status < 300) { - logForDebugging(`HybridTransport: POST success count=${events2.length}`); - return; - } - if (response7.status >= 400 && response7.status < 500 && response7.status !== 429) { - logForDebugging(`HybridTransport: POST returned ${response7.status} (permanent), dropping`); - logForDiagnosticsNoPII("warn", "cli_hybrid_post_client_error", { - status: response7.status - }); - return; - } - logForDebugging(`HybridTransport: POST returned ${response7.status} (retryable)`); - logForDiagnosticsNoPII("warn", "cli_hybrid_post_retryable_error", { - status: response7.status - }); - throw new Error(`POST failed with ${response7.status}`); - } - }; -}); - -// src/cli/transports/transportUtils.ts -import { URL as URL2 } from "url"; -function getTransportForUrl(url3, headers = {}, sessionId, refreshHeaders) { - if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) { - const sseUrl = new URL2(url3.href); - if (sseUrl.protocol === "wss:") { - sseUrl.protocol = "https:"; - } else if (sseUrl.protocol === "ws:") { - sseUrl.protocol = "http:"; - } - sseUrl.pathname = sseUrl.pathname.replace(/\/$/, "") + "/worker/events/stream"; - return new SSETransport(sseUrl, headers, sessionId, refreshHeaders); - } - if (url3.protocol === "ws:" || url3.protocol === "wss:") { - if (isEnvTruthy(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)) { - return new HybridTransport(url3, headers, sessionId, refreshHeaders); - } - return new WebSocketTransport2(url3, headers, sessionId, refreshHeaders); - } else { - throw new Error(`Unsupported protocol: ${url3.protocol}`); - } -} -var init_transportUtils = __esm(() => { - init_envUtils(); - init_HybridTransport(); - init_SSETransport(); - init_WebSocketTransport(); -}); - -// src/cli/remoteIO.ts -import { PassThrough as PassThrough5 } from "stream"; -import { URL as URL3 } from "url"; -var RemoteIO; -var init_remoteIO = __esm(() => { - init_state(); - init_pollConfig(); - init_cleanupRegistry(); - init_debug(); - init_diagLogs(); - init_envUtils(); - init_errors(); - init_gracefulShutdown(); - init_log2(); - init_sessionIngressAuth(); - init_sessionState(); - init_sessionStorage(); - init_ndjsonSafeStringify(); - init_structuredIO(); - init_ccrClient(); - init_SSETransport(); - init_transportUtils(); - RemoteIO = class RemoteIO extends StructuredIO { - url; - transport; - inputStream; - isBridge = false; - isDebug = false; - ccrClient = null; - keepAliveTimer = null; - constructor(streamUrl, initialPrompt, replayUserMessages) { - const inputStream = new PassThrough5({ encoding: "utf8" }); - super(inputStream, replayUserMessages); - this.inputStream = inputStream; - this.url = new URL3(streamUrl); - const headers = {}; - const sessionToken = getSessionIngressAuthToken(); - if (sessionToken) { - headers["Authorization"] = `Bearer ${sessionToken}`; - } else { - logForDebugging("[remote-io] No session ingress token available", { - level: "error" - }); - } - const erVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION; - if (erVersion) { - headers["x-environment-runner-version"] = erVersion; - } - const refreshHeaders = () => { - const h5 = {}; - const freshToken = getSessionIngressAuthToken(); - if (freshToken) { - h5["Authorization"] = `Bearer ${freshToken}`; - } - const freshErVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION; - if (freshErVersion) { - h5["x-environment-runner-version"] = freshErVersion; - } - return h5; - }; - this.transport = getTransportForUrl(this.url, headers, getSessionId(), refreshHeaders); - this.isBridge = process.env.CLAUDE_CODE_ENVIRONMENT_KIND === "bridge"; - this.isDebug = isDebugMode(); - this.transport.setOnData((data) => { - this.inputStream.write(data); - if (this.isBridge && this.isDebug) { - writeToStdout(data.endsWith(` -`) ? data : data + ` -`); - } - }); - this.transport.setOnClose(() => { - this.inputStream.end(); - }); - if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) { - if (!(this.transport instanceof SSETransport)) { - throw new Error("CCR v2 requires SSETransport; check getTransportForUrl"); - } - this.ccrClient = new CCRClient(this.transport, this.url); - const init3 = this.ccrClient.initialize(); - this.restoredWorkerState = init3.catch(() => null); - init3.catch((error46) => { - logForDiagnosticsNoPII("error", "cli_worker_lifecycle_init_failed", { - reason: error46 instanceof CCRInitError ? error46.reason : "unknown" - }); - logError2(new Error(`CCRClient initialization failed: ${errorMessage(error46)}`)); - gracefulShutdown(1, "other"); - }); - registerCleanup(async () => this.ccrClient?.close()); - setInternalEventWriter((eventType, payload, options2) => this.ccrClient.writeInternalEvent(eventType, payload, options2)); - setInternalEventReader(() => this.ccrClient.readInternalEvents(), () => this.ccrClient.readSubagentInternalEvents()); - const LIFECYCLE_TO_DELIVERY = { - started: "processing", - completed: "processed" - }; - setCommandLifecycleListener((uuid8, state4) => { - this.ccrClient?.reportDelivery(uuid8, LIFECYCLE_TO_DELIVERY[state4]); - }); - setSessionStateChangedListener((state4, details) => { - this.ccrClient?.reportState(state4, details); - }); - setSessionMetadataChangedListener((metadata) => { - this.ccrClient?.reportMetadata(metadata); - }); - } - this.transport.connect(); - const keepAliveIntervalMs = getPollIntervalConfig().session_keepalive_interval_v2_ms; - if (this.isBridge && keepAliveIntervalMs > 0) { - this.keepAliveTimer = setInterval(() => { - logForDebugging("[remote-io] keep_alive sent"); - this.write({ type: "keep_alive" }).catch((err2) => { - logForDebugging(`[remote-io] keep_alive write failed: ${errorMessage(err2)}`); - }); - }, keepAliveIntervalMs); - this.keepAliveTimer.unref?.(); - } - registerCleanup(async () => this.close()); - if (initialPrompt) { - const stream10 = this.inputStream; - (async () => { - for await (const chunk2 of initialPrompt) { - stream10.write(String(chunk2).replace(/\n$/, "") + ` -`); - } - })(); - } - } - flushInternalEvents() { - return this.ccrClient?.flushInternalEvents() ?? Promise.resolve(); - } - get internalEventsPending() { - return this.ccrClient?.internalEventsPending ?? 0; - } - async write(message) { - if (this.ccrClient) { - await this.ccrClient.writeEvent(message); - } else { - await this.transport.write(message); - } - if (this.isBridge) { - if (message.type === "control_request" || this.isDebug) { - writeToStdout(ndjsonSafeStringify(message) + ` -`); - } - } - } - close() { - if (this.keepAliveTimer) { - clearInterval(this.keepAliveTimer); - this.keepAliveTimer = null; - } - this.transport.close(); - this.inputStream.end(); - } - }; -}); - -// src/utils/streamlinedTransform.ts -var COMMAND_TOOLS; -var init_streamlinedTransform = __esm(() => { - init_prompt2(); - init_prompt3(); - init_prompt(); - init_prompt6(); - init_messages9(); - init_shellToolUtils(); - init_stringUtils(); - COMMAND_TOOLS = [...SHELL_TOOL_NAMES, "Tmux", TASK_STOP_TOOL_NAME]; -}); - -// src/utils/streamJsonStdoutGuard.ts -function isJsonLine(line) { - if (line.length === 0) { - return true; - } - try { - JSON.parse(line); - return true; - } catch { - return false; - } -} -function installStreamJsonStdoutGuard() { - if (installed) { - return; - } - installed = true; - originalWrite = process.stdout.write.bind(process.stdout); - process.stdout.write = function(chunk2, encodingOrCb, cb) { - const text = typeof chunk2 === "string" ? chunk2 : Buffer.from(chunk2).toString("utf-8"); - buffer += text; - let newlineIdx; - let wrote = true; - while ((newlineIdx = buffer.indexOf(` -`)) !== -1) { - const line = buffer.slice(0, newlineIdx); - buffer = buffer.slice(newlineIdx + 1); - if (isJsonLine(line)) { - wrote = originalWrite(line + ` -`); - } else { - process.stderr.write(`${STDOUT_GUARD_MARKER} ${line} -`); - logForDebugging(`streamJsonStdoutGuard diverted non-JSON stdout line: ${line.slice(0, 200)}`); - } - } - const callback = typeof encodingOrCb === "function" ? encodingOrCb : cb; - if (callback) { - queueMicrotask(() => callback()); - } - return wrote; - }; - registerCleanup(async () => { - if (buffer.length > 0) { - if (originalWrite && isJsonLine(buffer)) { - originalWrite(buffer + ` -`); - } else { - process.stderr.write(`${STDOUT_GUARD_MARKER} ${buffer} -`); - } - buffer = ""; - } - if (originalWrite) { - process.stdout.write = originalWrite; - originalWrite = null; - } - installed = false; - }); -} -var STDOUT_GUARD_MARKER = "[stdout-guard]", installed = false, buffer = "", originalWrite = null; -var init_streamJsonStdoutGuard = __esm(() => { - init_cleanupRegistry(); - init_debug(); -}); - -// src/utils/queryContext.ts -async function fetchSystemPromptParts({ - tools, - mainLoopModel, - additionalWorkingDirectories, - mcpClients, - customSystemPrompt -}) { - const [defaultSystemPrompt, userContext, systemContext] = await Promise.all([ - customSystemPrompt !== undefined ? Promise.resolve([]) : getSystemPrompt(tools, mainLoopModel, additionalWorkingDirectories, mcpClients), - getUserContext(), - customSystemPrompt !== undefined ? Promise.resolve({}) : getSystemContext() - ]); - return { defaultSystemPrompt, userContext, systemContext }; -} -async function buildSideQuestionFallbackParams({ - tools, - commands: commands7, - mcpClients, - messages, - readFileState, - getAppState, - setAppState, - customSystemPrompt, - appendSystemPrompt, - thinkingConfig, - agents: agents2 -}) { - const mainLoopModel = getMainLoopModel(); - const appState = getAppState(); - const { defaultSystemPrompt, userContext, systemContext } = await fetchSystemPromptParts({ - tools, - mainLoopModel, - additionalWorkingDirectories: Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys()), - mcpClients, - customSystemPrompt - }); - const systemPrompt = asSystemPrompt([ - ...customSystemPrompt !== undefined ? [customSystemPrompt] : defaultSystemPrompt, - ...appendSystemPrompt ? [appendSystemPrompt] : [] - ]); - const last2 = messages.at(-1); - const forkContextMessages = last2?.type === "assistant" && last2.message.stop_reason === null ? messages.slice(0, -1) : messages; - const toolUseContext = { - options: { - commands: commands7, - debug: false, - mainLoopModel, - tools, - verbose: false, - thinkingConfig: thinkingConfig ?? (shouldEnableThinkingByDefault() !== false ? { type: "adaptive" } : { type: "disabled" }), - mcpClients, - mcpResources: {}, - isNonInteractiveSession: true, - agentDefinitions: { activeAgents: agents2, allAgents: [] }, - customSystemPrompt, - appendSystemPrompt - }, - abortController: createAbortController(), - readFileState, - getAppState, - setAppState, - messages: forkContextMessages, - setInProgressToolUseIDs: () => {}, - setResponseLength: () => {}, - updateFileHistoryState: () => {}, - updateAttributionState: () => {} - }; - return { - systemPrompt, - userContext, - systemContext, - toolUseContext, - forkContextMessages - }; -} -var init_queryContext = __esm(() => { - init_prompts3(); - init_context4(); - init_abortController(); - init_model(); - init_thinking(); -}); - -// src/QueryEngine.ts -import { randomUUID as randomUUID51 } from "crypto"; - -class QueryEngine { - config; - mutableMessages; - abortController; - permissionDenials; - totalUsage; - hasHandledOrphanedPermission = false; - readFileState; - discoveredSkillNames = new Set; - loadedNestedMemoryPaths = new Set; - constructor(config10) { - this.config = config10; - this.mutableMessages = config10.initialMessages ?? []; - this.abortController = config10.abortController ?? createAbortController(); - this.permissionDenials = []; - this.readFileState = config10.readFileCache; - this.totalUsage = EMPTY_USAGE; - } - async* submitMessage(prompt, options2) { - const { - cwd: cwd2, - commands: commands7, - tools, - mcpClients, - verbose = false, - thinkingConfig, - maxTurns, - maxBudgetUsd, - taskBudget, - canUseTool, - customSystemPrompt, - appendSystemPrompt, - userSpecifiedModel, - fallbackModel, - jsonSchema, - getAppState, - setAppState, - replayUserMessages = false, - includePartialMessages = false, - agents: agents2 = [], - setSDKStatus, - orphanedPermission - } = this.config; - this.discoveredSkillNames.clear(); - setCwd(cwd2); - const persistSession = !isSessionPersistenceDisabled(); - const startTime = Date.now(); - const wrappedCanUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => { - const result2 = await canUseTool(tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision); - if (result2.behavior !== "allow") { - this.permissionDenials.push({ - tool_name: sdkCompatToolName(tool.name), - tool_use_id: toolUseID, - tool_input: input - }); - } - return result2; - }; - const initialAppState = getAppState(); - const initialMainLoopModel = userSpecifiedModel ? parseUserSpecifiedModel(userSpecifiedModel) : getMainLoopModel(); - const initialThinkingConfig = thinkingConfig ? thinkingConfig : shouldEnableThinkingByDefault() !== false ? { type: "adaptive" } : { type: "disabled" }; - headlessProfilerCheckpoint("before_getSystemPrompt"); - const customPrompt = typeof customSystemPrompt === "string" ? customSystemPrompt : undefined; - const { - defaultSystemPrompt, - userContext: baseUserContext, - systemContext - } = await fetchSystemPromptParts({ - tools, - mainLoopModel: initialMainLoopModel, - additionalWorkingDirectories: Array.from(initialAppState.toolPermissionContext.additionalWorkingDirectories.keys()), - mcpClients, - customSystemPrompt: customPrompt - }); - headlessProfilerCheckpoint("after_getSystemPrompt"); - const userContext = { - ...baseUserContext, - ...getCoordinatorUserContext2(mcpClients, isScratchpadEnabled() ? getScratchpadDir() : undefined) - }; - const memoryMechanicsPrompt = customPrompt !== undefined && hasAutoMemPathOverride() ? await loadMemoryPrompt() : null; - const systemPrompt = asSystemPrompt([ - ...customPrompt !== undefined ? [customPrompt] : defaultSystemPrompt, - ...memoryMechanicsPrompt ? [memoryMechanicsPrompt] : [], - ...appendSystemPrompt ? [appendSystemPrompt] : [] - ]); - const hasStructuredOutputTool = tools.some((t4) => toolMatchesName(t4, SYNTHETIC_OUTPUT_TOOL_NAME)); - if (jsonSchema && hasStructuredOutputTool) { - registerStructuredOutputEnforcement(setAppState, getSessionId()); - } - let processUserInputContext = { - messages: this.mutableMessages, - setMessages: (fn) => { - this.mutableMessages = fn(this.mutableMessages); - }, - onChangeAPIKey: () => {}, - handleElicitation: this.config.handleElicitation, - options: { - commands: commands7, - debug: false, - tools, - verbose, - mainLoopModel: initialMainLoopModel, - thinkingConfig: initialThinkingConfig, - mcpClients, - mcpResources: {}, - ideInstallationStatus: null, - isNonInteractiveSession: true, - customSystemPrompt, - appendSystemPrompt, - agentDefinitions: { activeAgents: agents2, allAgents: [] }, - theme: resolveThemeSetting(getGlobalConfig().theme), - maxBudgetUsd - }, - getAppState, - setAppState, - abortController: this.abortController, - readFileState: this.readFileState, - nestedMemoryAttachmentTriggers: new Set, - loadedNestedMemoryPaths: this.loadedNestedMemoryPaths, - dynamicSkillDirTriggers: new Set, - discoveredSkillNames: this.discoveredSkillNames, - setInProgressToolUseIDs: () => {}, - setResponseLength: () => {}, - updateFileHistoryState: (updater) => { - setAppState((prev) => { - const updated = updater(prev.fileHistory); - if (updated === prev.fileHistory) - return prev; - return { ...prev, fileHistory: updated }; - }); - }, - updateAttributionState: (updater) => { - setAppState((prev) => { - const updated = updater(prev.attribution); - if (updated === prev.attribution) - return prev; - return { ...prev, attribution: updated }; - }); - }, - setSDKStatus - }; - if (orphanedPermission && !this.hasHandledOrphanedPermission) { - this.hasHandledOrphanedPermission = true; - for await (const message of handleOrphanedPermission(orphanedPermission, tools, this.mutableMessages, processUserInputContext)) { - yield message; - } - } - const { - messages: messagesFromUserInput, - shouldQuery, - allowedTools, - model: modelFromUserInput, - resultText - } = await processUserInput({ - input: prompt, - mode: "prompt", - setToolJSX: () => {}, - context: { - ...processUserInputContext, - messages: this.mutableMessages - }, - messages: this.mutableMessages, - uuid: options2?.uuid, - isMeta: options2?.isMeta, - querySource: "sdk" - }); - this.mutableMessages.push(...messagesFromUserInput); - const messages = [...this.mutableMessages]; - if (persistSession && messagesFromUserInput.length > 0) { - const transcriptPromise = recordTranscript(messages); - if (isBareMode()) {} else { - await transcriptPromise; - if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) { - await flushSessionStorage(); - } - } - } - const replayableMessages = messagesFromUserInput.filter((msg) => msg.type === "user" && !msg.isMeta && !msg.toolUseResult && messageSelector().selectableUserMessagesFilter(msg) || msg.type === "system" && msg.subtype === "compact_boundary"); - const messagesToAck = replayUserMessages ? replayableMessages : []; - setAppState((prev) => ({ - ...prev, - toolPermissionContext: { - ...prev.toolPermissionContext, - alwaysAllowRules: { - ...prev.toolPermissionContext.alwaysAllowRules, - command: allowedTools - } - } - })); - const mainLoopModel = modelFromUserInput ?? initialMainLoopModel; - processUserInputContext = { - messages, - setMessages: () => {}, - onChangeAPIKey: () => {}, - handleElicitation: this.config.handleElicitation, - options: { - commands: commands7, - debug: false, - tools, - verbose, - mainLoopModel, - thinkingConfig: initialThinkingConfig, - mcpClients, - mcpResources: {}, - ideInstallationStatus: null, - isNonInteractiveSession: true, - customSystemPrompt, - appendSystemPrompt, - theme: resolveThemeSetting(getGlobalConfig().theme), - agentDefinitions: { activeAgents: agents2, allAgents: [] }, - maxBudgetUsd - }, - getAppState, - setAppState, - abortController: this.abortController, - readFileState: this.readFileState, - nestedMemoryAttachmentTriggers: new Set, - loadedNestedMemoryPaths: this.loadedNestedMemoryPaths, - dynamicSkillDirTriggers: new Set, - discoveredSkillNames: this.discoveredSkillNames, - setInProgressToolUseIDs: () => {}, - setResponseLength: () => {}, - updateFileHistoryState: processUserInputContext.updateFileHistoryState, - updateAttributionState: processUserInputContext.updateAttributionState, - setSDKStatus - }; - headlessProfilerCheckpoint("before_skills_plugins"); - const [skills2, { enabled: enabledPlugins }] = await Promise.all([ - getSlashCommandToolSkills(getCwd()), - loadAllPluginsCacheOnly() - ]); - headlessProfilerCheckpoint("after_skills_plugins"); - yield buildSystemInitMessage({ - tools, - mcpClients, - model: mainLoopModel, - permissionMode: initialAppState.toolPermissionContext.mode, - commands: commands7, - agents: agents2, - skills: skills2, - plugins: enabledPlugins, - fastMode: initialAppState.fastMode - }); - headlessProfilerCheckpoint("system_message_yielded"); - if (!shouldQuery) { - for (const msg of messagesFromUserInput) { - if (msg.type === "user" && typeof msg.message.content === "string" && (msg.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) || msg.message.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`) || msg.isCompactSummary)) { - yield { - type: "user", - message: { - ...msg.message, - content: stripAnsi(msg.message.content) - }, - session_id: getSessionId(), - parent_tool_use_id: null, - uuid: msg.uuid, - timestamp: msg.timestamp, - isReplay: !msg.isCompactSummary, - isSynthetic: msg.isMeta || msg.isVisibleInTranscriptOnly - }; - } - if (msg.type === "system" && msg.subtype === "local_command" && typeof msg.content === "string" && (msg.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) || msg.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`))) { - yield localCommandOutputToSDKAssistantMessage(msg.content, msg.uuid); - } - if (msg.type === "system" && msg.subtype === "compact_boundary") { - yield { - type: "system", - subtype: "compact_boundary", - session_id: getSessionId(), - uuid: msg.uuid, - compact_metadata: toSDKCompactMetadata(msg.compactMetadata) - }; - } - } - if (persistSession) { - await recordTranscript(messages); - if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) { - await flushSessionStorage(); - } - } - yield { - type: "result", - subtype: "success", - is_error: false, - duration_ms: Date.now() - startTime, - duration_api_ms: getTotalAPIDuration(), - num_turns: messages.length - 1, - result: resultText ?? "", - stop_reason: null, - session_id: getSessionId(), - total_cost_usd: getTotalCostUSD(), - usage: this.totalUsage, - modelUsage: getModelUsage(), - permission_denials: this.permissionDenials, - fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode), - uuid: randomUUID51() - }; - return; - } - if (fileHistoryEnabled() && persistSession) { - messagesFromUserInput.filter(messageSelector().selectableUserMessagesFilter).forEach((message) => { - fileHistoryMakeSnapshot((updater) => { - setAppState((prev) => ({ - ...prev, - fileHistory: updater(prev.fileHistory) - })); - }, message.uuid); - }); - } - let currentMessageUsage = EMPTY_USAGE; - let turnCount = 1; - let hasAcknowledgedInitialMessages = false; - let structuredOutputFromTool; - let lastStopReason = null; - const errorLogWatermark = getInMemoryErrors().at(-1); - const initialStructuredOutputCalls = jsonSchema ? countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME) : 0; - for await (const message of query({ - messages, - systemPrompt, - userContext, - systemContext, - canUseTool: wrappedCanUseTool, - toolUseContext: processUserInputContext, - fallbackModel, - querySource: "sdk", - maxTurns, - taskBudget - })) { - if (message.type === "assistant" || message.type === "user" || message.type === "system" && message.subtype === "compact_boundary") { - if (persistSession && message.type === "system" && message.subtype === "compact_boundary") { - const tailUuid = message.compactMetadata?.preservedSegment?.tailUuid; - if (tailUuid) { - const tailIdx = this.mutableMessages.findLastIndex((m4) => m4.uuid === tailUuid); - if (tailIdx !== -1) { - await recordTranscript(this.mutableMessages.slice(0, tailIdx + 1)); - } - } - } - messages.push(message); - if (persistSession) { - if (message.type === "assistant") { - recordTranscript(messages); - } else { - await recordTranscript(messages); - } - } - if (!hasAcknowledgedInitialMessages && messagesToAck.length > 0) { - hasAcknowledgedInitialMessages = true; - for (const msgToAck of messagesToAck) { - if (msgToAck.type === "user") { - yield { - type: "user", - message: msgToAck.message, - session_id: getSessionId(), - parent_tool_use_id: null, - uuid: msgToAck.uuid, - timestamp: msgToAck.timestamp, - isReplay: true - }; - } - } - } - } - if (message.type === "user") { - turnCount++; - } - switch (message.type) { - case "tombstone": - break; - case "assistant": - if (message.message.stop_reason != null) { - lastStopReason = message.message.stop_reason; - } - this.mutableMessages.push(message); - yield* normalizeMessage(message); - break; - case "progress": - this.mutableMessages.push(message); - if (persistSession) { - messages.push(message); - recordTranscript(messages); - } - yield* normalizeMessage(message); - break; - case "user": - this.mutableMessages.push(message); - yield* normalizeMessage(message); - break; - case "stream_event": - if (message.event.type === "message_start") { - currentMessageUsage = EMPTY_USAGE; - currentMessageUsage = updateUsage(currentMessageUsage, message.event.message.usage); - } - if (message.event.type === "message_delta") { - currentMessageUsage = updateUsage(currentMessageUsage, message.event.usage); - if (message.event.delta.stop_reason != null) { - lastStopReason = message.event.delta.stop_reason; - } - } - if (message.event.type === "message_stop") { - this.totalUsage = accumulateUsage(this.totalUsage, currentMessageUsage); - } - if (includePartialMessages) { - yield { - type: "stream_event", - event: message.event, - session_id: getSessionId(), - parent_tool_use_id: null, - uuid: randomUUID51() - }; - } - break; - case "attachment": - this.mutableMessages.push(message); - if (persistSession) { - messages.push(message); - recordTranscript(messages); - } - if (message.attachment.type === "structured_output") { - structuredOutputFromTool = message.attachment.data; - } else if (message.attachment.type === "max_turns_reached") { - if (persistSession) { - if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) { - await flushSessionStorage(); - } - } - yield { - type: "result", - subtype: "error_max_turns", - duration_ms: Date.now() - startTime, - duration_api_ms: getTotalAPIDuration(), - is_error: true, - num_turns: message.attachment.turnCount, - stop_reason: lastStopReason, - session_id: getSessionId(), - total_cost_usd: getTotalCostUSD(), - usage: this.totalUsage, - modelUsage: getModelUsage(), - permission_denials: this.permissionDenials, - fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode), - uuid: randomUUID51(), - errors: [ - `Reached maximum number of turns (${message.attachment.maxTurns})` - ] - }; - return; - } else if (replayUserMessages && message.attachment.type === "queued_command") { - yield { - type: "user", - message: { - role: "user", - content: message.attachment.prompt - }, - session_id: getSessionId(), - parent_tool_use_id: null, - uuid: message.attachment.source_uuid || message.uuid, - timestamp: message.timestamp, - isReplay: true - }; - } - break; - case "stream_request_start": - break; - case "system": { - const snipResult = this.config.snipReplay?.(message, this.mutableMessages); - if (snipResult !== undefined) { - if (snipResult.executed) { - this.mutableMessages.length = 0; - this.mutableMessages.push(...snipResult.messages); - } - break; - } - this.mutableMessages.push(message); - if (message.subtype === "compact_boundary" && message.compactMetadata) { - const mutableBoundaryIdx = this.mutableMessages.length - 1; - if (mutableBoundaryIdx > 0) { - this.mutableMessages.splice(0, mutableBoundaryIdx); - } - const localBoundaryIdx = messages.length - 1; - if (localBoundaryIdx > 0) { - messages.splice(0, localBoundaryIdx); - } - yield { - type: "system", - subtype: "compact_boundary", - session_id: getSessionId(), - uuid: message.uuid, - compact_metadata: toSDKCompactMetadata(message.compactMetadata) - }; - } - if (message.subtype === "api_error") { - yield { - type: "system", - subtype: "api_retry", - attempt: message.retryAttempt, - max_retries: message.maxRetries, - retry_delay_ms: message.retryInMs, - error_status: message.error.status ?? null, - error: categorizeRetryableAPIError(message.error), - session_id: getSessionId(), - uuid: message.uuid - }; - } - break; - } - case "tool_use_summary": - yield { - type: "tool_use_summary", - summary: message.summary, - preceding_tool_use_ids: message.precedingToolUseIds, - session_id: getSessionId(), - uuid: message.uuid - }; - break; - } - if (maxBudgetUsd !== undefined && getTotalCostUSD() >= maxBudgetUsd) { - if (persistSession) { - if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) { - await flushSessionStorage(); - } - } - yield { - type: "result", - subtype: "error_max_budget_usd", - duration_ms: Date.now() - startTime, - duration_api_ms: getTotalAPIDuration(), - is_error: true, - num_turns: turnCount, - stop_reason: lastStopReason, - session_id: getSessionId(), - total_cost_usd: getTotalCostUSD(), - usage: this.totalUsage, - modelUsage: getModelUsage(), - permission_denials: this.permissionDenials, - fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode), - uuid: randomUUID51(), - errors: [`Reached maximum budget ($${maxBudgetUsd})`] - }; - return; - } - if (message.type === "user" && jsonSchema) { - const currentCalls = countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME); - const callsThisQuery = currentCalls - initialStructuredOutputCalls; - const maxRetries = parseInt(process.env.MAX_STRUCTURED_OUTPUT_RETRIES || "5", 10); - if (callsThisQuery >= maxRetries) { - if (persistSession) { - if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) { - await flushSessionStorage(); - } - } - yield { - type: "result", - subtype: "error_max_structured_output_retries", - duration_ms: Date.now() - startTime, - duration_api_ms: getTotalAPIDuration(), - is_error: true, - num_turns: turnCount, - stop_reason: lastStopReason, - session_id: getSessionId(), - total_cost_usd: getTotalCostUSD(), - usage: this.totalUsage, - modelUsage: getModelUsage(), - permission_denials: this.permissionDenials, - fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode), - uuid: randomUUID51(), - errors: [ - `Failed to provide valid structured output after ${maxRetries} attempts` - ] - }; - return; - } - } - } - const result = messages.findLast((m4) => m4.type === "assistant" || m4.type === "user"); - const edeResultType = result?.type ?? "undefined"; - const edeLastContentType = result?.type === "assistant" ? last_default(result.message.content)?.type ?? "none" : "n/a"; - if (persistSession) { - if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) { - await flushSessionStorage(); - } - } - if (!isResultSuccessful(result, lastStopReason)) { - yield { - type: "result", - subtype: "error_during_execution", - duration_ms: Date.now() - startTime, - duration_api_ms: getTotalAPIDuration(), - is_error: true, - num_turns: turnCount, - stop_reason: lastStopReason, - session_id: getSessionId(), - total_cost_usd: getTotalCostUSD(), - usage: this.totalUsage, - modelUsage: getModelUsage(), - permission_denials: this.permissionDenials, - fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode), - uuid: randomUUID51(), - errors: (() => { - const all4 = getInMemoryErrors(); - const start = errorLogWatermark ? all4.lastIndexOf(errorLogWatermark) + 1 : 0; - return [ - `[ede_diagnostic] result_type=${edeResultType} last_content_type=${edeLastContentType} stop_reason=${lastStopReason}`, - ...all4.slice(start).map((_) => _.error) - ]; - })() - }; - return; - } - let textResult = ""; - let isApiError = false; - if (result.type === "assistant") { - const lastContent = last_default(result.message.content); - if (lastContent?.type === "text" && !SYNTHETIC_MESSAGES.has(lastContent.text)) { - textResult = lastContent.text; - } - isApiError = Boolean(result.isApiErrorMessage); - } - yield { - type: "result", - subtype: "success", - is_error: isApiError, - duration_ms: Date.now() - startTime, - duration_api_ms: getTotalAPIDuration(), - num_turns: turnCount, - result: textResult, - stop_reason: lastStopReason, - session_id: getSessionId(), - total_cost_usd: getTotalCostUSD(), - usage: this.totalUsage, - modelUsage: getModelUsage(), - permission_denials: this.permissionDenials, - structured_output: structuredOutputFromTool, - fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode), - uuid: randomUUID51() - }; - } - interrupt() { - this.abortController.abort(); - } - getMessages() { - return this.mutableMessages; - } - getReadFileState() { - return this.readFileState; - } - getSessionId() { - return getSessionId(); - } - setModel(model) { - this.config.userSpecifiedModel = model; - } -} -async function* ask({ - commands: commands7, - prompt, - promptUuid, - isMeta, - cwd: cwd2, - tools, - mcpClients, - verbose = false, - thinkingConfig, - maxTurns, - maxBudgetUsd, - taskBudget, - canUseTool, - mutableMessages = [], - getReadFileCache, - setReadFileCache, - customSystemPrompt, - appendSystemPrompt, - userSpecifiedModel, - fallbackModel, - jsonSchema, - getAppState, - setAppState, - abortController, - replayUserMessages = false, - includePartialMessages = false, - handleElicitation, - agents: agents2 = [], - setSDKStatus, - orphanedPermission -}) { - const engine = new QueryEngine({ - cwd: cwd2, - tools, - commands: commands7, - mcpClients, - agents: agents2, - canUseTool, - getAppState, - setAppState, - initialMessages: mutableMessages, - readFileCache: cloneFileStateCache(getReadFileCache()), - customSystemPrompt, - appendSystemPrompt, - userSpecifiedModel, - fallbackModel, - thinkingConfig, - maxTurns, - maxBudgetUsd, - taskBudget, - jsonSchema, - verbose, - handleElicitation, - replayUserMessages, - includePartialMessages, - setSDKStatus, - abortController, - orphanedPermission, - ...{} - }); - try { - yield* engine.submitMessage(prompt, { - uuid: promptUuid, - isMeta - }); - } finally { - setReadFileCache(engine.getReadFileState()); - } -} -var messageSelector = () => (init_MessageSelector(), __toCommonJS(exports_MessageSelector)), getCoordinatorUserContext2 = () => ({}); -var init_QueryEngine = __esm(() => { - init_last(); - init_state(); - init_claude(); - init_logging2(); - init_strip_ansi(); - init_commands5(); - init_xml(); - init_cost_tracker(); - init_memdir(); - init_paths(); - init_query4(); - init_errors10(); - init_Tool(); - init_SyntheticOutputTool(); - init_abortController(); - init_config(); - init_cwd(); - init_envUtils(); - init_fastMode(); - init_fileHistory(); - init_fileStateCache(); - init_headlessProfiler(); - init_hookHelpers(); - init_log2(); - init_messages9(); - init_model(); - init_pluginLoader(); - init_processUserInput(); - init_queryContext(); - init_Shell(); - init_sessionStorage(); - init_thinking(); - init_mappers(); - init_systemInit(); - init_filesystem(); - init_queryHelpers(); -}); -// src/utils/filePersistence/filePersistence.ts -var init_filePersistence = __esm(() => { - init_analytics(); - init_filesApi(); - init_cwd(); - init_errors(); - init_log2(); - init_sessionIngressAuth(); - init_outputsScanner(); -}); - -// src/utils/idleTimeout.ts -function createIdleTimeoutManager(isIdle) { - const exitAfterStopDelay = process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY; - const delayMs = exitAfterStopDelay ? parseInt(exitAfterStopDelay, 10) : null; - const isValidDelay = delayMs && !isNaN(delayMs) && delayMs > 0; - let timer = null; - let lastIdleTime = 0; - return { - start() { - if (timer) { - clearTimeout(timer); - timer = null; - } - if (isValidDelay) { - lastIdleTime = Date.now(); - timer = setTimeout(() => { - const idleDuration = Date.now() - lastIdleTime; - if (isIdle() && idleDuration >= delayMs) { - logForDebugging(`Exiting after ${delayMs}ms of idle time`); - gracefulShutdownSync(); - } - }, delayMs); - } - }, - stop() { - if (timer) { - clearTimeout(timer); - timer = null; - } - } - }; -} -var init_idleTimeout = __esm(() => { - init_debug(); - init_gracefulShutdown(); -}); - -// src/bridge/inboundAttachments.ts -import { randomUUID as randomUUID52 } from "crypto"; -import { mkdir as mkdir42, writeFile as writeFile49 } from "fs/promises"; -import { basename as basename57, join as join152 } from "path"; -function debug2(msg) { - logForDebugging(`[bridge:inbound-attach] ${msg}`); -} -function extractInboundAttachments(msg) { - if (typeof msg !== "object" || msg === null || !("file_attachments" in msg)) { - return []; - } - const parsed = attachmentsArraySchema().safeParse(msg.file_attachments); - return parsed.success ? parsed.data : []; -} -function sanitizeFileName(name3) { - const base2 = basename57(name3).replace(/[^a-zA-Z0-9._-]/g, "_"); - return base2 || "attachment"; -} -function uploadsDir() { - return join152(getClaudeConfigHomeDir(), "uploads", getSessionId()); -} -async function resolveOne(att) { - const token = getBridgeAccessToken(); - if (!token) { - debug2("skip: no oauth token"); - return; - } - let data; - try { - const url3 = `${getBridgeBaseUrl()}/api/oauth/files/${encodeURIComponent(att.file_uuid)}/content`; - const response7 = await axios_default.get(url3, { - headers: { Authorization: `Bearer ${token}` }, - responseType: "arraybuffer", - timeout: DOWNLOAD_TIMEOUT_MS, - validateStatus: () => true - }); - if (response7.status !== 200) { - debug2(`fetch ${att.file_uuid} failed: status=${response7.status}`); - return; - } - data = Buffer.from(response7.data); - } catch (e4) { - debug2(`fetch ${att.file_uuid} threw: ${e4}`); - return; - } - const safeName = sanitizeFileName(att.file_name); - const prefix = (att.file_uuid.slice(0, 8) || randomUUID52().slice(0, 8)).replace(/[^a-zA-Z0-9_-]/g, "_"); - const dir = uploadsDir(); - const outPath = join152(dir, `${prefix}-${safeName}`); - try { - await mkdir42(dir, { recursive: true }); - await writeFile49(outPath, data); - } catch (e4) { - debug2(`write ${outPath} failed: ${e4}`); - return; - } - debug2(`resolved ${att.file_uuid} \u2192 ${outPath} (${data.length} bytes)`); - return outPath; -} -async function resolveInboundAttachments(attachments) { - if (attachments.length === 0) - return ""; - debug2(`resolving ${attachments.length} attachment(s)`); - const paths2 = await Promise.all(attachments.map(resolveOne)); - const ok = paths2.filter((p4) => p4 !== undefined); - if (ok.length === 0) - return ""; - return ok.map((p4) => `@"${p4}"`).join(" ") + " "; -} -function prependPathRefs(content, prefix) { - if (!prefix) - return content; - if (typeof content === "string") - return prefix + content; - const i6 = content.findLastIndex((b5) => b5.type === "text"); - if (i6 !== -1) { - const b5 = content[i6]; - if (b5.type === "text") { - return [ - ...content.slice(0, i6), - { ...b5, text: prefix + b5.text }, - ...content.slice(i6 + 1) - ]; - } - } - return [...content, { type: "text", text: prefix.trimEnd() }]; -} -async function resolveAndPrepend(msg, content) { - const attachments = extractInboundAttachments(msg); - if (attachments.length === 0) - return content; - const prefix = await resolveInboundAttachments(attachments); - return prependPathRefs(content, prefix); -} -var DOWNLOAD_TIMEOUT_MS = 30000, attachmentSchema, attachmentsArraySchema; -var init_inboundAttachments = __esm(() => { - init_axios2(); - init_v4(); - init_state(); - init_debug(); - init_envUtils(); - init_bridgeConfig(); - attachmentSchema = lazySchema(() => exports_external.object({ - file_uuid: exports_external.string(), - file_name: exports_external.string() - })); - attachmentsArraySchema = lazySchema(() => exports_external.array(attachmentSchema())); -}); - -// src/utils/sessionUrl.ts -import { randomUUID as randomUUID53 } from "crypto"; -function parseSessionIdentifier(resumeIdentifier) { - if (resumeIdentifier.toLowerCase().endsWith(".jsonl")) { - return { - sessionId: randomUUID53(), - ingressUrl: null, - isUrl: false, - jsonlFile: resumeIdentifier, - isJsonlFile: true - }; - } - if (validateUuid2(resumeIdentifier)) { - return { - sessionId: resumeIdentifier, - ingressUrl: null, - isUrl: false, - jsonlFile: null, - isJsonlFile: false - }; - } - try { - const url3 = new URL(resumeIdentifier); - return { - sessionId: randomUUID53(), - ingressUrl: url3.href, - isUrl: true, - jsonlFile: null, - isJsonlFile: false - }; - } catch {} - return null; -} -var init_sessionUrl = __esm(() => { - init_uuid(); -}); - -// src/utils/plugins/zipCacheAdapters.ts -import { readFile as readFile56 } from "fs/promises"; -import { join as join153 } from "path"; -async function readZipCacheKnownMarketplaces() { - try { - const content = await readFile56(getZipCacheKnownMarketplacesPath(), "utf-8"); - const parsed = KnownMarketplacesFileSchema().safeParse(jsonParse(content)); - if (!parsed.success) { - logForDebugging(`Invalid known_marketplaces.json in zip cache: ${parsed.error.message}`, { level: "error" }); - return {}; - } - return parsed.data; - } catch { - return {}; - } -} -async function writeZipCacheKnownMarketplaces(data) { - await atomicWriteToZipCache(getZipCacheKnownMarketplacesPath(), jsonStringify(data, null, 2)); -} -async function saveMarketplaceJsonToZipCache(marketplaceName, installLocation) { - const zipCachePath = getPluginZipCachePath(); - if (!zipCachePath) { - return; - } - const content = await readMarketplaceJsonContent(installLocation); - if (content !== null) { - const relPath = getMarketplaceJsonRelativePath(marketplaceName); - await atomicWriteToZipCache(join153(zipCachePath, relPath), content); - } -} -async function readMarketplaceJsonContent(dir) { - const candidates = [ - join153(dir, ".claude-plugin", "marketplace.json"), - join153(dir, "marketplace.json"), - dir - ]; - for (const candidate of candidates) { - try { - return await readFile56(candidate, "utf-8"); - } catch {} - } - return null; -} -async function syncMarketplacesToZipCache() { - const knownMarketplaces = await loadKnownMarketplacesConfigSafe(); - for (const [name3, entry] of Object.entries(knownMarketplaces)) { - if (!entry.installLocation) - continue; - try { - await saveMarketplaceJsonToZipCache(name3, entry.installLocation); - } catch (error46) { - logForDebugging(`Failed to save marketplace JSON for ${name3}: ${error46}`); - } - } - const zipCacheKnownMarketplaces = await readZipCacheKnownMarketplaces(); - const mergedKnownMarketplaces = { - ...zipCacheKnownMarketplaces, - ...knownMarketplaces - }; - await writeZipCacheKnownMarketplaces(mergedKnownMarketplaces); -} -var init_zipCacheAdapters = __esm(() => { - init_debug(); - init_slowOperations(); - init_marketplaceManager(); - init_schemas3(); - init_zipCache(); -}); - -// src/utils/plugins/headlessPluginInstall.ts -async function installPluginsForHeadless() { - const zipCacheMode = isPluginZipCacheEnabled(); - logForDebugging(`installPluginsForHeadless: starting${zipCacheMode ? " (zip cache mode)" : ""}`); - const seedChanged = await registerSeedMarketplaces(); - if (seedChanged) { - clearMarketplacesCache(); - clearPluginCache("headlessPluginInstall: seed marketplaces registered"); - } - if (zipCacheMode) { - await getFsImplementation().mkdir(getZipCacheMarketplacesDir()); - await getFsImplementation().mkdir(getZipCachePluginsDir()); - } - const declaredCount = Object.keys(getDeclaredMarketplaces()).length; - const metrics = { - marketplaces_installed: 0, - delisted_count: 0 - }; - let pluginsChanged = seedChanged; - try { - if (declaredCount === 0) { - logForDebugging("installPluginsForHeadless: no marketplaces declared"); - } else { - const reconcileResult = await withDiagnosticsTiming("headless_marketplace_reconcile", () => reconcileMarketplaces({ - skip: zipCacheMode ? (_name, source) => !isMarketplaceSourceSupportedByZipCache(source) : undefined, - onProgress: (event) => { - if (event.type === "installed") { - logForDebugging(`installPluginsForHeadless: installed marketplace ${event.name}`); - } else if (event.type === "failed") { - logForDebugging(`installPluginsForHeadless: failed to install marketplace ${event.name}: ${event.error}`); - } - } - }), (r4) => ({ - installed_count: r4.installed.length, - updated_count: r4.updated.length, - failed_count: r4.failed.length, - skipped_count: r4.skipped.length - })); - if (reconcileResult.skipped.length > 0) { - logForDebugging(`installPluginsForHeadless: skipped ${reconcileResult.skipped.length} marketplace(s) unsupported by zip cache: ${reconcileResult.skipped.join(", ")}`); - } - const marketplacesChanged = reconcileResult.installed.length + reconcileResult.updated.length; - if (marketplacesChanged > 0) { - clearMarketplacesCache(); - clearPluginCache("headlessPluginInstall: marketplaces reconciled"); - pluginsChanged = true; - } - metrics.marketplaces_installed = marketplacesChanged; - } - if (zipCacheMode) { - await syncMarketplacesToZipCache(); - } - const newlyDelisted = await detectAndUninstallDelistedPlugins(); - metrics.delisted_count = newlyDelisted.length; - if (newlyDelisted.length > 0) { - pluginsChanged = true; - } - if (pluginsChanged) { - clearPluginCache("headlessPluginInstall: plugins changed"); - } - if (zipCacheMode) { - registerCleanup(cleanupSessionPluginCache); - } - return pluginsChanged; - } catch (error46) { - logError2(error46); - return false; - } finally { - logEvent("tengu_headless_plugin_install", metrics); - } -} -var init_headlessPluginInstall = __esm(() => { - init_analytics(); - init_cleanupRegistry(); - init_debug(); - init_diagLogs(); - init_fsOperations(); - init_log2(); - init_marketplaceManager(); - init_pluginBlocklist(); - init_pluginLoader(); - init_reconciler2(); - init_zipCache(); - init_zipCacheAdapters(); -}); - -// src/bridge/envLessBridgeConfig.ts -async function getEnvLessBridgeConfig() { - const raw = await getFeatureValue_DEPRECATED("tengu_bridge_repl_v2_config", DEFAULT_ENV_LESS_BRIDGE_CONFIG); - const parsed = envLessBridgeConfigSchema().safeParse(raw); - return parsed.success ? parsed.data : DEFAULT_ENV_LESS_BRIDGE_CONFIG; -} -async function checkEnvLessBridgeMinVersion() { - const cfg = await getEnvLessBridgeConfig(); - if (cfg.min_version && lt(MACRO.VERSION, cfg.min_version)) { - return `Your version of Claude Code (${MACRO.VERSION}) is too old for Remote Control. -Version ${cfg.min_version} or higher is required. Run \`claude update\` to update.`; - } - return null; -} -var DEFAULT_ENV_LESS_BRIDGE_CONFIG, envLessBridgeConfigSchema; -var init_envLessBridgeConfig = __esm(() => { - init_v4(); - init_growthbook(); - init_bridgeEnabled(); - DEFAULT_ENV_LESS_BRIDGE_CONFIG = { - init_retry_max_attempts: 3, - init_retry_base_delay_ms: 500, - init_retry_jitter_fraction: 0.25, - init_retry_max_delay_ms: 4000, - http_timeout_ms: 1e4, - uuid_dedup_buffer_size: 2000, - heartbeat_interval_ms: 20000, - heartbeat_jitter_fraction: 0.1, - token_refresh_buffer_ms: 300000, - teardown_archive_timeout_ms: 1500, - connect_timeout_ms: 15000, - min_version: "0.0.0", - should_show_app_upgrade_message: false - }; - envLessBridgeConfigSchema = lazySchema(() => exports_external.object({ - init_retry_max_attempts: exports_external.number().int().min(1).max(10).default(3), - init_retry_base_delay_ms: exports_external.number().int().min(100).default(500), - init_retry_jitter_fraction: exports_external.number().min(0).max(1).default(0.25), - init_retry_max_delay_ms: exports_external.number().int().min(500).default(4000), - http_timeout_ms: exports_external.number().int().min(2000).default(1e4), - uuid_dedup_buffer_size: exports_external.number().int().min(100).max(50000).default(2000), - heartbeat_interval_ms: exports_external.number().int().min(5000).max(30000).default(20000), - heartbeat_jitter_fraction: exports_external.number().min(0).max(0.5).default(0.1), - token_refresh_buffer_ms: exports_external.number().int().min(30000).max(1800000).default(300000), - teardown_archive_timeout_ms: exports_external.number().int().min(500).max(2000).default(1500), - connect_timeout_ms: exports_external.number().int().min(5000).max(60000).default(15000), - min_version: exports_external.string().refine((v6) => { - try { - lt(v6, "0.0.0"); - return true; - } catch { - return false; - } - }).default("0.0.0"), - should_show_app_upgrade_message: exports_external.boolean().default(false) - })); -}); - -// src/bridge/workSecret.ts -function decodeWorkSecret(secret) { - const json2 = Buffer.from(secret, "base64url").toString("utf-8"); - const parsed = jsonParse(json2); - if (!parsed || typeof parsed !== "object" || !("version" in parsed) || parsed.version !== 1) { - throw new Error(`Unsupported work secret version: ${parsed && typeof parsed === "object" && "version" in parsed ? parsed.version : "unknown"}`); - } - const obj = parsed; - if (typeof obj.session_ingress_token !== "string" || obj.session_ingress_token.length === 0) { - throw new Error("Invalid work secret: missing or empty session_ingress_token"); - } - if (typeof obj.api_base_url !== "string") { - throw new Error("Invalid work secret: missing api_base_url"); - } - return parsed; -} -function buildSdkUrl(apiBaseUrl, sessionId) { - const isLocalhost = apiBaseUrl.includes("localhost") || apiBaseUrl.includes("127.0.0.1"); - const protocol = isLocalhost ? "ws" : "wss"; - const version7 = isLocalhost ? "v2" : "v1"; - const host = apiBaseUrl.replace(/^https?:\/\//, "").replace(/\/+$/, ""); - return `${protocol}://${host}/${version7}/session_ingress/ws/${sessionId}`; -} -function sameSessionId(a5, b5) { - if (a5 === b5) - return true; - const aBody = a5.slice(a5.lastIndexOf("_") + 1); - const bBody = b5.slice(b5.lastIndexOf("_") + 1); - return aBody.length >= 4 && aBody === bBody; -} -function buildCCRv2SdkUrl(apiBaseUrl, sessionId) { - const base2 = apiBaseUrl.replace(/\/+$/, ""); - return `${base2}/v1/code/sessions/${sessionId}`; -} -async function registerWorker(sessionUrl, accessToken) { - const response7 = await axios_default.post(`${sessionUrl}/worker/register`, {}, { - headers: { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "anthropic-version": "2023-06-01" - }, - timeout: 1e4 - }); - const raw = response7.data?.worker_epoch; - const epoch = typeof raw === "string" ? Number(raw) : raw; - if (typeof epoch !== "number" || !Number.isFinite(epoch) || !Number.isSafeInteger(epoch)) { - throw new Error(`registerWorker: invalid worker_epoch in response: ${jsonStringify(response7.data)}`); - } - return epoch; -} -var init_workSecret = __esm(() => { - init_axios2(); - init_slowOperations(); -}); - -// src/bridge/replBridgeTransport.ts -function createV1ReplTransport(hybrid) { - return { - write: (msg) => hybrid.write(msg), - writeBatch: (msgs) => hybrid.writeBatch(msgs), - close: () => hybrid.close(), - isConnectedStatus: () => hybrid.isConnectedStatus(), - getStateLabel: () => hybrid.getStateLabel(), - setOnData: (cb) => hybrid.setOnData(cb), - setOnClose: (cb) => hybrid.setOnClose(cb), - setOnConnect: (cb) => hybrid.setOnConnect(cb), - connect: () => void hybrid.connect(), - getLastSequenceNum: () => 0, - get droppedBatchCount() { - return hybrid.droppedBatchCount; - }, - reportState: () => {}, - reportMetadata: () => {}, - reportDelivery: () => {}, - flush: () => Promise.resolve() - }; -} -async function createV2ReplTransport(opts) { - const { - sessionUrl, - ingressToken, - sessionId, - initialSequenceNum, - getAuthToken - } = opts; - let getAuthHeaders4; - if (getAuthToken) { - getAuthHeaders4 = () => { - const token = getAuthToken(); - if (!token) - return {}; - return { Authorization: `Bearer ${token}` }; - }; - } else { - updateSessionIngressAuthToken(ingressToken); - } - const epoch = opts.epoch ?? await registerWorker(sessionUrl, ingressToken); - logForDebugging(`[bridge:repl] CCR v2: worker sessionId=${sessionId} epoch=${epoch}${opts.epoch !== undefined ? " (from /bridge)" : " (via registerWorker)"}`); - const sseUrl = new URL(sessionUrl); - sseUrl.pathname = sseUrl.pathname.replace(/\/$/, "") + "/worker/events/stream"; - const sse = new SSETransport(sseUrl, {}, sessionId, undefined, initialSequenceNum, getAuthHeaders4); - let onCloseCb; - const ccr = new CCRClient(sse, new URL(sessionUrl), { - getAuthHeaders: getAuthHeaders4, - heartbeatIntervalMs: opts.heartbeatIntervalMs, - heartbeatJitterFraction: opts.heartbeatJitterFraction, - onEpochMismatch: () => { - logForDebugging("[bridge:repl] CCR v2: epoch superseded (409) \u2014 closing for poll-loop recovery"); - try { - ccr.close(); - sse.close(); - onCloseCb?.(4090); - } catch (closeErr) { - logForDebugging(`[bridge:repl] CCR v2: error during epoch-mismatch cleanup: ${errorMessage(closeErr)}`, { level: "error" }); - } - throw new Error("epoch superseded"); - } - }); - sse.setOnEvent((event) => { - ccr.reportDelivery(event.event_id, "received"); - ccr.reportDelivery(event.event_id, "processed"); - }); - let onConnectCb; - let ccrInitialized = false; - let closed = false; - return { - write(msg) { - return ccr.writeEvent(msg); - }, - async writeBatch(msgs) { - for (const m4 of msgs) { - if (closed) - break; - await ccr.writeEvent(m4); - } - }, - close() { - closed = true; - ccr.close(); - sse.close(); - }, - isConnectedStatus() { - return ccrInitialized; - }, - getStateLabel() { - if (sse.isClosedStatus()) - return "closed"; - if (sse.isConnectedStatus()) - return ccrInitialized ? "connected" : "init"; - return "connecting"; - }, - setOnData(cb) { - sse.setOnData(cb); - }, - setOnClose(cb) { - onCloseCb = cb; - sse.setOnClose((code) => { - ccr.close(); - cb(code ?? 4092); - }); - }, - setOnConnect(cb) { - onConnectCb = cb; - }, - getLastSequenceNum() { - return sse.getLastSequenceNum(); - }, - droppedBatchCount: 0, - reportState(state4) { - ccr.reportState(state4); - }, - reportMetadata(metadata) { - ccr.reportMetadata(metadata); - }, - reportDelivery(eventId, status2) { - ccr.reportDelivery(eventId, status2); - }, - flush() { - return ccr.flush(); - }, - connect() { - if (!opts.outboundOnly) { - sse.connect(); - } - ccr.initialize(epoch).then(() => { - ccrInitialized = true; - logForDebugging(`[bridge:repl] v2 transport ready for writes (epoch=${epoch}, sse=${sse.isConnectedStatus() ? "open" : "opening"})`); - onConnectCb?.(); - }, (err2) => { - logForDebugging(`[bridge:repl] CCR v2 initialize failed: ${errorMessage(err2)}`, { level: "error" }); - ccr.close(); - sse.close(); - onCloseCb?.(4091); - }); - } - }; -} -var init_replBridgeTransport = __esm(() => { - init_ccrClient(); - init_SSETransport(); - init_debug(); - init_errors(); - init_sessionIngressAuth(); - init_workSecret(); -}); - -// src/bridge/capacityWake.ts -function createCapacityWake(outerSignal) { - let wakeController = new AbortController; - function wake() { - wakeController.abort(); - wakeController = new AbortController; - } - function signal() { - const merged = new AbortController; - const abort7 = () => merged.abort(); - if (outerSignal.aborted || wakeController.signal.aborted) { - merged.abort(); - return { signal: merged.signal, cleanup: () => {} }; - } - outerSignal.addEventListener("abort", abort7, { once: true }); - const capSig = wakeController.signal; - capSig.addEventListener("abort", abort7, { once: true }); - return { - signal: merged.signal, - cleanup: () => { - outerSignal.removeEventListener("abort", abort7); - capSig.removeEventListener("abort", abort7); - } - }; - } - return { signal, wake }; -} - -// src/bridge/flushGate.ts -class FlushGate { - _active = false; - _pending = []; - get active() { - return this._active; - } - get pendingCount() { - return this._pending.length; - } - start() { - this._active = true; - } - end() { - this._active = false; - return this._pending.splice(0); - } - enqueue(...items) { - if (!this._active) - return false; - this._pending.push(...items); - return true; - } - drop() { - this._active = false; - const count4 = this._pending.length; - this._pending.length = 0; - return count4; - } - deactivate() { - this._active = false; - } -} - -// src/bridge/bridgePointer.ts -var exports_bridgePointer = {}; -__export(exports_bridgePointer, { - writeBridgePointer: () => writeBridgePointer, - readBridgePointerAcrossWorktrees: () => readBridgePointerAcrossWorktrees, - readBridgePointer: () => readBridgePointer, - getBridgePointerPath: () => getBridgePointerPath, - clearBridgePointer: () => clearBridgePointer, - BRIDGE_POINTER_TTL_MS: () => BRIDGE_POINTER_TTL_MS -}); -import { mkdir as mkdir43, readFile as readFile57, stat as stat49, unlink as unlink24, writeFile as writeFile50 } from "fs/promises"; -import { dirname as dirname62, join as join154 } from "path"; -function getBridgePointerPath(dir) { - return join154(getProjectsDir(), sanitizePath2(dir), "bridge-pointer.json"); -} -async function writeBridgePointer(dir, pointer) { - const path27 = getBridgePointerPath(dir); - try { - await mkdir43(dirname62(path27), { recursive: true }); - await writeFile50(path27, jsonStringify(pointer), "utf8"); - logForDebugging(`[bridge:pointer] wrote ${path27}`); - } catch (err2) { - logForDebugging(`[bridge:pointer] write failed: ${err2}`, { level: "warn" }); - } -} -async function readBridgePointer(dir) { - const path27 = getBridgePointerPath(dir); - let raw; - let mtimeMs; - try { - mtimeMs = (await stat49(path27)).mtimeMs; - raw = await readFile57(path27, "utf8"); - } catch { - return null; - } - const parsed = BridgePointerSchema().safeParse(safeJsonParse(raw)); - if (!parsed.success) { - logForDebugging(`[bridge:pointer] invalid schema, clearing: ${path27}`); - await clearBridgePointer(dir); - return null; - } - const ageMs = Math.max(0, Date.now() - mtimeMs); - if (ageMs > BRIDGE_POINTER_TTL_MS) { - logForDebugging(`[bridge:pointer] stale (>4h mtime), clearing: ${path27}`); - await clearBridgePointer(dir); - return null; - } - return { ...parsed.data, ageMs }; -} -async function readBridgePointerAcrossWorktrees(dir) { - const here = await readBridgePointer(dir); - if (here) { - return { pointer: here, dir }; - } - const worktrees = await getWorktreePathsPortable(dir); - if (worktrees.length <= 1) - return null; - if (worktrees.length > MAX_WORKTREE_FANOUT) { - logForDebugging(`[bridge:pointer] ${worktrees.length} worktrees exceeds fanout cap ${MAX_WORKTREE_FANOUT}, skipping`); - return null; - } - const dirKey = sanitizePath2(dir); - const candidates = worktrees.filter((wt) => sanitizePath2(wt) !== dirKey); - const results = await Promise.all(candidates.map(async (wt) => { - const p4 = await readBridgePointer(wt); - return p4 ? { pointer: p4, dir: wt } : null; - })); - let freshest = null; - for (const r4 of results) { - if (r4 && (!freshest || r4.pointer.ageMs < freshest.pointer.ageMs)) { - freshest = r4; - } - } - if (freshest) { - logForDebugging(`[bridge:pointer] fanout found pointer in worktree ${freshest.dir} (ageMs=${freshest.pointer.ageMs})`); - } - return freshest; -} -async function clearBridgePointer(dir) { - const path27 = getBridgePointerPath(dir); - try { - await unlink24(path27); - logForDebugging(`[bridge:pointer] cleared ${path27}`); - } catch (err2) { - if (!isENOENT(err2)) { - logForDebugging(`[bridge:pointer] clear failed: ${err2}`, { - level: "warn" - }); - } - } -} -function safeJsonParse(raw) { - try { - return jsonParse(raw); - } catch { - return null; - } -} -var MAX_WORKTREE_FANOUT = 50, BRIDGE_POINTER_TTL_MS, BridgePointerSchema; -var init_bridgePointer = __esm(() => { - init_v4(); - init_debug(); - init_errors(); - init_getWorktreePathsPortable(); - init_sessionStoragePortable(); - init_slowOperations(); - BRIDGE_POINTER_TTL_MS = 4 * 60 * 60 * 1000; - BridgePointerSchema = lazySchema(() => exports_external.object({ - sessionId: exports_external.string(), - environmentId: exports_external.string(), - source: exports_external.enum(["standalone", "repl"]) - })); -}); - -// src/bridge/replBridge.ts -import { randomUUID as randomUUID54 } from "crypto"; -async function initBridgeCore(params) { - const { - dir, - machineName, - branch: branch2, - gitRepoUrl, - title, - baseUrl, - sessionIngressUrl, - workerType, - getAccessToken, - createSession, - archiveSession, - getCurrentTitle = () => title, - toSDKMessages: toSDKMessages2 = () => { - throw new Error("BridgeCoreParams.toSDKMessages not provided. Pass it if you use writeMessages() or initialMessages \u2014 daemon callers that only use writeSdkMessages() never hit this path."); - }, - onAuth401, - getPollIntervalConfig: getPollIntervalConfig2 = () => DEFAULT_POLL_CONFIG, - initialHistoryCap = 200, - initialMessages, - previouslyFlushedUUIDs, - onInboundMessage, - onPermissionResponse, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode, - onStateChange, - onUserMessage, - perpetual, - initialSSESequenceNum = 0 - } = params; - const seq = ++initSequence; - const { writeBridgePointer: writeBridgePointer2, clearBridgePointer: clearBridgePointer2, readBridgePointer: readBridgePointer2 } = await Promise.resolve().then(() => (init_bridgePointer(), exports_bridgePointer)); - const rawPrior = perpetual ? await readBridgePointer2(dir) : null; - const prior = rawPrior?.source === "repl" ? rawPrior : null; - logForDebugging(`[bridge:repl] initBridgeCore #${seq} starting (initialMessages=${initialMessages?.length ?? 0}${prior ? ` perpetual prior=env:${prior.environmentId}` : ""})`); - const rawApi = createBridgeApiClient({ - baseUrl, - getAccessToken, - runnerVersion: MACRO.VERSION, - onDebug: logForDebugging, - onAuth401, - getTrustedDeviceToken - }); - const api4 = process.env.USER_TYPE === "ant" ? wrapApiForFaultInjection(rawApi) : rawApi; - const bridgeConfig = { - dir, - machineName, - branch: branch2, - gitRepoUrl, - maxSessions: 1, - spawnMode: "single-session", - verbose: false, - sandbox: false, - bridgeId: randomUUID54(), - workerType, - environmentId: randomUUID54(), - reuseEnvironmentId: prior?.environmentId, - apiBaseUrl: baseUrl, - sessionIngressUrl - }; - let environmentId; - let environmentSecret; - try { - const reg = await api4.registerBridgeEnvironment(bridgeConfig); - environmentId = reg.environment_id; - environmentSecret = reg.environment_secret; - } catch (err2) { - logBridgeSkip("registration_failed", `[bridge:repl] Environment registration failed: ${errorMessage(err2)}`); - if (prior) { - await clearBridgePointer2(dir); - } - onStateChange?.("failed", errorMessage(err2)); - return null; - } - logForDebugging(`[bridge:repl] Environment registered: ${environmentId}`); - logForDiagnosticsNoPII("info", "bridge_repl_env_registered"); - logEvent("tengu_bridge_repl_env_registered", {}); - async function tryReconnectInPlace(requestedEnvId, sessionId) { - if (environmentId !== requestedEnvId) { - logForDebugging(`[bridge:repl] Env mismatch (requested ${requestedEnvId}, got ${environmentId}) \u2014 cannot reconnect in place`); - return false; - } - const infraId = toInfraSessionId(sessionId); - const candidates = infraId === sessionId ? [sessionId] : [sessionId, infraId]; - for (const id of candidates) { - try { - await api4.reconnectSession(environmentId, id); - logForDebugging(`[bridge:repl] Reconnected session ${id} in place on env ${environmentId}`); - return true; - } catch (err2) { - logForDebugging(`[bridge:repl] reconnectSession(${id}) failed: ${errorMessage(err2)}`); - } - } - logForDebugging("[bridge:repl] reconnectSession exhausted \u2014 falling through to fresh session"); - return false; - } - const reusedPriorSession = prior ? await tryReconnectInPlace(prior.environmentId, prior.sessionId) : false; - if (prior && !reusedPriorSession) { - await clearBridgePointer2(dir); - } - let currentSessionId; - if (reusedPriorSession && prior) { - currentSessionId = prior.sessionId; - logForDebugging(`[bridge:repl] Perpetual session reused: ${currentSessionId}`); - if (initialMessages && previouslyFlushedUUIDs) { - for (const msg of initialMessages) { - previouslyFlushedUUIDs.add(msg.uuid); - } - } - } else { - const createdSessionId = await createSession({ - environmentId, - title, - gitRepoUrl, - branch: branch2, - signal: AbortSignal.timeout(15000) - }); - if (!createdSessionId) { - logForDebugging("[bridge:repl] Session creation failed, deregistering environment"); - logEvent("tengu_bridge_repl_session_failed", {}); - await api4.deregisterEnvironment(environmentId).catch(() => {}); - onStateChange?.("failed", "Session creation failed"); - return null; - } - currentSessionId = createdSessionId; - logForDebugging(`[bridge:repl] Session created: ${currentSessionId}`); - } - await writeBridgePointer2(dir, { - sessionId: currentSessionId, - environmentId, - source: "repl" - }); - logForDiagnosticsNoPII("info", "bridge_repl_session_created"); - logEvent("tengu_bridge_repl_started", { - has_initial_messages: !!(initialMessages && initialMessages.length > 0), - inProtectedNamespace: isInProtectedNamespace2() - }); - const initialMessageUUIDs = new Set; - if (initialMessages) { - for (const msg of initialMessages) { - initialMessageUUIDs.add(msg.uuid); - } - } - const recentPostedUUIDs = new BoundedUUIDSet(2000); - for (const uuid8 of initialMessageUUIDs) { - recentPostedUUIDs.add(uuid8); - } - const recentInboundUUIDs = new BoundedUUIDSet(2000); - const pollController = new AbortController; - let transport = null; - let v2Generation = 0; - let lastTransportSequenceNum = reusedPriorSession ? initialSSESequenceNum : 0; - let currentWorkId = null; - let currentIngressToken = null; - const capacityWake = createCapacityWake(pollController.signal); - const wakePollLoop = capacityWake.wake; - const capacitySignal = capacityWake.signal; - const flushGate = new FlushGate; - let userMessageCallbackDone = !onUserMessage; - const MAX_ENVIRONMENT_RECREATIONS = 3; - let environmentRecreations = 0; - let reconnectPromise = null; - async function reconnectEnvironmentWithSession() { - if (reconnectPromise) { - return reconnectPromise; - } - reconnectPromise = doReconnect(); - try { - return await reconnectPromise; - } finally { - reconnectPromise = null; - } - } - async function doReconnect() { - environmentRecreations++; - v2Generation++; - logForDebugging(`[bridge:repl] Reconnecting after env lost (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`); - if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) { - logForDebugging(`[bridge:repl] Environment reconnect limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`); - return false; - } - if (transport) { - const seq2 = transport.getLastSequenceNum(); - if (seq2 > lastTransportSequenceNum) { - lastTransportSequenceNum = seq2; - } - transport.close(); - transport = null; - } - wakePollLoop(); - flushGate.drop(); - if (currentWorkId) { - const workIdBeingCleared = currentWorkId; - await api4.stopWork(environmentId, workIdBeingCleared, false).catch(() => {}); - if (currentWorkId !== workIdBeingCleared) { - logForDebugging("[bridge:repl] Poll loop recovered during stopWork await \u2014 deferring to it"); - environmentRecreations = 0; - return true; - } - currentWorkId = null; - currentIngressToken = null; - } - if (pollController.signal.aborted) { - logForDebugging("[bridge:repl] Reconnect aborted by teardown"); - return false; - } - const requestedEnvId = environmentId; - bridgeConfig.reuseEnvironmentId = requestedEnvId; - try { - const reg = await api4.registerBridgeEnvironment(bridgeConfig); - environmentId = reg.environment_id; - environmentSecret = reg.environment_secret; - } catch (err2) { - bridgeConfig.reuseEnvironmentId = undefined; - logForDebugging(`[bridge:repl] Environment re-registration failed: ${errorMessage(err2)}`); - return false; - } - bridgeConfig.reuseEnvironmentId = undefined; - logForDebugging(`[bridge:repl] Re-registered: requested=${requestedEnvId} got=${environmentId}`); - if (pollController.signal.aborted) { - logForDebugging("[bridge:repl] Reconnect aborted after env registration, cleaning up"); - await api4.deregisterEnvironment(environmentId).catch(() => {}); - return false; - } - if (transport !== null) { - logForDebugging("[bridge:repl] Poll loop recovered during registerBridgeEnvironment await \u2014 deferring to it"); - environmentRecreations = 0; - return true; - } - if (await tryReconnectInPlace(requestedEnvId, currentSessionId)) { - logEvent("tengu_bridge_repl_reconnected_in_place", {}); - environmentRecreations = 0; - return true; - } - if (environmentId !== requestedEnvId) { - logEvent("tengu_bridge_repl_env_expired_fresh_session", {}); - } - await archiveSession(currentSessionId); - if (pollController.signal.aborted) { - logForDebugging("[bridge:repl] Reconnect aborted after archive, cleaning up"); - await api4.deregisterEnvironment(environmentId).catch(() => {}); - return false; - } - const currentTitle = getCurrentTitle(); - const newSessionId = await createSession({ - environmentId, - title: currentTitle, - gitRepoUrl, - branch: branch2, - signal: AbortSignal.timeout(15000) - }); - if (!newSessionId) { - logForDebugging("[bridge:repl] Session creation failed during reconnection"); - return false; - } - if (pollController.signal.aborted) { - logForDebugging("[bridge:repl] Reconnect aborted after session creation, cleaning up"); - await archiveSession(newSessionId); - return false; - } - currentSessionId = newSessionId; - updateSessionBridgeId(toCompatSessionId(newSessionId)).catch(() => {}); - lastTransportSequenceNum = 0; - recentInboundUUIDs.clear(); - userMessageCallbackDone = !onUserMessage; - logForDebugging(`[bridge:repl] Re-created session: ${currentSessionId}`); - await writeBridgePointer2(dir, { - sessionId: currentSessionId, - environmentId, - source: "repl" - }); - previouslyFlushedUUIDs?.clear(); - environmentRecreations = 0; - return true; - } - function getOAuthToken() { - return getAccessToken(); - } - function drainFlushGate() { - const msgs = flushGate.end(); - if (msgs.length === 0) - return; - if (!transport) { - logForDebugging(`[bridge:repl] Cannot drain ${msgs.length} pending message(s): no transport`); - return; - } - for (const msg of msgs) { - recentPostedUUIDs.add(msg.uuid); - } - const sdkMessages = toSDKMessages2(msgs); - const events2 = sdkMessages.map((sdkMsg) => ({ - ...sdkMsg, - session_id: currentSessionId - })); - logForDebugging(`[bridge:repl] Drained ${msgs.length} pending message(s) after flush`); - transport.writeBatch(events2); - } - let doTeardownImpl = null; - function triggerTeardown() { - doTeardownImpl?.(); - } - function handleTransportPermanentClose(closeCode) { - logForDebugging(`[bridge:repl] Transport permanently closed: code=${closeCode}`); - logEvent("tengu_bridge_repl_ws_closed", { - code: closeCode - }); - if (transport) { - const closedSeq = transport.getLastSequenceNum(); - if (closedSeq > lastTransportSequenceNum) { - lastTransportSequenceNum = closedSeq; - } - transport = null; - } - wakePollLoop(); - const dropped = flushGate.drop(); - if (dropped > 0) { - logForDebugging(`[bridge:repl] Dropping ${dropped} pending message(s) on transport close (code=${closeCode})`, { level: "warn" }); - } - if (closeCode === 1000) { - onStateChange?.("failed", "session ended"); - pollController.abort(); - triggerTeardown(); - return; - } - onStateChange?.("reconnecting", `Remote Control connection lost (code ${closeCode})`); - logForDebugging(`[bridge:repl] Transport reconnect budget exhausted (code=${closeCode}), attempting env reconnect`); - reconnectEnvironmentWithSession().then((success2) => { - if (success2) - return; - if (pollController.signal.aborted) - return; - logForDebugging("[bridge:repl] reconnectEnvironmentWithSession resolved false \u2014 tearing down"); - logEvent("tengu_bridge_repl_reconnect_failed", { - close_code: closeCode - }); - onStateChange?.("failed", "reconnection failed"); - triggerTeardown(); - }); - } - let sigusr2Handler; - if (process.env.USER_TYPE === "ant" && process.platform !== "win32") { - sigusr2Handler = () => { - logForDebugging("[bridge:repl] SIGUSR2 received \u2014 forcing doReconnect() for testing"); - reconnectEnvironmentWithSession(); - }; - process.on("SIGUSR2", sigusr2Handler); - } - let debugFireClose = null; - if (process.env.USER_TYPE === "ant") { - registerBridgeDebugHandle({ - fireClose: (code) => { - if (!debugFireClose) { - logForDebugging("[bridge:debug] fireClose: no transport wired yet"); - return; - } - logForDebugging(`[bridge:debug] fireClose(${code}) \u2014 injecting`); - debugFireClose(code); - }, - forceReconnect: () => { - logForDebugging("[bridge:debug] forceReconnect \u2014 injecting"); - reconnectEnvironmentWithSession(); - }, - injectFault: injectBridgeFault, - wakePollLoop, - describe: () => `env=${environmentId} session=${currentSessionId} transport=${transport?.getStateLabel() ?? "null"} workId=${currentWorkId ?? "null"}` - }); - } - const pollOpts = { - api: api4, - getCredentials: () => ({ environmentId, environmentSecret }), - signal: pollController.signal, - getPollIntervalConfig: getPollIntervalConfig2, - onStateChange, - getWsState: () => transport?.getStateLabel() ?? "null", - isAtCapacity: () => transport !== null, - capacitySignal, - onFatalError: triggerTeardown, - getHeartbeatInfo: () => { - if (!currentWorkId || !currentIngressToken) { - return null; - } - return { - environmentId, - workId: currentWorkId, - sessionToken: currentIngressToken - }; - }, - onHeartbeatFatal: (err2) => { - logForDebugging(`[bridge:repl] heartbeatWork fatal (status=${err2.status}) \u2014 tearing down work item for fast re-dispatch`); - if (transport) { - const seq2 = transport.getLastSequenceNum(); - if (seq2 > lastTransportSequenceNum) { - lastTransportSequenceNum = seq2; - } - transport.close(); - transport = null; - } - flushGate.drop(); - if (currentWorkId) { - api4.stopWork(environmentId, currentWorkId, false).catch((e4) => { - logForDebugging(`[bridge:repl] stopWork after heartbeat fatal: ${errorMessage(e4)}`); - }); - } - currentWorkId = null; - currentIngressToken = null; - wakePollLoop(); - onStateChange?.("reconnecting", "Work item lease expired, fetching fresh token"); - }, - async onEnvironmentLost() { - const success2 = await reconnectEnvironmentWithSession(); - if (!success2) { - return null; - } - return { environmentId, environmentSecret }; - }, - onWorkReceived: (workSessionId, ingressToken, workId, serverUseCcrV2) => { - if (transport?.isConnectedStatus()) { - logForDebugging(`[bridge:repl] Work received while transport connected, replacing with fresh token (workId=${workId})`); - } - logForDebugging(`[bridge:repl] Work received: workId=${workId} workSessionId=${workSessionId} currentSessionId=${currentSessionId} match=${sameSessionId(workSessionId, currentSessionId)}`); - writeBridgePointer2(dir, { - sessionId: currentSessionId, - environmentId, - source: "repl" - }); - if (!sameSessionId(workSessionId, currentSessionId)) { - logForDebugging(`[bridge:repl] Rejecting foreign session: expected=${currentSessionId} got=${workSessionId}`); - return; - } - currentWorkId = workId; - currentIngressToken = ingressToken; - const useCcrV2 = serverUseCcrV2 || isEnvTruthy(process.env.CLAUDE_BRIDGE_USE_CCR_V2); - let v1OauthToken; - if (!useCcrV2) { - v1OauthToken = getOAuthToken(); - if (!v1OauthToken) { - logForDebugging("[bridge:repl] No OAuth token available for session ingress, skipping work"); - return; - } - updateSessionIngressAuthToken(v1OauthToken); - } - logEvent("tengu_bridge_repl_work_received", {}); - if (transport) { - const oldTransport = transport; - transport = null; - const oldSeq = oldTransport.getLastSequenceNum(); - if (oldSeq > lastTransportSequenceNum) { - lastTransportSequenceNum = oldSeq; - } - oldTransport.close(); - } - flushGate.deactivate(); - const onServerControlRequest = (request2) => handleServerControlRequest(request2, { - transport, - sessionId: currentSessionId, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode - }); - let initialFlushDone = false; - const wireTransport = (newTransport) => { - transport = newTransport; - newTransport.setOnConnect(() => { - if (transport !== newTransport) - return; - logForDebugging("[bridge:repl] Ingress transport connected"); - logEvent("tengu_bridge_repl_ws_connected", {}); - if (!useCcrV2) { - const freshToken = getOAuthToken(); - if (freshToken) { - updateSessionIngressAuthToken(freshToken); - } - } - teardownStarted = false; - if (!initialFlushDone && initialMessages && initialMessages.length > 0) { - initialFlushDone = true; - const historyCap = initialHistoryCap; - const eligibleMessages = initialMessages.filter((m4) => isEligibleBridgeMessage(m4) && !previouslyFlushedUUIDs?.has(m4.uuid)); - const cappedMessages = historyCap > 0 && eligibleMessages.length > historyCap ? eligibleMessages.slice(-historyCap) : eligibleMessages; - if (cappedMessages.length < eligibleMessages.length) { - logForDebugging(`[bridge:repl] Capped initial flush: ${eligibleMessages.length} -> ${cappedMessages.length} (cap=${historyCap})`); - logEvent("tengu_bridge_repl_history_capped", { - eligible_count: eligibleMessages.length, - capped_count: cappedMessages.length - }); - } - const sdkMessages = toSDKMessages2(cappedMessages); - if (sdkMessages.length > 0) { - logForDebugging(`[bridge:repl] Flushing ${sdkMessages.length} initial message(s) via transport`); - const events2 = sdkMessages.map((sdkMsg) => ({ - ...sdkMsg, - session_id: currentSessionId - })); - const dropsBefore = newTransport.droppedBatchCount; - newTransport.writeBatch(events2).then(() => { - if (newTransport.droppedBatchCount > dropsBefore) { - logForDebugging(`[bridge:repl] Initial flush dropped ${newTransport.droppedBatchCount - dropsBefore} batch(es) \u2014 not marking ${sdkMessages.length} UUID(s) as flushed`); - return; - } - if (previouslyFlushedUUIDs) { - for (const sdkMsg of sdkMessages) { - if (sdkMsg.uuid) { - previouslyFlushedUUIDs.add(sdkMsg.uuid); - } - } - } - }).catch((e4) => logForDebugging(`[bridge:repl] Initial flush failed: ${e4}`)).finally(() => { - if (transport !== newTransport) - return; - drainFlushGate(); - onStateChange?.("connected"); - }); - } else { - drainFlushGate(); - onStateChange?.("connected"); - } - } else if (!flushGate.active) { - onStateChange?.("connected"); - } - }); - newTransport.setOnData((data) => { - handleIngressMessage(data, recentPostedUUIDs, recentInboundUUIDs, onInboundMessage, onPermissionResponse, onServerControlRequest); - }); - debugFireClose = handleTransportPermanentClose; - newTransport.setOnClose((closeCode) => { - if (transport !== newTransport) - return; - handleTransportPermanentClose(closeCode); - }); - if (!initialFlushDone && initialMessages && initialMessages.length > 0) { - flushGate.start(); - } - newTransport.connect(); - }; - v2Generation++; - if (useCcrV2) { - const sessionUrl = buildCCRv2SdkUrl(baseUrl, workSessionId); - const thisGen = v2Generation; - logForDebugging(`[bridge:repl] CCR v2: sessionUrl=${sessionUrl} session=${workSessionId} gen=${thisGen}`); - createV2ReplTransport({ - sessionUrl, - ingressToken, - sessionId: workSessionId, - initialSequenceNum: lastTransportSequenceNum - }).then((t4) => { - if (pollController.signal.aborted) { - t4.close(); - return; - } - if (thisGen !== v2Generation) { - logForDebugging(`[bridge:repl] CCR v2: discarding stale handshake gen=${thisGen} current=${v2Generation}`); - t4.close(); - return; - } - wireTransport(t4); - }, (err2) => { - logForDebugging(`[bridge:repl] CCR v2: createV2ReplTransport failed: ${errorMessage(err2)}`, { level: "error" }); - logEvent("tengu_bridge_repl_ccr_v2_init_failed", {}); - if (thisGen !== v2Generation) - return; - if (currentWorkId) { - api4.stopWork(environmentId, currentWorkId, false).catch((e4) => { - logForDebugging(`[bridge:repl] stopWork after v2 init failure: ${errorMessage(e4)}`); - }); - currentWorkId = null; - currentIngressToken = null; - } - wakePollLoop(); - }); - } else { - const wsUrl = buildSdkUrl(sessionIngressUrl, workSessionId); - logForDebugging(`[bridge:repl] Ingress URL: ${wsUrl}`); - logForDebugging(`[bridge:repl] Creating HybridTransport: session=${workSessionId}`); - const oauthToken = v1OauthToken ?? ""; - wireTransport(createV1ReplTransport(new HybridTransport(new URL(wsUrl), { - Authorization: `Bearer ${oauthToken}`, - "anthropic-version": "2023-06-01" - }, workSessionId, () => ({ - Authorization: `Bearer ${getOAuthToken() ?? oauthToken}`, - "anthropic-version": "2023-06-01" - }), { - maxConsecutiveFailures: 50, - isBridge: true, - onBatchDropped: () => { - onStateChange?.("reconnecting", "Lost sync with Remote Control \u2014 events could not be delivered"); - wakePollLoop(); - } - }))); - } - } - }; - startWorkPollLoop(pollOpts); - const pointerRefreshTimer = perpetual ? setInterval(() => { - if (reconnectPromise) - return; - writeBridgePointer2(dir, { - sessionId: currentSessionId, - environmentId, - source: "repl" - }); - }, 3600000) : null; - pointerRefreshTimer?.unref?.(); - const keepAliveIntervalMs = getPollIntervalConfig2().session_keepalive_interval_v2_ms; - const keepAliveTimer = keepAliveIntervalMs > 0 ? setInterval(() => { - if (!transport) - return; - logForDebugging("[bridge:repl] keep_alive sent"); - transport.write({ type: "keep_alive" }).catch((err2) => { - logForDebugging(`[bridge:repl] keep_alive write failed: ${errorMessage(err2)}`); - }); - }, keepAliveIntervalMs) : null; - keepAliveTimer?.unref?.(); - let teardownStarted = false; - doTeardownImpl = async () => { - if (teardownStarted) { - logForDebugging(`[bridge:repl] Teardown already in progress, skipping duplicate call env=${environmentId} session=${currentSessionId}`); - return; - } - teardownStarted = true; - const teardownStart = Date.now(); - logForDebugging(`[bridge:repl] Teardown starting: env=${environmentId} session=${currentSessionId} workId=${currentWorkId ?? "none"} transportState=${transport?.getStateLabel() ?? "null"}`); - if (pointerRefreshTimer !== null) { - clearInterval(pointerRefreshTimer); - } - if (keepAliveTimer !== null) { - clearInterval(keepAliveTimer); - } - if (sigusr2Handler) { - process.off("SIGUSR2", sigusr2Handler); - } - if (process.env.USER_TYPE === "ant") { - clearBridgeDebugHandle(); - debugFireClose = null; - } - pollController.abort(); - logForDebugging("[bridge:repl] Teardown: poll loop aborted"); - if (transport) { - const finalSeq = transport.getLastSequenceNum(); - if (finalSeq > lastTransportSequenceNum) { - lastTransportSequenceNum = finalSeq; - } - } - if (perpetual) { - transport = null; - flushGate.drop(); - await writeBridgePointer2(dir, { - sessionId: currentSessionId, - environmentId, - source: "repl" - }); - logForDebugging(`[bridge:repl] Teardown (perpetual): leaving env=${environmentId} session=${currentSessionId} alive on server, duration=${Date.now() - teardownStart}ms`); - return; - } - const teardownTransport = transport; - transport = null; - flushGate.drop(); - if (teardownTransport) { - teardownTransport.write(makeResultMessage(currentSessionId)); - } - const stopWorkP = currentWorkId ? api4.stopWork(environmentId, currentWorkId, true).then(() => { - logForDebugging("[bridge:repl] Teardown: stopWork completed"); - }).catch((err2) => { - logForDebugging(`[bridge:repl] Teardown stopWork failed: ${errorMessage(err2)}`); - }) : Promise.resolve(); - await Promise.all([stopWorkP, archiveSession(currentSessionId)]); - teardownTransport?.close(); - logForDebugging("[bridge:repl] Teardown: transport closed"); - await api4.deregisterEnvironment(environmentId).catch((err2) => { - logForDebugging(`[bridge:repl] Teardown deregister failed: ${errorMessage(err2)}`); - }); - await clearBridgePointer2(dir); - logForDebugging(`[bridge:repl] Teardown complete: env=${environmentId} duration=${Date.now() - teardownStart}ms`); - }; - const unregister = registerCleanup(() => doTeardownImpl?.()); - logForDebugging(`[bridge:repl] Ready: env=${environmentId} session=${currentSessionId}`); - onStateChange?.("ready"); - return { - get bridgeSessionId() { - return currentSessionId; - }, - get environmentId() { - return environmentId; - }, - getSSESequenceNum() { - const live = transport?.getLastSequenceNum() ?? 0; - return Math.max(lastTransportSequenceNum, live); - }, - sessionIngressUrl, - writeMessages(messages) { - const filtered = messages.filter((m4) => isEligibleBridgeMessage(m4) && !initialMessageUUIDs.has(m4.uuid) && !recentPostedUUIDs.has(m4.uuid)); - if (filtered.length === 0) - return; - if (!userMessageCallbackDone) { - for (const m4 of filtered) { - const text = extractTitleText(m4); - if (text !== undefined && onUserMessage?.(text, currentSessionId)) { - userMessageCallbackDone = true; - break; - } - } - } - if (flushGate.enqueue(...filtered)) { - logForDebugging(`[bridge:repl] Queued ${filtered.length} message(s) during initial flush`); - return; - } - if (!transport) { - const types14 = filtered.map((m4) => m4.type).join(","); - logForDebugging(`[bridge:repl] Transport not configured, dropping ${filtered.length} message(s) [${types14}] for session=${currentSessionId}`, { level: "warn" }); - return; - } - for (const msg of filtered) { - recentPostedUUIDs.add(msg.uuid); - } - logForDebugging(`[bridge:repl] Sending ${filtered.length} message(s) via transport`); - const sdkMessages = toSDKMessages2(filtered); - const events2 = sdkMessages.map((sdkMsg) => ({ - ...sdkMsg, - session_id: currentSessionId - })); - transport.writeBatch(events2); - }, - writeSdkMessages(messages) { - const filtered = messages.filter((m4) => !m4.uuid || !recentPostedUUIDs.has(m4.uuid)); - if (filtered.length === 0) - return; - if (!transport) { - logForDebugging(`[bridge:repl] Transport not configured, dropping ${filtered.length} SDK message(s) for session=${currentSessionId}`, { level: "warn" }); - return; - } - for (const msg of filtered) { - if (msg.uuid) - recentPostedUUIDs.add(msg.uuid); - } - const events2 = filtered.map((m4) => ({ ...m4, session_id: currentSessionId })); - transport.writeBatch(events2); - }, - sendControlRequest(request2) { - if (!transport) { - logForDebugging("[bridge:repl] Transport not configured, skipping control_request"); - return; - } - const event = { ...request2, session_id: currentSessionId }; - transport.write(event); - logForDebugging(`[bridge:repl] Sent control_request request_id=${request2.request_id}`); - }, - sendControlResponse(response7) { - if (!transport) { - logForDebugging("[bridge:repl] Transport not configured, skipping control_response"); - return; - } - const event = { ...response7, session_id: currentSessionId }; - transport.write(event); - logForDebugging("[bridge:repl] Sent control_response"); - }, - sendControlCancelRequest(requestId) { - if (!transport) { - logForDebugging("[bridge:repl] Transport not configured, skipping control_cancel_request"); - return; - } - const event = { - type: "control_cancel_request", - request_id: requestId, - session_id: currentSessionId - }; - transport.write(event); - logForDebugging(`[bridge:repl] Sent control_cancel_request request_id=${requestId}`); - }, - sendResult() { - if (!transport) { - logForDebugging(`[bridge:repl] sendResult: skipping, transport not configured session=${currentSessionId}`); - return; - } - transport.write(makeResultMessage(currentSessionId)); - logForDebugging(`[bridge:repl] Sent result for session=${currentSessionId}`); - }, - async teardown() { - unregister(); - await doTeardownImpl?.(); - logForDebugging("[bridge:repl] Torn down"); - logEvent("tengu_bridge_repl_teardown", {}); - } - }; -} -async function startWorkPollLoop({ - api: api4, - getCredentials: getCredentials2, - signal, - onStateChange, - onWorkReceived, - onEnvironmentLost, - getWsState, - isAtCapacity, - capacitySignal, - onFatalError, - getPollIntervalConfig: getPollIntervalConfig2 = () => DEFAULT_POLL_CONFIG, - getHeartbeatInfo, - onHeartbeatFatal -}) { - const MAX_ENVIRONMENT_RECREATIONS = 3; - logForDebugging(`[bridge:repl] Starting work poll loop for env=${getCredentials2().environmentId}`); - let consecutiveErrors = 0; - let firstErrorTime = null; - let lastPollErrorTime = null; - let environmentRecreations = 0; - let suspensionDetected = false; - while (!signal.aborted) { - const { environmentId: envId, environmentSecret: envSecret } = getCredentials2(); - const pollConfig = getPollIntervalConfig2(); - try { - const work = await api4.pollForWork(envId, envSecret, signal, pollConfig.reclaim_older_than_ms); - environmentRecreations = 0; - if (consecutiveErrors > 0) { - logForDebugging(`[bridge:repl] Poll recovered after ${consecutiveErrors} consecutive error(s)`); - consecutiveErrors = 0; - firstErrorTime = null; - lastPollErrorTime = null; - onStateChange?.("ready"); - } - if (!work) { - const skipAtCapacityOnce = suspensionDetected; - suspensionDetected = false; - if (isAtCapacity?.() && capacitySignal && !skipAtCapacityOnce) { - const atCapMs = pollConfig.poll_interval_ms_at_capacity; - if (pollConfig.non_exclusive_heartbeat_interval_ms > 0 && getHeartbeatInfo) { - logEvent("tengu_bridge_heartbeat_mode_entered", { - heartbeat_interval_ms: pollConfig.non_exclusive_heartbeat_interval_ms - }); - const pollDeadline = atCapMs > 0 ? Date.now() + atCapMs : null; - let needsBackoff = false; - let hbCycles = 0; - while (!signal.aborted && isAtCapacity() && (pollDeadline === null || Date.now() < pollDeadline)) { - const hbConfig = getPollIntervalConfig2(); - if (hbConfig.non_exclusive_heartbeat_interval_ms <= 0) - break; - const info = getHeartbeatInfo(); - if (!info) - break; - const cap = capacitySignal(); - try { - await api4.heartbeatWork(info.environmentId, info.workId, info.sessionToken); - } catch (err2) { - logForDebugging(`[bridge:repl:heartbeat] Failed: ${errorMessage(err2)}`); - if (err2 instanceof BridgeFatalError) { - cap.cleanup(); - logEvent("tengu_bridge_heartbeat_error", { - status: err2.status, - error_type: err2.status === 401 || err2.status === 403 ? "auth_failed" : "fatal" - }); - if (onHeartbeatFatal) { - onHeartbeatFatal(err2); - logForDebugging(`[bridge:repl:heartbeat] Fatal (status=${err2.status}), work state cleared \u2014 fast-polling for re-dispatch`); - } else { - needsBackoff = true; - } - break; - } - } - hbCycles++; - await sleep6(hbConfig.non_exclusive_heartbeat_interval_ms, cap.signal); - cap.cleanup(); - } - const exitReason = needsBackoff ? "error" : signal.aborted ? "shutdown" : !isAtCapacity() ? "capacity_changed" : pollDeadline !== null && Date.now() >= pollDeadline ? "poll_due" : "config_disabled"; - logEvent("tengu_bridge_heartbeat_mode_exited", { - reason: exitReason, - heartbeat_cycles: hbCycles - }); - if (!needsBackoff) { - if (exitReason === "poll_due") { - logForDebugging(`[bridge:repl] Heartbeat poll_due after ${hbCycles} cycles \u2014 falling through to pollForWork`); - } - continue; - } - } - const sleepMs = atCapMs > 0 ? atCapMs : pollConfig.non_exclusive_heartbeat_interval_ms; - if (sleepMs > 0) { - const cap = capacitySignal(); - const sleepStart = Date.now(); - await sleep6(sleepMs, cap.signal); - cap.cleanup(); - const overrun = Date.now() - sleepStart - sleepMs; - if (overrun > 60000) { - logForDebugging(`[bridge:repl] At-capacity sleep overran by ${Math.round(overrun / 1000)}s \u2014 process suspension detected, forcing one fast-poll cycle`); - logEvent("tengu_bridge_repl_suspension_detected", { - overrun_ms: overrun - }); - suspensionDetected = true; - } - } - } else { - await sleep6(pollConfig.poll_interval_ms_not_at_capacity, signal); - } - continue; - } - let secret; - try { - secret = decodeWorkSecret(work.secret); - } catch (err2) { - logForDebugging(`[bridge:repl] Failed to decode work secret: ${errorMessage(err2)}`); - logEvent("tengu_bridge_repl_work_secret_failed", {}); - await api4.stopWork(envId, work.id, false).catch(() => {}); - continue; - } - logForDebugging(`[bridge:repl] Acknowledging workId=${work.id}`); - try { - await api4.acknowledgeWork(envId, work.id, secret.session_ingress_token); - } catch (err2) { - logForDebugging(`[bridge:repl] Acknowledge failed workId=${work.id}: ${errorMessage(err2)}`); - } - if (work.data.type === "healthcheck") { - logForDebugging("[bridge:repl] Healthcheck received"); - continue; - } - if (work.data.type === "session") { - const workSessionId = work.data.id; - try { - validateBridgeId(workSessionId, "session_id"); - } catch { - logForDebugging(`[bridge:repl] Invalid session_id in work: ${workSessionId}`); - continue; - } - onWorkReceived(workSessionId, secret.session_ingress_token, work.id, secret.use_code_sessions === true); - logForDebugging("[bridge:repl] Work accepted, continuing poll loop"); - } - } catch (err2) { - if (signal.aborted) - break; - if (err2 instanceof BridgeFatalError && err2.status === 404 && onEnvironmentLost) { - const currentEnvId = getCredentials2().environmentId; - if (envId !== currentEnvId) { - logForDebugging(`[bridge:repl] Stale poll error for old env=${envId}, current env=${currentEnvId} \u2014 skipping onEnvironmentLost`); - consecutiveErrors = 0; - firstErrorTime = null; - continue; - } - environmentRecreations++; - logForDebugging(`[bridge:repl] Environment deleted, attempting re-registration (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`); - logEvent("tengu_bridge_repl_env_lost", { - attempt: environmentRecreations - }); - if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) { - logForDebugging(`[bridge:repl] Environment re-registration limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`); - onStateChange?.("failed", "Environment deleted and re-registration limit reached"); - onFatalError?.(); - break; - } - onStateChange?.("reconnecting", "environment lost, recreating session"); - const newCreds = await onEnvironmentLost(); - if (signal.aborted) - break; - if (newCreds) { - consecutiveErrors = 0; - firstErrorTime = null; - onStateChange?.("ready"); - logForDebugging(`[bridge:repl] Re-registered environment: ${newCreds.environmentId}`); - continue; - } - onStateChange?.("failed", "Environment deleted and re-registration failed"); - onFatalError?.(); - break; - } - if (err2 instanceof BridgeFatalError) { - const isExpiry = isExpiredErrorType(err2.errorType); - const isSuppressible = isSuppressible403(err2); - logForDebugging(`[bridge:repl] Fatal poll error: ${err2.message} (status=${err2.status}, type=${err2.errorType ?? "unknown"})${isSuppressible ? " (suppressed)" : ""}`); - logEvent("tengu_bridge_repl_fatal_error", { - status: err2.status, - error_type: err2.errorType - }); - logForDiagnosticsNoPII(isExpiry ? "info" : "error", "bridge_repl_fatal_error", { status: err2.status, error_type: err2.errorType }); - if (!isSuppressible) { - onStateChange?.("failed", isExpiry ? "session expired \xB7 /remote-control to reconnect" : err2.message); - } - onFatalError?.(); - break; - } - const now2 = Date.now(); - if (lastPollErrorTime !== null && now2 - lastPollErrorTime > POLL_ERROR_MAX_DELAY_MS * 2) { - logForDebugging(`[bridge:repl] Detected system sleep (${Math.round((now2 - lastPollErrorTime) / 1000)}s gap), resetting poll error budget`); - logForDiagnosticsNoPII("info", "bridge_repl_poll_sleep_detected", { - gapMs: now2 - lastPollErrorTime - }); - consecutiveErrors = 0; - firstErrorTime = null; - } - lastPollErrorTime = now2; - consecutiveErrors++; - if (firstErrorTime === null) { - firstErrorTime = now2; - } - const elapsed = now2 - firstErrorTime; - const httpStatus = extractHttpStatus(err2); - const errMsg = describeAxiosError(err2); - const wsLabel = getWsState?.() ?? "unknown"; - logForDebugging(`[bridge:repl] Poll error (attempt ${consecutiveErrors}, elapsed ${Math.round(elapsed / 1000)}s, ws=${wsLabel}): ${errMsg}`); - logEvent("tengu_bridge_repl_poll_error", { - status: httpStatus, - consecutiveErrors, - elapsedMs: elapsed - }); - if (consecutiveErrors === 1) { - onStateChange?.("reconnecting", errMsg); - } - if (elapsed >= POLL_ERROR_GIVE_UP_MS) { - logForDebugging(`[bridge:repl] Poll failures exceeded ${POLL_ERROR_GIVE_UP_MS / 1000}s (${consecutiveErrors} errors), giving up`); - logForDiagnosticsNoPII("info", "bridge_repl_poll_give_up"); - logEvent("tengu_bridge_repl_poll_give_up", { - consecutiveErrors, - elapsedMs: elapsed, - lastStatus: httpStatus - }); - onStateChange?.("failed", "connection to server lost"); - break; - } - const backoff = Math.min(POLL_ERROR_INITIAL_DELAY_MS * 2 ** (consecutiveErrors - 1), POLL_ERROR_MAX_DELAY_MS); - if (getPollIntervalConfig2().non_exclusive_heartbeat_interval_ms > 0) { - const info = getHeartbeatInfo?.(); - if (info) { - try { - await api4.heartbeatWork(info.environmentId, info.workId, info.sessionToken); - } catch {} - } - } - await sleep6(backoff, signal); - } - } - logForDebugging(`[bridge:repl] Work poll loop ended (aborted=${signal.aborted}) env=${getCredentials2().environmentId}`); -} -var POLL_ERROR_INITIAL_DELAY_MS = 2000, POLL_ERROR_MAX_DELAY_MS = 60000, POLL_ERROR_GIVE_UP_MS, initSequence = 0; -var init_replBridge = __esm(() => { - init_bridgeApi(); - init_debug(); - init_diagLogs(); - init_analytics(); - init_cleanupRegistry(); - init_bridgeMessaging(); - init_workSecret(); - init_concurrentSessions(); - init_trustedDevice(); - init_HybridTransport(); - init_replBridgeTransport(); - init_sessionIngressAuth(); - init_envUtils(); - init_bridgeApi(); - init_debugUtils(); - init_pollConfigDefaults(); - init_errors(); - init_bridgeDebug(); - POLL_ERROR_GIVE_UP_MS = 15 * 60 * 1000; -}); - -// src/bridge/codeSessionApi.ts -function oauthHeaders(accessToken) { - return { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "anthropic-version": ANTHROPIC_VERSION2 - }; -} -async function createCodeSession(baseUrl, accessToken, title, timeoutMs, tags) { - const url3 = `${baseUrl}/v1/code/sessions`; - let response7; - try { - response7 = await axios_default.post(url3, { title, bridge: {}, ...tags?.length ? { tags } : {} }, { - headers: oauthHeaders(accessToken), - timeout: timeoutMs, - validateStatus: (s4) => s4 < 500 - }); - } catch (err2) { - logForDebugging(`[code-session] Session create request failed: ${errorMessage(err2)}`); - return null; - } - if (response7.status !== 200 && response7.status !== 201) { - const detail = extractErrorDetail(response7.data); - logForDebugging(`[code-session] Session create failed ${response7.status}${detail ? `: ${detail}` : ""}`); - return null; - } - const data = response7.data; - if (!data || typeof data !== "object" || !("session" in data) || !data.session || typeof data.session !== "object" || !("id" in data.session) || typeof data.session.id !== "string" || !data.session.id.startsWith("cse_")) { - logForDebugging(`[code-session] No session.id (cse_*) in response: ${jsonStringify(data).slice(0, 200)}`); - return null; - } - return data.session.id; -} -async function fetchRemoteCredentials(sessionId, baseUrl, accessToken, timeoutMs, trustedDeviceToken) { - const url3 = `${baseUrl}/v1/code/sessions/${sessionId}/bridge`; - const headers = oauthHeaders(accessToken); - if (trustedDeviceToken) { - headers["X-Trusted-Device-Token"] = trustedDeviceToken; - } - let response7; - try { - response7 = await axios_default.post(url3, {}, { - headers, - timeout: timeoutMs, - validateStatus: (s4) => s4 < 500 - }); - } catch (err2) { - logForDebugging(`[code-session] /bridge request failed: ${errorMessage(err2)}`); - return null; - } - if (response7.status !== 200) { - const detail = extractErrorDetail(response7.data); - logForDebugging(`[code-session] /bridge failed ${response7.status}${detail ? `: ${detail}` : ""}`); - return null; - } - const data = response7.data; - if (data === null || typeof data !== "object" || !("worker_jwt" in data) || typeof data.worker_jwt !== "string" || !("expires_in" in data) || typeof data.expires_in !== "number" || !("api_base_url" in data) || typeof data.api_base_url !== "string" || !("worker_epoch" in data)) { - logForDebugging(`[code-session] /bridge response malformed (need worker_jwt, expires_in, api_base_url, worker_epoch): ${jsonStringify(data).slice(0, 200)}`); - return null; - } - const rawEpoch = data.worker_epoch; - const epoch = typeof rawEpoch === "string" ? Number(rawEpoch) : rawEpoch; - if (typeof epoch !== "number" || !Number.isFinite(epoch) || !Number.isSafeInteger(epoch)) { - logForDebugging(`[code-session] /bridge worker_epoch invalid: ${jsonStringify(rawEpoch)}`); - return null; - } - return { - worker_jwt: data.worker_jwt, - api_base_url: data.api_base_url, - expires_in: data.expires_in, - worker_epoch: epoch - }; -} -var ANTHROPIC_VERSION2 = "2023-06-01"; -var init_codeSessionApi = __esm(() => { - init_axios2(); - init_debug(); - init_errors(); - init_slowOperations(); - init_debugUtils(); -}); - -// src/bridge/remoteBridgeCore.ts -var exports_remoteBridgeCore = {}; -__export(exports_remoteBridgeCore, { - initEnvLessBridgeCore: () => initEnvLessBridgeCore, - fetchRemoteCredentials: () => fetchRemoteCredentials2, - createCodeSession: () => createCodeSession -}); -function oauthHeaders2(accessToken) { - return { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "anthropic-version": ANTHROPIC_VERSION3 - }; -} -async function initEnvLessBridgeCore(params) { - const { - baseUrl, - orgUUID, - title, - getAccessToken, - onAuth401, - toSDKMessages: toSDKMessages2, - initialHistoryCap, - initialMessages, - onInboundMessage, - onUserMessage, - onPermissionResponse, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode, - onStateChange, - outboundOnly, - tags - } = params; - const cfg = await getEnvLessBridgeConfig(); - const accessToken = getAccessToken(); - if (!accessToken) { - logForDebugging("[remote-bridge] No OAuth token"); - return null; - } - const createdSessionId = await withRetry2(() => createCodeSession(baseUrl, accessToken, title, cfg.http_timeout_ms, tags), "createCodeSession", cfg); - if (!createdSessionId) { - onStateChange?.("failed", "Session creation failed \u2014 see debug log"); - logBridgeSkip("v2_session_create_failed", undefined, true); - return null; - } - const sessionId = createdSessionId; - logForDebugging(`[remote-bridge] Created session ${sessionId}`); - logForDiagnosticsNoPII("info", "bridge_repl_v2_session_created"); - const credentials = await withRetry2(() => fetchRemoteCredentials2(sessionId, baseUrl, accessToken, cfg.http_timeout_ms), "fetchRemoteCredentials", cfg); - if (!credentials) { - onStateChange?.("failed", "Remote credentials fetch failed \u2014 see debug log"); - logBridgeSkip("v2_remote_creds_failed", undefined, true); - archiveSession(sessionId, baseUrl, accessToken, orgUUID, cfg.http_timeout_ms); - return null; - } - logForDebugging(`[remote-bridge] Fetched bridge credentials (expires_in=${credentials.expires_in}s)`); - const sessionUrl = buildCCRv2SdkUrl(credentials.api_base_url, sessionId); - logForDebugging(`[remote-bridge] v2 session URL: ${sessionUrl}`); - let transport; - try { - transport = await createV2ReplTransport({ - sessionUrl, - ingressToken: credentials.worker_jwt, - sessionId, - epoch: credentials.worker_epoch, - heartbeatIntervalMs: cfg.heartbeat_interval_ms, - heartbeatJitterFraction: cfg.heartbeat_jitter_fraction, - getAuthToken: () => credentials.worker_jwt, - outboundOnly - }); - } catch (err2) { - logForDebugging(`[remote-bridge] v2 transport setup failed: ${errorMessage(err2)}`, { level: "error" }); - onStateChange?.("failed", `Transport setup failed: ${errorMessage(err2)}`); - logBridgeSkip("v2_transport_setup_failed", undefined, true); - archiveSession(sessionId, baseUrl, accessToken, orgUUID, cfg.http_timeout_ms); - return null; - } - logForDebugging(`[remote-bridge] v2 transport created (epoch=${credentials.worker_epoch})`); - onStateChange?.("ready"); - const recentPostedUUIDs = new BoundedUUIDSet(cfg.uuid_dedup_buffer_size); - const initialMessageUUIDs = new Set; - if (initialMessages) { - for (const msg of initialMessages) { - initialMessageUUIDs.add(msg.uuid); - recentPostedUUIDs.add(msg.uuid); - } - } - const recentInboundUUIDs = new BoundedUUIDSet(cfg.uuid_dedup_buffer_size); - const flushGate = new FlushGate; - let initialFlushDone = false; - let tornDown = false; - let authRecoveryInFlight = false; - let userMessageCallbackDone = !onUserMessage; - let connectCause = "initial"; - let connectDeadline; - function onConnectTimeout(cause) { - if (tornDown) - return; - logEvent("tengu_bridge_repl_connect_timeout", { - v2: true, - elapsed_ms: cfg.connect_timeout_ms, - cause - }); - } - const refresh = createTokenRefreshScheduler({ - refreshBufferMs: cfg.token_refresh_buffer_ms, - getAccessToken: async () => { - const stale = getAccessToken(); - if (onAuth401) - await onAuth401(stale ?? ""); - return getAccessToken() ?? stale; - }, - onRefresh: (sid, oauthToken) => { - (async () => { - if (authRecoveryInFlight || tornDown) { - logForDebugging("[remote-bridge] Recovery already in flight, skipping proactive refresh"); - return; - } - authRecoveryInFlight = true; - try { - const fresh = await withRetry2(() => fetchRemoteCredentials2(sid, baseUrl, oauthToken, cfg.http_timeout_ms), "fetchRemoteCredentials (proactive)", cfg); - if (!fresh || tornDown) - return; - await rebuildTransport(fresh, "proactive_refresh"); - logForDebugging("[remote-bridge] Transport rebuilt (proactive refresh)"); - } catch (err2) { - logForDebugging(`[remote-bridge] Proactive refresh rebuild failed: ${errorMessage(err2)}`, { level: "error" }); - logForDiagnosticsNoPII("error", "bridge_repl_v2_proactive_refresh_failed"); - if (!tornDown) { - onStateChange?.("failed", `Refresh failed: ${errorMessage(err2)}`); - } - } finally { - authRecoveryInFlight = false; - } - })(); - }, - label: "remote" - }); - refresh.scheduleFromExpiresIn(sessionId, credentials.expires_in); - function wireTransportCallbacks() { - transport.setOnConnect(() => { - clearTimeout(connectDeadline); - logForDebugging("[remote-bridge] v2 transport connected"); - logForDiagnosticsNoPII("info", "bridge_repl_v2_transport_connected"); - logEvent("tengu_bridge_repl_ws_connected", { - v2: true, - cause: connectCause - }); - if (!initialFlushDone && initialMessages && initialMessages.length > 0) { - initialFlushDone = true; - const flushTransport = transport; - flushHistory(initialMessages).catch((e4) => logForDebugging(`[remote-bridge] flushHistory failed: ${e4}`)).finally(() => { - if (transport !== flushTransport || tornDown || authRecoveryInFlight) { - return; - } - drainFlushGate(); - onStateChange?.("connected"); - }); - } else if (!flushGate.active) { - onStateChange?.("connected"); - } - }); - transport.setOnData((data) => { - handleIngressMessage(data, recentPostedUUIDs, recentInboundUUIDs, onInboundMessage, onPermissionResponse ? (res) => { - transport.reportState("running"); - onPermissionResponse(res); - } : undefined, (req) => handleServerControlRequest(req, { - transport, - sessionId, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode, - outboundOnly - })); - }); - transport.setOnClose((code) => { - clearTimeout(connectDeadline); - if (tornDown) - return; - logForDebugging(`[remote-bridge] v2 transport closed (code=${code})`); - logEvent("tengu_bridge_repl_ws_closed", { code, v2: true }); - if (code === 401 && !authRecoveryInFlight) { - recoverFromAuthFailure(); - return; - } - onStateChange?.("failed", `Transport closed (code ${code})`); - }); - } - async function rebuildTransport(fresh, cause) { - connectCause = cause; - flushGate.start(); - try { - const seq = transport.getLastSequenceNum(); - transport.close(); - transport = await createV2ReplTransport({ - sessionUrl: buildCCRv2SdkUrl(fresh.api_base_url, sessionId), - ingressToken: fresh.worker_jwt, - sessionId, - epoch: fresh.worker_epoch, - heartbeatIntervalMs: cfg.heartbeat_interval_ms, - heartbeatJitterFraction: cfg.heartbeat_jitter_fraction, - initialSequenceNum: seq, - getAuthToken: () => fresh.worker_jwt, - outboundOnly - }); - if (tornDown) { - transport.close(); - return; - } - wireTransportCallbacks(); - transport.connect(); - connectDeadline = setTimeout(onConnectTimeout, cfg.connect_timeout_ms, connectCause); - refresh.scheduleFromExpiresIn(sessionId, fresh.expires_in); - drainFlushGate(); - } finally { - flushGate.drop(); - } - } - async function recoverFromAuthFailure() { - if (authRecoveryInFlight) - return; - authRecoveryInFlight = true; - onStateChange?.("reconnecting", "JWT expired \u2014 refreshing"); - logForDebugging("[remote-bridge] 401 on SSE \u2014 attempting JWT refresh"); - try { - const stale = getAccessToken(); - if (onAuth401) - await onAuth401(stale ?? ""); - const oauthToken = getAccessToken() ?? stale; - if (!oauthToken || tornDown) { - if (!tornDown) { - onStateChange?.("failed", "JWT refresh failed: no OAuth token"); - } - return; - } - const fresh = await withRetry2(() => fetchRemoteCredentials2(sessionId, baseUrl, oauthToken, cfg.http_timeout_ms), "fetchRemoteCredentials (recovery)", cfg); - if (!fresh || tornDown) { - if (!tornDown) { - onStateChange?.("failed", "JWT refresh failed after 401"); - } - return; - } - initialFlushDone = false; - await rebuildTransport(fresh, "auth_401_recovery"); - logForDebugging("[remote-bridge] Transport rebuilt after 401"); - } catch (err2) { - logForDebugging(`[remote-bridge] 401 recovery failed: ${errorMessage(err2)}`, { level: "error" }); - logForDiagnosticsNoPII("error", "bridge_repl_v2_jwt_refresh_failed"); - if (!tornDown) { - onStateChange?.("failed", `JWT refresh failed: ${errorMessage(err2)}`); - } - } finally { - authRecoveryInFlight = false; - } - } - wireTransportCallbacks(); - if (initialMessages && initialMessages.length > 0) { - flushGate.start(); - } - transport.connect(); - connectDeadline = setTimeout(onConnectTimeout, cfg.connect_timeout_ms, connectCause); - function drainFlushGate() { - const msgs = flushGate.end(); - if (msgs.length === 0) - return; - for (const msg of msgs) - recentPostedUUIDs.add(msg.uuid); - const events2 = toSDKMessages2(msgs).map((m4) => ({ - ...m4, - session_id: sessionId - })); - if (msgs.some((m4) => m4.type === "user")) { - transport.reportState("running"); - } - logForDebugging(`[remote-bridge] Drained ${msgs.length} queued message(s) after flush`); - transport.writeBatch(events2); - } - async function flushHistory(msgs) { - const eligible2 = msgs.filter(isEligibleBridgeMessage); - const capped = initialHistoryCap > 0 && eligible2.length > initialHistoryCap ? eligible2.slice(-initialHistoryCap) : eligible2; - if (capped.length < eligible2.length) { - logForDebugging(`[remote-bridge] Capped initial flush: ${eligible2.length} -> ${capped.length} (cap=${initialHistoryCap})`); - } - const events2 = toSDKMessages2(capped).map((m4) => ({ - ...m4, - session_id: sessionId - })); - if (events2.length === 0) - return; - if (eligible2.at(-1)?.type === "user") { - transport.reportState("running"); - } - logForDebugging(`[remote-bridge] Flushing ${events2.length} history events`); - await transport.writeBatch(events2); - } - async function teardown() { - if (tornDown) - return; - tornDown = true; - refresh.cancelAll(); - clearTimeout(connectDeadline); - flushGate.drop(); - transport.reportState("idle"); - transport.write(makeResultMessage(sessionId)); - let token = getAccessToken(); - let status2 = await archiveSession(sessionId, baseUrl, token, orgUUID, cfg.teardown_archive_timeout_ms); - if (status2 === 401 && onAuth401) { - try { - await onAuth401(token ?? ""); - token = getAccessToken(); - status2 = await archiveSession(sessionId, baseUrl, token, orgUUID, cfg.teardown_archive_timeout_ms); - } catch (err2) { - logForDebugging(`[remote-bridge] Teardown 401 retry threw: ${errorMessage(err2)}`, { level: "error" }); - } - } - transport.close(); - const archiveStatus = status2 === "no_token" ? "skipped_no_token" : status2 === "timeout" || status2 === "error" ? "network_error" : status2 >= 500 ? "server_5xx" : status2 >= 400 ? "server_4xx" : "ok"; - logForDebugging(`[remote-bridge] Torn down (archive=${status2})`); - logForDiagnosticsNoPII("info", "bridge_repl_v2_teardown"); - logEvent("tengu_bridge_repl_teardown", { - v2: true, - archive_status: archiveStatus, - archive_ok: typeof status2 === "number" && status2 < 400, - archive_http_status: typeof status2 === "number" ? status2 : undefined, - archive_timeout: status2 === "timeout", - archive_no_token: status2 === "no_token" - }); - } - const unregister = registerCleanup(teardown); - if (false) {} else { - logEvent("tengu_bridge_repl_started", { - has_initial_messages: !!(initialMessages && initialMessages.length > 0), - v2: true, - expires_in_s: credentials.expires_in, - inProtectedNamespace: isInProtectedNamespace2() - }); - } - return { - bridgeSessionId: sessionId, - environmentId: "", - sessionIngressUrl: credentials.api_base_url, - writeMessages(messages) { - const filtered = messages.filter((m4) => isEligibleBridgeMessage(m4) && !initialMessageUUIDs.has(m4.uuid) && !recentPostedUUIDs.has(m4.uuid)); - if (filtered.length === 0) - return; - if (!userMessageCallbackDone) { - for (const m4 of filtered) { - const text = extractTitleText(m4); - if (text !== undefined && onUserMessage?.(text, sessionId)) { - userMessageCallbackDone = true; - break; - } - } - } - if (flushGate.enqueue(...filtered)) { - logForDebugging(`[remote-bridge] Queued ${filtered.length} message(s) during flush`); - return; - } - for (const msg of filtered) - recentPostedUUIDs.add(msg.uuid); - const events2 = toSDKMessages2(filtered).map((m4) => ({ - ...m4, - session_id: sessionId - })); - if (filtered.some((m4) => m4.type === "user")) { - transport.reportState("running"); - } - logForDebugging(`[remote-bridge] Sending ${filtered.length} message(s)`); - transport.writeBatch(events2); - }, - writeSdkMessages(messages) { - const filtered = messages.filter((m4) => !m4.uuid || !recentPostedUUIDs.has(m4.uuid)); - if (filtered.length === 0) - return; - for (const msg of filtered) { - if (msg.uuid) - recentPostedUUIDs.add(msg.uuid); - } - const events2 = filtered.map((m4) => ({ ...m4, session_id: sessionId })); - transport.writeBatch(events2); - }, - sendControlRequest(request2) { - if (authRecoveryInFlight) { - logForDebugging(`[remote-bridge] Dropping control_request during 401 recovery: ${request2.request_id}`); - return; - } - const event = { ...request2, session_id: sessionId }; - if (request2.request.subtype === "can_use_tool") { - transport.reportState("requires_action"); - } - transport.write(event); - logForDebugging(`[remote-bridge] Sent control_request request_id=${request2.request_id}`); - }, - sendControlResponse(response7) { - if (authRecoveryInFlight) { - logForDebugging("[remote-bridge] Dropping control_response during 401 recovery"); - return; - } - const event = { ...response7, session_id: sessionId }; - transport.reportState("running"); - transport.write(event); - logForDebugging("[remote-bridge] Sent control_response"); - }, - sendControlCancelRequest(requestId) { - if (authRecoveryInFlight) { - logForDebugging(`[remote-bridge] Dropping control_cancel_request during 401 recovery: ${requestId}`); - return; - } - const event = { - type: "control_cancel_request", - request_id: requestId, - session_id: sessionId - }; - transport.reportState("running"); - transport.write(event); - logForDebugging(`[remote-bridge] Sent control_cancel_request request_id=${requestId}`); - }, - sendResult() { - if (authRecoveryInFlight) { - logForDebugging("[remote-bridge] Dropping result during 401 recovery"); - return; - } - transport.reportState("idle"); - transport.write(makeResultMessage(sessionId)); - logForDebugging(`[remote-bridge] Sent result`); - }, - async teardown() { - unregister(); - await teardown(); - } - }; -} -async function withRetry2(fn, label, cfg) { - const max2 = cfg.init_retry_max_attempts; - for (let attempt = 1;attempt <= max2; attempt++) { - const result = await fn(); - if (result !== null) - return result; - if (attempt < max2) { - const base2 = cfg.init_retry_base_delay_ms * 2 ** (attempt - 1); - const jitter = base2 * cfg.init_retry_jitter_fraction * (2 * Math.random() - 1); - const delay4 = Math.min(base2 + jitter, cfg.init_retry_max_delay_ms); - logForDebugging(`[remote-bridge] ${label} failed (attempt ${attempt}/${max2}), retrying in ${Math.round(delay4)}ms`); - await sleep6(delay4); - } - } - return null; -} -async function fetchRemoteCredentials2(sessionId, baseUrl, accessToken, timeoutMs) { - const creds = await fetchRemoteCredentials(sessionId, baseUrl, accessToken, timeoutMs, getTrustedDeviceToken()); - if (!creds) - return null; - return getBridgeBaseUrlOverride() ? { ...creds, api_base_url: baseUrl } : creds; -} -async function archiveSession(sessionId, baseUrl, accessToken, orgUUID, timeoutMs) { - if (!accessToken) - return "no_token"; - const compatId = toCompatSessionId(sessionId); - try { - const response7 = await axios_default.post(`${baseUrl}/v1/sessions/${compatId}/archive`, {}, { - headers: { - ...oauthHeaders2(accessToken), - "anthropic-beta": "ccr-byoc-2025-07-29", - "x-organization-uuid": orgUUID - }, - timeout: timeoutMs, - validateStatus: () => true - }); - logForDebugging(`[remote-bridge] Archive ${compatId} status=${response7.status}`); - return response7.status; - } catch (err2) { - const msg = errorMessage(err2); - logForDebugging(`[remote-bridge] Archive failed: ${msg}`); - return axios_default.isAxiosError(err2) && err2.code === "ECONNABORTED" ? "timeout" : "error"; - } -} -var ANTHROPIC_VERSION3 = "2023-06-01"; -var init_remoteBridgeCore = __esm(() => { - init_axios2(); - init_replBridgeTransport(); - init_workSecret(); - init_jwtUtils(); - init_trustedDevice(); - init_envLessBridgeConfig(); - init_bridgeMessaging(); - init_debugUtils(); - init_debug(); - init_diagLogs(); - init_envUtils(); - init_errors(); - init_cleanupRegistry(); - init_analytics(); - init_codeSessionApi(); - init_codeSessionApi(); - init_bridgeConfig(); -}); - -// src/bridge/initReplBridge.ts -var exports_initReplBridge = {}; -__export(exports_initReplBridge, { - initReplBridge: () => initReplBridge -}); -import { hostname as hostname3 } from "os"; -async function initReplBridge(options2) { - const { - onInboundMessage, - onPermissionResponse, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode, - onStateChange, - initialMessages, - getMessages, - previouslyFlushedUUIDs, - initialName, - perpetual, - outboundOnly, - tags - } = options2 ?? {}; - setCseShimGate(isCseShimEnabled); - if (!await isBridgeEnabledBlocking()) { - logBridgeSkip("not_enabled", "[bridge:repl] Skipping: bridge not enabled"); - return null; - } - if (!getBridgeAccessToken()) { - logBridgeSkip("no_oauth", "[bridge:repl] Skipping: no OAuth tokens"); - onStateChange?.("failed", "/login"); - return null; - } - await waitForPolicyLimitsToLoad(); - if (!isPolicyAllowed("allow_remote_control")) { - logBridgeSkip("policy_denied", "[bridge:repl] Skipping: allow_remote_control policy not allowed"); - onStateChange?.("failed", "disabled by your organization's policy"); - return null; - } - if (!getBridgeTokenOverride()) { - const cfg = getGlobalConfig(); - if (cfg.bridgeOauthDeadExpiresAt != null && (cfg.bridgeOauthDeadFailCount ?? 0) >= 3 && getClaudeAIOAuthTokens()?.expiresAt === cfg.bridgeOauthDeadExpiresAt) { - logForDebugging(`[bridge:repl] Skipping: cross-process backoff (dead token seen ${cfg.bridgeOauthDeadFailCount} times)`); - return null; - } - await checkAndRefreshOAuthTokenIfNeeded(); - const tokens = getClaudeAIOAuthTokens(); - if (tokens && tokens.expiresAt !== null && tokens.expiresAt <= Date.now()) { - logBridgeSkip("oauth_expired_unrefreshable", "[bridge:repl] Skipping: OAuth token expired and refresh failed (re-login required)"); - onStateChange?.("failed", "/login"); - const deadExpiresAt = tokens.expiresAt; - saveGlobalConfig((c9) => ({ - ...c9, - bridgeOauthDeadExpiresAt: deadExpiresAt, - bridgeOauthDeadFailCount: c9.bridgeOauthDeadExpiresAt === deadExpiresAt ? (c9.bridgeOauthDeadFailCount ?? 0) + 1 : 1 - })); - return null; - } - } - const baseUrl = getBridgeBaseUrl(); - let title = `remote-control-${generateShortWordSlug()}`; - let hasTitle = false; - let hasExplicitTitle = false; - if (initialName) { - title = initialName; - hasTitle = true; - hasExplicitTitle = true; - } else { - const sessionId = getSessionId(); - const customTitle = sessionId ? getCurrentSessionTitle(sessionId) : undefined; - if (customTitle) { - title = customTitle; - hasTitle = true; - hasExplicitTitle = true; - } else if (initialMessages && initialMessages.length > 0) { - for (let i6 = initialMessages.length - 1;i6 >= 0; i6--) { - const msg = initialMessages[i6]; - if (msg.type !== "user" || msg.isMeta || msg.toolUseResult || msg.isCompactSummary || msg.origin && msg.origin.kind !== "human" || isSyntheticMessage(msg)) - continue; - const rawContent2 = getContentText(msg.message.content); - if (!rawContent2) - continue; - const derived = deriveTitle(rawContent2); - if (!derived) - continue; - title = derived; - hasTitle = true; - break; - } - } - } - let userMessageCount = 0; - let lastBridgeSessionId; - let genSeq = 0; - const patch2 = (derived, bridgeSessionId, atCount) => { - hasTitle = true; - title = derived; - logForDebugging(`[bridge:repl] derived title from message ${atCount}: ${derived}`); - updateBridgeSessionTitle(bridgeSessionId, derived, { - baseUrl, - getAccessToken: getBridgeAccessToken - }).catch(() => {}); - }; - const generateAndPatch = (input, bridgeSessionId) => { - const gen = ++genSeq; - const atCount = userMessageCount; - generateSessionTitle(input, AbortSignal.timeout(15000)).then((generated) => { - if (generated && gen === genSeq && lastBridgeSessionId === bridgeSessionId && !getCurrentSessionTitle(getSessionId())) { - patch2(generated, bridgeSessionId, atCount); - } - }); - }; - const onUserMessage = (text, bridgeSessionId) => { - if (hasExplicitTitle || getCurrentSessionTitle(getSessionId())) { - return true; - } - if (lastBridgeSessionId !== undefined && lastBridgeSessionId !== bridgeSessionId) { - userMessageCount = 0; - } - lastBridgeSessionId = bridgeSessionId; - userMessageCount++; - if (userMessageCount === 1 && !hasTitle) { - const placeholder = deriveTitle(text); - if (placeholder) - patch2(placeholder, bridgeSessionId, userMessageCount); - generateAndPatch(text, bridgeSessionId); - } else if (userMessageCount === 3) { - const msgs = getMessages?.(); - const input = msgs ? extractConversationText(getMessagesAfterCompactBoundary(msgs)) : text; - generateAndPatch(input, bridgeSessionId); - } - return userMessageCount >= 3; - }; - const initialHistoryCap = getFeatureValue_CACHED_WITH_REFRESH("tengu_bridge_initial_history_cap", 200, 5 * 60 * 1000); - const orgUUID = await getOrganizationUUID(); - if (!orgUUID) { - logBridgeSkip("no_org_uuid", "[bridge:repl] Skipping: no org UUID"); - onStateChange?.("failed", "/login"); - return null; - } - if (isEnvLessBridgeEnabled() && !perpetual) { - const versionError2 = await checkEnvLessBridgeMinVersion(); - if (versionError2) { - logBridgeSkip("version_too_old", `[bridge:repl] Skipping: ${versionError2}`, true); - onStateChange?.("failed", "run `claude update` to upgrade"); - return null; - } - logForDebugging("[bridge:repl] Using env-less bridge path (tengu_bridge_repl_v2)"); - const { initEnvLessBridgeCore: initEnvLessBridgeCore2 } = await Promise.resolve().then(() => (init_remoteBridgeCore(), exports_remoteBridgeCore)); - return initEnvLessBridgeCore2({ - baseUrl, - orgUUID, - title, - getAccessToken: getBridgeAccessToken, - onAuth401: handleOAuth401Error, - toSDKMessages, - initialHistoryCap, - initialMessages, - onInboundMessage, - onUserMessage, - onPermissionResponse, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode, - onStateChange, - outboundOnly, - tags - }); - } - const versionError = checkBridgeMinVersion(); - if (versionError) { - logBridgeSkip("version_too_old", `[bridge:repl] Skipping: ${versionError}`); - onStateChange?.("failed", "run `claude update` to upgrade"); - return null; - } - const branch2 = await getBranch(); - const gitRepoUrl = await getRemoteUrl(); - const sessionIngressUrl = process.env.USER_TYPE === "ant" && process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL ? process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL : baseUrl; - let workerType = "claude_code"; - if (false) {} - return initBridgeCore({ - dir: getOriginalCwd(), - machineName: hostname3(), - branch: branch2, - gitRepoUrl, - title, - baseUrl, - sessionIngressUrl, - workerType, - getAccessToken: getBridgeAccessToken, - createSession: (opts) => createBridgeSession({ - ...opts, - events: [], - baseUrl, - getAccessToken: getBridgeAccessToken - }), - archiveSession: (sessionId) => archiveBridgeSession(sessionId, { - baseUrl, - getAccessToken: getBridgeAccessToken, - timeoutMs: 1500 - }).catch((err2) => { - logForDebugging(`[bridge:repl] archiveBridgeSession threw: ${errorMessage(err2)}`, { level: "error" }); - }), - getCurrentTitle: () => getCurrentSessionTitle(getSessionId()) ?? title, - onUserMessage, - toSDKMessages, - onAuth401: handleOAuth401Error, - getPollIntervalConfig, - initialHistoryCap, - initialMessages, - previouslyFlushedUUIDs, - onInboundMessage, - onPermissionResponse, - onInterrupt, - onSetModel, - onSetMaxThinkingTokens, - onSetPermissionMode, - onStateChange, - perpetual - }); -} -function deriveTitle(raw) { - const clean = stripDisplayTagsAllowEmpty(raw); - const firstSentence = /^(.*?[.!?])\s/.exec(clean)?.[1] ?? clean; - const flat = firstSentence.replace(/\s+/g, " ").trim(); - if (!flat) - return; - return flat.length > TITLE_MAX_LEN ? flat.slice(0, TITLE_MAX_LEN - 1) + "\u2026" : flat; -} -var TITLE_MAX_LEN = 50; -var init_initReplBridge = __esm(() => { - init_state(); - init_growthbook(); - init_client7(); - init_policyLimits(); - init_auth14(); - init_config(); - init_debug(); - init_displayTags(); - init_errors(); - init_git(); - init_mappers(); - init_messages9(); - init_sessionStorage(); - init_sessionTitle(); - init_words(); - init_bridgeConfig(); - init_bridgeEnabled(); - init_createSession(); - init_debugUtils(); - init_envLessBridgeConfig(); - init_pollConfig(); - init_replBridge(); -}); - -// src/cli/print.ts -var exports_print = {}; -__export(exports_print, { - runHeadless: () => runHeadless, - removeInterruptedMessage: () => removeInterruptedMessage, - reconcileMcpServers: () => reconcileMcpServers, - joinPromptValues: () => joinPromptValues, - handleOrphanedPermissionResponse: () => handleOrphanedPermissionResponse, - handleMcpSetServers: () => handleMcpSetServers, - getCanUseToolFn: () => getCanUseToolFn, - createCanUseToolWithPermissionPrompt: () => createCanUseToolWithPermissionPrompt, - canBatchWith: () => canBatchWith -}); -import { readFile as readFile58, stat as stat50 } from "fs/promises"; -import { dirname as dirname63 } from "path"; -import { cwd as cwd2 } from "process"; -import { randomUUID as randomUUID55 } from "crypto"; -function trackReceivedMessageUuid(uuid8) { - if (receivedMessageUuids.has(uuid8)) { - return false; - } - receivedMessageUuids.add(uuid8); - receivedMessageUuidsOrder.push(uuid8); - if (receivedMessageUuidsOrder.length > MAX_RECEIVED_UUIDS) { - const toEvict = receivedMessageUuidsOrder.splice(0, receivedMessageUuidsOrder.length - MAX_RECEIVED_UUIDS); - for (const old of toEvict) { - receivedMessageUuids.delete(old); - } - } - return true; -} -function toBlocks(v6) { - return typeof v6 === "string" ? [{ type: "text", text: v6 }] : v6; -} -function joinPromptValues(values3) { - if (values3.length === 1) - return values3[0]; - if (values3.every((v6) => typeof v6 === "string")) { - return values3.join(` -`); - } - return values3.flatMap(toBlocks); -} -function canBatchWith(head, next2) { - return next2 !== undefined && next2.mode === "prompt" && next2.workload === head.workload && next2.isMeta === head.isMeta; -} -async function runHeadless(inputPrompt, getAppState, setAppState, commands7, tools, sdkMcpConfigs, agents2, options2) { - if (process.env.USER_TYPE === "ant" && isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER)) { - process.stderr.write(` -Startup time: ${Math.round(process.uptime() * 1000)}ms -`); - process.exit(0); - } - if (false) {} - settingsChangeDetector.subscribe((source) => { - applySettingsChange(source, setAppState); - if (isFastModeEnabled()) { - setAppState((prev) => { - const s4 = prev.settings; - const fastMode = s4.fastMode === true && !s4.fastModePerSessionOptIn; - return { ...prev, fastMode }; - }); - } - }); - if (false) {} - if (typeof Bun !== "undefined") { - const gcTimer = setInterval(Bun.gc, 1000); - gcTimer.unref(); - } - headlessProfilerStartTurn(); - headlessProfilerCheckpoint("runHeadless_entry"); - if (await isQualifiedForGrove()) { - await checkGroveForNonInteractive(); - } - headlessProfilerCheckpoint("after_grove_check"); - initializeGrowthBook(); - if (options2.resumeSessionAt && !options2.resume) { - process.stderr.write(`Error: --resume-session-at requires --resume -`); - gracefulShutdownSync(1); - return; - } - if (options2.rewindFiles && !options2.resume) { - process.stderr.write(`Error: --rewind-files requires --resume -`); - gracefulShutdownSync(1); - return; - } - if (options2.rewindFiles && inputPrompt) { - process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt -`); - gracefulShutdownSync(1); - return; - } - const structuredIO = getStructuredIO(inputPrompt, options2); - if (options2.outputFormat === "stream-json") { - installStreamJsonStdoutGuard(); - } - const sandboxUnavailableReason = SandboxManager.getSandboxUnavailableReason(); - if (sandboxUnavailableReason) { - if (SandboxManager.isSandboxRequired()) { - process.stderr.write(` -Error: sandbox required but unavailable: ${sandboxUnavailableReason} -` + ` sandbox.failIfUnavailable is set \u2014 refusing to start without a working sandbox. - -`); - gracefulShutdownSync(1); - return; - } - process.stderr.write(` -\u26A0 Sandbox disabled: ${sandboxUnavailableReason} -` + ` Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced. - -`); - } else if (SandboxManager.isSandboxingEnabled()) { - try { - await SandboxManager.initialize(structuredIO.createSandboxAskCallback()); - } catch (err2) { - process.stderr.write(` -\u274C Sandbox Error: ${errorMessage(err2)} -`); - gracefulShutdownSync(1, "other"); - return; - } - } - if (options2.outputFormat === "stream-json" && options2.verbose) { - registerHookEventHandler((event) => { - const message = (() => { - switch (event.type) { - case "started": - return { - type: "system", - subtype: "hook_started", - hook_id: event.hookId, - hook_name: event.hookName, - hook_event: event.hookEvent, - uuid: randomUUID55(), - session_id: getSessionId() - }; - case "progress": - return { - type: "system", - subtype: "hook_progress", - hook_id: event.hookId, - hook_name: event.hookName, - hook_event: event.hookEvent, - stdout: event.stdout, - stderr: event.stderr, - output: event.output, - uuid: randomUUID55(), - session_id: getSessionId() - }; - case "response": - return { - type: "system", - subtype: "hook_response", - hook_id: event.hookId, - hook_name: event.hookName, - hook_event: event.hookEvent, - output: event.output, - stdout: event.stdout, - stderr: event.stderr, - exit_code: event.exitCode, - outcome: event.outcome, - uuid: randomUUID55(), - session_id: getSessionId() - }; - } - })(); - structuredIO.write(message); - }); - } - if (options2.setupTrigger) { - await processSetupHooks(options2.setupTrigger); - } - headlessProfilerCheckpoint("before_loadInitialMessages"); - const appState = getAppState(); - const { - messages: initialMessages, - turnInterruptionState, - agentSetting: resumedAgentSetting - } = await loadInitialMessages(setAppState, { - continue: options2.continue, - teleport: options2.teleport, - resume: options2.resume, - resumeSessionAt: options2.resumeSessionAt, - forkSession: options2.forkSession, - outputFormat: options2.outputFormat, - sessionStartHooksPromise: options2.sessionStartHooksPromise, - restoredWorkerState: structuredIO.restoredWorkerState - }); - const hookInitialUserMessage = takeInitialUserMessage(); - if (hookInitialUserMessage) { - structuredIO.prependUserMessage(hookInitialUserMessage); - } - if (!options2.agent && !getMainThreadAgentType() && resumedAgentSetting) { - const { agentDefinition: restoredAgent } = restoreAgentFromSession(resumedAgentSetting, undefined, { activeAgents: agents2, allAgents: agents2 }); - if (restoredAgent) { - setAppState((prev) => ({ ...prev, agent: restoredAgent.agentType })); - if (!options2.systemPrompt && !isBuiltInAgent(restoredAgent)) { - const agentSystemPrompt = restoredAgent.getSystemPrompt(); - if (agentSystemPrompt) { - options2.systemPrompt = agentSystemPrompt; - } - } - saveAgentSetting(restoredAgent.agentType); - } - } - if (initialMessages.length === 0 && process.exitCode !== undefined) { - return; - } - if (options2.rewindFiles) { - const targetMessage = initialMessages.find((m4) => m4.uuid === options2.rewindFiles); - if (!targetMessage || targetMessage.type !== "user") { - process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${options2.rewindFiles} is not a user message in this session -`); - gracefulShutdownSync(1); - return; - } - const currentAppState = getAppState(); - const result = await handleRewindFiles(options2.rewindFiles, currentAppState, setAppState, false); - if (!result.canRewind) { - process.stderr.write(`Error: ${result.error || "Unexpected error"} -`); - gracefulShutdownSync(1); - return; - } - process.stdout.write(`Files rewound to state at message ${options2.rewindFiles} -`); - gracefulShutdownSync(0); - return; - } - const hasValidResumeSessionId = typeof options2.resume === "string" && (Boolean(validateUuid2(options2.resume)) || options2.resume.endsWith(".jsonl")); - const isUsingSdkUrl = Boolean(options2.sdkUrl); - if (!inputPrompt && !hasValidResumeSessionId && !isUsingSdkUrl) { - process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print -`); - gracefulShutdownSync(1); - return; - } - if (options2.outputFormat === "stream-json" && !options2.verbose) { - process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose -`); - gracefulShutdownSync(1); - return; - } - const allowedMcpTools = filterToolsByDenyRules(appState.mcp.tools, appState.toolPermissionContext); - let filteredTools = [...tools, ...allowedMcpTools]; - const effectivePermissionPromptToolName = options2.sdkUrl ? "stdio" : options2.permissionPromptToolName; - const onPermissionPrompt = (details) => { - if (false) {} - notifySessionStateChanged("requires_action", details); - }; - const canUseTool = getCanUseToolFn(effectivePermissionPromptToolName, structuredIO, () => getAppState().mcp.tools, onPermissionPrompt); - if (options2.permissionPromptToolName) { - filteredTools = filteredTools.filter((tool) => !toolMatchesName(tool, options2.permissionPromptToolName)); - } - registerProcessOutputErrorHandlers(); - headlessProfilerCheckpoint("after_loadInitialMessages"); - await ensureModelStringsInitialized(); - headlessProfilerCheckpoint("after_modelStrings"); - const needsFullArray = options2.outputFormat === "json" && options2.verbose; - const messages = []; - let lastMessage; - const transformToStreamlined = null; - headlessProfilerCheckpoint("before_runHeadlessStreaming"); - for await (const message of runHeadlessStreaming(structuredIO, appState.mcp.clients, [...commands7, ...appState.mcp.commands], filteredTools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents2, options2, turnInterruptionState)) { - if (transformToStreamlined) { - const transformed = transformToStreamlined(message); - if (transformed) { - await structuredIO.write(transformed); - } - } else if (options2.outputFormat === "stream-json" && options2.verbose) { - await structuredIO.write(message); - } - if (message.type !== "control_response" && message.type !== "control_request" && message.type !== "control_cancel_request" && !(message.type === "system" && (message.subtype === "session_state_changed" || message.subtype === "task_notification" || message.subtype === "task_started" || message.subtype === "task_progress" || message.subtype === "post_turn_summary")) && message.type !== "stream_event" && message.type !== "keep_alive" && message.type !== "streamlined_text" && message.type !== "streamlined_tool_use_summary" && message.type !== "prompt_suggestion") { - if (needsFullArray) { - messages.push(message); - } - lastMessage = message; - } - } - switch (options2.outputFormat) { - case "json": - if (!lastMessage || lastMessage.type !== "result") { - throw new Error("No messages returned"); - } - if (options2.verbose) { - writeToStdout(jsonStringify(messages) + ` -`); - break; - } - writeToStdout(jsonStringify(lastMessage) + ` -`); - break; - case "stream-json": - break; - default: - if (!lastMessage || lastMessage.type !== "result") { - throw new Error("No messages returned"); - } - switch (lastMessage.subtype) { - case "success": - writeToStdout(lastMessage.result.endsWith(` -`) ? lastMessage.result : lastMessage.result + ` -`); - break; - case "error_during_execution": - writeToStdout(`Execution error`); - break; - case "error_max_turns": - writeToStdout(`Error: Reached max turns (${options2.maxTurns})`); - break; - case "error_max_budget_usd": - writeToStdout(`Error: Exceeded USD budget (${options2.maxBudgetUsd})`); - break; - case "error_max_structured_output_retries": - writeToStdout(`Error: Failed to provide valid structured output after maximum retries`); - } - } - logHeadlessProfilerTurn(); - if (false) {} - gracefulShutdownSync(lastMessage?.type === "result" && lastMessage?.is_error ? 1 : 0); -} -function runHeadlessStreaming(structuredIO, mcpClients, commands7, tools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents2, options2, turnInterruptionState) { - let running = false; - let runPhase; - let inputClosed = false; - let shutdownPromptInjected = false; - let heldBackResult = null; - let abortController; - const output = structuredIO.outbound; - const sigintHandler = () => { - logForDiagnosticsNoPII("info", "shutdown_signal", { signal: "SIGINT" }); - if (abortController && !abortController.signal.aborted) { - abortController.abort(); - } - gracefulShutdown(0); - }; - process.on("SIGINT", sigintHandler); - registerCleanup(async () => { - const bg = {}; - for (const t4 of getRunningTasks(getAppState())) { - if (isBackgroundTask(t4)) - bg[t4.type] = (bg[t4.type] ?? 0) + 1; - } - logForDiagnosticsNoPII("info", "run_state_at_shutdown", { - run_active: running, - run_phase: runPhase, - worker_status: getSessionState(), - internal_events_pending: structuredIO.internalEventsPending, - bg_tasks: bg - }); - }); - setPermissionModeChangedListener((newMode) => { - if (newMode === "default" || newMode === "acceptEdits" || newMode === "bypassPermissions" || newMode === "plan" || newMode === false || newMode === "dontAsk") { - output.enqueue({ - type: "system", - subtype: "status", - status: null, - permissionMode: newMode, - uuid: randomUUID55(), - session_id: getSessionId() - }); - } - }); - const suggestionState = { - abortController: null, - inflightPromise: null, - lastEmitted: null, - pendingSuggestion: null, - pendingLastEmittedEntry: null - }; - let unsubscribeAuthStatus; - if (options2.enableAuthStatus) { - const authStatusManager = AwsAuthStatusManager.getInstance(); - unsubscribeAuthStatus = authStatusManager.subscribe((status2) => { - output.enqueue({ - type: "auth_status", - isAuthenticating: status2.isAuthenticating, - output: status2.output, - error: status2.error, - uuid: randomUUID55(), - session_id: getSessionId() - }); - }); - } - const rateLimitListener = (limits) => { - const rateLimitInfo = toSDKRateLimitInfo(limits); - if (rateLimitInfo) { - output.enqueue({ - type: "rate_limit_event", - rate_limit_info: rateLimitInfo, - uuid: randomUUID55(), - session_id: getSessionId() - }); - } - }; - statusListeners.add(rateLimitListener); - const mutableMessages = initialMessages; - let readFileState = extractReadFilesFromMessages(initialMessages, cwd2(), READ_FILE_STATE_CACHE_SIZE); - const pendingSeeds = createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE); - const resumeInterruptedTurnEnv = process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN; - if (turnInterruptionState && turnInterruptionState.kind !== "none" && resumeInterruptedTurnEnv) { - logForDebugging(`[print.ts] Auto-resuming interrupted turn (kind: ${turnInterruptionState.kind})`); - removeInterruptedMessage(mutableMessages, turnInterruptionState.message); - enqueue({ - mode: "prompt", - value: turnInterruptionState.message.message.content, - uuid: randomUUID55() - }); - } - const modelOptions = getModelOptions(); - const modelInfos = modelOptions.map((option) => { - const modelId = option.value === null ? "default" : option.value; - const resolvedModel = modelId === "default" ? getDefaultMainLoopModel() : parseUserSpecifiedModel(modelId); - const hasEffort = modelSupportsEffort(resolvedModel); - const hasAdaptiveThinking = modelSupportsAdaptiveThinking(resolvedModel); - const hasFastMode = isFastModeSupportedByModel(option.value); - const hasAutoMode = modelSupportsAutoMode(resolvedModel); - return { - value: modelId, - displayName: option.label, - description: option.description, - ...hasEffort && { - supportsEffort: true, - supportedEffortLevels: modelSupportsMaxEffort(resolvedModel) ? [...EFFORT_LEVELS] : EFFORT_LEVELS.filter((l4) => l4 !== "max") - }, - ...hasAdaptiveThinking && { supportsAdaptiveThinking: true }, - ...hasFastMode && { supportsFastMode: true }, - ...hasAutoMode && { supportsAutoMode: true } - }; - }); - let activeUserSpecifiedModel = options2.userSpecifiedModel; - function injectModelSwitchBreadcrumbs(modelArg, resolvedModel) { - const breadcrumbs = createModelSwitchBreadcrumbs(modelArg, modelDisplayString(resolvedModel)); - mutableMessages.push(...breadcrumbs); - for (const crumb of breadcrumbs) { - if (typeof crumb.message.content === "string" && crumb.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`)) { - output.enqueue({ - type: "user", - message: crumb.message, - session_id: getSessionId(), - parent_tool_use_id: null, - uuid: crumb.uuid, - timestamp: crumb.timestamp, - isReplay: true - }); - } - } - } - let sdkClients = []; - let sdkTools = []; - const elicitationRegistered = new Set; - function registerElicitationHandlers(clients) { - for (const connection7 of clients) { - if (connection7.type !== "connected" || elicitationRegistered.has(connection7.name)) { - continue; - } - if (connection7.config.type === "sdk") { - continue; - } - const serverName = connection7.name; - try { - connection7.client.setRequestHandler(ElicitRequestSchema, async (request2, extra) => { - logMCPDebug(serverName, `Elicitation request received in print mode: ${jsonStringify(request2)}`); - const mode = request2.params.mode === "url" ? "url" : "form"; - logEvent("tengu_mcp_elicitation_shown", { - mode - }); - const hookResponse = await runElicitationHooks(serverName, request2.params, extra.signal); - if (hookResponse) { - logMCPDebug(serverName, `Elicitation resolved by hook: ${jsonStringify(hookResponse)}`); - logEvent("tengu_mcp_elicitation_response", { - mode, - action: hookResponse.action - }); - return hookResponse; - } - const url3 = "url" in request2.params ? request2.params.url : undefined; - const requestedSchema = "requestedSchema" in request2.params ? request2.params.requestedSchema : undefined; - const elicitationId = "elicitationId" in request2.params ? request2.params.elicitationId : undefined; - const rawResult = await structuredIO.handleElicitation(serverName, request2.params.message, requestedSchema, extra.signal, mode, url3, elicitationId); - const result = await runElicitationResultHooks(serverName, rawResult, extra.signal, mode, elicitationId); - logEvent("tengu_mcp_elicitation_response", { - mode, - action: result.action - }); - return result; - }); - connection7.client.setNotificationHandler(ElicitationCompleteNotificationSchema, (notification) => { - const { elicitationId } = notification.params; - logMCPDebug(serverName, `Elicitation completion notification: ${elicitationId}`); - executeNotificationHooks({ - message: `MCP server "${serverName}" confirmed elicitation ${elicitationId} complete`, - notificationType: "elicitation_complete" - }); - output.enqueue({ - type: "system", - subtype: "elicitation_complete", - mcp_server_name: serverName, - elicitation_id: elicitationId, - uuid: randomUUID55(), - session_id: getSessionId() - }); - }); - elicitationRegistered.add(serverName); - } catch {} - } - } - async function updateSdkMcp() { - const currentServerNames = new Set(Object.keys(sdkMcpConfigs)); - const connectedServerNames = new Set(sdkClients.map((c9) => c9.name)); - const hasNewServers = Array.from(currentServerNames).some((name3) => !connectedServerNames.has(name3)); - const hasRemovedServers = Array.from(connectedServerNames).some((name3) => !currentServerNames.has(name3)); - const hasPendingSdkClients = sdkClients.some((c9) => c9.type === "pending"); - const hasFailedSdkClients = sdkClients.some((c9) => c9.type === "failed"); - const haveServersChanged = hasNewServers || hasRemovedServers || hasPendingSdkClients || hasFailedSdkClients; - if (haveServersChanged) { - for (const client16 of sdkClients) { - if (!currentServerNames.has(client16.name)) { - if (client16.type === "connected") { - await client16.cleanup(); - } - } - } - const sdkSetup = await setupSdkMcpClients(sdkMcpConfigs, (serverName, message) => structuredIO.sendMcpMessage(serverName, message)); - sdkClients = sdkSetup.clients; - sdkTools = sdkSetup.tools; - const allSdkNames = uniq([...connectedServerNames, ...currentServerNames]); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - tools: [ - ...prev.mcp.tools.filter((t4) => !allSdkNames.some((name3) => t4.name.startsWith(getMcpPrefix(name3)))), - ...sdkTools - ] - } - })); - setupVscodeSdkMcp(sdkClients); - } - } - updateSdkMcp(); - let dynamicMcpState = { - clients: [], - tools: [], - configs: {} - }; - const buildAllTools = (appState) => { - const assembledTools = assembleToolPool(appState.toolPermissionContext, appState.mcp.tools); - let allTools = uniqBy_default(mergeAndFilterTools([...tools, ...sdkTools, ...dynamicMcpState.tools], assembledTools, appState.toolPermissionContext.mode), "name"); - if (options2.permissionPromptToolName) { - allTools = allTools.filter((tool) => !toolMatchesName(tool, options2.permissionPromptToolName)); - } - const initJsonSchema = getInitJsonSchema(); - if (initJsonSchema && !options2.jsonSchema) { - const syntheticOutputResult = createSyntheticOutputTool(initJsonSchema); - if ("tool" in syntheticOutputResult) { - allTools = [...allTools, syntheticOutputResult.tool]; - } - } - return allTools; - }; - let bridgeHandle = null; - let bridgeLastForwardedIndex = 0; - function forwardMessagesToBridge() { - if (!bridgeHandle) - return; - const startIndex = Math.min(bridgeLastForwardedIndex, mutableMessages.length); - const newMessages = mutableMessages.slice(startIndex).filter((m4) => m4.type === "user" || m4.type === "assistant"); - bridgeLastForwardedIndex = mutableMessages.length; - if (newMessages.length > 0) { - bridgeHandle.writeMessages(newMessages); - } - } - let mcpChangesPromise = Promise.resolve({ - response: { - added: [], - removed: [], - errors: {} - }, - sdkServersChanged: false - }); - function applyMcpServerChanges(servers) { - const doWork = async () => { - const oldSdkClientNames = new Set(sdkClients.map((c9) => c9.name)); - const result = await handleMcpSetServers(servers, { configs: sdkMcpConfigs, clients: sdkClients, tools: sdkTools }, dynamicMcpState, setAppState); - for (const key2 of Object.keys(sdkMcpConfigs)) { - delete sdkMcpConfigs[key2]; - } - Object.assign(sdkMcpConfigs, result.newSdkState.configs); - sdkClients = result.newSdkState.clients; - sdkTools = result.newSdkState.tools; - dynamicMcpState = result.newDynamicState; - if (result.sdkServersChanged) { - const newSdkClientNames = new Set(sdkClients.map((c9) => c9.name)); - const allSdkNames = uniq([...oldSdkClientNames, ...newSdkClientNames]); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - tools: [ - ...prev.mcp.tools.filter((t4) => !allSdkNames.some((name3) => t4.name.startsWith(getMcpPrefix(name3)))), - ...sdkTools - ] - } - })); - } - return { - response: result.response, - sdkServersChanged: result.sdkServersChanged - }; - }; - mcpChangesPromise = mcpChangesPromise.then(doWork, doWork); - return mcpChangesPromise; - } - function buildMcpServerStatuses() { - const currentAppState = getAppState(); - const currentMcpClients = currentAppState.mcp.clients; - const allMcpTools = uniqBy_default([...currentAppState.mcp.tools, ...dynamicMcpState.tools], "name"); - const existingNames = new Set([ - ...currentMcpClients.map((c9) => c9.name), - ...sdkClients.map((c9) => c9.name) - ]); - return [ - ...currentMcpClients, - ...sdkClients, - ...dynamicMcpState.clients.filter((c9) => !existingNames.has(c9.name)) - ].map((connection7) => { - let config10; - if (connection7.config.type === "sse" || connection7.config.type === "http") { - config10 = { - type: connection7.config.type, - url: connection7.config.url, - headers: connection7.config.headers, - oauth: connection7.config.oauth - }; - } else if (connection7.config.type === "claudeai-proxy") { - config10 = { - type: "claudeai-proxy", - url: connection7.config.url, - id: connection7.config.id - }; - } else if (connection7.config.type === "stdio" || connection7.config.type === undefined) { - config10 = { - type: "stdio", - command: connection7.config.command, - args: connection7.config.args - }; - } - const serverTools = connection7.type === "connected" ? filterToolsByServer(allMcpTools, connection7.name).map((tool) => ({ - name: tool.mcpInfo?.toolName ?? tool.name, - annotations: { - readOnly: tool.isReadOnly({}) || undefined, - destructive: tool.isDestructive?.({}) || undefined, - openWorld: tool.isOpenWorld?.({}) || undefined - } - })) : undefined; - let capabilities; - if (false) {} - return { - name: connection7.name, - status: connection7.type, - serverInfo: connection7.type === "connected" ? connection7.serverInfo : undefined, - error: connection7.type === "failed" ? connection7.error : undefined, - config: config10, - scope: connection7.config.scope, - tools: serverTools, - capabilities - }; - }); - } - async function installPluginsAndApplyMcpInBackground() { - try { - await Promise.all([ - Promise.resolve(), - withDiagnosticsTiming("headless_managed_settings_wait", () => waitForRemoteManagedSettingsToLoad()) - ]); - const pluginsInstalled = await installPluginsForHeadless(); - if (pluginsInstalled) { - await applyPluginMcpDiff(); - } - } catch (error46) { - logError2(error46); - } - } - let pluginInstallPromise = null; - if (!isBareMode()) { - if (isEnvTruthy(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)) { - pluginInstallPromise = installPluginsAndApplyMcpInBackground(); - } else { - installPluginsAndApplyMcpInBackground(); - } - } - const idleTimeout = createIdleTimeoutManager(() => !running); - let currentCommands = commands7; - let currentAgents = agents2; - async function refreshPluginState() { - const { agentDefinitions: freshAgentDefs } = await refreshActivePlugins(setAppState); - currentCommands = await getCommands(cwd2()); - const sdkAgents = currentAgents.filter((a5) => a5.source === "flagSettings"); - currentAgents = [...freshAgentDefs.allAgents, ...sdkAgents]; - } - async function applyPluginMcpDiff() { - const { servers: newConfigs } = await getAllMcpConfigs(); - const supportedConfigs = {}; - for (const [name3, config10] of Object.entries(newConfigs)) { - const type = config10.type; - if (type === undefined || type === "stdio" || type === "sse" || type === "http" || type === "sdk") { - supportedConfigs[name3] = config10; - } - } - for (const [name3, config10] of Object.entries(sdkMcpConfigs)) { - if (config10.type === "sdk" && !(name3 in supportedConfigs)) { - supportedConfigs[name3] = config10; - } - } - const { response: response7, sdkServersChanged } = await applyMcpServerChanges(supportedConfigs); - if (sdkServersChanged) { - updateSdkMcp(); - } - logForDebugging(`Headless MCP refresh: added=${response7.added.length}, removed=${response7.removed.length}`); - } - const unsubscribeSkillChanges = skillChangeDetector.subscribe(() => { - clearCommandsCache(); - getCommands(cwd2()).then((newCommands) => { - currentCommands = newCommands; - }); - }); - const scheduleProactiveTick = undefined; - subscribeToCommandQueue(() => { - if (abortController && getCommandsByMaxPriority("now").length > 0) { - abortController.abort("interrupt"); - } - }); - const run = async () => { - if (running) { - return; - } - running = true; - runPhase = undefined; - notifySessionStateChanged("running"); - idleTimeout.stop(); - headlessProfilerCheckpoint("run_entry"); - await updateSdkMcp(); - headlessProfilerCheckpoint("after_updateSdkMcp"); - if (pluginInstallPromise) { - const timeoutMs = parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS || "", 10); - if (timeoutMs > 0) { - const timeout2 = sleep6(timeoutMs).then(() => "timeout"); - const result = await Promise.race([pluginInstallPromise, timeout2]); - if (result === "timeout") { - logError2(new Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${timeoutMs}ms`)); - logEvent("tengu_sync_plugin_install_timeout", { - timeout_ms: timeoutMs - }); - } - } else { - await pluginInstallPromise; - } - pluginInstallPromise = null; - await refreshPluginState(); - const { setupPluginHookHotReload: setupPluginHookHotReload2 } = await Promise.resolve().then(() => (init_loadPluginHooks(), exports_loadPluginHooks)); - setupPluginHookHotReload2(); - } - const isMainThread = (cmd) => cmd.agentId === undefined; - try { - let command19; - let waitingForAgents = false; - const drainCommandQueue = async () => { - while (command19 = dequeue(isMainThread)) { - if (command19.mode !== "prompt" && command19.mode !== "orphaned-permission" && command19.mode !== "task-notification") { - throw new Error("only prompt commands are supported in streaming mode"); - } - const batch = [command19]; - if (command19.mode === "prompt") { - while (canBatchWith(command19, peek(isMainThread))) { - batch.push(dequeue(isMainThread)); - } - if (batch.length > 1) { - command19 = { - ...command19, - value: joinPromptValues(batch.map((c9) => c9.value)), - uuid: batch.findLast((c9) => c9.uuid)?.uuid ?? command19.uuid - }; - } - } - const batchUuids = batch.map((c9) => c9.uuid).filter((u5) => u5 !== undefined); - if (options2.replayUserMessages && batch.length > 1) { - for (const c9 of batch) { - if (c9.uuid && c9.uuid !== command19.uuid) { - output.enqueue({ - type: "user", - message: { role: "user", content: c9.value }, - session_id: getSessionId(), - parent_tool_use_id: null, - uuid: c9.uuid, - isReplay: true - }); - } - } - } - const appState = getAppState(); - const allMcpClients = [ - ...appState.mcp.clients, - ...sdkClients, - ...dynamicMcpState.clients - ]; - registerElicitationHandlers(allMcpClients); - for (const client16 of allMcpClients) { - reregisterChannelHandlerAfterReconnect(client16); - } - const allTools = buildAllTools(appState); - for (const uuid8 of batchUuids) { - notifyCommandLifecycle(uuid8, "started"); - } - if (command19.mode === "task-notification") { - const notificationText = typeof command19.value === "string" ? command19.value : ""; - const taskIdMatch = notificationText.match(/([^<]+)<\/task-id>/); - const toolUseIdMatch = notificationText.match(/([^<]+)<\/tool-use-id>/); - const outputFileMatch = notificationText.match(/([^<]+)<\/output-file>/); - const statusMatch = notificationText.match(/([^<]+)<\/status>/); - const summaryMatch = notificationText.match(/([^<]+)<\/summary>/); - const isValidStatus = (s4) => s4 === "completed" || s4 === "failed" || s4 === "stopped" || s4 === "killed"; - const rawStatus = statusMatch?.[1]; - const status2 = isValidStatus(rawStatus) ? rawStatus === "killed" ? "stopped" : rawStatus : "completed"; - const usageMatch = notificationText.match(/([\s\S]*?)<\/usage>/); - const usageContent = usageMatch?.[1] ?? ""; - const totalTokensMatch = usageContent.match(/(\d+)<\/total_tokens>/); - const toolUsesMatch = usageContent.match(/(\d+)<\/tool_uses>/); - const durationMsMatch = usageContent.match(/(\d+)<\/duration_ms>/); - if (statusMatch) { - output.enqueue({ - type: "system", - subtype: "task_notification", - task_id: taskIdMatch?.[1] ?? "", - tool_use_id: toolUseIdMatch?.[1], - status: status2, - output_file: outputFileMatch?.[1] ?? "", - summary: summaryMatch?.[1] ?? "", - usage: totalTokensMatch && toolUsesMatch ? { - total_tokens: parseInt(totalTokensMatch[1], 10), - tool_uses: parseInt(toolUsesMatch[1], 10), - duration_ms: durationMsMatch ? parseInt(durationMsMatch[1], 10) : 0 - } : undefined, - session_id: getSessionId(), - uuid: randomUUID55() - }); - } - } - const input = command19.value; - if (structuredIO instanceof RemoteIO && command19.mode === "prompt") { - logEvent("tengu_bridge_message_received", { - is_repl: false - }); - } - suggestionState.abortController?.abort(); - suggestionState.abortController = null; - suggestionState.pendingSuggestion = null; - suggestionState.pendingLastEmittedEntry = null; - if (suggestionState.lastEmitted) { - if (command19.mode === "prompt") { - const inputText = typeof input === "string" ? input : input.find((b5) => b5.type === "text")?.text; - if (typeof inputText === "string") { - logSuggestionOutcome(suggestionState.lastEmitted.text, inputText, suggestionState.lastEmitted.emittedAt, suggestionState.lastEmitted.promptId, suggestionState.lastEmitted.generationRequestId); - } - suggestionState.lastEmitted = null; - } - } - abortController = createAbortController(); - const turnStartTime = undefined; - headlessProfilerCheckpoint("before_ask"); - startQueryProfile(); - const cmd = command19; - await runWithWorkload(cmd.workload ?? options2.workload, async () => { - for await (const message of ask({ - commands: uniqBy_default([...currentCommands, ...appState.mcp.commands], "name"), - prompt: input, - promptUuid: cmd.uuid, - isMeta: cmd.isMeta, - cwd: cwd2(), - tools: allTools, - verbose: options2.verbose, - mcpClients: allMcpClients, - thinkingConfig: options2.thinkingConfig, - maxTurns: options2.maxTurns, - maxBudgetUsd: options2.maxBudgetUsd, - taskBudget: options2.taskBudget, - canUseTool, - userSpecifiedModel: activeUserSpecifiedModel, - fallbackModel: options2.fallbackModel, - jsonSchema: getInitJsonSchema() ?? options2.jsonSchema, - mutableMessages, - getReadFileCache: () => pendingSeeds.size === 0 ? readFileState : mergeFileStateCaches(readFileState, pendingSeeds), - setReadFileCache: (cache9) => { - readFileState = cache9; - for (const [path27, seed] of pendingSeeds.entries()) { - const existing = readFileState.get(path27); - if (!existing || seed.timestamp > existing.timestamp) { - readFileState.set(path27, seed); - } - } - pendingSeeds.clear(); - }, - customSystemPrompt: options2.systemPrompt, - appendSystemPrompt: options2.appendSystemPrompt, - getAppState, - setAppState, - abortController, - replayUserMessages: options2.replayUserMessages, - includePartialMessages: options2.includePartialMessages, - handleElicitation: (serverName, params, elicitSignal) => structuredIO.handleElicitation(serverName, params.message, undefined, elicitSignal, params.mode, params.url, "elicitationId" in params ? params.elicitationId : undefined), - agents: currentAgents, - orphanedPermission: cmd.orphanedPermission, - setSDKStatus: (status2) => { - output.enqueue({ - type: "system", - subtype: "status", - status: status2, - session_id: getSessionId(), - uuid: randomUUID55() - }); - } - })) { - forwardMessagesToBridge(); - if (message.type === "result") { - for (const event of drainSdkEvents()) { - output.enqueue(event); - } - const currentState2 = getAppState(); - if (getRunningTasks(currentState2).some((t4) => (t4.type === "local_agent" || t4.type === "local_workflow") && isBackgroundTask(t4))) { - heldBackResult = message; - } else { - heldBackResult = null; - output.enqueue(message); - } - } else { - for (const event of drainSdkEvents()) { - output.enqueue(event); - } - output.enqueue(message); - } - } - }); - for (const uuid8 of batchUuids) { - notifyCommandLifecycle(uuid8, "completed"); - } - forwardMessagesToBridge(); - bridgeHandle?.sendResult(); - if (false) {} - if (options2.promptSuggestions && !isEnvDefinedFalsy(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)) { - const state4 = suggestionState; - state4.abortController?.abort(); - const localAbort = new AbortController; - suggestionState.abortController = localAbort; - const cacheSafeParams = getLastCacheSafeParams(); - if (!cacheSafeParams) { - logSuggestionSuppressed("sdk_no_params", undefined, undefined, "sdk"); - } else { - const ref = { promise: null }; - ref.promise = (async () => { - try { - const result = await tryGenerateSuggestion(localAbort, mutableMessages, getAppState, cacheSafeParams, "sdk"); - if (!result || localAbort.signal.aborted) - return; - const suggestionMsg = { - type: "prompt_suggestion", - suggestion: result.suggestion, - uuid: randomUUID55(), - session_id: getSessionId() - }; - const lastEmittedEntry = { - text: result.suggestion, - emittedAt: Date.now(), - promptId: result.promptId, - generationRequestId: result.generationRequestId - }; - if (heldBackResult) { - suggestionState.pendingSuggestion = suggestionMsg; - suggestionState.pendingLastEmittedEntry = { - text: lastEmittedEntry.text, - promptId: lastEmittedEntry.promptId, - generationRequestId: lastEmittedEntry.generationRequestId - }; - } else { - suggestionState.lastEmitted = lastEmittedEntry; - output.enqueue(suggestionMsg); - } - } catch (error46) { - if (error46 instanceof Error && (error46.name === "AbortError" || error46.name === "APIUserAbortError")) { - logSuggestionSuppressed("aborted", undefined, undefined, "sdk"); - return; - } - logError2(toError(error46)); - } finally { - if (suggestionState.inflightPromise === ref.promise) { - suggestionState.inflightPromise = null; - } - } - })(); - suggestionState.inflightPromise = ref.promise; - } - } - logHeadlessProfilerTurn(); - logQueryProfileReport(); - headlessProfilerStartTurn(); - } - }; - do { - for (const event of drainSdkEvents()) { - output.enqueue(event); - } - runPhase = "draining_commands"; - await drainCommandQueue(); - waitingForAgents = false; - { - const state4 = getAppState(); - const hasRunningBg = getRunningTasks(state4).some((t4) => isBackgroundTask(t4) && t4.type !== "in_process_teammate"); - const hasMainThreadQueued = peek(isMainThread) !== undefined; - if (hasRunningBg || hasMainThreadQueued) { - waitingForAgents = true; - if (!hasMainThreadQueued) { - runPhase = "waiting_for_agents"; - await sleep6(100); - } - } - } - } while (waitingForAgents); - if (heldBackResult) { - output.enqueue(heldBackResult); - heldBackResult = null; - if (suggestionState.pendingSuggestion) { - output.enqueue(suggestionState.pendingSuggestion); - if (suggestionState.pendingLastEmittedEntry) { - suggestionState.lastEmitted = { - ...suggestionState.pendingLastEmittedEntry, - emittedAt: Date.now() - }; - suggestionState.pendingLastEmittedEntry = null; - } - suggestionState.pendingSuggestion = null; - } - } - } catch (error46) { - try { - await structuredIO.write({ - type: "result", - subtype: "error_during_execution", - duration_ms: 0, - duration_api_ms: 0, - is_error: true, - num_turns: 0, - stop_reason: null, - session_id: getSessionId(), - total_cost_usd: 0, - usage: EMPTY_USAGE, - modelUsage: {}, - permission_denials: [], - uuid: randomUUID55(), - errors: [ - errorMessage(error46), - ...getInMemoryErrors().map((_) => _.error) - ] - }); - } catch {} - suggestionState.abortController?.abort(); - gracefulShutdownSync(1); - return; - } finally { - runPhase = "finally_flush"; - await structuredIO.flushInternalEvents(); - runPhase = "finally_post_flush"; - if (!isShuttingDown()) { - notifySessionStateChanged("idle"); - for (const event of drainSdkEvents()) { - output.enqueue(event); - } - } - running = false; - idleTimeout.start(); - } - if (false) {} - if (peek(isMainThread) !== undefined) { - run(); - return; - } - { - const currentAppState = getAppState(); - const teamContext = currentAppState.teamContext; - if (teamContext && isTeamLead(teamContext)) { - const agentName = "team-lead"; - const POLL_INTERVAL_MS4 = 500; - while (true) { - const refreshedState = getAppState(); - const hasActiveTeammates = hasActiveInProcessTeammates(refreshedState) || refreshedState.teamContext && Object.keys(refreshedState.teamContext.teammates).length > 0; - if (!hasActiveTeammates) { - logForDebugging("[print.ts] No more active teammates, stopping poll"); - break; - } - const unread = await readUnreadMessages(agentName, refreshedState.teamContext?.teamName); - if (unread.length > 0) { - logForDebugging(`[print.ts] Team-lead found ${unread.length} unread messages`); - await markMessagesAsRead(agentName, refreshedState.teamContext?.teamName); - const teamName = refreshedState.teamContext?.teamName; - for (const m4 of unread) { - const shutdownApproval = isShutdownApproved(m4.text); - if (shutdownApproval && teamName) { - const teammateToRemove = shutdownApproval.from; - logForDebugging(`[print.ts] Processing shutdown_approved from ${teammateToRemove}`); - const teammateId = refreshedState.teamContext?.teammates ? Object.entries(refreshedState.teamContext.teammates).find(([, t4]) => t4.name === teammateToRemove)?.[0] : undefined; - if (teammateId) { - removeTeammateFromTeamFile(teamName, { - agentId: teammateId, - name: teammateToRemove - }); - logForDebugging(`[print.ts] Removed ${teammateToRemove} from team file`); - await unassignTeammateTasks(teamName, teammateId, teammateToRemove, "shutdown"); - setAppState((prev) => { - if (!prev.teamContext?.teammates) - return prev; - if (!(teammateId in prev.teamContext.teammates)) - return prev; - const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates; - return { - ...prev, - teamContext: { - ...prev.teamContext, - teammates: remainingTeammates - } - }; - }); - } - } - } - const formatted = unread.map((m4) => `<${TEAMMATE_MESSAGE_TAG} teammate_id="${m4.from}"${m4.color ? ` color="${m4.color}"` : ""}> -${m4.text} -`).join(` - -`); - enqueue({ - mode: "prompt", - value: formatted, - uuid: randomUUID55() - }); - run(); - return; - } - if (inputClosed && !shutdownPromptInjected) { - shutdownPromptInjected = true; - logForDebugging("[print.ts] Input closed with active teammates, injecting shutdown prompt"); - enqueue({ - mode: "prompt", - value: SHUTDOWN_TEAM_PROMPT, - uuid: randomUUID55() - }); - run(); - return; - } - await sleep6(POLL_INTERVAL_MS4); - } - } - } - if (inputClosed) { - const hasActiveSwarm = await (async () => { - const currentAppState = getAppState(); - if (hasWorkingInProcessTeammates(currentAppState)) { - await waitForTeammatesToBecomeIdle(setAppState, currentAppState); - } - const refreshedAppState = getAppState(); - const refreshedTeamContext = refreshedAppState.teamContext; - const hasTeamMembersNotCleanedUp = refreshedTeamContext && Object.keys(refreshedTeamContext.teammates).length > 0; - return hasTeamMembersNotCleanedUp || hasActiveInProcessTeammates(refreshedAppState); - })(); - if (hasActiveSwarm) { - enqueue({ - mode: "prompt", - value: SHUTDOWN_TEAM_PROMPT, - uuid: randomUUID55() - }); - run(); - } else { - if (suggestionState.inflightPromise) { - await Promise.race([suggestionState.inflightPromise, sleep6(5000)]); - } - suggestionState.abortController?.abort(); - suggestionState.abortController = null; - await finalizePendingAsyncHooks(); - unsubscribeSkillChanges(); - unsubscribeAuthStatus?.(); - statusListeners.delete(rateLimitListener); - output.done(); - } - } - }; - if (false) {} - let cronScheduler = null; - if (false) {} - const sendControlResponseSuccess = function(message, response7) { - output.enqueue({ - type: "control_response", - response: { - subtype: "success", - request_id: message.request_id, - response: response7 - } - }); - }; - const sendControlResponseError = function(message, errorMessage4) { - output.enqueue({ - type: "control_response", - response: { - subtype: "error", - request_id: message.request_id, - error: errorMessage4 - } - }); - }; - const handledOrphanedToolUseIds = new Set; - structuredIO.setUnexpectedResponseCallback(async (message) => { - await handleOrphanedPermissionResponse({ - message, - setAppState, - handledToolUseIds: handledOrphanedToolUseIds, - onEnqueued: () => { - run(); - } - }); - }); - const activeOAuthFlows = new Map; - const oauthCallbackSubmitters = new Map; - const oauthManualCallbackUsed = new Set; - const oauthAuthPromises = new Map; - let claudeOAuth = null; - (async () => { - let initialized5 = false; - logForDiagnosticsNoPII("info", "cli_message_loop_started"); - for await (const message of structuredIO.structuredInput) { - const eventId = "uuid" in message ? message.uuid : undefined; - if (eventId && message.type !== "user" && message.type !== "control_response") { - notifyCommandLifecycle(eventId, "completed"); - } - if (message.type === "control_request") { - if (message.request.subtype === "interrupt") { - if (false) {} - if (abortController) { - abortController.abort(); - } - suggestionState.abortController?.abort(); - suggestionState.abortController = null; - suggestionState.lastEmitted = null; - suggestionState.pendingSuggestion = null; - sendControlResponseSuccess(message); - } else if (message.request.subtype === "end_session") { - logForDebugging(`[print.ts] end_session received, reason=${message.request.reason ?? "unspecified"}`); - if (abortController) { - abortController.abort(); - } - suggestionState.abortController?.abort(); - suggestionState.abortController = null; - suggestionState.lastEmitted = null; - suggestionState.pendingSuggestion = null; - sendControlResponseSuccess(message); - break; - } else if (message.request.subtype === "initialize") { - if (message.request.sdkMcpServers && message.request.sdkMcpServers.length > 0) { - for (const serverName of message.request.sdkMcpServers) { - sdkMcpConfigs[serverName] = { - type: "sdk", - name: serverName - }; - } - } - await handleInitializeRequest(message.request, message.request_id, initialized5, output, commands7, modelInfos, structuredIO, !!options2.enableAuthStatus, options2, agents2, getAppState); - if (message.request.promptSuggestions) { - setAppState((prev) => { - if (prev.promptSuggestionEnabled) - return prev; - return { ...prev, promptSuggestionEnabled: true }; - }); - } - if (message.request.agentProgressSummaries && getFeatureValue_CACHED_MAY_BE_STALE("tengu_slate_prism", true)) { - setSdkAgentProgressSummariesEnabled(true); - } - initialized5 = true; - if (hasCommandsInQueue()) { - run(); - } - } else if (message.request.subtype === "set_permission_mode") { - const m4 = message.request; - setAppState((prev) => ({ - ...prev, - toolPermissionContext: handleSetPermissionMode(m4, message.request_id, prev.toolPermissionContext, output), - isUltraplanMode: m4.ultraplan ?? prev.isUltraplanMode - })); - } else if (message.request.subtype === "set_model") { - const requestedModel = message.request.model ?? "default"; - const model = requestedModel === "default" ? getDefaultMainLoopModel() : requestedModel; - activeUserSpecifiedModel = model; - setMainLoopModelOverride(model); - notifySessionMetadataChanged({ model }); - injectModelSwitchBreadcrumbs(requestedModel, model); - sendControlResponseSuccess(message); - } else if (message.request.subtype === "set_max_thinking_tokens") { - if (message.request.max_thinking_tokens === null) { - options2.thinkingConfig = undefined; - } else if (message.request.max_thinking_tokens === 0) { - options2.thinkingConfig = { type: "disabled" }; - } else { - options2.thinkingConfig = { - type: "enabled", - budgetTokens: message.request.max_thinking_tokens - }; - } - sendControlResponseSuccess(message); - } else if (message.request.subtype === "mcp_status") { - sendControlResponseSuccess(message, { - mcpServers: buildMcpServerStatuses() - }); - } else if (message.request.subtype === "get_context_usage") { - try { - const appState = getAppState(); - const data = await collectContextData({ - messages: mutableMessages, - getAppState, - options: { - mainLoopModel: getMainLoopModel(), - tools: buildAllTools(appState), - agentDefinitions: appState.agentDefinitions, - customSystemPrompt: options2.systemPrompt, - appendSystemPrompt: options2.appendSystemPrompt - } - }); - sendControlResponseSuccess(message, { ...data }); - } catch (error46) { - sendControlResponseError(message, errorMessage(error46)); - } - } else if (message.request.subtype === "mcp_message") { - const mcpRequest = message.request; - const sdkClient = sdkClients.find((client16) => client16.name === mcpRequest.server_name); - if (sdkClient && sdkClient.type === "connected" && sdkClient.client?.transport?.onmessage) { - sdkClient.client.transport.onmessage(mcpRequest.message); - } - sendControlResponseSuccess(message); - } else if (message.request.subtype === "rewind_files") { - const appState = getAppState(); - const result = await handleRewindFiles(message.request.user_message_id, appState, setAppState, message.request.dry_run ?? false); - if (result.canRewind || message.request.dry_run) { - sendControlResponseSuccess(message, result); - } else { - sendControlResponseError(message, result.error ?? "Unexpected error"); - } - } else if (message.request.subtype === "cancel_async_message") { - const targetUuid = message.request.message_uuid; - const removed = dequeueAllMatching((cmd) => cmd.uuid === targetUuid); - sendControlResponseSuccess(message, { - cancelled: removed.length > 0 - }); - } else if (message.request.subtype === "seed_read_state") { - try { - const normalizedPath = expandPath(message.request.path); - const diskMtime = Math.floor((await stat50(normalizedPath)).mtimeMs); - if (diskMtime <= message.request.mtime) { - const raw = await readFile58(normalizedPath, "utf-8"); - const content = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replaceAll(`\r -`, ` -`); - pendingSeeds.set(normalizedPath, { - content, - timestamp: diskMtime, - offset: undefined, - limit: undefined - }); - } - } catch {} - sendControlResponseSuccess(message); - } else if (message.request.subtype === "mcp_set_servers") { - const { response: response7, sdkServersChanged } = await applyMcpServerChanges(message.request.servers); - sendControlResponseSuccess(message, response7); - if (sdkServersChanged) { - updateSdkMcp(); - } - } else if (message.request.subtype === "reload_plugins") { - try { - if (false) {} - const r4 = await refreshActivePlugins(setAppState); - const sdkAgents = currentAgents.filter((a5) => a5.source === "flagSettings"); - currentAgents = [...r4.agentDefinitions.allAgents, ...sdkAgents]; - let plugins = []; - const [cmdsR, mcpR, pluginsR] = await Promise.allSettled([ - getCommands(cwd2()), - applyPluginMcpDiff(), - loadAllPluginsCacheOnly() - ]); - if (cmdsR.status === "fulfilled") { - currentCommands = cmdsR.value; - } else { - logError2(cmdsR.reason); - } - if (mcpR.status === "rejected") { - logError2(mcpR.reason); - } - if (pluginsR.status === "fulfilled") { - plugins = pluginsR.value.enabled.map((p4) => ({ - name: p4.name, - path: p4.path, - source: p4.source - })); - } else { - logError2(pluginsR.reason); - } - sendControlResponseSuccess(message, { - commands: currentCommands.filter((cmd) => cmd.userInvocable !== false).map((cmd) => ({ - name: getCommandName(cmd), - description: formatDescriptionWithSource(cmd), - argumentHint: cmd.argumentHint || "" - })), - agents: currentAgents.map((a5) => ({ - name: a5.agentType, - description: a5.whenToUse, - model: a5.model === "inherit" ? undefined : a5.model - })), - plugins, - mcpServers: buildMcpServerStatuses(), - error_count: r4.error_count - }); - } catch (error46) { - sendControlResponseError(message, errorMessage(error46)); - } - } else if (message.request.subtype === "mcp_reconnect") { - const currentAppState = getAppState(); - const { serverName } = message.request; - elicitationRegistered.delete(serverName); - const config10 = getMcpConfigByName(serverName) ?? mcpClients.find((c9) => c9.name === serverName)?.config ?? sdkClients.find((c9) => c9.name === serverName)?.config ?? dynamicMcpState.clients.find((c9) => c9.name === serverName)?.config ?? currentAppState.mcp.clients.find((c9) => c9.name === serverName)?.config ?? null; - if (!config10) { - sendControlResponseError(message, `Server not found: ${serverName}`); - } else { - const result = await reconnectMcpServerImpl(serverName, config10); - const prefix = getMcpPrefix(serverName); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: prev.mcp.clients.map((c9) => c9.name === serverName ? result.client : c9), - tools: [ - ...reject_default(prev.mcp.tools, (t4) => t4.name?.startsWith(prefix)), - ...result.tools - ], - commands: [ - ...reject_default(prev.mcp.commands, (c9) => commandBelongsToServer(c9, serverName)), - ...result.commands - ], - resources: result.resources && result.resources.length > 0 ? { ...prev.mcp.resources, [serverName]: result.resources } : omit_default(prev.mcp.resources, serverName) - } - })); - dynamicMcpState = { - ...dynamicMcpState, - clients: [ - ...dynamicMcpState.clients.filter((c9) => c9.name !== serverName), - result.client - ], - tools: [ - ...dynamicMcpState.tools.filter((t4) => !t4.name?.startsWith(prefix)), - ...result.tools - ] - }; - if (result.client.type === "connected") { - registerElicitationHandlers([result.client]); - reregisterChannelHandlerAfterReconnect(result.client); - sendControlResponseSuccess(message); - } else { - const errorMessage4 = result.client.type === "failed" ? result.client.error ?? "Connection failed" : `Server status: ${result.client.type}`; - sendControlResponseError(message, errorMessage4); - } - } - } else if (message.request.subtype === "mcp_toggle") { - const currentAppState = getAppState(); - const { serverName, enabled: enabled2 } = message.request; - elicitationRegistered.delete(serverName); - const config10 = getMcpConfigByName(serverName) ?? mcpClients.find((c9) => c9.name === serverName)?.config ?? sdkClients.find((c9) => c9.name === serverName)?.config ?? dynamicMcpState.clients.find((c9) => c9.name === serverName)?.config ?? currentAppState.mcp.clients.find((c9) => c9.name === serverName)?.config ?? null; - if (!config10) { - sendControlResponseError(message, `Server not found: ${serverName}`); - } else if (!enabled2) { - setMcpServerEnabled(serverName, false); - const client16 = [ - ...mcpClients, - ...sdkClients, - ...dynamicMcpState.clients, - ...currentAppState.mcp.clients - ].find((c9) => c9.name === serverName); - if (client16 && client16.type === "connected") { - await clearServerCache(serverName, config10); - } - const prefix = getMcpPrefix(serverName); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: prev.mcp.clients.map((c9) => c9.name === serverName ? { name: serverName, type: "disabled", config: config10 } : c9), - tools: reject_default(prev.mcp.tools, (t4) => t4.name?.startsWith(prefix)), - commands: reject_default(prev.mcp.commands, (c9) => commandBelongsToServer(c9, serverName)), - resources: omit_default(prev.mcp.resources, serverName) - } - })); - sendControlResponseSuccess(message); - } else { - setMcpServerEnabled(serverName, true); - const result = await reconnectMcpServerImpl(serverName, config10); - const prefix = getMcpPrefix(serverName); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: prev.mcp.clients.map((c9) => c9.name === serverName ? result.client : c9), - tools: [ - ...reject_default(prev.mcp.tools, (t4) => t4.name?.startsWith(prefix)), - ...result.tools - ], - commands: [ - ...reject_default(prev.mcp.commands, (c9) => commandBelongsToServer(c9, serverName)), - ...result.commands - ], - resources: result.resources && result.resources.length > 0 ? { ...prev.mcp.resources, [serverName]: result.resources } : omit_default(prev.mcp.resources, serverName) - } - })); - if (result.client.type === "connected") { - registerElicitationHandlers([result.client]); - reregisterChannelHandlerAfterReconnect(result.client); - sendControlResponseSuccess(message); - } else { - const errorMessage4 = result.client.type === "failed" ? result.client.error ?? "Connection failed" : `Server status: ${result.client.type}`; - sendControlResponseError(message, errorMessage4); - } - } - } else if (message.request.subtype === "channel_enable") { - const currentAppState = getAppState(); - handleChannelEnable(message.request_id, message.request.serverName, [ - ...currentAppState.mcp.clients, - ...sdkClients, - ...dynamicMcpState.clients - ], output); - } else if (message.request.subtype === "mcp_authenticate") { - const { serverName } = message.request; - const currentAppState = getAppState(); - const config10 = getMcpConfigByName(serverName) ?? mcpClients.find((c9) => c9.name === serverName)?.config ?? currentAppState.mcp.clients.find((c9) => c9.name === serverName)?.config ?? null; - if (!config10) { - sendControlResponseError(message, `Server not found: ${serverName}`); - } else if (config10.type !== "sse" && config10.type !== "http") { - sendControlResponseError(message, `Server type "${config10.type}" does not support OAuth authentication`); - } else { - try { - activeOAuthFlows.get(serverName)?.abort(); - const controller = new AbortController; - activeOAuthFlows.set(serverName, controller); - let resolveAuthUrl; - const authUrlPromise = new Promise((resolve44) => { - resolveAuthUrl = resolve44; - }); - const oauthPromise = performMCPOAuthFlow(serverName, config10, (url3) => resolveAuthUrl(url3), controller.signal, { - skipBrowserOpen: true, - onWaitingForCallback: (submit) => { - oauthCallbackSubmitters.set(serverName, submit); - } - }); - const authUrl = await Promise.race([ - authUrlPromise, - oauthPromise.then(() => null) - ]); - if (authUrl) { - sendControlResponseSuccess(message, { - authUrl, - requiresUserAction: true - }); - } else { - sendControlResponseSuccess(message, { - requiresUserAction: false - }); - } - oauthAuthPromises.set(serverName, oauthPromise); - const fullFlowPromise = oauthPromise.then(async () => { - if (isMcpServerDisabled(serverName)) { - return; - } - if (oauthManualCallbackUsed.has(serverName)) { - return; - } - const result = await reconnectMcpServerImpl(serverName, config10); - const prefix = getMcpPrefix(serverName); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: prev.mcp.clients.map((c9) => c9.name === serverName ? result.client : c9), - tools: [ - ...reject_default(prev.mcp.tools, (t4) => t4.name?.startsWith(prefix)), - ...result.tools - ], - commands: [ - ...reject_default(prev.mcp.commands, (c9) => commandBelongsToServer(c9, serverName)), - ...result.commands - ], - resources: result.resources && result.resources.length > 0 ? { - ...prev.mcp.resources, - [serverName]: result.resources - } : omit_default(prev.mcp.resources, serverName) - } - })); - dynamicMcpState = { - ...dynamicMcpState, - clients: [ - ...dynamicMcpState.clients.filter((c9) => c9.name !== serverName), - result.client - ], - tools: [ - ...dynamicMcpState.tools.filter((t4) => !t4.name?.startsWith(prefix)), - ...result.tools - ] - }; - }).catch((error46) => { - logForDebugging(`MCP OAuth failed for ${serverName}: ${error46}`, { level: "error" }); - }).finally(() => { - if (activeOAuthFlows.get(serverName) === controller) { - activeOAuthFlows.delete(serverName); - oauthCallbackSubmitters.delete(serverName); - oauthManualCallbackUsed.delete(serverName); - oauthAuthPromises.delete(serverName); - } - }); - } catch (error46) { - sendControlResponseError(message, errorMessage(error46)); - } - } - } else if (message.request.subtype === "mcp_oauth_callback_url") { - const { serverName, callbackUrl } = message.request; - const submit = oauthCallbackSubmitters.get(serverName); - if (submit) { - let hasCodeOrError = false; - try { - const parsed = new URL(callbackUrl); - hasCodeOrError = parsed.searchParams.has("code") || parsed.searchParams.has("error"); - } catch {} - if (!hasCodeOrError) { - sendControlResponseError(message, "Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter."); - } else { - oauthManualCallbackUsed.add(serverName); - submit(callbackUrl); - const authPromise = oauthAuthPromises.get(serverName); - if (authPromise) { - try { - await authPromise; - sendControlResponseSuccess(message); - } catch (error46) { - sendControlResponseError(message, error46 instanceof Error ? error46.message : "OAuth authentication failed"); - } - } else { - sendControlResponseSuccess(message); - } - } - } else { - sendControlResponseError(message, `No active OAuth flow for server: ${serverName}`); - } - } else if (message.request.subtype === "claude_authenticate") { - const { loginWithClaudeAi } = message.request; - claudeOAuth?.service.cleanup(); - logEvent("tengu_oauth_flow_start", { - loginWithClaudeAi: loginWithClaudeAi ?? true - }); - const service = new OAuthService; - let urlResolver; - const urlPromise = new Promise((resolve44) => { - urlResolver = resolve44; - }); - const flow = service.startOAuthFlow(async (manualUrl, automaticUrl) => { - urlResolver({ manualUrl, automaticUrl }); - }, { - loginWithClaudeAi: loginWithClaudeAi ?? true, - skipBrowserOpen: true - }).then(async (tokens) => { - await installOAuthTokens(tokens); - logEvent("tengu_oauth_success", { - loginWithClaudeAi: loginWithClaudeAi ?? true - }); - }).finally(() => { - service.cleanup(); - if (claudeOAuth?.service === service) { - claudeOAuth = null; - } - }); - claudeOAuth = { service, flow }; - flow.catch((err2) => logForDebugging(`claude_authenticate flow ended: ${err2}`, { - level: "info" - })); - try { - const { manualUrl, automaticUrl } = await Promise.race([ - urlPromise, - flow.then(() => { - throw new Error("OAuth flow completed without producing auth URLs"); - }) - ]); - sendControlResponseSuccess(message, { - manualUrl, - automaticUrl - }); - } catch (error46) { - sendControlResponseError(message, errorMessage(error46)); - } - } else if (message.request.subtype === "claude_oauth_callback" || message.request.subtype === "claude_oauth_wait_for_completion") { - if (!claudeOAuth) { - sendControlResponseError(message, "No active claude_authenticate flow"); - } else { - if (message.request.subtype === "claude_oauth_callback") { - claudeOAuth.service.handleManualAuthCodeInput({ - authorizationCode: message.request.authorizationCode, - state: message.request.state - }); - } - const { flow } = claudeOAuth; - flow.then(() => { - const accountInfo = getAccountInformation(); - sendControlResponseSuccess(message, { - account: { - email: accountInfo?.email, - organization: accountInfo?.organization, - subscriptionType: accountInfo?.subscription, - tokenSource: accountInfo?.tokenSource, - apiKeySource: accountInfo?.apiKeySource, - apiProvider: getAPIProvider() - } - }); - }, (error46) => sendControlResponseError(message, errorMessage(error46))); - } - } else if (message.request.subtype === "mcp_clear_auth") { - const { serverName } = message.request; - const currentAppState = getAppState(); - const config10 = getMcpConfigByName(serverName) ?? mcpClients.find((c9) => c9.name === serverName)?.config ?? currentAppState.mcp.clients.find((c9) => c9.name === serverName)?.config ?? null; - if (!config10) { - sendControlResponseError(message, `Server not found: ${serverName}`); - } else if (config10.type !== "sse" && config10.type !== "http") { - sendControlResponseError(message, `Cannot clear auth for server type "${config10.type}"`); - } else { - await revokeServerTokens(serverName, config10); - const result = await reconnectMcpServerImpl(serverName, config10); - const prefix = getMcpPrefix(serverName); - setAppState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: prev.mcp.clients.map((c9) => c9.name === serverName ? result.client : c9), - tools: [ - ...reject_default(prev.mcp.tools, (t4) => t4.name?.startsWith(prefix)), - ...result.tools - ], - commands: [ - ...reject_default(prev.mcp.commands, (c9) => commandBelongsToServer(c9, serverName)), - ...result.commands - ], - resources: result.resources && result.resources.length > 0 ? { - ...prev.mcp.resources, - [serverName]: result.resources - } : omit_default(prev.mcp.resources, serverName) - } - })); - sendControlResponseSuccess(message, {}); - } - } else if (message.request.subtype === "apply_flag_settings") { - const prevModel = getMainLoopModel(); - const existing = getFlagSettingsInline() ?? {}; - const incoming = message.request.settings; - const merged = { ...existing, ...incoming }; - for (const key2 of Object.keys(merged)) { - if (merged[key2] === null) { - delete merged[key2]; - } - } - setFlagSettingsInline(merged); - settingsChangeDetector.notifyChange("flagSettings"); - if ("model" in incoming) { - if (incoming.model != null) { - setMainLoopModelOverride(String(incoming.model)); - } else { - setMainLoopModelOverride(undefined); - } - } - const newModel = getMainLoopModel(); - if (newModel !== prevModel) { - activeUserSpecifiedModel = newModel; - const modelArg = incoming.model ? String(incoming.model) : "default"; - notifySessionMetadataChanged({ model: newModel }); - injectModelSwitchBreadcrumbs(modelArg, newModel); - } - sendControlResponseSuccess(message); - } else if (message.request.subtype === "get_settings") { - const currentAppState = getAppState(); - const model = getMainLoopModel(); - const effort = modelSupportsEffort(model) ? resolveAppliedEffort(model, currentAppState.effortValue) : undefined; - sendControlResponseSuccess(message, { - ...getSettingsWithSources(), - applied: { - model, - effort: typeof effort === "string" ? effort : null - } - }); - } else if (message.request.subtype === "stop_task") { - const { task_id: taskId } = message.request; - try { - await stopTask(taskId, { - getAppState, - setAppState - }); - sendControlResponseSuccess(message, {}); - } catch (error46) { - sendControlResponseError(message, errorMessage(error46)); - } - } else if (message.request.subtype === "generate_session_title") { - const { description, persist } = message.request; - const titleSignal = (abortController && !abortController.signal.aborted ? abortController : createAbortController()).signal; - (async () => { - try { - const title = await generateSessionTitle(description, titleSignal); - if (title && persist) { - try { - saveAiGeneratedTitle(getSessionId(), title); - } catch (e4) { - logError2(e4); - } - } - sendControlResponseSuccess(message, { title }); - } catch (e4) { - sendControlResponseError(message, errorMessage(e4)); - } - })(); - } else if (message.request.subtype === "side_question") { - const { question } = message.request; - (async () => { - try { - const saved = getLastCacheSafeParams(); - const cacheSafeParams = saved ? { - ...saved, - toolUseContext: { - ...saved.toolUseContext, - abortController: createAbortController() - } - } : await buildSideQuestionFallbackParams({ - tools: buildAllTools(getAppState()), - commands: currentCommands, - mcpClients: [ - ...getAppState().mcp.clients, - ...sdkClients, - ...dynamicMcpState.clients - ], - messages: mutableMessages, - readFileState, - getAppState, - setAppState, - customSystemPrompt: options2.systemPrompt, - appendSystemPrompt: options2.appendSystemPrompt, - thinkingConfig: options2.thinkingConfig, - agents: currentAgents - }); - const result = await runSideQuestion({ - question, - cacheSafeParams - }); - sendControlResponseSuccess(message, { response: result.response }); - } catch (e4) { - sendControlResponseError(message, errorMessage(e4)); - } - })(); - } else if (false) {} else if (message.request.subtype === "remote_control") { - if (message.request.enabled) { - if (bridgeHandle) { - sendControlResponseSuccess(message, { - session_url: getRemoteSessionUrl(bridgeHandle.bridgeSessionId, bridgeHandle.sessionIngressUrl), - connect_url: buildBridgeConnectUrl(bridgeHandle.environmentId, bridgeHandle.sessionIngressUrl), - environment_id: bridgeHandle.environmentId - }); - } else { - let bridgeFailureDetail; - try { - const { initReplBridge: initReplBridge2 } = await Promise.resolve().then(() => (init_initReplBridge(), exports_initReplBridge)); - const handle = await initReplBridge2({ - onInboundMessage(msg) { - const fields = extractInboundMessageFields(msg); - if (!fields) - return; - const { content, uuid: uuid8 } = fields; - enqueue({ - value: content, - mode: "prompt", - uuid: uuid8, - skipSlashCommands: true - }); - run(); - }, - onPermissionResponse(response7) { - structuredIO.injectControlResponse(response7); - }, - onInterrupt() { - abortController?.abort(); - }, - onSetModel(model) { - const resolved = model === "default" ? getDefaultMainLoopModel() : model; - activeUserSpecifiedModel = resolved; - setMainLoopModelOverride(resolved); - }, - onSetMaxThinkingTokens(maxTokens) { - if (maxTokens === null) { - options2.thinkingConfig = undefined; - } else if (maxTokens === 0) { - options2.thinkingConfig = { type: "disabled" }; - } else { - options2.thinkingConfig = { - type: "enabled", - budgetTokens: maxTokens - }; - } - }, - onStateChange(state4, detail) { - if (state4 === "failed") { - bridgeFailureDetail = detail; - } - logForDebugging(`[bridge:sdk] State change: ${state4}${detail ? ` \u2014 ${detail}` : ""}`); - output.enqueue({ - type: "system", - subtype: "bridge_state", - state: state4, - detail, - uuid: randomUUID55(), - session_id: getSessionId() - }); - }, - initialMessages: mutableMessages.length > 0 ? mutableMessages : undefined - }); - if (!handle) { - sendControlResponseError(message, bridgeFailureDetail ?? "Remote Control initialization failed"); - } else { - bridgeHandle = handle; - bridgeLastForwardedIndex = mutableMessages.length; - structuredIO.setOnControlRequestSent((request2) => { - handle.sendControlRequest(request2); - }); - structuredIO.setOnControlRequestResolved((requestId) => { - handle.sendControlCancelRequest(requestId); - }); - sendControlResponseSuccess(message, { - session_url: getRemoteSessionUrl(handle.bridgeSessionId, handle.sessionIngressUrl), - connect_url: buildBridgeConnectUrl(handle.environmentId, handle.sessionIngressUrl), - environment_id: handle.environmentId - }); - } - } catch (err2) { - sendControlResponseError(message, errorMessage(err2)); - } - } - } else { - if (bridgeHandle) { - structuredIO.setOnControlRequestSent(undefined); - structuredIO.setOnControlRequestResolved(undefined); - await bridgeHandle.teardown(); - bridgeHandle = null; - } - sendControlResponseSuccess(message); - } - } else { - sendControlResponseError(message, `Unsupported control request subtype: ${message.request.subtype}`); - } - continue; - } else if (message.type === "control_response") { - if (options2.replayUserMessages) { - output.enqueue(message); - } - continue; - } else if (message.type === "keep_alive") { - continue; - } else if (message.type === "update_environment_variables") { - continue; - } else if (message.type === "assistant" || message.type === "system") { - const internalMsgs = toInternalMessages([message]); - mutableMessages.push(...internalMsgs); - if (message.type === "assistant" && options2.replayUserMessages) { - output.enqueue(message); - } - continue; - } - if (message.type !== "user") { - continue; - } - initialized5 = true; - if (message.uuid) { - const sessionId = getSessionId(); - const existsInSession = await doesMessageExistInSession(sessionId, message.uuid); - if (existsInSession || receivedMessageUuids.has(message.uuid)) { - logForDebugging(`Skipping duplicate user message: ${message.uuid}`); - if (options2.replayUserMessages) { - logForDebugging(`Sending acknowledgment for duplicate user message: ${message.uuid}`); - output.enqueue({ - type: "user", - message: message.message, - session_id: sessionId, - parent_tool_use_id: null, - uuid: message.uuid, - timestamp: message.timestamp, - isReplay: true - }); - } - if (existsInSession) { - notifyCommandLifecycle(message.uuid, "completed"); - } - continue; - } - trackReceivedMessageUuid(message.uuid); - } - enqueue({ - mode: "prompt", - value: await resolveAndPrepend(message, message.message.content), - uuid: message.uuid, - priority: message.priority - }); - if (false) {} - run(); - } - inputClosed = true; - cronScheduler?.stop(); - if (!running) { - if (suggestionState.inflightPromise) { - await Promise.race([suggestionState.inflightPromise, sleep6(5000)]); - } - suggestionState.abortController?.abort(); - suggestionState.abortController = null; - await finalizePendingAsyncHooks(); - unsubscribeSkillChanges(); - unsubscribeAuthStatus?.(); - statusListeners.delete(rateLimitListener); - output.done(); - } - })(); - return output; -} -function createCanUseToolWithPermissionPrompt(permissionPromptTool) { - const canUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => { - const mainPermissionResult = forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId); - if (mainPermissionResult.behavior === "allow" || mainPermissionResult.behavior === "deny") { - return mainPermissionResult; - } - const { signal: combinedSignal, cleanup: cleanupAbortListener } = createCombinedAbortSignal(toolUseContext.abortController.signal); - if (combinedSignal.aborted) { - cleanupAbortListener(); - return { - behavior: "deny", - message: "Permission prompt was aborted.", - decisionReason: { - type: "permissionPromptTool", - permissionPromptToolName: tool.name, - toolResult: undefined - } - }; - } - const abortPromise = new Promise((resolve44) => { - combinedSignal.addEventListener("abort", () => resolve44("aborted"), { - once: true - }); - }); - const toolCallPromise = permissionPromptTool.call({ - tool_name: tool.name, - input, - tool_use_id: toolUseId - }, toolUseContext, canUseTool, assistantMessage); - const raceResult = await Promise.race([toolCallPromise, abortPromise]); - cleanupAbortListener(); - if (raceResult === "aborted" || combinedSignal.aborted) { - return { - behavior: "deny", - message: "Permission prompt was aborted.", - decisionReason: { - type: "permissionPromptTool", - permissionPromptToolName: tool.name, - toolResult: undefined - } - }; - } - const result = raceResult; - const permissionToolResultBlockParam = permissionPromptTool.mapToolResultToToolResultBlockParam(result.data, "1"); - if (!permissionToolResultBlockParam.content || !Array.isArray(permissionToolResultBlockParam.content) || !permissionToolResultBlockParam.content[0] || permissionToolResultBlockParam.content[0].type !== "text" || typeof permissionToolResultBlockParam.content[0].text !== "string") { - throw new Error('Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.'); - } - return permissionPromptToolResultToPermissionDecision(outputSchema32().parse(safeParseJSON(permissionToolResultBlockParam.content[0].text)), permissionPromptTool, input, toolUseContext); - }; - return canUseTool; -} -function getCanUseToolFn(permissionPromptToolName, structuredIO, getMcpTools, onPermissionPrompt) { - if (permissionPromptToolName === "stdio") { - return structuredIO.createCanUseTool(onPermissionPrompt); - } - if (!permissionPromptToolName) { - return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId); - } - let resolved = null; - return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => { - if (!resolved) { - const mcpTools = getMcpTools(); - const permissionPromptTool = mcpTools.find((t4) => toolMatchesName(t4, permissionPromptToolName)); - if (!permissionPromptTool) { - const error46 = `Error: MCP tool ${permissionPromptToolName} (passed via --permission-prompt-tool) not found. Available MCP tools: ${mcpTools.map((t4) => t4.name).join(", ") || "none"}`; - process.stderr.write(`${error46} -`); - gracefulShutdownSync(1); - throw new Error(error46); - } - if (!permissionPromptTool.inputJSONSchema) { - const error46 = `Error: tool ${permissionPromptToolName} (passed via --permission-prompt-tool) must be an MCP tool`; - process.stderr.write(`${error46} -`); - gracefulShutdownSync(1); - throw new Error(error46); - } - resolved = createCanUseToolWithPermissionPrompt(permissionPromptTool); - } - return resolved(tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision); - }; -} -async function handleInitializeRequest(request2, requestId, initialized5, output, commands7, modelInfos, structuredIO, enableAuthStatus, options2, agents2, getAppState) { - if (initialized5) { - output.enqueue({ - type: "control_response", - response: { - subtype: "error", - error: "Already initialized", - request_id: requestId, - pending_permission_requests: structuredIO.getPendingPermissionRequests() - } - }); - return; - } - if (request2.systemPrompt !== undefined) { - options2.systemPrompt = request2.systemPrompt; - } - if (request2.appendSystemPrompt !== undefined) { - options2.appendSystemPrompt = request2.appendSystemPrompt; - } - if (request2.promptSuggestions !== undefined) { - options2.promptSuggestions = request2.promptSuggestions; - } - if (request2.agents) { - const stdinAgents = parseAgentsFromJson(request2.agents, "flagSettings"); - agents2.push(...stdinAgents); - } - if (options2.agent) { - const alreadyResolved = getMainThreadAgentType() === options2.agent; - const mainThreadAgent = agents2.find((a5) => a5.agentType === options2.agent); - if (mainThreadAgent && !alreadyResolved) { - setMainThreadAgentType(mainThreadAgent.agentType); - if (!options2.systemPrompt && !isBuiltInAgent(mainThreadAgent)) { - const agentSystemPrompt = mainThreadAgent.getSystemPrompt(); - if (agentSystemPrompt) { - options2.systemPrompt = agentSystemPrompt; - } - } - if (!options2.userSpecifiedModel && mainThreadAgent.model && mainThreadAgent.model !== "inherit") { - const agentModel = parseUserSpecifiedModel(mainThreadAgent.model); - setMainLoopModelOverride(agentModel); - } - if (mainThreadAgent.initialPrompt) { - structuredIO.prependUserMessage(mainThreadAgent.initialPrompt); - } - } else if (mainThreadAgent?.initialPrompt) { - structuredIO.prependUserMessage(mainThreadAgent.initialPrompt); - } - } - const settings = getSettings_DEPRECATED(); - const outputStyle2 = settings?.outputStyle || DEFAULT_OUTPUT_STYLE_NAME; - const availableOutputStyles = await getAllOutputStyles(getCwd()); - const accountInfo = getAccountInformation(); - if (request2.hooks) { - const hooks2 = {}; - for (const [event, matchers] of Object.entries(request2.hooks)) { - hooks2[event] = matchers.map((matcher) => { - const callbacks = matcher.hookCallbackIds.map((callbackId) => { - return structuredIO.createHookCallback(callbackId, matcher.timeout); - }); - return { - matcher: matcher.matcher, - hooks: callbacks - }; - }); - } - registerHookCallbacks(hooks2); - } - if (request2.jsonSchema) { - setInitJsonSchema(request2.jsonSchema); - } - const initResponse = { - commands: commands7.filter((cmd) => cmd.userInvocable !== false).map((cmd) => ({ - name: getCommandName(cmd), - description: formatDescriptionWithSource(cmd), - argumentHint: cmd.argumentHint || "" - })), - agents: agents2.map((agent) => ({ - name: agent.agentType, - description: agent.whenToUse, - model: agent.model === "inherit" ? undefined : agent.model - })), - output_style: outputStyle2, - available_output_styles: Object.keys(availableOutputStyles), - models: modelInfos, - account: { - email: accountInfo?.email, - organization: accountInfo?.organization, - subscriptionType: accountInfo?.subscription, - tokenSource: accountInfo?.tokenSource, - apiKeySource: accountInfo?.apiKeySource, - apiProvider: getAPIProvider() - }, - pid: process.pid - }; - if (isFastModeEnabled() && isFastModeAvailable()) { - const appState = getAppState(); - initResponse.fast_mode_state = getFastModeState(options2.userSpecifiedModel ?? null, appState.fastMode); - } - output.enqueue({ - type: "control_response", - response: { - subtype: "success", - request_id: requestId, - response: initResponse - } - }); - if (enableAuthStatus) { - const authStatusManager = AwsAuthStatusManager.getInstance(); - const status2 = authStatusManager.getStatus(); - if (status2) { - output.enqueue({ - type: "auth_status", - isAuthenticating: status2.isAuthenticating, - output: status2.output, - error: status2.error, - uuid: randomUUID55(), - session_id: getSessionId() - }); - } - } -} -async function handleRewindFiles(userMessageId, appState, setAppState, dryRun) { - if (!fileHistoryEnabled()) { - return { canRewind: false, error: "File rewinding is not enabled." }; - } - if (!fileHistoryCanRestore(appState.fileHistory, userMessageId)) { - return { - canRewind: false, - error: "No file checkpoint found for this message." - }; - } - if (dryRun) { - const diffStats = await fileHistoryGetDiffStats(appState.fileHistory, userMessageId); - return { - canRewind: true, - filesChanged: diffStats?.filesChanged, - insertions: diffStats?.insertions, - deletions: diffStats?.deletions - }; - } - try { - await fileHistoryRewind((updater) => setAppState((prev) => ({ - ...prev, - fileHistory: updater(prev.fileHistory) - })), userMessageId); - } catch (error46) { - return { - canRewind: false, - error: `Failed to rewind: ${errorMessage(error46)}` - }; - } - return { canRewind: true }; -} -function handleSetPermissionMode(request2, requestId, toolPermissionContext, output) { - if (request2.mode === "bypassPermissions") { - if (isBypassPermissionsModeDisabled()) { - output.enqueue({ - type: "control_response", - response: { - subtype: "error", - request_id: requestId, - error: "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration" - } - }); - return toolPermissionContext; - } - if (!toolPermissionContext.isBypassPermissionsModeAvailable) { - output.enqueue({ - type: "control_response", - response: { - subtype: "error", - request_id: requestId, - error: "Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions" - } - }); - return toolPermissionContext; - } - } - if (false) {} - output.enqueue({ - type: "control_response", - response: { - subtype: "success", - request_id: requestId, - response: { - mode: request2.mode - } - } - }); - return { - ...transitionPermissionMode(toolPermissionContext.mode, request2.mode, toolPermissionContext), - mode: request2.mode - }; -} -function handleChannelEnable(requestId, serverName, connectionPool, output) { - const respondError = (error46) => output.enqueue({ - type: "control_response", - response: { subtype: "error", request_id: requestId, error: error46 } - }); - if (true) { - return respondError("channels feature not available in this build"); - } - const connection7 = connectionPool.find((c9) => c9.name === serverName && c9.type === "connected"); - if (!connection7 || connection7.type !== "connected") { - return respondError(`server ${serverName} is not connected`); - } - const pluginSource = connection7.config.pluginSource; - const parsed = pluginSource ? parsePluginIdentifier(pluginSource) : undefined; - if (!parsed?.marketplace) { - return respondError(`server ${serverName} is not plugin-sourced; channel_enable requires a marketplace plugin`); - } - const entry = { - kind: "plugin", - name: parsed.name, - marketplace: parsed.marketplace - }; - const prior = getAllowedChannels(); - const already = prior.some((e4) => e4.kind === "plugin" && e4.name === entry.name && e4.marketplace === entry.marketplace); - if (!already) - setAllowedChannels([...prior, entry]); - const gate = gateChannelServer(serverName, connection7.capabilities, pluginSource); - if (gate.action === "skip") { - if (!already) - setAllowedChannels(prior); - return respondError(gate.reason); - } - const pluginId = `${entry.name}@${entry.marketplace}`; - logMCPDebug(serverName, "Channel notifications registered"); - logEvent("tengu_mcp_channel_enable", { plugin: pluginId }); - connection7.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => { - const { content, meta } = notification.params; - logMCPDebug(serverName, `notifications/claude/channel: ${content.slice(0, 80)}`); - logEvent("tengu_mcp_channel_message", { - content_length: content.length, - meta_key_count: Object.keys(meta ?? {}).length, - entry_kind: "plugin", - is_dev: false, - plugin: pluginId - }); - enqueue({ - mode: "prompt", - value: wrapChannelMessage(serverName, content, meta), - priority: "next", - isMeta: true, - origin: { kind: "channel", server: serverName }, - skipSlashCommands: true - }); - }); - output.enqueue({ - type: "control_response", - response: { - subtype: "success", - request_id: requestId, - response: undefined - } - }); -} -function reregisterChannelHandlerAfterReconnect(connection7) { - if (true) - return; - if (connection7.type !== "connected") - return; - const gate = gateChannelServer(connection7.name, connection7.capabilities, connection7.config.pluginSource); - if (gate.action !== "register") - return; - const entry = findChannelEntry(connection7.name, getAllowedChannels()); - const pluginId = entry?.kind === "plugin" ? `${entry.name}@${entry.marketplace}` : undefined; - logMCPDebug(connection7.name, "Channel notifications re-registered after reconnect"); - connection7.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => { - const { content, meta } = notification.params; - logMCPDebug(connection7.name, `notifications/claude/channel: ${content.slice(0, 80)}`); - logEvent("tengu_mcp_channel_message", { - content_length: content.length, - meta_key_count: Object.keys(meta ?? {}).length, - entry_kind: entry?.kind, - is_dev: entry?.dev ?? false, - plugin: pluginId - }); - enqueue({ - mode: "prompt", - value: wrapChannelMessage(connection7.name, content, meta), - priority: "next", - isMeta: true, - origin: { kind: "channel", server: connection7.name }, - skipSlashCommands: true - }); - }); -} -function emitLoadError(message, outputFormat) { - if (outputFormat === "stream-json") { - const errorResult = { - type: "result", - subtype: "error_during_execution", - duration_ms: 0, - duration_api_ms: 0, - is_error: true, - num_turns: 0, - stop_reason: null, - session_id: getSessionId(), - total_cost_usd: 0, - usage: EMPTY_USAGE, - modelUsage: {}, - permission_denials: [], - uuid: randomUUID55(), - errors: [message] - }; - process.stdout.write(jsonStringify(errorResult) + ` -`); - } else { - process.stderr.write(message + ` -`); - } -} -function removeInterruptedMessage(messages, interruptedUserMessage) { - const idx = messages.findIndex((m4) => m4.uuid === interruptedUserMessage.uuid); - if (idx !== -1) { - messages.splice(idx, 2); - } -} -async function loadInitialMessages(setAppState, options2) { - const persistSession = !isSessionPersistenceDisabled(); - if (options2.continue) { - try { - logEvent("tengu_continue_print", {}); - const result = await loadConversationForResume(undefined, undefined); - if (result) { - if (false) {} - if (!options2.forkSession) { - if (result.sessionId) { - switchSession(asSessionId(result.sessionId), result.fullPath ? dirname63(result.fullPath) : null); - if (persistSession) { - await resetSessionFilePointer(); - } - } - } - restoreSessionStateFromLog(result, setAppState); - restoreSessionMetadata(options2.forkSession ? { ...result, worktreeSession: undefined } : result); - if (false) {} - return { - messages: result.messages, - turnInterruptionState: result.turnInterruptionState, - agentSetting: result.agentSetting - }; - } - } catch (error46) { - logError2(error46); - gracefulShutdownSync(1); - return { messages: [] }; - } - } - if (options2.teleport) { - try { - if (!isPolicyAllowed("allow_remote_sessions")) { - throw new Error("Remote sessions are disabled by your organization's policy."); - } - logEvent("tengu_teleport_print", {}); - if (typeof options2.teleport !== "string") { - throw new Error("No session ID provided for teleport"); - } - const { - checkOutTeleportedSessionBranch: checkOutTeleportedSessionBranch2, - processMessagesForTeleportResume: processMessagesForTeleportResume2, - teleportResumeCodeSession: teleportResumeCodeSession2, - validateGitState: validateGitState2 - } = await Promise.resolve().then(() => (init_teleport(), exports_teleport)); - await validateGitState2(); - const teleportResult = await teleportResumeCodeSession2(options2.teleport); - const { branchError } = await checkOutTeleportedSessionBranch2(teleportResult.branch); - return { - messages: processMessagesForTeleportResume2(teleportResult.log, branchError) - }; - } catch (error46) { - logError2(error46); - gracefulShutdownSync(1); - return { messages: [] }; - } - } - if (options2.resume) { - try { - logEvent("tengu_resume_print", {}); - const parsedSessionId = parseSessionIdentifier(typeof options2.resume === "string" ? options2.resume : ""); - if (!parsedSessionId) { - let errorMessage4 = "Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume "; - if (typeof options2.resume === "string") { - errorMessage4 += `. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${options2.resume}" is not a valid UUID`; - } - emitLoadError(errorMessage4, options2.outputFormat); - gracefulShutdownSync(1); - return { messages: [] }; - } - if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) { - const [, metadata] = await Promise.all([ - hydrateFromCCRv2InternalEvents(parsedSessionId.sessionId), - options2.restoredWorkerState - ]); - if (metadata) { - setAppState(externalMetadataToAppState(metadata)); - if (typeof metadata.model === "string") { - setMainLoopModelOverride(metadata.model); - } - } - } else if (parsedSessionId.isUrl && parsedSessionId.ingressUrl && isEnvTruthy(process.env.ENABLE_SESSION_PERSISTENCE)) { - await hydrateRemoteSession(parsedSessionId.sessionId, parsedSessionId.ingressUrl); - } - const result = await loadConversationForResume(parsedSessionId.sessionId, parsedSessionId.jsonlFile || undefined); - if (!result || result.messages.length === 0) { - if (parsedSessionId.isUrl || isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) { - return { - messages: await (options2.sessionStartHooksPromise ?? processSessionStartHooks("startup")) - }; - } else { - emitLoadError(`No conversation found with session ID: ${parsedSessionId.sessionId}`, options2.outputFormat); - gracefulShutdownSync(1); - return { messages: [] }; - } - } - if (options2.resumeSessionAt) { - const index2 = result.messages.findIndex((m4) => m4.uuid === options2.resumeSessionAt); - if (index2 < 0) { - emitLoadError(`No message found with message.uuid of: ${options2.resumeSessionAt}`, options2.outputFormat); - gracefulShutdownSync(1); - return { messages: [] }; - } - result.messages = index2 >= 0 ? result.messages.slice(0, index2 + 1) : []; - } - if (false) {} - if (!options2.forkSession && result.sessionId) { - switchSession(asSessionId(result.sessionId), result.fullPath ? dirname63(result.fullPath) : null); - if (persistSession) { - await resetSessionFilePointer(); - } - } - restoreSessionStateFromLog(result, setAppState); - restoreSessionMetadata(options2.forkSession ? { ...result, worktreeSession: undefined } : result); - if (false) {} - return { - messages: result.messages, - turnInterruptionState: result.turnInterruptionState, - agentSetting: result.agentSetting - }; - } catch (error46) { - logError2(error46); - const errorMessage4 = error46 instanceof Error ? `Failed to resume session: ${error46.message}` : "Failed to resume session with --print mode"; - emitLoadError(errorMessage4, options2.outputFormat); - gracefulShutdownSync(1); - return { messages: [] }; - } - } - return { - messages: await (options2.sessionStartHooksPromise ?? processSessionStartHooks("startup")) - }; -} -function getStructuredIO(inputPrompt, options2) { - let inputStream; - if (typeof inputPrompt === "string") { - if (inputPrompt.trim() !== "") { - inputStream = fromArray([ - jsonStringify({ - type: "user", - session_id: "", - message: { - role: "user", - content: inputPrompt - }, - parent_tool_use_id: null - }) - ]); - } else { - inputStream = fromArray([]); - } - } else { - inputStream = inputPrompt; - } - return options2.sdkUrl ? new RemoteIO(options2.sdkUrl, inputStream, options2.replayUserMessages) : new StructuredIO(inputStream, options2.replayUserMessages); -} -async function handleOrphanedPermissionResponse({ - message, - setAppState, - onEnqueued, - handledToolUseIds -}) { - if (message.response.subtype === "success" && message.response.response?.toolUseID && typeof message.response.response.toolUseID === "string") { - const permissionResult = message.response.response; - const { toolUseID } = permissionResult; - if (!toolUseID) { - return false; - } - logForDebugging(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${toolUseID} request_id=${message.response.request_id}`); - if (handledToolUseIds.has(toolUseID)) { - logForDebugging(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${toolUseID} (already handled)`); - return false; - } - const assistantMessage = await findUnresolvedToolUse(toolUseID); - if (!assistantMessage) { - logForDebugging(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${toolUseID} (already resolved in transcript)`); - return false; - } - handledToolUseIds.add(toolUseID); - logForDebugging(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${toolUseID} messageID=${assistantMessage.message.id}`); - enqueue({ - mode: "orphaned-permission", - value: [], - orphanedPermission: { - permissionResult, - assistantMessage - } - }); - onEnqueued?.(); - return true; - } - return false; -} -function toScopedConfig(config10) { - return { ...config10, scope: "dynamic" }; -} -async function handleMcpSetServers(servers, sdkState, dynamicState, setAppState) { - const { allowed: allowedServers, blocked } = filterMcpServersByPolicy(servers); - const policyErrors = {}; - for (const name3 of blocked) { - policyErrors[name3] = "Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)"; - } - const sdkServers = {}; - const processServers = {}; - for (const [name3, config10] of Object.entries(allowedServers)) { - if (config10.type === "sdk") { - sdkServers[name3] = config10; - } else { - processServers[name3] = config10; - } - } - const currentSdkNames = new Set(Object.keys(sdkState.configs)); - const newSdkNames = new Set(Object.keys(sdkServers)); - const sdkAdded = []; - const sdkRemoved = []; - const newSdkConfigs = { ...sdkState.configs }; - let newSdkClients = [...sdkState.clients]; - let newSdkTools = [...sdkState.tools]; - for (const name3 of currentSdkNames) { - if (!newSdkNames.has(name3)) { - const client16 = newSdkClients.find((c9) => c9.name === name3); - if (client16 && client16.type === "connected") { - await client16.cleanup(); - } - newSdkClients = newSdkClients.filter((c9) => c9.name !== name3); - const prefix = `mcp__${name3}__`; - newSdkTools = newSdkTools.filter((t4) => !t4.name.startsWith(prefix)); - delete newSdkConfigs[name3]; - sdkRemoved.push(name3); - } - } - for (const [name3, config10] of Object.entries(sdkServers)) { - if (!currentSdkNames.has(name3)) { - newSdkConfigs[name3] = config10; - const pendingClient = { - type: "pending", - name: name3, - config: { ...config10, scope: "dynamic" } - }; - newSdkClients = [...newSdkClients, pendingClient]; - sdkAdded.push(name3); - } - } - const processResult = await reconcileMcpServers(processServers, dynamicState, setAppState); - return { - response: { - added: [...sdkAdded, ...processResult.response.added], - removed: [...sdkRemoved, ...processResult.response.removed], - errors: { ...policyErrors, ...processResult.response.errors } - }, - newSdkState: { - configs: newSdkConfigs, - clients: newSdkClients, - tools: newSdkTools - }, - newDynamicState: processResult.newState, - sdkServersChanged: sdkAdded.length > 0 || sdkRemoved.length > 0 - }; -} -async function reconcileMcpServers(desiredConfigs, currentState2, setAppState) { - const currentNames = new Set(Object.keys(currentState2.configs)); - const desiredNames = new Set(Object.keys(desiredConfigs)); - const toRemove = [...currentNames].filter((n6) => !desiredNames.has(n6)); - const toAdd = [...desiredNames].filter((n6) => !currentNames.has(n6)); - const toCheck = [...currentNames].filter((n6) => desiredNames.has(n6)); - const toReplace = toCheck.filter((name3) => { - const currentConfig = currentState2.configs[name3]; - const desiredConfigRaw = desiredConfigs[name3]; - if (!currentConfig || !desiredConfigRaw) - return true; - const desiredConfig = toScopedConfig(desiredConfigRaw); - return !areMcpConfigsEqual(currentConfig, desiredConfig); - }); - const removed = []; - const added = []; - const errors8 = {}; - let newClients = [...currentState2.clients]; - let newTools = [...currentState2.tools]; - for (const name3 of [...toRemove, ...toReplace]) { - const client16 = newClients.find((c9) => c9.name === name3); - const config10 = currentState2.configs[name3]; - if (client16 && config10) { - if (client16.type === "connected") { - try { - await client16.cleanup(); - } catch (e4) { - logError2(e4); - } - } - await clearServerCache(name3, config10); - } - const prefix = `mcp__${name3}__`; - newTools = newTools.filter((t4) => !t4.name.startsWith(prefix)); - newClients = newClients.filter((c9) => c9.name !== name3); - if (toRemove.includes(name3)) { - removed.push(name3); - } - } - for (const name3 of [...toAdd, ...toReplace]) { - const config10 = desiredConfigs[name3]; - if (!config10) - continue; - const scopedConfig = toScopedConfig(config10); - if (config10.type === "sdk") { - added.push(name3); - continue; - } - try { - const client16 = await connectToServer(name3, scopedConfig); - newClients.push(client16); - if (client16.type === "connected") { - const serverTools = await fetchToolsForClient(client16); - newTools.push(...serverTools); - } else if (client16.type === "failed") { - errors8[name3] = client16.error || "Connection failed"; - } - added.push(name3); - } catch (e4) { - const err2 = toError(e4); - errors8[name3] = err2.message; - logError2(err2); - } - } - const newConfigs = {}; - for (const name3 of desiredNames) { - const config10 = desiredConfigs[name3]; - if (config10) { - newConfigs[name3] = toScopedConfig(config10); - } - } - const newState = { - clients: newClients, - tools: newTools, - configs: newConfigs - }; - setAppState((prev) => { - const allDynamicServerNames = new Set([ - ...Object.keys(currentState2.configs), - ...Object.keys(newConfigs) - ]); - const nonDynamicTools = prev.mcp.tools.filter((t4) => { - for (const serverName of allDynamicServerNames) { - if (t4.name.startsWith(`mcp__${serverName}__`)) { - return false; - } - } - return true; - }); - const nonDynamicClients = prev.mcp.clients.filter((c9) => { - return !allDynamicServerNames.has(c9.name); - }); - return { - ...prev, - mcp: { - ...prev.mcp, - tools: [...nonDynamicTools, ...newTools], - clients: [...nonDynamicClients, ...newClients] - } - }; - }); - return { - response: { added, removed, errors: errors8 }, - newState - }; -} -var SHUTDOWN_TEAM_PROMPT = ` -You are running in non-interactive mode and cannot return a response to the user until your team is shut down. - -You MUST shut down your team before preparing your final response: -1. Use requestShutdown to ask each team member to shut down gracefully -2. Wait for shutdown approvals -3. Use the cleanup operation to clean up the team -4. Only then provide your final response to the user - -The user cannot receive your response until the team is completely shut down. - - -Shut down your team and prepare your final response for the user.`, MAX_RECEIVED_UUIDS = 1e4, receivedMessageUuids, receivedMessageUuidsOrder; -var init_print = __esm(() => { - init_settingsSync(); - init_remoteManagedSettings(); - init_structuredIO(); - init_remoteIO(); - init_commands5(); - init_streamlinedTransform(); - init_streamJsonStdoutGuard(); - init_tools2(); - init_uniqBy(); - init_toolPool(); - init_analytics(); - init_growthbook(); - init_debug(); - init_diagLogs(); - init_Tool(); - init_loadAgentsDir(); - init_messageQueueManager(); - init_sessionState(); - init_onChangeAppState(); - init_log2(); - init_logging2(); - init_conversationRecovery(); - init_channelNotification(); - init_channelAllowlist(); - init_pluginIdentifier(); - init_uuid(); - init_generators(); - init_QueryEngine(); - init_fileStateCache(); - init_path(); - init_queryHelpers(); - init_hookEvents(); - init_filePersistence(); - init_AsyncHookRegistry(); - init_gracefulShutdown(); - init_cleanupRegistry(); - init_idleTimeout(); - init_cwd(); - init_omit(); - init_reject2(); - init_policyLimits(); - init_bridgeStatusUtil(); - init_inboundMessages(); - init_inboundAttachments(); - init_permissions2(); - init_json(); - init_PermissionPromptToolResultSchema(); - init_abortController(); - init_combinedAbortSignal(); - init_sessionTitle(); - init_queryContext(); - init_sideQuestion(); - init_sessionStart(); - init_outputStyles(); - init_xml(); - init_settings2(); - init_changeDetector(); - init_applySettingsChange(); - init_fastMode(); - init_permissionSetup(); - init_promptSuggestion(); - init_forkedAgent(); - init_auth14(); - init_oauth2(); - init_auth19(); - init_providers(); - init_awsAuthStatusManager(); - init_state(); - init_SyntheticOutputTool(); - init_sessionUrl(); - init_sessionStorage(); - init_commitAttribution(); - init_client22(); - init_config9(); - init_auth18(); - init_elicitationHandler(); - init_hooks3(); - init_types17(); - init_mcpStringUtils(); - init_utils8(); - init_vscodeSdkMcp(); - init_config9(); - init_grove(); - init_mappers(); - init_messages9(); - init_context_noninteractive(); - init_xml(); - init_claudeAiLimits(); - init_model(); - init_modelOptions(); - init_effort(); - init_thinking(); - init_betas2(); - init_modelStrings(); - init_state(); - init_workloadContext(); - init_fileHistory(); - init_sessionRestore(); - init_sandbox_adapter(); - init_headlessProfiler(); - init_queryProfiler(); - init_ids(); - init_slowOperations(); - init_skillChangeDetector(); - init_commands5(); - init_envUtils(); - init_headlessPluginInstall(); - init_refresh(); - init_pluginLoader(); - init_teammate(); - init_teammateMailbox(); - init_teamHelpers(); - init_tasks(); - init_framework(); - init_stopTask(); - init_sdkEventQueue(); - init_growthbook(); - init_errors(); - init_paths(); - receivedMessageUuids = new Set; - receivedMessageUuidsOrder = []; -}); - -// src/components/TeleportProgress.tsx -var exports_TeleportProgress = {}; -__export(exports_TeleportProgress, { - teleportWithProgress: () => teleportWithProgress, - TeleportProgress: () => TeleportProgress -}); -function TeleportProgress(t0) { - const $2 = import_compiler_runtime386.c(16); - const { - currentStep, - sessionId - } = t0; - const [ref, time4] = useAnimationFrame(100); - const frame = Math.floor(time4 / 100) % SPINNER_FRAMES3.length; - let t1; - if ($2[0] !== currentStep) { - t1 = (s4) => s4.key === currentStep; - $2[0] = currentStep; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const currentStepIndex = STEPS.findIndex(t1); - const t22 = SPINNER_FRAMES3[frame]; - let t32; - if ($2[2] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedText, { - bold: true, - color: "claude", - children: [ - t22, - " Teleporting session\u2026" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[2] = t22; - $2[3] = t32; - } else { - t32 = $2[3]; - } - let t4; - if ($2[4] !== sessionId) { - t4 = sessionId && /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedBox_default, { - marginBottom: 1, - children: /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedText, { - dimColor: true, - children: sessionId - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[4] = sessionId; - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] !== currentStepIndex || $2[7] !== frame) { - t5 = STEPS.map((step, index2) => { - const isComplete = index2 < currentStepIndex; - const isCurrent = index2 === currentStepIndex; - const isPending = index2 > currentStepIndex; - let icon; - let color3; - if (isComplete) { - icon = figures_default.tick; - color3 = "green"; - } else { - if (isCurrent) { - icon = SPINNER_FRAMES3[frame]; - color3 = "claude"; - } else { - icon = figures_default.circle; - color3 = undefined; - } - } - return /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedBox_default, { - flexDirection: "row", - children: [ - /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedBox_default, { - width: 2, - children: /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedText, { - color: color3, - dimColor: isPending, - children: icon - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedText, { - dimColor: isPending, - bold: isCurrent, - children: step.label - }, undefined, false, undefined, this) - ] - }, step.key, true, undefined, this); - }); - $2[6] = currentStepIndex; - $2[7] = frame; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginLeft: 2, - children: t5 - }, undefined, false, undefined, this); - $2[9] = t5; - $2[10] = t6; - } else { - t6 = $2[10]; - } - let t7; - if ($2[11] !== ref || $2[12] !== t32 || $2[13] !== t4 || $2[14] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(ThemedBox_default, { - ref, - flexDirection: "column", - paddingX: 1, - paddingY: 1, - children: [ - t32, - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[11] = ref; - $2[12] = t32; - $2[13] = t4; - $2[14] = t6; - $2[15] = t7; - } else { - t7 = $2[15]; - } - return t7; -} -async function teleportWithProgress(root3, sessionId) { - let setStep = () => {}; - function TeleportProgressWrapper() { - const [step, _setStep] = import_react332.useState("validating"); - setStep = _setStep; - return /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(TeleportProgress, { - currentStep: step, - sessionId - }, undefined, false, undefined, this); - } - root3.render(/* @__PURE__ */ jsx_dev_runtime489.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime489.jsxDEV(TeleportProgressWrapper, {}, undefined, false, undefined, this) - }, undefined, false, undefined, this)); - const result = await teleportResumeCodeSession(sessionId, setStep); - setStep("checking_out"); - const { - branchName, - branchError - } = await checkOutTeleportedSessionBranch(result.branch); - return { - messages: processMessagesForTeleportResume(result.log, branchError), - branchName - }; -} -var import_compiler_runtime386, import_react332, jsx_dev_runtime489, SPINNER_FRAMES3, STEPS; -var init_TeleportProgress = __esm(() => { - init_figures(); - init_ink2(); - init_AppState(); - init_teleport(); - import_compiler_runtime386 = __toESM(require_compiler_runtime(), 1); - import_react332 = __toESM(require_react(), 1); - jsx_dev_runtime489 = __toESM(require_jsx_dev_runtime(), 1); - SPINNER_FRAMES3 = ["\u25D0", "\u25D3", "\u25D1", "\u25D2"]; - STEPS = [{ - key: "validating", - label: "Validating session" - }, { - key: "fetching_logs", - label: "Fetching session logs" - }, { - key: "fetching_branch", - label: "Getting branch info" - }, { - key: "checking_out", - label: "Checking out branch" - }]; -}); - -// src/components/MCPServerDesktopImportDialog.tsx -function MCPServerDesktopImportDialog(t0) { - const $2 = import_compiler_runtime387.c(36); - const { - servers, - scope, - onDone - } = t0; - let t1; - if ($2[0] !== servers) { - t1 = Object.keys(servers); - $2[0] = servers; - $2[1] = t1; - } else { - t1 = $2[1]; - } - const serverNames = t1; - let t22; - if ($2[2] === Symbol.for("react.memo_cache_sentinel")) { - t22 = {}; - $2[2] = t22; - } else { - t22 = $2[2]; - } - const [existingServers, setExistingServers] = import_react333.useState(t22); - let t32; - let t4; - if ($2[3] === Symbol.for("react.memo_cache_sentinel")) { - t32 = () => { - getAllMcpConfigs().then((t52) => { - const { - servers: servers_0 - } = t52; - return setExistingServers(servers_0); - }); - }; - t4 = []; - $2[3] = t32; - $2[4] = t4; - } else { - t32 = $2[3]; - t4 = $2[4]; - } - import_react333.useEffect(t32, t4); - let t5; - if ($2[5] !== existingServers || $2[6] !== serverNames) { - t5 = serverNames.filter((name3) => existingServers[name3] !== undefined); - $2[5] = existingServers; - $2[6] = serverNames; - $2[7] = t5; - } else { - t5 = $2[7]; - } - const collisions = t5; - const onSubmit = async function onSubmit2(selectedServers) { - let importedCount = 0; - for (const serverName of selectedServers) { - const serverConfig = servers[serverName]; - if (serverConfig) { - let finalName = serverName; - if (existingServers[finalName] !== undefined) { - let counter = 1; - while (existingServers[`${serverName}_${counter}`] !== undefined) { - counter++; - } - finalName = `${serverName}_${counter}`; - } - await addMcpConfig(finalName, serverConfig, scope); - importedCount++; - } - } - done(importedCount); - }; - const [theme2] = useTheme(); - let t6; - if ($2[8] !== onDone || $2[9] !== scope || $2[10] !== theme2) { - t6 = (importedCount_0) => { - if (importedCount_0 > 0) { - writeToStdout(` -${color("success", theme2)(`Successfully imported ${importedCount_0} MCP ${plural(importedCount_0, "server")} to ${scope} config.`)} -`); - } else { - writeToStdout(` -No servers were imported.`); - } - onDone(); - gracefulShutdown(); - }; - $2[8] = onDone; - $2[9] = scope; - $2[10] = theme2; - $2[11] = t6; - } else { - t6 = $2[11]; - } - const done = t6; - let t7; - if ($2[12] !== done) { - t7 = () => { - done(0); - }; - $2[12] = done; - $2[13] = t7; - } else { - t7 = $2[13]; - } - const handleEscCancel = t7; - const t8 = serverNames.length; - let t9; - if ($2[14] !== serverNames.length) { - t9 = plural(serverNames.length, "server"); - $2[14] = serverNames.length; - $2[15] = t9; - } else { - t9 = $2[15]; - } - const t10 = `Found ${t8} MCP ${t9} in Claude Desktop.`; - let t11; - if ($2[16] !== collisions.length) { - t11 = collisions.length > 0 && /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(ThemedText, { - color: "warning", - children: "Note: Some servers already exist with the same name. If selected, they will be imported with a numbered suffix." - }, undefined, false, undefined, this); - $2[16] = collisions.length; - $2[17] = t11; - } else { - t11 = $2[17]; - } - let t12; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t12 = /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(ThemedText, { - children: "Please select the servers you want to import:" - }, undefined, false, undefined, this); - $2[18] = t12; - } else { - t12 = $2[18]; - } - let t13; - let t14; - if ($2[19] !== collisions || $2[20] !== serverNames) { - t13 = serverNames.map((server) => ({ - label: `${server}${collisions.includes(server) ? " (already exists)" : ""}`, - value: server - })); - t14 = serverNames.filter((name_0) => !collisions.includes(name_0)); - $2[19] = collisions; - $2[20] = serverNames; - $2[21] = t13; - $2[22] = t14; - } else { - t13 = $2[21]; - t14 = $2[22]; - } - let t15; - if ($2[23] !== handleEscCancel || $2[24] !== onSubmit || $2[25] !== t13 || $2[26] !== t14) { - t15 = /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(SelectMulti, { - options: t13, - defaultValue: t14, - onSubmit, - onCancel: handleEscCancel, - hideIndexes: true - }, undefined, false, undefined, this); - $2[23] = handleEscCancel; - $2[24] = onSubmit; - $2[25] = t13; - $2[26] = t14; - $2[27] = t15; - } else { - t15 = $2[27]; - } - let t16; - if ($2[28] !== handleEscCancel || $2[29] !== t10 || $2[30] !== t11 || $2[31] !== t15) { - t16 = /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(Dialog, { - title: "Import MCP Servers from Claude Desktop", - subtitle: t10, - color: "success", - onCancel: handleEscCancel, - hideInputGuide: true, - children: [ - t11, - t12, - t15 - ] - }, undefined, true, undefined, this); - $2[28] = handleEscCancel; - $2[29] = t10; - $2[30] = t11; - $2[31] = t15; - $2[32] = t16; - } else { - t16 = $2[32]; - } - let t17; - if ($2[33] === Symbol.for("react.memo_cache_sentinel")) { - t17 = /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(ThemedBox_default, { - paddingX: 1, - children: /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(KeyboardShortcutHint, { - shortcut: "Space", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "confirm" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "cancel" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[33] = t17; - } else { - t17 = $2[33]; - } - let t18; - if ($2[34] !== t16) { - t18 = /* @__PURE__ */ jsx_dev_runtime490.jsxDEV(jsx_dev_runtime490.Fragment, { - children: [ - t16, - t17 - ] - }, undefined, true, undefined, this); - $2[34] = t16; - $2[35] = t18; - } else { - t18 = $2[35]; - } - return t18; -} -var import_compiler_runtime387, import_react333, jsx_dev_runtime490; -var init_MCPServerDesktopImportDialog = __esm(() => { - init_gracefulShutdown(); - init_ink2(); - init_config9(); - init_stringUtils(); - init_ConfigurableShortcutHint(); - init_SelectMulti(); - init_Byline(); - init_Dialog(); - init_KeyboardShortcutHint(); - import_compiler_runtime387 = __toESM(require_compiler_runtime(), 1); - import_react333 = __toESM(require_react(), 1); - jsx_dev_runtime490 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js -class ExperimentalServerTasks { - constructor(_server) { - this._server = _server; - } - requestStream(request2, resultSchema, options2) { - return this._server.requestStream(request2, resultSchema, options2); - } - createMessageStream(params, options2) { - const clientCapabilities = this._server.getClientCapabilities(); - if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { - throw new Error("Client does not support sampling tools capability."); - } - if (params.messages.length > 0) { - const lastMessage = params.messages[params.messages.length - 1]; - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c9) => c9.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c9) => c9.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c9) => c9.type !== "tool_result")) { - throw new Error("The last message must contain only tool_result content if any is present"); - } - if (!hasPreviousToolUse) { - throw new Error("tool_result blocks are not matching any tool_use from the previous message"); - } - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c9) => c9.type === "tool_use").map((c9) => c9.id)); - const toolResultIds = new Set(lastContent.filter((c9) => c9.type === "tool_result").map((c9) => c9.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { - throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - } - return this.requestStream({ - method: "sampling/createMessage", - params - }, CreateMessageResultSchema, options2); - } - elicitInputStream(params, options2) { - const clientCapabilities = this._server.getClientCapabilities(); - const mode = params.mode ?? "form"; - switch (mode) { - case "url": { - if (!clientCapabilities?.elicitation?.url) { - throw new Error("Client does not support url elicitation."); - } - break; - } - case "form": { - if (!clientCapabilities?.elicitation?.form) { - throw new Error("Client does not support form elicitation."); - } - break; - } - } - const normalizedParams = mode === "form" && params.mode === undefined ? { ...params, mode: "form" } : params; - return this.requestStream({ - method: "elicitation/create", - params: normalizedParams - }, ElicitResultSchema, options2); - } - async getTask(taskId, options2) { - return this._server.getTask({ taskId }, options2); - } - async getTaskResult(taskId, resultSchema, options2) { - return this._server.getTaskResult({ taskId }, resultSchema, options2); - } - async listTasks(cursor, options2) { - return this._server.listTasks(cursor ? { cursor } : undefined, options2); - } - async cancelTask(taskId, options2) { - return this._server.cancelTask({ taskId }, options2); - } -} -var init_server2 = __esm(() => { - init_types17(); -}); - -// node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js -var Server; -var init_server3 = __esm(() => { - init_protocol(); - init_types17(); - init_ajv_provider(); - init_zod_compat(); - init_server2(); - Server = class Server extends Protocol { - constructor(_serverInfo, options2) { - super(options2); - this._serverInfo = _serverInfo; - this._loggingLevels = new Map; - this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index2) => [level, index2])); - this.isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - this._capabilities = options2?.capabilities ?? {}; - this._instructions = options2?.instructions; - this._jsonSchemaValidator = options2?.jsonSchemaValidator ?? new AjvJsonSchemaValidator; - this.setRequestHandler(InitializeRequestSchema, (request2) => this._oninitialize(request2)); - this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); - if (this._capabilities.logging) { - this.setRequestHandler(SetLevelRequestSchema, async (request2, extra) => { - const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || undefined; - const { level } = request2.params; - const parseResult = LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - get experimental() { - if (!this._experimental) { - this._experimental = { - tasks: new ExperimentalServerTasks(this) - }; - } - return this._experimental; - } - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error("Cannot register capabilities after connecting to transport"); - } - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - setRequestHandler(requestSchema, handler) { - const shape = getObjectShape(requestSchema); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error("Schema is missing a method literal"); - } - let methodValue; - if (isZ4Schema(methodSchema)) { - const v4Schema = methodSchema; - const v4Def = v4Schema._zod?.def; - methodValue = v4Def?.value ?? v4Schema.value; - } else { - const v3Schema = methodSchema; - const legacyDef = v3Schema._def; - methodValue = legacyDef?.value ?? v3Schema.value; - } - if (typeof methodValue !== "string") { - throw new Error("Schema method literal must be a string"); - } - const method = methodValue; - if (method === "tools/call") { - const wrappedHandler = async (request2, extra) => { - const validatedRequest = safeParse3(CallToolRequestSchema, request2); - if (!validatedRequest.success) { - const errorMessage4 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage4}`); - } - const { params } = validatedRequest.data; - const result = await Promise.resolve(handler(request2, extra)); - if (params.task) { - const taskValidationResult = safeParse3(CreateTaskResultSchema, result); - if (!taskValidationResult.success) { - const errorMessage4 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage4}`); - } - return taskValidationResult.data; - } - const validationResult = safeParse3(CallToolResultSchema, result); - if (!validationResult.success) { - const errorMessage4 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage4}`); - } - return validationResult.data; - }; - return super.setRequestHandler(requestSchema, wrappedHandler); - } - return super.setRequestHandler(requestSchema, handler); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case "roots/list": - if (!this._clientCapabilities?.roots) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - case "ping": - break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error(`Client does not support URL elicitation (required for ${method})`); - } - break; - case "notifications/cancelled": - break; - case "notifications/progress": - break; - } - } - assertRequestHandlerCapability(method) { - if (!this._capabilities) { - return; - } - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case "logging/setLevel": - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case "tasks/get": - case "tasks/list": - case "tasks/result": - case "tasks/cancel": - if (!this._capabilities.tasks) { - throw new Error(`Server does not support tasks capability (required for ${method})`); - } - break; - case "ping": - case "initialize": - break; - } - } - assertTaskCapability(method) { - assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client"); - } - assertTaskHandlerCapability(method) { - if (!this._capabilities) { - return; - } - assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server"); - } - async _oninitialize(request2) { - const requestedVersion = request2.params.protocolVersion; - this._clientCapabilities = request2.params.capabilities; - this._clientVersion = request2.params.clientInfo; - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - getClientCapabilities() { - return this._clientCapabilities; - } - getClientVersion() { - return this._clientVersion; - } - getCapabilities() { - return this._capabilities; - } - async ping() { - return this.request({ method: "ping" }, EmptyResultSchema); - } - async createMessage(params, options2) { - if (params.tools || params.toolChoice) { - if (!this._clientCapabilities?.sampling?.tools) { - throw new Error("Client does not support sampling tools capability."); - } - } - if (params.messages.length > 0) { - const lastMessage = params.messages[params.messages.length - 1]; - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c9) => c9.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c9) => c9.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c9) => c9.type !== "tool_result")) { - throw new Error("The last message must contain only tool_result content if any is present"); - } - if (!hasPreviousToolUse) { - throw new Error("tool_result blocks are not matching any tool_use from the previous message"); - } - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c9) => c9.type === "tool_use").map((c9) => c9.id)); - const toolResultIds = new Set(lastContent.filter((c9) => c9.type === "tool_result").map((c9) => c9.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { - throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - } - if (params.tools) { - return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options2); - } - return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options2); - } - async elicitInput(params, options2) { - const mode = params.mode ?? "form"; - switch (mode) { - case "url": { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error("Client does not support url elicitation."); - } - const urlParams = params; - return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options2); - } - case "form": { - if (!this._clientCapabilities?.elicitation?.form) { - throw new Error("Client does not support form elicitation."); - } - const formParams = params.mode === "form" ? params : { ...params, mode: "form" }; - const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options2); - if (result.action === "accept" && result.content && formParams.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); - const validationResult = validator(result.content); - if (!validationResult.valid) { - throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } - } catch (error46) { - if (error46 instanceof McpError) { - throw error46; - } - throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error46 instanceof Error ? error46.message : String(error46)}`); - } - } - return result; - } - } - } - createElicitationCompletionNotifier(elicitationId, options2) { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)"); - } - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { - elicitationId - } - }, options2); - } - async listRoots(params, options2) { - return this.request({ method: "roots/list", params }, ListRootsResultSchema, options2); - } - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: "notifications/message", params }); - } - } - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: "notifications/resources/list_changed" - }); - } - async sendToolListChanged() { - return this.notification({ method: "notifications/tools/list_changed" }); - } - async sendPromptListChanged() { - return this.notification({ method: "notifications/prompts/list_changed" }); - } - }; -}); - -// src/entrypoints/mcp.ts -var exports_mcp2 = {}; -__export(exports_mcp2, { - startMCPServer: () => startMCPServer -}); -async function startMCPServer(cwd3, debug3, verbose) { - const READ_FILE_STATE_CACHE_SIZE2 = 100; - const readFileStateCache = createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE2); - setCwd(cwd3); - const server = new Server({ - name: "claude/tengu", - version: MACRO.VERSION - }, { - capabilities: { - tools: {} - } - }); - server.setRequestHandler(ListToolsRequestSchema, async () => { - const toolPermissionContext = getEmptyToolPermissionContext(); - const tools = getTools(toolPermissionContext); - return { - tools: await Promise.all(tools.map(async (tool) => { - let outputSchema33; - if (tool.outputSchema) { - const convertedSchema = zodToJsonSchema3(tool.outputSchema); - if (typeof convertedSchema === "object" && convertedSchema !== null && "type" in convertedSchema && convertedSchema.type === "object") { - outputSchema33 = convertedSchema; - } - } - return { - ...tool, - description: await tool.prompt({ - getToolPermissionContext: async () => toolPermissionContext, - tools, - agents: [] - }), - inputSchema: zodToJsonSchema3(tool.inputSchema), - outputSchema: outputSchema33 - }; - })) - }; - }); - server.setRequestHandler(CallToolRequestSchema, async ({ params: { name: name3, arguments: args } }) => { - const toolPermissionContext = getEmptyToolPermissionContext(); - const tools = getTools(toolPermissionContext); - const tool = findToolByName(tools, name3); - if (!tool) { - throw new Error(`Tool ${name3} not found`); - } - const toolUseContext = { - abortController: createAbortController(), - options: { - commands: MCP_COMMANDS, - tools, - mainLoopModel: getMainLoopModel(), - thinkingConfig: { type: "disabled" }, - mcpClients: [], - mcpResources: {}, - isNonInteractiveSession: true, - debug: debug3, - verbose, - agentDefinitions: { activeAgents: [], allAgents: [] } - }, - getAppState: () => getDefaultAppState(), - setAppState: () => {}, - messages: [], - readFileState: readFileStateCache, - setInProgressToolUseIDs: () => {}, - setResponseLength: () => {}, - updateFileHistoryState: () => {}, - updateAttributionState: () => {} - }; - try { - if (!tool.isEnabled()) { - throw new Error(`Tool ${name3} is not enabled`); - } - const validationResult = await tool.validateInput?.(args ?? {}, toolUseContext); - if (validationResult && !validationResult.result) { - throw new Error(`Tool ${name3} input is invalid: ${validationResult.message}`); - } - const finalResult = await tool.call(args ?? {}, toolUseContext, hasPermissionsToUseTool, createAssistantMessage({ - content: [] - })); - return { - content: [ - { - type: "text", - text: typeof finalResult === "string" ? finalResult : jsonStringify(finalResult.data) - } - ] - }; - } catch (error46) { - logError2(error46); - const parts = error46 instanceof Error ? getErrorParts(error46) : [String(error46)]; - const errorText = parts.filter(Boolean).join(` -`).trim() || "Error"; - return { - isError: true, - content: [ - { - type: "text", - text: errorText - } - ] - }; - } - }); - async function runServer() { - const transport = new StdioServerTransport; - await server.connect(transport); - } - return await runServer(); -} -var MCP_COMMANDS; -var init_mcp4 = __esm(() => { - init_server3(); - init_stdio4(); - init_types17(); - init_AppStateStore(); - init_review(); - init_Tool(); - init_tools2(); - init_abortController(); - init_fileStateCache(); - init_log2(); - init_messages9(); - init_model(); - init_permissions2(); - init_Shell(); - init_slowOperations(); - init_toolErrors(); - init_zodToJsonSchema2(); - MCP_COMMANDS = [review_default]; -}); - -// src/utils/claudeDesktop.ts -var exports_claudeDesktop = {}; -__export(exports_claudeDesktop, { - readClaudeDesktopMcpServers: () => readClaudeDesktopMcpServers, - getClaudeDesktopConfigPath: () => getClaudeDesktopConfigPath -}); -import { readdir as readdir30, readFile as readFile59, stat as stat51 } from "fs/promises"; -import { homedir as homedir38 } from "os"; -import { join as join155 } from "path"; -async function getClaudeDesktopConfigPath() { - const platform6 = getPlatform(); - if (!SUPPORTED_PLATFORMS.includes(platform6)) { - throw new Error(`Unsupported platform: ${platform6} - Claude Desktop integration only works on macOS and WSL.`); - } - if (platform6 === "macos") { - return join155(homedir38(), "Library", "Application Support", "Claude", "claude_desktop_config.json"); - } - const windowsHome = process.env.USERPROFILE ? process.env.USERPROFILE.replace(/\\/g, "/") : null; - if (windowsHome) { - const wslPath = windowsHome.replace(/^[A-Z]:/, ""); - const configPath = `/mnt/c${wslPath}/AppData/Roaming/Claude/claude_desktop_config.json`; - try { - await stat51(configPath); - return configPath; - } catch {} - } - try { - const usersDir = "/mnt/c/Users"; - try { - const userDirs = await readdir30(usersDir, { withFileTypes: true }); - for (const user of userDirs) { - if (user.name === "Public" || user.name === "Default" || user.name === "Default User" || user.name === "All Users") { - continue; - } - const potentialConfigPath = join155(usersDir, user.name, "AppData", "Roaming", "Claude", "claude_desktop_config.json"); - try { - await stat51(potentialConfigPath); - return potentialConfigPath; - } catch {} - } - } catch {} - } catch (dirError) { - logError2(dirError); - } - throw new Error("Could not find Claude Desktop config file in Windows. Make sure Claude Desktop is installed on Windows."); -} -async function readClaudeDesktopMcpServers() { - if (!SUPPORTED_PLATFORMS.includes(getPlatform())) { - throw new Error("Unsupported platform - Claude Desktop integration only works on macOS and WSL."); - } - try { - const configPath = await getClaudeDesktopConfigPath(); - let configContent; - try { - configContent = await readFile59(configPath, { encoding: "utf8" }); - } catch (e4) { - const code = getErrnoCode(e4); - if (code === "ENOENT") { - return {}; - } - throw e4; - } - const config10 = safeParseJSON(configContent); - if (!config10 || typeof config10 !== "object") { - return {}; - } - const mcpServers = config10.mcpServers; - if (!mcpServers || typeof mcpServers !== "object") { - return {}; - } - const servers = {}; - for (const [name3, serverConfig] of Object.entries(mcpServers)) { - if (!serverConfig || typeof serverConfig !== "object") { - continue; - } - const result = McpStdioServerConfigSchema().safeParse(serverConfig); - if (result.success) { - servers[name3] = result.data; - } - } - return servers; - } catch (error46) { - logError2(error46); - return {}; - } -} -var init_claudeDesktop = __esm(() => { - init_types(); - init_errors(); - init_json(); - init_log2(); - init_platform2(); -}); - -// src/cli/handlers/mcp.tsx -var exports_mcp3 = {}; -__export(exports_mcp3, { - mcpServeHandler: () => mcpServeHandler, - mcpResetChoicesHandler: () => mcpResetChoicesHandler, - mcpRemoveHandler: () => mcpRemoveHandler, - mcpListHandler: () => mcpListHandler, - mcpGetHandler: () => mcpGetHandler, - mcpAddJsonHandler: () => mcpAddJsonHandler, - mcpAddFromDesktopHandler: () => mcpAddFromDesktopHandler -}); -import { stat as stat52 } from "fs/promises"; -import { cwd as cwd3 } from "process"; -async function checkMcpServerHealth(name3, server) { - try { - const result = await connectToServer(name3, server); - if (result.type === "connected") { - return "\u2713 Connected"; - } else if (result.type === "needs-auth") { - return "! Needs authentication"; - } else { - return "\u2717 Failed to connect"; - } - } catch (_error) { - return "\u2717 Connection error"; - } -} -async function mcpServeHandler({ - debug: debug3, - verbose -}) { - const providedCwd = cwd3(); - logEvent("tengu_mcp_start", {}); - try { - await stat52(providedCwd); - } catch (error46) { - if (isFsInaccessible(error46)) { - cliError(`Error: Directory ${providedCwd} does not exist`); - } - throw error46; - } - try { - const { - setup: setup2 - } = await Promise.resolve().then(() => (init_setup3(), exports_setup)); - await setup2(providedCwd, "default", false, false, undefined, false); - const { - startMCPServer: startMCPServer2 - } = await Promise.resolve().then(() => (init_mcp4(), exports_mcp2)); - await startMCPServer2(providedCwd, debug3 ?? false, verbose ?? false); - } catch (error46) { - cliError(`Error: Failed to start MCP server: ${error46}`); - } -} -async function mcpRemoveHandler(name3, options2) { - const serverBeforeRemoval = getMcpConfigByName(name3); - const cleanupSecureStorage = () => { - if (serverBeforeRemoval && (serverBeforeRemoval.type === "sse" || serverBeforeRemoval.type === "http")) { - clearServerTokensFromLocalStorage(name3, serverBeforeRemoval); - clearMcpClientConfig(name3, serverBeforeRemoval); - } - }; - try { - if (options2.scope) { - const scope = ensureConfigScope(options2.scope); - logEvent("tengu_mcp_delete", { - name: name3, - scope - }); - await removeMcpConfig(name3, scope); - cleanupSecureStorage(); - process.stdout.write(`Removed MCP server ${name3} from ${scope} config -`); - cliOk(`File modified: ${describeMcpConfigFilePath(scope)}`); - } - const projectConfig = getCurrentProjectConfig(); - const globalConfig2 = getGlobalConfig(); - const { - servers: projectServers - } = getMcpConfigsByScope("project"); - const mcpJsonExists = !!projectServers[name3]; - const scopes = []; - if (projectConfig.mcpServers?.[name3]) - scopes.push("local"); - if (mcpJsonExists) - scopes.push("project"); - if (globalConfig2.mcpServers?.[name3]) - scopes.push("user"); - if (scopes.length === 0) { - cliError(`No MCP server found with name: "${name3}"`); - } else if (scopes.length === 1) { - const scope = scopes[0]; - logEvent("tengu_mcp_delete", { - name: name3, - scope - }); - await removeMcpConfig(name3, scope); - cleanupSecureStorage(); - process.stdout.write(`Removed MCP server "${name3}" from ${scope} config -`); - cliOk(`File modified: ${describeMcpConfigFilePath(scope)}`); - } else { - process.stderr.write(`MCP server "${name3}" exists in multiple scopes: -`); - scopes.forEach((scope) => { - process.stderr.write(` - ${getScopeLabel(scope)} (${describeMcpConfigFilePath(scope)}) -`); - }); - process.stderr.write(` -To remove from a specific scope, use: -`); - scopes.forEach((scope) => { - process.stderr.write(` claude mcp remove "${name3}" -s ${scope} -`); - }); - cliError(); - } - } catch (error46) { - cliError(error46.message); - } -} -async function mcpListHandler() { - logEvent("tengu_mcp_list", {}); - const { - servers: configs - } = await getAllMcpConfigs(); - if (Object.keys(configs).length === 0) { - console.log("No MCP servers configured. Use `claude mcp add` to add a server."); - } else { - console.log(`Checking MCP server health... -`); - const entries = Object.entries(configs); - const results = await pMap(entries, async ([name3, server]) => ({ - name: name3, - server, - status: await checkMcpServerHealth(name3, server) - }), { - concurrency: getMcpServerConnectionBatchSize() - }); - for (const { - name: name3, - server, - status: status2 - } of results) { - if (server.type === "sse") { - console.log(`${name3}: ${server.url} (SSE) - ${status2}`); - } else if (server.type === "http") { - console.log(`${name3}: ${server.url} (HTTP) - ${status2}`); - } else if (server.type === "claudeai-proxy") { - console.log(`${name3}: ${server.url} - ${status2}`); - } else if (!server.type || server.type === "stdio") { - const args = Array.isArray(server.args) ? server.args : []; - console.log(`${name3}: ${server.command} ${args.join(" ")} - ${status2}`); - } - } - } - await gracefulShutdown(0); -} -async function mcpGetHandler(name3) { - logEvent("tengu_mcp_get", { - name: name3 - }); - const server = getMcpConfigByName(name3); - if (!server) { - cliError(`No MCP server found with name: ${name3}`); - } - console.log(`${name3}:`); - console.log(` Scope: ${getScopeLabel(server.scope)}`); - const status2 = await checkMcpServerHealth(name3, server); - console.log(` Status: ${status2}`); - if (server.type === "sse") { - console.log(` Type: sse`); - console.log(` URL: ${server.url}`); - if (server.headers) { - console.log(" Headers:"); - for (const [key2, value] of Object.entries(server.headers)) { - console.log(` ${key2}: ${value}`); - } - } - if (server.oauth?.clientId || server.oauth?.callbackPort) { - const parts = []; - if (server.oauth.clientId) { - parts.push("client_id configured"); - const clientConfig = getMcpClientConfig(name3, server); - if (clientConfig?.clientSecret) - parts.push("client_secret configured"); - } - if (server.oauth.callbackPort) - parts.push(`callback_port ${server.oauth.callbackPort}`); - console.log(` OAuth: ${parts.join(", ")}`); - } - } else if (server.type === "http") { - console.log(` Type: http`); - console.log(` URL: ${server.url}`); - if (server.headers) { - console.log(" Headers:"); - for (const [key2, value] of Object.entries(server.headers)) { - console.log(` ${key2}: ${value}`); - } - } - if (server.oauth?.clientId || server.oauth?.callbackPort) { - const parts = []; - if (server.oauth.clientId) { - parts.push("client_id configured"); - const clientConfig = getMcpClientConfig(name3, server); - if (clientConfig?.clientSecret) - parts.push("client_secret configured"); - } - if (server.oauth.callbackPort) - parts.push(`callback_port ${server.oauth.callbackPort}`); - console.log(` OAuth: ${parts.join(", ")}`); - } - } else if (server.type === "stdio") { - console.log(` Type: stdio`); - console.log(` Command: ${server.command}`); - const args = Array.isArray(server.args) ? server.args : []; - console.log(` Args: ${args.join(" ")}`); - if (server.env) { - console.log(" Environment:"); - for (const [key2, value] of Object.entries(server.env)) { - console.log(` ${key2}=${value}`); - } - } - } - console.log(` -To remove this server, run: claude mcp remove "${name3}" -s ${server.scope}`); - await gracefulShutdown(0); -} -async function mcpAddJsonHandler(name3, json2, options2) { - try { - const scope = ensureConfigScope(options2.scope); - const parsedJson = safeParseJSON(json2); - const needsSecret = options2.clientSecret && parsedJson && typeof parsedJson === "object" && "type" in parsedJson && (parsedJson.type === "sse" || parsedJson.type === "http") && "url" in parsedJson && typeof parsedJson.url === "string" && "oauth" in parsedJson && parsedJson.oauth && typeof parsedJson.oauth === "object" && "clientId" in parsedJson.oauth; - const clientSecret = needsSecret ? await readClientSecret() : undefined; - await addMcpConfig(name3, parsedJson, scope); - const transportType = parsedJson && typeof parsedJson === "object" && "type" in parsedJson ? String(parsedJson.type || "stdio") : "stdio"; - if (clientSecret && parsedJson && typeof parsedJson === "object" && "type" in parsedJson && (parsedJson.type === "sse" || parsedJson.type === "http") && "url" in parsedJson && typeof parsedJson.url === "string") { - saveMcpClientSecret(name3, { - type: parsedJson.type, - url: parsedJson.url - }, clientSecret); - } - logEvent("tengu_mcp_add", { - scope, - source: "json", - type: transportType - }); - cliOk(`Added ${transportType} MCP server ${name3} to ${scope} config`); - } catch (error46) { - cliError(error46.message); - } -} -async function mcpAddFromDesktopHandler(options2) { - try { - const scope = ensureConfigScope(options2.scope); - const platform6 = getPlatform(); - logEvent("tengu_mcp_add", { - scope, - platform: platform6, - source: "desktop" - }); - const { - readClaudeDesktopMcpServers: readClaudeDesktopMcpServers2 - } = await Promise.resolve().then(() => (init_claudeDesktop(), exports_claudeDesktop)); - const servers = await readClaudeDesktopMcpServers2(); - if (Object.keys(servers).length === 0) { - cliOk("No MCP servers found in Claude Desktop configuration or configuration file does not exist."); - } - const { - unmount - } = await render(/* @__PURE__ */ jsx_dev_runtime491.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime491.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime491.jsxDEV(MCPServerDesktopImportDialog, { - servers, - scope, - onDone: () => { - unmount(); - } - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this), { - exitOnCtrlC: true - }); - } catch (error46) { - cliError(error46.message); - } -} -async function mcpResetChoicesHandler() { - logEvent("tengu_mcp_reset_mcpjson_choices", {}); - saveCurrentProjectConfig((current) => ({ - ...current, - enabledMcpjsonServers: [], - disabledMcpjsonServers: [], - enableAllProjectMcpServers: false - })); - cliOk(`All project-scoped (.mcp.json) server approvals and rejections have been reset. -You will be prompted for approval next time you start Claude Code.`); -} -var jsx_dev_runtime491; -var init_mcp5 = __esm(() => { - init_p_map(); - init_MCPServerDesktopImportDialog(); - init_ink2(); - init_KeybindingProviderSetup(); - init_analytics(); - init_auth18(); - init_client22(); - init_config9(); - init_utils8(); - init_AppState(); - init_config(); - init_errors(); - init_gracefulShutdown(); - init_json(); - init_platform2(); - jsx_dev_runtime491 = __toESM(require_jsx_dev_runtime(), 1); -}); - -// src/cli/handlers/plugins.ts -var exports_plugins = {}; -__export(exports_plugins, { - pluginValidateHandler: () => pluginValidateHandler, - pluginUpdateHandler: () => pluginUpdateHandler, - pluginUninstallHandler: () => pluginUninstallHandler, - pluginListHandler: () => pluginListHandler, - pluginInstallHandler: () => pluginInstallHandler, - pluginEnableHandler: () => pluginEnableHandler, - pluginDisableHandler: () => pluginDisableHandler, - marketplaceUpdateHandler: () => marketplaceUpdateHandler, - marketplaceRemoveHandler: () => marketplaceRemoveHandler, - marketplaceListHandler: () => marketplaceListHandler, - marketplaceAddHandler: () => marketplaceAddHandler, - handleMarketplaceError: () => handleMarketplaceError, - VALID_UPDATE_SCOPES: () => VALID_UPDATE_SCOPES, - VALID_INSTALLABLE_SCOPES: () => VALID_INSTALLABLE_SCOPES -}); -import { basename as basename58, dirname as dirname64 } from "path"; -function handleMarketplaceError(error46, action2) { - logError2(error46); - cliError(`${figures_default.cross} Failed to ${action2}: ${errorMessage(error46)}`); -} -function printValidationResult(result) { - if (result.errors.length > 0) { - console.log(`${figures_default.cross} Found ${result.errors.length} ${plural(result.errors.length, "error")}: -`); - result.errors.forEach((error46) => { - console.log(` ${figures_default.pointer} ${error46.path}: ${error46.message}`); - }); - console.log(""); - } - if (result.warnings.length > 0) { - console.log(`${figures_default.warning} Found ${result.warnings.length} ${plural(result.warnings.length, "warning")}: -`); - result.warnings.forEach((warning) => { - console.log(` ${figures_default.pointer} ${warning.path}: ${warning.message}`); - }); - console.log(""); - } -} -async function pluginValidateHandler(manifestPath, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - try { - const result = await validateManifest3(manifestPath); - console.log(`Validating ${result.fileType} manifest: ${result.filePath} -`); - printValidationResult(result); - let contentResults = []; - if (result.fileType === "plugin") { - const manifestDir = dirname64(result.filePath); - if (basename58(manifestDir) === ".claude-plugin") { - contentResults = await validatePluginContents(dirname64(manifestDir)); - for (const r4 of contentResults) { - console.log(`Validating ${r4.fileType}: ${r4.filePath} -`); - printValidationResult(r4); - } - } - } - const allSuccess = result.success && contentResults.every((r4) => r4.success); - const hasWarnings = result.warnings.length > 0 || contentResults.some((r4) => r4.warnings.length > 0); - if (allSuccess) { - cliOk(hasWarnings ? `${figures_default.tick} Validation passed with warnings` : `${figures_default.tick} Validation passed`); - } else { - console.log(`${figures_default.cross} Validation failed`); - process.exit(1); - } - } catch (error46) { - logError2(error46); - console.error(`${figures_default.cross} Unexpected error during validation: ${errorMessage(error46)}`); - process.exit(2); - } -} -async function pluginListHandler(options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - logEvent("tengu_plugin_list_command", {}); - const installedData = loadInstalledPluginsV2(); - const { getPluginEditableScopes: getPluginEditableScopes2 } = await Promise.resolve().then(() => (init_pluginStartupCheck(), exports_pluginStartupCheck)); - const enabledPlugins = getPluginEditableScopes2(); - const pluginIds = Object.keys(installedData.plugins); - const { - enabled: loadedEnabled, - disabled: loadedDisabled, - errors: loadErrors - } = await loadAllPlugins(); - const allLoadedPlugins = [...loadedEnabled, ...loadedDisabled]; - const inlinePlugins = allLoadedPlugins.filter((p4) => p4.source.endsWith("@inline")); - const inlineLoadErrors = loadErrors.filter((e4) => e4.source.endsWith("@inline") || e4.source.startsWith("inline[")); - if (options2.json) { - const loadedPluginMap = new Map(allLoadedPlugins.map((p4) => [p4.source, p4])); - const plugins = []; - for (const pluginId of pluginIds.sort()) { - const installations = installedData.plugins[pluginId]; - if (!installations || installations.length === 0) - continue; - const pluginName = parsePluginIdentifier(pluginId).name; - const pluginErrors = loadErrors.filter((e4) => e4.source === pluginId || ("plugin" in e4) && e4.plugin === pluginName).map(getPluginErrorMessage); - for (const installation of installations) { - const loadedPlugin = loadedPluginMap.get(pluginId); - let mcpServers; - if (loadedPlugin) { - const servers = loadedPlugin.mcpServers || await loadPluginMcpServers(loadedPlugin); - if (servers && Object.keys(servers).length > 0) { - mcpServers = servers; - } - } - plugins.push({ - id: pluginId, - version: installation.version || "unknown", - scope: installation.scope, - enabled: enabledPlugins.has(pluginId), - installPath: installation.installPath, - installedAt: installation.installedAt, - lastUpdated: installation.lastUpdated, - projectPath: installation.projectPath, - mcpServers, - errors: pluginErrors.length > 0 ? pluginErrors : undefined - }); - } - } - for (const p4 of inlinePlugins) { - const servers = p4.mcpServers || await loadPluginMcpServers(p4); - const pErrors = inlineLoadErrors.filter((e4) => e4.source === p4.source || ("plugin" in e4) && e4.plugin === p4.name).map(getPluginErrorMessage); - plugins.push({ - id: p4.source, - version: p4.manifest.version ?? "unknown", - scope: "session", - enabled: p4.enabled !== false, - installPath: p4.path, - mcpServers: servers && Object.keys(servers).length > 0 ? servers : undefined, - errors: pErrors.length > 0 ? pErrors : undefined - }); - } - for (const e4 of inlineLoadErrors.filter((e5) => e5.source.startsWith("inline["))) { - plugins.push({ - id: e4.source, - version: "unknown", - scope: "session", - enabled: false, - installPath: "path" in e4 ? e4.path : "", - errors: [getPluginErrorMessage(e4)] - }); - } - if (options2.available) { - const available = []; - try { - const [config10, installCounts] = await Promise.all([ - loadKnownMarketplacesConfig(), - getInstallCounts() - ]); - const { marketplaces } = await loadMarketplacesWithGracefulDegradation(config10); - for (const { - name: marketplaceName, - data: marketplace - } of marketplaces) { - if (marketplace) { - for (const entry of marketplace.plugins) { - const pluginId = createPluginId(entry.name, marketplaceName); - if (!isPluginInstalled(pluginId)) { - available.push({ - pluginId, - name: entry.name, - description: entry.description, - marketplaceName, - version: entry.version, - source: entry.source, - installCount: installCounts?.get(pluginId) - }); - } - } - } - } - } catch {} - cliOk(jsonStringify({ installed: plugins, available }, null, 2)); - } else { - cliOk(jsonStringify(plugins, null, 2)); - } - } - if (pluginIds.length === 0 && inlinePlugins.length === 0) { - if (inlineLoadErrors.length === 0) { - cliOk("No plugins installed. Use `claude plugin install` to install a plugin."); - } - } - if (pluginIds.length > 0) { - console.log(`Installed plugins: -`); - } - for (const pluginId of pluginIds.sort()) { - const installations = installedData.plugins[pluginId]; - if (!installations || installations.length === 0) - continue; - const pluginName = parsePluginIdentifier(pluginId).name; - const pluginErrors = loadErrors.filter((e4) => e4.source === pluginId || ("plugin" in e4) && e4.plugin === pluginName); - for (const installation of installations) { - const isEnabled2 = enabledPlugins.has(pluginId); - const status2 = pluginErrors.length > 0 ? `${figures_default.cross} failed to load` : isEnabled2 ? `${figures_default.tick} enabled` : `${figures_default.cross} disabled`; - const version7 = installation.version || "unknown"; - const scope = installation.scope; - console.log(` ${figures_default.pointer} ${pluginId}`); - console.log(` Version: ${version7}`); - console.log(` Scope: ${scope}`); - console.log(` Status: ${status2}`); - for (const error46 of pluginErrors) { - console.log(` Error: ${getPluginErrorMessage(error46)}`); - } - console.log(""); - } - } - if (inlinePlugins.length > 0 || inlineLoadErrors.length > 0) { - console.log(`Session-only plugins (--plugin-dir): -`); - for (const p4 of inlinePlugins) { - const pErrors = inlineLoadErrors.filter((e4) => e4.source === p4.source || ("plugin" in e4) && e4.plugin === p4.name); - const status2 = pErrors.length > 0 ? `${figures_default.cross} loaded with errors` : `${figures_default.tick} loaded`; - console.log(` ${figures_default.pointer} ${p4.source}`); - console.log(` Version: ${p4.manifest.version ?? "unknown"}`); - console.log(` Path: ${p4.path}`); - console.log(` Status: ${status2}`); - for (const e4 of pErrors) { - console.log(` Error: ${getPluginErrorMessage(e4)}`); - } - console.log(""); - } - for (const e4 of inlineLoadErrors.filter((e5) => e5.source.startsWith("inline["))) { - console.log(` ${figures_default.pointer} ${e4.source}: ${figures_default.cross} ${getPluginErrorMessage(e4)} -`); - } - } - cliOk(); -} -async function marketplaceAddHandler(source, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - try { - const parsed = await parseMarketplaceInput(source); - if (!parsed) { - cliError(`${figures_default.cross} Invalid marketplace source format. Try: owner/repo, https://..., or ./path`); - } - if ("error" in parsed) { - cliError(`${figures_default.cross} ${parsed.error}`); - } - const scope = options2.scope ?? "user"; - if (scope !== "user" && scope !== "project" && scope !== "local") { - cliError(`${figures_default.cross} Invalid scope '${scope}'. Use: user, project, or local`); - } - const settingSource = scopeToSettingSource(scope); - let marketplaceSource = parsed; - if (options2.sparse && options2.sparse.length > 0) { - if (marketplaceSource.source === "github" || marketplaceSource.source === "git") { - marketplaceSource = { - ...marketplaceSource, - sparsePaths: options2.sparse - }; - } else { - cliError(`${figures_default.cross} --sparse is only supported for github and git marketplace sources (got: ${marketplaceSource.source})`); - } - } - console.log("Adding marketplace..."); - const { name: name3, alreadyMaterialized, resolvedSource } = await addMarketplaceSource(marketplaceSource, (message) => { - console.log(message); - }); - saveMarketplaceToSettings(name3, { source: resolvedSource }, settingSource); - clearAllCaches(); - let sourceType = marketplaceSource.source; - if (marketplaceSource.source === "github") { - sourceType = marketplaceSource.repo; - } - logEvent("tengu_marketplace_added", { - source_type: sourceType - }); - cliOk(alreadyMaterialized ? `${figures_default.tick} Marketplace '${name3}' already on disk \u2014 declared in ${scope} settings` : `${figures_default.tick} Successfully added marketplace: ${name3} (declared in ${scope} settings)`); - } catch (error46) { - handleMarketplaceError(error46, "add marketplace"); - } -} -async function marketplaceListHandler(options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - try { - const config10 = await loadKnownMarketplacesConfig(); - const names = Object.keys(config10); - if (options2.json) { - const marketplaces = names.sort().map((name3) => { - const marketplace = config10[name3]; - const source = marketplace?.source; - return { - name: name3, - source: source?.source, - ...source?.source === "github" && { repo: source.repo }, - ...source?.source === "git" && { url: source.url }, - ...source?.source === "url" && { url: source.url }, - ...source?.source === "directory" && { path: source.path }, - ...source?.source === "file" && { path: source.path }, - installLocation: marketplace?.installLocation - }; - }); - cliOk(jsonStringify(marketplaces, null, 2)); - } - if (names.length === 0) { - cliOk("No marketplaces configured"); - } - console.log(`Configured marketplaces: -`); - names.forEach((name3) => { - const marketplace = config10[name3]; - console.log(` ${figures_default.pointer} ${name3}`); - if (marketplace?.source) { - const src = marketplace.source; - if (src.source === "github") { - console.log(` Source: GitHub (${src.repo})`); - } else if (src.source === "git") { - console.log(` Source: Git (${src.url})`); - } else if (src.source === "url") { - console.log(` Source: URL (${src.url})`); - } else if (src.source === "directory") { - console.log(` Source: Directory (${src.path})`); - } else if (src.source === "file") { - console.log(` Source: File (${src.path})`); - } - } - console.log(""); - }); - cliOk(); - } catch (error46) { - handleMarketplaceError(error46, "list marketplaces"); - } -} -async function marketplaceRemoveHandler(name3, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - try { - await removeMarketplaceSource(name3); - clearAllCaches(); - logEvent("tengu_marketplace_removed", { - marketplace_name: name3 - }); - cliOk(`${figures_default.tick} Successfully removed marketplace: ${name3}`); - } catch (error46) { - handleMarketplaceError(error46, "remove marketplace"); - } -} -async function marketplaceUpdateHandler(name3, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - try { - if (name3) { - console.log(`Updating marketplace: ${name3}...`); - await refreshMarketplace(name3, (message) => { - console.log(message); - }); - clearAllCaches(); - logEvent("tengu_marketplace_updated", { - marketplace_name: name3 - }); - cliOk(`${figures_default.tick} Successfully updated marketplace: ${name3}`); - } else { - const config10 = await loadKnownMarketplacesConfig(); - const marketplaceNames = Object.keys(config10); - if (marketplaceNames.length === 0) { - cliOk("No marketplaces configured"); - } - console.log(`Updating ${marketplaceNames.length} marketplace(s)...`); - await refreshAllMarketplaces(); - clearAllCaches(); - logEvent("tengu_marketplace_updated_all", { - count: marketplaceNames.length - }); - cliOk(`${figures_default.tick} Successfully updated ${marketplaceNames.length} marketplace(s)`); - } - } catch (error46) { - handleMarketplaceError(error46, "update marketplace(s)"); - } -} -async function pluginInstallHandler(plugin2, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - const scope = options2.scope || "user"; - if (options2.cowork && scope !== "user") { - cliError("--cowork can only be used with user scope"); - } - if (!VALID_INSTALLABLE_SCOPES.includes(scope)) { - cliError(`Invalid scope: ${scope}. Must be one of: ${VALID_INSTALLABLE_SCOPES.join(", ")}.`); - } - const { name: name3, marketplace } = parsePluginIdentifier(plugin2); - logEvent("tengu_plugin_install_command", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope - }); - await installPlugin(plugin2, scope); -} -async function pluginUninstallHandler(plugin2, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - const scope = options2.scope || "user"; - if (options2.cowork && scope !== "user") { - cliError("--cowork can only be used with user scope"); - } - if (!VALID_INSTALLABLE_SCOPES.includes(scope)) { - cliError(`Invalid scope: ${scope}. Must be one of: ${VALID_INSTALLABLE_SCOPES.join(", ")}.`); - } - const { name: name3, marketplace } = parsePluginIdentifier(plugin2); - logEvent("tengu_plugin_uninstall_command", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope - }); - await uninstallPlugin(plugin2, scope, options2.keepData); -} -async function pluginEnableHandler(plugin2, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - let scope; - if (options2.scope) { - if (!VALID_INSTALLABLE_SCOPES.includes(options2.scope)) { - cliError(`Invalid scope "${options2.scope}". Valid scopes: ${VALID_INSTALLABLE_SCOPES.join(", ")}`); - } - scope = options2.scope; - } - if (options2.cowork && scope !== undefined && scope !== "user") { - cliError("--cowork can only be used with user scope"); - } - if (options2.cowork && scope === undefined) { - scope = "user"; - } - const { name: name3, marketplace } = parsePluginIdentifier(plugin2); - logEvent("tengu_plugin_enable_command", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope: scope ?? "auto" - }); - await enablePlugin(plugin2, scope); -} -async function pluginDisableHandler(plugin2, options2) { - if (options2.all && plugin2) { - cliError("Cannot use --all with a specific plugin"); - } - if (!options2.all && !plugin2) { - cliError("Please specify a plugin name or use --all to disable all plugins"); - } - if (options2.cowork) - setUseCoworkPlugins(true); - if (options2.all) { - if (options2.scope) { - cliError("Cannot use --scope with --all"); - } - logEvent("tengu_plugin_disable_command", {}); - await disableAllPlugins(); - return; - } - let scope; - if (options2.scope) { - if (!VALID_INSTALLABLE_SCOPES.includes(options2.scope)) { - cliError(`Invalid scope "${options2.scope}". Valid scopes: ${VALID_INSTALLABLE_SCOPES.join(", ")}`); - } - scope = options2.scope; - } - if (options2.cowork && scope !== undefined && scope !== "user") { - cliError("--cowork can only be used with user scope"); - } - if (options2.cowork && scope === undefined) { - scope = "user"; - } - const { name: name3, marketplace } = parsePluginIdentifier(plugin2); - logEvent("tengu_plugin_disable_command", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - }, - scope: scope ?? "auto" - }); - await disablePlugin(plugin2, scope); -} -async function pluginUpdateHandler(plugin2, options2) { - if (options2.cowork) - setUseCoworkPlugins(true); - const { name: name3, marketplace } = parsePluginIdentifier(plugin2); - logEvent("tengu_plugin_update_command", { - _PROTO_plugin_name: name3, - ...marketplace && { - _PROTO_marketplace_name: marketplace - } - }); - let scope = "user"; - if (options2.scope) { - if (!VALID_UPDATE_SCOPES.includes(options2.scope)) { - cliError(`Invalid scope "${options2.scope}". Valid scopes: ${VALID_UPDATE_SCOPES.join(", ")}`); - } - scope = options2.scope; - } - if (options2.cowork && scope !== "user") { - cliError("--cowork can only be used with user scope"); - } - await updatePluginCli(plugin2, scope); -} -var init_plugins = __esm(() => { - init_figures(); - init_state(); - init_analytics(); - init_pluginCliCommands(); - init_errors(); - init_log2(); - init_cacheUtils(); - init_installCounts(); - init_installedPluginsManager(); - init_marketplaceHelpers(); - init_marketplaceManager(); - init_mcpPluginIntegration(); - init_parseMarketplaceInput(); - init_pluginIdentifier(); - init_pluginLoader(); - init_validatePlugin(); - init_slowOperations(); - init_stringUtils(); -}); - -// src/commands/install.tsx -var exports_install = {}; -__export(exports_install, { - install: () => install -}); -import { homedir as homedir39 } from "os"; -import { join as join156 } from "path"; -function getInstallationPath2() { - const isWindows3 = env2.platform === "win32"; - const homeDir = homedir39(); - if (isWindows3) { - const windowsPath = join156(homeDir, ".local", "bin", "claude.exe"); - return windowsPath.replace(/\//g, "\\"); - } - return "~/.local/bin/claude"; -} -function SetupNotes(t0) { - const $2 = import_compiler_runtime388.c(5); - const { - messages - } = t0; - if (messages.length === 0) { - return null; - } - let t1; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t1 = /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - children: /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "warning", - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(StatusIcon, { - status: "warning", - withSpace: true - }, undefined, false, undefined, this), - "Setup notes:" - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this); - $2[0] = t1; - } else { - t1 = $2[0]; - } - let t22; - if ($2[1] !== messages) { - t22 = messages.map(_temp309); - $2[1] = messages; - $2[2] = t22; - } else { - t22 = $2[2]; - } - let t32; - if ($2[3] !== t22) { - t32 = /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 0, - marginBottom: 1, - children: [ - t1, - t22 - ] - }, undefined, true, undefined, this); - $2[3] = t22; - $2[4] = t32; - } else { - t32 = $2[4]; - } - return t32; -} -function _temp309(message, index2) { - return /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - marginLeft: 2, - children: /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - dimColor: true, - children: [ - "\u2022 ", - message - ] - }, undefined, true, undefined, this) - }, index2, false, undefined, this); -} -function Install({ - onDone, - force, - target -}) { - const [state4, setState] = import_react334.useState({ - type: "checking" - }); - import_react334.useEffect(() => { - async function run() { - try { - logForDebugging(`Install: Starting installation process (force=${force}, target=${target})`); - const channelOrVersion = target || getInitialSettings()?.autoUpdatesChannel || "latest"; - setState({ - type: "installing", - version: channelOrVersion - }); - logForDebugging(`Install: Calling installLatest(channelOrVersion=${channelOrVersion}, forceReinstall=${force})`); - const result = await installLatest(channelOrVersion, force); - logForDebugging(`Install: installLatest returned version=${result.latestVersion}, wasUpdated=${result.wasUpdated}, lockFailed=${result.lockFailed}`); - if (result.lockFailed) { - throw new Error("Could not install - another process is currently installing Claude. Please try again in a moment."); - } - if (!result.latestVersion) { - logForDebugging("Install: Failed to retrieve version information during install", { - level: "error" - }); - } - if (!result.wasUpdated) { - logForDebugging("Install: Already up to date"); - } - setState({ - type: "setting-up" - }); - const setupMessages = await checkInstall(true); - logForDebugging(`Install: Setup launcher completed with ${setupMessages.length} messages`); - if (setupMessages.length > 0) { - setupMessages.forEach((msg) => logForDebugging(`Install: Setup message: ${msg.message}`)); - } - logForDebugging("Install: Cleaning up npm installations after successful install"); - const { - removed, - errors: errors8, - warnings - } = await cleanupNpmInstallations(); - if (removed > 0) { - logForDebugging(`Cleaned up ${removed} npm installation(s)`); - } - if (errors8.length > 0) { - logForDebugging(`Cleanup errors: ${errors8.join(", ")}`); - } - const aliasMessages = await cleanupShellAliases(); - if (aliasMessages.length > 0) { - logForDebugging(`Shell alias cleanup: ${aliasMessages.map((m4) => m4.message).join("; ")}`); - } - logEvent("tengu_claude_install_command", { - has_version: result.latestVersion ? 1 : 0, - forced: force ? 1 : 0 - }); - if (target === "latest" || target === "stable") { - updateSettingsForSource("userSettings", { - autoUpdatesChannel: target - }); - logForDebugging(`Install: Saved autoUpdatesChannel=${target} to user settings`); - } - const allWarnings = [...warnings, ...aliasMessages.map((m_0) => m_0.message)]; - if (setupMessages.length > 0) { - setState({ - type: "set-up", - messages: setupMessages.map((m_1) => m_1.message) - }); - setTimeout(setState, 2000, { - type: "success", - version: result.latestVersion || "current", - setupMessages: [...setupMessages.map((m_2) => m_2.message), ...allWarnings] - }); - } else { - logForDebugging("Install: Shell PATH already configured"); - setState({ - type: "success", - version: result.latestVersion || "current", - setupMessages: allWarnings.length > 0 ? allWarnings : undefined - }); - } - } catch (error46) { - logForDebugging(`Install command failed: ${error46}`, { - level: "error" - }); - setState({ - type: "error", - message: errorMessage(error46) - }); - } - } - run(); - }, [force, target]); - import_react334.useEffect(() => { - if (state4.type === "success") { - setTimeout(onDone, 2000, "Claude Code installation completed successfully", { - display: "system" - }); - } else if (state4.type === "error") { - setTimeout(onDone, 3000, "Claude Code installation failed", { - display: "system" - }); - } - }, [state4, onDone]); - return /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - flexDirection: "column", - marginTop: 1, - children: [ - state4.type === "checking" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "claude", - children: "Checking installation status..." - }, undefined, false, undefined, this), - state4.type === "cleaning-npm" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "warning", - children: "Cleaning up old npm installations..." - }, undefined, false, undefined, this), - state4.type === "installing" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "claude", - children: [ - "Installing Claude Code native build ", - state4.version, - "..." - ] - }, undefined, true, undefined, this), - state4.type === "setting-up" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "claude", - children: "Setting up launcher and shell integration..." - }, undefined, false, undefined, this), - state4.type === "set-up" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(SetupNotes, { - messages: state4.messages - }, undefined, false, undefined, this), - state4.type === "success" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(StatusIcon, { - status: "success", - withSpace: true - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "success", - bold: true, - children: "Claude Code successfully installed!" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - marginLeft: 2, - flexDirection: "column", - gap: 1, - children: [ - state4.version !== "current" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - dimColor: true, - children: "Version: " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "claude", - children: state4.version - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - dimColor: true, - children: "Location: " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "text", - children: getInstallationPath2() - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - marginLeft: 2, - flexDirection: "column", - gap: 1, - children: /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - dimColor: true, - children: "Next: Run " - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "claude", - bold: true, - children: "claude --help" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - dimColor: true, - children: " to get started" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this), - state4.setupMessages && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(SetupNotes, { - messages: state4.setupMessages - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - state4.type === "error" && /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - children: [ - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(StatusIcon, { - status: "error", - withSpace: true - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "error", - children: "Installation failed" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - color: "error", - children: state4.message - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedBox_default, { - marginTop: 1, - children: /* @__PURE__ */ jsx_dev_runtime492.jsxDEV(ThemedText, { - dimColor: true, - children: "Try running with --force to override checks" - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - ] - }, undefined, true, undefined, this); -} -var import_compiler_runtime388, import_react334, jsx_dev_runtime492, install; -var init_install = __esm(() => { - init_analytics(); - init_StatusIcon(); - init_ink2(); - init_debug(); - init_env(); - init_errors(); - init_nativeInstaller(); - init_settings2(); - import_compiler_runtime388 = __toESM(require_compiler_runtime(), 1); - import_react334 = __toESM(require_react(), 1); - jsx_dev_runtime492 = __toESM(require_jsx_dev_runtime(), 1); - install = { - type: "local-jsx", - name: "install", - description: "Install Claude Code native build", - argumentHint: "[options]", - async call(onDone, _context, args) { - const force = args.includes("--force"); - const nonFlagArgs = args.filter((arg) => !arg.startsWith("--")); - const target = nonFlagArgs[0]; - const { - unmount - } = await render(/* @__PURE__ */ jsx_dev_runtime492.jsxDEV(Install, { - onDone: (result, options2) => { - unmount(); - onDone(result, options2); - }, - force, - target - }, undefined, false, undefined, this)); - } - }; -}); - -// src/cli/handlers/util.tsx -var exports_util2 = {}; -__export(exports_util2, { - setupTokenHandler: () => setupTokenHandler, - installHandler: () => installHandler, - doctorHandler: () => doctorHandler -}); -import { cwd as cwd4 } from "process"; -async function setupTokenHandler(root3) { - logEvent("tengu_setup_token_command", {}); - const showAuthWarning = !isAnthropicAuthEnabled(); - const { - ConsoleOAuthFlow: ConsoleOAuthFlow2 - } = await Promise.resolve().then(() => (init_ConsoleOAuthFlow(), exports_ConsoleOAuthFlow)); - await new Promise((resolve44) => { - root3.render(/* @__PURE__ */ jsx_dev_runtime493.jsxDEV(AppStateProvider, { - onChangeAppState, - children: /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(ThemedBox_default, { - flexDirection: "column", - gap: 1, - children: [ - /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(WelcomeV2, {}, undefined, false, undefined, this), - showAuthWarning && /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(ThemedBox_default, { - flexDirection: "column", - children: [ - /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(ThemedText, { - color: "warning", - children: "Warning: You already have authentication configured via environment variable or API key helper." - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(ThemedText, { - color: "warning", - children: "The setup-token command will create a new OAuth token which you can use instead." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this), - /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(ConsoleOAuthFlow2, { - onDone: () => { - resolve44(); - }, - mode: "setup-token", - startingMessage: "This will guide you through long-lived (1-year) auth token setup for your Claude account. Claude subscription required." - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); - }); - root3.unmount(); - process.exit(0); -} -function DoctorWithPlugins(t0) { - const $2 = import_compiler_runtime389.c(2); - const { - onDone - } = t0; - useManagePlugins(); - let t1; - if ($2[0] !== onDone) { - t1 = /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(import_react335.default.Suspense, { - fallback: null, - children: /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(DoctorLazy, { - onDone - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[0] = onDone; - $2[1] = t1; - } else { - t1 = $2[1]; - } - return t1; -} -async function doctorHandler(root3) { - logEvent("tengu_doctor_command", {}); - await new Promise((resolve44) => { - root3.render(/* @__PURE__ */ jsx_dev_runtime493.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(MCPConnectionManager, { - dynamicMcpConfig: undefined, - isStrictMcpConfig: false, - children: /* @__PURE__ */ jsx_dev_runtime493.jsxDEV(DoctorWithPlugins, { - onDone: () => { - resolve44(); - } - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); - }); - root3.unmount(); - process.exit(0); -} -async function installHandler(target, options2) { - const { - setup: setup2 - } = await Promise.resolve().then(() => (init_setup3(), exports_setup)); - await setup2(cwd4(), "default", false, false, undefined, false); - const { - install: install2 - } = await Promise.resolve().then(() => (init_install(), exports_install)); - await new Promise((resolve44) => { - const args = []; - if (target) - args.push(target); - if (options2.force) - args.push("--force"); - install2.call((result) => { - resolve44(); - process.exit(result.includes("failed") ? 1 : 0); - }, {}, args); - }); -} -var import_compiler_runtime389, import_react335, jsx_dev_runtime493, DoctorLazy; -var init_util10 = __esm(() => { - init_WelcomeV2(); - init_useManagePlugins(); - init_ink2(); - init_KeybindingProviderSetup(); - init_analytics(); - init_MCPConnectionManager(); - init_AppState(); - init_onChangeAppState(); - init_auth14(); - import_compiler_runtime389 = __toESM(require_compiler_runtime(), 1); - import_react335 = __toESM(require_react(), 1); - jsx_dev_runtime493 = __toESM(require_jsx_dev_runtime(), 1); - DoctorLazy = import_react335.default.lazy(() => Promise.resolve().then(() => (init_Doctor(), exports_Doctor)).then((m4) => ({ - default: m4.Doctor - }))); -}); - -// src/cli/handlers/agents.ts -var exports_agents2 = {}; -__export(exports_agents2, { - agentsHandler: () => agentsHandler -}); -function formatAgent(agent) { - const model = resolveAgentModelDisplay(agent); - const parts = [agent.agentType]; - if (model) { - parts.push(model); - } - if (agent.memory) { - parts.push(`${agent.memory} memory`); - } - return parts.join(" \xB7 "); -} -async function agentsHandler() { - const cwd5 = getCwd(); - const { allAgents } = await getAgentDefinitionsWithOverrides(cwd5); - const activeAgents = getActiveAgentsFromList(allAgents); - const resolvedAgents = resolveAgentOverrides(allAgents, activeAgents); - const lines2 = []; - let totalActive = 0; - for (const { label, source } of AGENT_SOURCE_GROUPS) { - const groupAgents = resolvedAgents.filter((a5) => a5.source === source).sort(compareAgentsByName); - if (groupAgents.length === 0) - continue; - lines2.push(`${label}:`); - for (const agent of groupAgents) { - if (agent.overriddenBy) { - const winnerSource = getOverrideSourceLabel(agent.overriddenBy); - lines2.push(` (shadowed by ${winnerSource}) ${formatAgent(agent)}`); - } else { - lines2.push(` ${formatAgent(agent)}`); - totalActive++; - } - } - lines2.push(""); - } - if (lines2.length === 0) { - console.log("No agents found."); - } else { - console.log(`${totalActive} active agents -`); - console.log(lines2.join(` -`).trimEnd()); - } -} -var init_agents3 = __esm(() => { - init_agentDisplay(); - init_loadAgentsDir(); - init_cwd(); -}); - -// src/cli/update.ts -var exports_update = {}; -__export(exports_update, { - update: () => update -}); -async function update() { - logEvent("tengu_update_check", {}); - writeToStdout(`Current version: ${MACRO.VERSION} -`); - const channel = getInitialSettings()?.autoUpdatesChannel ?? "latest"; - writeToStdout(`Checking for updates to ${channel} version... -`); - logForDebugging("update: Starting update check"); - logForDebugging("update: Running diagnostic"); - const diagnostic = await getDoctorDiagnostic(); - logForDebugging(`update: Installation type: ${diagnostic.installationType}`); - logForDebugging(`update: Config install method: ${diagnostic.configInstallMethod}`); - if (diagnostic.multipleInstallations.length > 1) { - writeToStdout(` -`); - writeToStdout(source_default.yellow("Warning: Multiple installations found") + ` -`); - for (const install2 of diagnostic.multipleInstallations) { - const current = diagnostic.installationType === install2.type ? " (currently running)" : ""; - writeToStdout(`- ${install2.type} at ${install2.path}${current} -`); - } - } - if (diagnostic.warnings.length > 0) { - writeToStdout(` -`); - for (const warning of diagnostic.warnings) { - logForDebugging(`update: Warning detected: ${warning.issue}`); - logForDebugging(`update: Showing warning: ${warning.issue}`); - writeToStdout(source_default.yellow(`Warning: ${warning.issue} -`)); - writeToStdout(source_default.bold(`Fix: ${warning.fix} -`)); - } - } - const config10 = getGlobalConfig(); - if (!config10.installMethod && diagnostic.installationType !== "package-manager") { - writeToStdout(` -`); - writeToStdout(`Updating configuration to track installation method... -`); - let detectedMethod = "unknown"; - switch (diagnostic.installationType) { - case "npm-local": - detectedMethod = "local"; - break; - case "native": - detectedMethod = "native"; - break; - case "npm-global": - detectedMethod = "global"; - break; - default: - detectedMethod = "unknown"; - } - saveGlobalConfig((current) => ({ - ...current, - installMethod: detectedMethod - })); - writeToStdout(`Installation method set to: ${detectedMethod} -`); - } - if (diagnostic.installationType === "development") { - writeToStdout(` -`); - writeToStdout(source_default.yellow("Warning: Cannot update development build") + ` -`); - await gracefulShutdown(1); - } - if (diagnostic.installationType === "package-manager") { - const packageManager = await getPackageManager(); - writeToStdout(` -`); - if (packageManager === "homebrew") { - writeToStdout(`Claude is managed by Homebrew. -`); - const latest = await getLatestVersion(channel); - if (latest && !gte(MACRO.VERSION, latest)) { - writeToStdout(`Update available: ${MACRO.VERSION} \u2192 ${latest} -`); - writeToStdout(` -`); - writeToStdout(`To update, run: -`); - writeToStdout(source_default.bold(" brew upgrade claude-code") + ` -`); - } else { - writeToStdout(`Claude is up to date! -`); - } - } else if (packageManager === "winget") { - writeToStdout(`Claude is managed by winget. -`); - const latest = await getLatestVersion(channel); - if (latest && !gte(MACRO.VERSION, latest)) { - writeToStdout(`Update available: ${MACRO.VERSION} \u2192 ${latest} -`); - writeToStdout(` -`); - writeToStdout(`To update, run: -`); - writeToStdout(source_default.bold(" winget upgrade Anthropic.ClaudeCode") + ` -`); - } else { - writeToStdout(`Claude is up to date! -`); - } - } else if (packageManager === "apk") { - writeToStdout(`Claude is managed by apk. -`); - const latest = await getLatestVersion(channel); - if (latest && !gte(MACRO.VERSION, latest)) { - writeToStdout(`Update available: ${MACRO.VERSION} \u2192 ${latest} -`); - writeToStdout(` -`); - writeToStdout(`To update, run: -`); - writeToStdout(source_default.bold(" apk upgrade claude-code") + ` -`); - } else { - writeToStdout(`Claude is up to date! -`); - } - } else { - writeToStdout(`Claude is managed by a package manager. -`); - writeToStdout(`Please use your package manager to update. -`); - } - await gracefulShutdown(0); - } - if (config10.installMethod && diagnostic.configInstallMethod !== "not set" && diagnostic.installationType !== "package-manager") { - const runningType = diagnostic.installationType; - const configExpects = diagnostic.configInstallMethod; - const typeMapping = { - "npm-local": "local", - "npm-global": "global", - native: "native", - development: "development", - unknown: "unknown" - }; - const normalizedRunningType = typeMapping[runningType] || runningType; - if (normalizedRunningType !== configExpects && configExpects !== "unknown") { - writeToStdout(` -`); - writeToStdout(source_default.yellow("Warning: Configuration mismatch") + ` -`); - writeToStdout(`Config expects: ${configExpects} installation -`); - writeToStdout(`Currently running: ${runningType} -`); - writeToStdout(source_default.yellow(`Updating the ${runningType} installation you are currently using`) + ` -`); - saveGlobalConfig((current) => ({ - ...current, - installMethod: normalizedRunningType - })); - writeToStdout(`Config updated to reflect current installation method: ${normalizedRunningType} -`); - } - } - if (diagnostic.installationType === "native") { - logForDebugging("update: Detected native installation, using native updater"); - try { - const result = await installLatest(channel, true); - if (result.lockFailed) { - const pidInfo = result.lockHolderPid ? ` (PID ${result.lockHolderPid})` : ""; - writeToStdout(source_default.yellow(`Another Claude process${pidInfo} is currently running. Please try again in a moment.`) + ` -`); - await gracefulShutdown(0); - } - if (!result.latestVersion) { - process.stderr.write(`Failed to check for updates -`); - await gracefulShutdown(1); - } - if (result.latestVersion === MACRO.VERSION) { - writeToStdout(source_default.green(`Claude Code is up to date (${MACRO.VERSION})`) + ` -`); - } else { - writeToStdout(source_default.green(`Successfully updated from ${MACRO.VERSION} to version ${result.latestVersion}`) + ` -`); - await regenerateCompletionCache(); - } - await gracefulShutdown(0); - } catch (error46) { - process.stderr.write(`Error: Failed to install native update -`); - process.stderr.write(String(error46) + ` -`); - process.stderr.write(`Try running "claude doctor" for diagnostics -`); - await gracefulShutdown(1); - } - } - if (config10.installMethod !== "native") { - await removeInstalledSymlink(); - } - logForDebugging("update: Checking npm registry for latest version"); - logForDebugging(`update: Package URL: ${MACRO.PACKAGE_URL}`); - const npmTag = channel === "stable" ? "stable" : "latest"; - const npmCommand = `npm view ${MACRO.PACKAGE_URL}@${npmTag} version`; - logForDebugging(`update: Running: ${npmCommand}`); - const latestVersion = await getLatestVersion(channel); - logForDebugging(`update: Latest version from npm: ${latestVersion || "FAILED"}`); - if (!latestVersion) { - logForDebugging("update: Failed to get latest version from npm registry"); - process.stderr.write(source_default.red("Failed to check for updates") + ` -`); - process.stderr.write(`Unable to fetch latest version from npm registry -`); - process.stderr.write(` -`); - process.stderr.write(`Possible causes: -`); - process.stderr.write(` \u2022 Network connectivity issues -`); - process.stderr.write(` \u2022 npm registry is unreachable -`); - process.stderr.write(` \u2022 Corporate proxy/firewall blocking npm -`); - if (MACRO.PACKAGE_URL && !MACRO.PACKAGE_URL.startsWith("@anthropic")) { - process.stderr.write(` \u2022 Internal/development build not published to npm -`); - } - process.stderr.write(` -`); - process.stderr.write(`Try: -`); - process.stderr.write(` \u2022 Check your internet connection -`); - process.stderr.write(` \u2022 Run with --debug flag for more details -`); - const packageName = MACRO.PACKAGE_URL || (process.env.USER_TYPE === "ant" ? "@anthropic-ai/claude-cli" : "@anthropic-ai/claude-code"); - process.stderr.write(` \u2022 Manually check: npm view ${packageName} version -`); - process.stderr.write(` \u2022 Check if you need to login: npm whoami -`); - await gracefulShutdown(1); - } - if (latestVersion === MACRO.VERSION) { - writeToStdout(source_default.green(`Claude Code is up to date (${MACRO.VERSION})`) + ` -`); - await gracefulShutdown(0); - } - writeToStdout(`New version available: ${latestVersion} (current: ${MACRO.VERSION}) -`); - writeToStdout(`Installing update... -`); - let useLocalUpdate = false; - let updateMethodName = ""; - switch (diagnostic.installationType) { - case "npm-local": - useLocalUpdate = true; - updateMethodName = "local"; - break; - case "npm-global": - useLocalUpdate = false; - updateMethodName = "global"; - break; - case "unknown": { - const isLocal = await localInstallationExists(); - useLocalUpdate = isLocal; - updateMethodName = isLocal ? "local" : "global"; - writeToStdout(source_default.yellow("Warning: Could not determine installation type") + ` -`); - writeToStdout(`Attempting ${updateMethodName} update based on file detection... -`); - break; - } - default: - process.stderr.write(`Error: Cannot update ${diagnostic.installationType} installation -`); - await gracefulShutdown(1); - } - writeToStdout(`Using ${updateMethodName} installation update method... -`); - logForDebugging(`update: Update method determined: ${updateMethodName}`); - logForDebugging(`update: useLocalUpdate: ${useLocalUpdate}`); - let status2; - if (useLocalUpdate) { - logForDebugging("update: Calling installOrUpdateClaudePackage() for local update"); - status2 = await installOrUpdateClaudePackage(channel); - } else { - logForDebugging("update: Calling installGlobalPackage() for global update"); - status2 = await installGlobalPackage(); - } - logForDebugging(`update: Installation status: ${status2}`); - switch (status2) { - case "success": - writeToStdout(source_default.green(`Successfully updated from ${MACRO.VERSION} to version ${latestVersion}`) + ` -`); - await regenerateCompletionCache(); - break; - case "no_permissions": - process.stderr.write(`Error: Insufficient permissions to install update -`); - if (useLocalUpdate) { - process.stderr.write(`Try manually updating with: -`); - process.stderr.write(` cd ~/.claude/local && npm update ${MACRO.PACKAGE_URL} -`); - } else { - process.stderr.write(`Try running with sudo or fix npm permissions -`); - process.stderr.write(`Or consider using native installation with: claude install -`); - } - await gracefulShutdown(1); - break; - case "install_failed": - process.stderr.write(`Error: Failed to install update -`); - if (useLocalUpdate) { - process.stderr.write(`Try manually updating with: -`); - process.stderr.write(` cd ~/.claude/local && npm update ${MACRO.PACKAGE_URL} -`); - } else { - process.stderr.write(`Or consider using native installation with: claude install -`); - } - await gracefulShutdown(1); - break; - case "in_progress": - process.stderr.write(`Error: Another instance is currently performing an update -`); - process.stderr.write(`Please wait and try again later -`); - await gracefulShutdown(1); - break; - } - await gracefulShutdown(0); -} -var init_update = __esm(() => { - init_source(); - init_analytics(); - init_autoUpdater(); - init_completionCache(); - init_config(); - init_debug(); - init_doctorDiagnostic(); - init_gracefulShutdown(); - init_localInstaller(); - init_nativeInstaller(); - init_packageManagers(); - init_settings2(); -}); - -// src/main.tsx -init_startupProfiler(); -init_rawRead(); -init_keychainPrefetch(); - -// node_modules/@commander-js/extra-typings/esm.mjs -var import__ = __toESM(require_extra_typings(), 1); -var { - program, - createCommand, - createArgument, - createOption, - CommanderError, - InvalidArgumentError, - InvalidOptionArgumentError, - Command, - Argument, - Option, - Help -} = import__.default; - -// src/main.tsx -init_source(); -init_mapValues(); -init_pickBy(); -init_uniqBy(); -init_oauth(); -init_context4(); -import { readFileSync as readFileSync19 } from "fs"; - -// src/entrypoints/init.ts -init_startupProfiler(); -init_state(); -init_config(); -init_memoize(); -init_state(); -init_state(); -init_manager7(); -init_client7(); -init_policyLimits(); -init_remoteManagedSettings(); - -// src/utils/apiPreconnect.ts -init_oauth(); -init_envUtils(); -var fired = false; -function preconnectAnthropicApi() { - if (fired) - return; - fired = true; - if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) || isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) || isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)) { - return; - } - if (process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || process.env.ANTHROPIC_UNIX_SOCKET || process.env.CLAUDE_CODE_CLIENT_CERT || process.env.CLAUDE_CODE_CLIENT_KEY) { - return; - } - const baseUrl = process.env.ANTHROPIC_BASE_URL || getOauthConfig().BASE_API_URL; - fetch(baseUrl, { - method: "HEAD", - signal: AbortSignal.timeout(1e4) - }).catch(() => {}); -} - -// src/utils/caCertsConfig.ts -init_config(); -init_debug(); -init_settings2(); -function applyExtraCACertsFromConfig() { - if (process.env.NODE_EXTRA_CA_CERTS) { - return; - } - const configPath = getExtraCertsPathFromConfig(); - if (configPath) { - process.env.NODE_EXTRA_CA_CERTS = configPath; - logForDebugging(`CA certs: Applied NODE_EXTRA_CA_CERTS from config to process.env: ${configPath}`); - } -} -function getExtraCertsPathFromConfig() { - try { - const globalConfig2 = getGlobalConfig(); - const globalEnv = globalConfig2?.env; - const settings = getSettingsForSource("userSettings"); - const settingsEnv = settings?.env; - logForDebugging(`CA certs: Config fallback - globalEnv keys: ${globalEnv ? Object.keys(globalEnv).join(",") : "none"}, settingsEnv keys: ${settingsEnv ? Object.keys(settingsEnv).join(",") : "none"}`); - const path25 = settingsEnv?.NODE_EXTRA_CA_CERTS || globalEnv?.NODE_EXTRA_CA_CERTS; - if (path25) { - logForDebugging(`CA certs: Found NODE_EXTRA_CA_CERTS in config/settings: ${path25}`); - } - return path25; - } catch (error46) { - logForDebugging(`CA certs: Config fallback failed: ${error46}`, { - level: "error" - }); - return; - } -} - -// src/entrypoints/init.ts -init_cleanupRegistry(); -init_config(); -init_debug(); -init_detectRepository(); -init_diagLogs(); -init_envDynamic(); -init_envUtils(); -init_errors(); -init_gracefulShutdown(); -init_managedEnv(); -init_mtls(); -init_filesystem(); -init_proxy(); -init_betaSessionTracing(); -init_telemetryAttributes(); -init_windowsPaths(); -var telemetryInitialized = false; -var init2 = memoize_default(async () => { - const initStartTime = Date.now(); - logForDiagnosticsNoPII("info", "init_started"); - profileCheckpoint("init_function_start"); - try { - const configsStart = Date.now(); - enableConfigs(); - logForDiagnosticsNoPII("info", "init_configs_enabled", { - duration_ms: Date.now() - configsStart - }); - profileCheckpoint("init_configs_enabled"); - const envVarsStart = Date.now(); - applySafeConfigEnvironmentVariables(); - applyExtraCACertsFromConfig(); - logForDiagnosticsNoPII("info", "init_safe_env_vars_applied", { - duration_ms: Date.now() - envVarsStart - }); - profileCheckpoint("init_safe_env_vars_applied"); - setupGracefulShutdown(); - profileCheckpoint("init_after_graceful_shutdown"); - Promise.all([ - Promise.resolve().then(() => (init_firstPartyEventLogger(), exports_firstPartyEventLogger)), - Promise.resolve().then(() => (init_growthbook(), exports_growthbook)) - ]).then(([fp, gb]) => { - fp.initialize1PEventLogging(); - gb.onGrowthBookRefresh(() => { - fp.reinitialize1PEventLoggingIfConfigChanged(); - }); - }); - profileCheckpoint("init_after_1p_event_logging"); - populateOAuthAccountInfoIfNeeded(); - profileCheckpoint("init_after_oauth_populate"); - initJetBrainsDetection(); - profileCheckpoint("init_after_jetbrains_detection"); - detectCurrentRepository(); - if (isEligibleForRemoteManagedSettings()) { - initializeRemoteManagedSettingsLoadingPromise(); - } - if (isPolicyLimitsEligible()) { - initializePolicyLimitsLoadingPromise(); - } - profileCheckpoint("init_after_remote_settings_check"); - recordFirstStartTime(); - const mtlsStart = Date.now(); - logForDebugging("[init] configureGlobalMTLS starting"); - configureGlobalMTLS(); - logForDiagnosticsNoPII("info", "init_mtls_configured", { - duration_ms: Date.now() - mtlsStart - }); - logForDebugging("[init] configureGlobalMTLS complete"); - const proxyStart = Date.now(); - logForDebugging("[init] configureGlobalAgents starting"); - configureGlobalAgents(); - logForDiagnosticsNoPII("info", "init_proxy_configured", { - duration_ms: Date.now() - proxyStart - }); - logForDebugging("[init] configureGlobalAgents complete"); - profileCheckpoint("init_network_configured"); - preconnectAnthropicApi(); - if (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) { - try { - const { initUpstreamProxy: initUpstreamProxy2, getUpstreamProxyEnv: getUpstreamProxyEnv2 } = await Promise.resolve().then(() => (init_upstreamproxy(), exports_upstreamproxy)); - const { registerUpstreamProxyEnvFn: registerUpstreamProxyEnvFn2 } = await Promise.resolve().then(() => (init_subprocessEnv(), exports_subprocessEnv)); - registerUpstreamProxyEnvFn2(getUpstreamProxyEnv2); - await initUpstreamProxy2(); - } catch (err2) { - logForDebugging(`[init] upstreamproxy init failed: ${err2 instanceof Error ? err2.message : String(err2)}; continuing without proxy`, { level: "warn" }); - } - } - setShellIfWindows(); - registerCleanup(shutdownLspServerManager); - registerCleanup(async () => { - const { cleanupSessionTeams: cleanupSessionTeams2 } = await Promise.resolve().then(() => (init_teamHelpers(), exports_teamHelpers)); - await cleanupSessionTeams2(); - }); - if (isScratchpadEnabled()) { - const scratchpadStart = Date.now(); - await ensureScratchpadDir(); - logForDiagnosticsNoPII("info", "init_scratchpad_created", { - duration_ms: Date.now() - scratchpadStart - }); - } - logForDiagnosticsNoPII("info", "init_completed", { - duration_ms: Date.now() - initStartTime - }); - profileCheckpoint("init_function_end"); - } catch (error46) { - if (error46 instanceof ConfigParseError) { - if (getIsNonInteractiveSession()) { - process.stderr.write(`Configuration error in ${error46.filePath}: ${error46.message} -`); - gracefulShutdownSync(1); - return; - } - return Promise.resolve().then(() => (init_InvalidConfigDialog(), exports_InvalidConfigDialog)).then((m4) => m4.showInvalidConfigDialog({ error: error46 })); - } else { - throw error46; - } - } -}); -function initializeTelemetryAfterTrust() { - if (isEligibleForRemoteManagedSettings()) { - if (getIsNonInteractiveSession() && isBetaTracingEnabled()) { - doInitializeTelemetry().catch((error46) => { - logForDebugging(`[3P telemetry] Eager telemetry init failed (beta tracing): ${errorMessage(error46)}`, { level: "error" }); - }); - } - logForDebugging("[3P telemetry] Waiting for remote managed settings before telemetry init"); - waitForRemoteManagedSettingsToLoad().then(async () => { - logForDebugging("[3P telemetry] Remote managed settings loaded, initializing telemetry"); - applyConfigEnvironmentVariables(); - await doInitializeTelemetry(); - }).catch((error46) => { - logForDebugging(`[3P telemetry] Telemetry init failed (remote settings path): ${errorMessage(error46)}`, { level: "error" }); - }); - } else { - doInitializeTelemetry().catch((error46) => { - logForDebugging(`[3P telemetry] Telemetry init failed: ${errorMessage(error46)}`, { level: "error" }); - }); - } -} -async function doInitializeTelemetry() { - if (telemetryInitialized) { - return; - } - telemetryInitialized = true; - try { - await setMeterState(); - } catch (error46) { - telemetryInitialized = false; - throw error46; - } -} -async function setMeterState() { - const { initializeTelemetry: initializeTelemetry2 } = await Promise.resolve().then(() => (init_instrumentation(), exports_instrumentation)); - const meter = await initializeTelemetry2(); - if (meter) { - const createAttributedCounter = (name3, options2) => { - const counter = meter?.createCounter(name3, options2); - return { - add(value, additionalAttributes = {}) { - const currentAttributes = getTelemetryAttributes(); - const mergedAttributes = { - ...currentAttributes, - ...additionalAttributes - }; - counter?.add(value, mergedAttributes); - } - }; - }; - setMeter(meter, createAttributedCounter); - getSessionCounter()?.add(1); - } -} - -// src/main.tsx -init_history(); - -// src/replLauncher.tsx -var jsx_dev_runtime468 = __toESM(require_jsx_dev_runtime(), 1); -async function launchRepl(root3, appProps, replProps, renderAndRun) { - const { - App: App3 - } = await Promise.resolve().then(() => (init_App2(), exports_App)); - const { - REPL: REPL2 - } = await Promise.resolve().then(() => (init_REPL(), exports_REPL)); - await renderAndRun(root3, /* @__PURE__ */ jsx_dev_runtime468.jsxDEV(App3, { - ...appProps, - children: /* @__PURE__ */ jsx_dev_runtime468.jsxDEV(REPL2, { - ...replProps - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); -} - -// src/main.tsx -init_growthbook(); - -// src/services/api/bootstrap.ts -init_axios2(); -init_isEqual(); -init_auth14(); -init_zod(); -init_oauth(); -init_config(); -init_debug(); -init_http8(); -init_log2(); -init_providers(); -var bootstrapResponseSchema = lazySchema(() => exports_external2.object({ - client_data: exports_external2.record(exports_external2.unknown()).nullish(), - additional_model_options: exports_external2.array(exports_external2.object({ - model: exports_external2.string(), - name: exports_external2.string(), - description: exports_external2.string() - }).transform(({ model, name: name3, description }) => ({ - value: model, - label: name3, - description - }))).nullish() -})); -async function fetchBootstrapAPI() { - if (isEssentialTrafficOnly()) { - logForDebugging("[Bootstrap] Skipped: Nonessential traffic disabled"); - return null; - } - if (getAPIProvider() !== "firstParty") { - logForDebugging("[Bootstrap] Skipped: 3P provider"); - return null; - } - const apiKey = getAnthropicApiKey(); - const hasUsableOAuth = getClaudeAIOAuthTokens()?.accessToken && hasProfileScope(); - if (!hasUsableOAuth && !apiKey) { - logForDebugging("[Bootstrap] Skipped: no usable OAuth or API key"); - return null; - } - const endpoint7 = `${getOauthConfig().BASE_API_URL}/api/claude_cli/bootstrap`; - try { - return await withOAuth401Retry(async () => { - const token = getClaudeAIOAuthTokens()?.accessToken; - let authHeaders; - if (token && hasProfileScope()) { - authHeaders = { - Authorization: `Bearer ${token}`, - "anthropic-beta": OAUTH_BETA_HEADER - }; - } else if (apiKey) { - authHeaders = { "x-api-key": apiKey }; - } else { - logForDebugging("[Bootstrap] No auth available on retry, aborting"); - return null; - } - logForDebugging("[Bootstrap] Fetching"); - const response7 = await axios_default.get(endpoint7, { - headers: { - "Content-Type": "application/json", - "User-Agent": getClaudeCodeUserAgent(), - ...authHeaders - }, - timeout: 5000 - }); - const parsed = bootstrapResponseSchema().safeParse(response7.data); - if (!parsed.success) { - logForDebugging(`[Bootstrap] Response failed validation: ${parsed.error.message}`); - return null; - } - logForDebugging("[Bootstrap] Fetch ok"); - return parsed.data; - }); - } catch (error46) { - logForDebugging(`[Bootstrap] Fetch failed: ${axios_default.isAxiosError(error46) ? error46.response?.status ?? error46.code : "unknown"}`); - throw error46; - } -} -async function fetchBootstrapData() { - try { - const response7 = await fetchBootstrapAPI(); - if (!response7) - return; - const clientData = response7.client_data ?? null; - const additionalModelOptions = response7.additional_model_options ?? []; - const config10 = getGlobalConfig(); - if (isEqual_default(config10.clientDataCache, clientData) && isEqual_default(config10.additionalModelOptionsCache, additionalModelOptions)) { - logForDebugging("[Bootstrap] Cache unchanged, skipping write"); - return; - } - logForDebugging("[Bootstrap] Cache updated, persisting to disk"); - saveGlobalConfig((current) => ({ - ...current, - clientDataCache: clientData, - additionalModelOptionsCache: additionalModelOptions - })); - } catch (error46) { - logError2(error46); - } -} - -// src/main.tsx -init_filesApi(); -init_referral(); -init_officialRegistry(); -init_policyLimits(); -init_remoteManagedSettings(); -init_SyntheticOutputTool(); -init_tools2(); -init_advisor(); -init_agentSwarmsEnabled(); -init_asciicast(); -init_auth14(); -init_config(); -init_earlyInput(); -init_effort(); -init_fastMode(); -init_managedEnv(); -init_messages9(); -init_platform2(); -init_renderOptions(); -init_sessionIngressAuth(); -init_changeDetector(); -init_skillChangeDetector(); -init_slowOperations(); -init_reconnection(); - -// src/utils/warningHandler.ts -init_analytics(); -init_debug(); -init_envUtils(); -init_platform2(); -var MAX_WARNING_KEYS = 1000; -var warningCounts = new Map; -var INTERNAL_WARNINGS = [ - /MaxListenersExceededWarning.*AbortSignal/, - /MaxListenersExceededWarning.*EventTarget/ -]; -function isInternalWarning(warning) { - const warningStr = `${warning.name}: ${warning.message}`; - return INTERNAL_WARNINGS.some((pattern) => pattern.test(warningStr)); -} -var warningHandler = null; -function initializeWarningHandler() { - const currentListeners = process.listeners("warning"); - if (warningHandler && currentListeners.includes(warningHandler)) { - return; - } - const isDevelopment = true; - if (!isDevelopment) { - process.removeAllListeners("warning"); - } - warningHandler = (warning) => { - try { - const warningKey = `${warning.name}: ${warning.message.slice(0, 50)}`; - const count4 = warningCounts.get(warningKey) || 0; - if (warningCounts.has(warningKey) || warningCounts.size < MAX_WARNING_KEYS) { - warningCounts.set(warningKey, count4 + 1); - } - const isInternal = isInternalWarning(warning); - logEvent("tengu_node_warning", { - is_internal: isInternal ? 1 : 0, - occurrence_count: count4 + 1, - classname: warning.name, - ...process.env.USER_TYPE === "ant" && { - message: warning.message - } - }); - if (isEnvTruthy(process.env.CLAUDE_DEBUG)) { - const prefix = isInternal ? "[Internal Warning]" : "[Warning]"; - logForDebugging(`${prefix} ${warning.toString()}`, { level: "warn" }); - } - } catch {} - }; - process.on("warning", warningHandler); -} - -// src/main.tsx -init_config8(); -init_growthbook(); -init_analytics(); -init_sink(); -init_state(); -init_commands5(); -import { resolve as resolve44 } from "path"; - -// src/interactiveHelpers.tsx -init_analytics(); -init_gracefulShutdown(); -init_state(); -init_stats4(); -init_context4(); -import { appendFileSync as appendFileSync4 } from "fs"; -init_terminal(); -init_KeybindingProviderSetup(); -init_growthbook(); -init_grove(); - -// src/components/MCPServerApprovalDialog.tsx -init_analytics(); -init_settings2(); -init_CustomSelect(); -init_Dialog(); -var import_compiler_runtime370 = __toESM(require_compiler_runtime(), 1); - -// src/components/MCPServerDialogCopy.tsx -init_ink2(); -var import_compiler_runtime369 = __toESM(require_compiler_runtime(), 1); -var jsx_dev_runtime469 = __toESM(require_jsx_dev_runtime(), 1); -function MCPServerDialogCopy() { - const $2 = import_compiler_runtime369.c(1); - let t0; - if ($2[0] === Symbol.for("react.memo_cache_sentinel")) { - t0 = /* @__PURE__ */ jsx_dev_runtime469.jsxDEV(ThemedText, { - children: [ - "MCP servers may execute code or access system resources. All tool calls require approval. Learn more in the", - " ", - /* @__PURE__ */ jsx_dev_runtime469.jsxDEV(Link, { - url: "https://code.claude.com/docs/en/mcp", - children: "MCP documentation" - }, undefined, false, undefined, this), - "." - ] - }, undefined, true, undefined, this); - $2[0] = t0; - } else { - t0 = $2[0]; - } - return t0; -} - -// src/components/MCPServerApprovalDialog.tsx -var jsx_dev_runtime470 = __toESM(require_jsx_dev_runtime(), 1); -function MCPServerApprovalDialog(t0) { - const $2 = import_compiler_runtime370.c(13); - const { - serverName, - onDone - } = t0; - let t1; - if ($2[0] !== onDone || $2[1] !== serverName) { - t1 = function onChange2(value) { - logEvent("tengu_mcp_dialog_choice", { - choice: value - }); - bb2: - switch (value) { - case "yes": - case "yes_all": { - const currentSettings_0 = getSettings_DEPRECATED() || {}; - const enabledServers = currentSettings_0.enabledMcpjsonServers || []; - if (!enabledServers.includes(serverName)) { - updateSettingsForSource("localSettings", { - enabledMcpjsonServers: [...enabledServers, serverName] - }); - } - if (value === "yes_all") { - updateSettingsForSource("localSettings", { - enableAllProjectMcpServers: true - }); - } - onDone(); - break bb2; - } - case "no": { - const currentSettings = getSettings_DEPRECATED() || {}; - const disabledServers = currentSettings.disabledMcpjsonServers || []; - if (!disabledServers.includes(serverName)) { - updateSettingsForSource("localSettings", { - disabledMcpjsonServers: [...disabledServers, serverName] - }); - } - onDone(); - } - } - }; - $2[0] = onDone; - $2[1] = serverName; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const onChange = t1; - const t22 = `New MCP server found in .mcp.json: ${serverName}`; - let t32; - if ($2[3] !== onChange) { - t32 = () => onChange("no"); - $2[3] = onChange; - $2[4] = t32; - } else { - t32 = $2[4]; - } - let t4; - if ($2[5] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime470.jsxDEV(MCPServerDialogCopy, {}, undefined, false, undefined, this); - $2[5] = t4; - } else { - t4 = $2[5]; - } - let t5; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t5 = [{ - label: "Use this and all future MCP servers in this project", - value: "yes_all" - }, { - label: "Use this MCP server", - value: "yes" - }, { - label: "Continue without using this MCP server", - value: "no" - }]; - $2[6] = t5; - } else { - t5 = $2[6]; - } - let t6; - if ($2[7] !== onChange) { - t6 = /* @__PURE__ */ jsx_dev_runtime470.jsxDEV(Select, { - options: t5, - onChange: (value_0) => onChange(value_0), - onCancel: () => onChange("no") - }, undefined, false, undefined, this); - $2[7] = onChange; - $2[8] = t6; - } else { - t6 = $2[8]; - } - let t7; - if ($2[9] !== t22 || $2[10] !== t32 || $2[11] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime470.jsxDEV(Dialog, { - title: t22, - color: "warning", - onCancel: t32, - children: [ - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[9] = t22; - $2[10] = t32; - $2[11] = t6; - $2[12] = t7; - } else { - t7 = $2[12]; - } - return t7; -} - -// src/components/MCPServerMultiselectDialog.tsx -init_partition(); -init_analytics(); -init_ink2(); -init_settings2(); -init_ConfigurableShortcutHint(); -init_SelectMulti(); -init_Byline(); -init_Dialog(); -init_KeyboardShortcutHint(); -var import_compiler_runtime371 = __toESM(require_compiler_runtime(), 1); -var jsx_dev_runtime471 = __toESM(require_jsx_dev_runtime(), 1); -function MCPServerMultiselectDialog(t0) { - const $2 = import_compiler_runtime371.c(21); - const { - serverNames, - onDone - } = t0; - let t1; - if ($2[0] !== onDone || $2[1] !== serverNames) { - t1 = function onSubmit2(selectedServers) { - const currentSettings = getSettings_DEPRECATED() || {}; - const enabledServers = currentSettings.enabledMcpjsonServers || []; - const disabledServers = currentSettings.disabledMcpjsonServers || []; - const [approvedServers, rejectedServers] = partition_default(serverNames, (server) => selectedServers.includes(server)); - logEvent("tengu_mcp_multidialog_choice", { - approved: approvedServers.length, - rejected: rejectedServers.length - }); - if (approvedServers.length > 0) { - const newEnabledServers = [...new Set([...enabledServers, ...approvedServers])]; - updateSettingsForSource("localSettings", { - enabledMcpjsonServers: newEnabledServers - }); - } - if (rejectedServers.length > 0) { - const newDisabledServers = [...new Set([...disabledServers, ...rejectedServers])]; - updateSettingsForSource("localSettings", { - disabledMcpjsonServers: newDisabledServers - }); - } - onDone(); - }; - $2[0] = onDone; - $2[1] = serverNames; - $2[2] = t1; - } else { - t1 = $2[2]; - } - const onSubmit = t1; - let t22; - if ($2[3] !== onDone || $2[4] !== serverNames) { - t22 = () => { - const currentSettings_0 = getSettings_DEPRECATED() || {}; - const disabledServers_0 = currentSettings_0.disabledMcpjsonServers || []; - const newDisabledServers_0 = [...new Set([...disabledServers_0, ...serverNames])]; - updateSettingsForSource("localSettings", { - disabledMcpjsonServers: newDisabledServers_0 - }); - onDone(); - }; - $2[3] = onDone; - $2[4] = serverNames; - $2[5] = t22; - } else { - t22 = $2[5]; - } - const handleEscRejectAll = t22; - const t32 = `${serverNames.length} new MCP servers found in .mcp.json`; - let t4; - if ($2[6] === Symbol.for("react.memo_cache_sentinel")) { - t4 = /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(MCPServerDialogCopy, {}, undefined, false, undefined, this); - $2[6] = t4; - } else { - t4 = $2[6]; - } - let t5; - if ($2[7] !== serverNames) { - t5 = serverNames.map(_temp302); - $2[7] = serverNames; - $2[8] = t5; - } else { - t5 = $2[8]; - } - let t6; - if ($2[9] !== handleEscRejectAll || $2[10] !== onSubmit || $2[11] !== serverNames || $2[12] !== t5) { - t6 = /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(SelectMulti, { - options: t5, - defaultValue: serverNames, - onSubmit, - onCancel: handleEscRejectAll, - hideIndexes: true - }, undefined, false, undefined, this); - $2[9] = handleEscRejectAll; - $2[10] = onSubmit; - $2[11] = serverNames; - $2[12] = t5; - $2[13] = t6; - } else { - t6 = $2[13]; - } - let t7; - if ($2[14] !== handleEscRejectAll || $2[15] !== t32 || $2[16] !== t6) { - t7 = /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(Dialog, { - title: t32, - subtitle: "Select any you wish to enable.", - color: "warning", - onCancel: handleEscRejectAll, - hideInputGuide: true, - children: [ - t4, - t6 - ] - }, undefined, true, undefined, this); - $2[14] = handleEscRejectAll; - $2[15] = t32; - $2[16] = t6; - $2[17] = t7; - } else { - t7 = $2[17]; - } - let t8; - if ($2[18] === Symbol.for("react.memo_cache_sentinel")) { - t8 = /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(ThemedBox_default, { - paddingX: 1, - children: /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(ThemedText, { - dimColor: true, - italic: true, - children: /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(Byline, { - children: [ - /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(KeyboardShortcutHint, { - shortcut: "Space", - action: "select" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(KeyboardShortcutHint, { - shortcut: "Enter", - action: "confirm" - }, undefined, false, undefined, this), - /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(ConfigurableShortcutHint, { - action: "confirm:no", - context: "Confirmation", - fallback: "Esc", - description: "reject all" - }, undefined, false, undefined, this) - ] - }, undefined, true, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this); - $2[18] = t8; - } else { - t8 = $2[18]; - } - let t9; - if ($2[19] !== t7) { - t9 = /* @__PURE__ */ jsx_dev_runtime471.jsxDEV(jsx_dev_runtime471.Fragment, { - children: [ - t7, - t8 - ] - }, undefined, true, undefined, this); - $2[19] = t7; - $2[20] = t9; - } else { - t9 = $2[20]; - } - return t9; -} -function _temp302(server_0) { - return { - label: server_0, - value: server_0 - }; -} - -// src/services/mcpServerApproval.tsx -init_KeybindingProviderSetup(); -init_AppState(); -init_config9(); -init_utils8(); -var jsx_dev_runtime472 = __toESM(require_jsx_dev_runtime(), 1); -async function handleMcpjsonServerApprovals(root3) { - const { - servers: projectServers - } = getMcpConfigsByScope("project"); - const pendingServers = Object.keys(projectServers).filter((serverName) => getProjectMcpServerStatus(serverName) === "pending"); - if (pendingServers.length === 0) { - return; - } - await new Promise((resolve44) => { - const done = () => void resolve44(); - if (pendingServers.length === 1 && pendingServers[0] !== undefined) { - const serverName = pendingServers[0]; - root3.render(/* @__PURE__ */ jsx_dev_runtime472.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime472.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime472.jsxDEV(MCPServerApprovalDialog, { - serverName, - onDone: done - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); - } else { - root3.render(/* @__PURE__ */ jsx_dev_runtime472.jsxDEV(AppStateProvider, { - children: /* @__PURE__ */ jsx_dev_runtime472.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime472.jsxDEV(MCPServerMultiselectDialog, { - serverNames: pendingServers, - onDone: done - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); - } - }); -} - -// src/interactiveHelpers.tsx -init_AppState(); -init_onChangeAppState(); -init_authPortable(); -init_claudemd(); -init_config(); - -// src/utils/deepLink/terminalPreference.ts -init_config(); -init_debug(); - -// src/interactiveHelpers.tsx -init_envUtils(); - -// src/utils/fpsTracker.ts -class FpsTracker { - frameDurations = []; - firstRenderTime; - lastRenderTime; - record(durationMs) { - const now2 = performance.now(); - if (this.firstRenderTime === undefined) { - this.firstRenderTime = now2; - } - this.lastRenderTime = now2; - this.frameDurations.push(durationMs); - } - getMetrics() { - if (this.frameDurations.length === 0 || this.firstRenderTime === undefined || this.lastRenderTime === undefined) { - return; - } - const totalTimeMs = this.lastRenderTime - this.firstRenderTime; - if (totalTimeMs <= 0) { - return; - } - const totalFrames = this.frameDurations.length; - const averageFps = totalFrames / (totalTimeMs / 1000); - const sorted = this.frameDurations.slice().sort((a5, b5) => b5 - a5); - const p99Index = Math.max(0, Math.ceil(sorted.length * 0.01) - 1); - const p99FrameTimeMs = sorted[p99Index]; - const low1PctFps = p99FrameTimeMs > 0 ? 1000 / p99FrameTimeMs : 0; - return { - averageFps: Math.round(averageFps * 100) / 100, - low1PctFps: Math.round(low1PctFps * 100) / 100 - }; - } -} - -// src/interactiveHelpers.tsx -init_githubRepoPathMapping(); -init_managedEnv(); -init_renderOptions(); -init_allErrors(); -init_settings2(); -var jsx_dev_runtime482 = __toESM(require_jsx_dev_runtime(), 1); -function completeOnboarding() { - saveGlobalConfig((current) => ({ - ...current, - hasCompletedOnboarding: true, - lastOnboardingVersion: MACRO.VERSION - })); -} -function showDialog(root3, renderer) { - return new Promise((resolve44) => { - const done = (result) => void resolve44(result); - root3.render(renderer(done)); - }); -} -async function exitWithError(root3, message, beforeExit) { - return exitWithMessage2(root3, message, { - color: "error", - beforeExit - }); -} -async function exitWithMessage2(root3, message, options2) { - const { - Text: Text6 - } = await Promise.resolve().then(() => (init_ink2(), exports_ink)); - const color3 = options2?.color; - const exitCode = options2?.exitCode ?? 1; - root3.render(color3 ? /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(Text6, { - color: color3, - children: message - }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(Text6, { - children: message - }, undefined, false, undefined, this)); - root3.unmount(); - await options2?.beforeExit?.(); - process.exit(exitCode); -} -function showSetupDialog(root3, renderer, options2) { - return showDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(AppStateProvider, { - onChangeAppState: options2?.onChangeAppState, - children: /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(KeybindingSetup, { - children: renderer(done) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); -} -async function renderAndRun(root3, element) { - root3.render(element); - startDeferredPrefetches(); - await root3.waitUntilExit(); - await gracefulShutdown(0); -} -async function showSetupScreens(root3, permissionMode, allowDangerouslySkipPermissions, commands7, claudeInChrome, devChannels) { - if (isEnvTruthy(false) || process.env.IS_DEMO) { - return false; - } - const config10 = getGlobalConfig(); - let onboardingShown = false; - if (!config10.theme || !config10.hasCompletedOnboarding) { - onboardingShown = true; - const { - Onboarding: Onboarding2 - } = await Promise.resolve().then(() => (init_Onboarding(), exports_Onboarding)); - await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(Onboarding2, { - onDone: () => { - completeOnboarding(); - done(); - } - }, undefined, false, undefined, this), { - onChangeAppState - }); - } - if (!isEnvTruthy(process.env.CLAUBBIT)) { - if (!checkHasTrustDialogAccepted()) { - const { - TrustDialog: TrustDialog2 - } = await Promise.resolve().then(() => (init_TrustDialog(), exports_TrustDialog)); - await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(TrustDialog2, { - commands: commands7, - onDone: done - }, undefined, false, undefined, this)); - } - setSessionTrustAccepted(true); - resetGrowthBook(); - initializeGrowthBook(); - getSystemContext(); - const { - errors: allErrors - } = getSettingsWithAllErrors(); - if (allErrors.length === 0) { - await handleMcpjsonServerApprovals(root3); - } - if (await shouldShowClaudeMdExternalIncludesWarning()) { - const externalIncludes = getExternalClaudeMdIncludes(await getMemoryFiles(true)); - const { - ClaudeMdExternalIncludesDialog: ClaudeMdExternalIncludesDialog2 - } = await Promise.resolve().then(() => (init_ClaudeMdExternalIncludesDialog(), exports_ClaudeMdExternalIncludesDialog)); - await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(ClaudeMdExternalIncludesDialog2, { - onDone: done, - isStandaloneDialog: true, - externalIncludes - }, undefined, false, undefined, this)); - } - } - updateGithubRepoPathMapping(); - if (false) {} - applyConfigEnvironmentVariables(); - setImmediate(() => initializeTelemetryAfterTrust()); - if (await isQualifiedForGrove()) { - const { - GroveDialog: GroveDialog2 - } = await Promise.resolve().then(() => (init_Grove(), exports_Grove)); - const decision = await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(GroveDialog2, { - showIfAlreadyViewed: false, - location: onboardingShown ? "onboarding" : "policy_update_modal", - onDone: done - }, undefined, false, undefined, this)); - if (decision === "escape") { - logEvent("tengu_grove_policy_exited", {}); - gracefulShutdownSync(0); - return false; - } - } - if (process.env.ANTHROPIC_API_KEY && !isRunningOnHomespace()) { - const customApiKeyTruncated = normalizeApiKeyForConfig(process.env.ANTHROPIC_API_KEY); - const keyStatus = getCustomApiKeyStatus(customApiKeyTruncated); - if (keyStatus === "new") { - const { - ApproveApiKey: ApproveApiKey2 - } = await Promise.resolve().then(() => (init_ApproveApiKey(), exports_ApproveApiKey)); - await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(ApproveApiKey2, { - customApiKeyTruncated, - onDone: done - }, undefined, false, undefined, this), { - onChangeAppState - }); - } - } - if ((permissionMode === "bypassPermissions" || allowDangerouslySkipPermissions) && !hasSkipDangerousModePermissionPrompt()) { - const { - BypassPermissionsModeDialog: BypassPermissionsModeDialog2 - } = await Promise.resolve().then(() => (init_BypassPermissionsModeDialog(), exports_BypassPermissionsModeDialog)); - await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(BypassPermissionsModeDialog2, { - onAccept: done - }, undefined, false, undefined, this)); - } - if (false) {} - if (false) {} - if (claudeInChrome && !getGlobalConfig().hasCompletedClaudeInChromeOnboarding) { - const { - ClaudeInChromeOnboarding: ClaudeInChromeOnboarding2 - } = await Promise.resolve().then(() => (init_ClaudeInChromeOnboarding(), exports_ClaudeInChromeOnboarding)); - await showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime482.jsxDEV(ClaudeInChromeOnboarding2, { - onDone: done - }, undefined, false, undefined, this)); - } - return onboardingShown; -} -function getRenderContext(exitOnCtrlC) { - let lastFlickerTime = 0; - const baseOptions = getBaseRenderOptions(exitOnCtrlC); - if (baseOptions.stdin) { - logEvent("tengu_stdin_interactive", {}); - } - const fpsTracker = new FpsTracker; - const stats2 = createStatsStore(); - setStatsStore(stats2); - const frameTimingLogPath = process.env.CLAUDE_CODE_FRAME_TIMING_LOG; - return { - getFpsMetrics: () => fpsTracker.getMetrics(), - stats: stats2, - renderOptions: { - ...baseOptions, - onFrame: (event) => { - fpsTracker.record(event.durationMs); - stats2.observe("frame_duration_ms", event.durationMs); - if (frameTimingLogPath && event.phases) { - const line = JSON.stringify({ - total: event.durationMs, - ...event.phases, - rss: process.memoryUsage.rss(), - cpu: process.cpuUsage() - }) + ` -`; - appendFileSync4(frameTimingLogPath, line); - } - if (isSynchronizedOutputSupported()) { - return; - } - for (const flicker of event.flickers) { - if (flicker.reason === "resize") { - continue; - } - const now2 = Date.now(); - if (now2 - lastFlickerTime < 1000) { - logEvent("tengu_flicker", { - desiredHeight: flicker.desiredHeight, - actualHeight: flicker.availableHeight, - reason: flicker.reason - }); - } - lastFlickerTime = now2; - } - } - } - }; -} - -// src/dialogLaunchers.tsx -init_KeybindingProviderSetup(); -var jsx_dev_runtime488 = __toESM(require_jsx_dev_runtime(), 1); -async function launchInvalidSettingsDialog(root3, props) { - const { - InvalidSettingsDialog: InvalidSettingsDialog2 - } = await Promise.resolve().then(() => (init_InvalidSettingsDialog(), exports_InvalidSettingsDialog)); - return showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime488.jsxDEV(InvalidSettingsDialog2, { - settingsErrors: props.settingsErrors, - onContinue: done, - onExit: props.onExit - }, undefined, false, undefined, this)); -} -async function launchTeleportResumeWrapper(root3) { - const { - TeleportResumeWrapper: TeleportResumeWrapper2 - } = await Promise.resolve().then(() => (init_TeleportResumeWrapper(), exports_TeleportResumeWrapper)); - return showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime488.jsxDEV(TeleportResumeWrapper2, { - onComplete: done, - onCancel: () => done(null), - source: "cliArg" - }, undefined, false, undefined, this)); -} -async function launchTeleportRepoMismatchDialog(root3, props) { - const { - TeleportRepoMismatchDialog: TeleportRepoMismatchDialog2 - } = await Promise.resolve().then(() => (init_TeleportRepoMismatchDialog(), exports_TeleportRepoMismatchDialog)); - return showSetupDialog(root3, (done) => /* @__PURE__ */ jsx_dev_runtime488.jsxDEV(TeleportRepoMismatchDialog2, { - targetRepo: props.targetRepo, - initialPaths: props.initialPaths, - onSelectPath: done, - onCancel: () => done(null) - }, undefined, false, undefined, this)); -} -async function launchResumeChooser(root3, appProps, worktreePathsPromise, resumeProps) { - const [worktreePaths, { - ResumeConversation: ResumeConversation2 - }, { - App: App3 - }] = await Promise.all([worktreePathsPromise, Promise.resolve().then(() => (init_ResumeConversation(), exports_ResumeConversation)), Promise.resolve().then(() => (init_App2(), exports_App))]); - await renderAndRun(root3, /* @__PURE__ */ jsx_dev_runtime488.jsxDEV(App3, { - getFpsMetrics: appProps.getFpsMetrics, - stats: appProps.stats, - initialState: appProps.initialState, - children: /* @__PURE__ */ jsx_dev_runtime488.jsxDEV(KeybindingSetup, { - children: /* @__PURE__ */ jsx_dev_runtime488.jsxDEV(ResumeConversation2, { - ...resumeProps, - worktreePaths - }, undefined, false, undefined, this) - }, undefined, false, undefined, this) - }, undefined, false, undefined, this)); -} - -// src/main.tsx -init_dec(); - -// src/plugins/bundled/index.ts -function initBuiltinPlugins() {} - -// src/main.tsx -init_claudeAiLimits(); -init_client22(); -init_pluginCliCommands(); - -// src/skills/bundled/index.ts -init_setup2(); - -// src/skills/bundled/batch.ts -init_constants3(); -init_prompt5(); -init_git(); -init_bundledSkills(); -var MIN_AGENTS = 5; -var MAX_AGENTS = 30; -var WORKER_INSTRUCTIONS = `After you finish implementing the change: -1. **Simplify** \u2014 Invoke the \`${SKILL_TOOL_NAME}\` tool with \`skill: "simplify"\` to review and clean up your changes. -2. **Run unit tests** \u2014 Run the project's test suite (check for package.json scripts, Makefile targets, or common commands like \`npm test\`, \`bun test\`, \`pytest\`, \`go test\`). If tests fail, fix them. -3. **Test end-to-end** \u2014 Follow the e2e test recipe from the coordinator's prompt (below). If the recipe says to skip e2e for this unit, skip it. -4. **Commit and push** \u2014 Commit all changes with a clear message, push the branch, and create a PR with \`gh pr create\`. Use a descriptive title. If \`gh\` is not available or the push fails, note it in your final message. -5. **Report** \u2014 End with a single line: \`PR: \` so the coordinator can track it. If no PR was created, end with \`PR: none \u2014 \`.`; -function buildPrompt(instruction) { - return `# Batch: Parallel Work Orchestration - -You are orchestrating a large, parallelizable change across this codebase. - -## User Instruction - -${instruction} - -## Phase 1: Research and Plan (Plan Mode) - -Call the \`${ENTER_PLAN_MODE_TOOL_NAME}\` tool now to enter plan mode, then: - -1. **Understand the scope.** Launch one or more subagents (in the foreground \u2014 you need their results) to deeply research what this instruction touches. Find all the files, patterns, and call sites that need to change. Understand the existing conventions so the migration is consistent. - -2. **Decompose into independent units.** Break the work into ${MIN_AGENTS}\u2013${MAX_AGENTS} self-contained units. Each unit must: - - Be independently implementable in an isolated git worktree (no shared state with sibling units) - - Be mergeable on its own without depending on another unit's PR landing first - - Be roughly uniform in size (split large units, merge trivial ones) - - Scale the count to the actual work: few files \u2192 closer to ${MIN_AGENTS}; hundreds of files \u2192 closer to ${MAX_AGENTS}. Prefer per-directory or per-module slicing over arbitrary file lists. - -3. **Determine the e2e test recipe.** Figure out how a worker can verify its change actually works end-to-end \u2014 not just that unit tests pass. Look for: - - A \`claude-in-chrome\` skill or browser-automation tool (for UI changes: click through the affected flow, screenshot the result) - - A \`tmux\` or CLI-verifier skill (for CLI changes: launch the app interactively, exercise the changed behavior) - - A dev-server + curl pattern (for API changes: start the server, hit the affected endpoints) - - An existing e2e/integration test suite the worker can run - - If you cannot find a concrete e2e path, use the \`${ASK_USER_QUESTION_TOOL_NAME}\` tool to ask the user how to verify this change end-to-end. Offer 2\u20133 specific options based on what you found (e.g., "Screenshot via chrome extension", "Run \`bun run dev\` and curl the endpoint", "No e2e \u2014 unit tests are sufficient"). Do not skip this \u2014 the workers cannot ask the user themselves. - - Write the recipe as a short, concrete set of steps that a worker can execute autonomously. Include any setup (start a dev server, build first) and the exact command/interaction to verify. - -4. **Write the plan.** In your plan file, include: - - A summary of what you found during research - - A numbered list of work units \u2014 for each: a short title, the list of files/directories it covers, and a one-line description of the change - - The e2e test recipe (or "skip e2e because \u2026" if the user chose that) - - The exact worker instructions you will give each agent (the shared template) - -5. Call \`${EXIT_PLAN_MODE_TOOL_NAME}\` to present the plan for approval. - -## Phase 2: Spawn Workers (After Plan Approval) - -Once the plan is approved, spawn one background agent per work unit using the \`${AGENT_TOOL_NAME}\` tool. **All agents must use \`isolation: "worktree"\` and \`run_in_background: true\`.** Launch them all in a single message block so they run in parallel. - -For each agent, the prompt must be fully self-contained. Include: -- The overall goal (the user's instruction) -- This unit's specific task (title, file list, change description \u2014 copied verbatim from your plan) -- Any codebase conventions you discovered that the worker needs to follow -- The e2e test recipe from your plan (or "skip e2e because \u2026") -- The worker instructions below, copied verbatim: - -\`\`\` -${WORKER_INSTRUCTIONS} -\`\`\` - -Use \`subagent_type: "general-purpose"\` unless a more specific agent type fits. - -## Phase 3: Track Progress - -After launching all workers, render an initial status table: - -| # | Unit | Status | PR | -|---|------|--------|----| -| 1 | | running | \u2014 | -| 2 | <title> | running | \u2014 | - -As background-agent completion notifications arrive, parse the \`PR: <url>\` line from each agent's result and re-render the table with updated status (\`done\` / \`failed\`) and PR links. Keep a brief failure note for any agent that did not produce a PR. - -When all agents have reported, render the final table and a one-line summary (e.g., "22/24 units landed as PRs"). -`; -} -var NOT_A_GIT_REPO_MESSAGE = `This is not a git repository. The \`/batch\` command requires a git repo because it spawns agents in isolated git worktrees and creates PRs from each. Initialize a repo first, or run this from inside an existing one.`; -var MISSING_INSTRUCTION_MESSAGE = `Provide an instruction describing the batch change you want to make. - -Examples: - /batch migrate from react to vue - /batch replace all uses of lodash with native equivalents - /batch add type annotations to all untyped function parameters`; -function registerBatchSkill() { - registerBundledSkill({ - name: "batch", - description: "Research and plan a large-scale change, then execute it in parallel across 5\u201330 isolated worktree agents that each open a PR.", - whenToUse: "Use when the user wants to make a sweeping, mechanical change across many files (migrations, refactors, bulk renames) that can be decomposed into independent parallel units.", - argumentHint: "<instruction>", - userInvocable: true, - disableModelInvocation: true, - async getPromptForCommand(args) { - const instruction = args.trim(); - if (!instruction) { - return [{ type: "text", text: MISSING_INSTRUCTION_MESSAGE }]; - } - const isGit = await getIsGit(); - if (!isGit) { - return [{ type: "text", text: NOT_A_GIT_REPO_MESSAGE }]; - } - return [{ type: "text", text: buildPrompt(instruction) }]; - } - }); -} - -// src/skills/bundled/claudeInChrome.ts -init_setup2(); -init_bundledSkills(); -var import_claude_for_chrome_mcp3 = __toESM(require_claude_for_chrome_mcp(), 1); -var CLAUDE_IN_CHROME_MCP_TOOLS = import_claude_for_chrome_mcp3.BROWSER_TOOLS.map((tool) => `mcp__claude-in-chrome__${tool.name}`); -var SKILL_ACTIVATION_MESSAGE = ` -Now that this skill is invoked, you have access to Chrome browser automation tools. You can now use the mcp__claude-in-chrome__* tools to interact with web pages. - -IMPORTANT: Start by calling mcp__claude-in-chrome__tabs_context_mcp to get information about the user's current browser tabs. -`; -function registerClaudeInChromeSkill() { - registerBundledSkill({ - name: "claude-in-chrome", - description: "Automates your Chrome browser to interact with web pages - clicking elements, filling forms, capturing screenshots, reading console logs, and navigating sites. Opens pages in new tabs within your existing Chrome session. Requires site-level permissions before executing (configured in the extension).", - whenToUse: "When the user wants to interact with web pages, automate browser tasks, capture screenshots, read console logs, or perform any browser-based actions. Always invoke BEFORE attempting to use any mcp__claude-in-chrome__* tools.", - allowedTools: CLAUDE_IN_CHROME_MCP_TOOLS, - userInvocable: true, - isEnabled: () => shouldAutoEnableClaudeInChrome(), - async getPromptForCommand(args) { - let prompt = `${BASE_CHROME_PROMPT} -${SKILL_ACTIVATION_MESSAGE}`; - if (args) { - prompt += ` -## Task - -${args}`; - } - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/debug.ts -init_claudeCodeGuideAgent(); -init_settings2(); -init_debug(); -init_errors(); -init_format(); -init_bundledSkills(); -import { open as open18, stat as stat47 } from "fs/promises"; -var DEFAULT_DEBUG_LINES_READ = 20; -var TAIL_READ_BYTES = 64 * 1024; -function registerDebugSkill() { - registerBundledSkill({ - name: "debug", - description: process.env.USER_TYPE === "ant" ? "Debug your current Claude Code session by reading the session debug log. Includes all event logging" : "Enable debug logging for this session and help diagnose issues", - allowedTools: ["Read", "Grep", "Glob"], - argumentHint: "[issue description]", - disableModelInvocation: true, - userInvocable: true, - async getPromptForCommand(args) { - const wasAlreadyLogging = enableDebugLogging(); - const debugLogPath = getDebugLogPath(); - let logInfo; - try { - const stats2 = await stat47(debugLogPath); - const readSize = Math.min(stats2.size, TAIL_READ_BYTES); - const startOffset = stats2.size - readSize; - const fd2 = await open18(debugLogPath, "r"); - try { - const { buffer, bytesRead } = await fd2.read({ - buffer: Buffer.alloc(readSize), - position: startOffset - }); - const tail = buffer.toString("utf-8", 0, bytesRead).split(` -`).slice(-DEFAULT_DEBUG_LINES_READ).join(` -`); - logInfo = `Log size: ${formatFileSize(stats2.size)} - -### Last ${DEFAULT_DEBUG_LINES_READ} lines - -\`\`\` -${tail} -\`\`\``; - } finally { - await fd2.close(); - } - } catch (e4) { - logInfo = isENOENT(e4) ? "No debug log exists yet \u2014 logging was just enabled." : `Failed to read last ${DEFAULT_DEBUG_LINES_READ} lines of debug log: ${errorMessage(e4)}`; - } - const justEnabledSection = wasAlreadyLogging ? "" : ` -## Debug Logging Just Enabled - -Debug logging was OFF for this session until now. Nothing prior to this /debug invocation was captured. - -Tell the user that debug logging is now active at \`${debugLogPath}\`, ask them to reproduce the issue, then re-read the log. If they can't reproduce, they can also restart with \`claude --debug\` to capture logs from startup. -`; - const prompt = `# Debug Skill - -Help the user debug an issue they're encountering in this current Claude Code session. -${justEnabledSection} -## Session Debug Log - -The debug log for the current session is at: \`${debugLogPath}\` - -${logInfo} - -For additional context, grep for [ERROR] and [WARN] lines across the full file. - -## Issue Description - -${args || "The user did not describe a specific issue. Read the debug log and summarize any errors, warnings, or notable issues."} - -## Settings - -Remember that settings are in: -* user - ${getSettingsFilePathForSource("userSettings")} -* project - ${getSettingsFilePathForSource("projectSettings")} -* local - ${getSettingsFilePathForSource("localSettings")} - -## Instructions - -1. Review the user's issue description -2. The last ${DEFAULT_DEBUG_LINES_READ} lines show the debug file format. Look for [ERROR] and [WARN] entries, stack traces, and failure patterns across the file -3. Consider launching the ${CLAUDE_CODE_GUIDE_AGENT_TYPE} subagent to understand the relevant Claude Code features -4. Explain what you found in plain language -5. Suggest concrete fixes or next steps -`; - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/keybindings.ts -init_defaultBindings(); -init_loadUserBindings(); -init_reservedShortcuts(); - -// src/keybindings/schema.ts -init_v4(); -var KEYBINDING_CONTEXTS = [ - "Global", - "Chat", - "Autocomplete", - "Confirmation", - "Help", - "Transcript", - "HistorySearch", - "Task", - "ThemePicker", - "Settings", - "Tabs", - "Attachments", - "Footer", - "MessageSelector", - "DiffDialog", - "ModelPicker", - "Select", - "Plugin" -]; -var KEYBINDING_CONTEXT_DESCRIPTIONS = { - Global: "Active everywhere, regardless of focus", - Chat: "When the chat input is focused", - Autocomplete: "When autocomplete menu is visible", - Confirmation: "When a confirmation/permission dialog is shown", - Help: "When the help overlay is open", - Transcript: "When viewing the transcript", - HistorySearch: "When searching command history (ctrl+r)", - Task: "When a task/agent is running in the foreground", - ThemePicker: "When the theme picker is open", - Settings: "When the settings menu is open", - Tabs: "When tab navigation is active", - Attachments: "When navigating image attachments in a select dialog", - Footer: "When footer indicators are focused", - MessageSelector: "When the message selector (rewind) is open", - DiffDialog: "When the diff dialog is open", - ModelPicker: "When the model picker is open", - Select: "When a select/list component is focused", - Plugin: "When the plugin dialog is open" -}; -var KEYBINDING_ACTIONS = [ - "app:interrupt", - "app:exit", - "app:toggleTodos", - "app:toggleTranscript", - "app:toggleBrief", - "app:toggleTeammatePreview", - "app:toggleTerminal", - "app:redraw", - "app:globalSearch", - "app:quickOpen", - "history:search", - "history:previous", - "history:next", - "chat:cancel", - "chat:killAgents", - "chat:cycleMode", - "chat:modelPicker", - "chat:fastMode", - "chat:thinkingToggle", - "chat:submit", - "chat:newline", - "chat:undo", - "chat:externalEditor", - "chat:stash", - "chat:imagePaste", - "chat:messageActions", - "autocomplete:accept", - "autocomplete:dismiss", - "autocomplete:previous", - "autocomplete:next", - "confirm:yes", - "confirm:no", - "confirm:previous", - "confirm:next", - "confirm:nextField", - "confirm:previousField", - "confirm:cycleMode", - "confirm:toggle", - "confirm:toggleExplanation", - "tabs:next", - "tabs:previous", - "transcript:toggleShowAll", - "transcript:exit", - "historySearch:next", - "historySearch:accept", - "historySearch:cancel", - "historySearch:execute", - "task:background", - "theme:toggleSyntaxHighlighting", - "help:dismiss", - "attachments:next", - "attachments:previous", - "attachments:remove", - "attachments:exit", - "footer:up", - "footer:down", - "footer:next", - "footer:previous", - "footer:openSelected", - "footer:clearSelection", - "footer:close", - "messageSelector:up", - "messageSelector:down", - "messageSelector:top", - "messageSelector:bottom", - "messageSelector:select", - "diff:dismiss", - "diff:previousSource", - "diff:nextSource", - "diff:back", - "diff:viewDetails", - "diff:previousFile", - "diff:nextFile", - "modelPicker:decreaseEffort", - "modelPicker:increaseEffort", - "select:next", - "select:previous", - "select:accept", - "select:cancel", - "plugin:toggle", - "plugin:install", - "permission:toggleDebug", - "settings:search", - "settings:retry", - "settings:close", - "voice:pushToTalk" -]; -var KeybindingBlockSchema = lazySchema(() => exports_external.object({ - context: exports_external.enum(KEYBINDING_CONTEXTS).describe("UI context where these bindings apply. Global bindings work everywhere."), - bindings: exports_external.record(exports_external.string().describe('Keystroke pattern (e.g., "ctrl+k", "shift+tab")'), exports_external.union([ - exports_external.enum(KEYBINDING_ACTIONS), - exports_external.string().regex(/^command:[a-zA-Z0-9:\-_]+$/).describe('Command binding (e.g., "command:help", "command:compact"). Executes the slash command as if typed.'), - exports_external.null().describe("Set to null to unbind a default shortcut") - ]).describe("Action to trigger, command to invoke, or null to unbind")).describe("Map of keystroke patterns to actions") -}).describe("A block of keybindings for a specific context")); -var KeybindingsSchema = lazySchema(() => exports_external.object({ - $schema: exports_external.string().optional().describe("JSON Schema URL for editor validation"), - $docs: exports_external.string().optional().describe("Documentation URL"), - bindings: exports_external.array(KeybindingBlockSchema()).describe("Array of keybinding blocks by context") -}).describe("Claude Code keybindings configuration. Customize keyboard shortcuts by context.")); - -// src/skills/bundled/keybindings.ts -init_slowOperations(); -init_bundledSkills(); -function generateContextsTable() { - return markdownTable(["Context", "Description"], KEYBINDING_CONTEXTS.map((ctx) => [ - `\`${ctx}\``, - KEYBINDING_CONTEXT_DESCRIPTIONS[ctx] - ])); -} -function generateActionsTable() { - const actionInfo = {}; - for (const block2 of DEFAULT_BINDINGS) { - for (const [key2, action2] of Object.entries(block2.bindings)) { - if (action2) { - if (!actionInfo[action2]) { - actionInfo[action2] = { keys: [], context: block2.context }; - } - actionInfo[action2].keys.push(key2); - } - } - } - return markdownTable(["Action", "Default Key(s)", "Context"], KEYBINDING_ACTIONS.map((action2) => { - const info = actionInfo[action2]; - const keys2 = info ? info.keys.map((k4) => `\`${k4}\``).join(", ") : "(none)"; - const context7 = info ? info.context : inferContextFromAction(action2); - return [`\`${action2}\``, keys2, context7]; - })); -} -function inferContextFromAction(action2) { - const prefix = action2.split(":")[0]; - const prefixToContext = { - app: "Global", - history: "Global or Chat", - chat: "Chat", - autocomplete: "Autocomplete", - confirm: "Confirmation", - tabs: "Tabs", - transcript: "Transcript", - historySearch: "HistorySearch", - task: "Task", - theme: "ThemePicker", - help: "Help", - attachments: "Attachments", - footer: "Footer", - messageSelector: "MessageSelector", - diff: "DiffDialog", - modelPicker: "ModelPicker", - select: "Select", - permission: "Confirmation" - }; - return prefixToContext[prefix ?? ""] ?? "Unknown"; -} -function generateReservedShortcuts() { - const lines2 = []; - lines2.push("### Non-rebindable (errors)"); - for (const s4 of NON_REBINDABLE) { - lines2.push(`- \`${s4.key}\` \u2014 ${s4.reason}`); - } - lines2.push(""); - lines2.push("### Terminal reserved (errors/warnings)"); - for (const s4 of TERMINAL_RESERVED) { - lines2.push(`- \`${s4.key}\` \u2014 ${s4.reason} (${s4.severity === "error" ? "will not work" : "may conflict"})`); - } - lines2.push(""); - lines2.push("### macOS reserved (errors)"); - for (const s4 of MACOS_RESERVED) { - lines2.push(`- \`${s4.key}\` \u2014 ${s4.reason}`); - } - return lines2.join(` -`); -} -var FILE_FORMAT_EXAMPLE = { - $schema: "https://www.schemastore.org/claude-code-keybindings.json", - $docs: "https://code.claude.com/docs/en/keybindings", - bindings: [ - { - context: "Chat", - bindings: { - "ctrl+e": "chat:externalEditor" - } - } - ] -}; -var UNBIND_EXAMPLE = { - context: "Chat", - bindings: { - "ctrl+s": null - } -}; -var REBIND_EXAMPLE = { - context: "Chat", - bindings: { - "ctrl+g": null, - "ctrl+e": "chat:externalEditor" - } -}; -var CHORD_EXAMPLE = { - context: "Global", - bindings: { - "ctrl+k ctrl+t": "app:toggleTodos" - } -}; -var SECTION_INTRO = [ - "# Keybindings Skill", - "", - "Create or modify `~/.claude/keybindings.json` to customize keyboard shortcuts.", - "", - "## CRITICAL: Read Before Write", - "", - "**Always read `~/.claude/keybindings.json` first** (it may not exist yet). Merge changes with existing bindings \u2014 never replace the entire file.", - "", - "- Use **Edit** tool for modifications to existing files", - "- Use **Write** tool only if the file does not exist yet" -].join(` -`); -var SECTION_FILE_FORMAT = [ - "## File Format", - "", - "```json", - jsonStringify(FILE_FORMAT_EXAMPLE, null, 2), - "```", - "", - "Always include the `$schema` and `$docs` fields." -].join(` -`); -var SECTION_KEYSTROKE_SYNTAX = [ - "## Keystroke Syntax", - "", - "**Modifiers** (combine with `+`):", - "- `ctrl` (alias: `control`)", - "- `alt` (aliases: `opt`, `option`) \u2014 note: `alt` and `meta` are identical in terminals", - "- `shift`", - "- `meta` (aliases: `cmd`, `command`)", - "", - "**Special keys**: `escape`/`esc`, `enter`/`return`, `tab`, `space`, `backspace`, `delete`, `up`, `down`, `left`, `right`", - "", - "**Chords**: Space-separated keystrokes, e.g. `ctrl+k ctrl+s` (1-second timeout between keystrokes)", - "", - "**Examples**: `ctrl+shift+p`, `alt+enter`, `ctrl+k ctrl+n`" -].join(` -`); -var SECTION_UNBINDING = [ - "## Unbinding Default Shortcuts", - "", - "Set a key to `null` to remove its default binding:", - "", - "```json", - jsonStringify(UNBIND_EXAMPLE, null, 2), - "```" -].join(` -`); -var SECTION_INTERACTION = [ - "## How User Bindings Interact with Defaults", - "", - "- User bindings are **additive** \u2014 they are appended after the default bindings", - "- To **move** a binding to a different key: unbind the old key (`null`) AND add the new binding", - "- A context only needs to appear in the user's file if they want to change something in that context" -].join(` -`); -var SECTION_COMMON_PATTERNS = [ - "## Common Patterns", - "", - "### Rebind a key", - "To change the external editor shortcut from `ctrl+g` to `ctrl+e`:", - "```json", - jsonStringify(REBIND_EXAMPLE, null, 2), - "```", - "", - "### Add a chord binding", - "```json", - jsonStringify(CHORD_EXAMPLE, null, 2), - "```" -].join(` -`); -var SECTION_BEHAVIORAL_RULES = [ - "## Behavioral Rules", - "", - "1. Only include contexts the user wants to change (minimal overrides)", - "2. Validate that actions and contexts are from the known lists below", - "3. Warn the user proactively if they choose a key that conflicts with reserved shortcuts or common tools like tmux (`ctrl+b`) and screen (`ctrl+a`)", - "4. When adding a new binding for an existing action, the new binding is additive (existing default still works unless explicitly unbound)", - "5. To fully replace a default binding, unbind the old key AND add the new one" -].join(` -`); -var SECTION_DOCTOR = [ - "## Validation with /doctor", - "", - 'The `/doctor` command includes a "Keybinding Configuration Issues" section that validates `~/.claude/keybindings.json`.', - "", - "### Common Issues and Fixes", - "", - markdownTable(["Issue", "Cause", "Fix"], [ - [ - '`keybindings.json must have a "bindings" array`', - "Missing wrapper object", - 'Wrap bindings in `{ "bindings": [...] }`' - ], - [ - '`"bindings" must be an array`', - "`bindings` is not an array", - 'Set `"bindings"` to an array: `[{ context: ..., bindings: ... }]`' - ], - [ - '`Unknown context "X"`', - "Typo or invalid context name", - "Use exact context names from the Available Contexts table" - ], - [ - '`Duplicate key "X" in Y bindings`', - "Same key defined twice in one context", - "Remove the duplicate; JSON uses only the last value" - ], - [ - '`"X" may not work: ...`', - "Key conflicts with terminal/OS reserved shortcut", - "Choose a different key (see Reserved Shortcuts section)" - ], - [ - '`Could not parse keystroke "X"`', - "Invalid key syntax", - "Check syntax: use `+` between modifiers, valid key names" - ], - [ - '`Invalid action for "X"`', - "Action value is not a string or null", - 'Actions must be strings like `"app:help"` or `null` to unbind' - ] - ]), - "", - "### Example /doctor Output", - "", - "```", - "Keybinding Configuration Issues", - "Location: ~/.claude/keybindings.json", - ' \u2514 [Error] Unknown context "chat"', - " \u2192 Valid contexts: Global, Chat, Autocomplete, ...", - ' \u2514 [Warning] "ctrl+c" may not work: Terminal interrupt (SIGINT)', - "```", - "", - "**Errors** prevent bindings from working and must be fixed. **Warnings** indicate potential conflicts but the binding may still work." -].join(` -`); -function registerKeybindingsSkill() { - registerBundledSkill({ - name: "keybindings-help", - description: 'Use when the user wants to customize keyboard shortcuts, rebind keys, add chord bindings, or modify ~/.claude/keybindings.json. Examples: "rebind ctrl+s", "add a chord shortcut", "change the submit key", "customize keybindings".', - allowedTools: ["Read"], - userInvocable: false, - isEnabled: isKeybindingCustomizationEnabled, - async getPromptForCommand(args) { - const contextsTable = generateContextsTable(); - const actionsTable = generateActionsTable(); - const reservedShortcuts = generateReservedShortcuts(); - const sections = [ - SECTION_INTRO, - SECTION_FILE_FORMAT, - SECTION_KEYSTROKE_SYNTAX, - SECTION_UNBINDING, - SECTION_INTERACTION, - SECTION_COMMON_PATTERNS, - SECTION_BEHAVIORAL_RULES, - SECTION_DOCTOR, - `## Reserved Shortcuts - -${reservedShortcuts}`, - `## Available Contexts - -${contextsTable}`, - `## Available Actions - -${actionsTable}` - ]; - if (args) { - sections.push(`## User Request - -${args}`); - } - return [{ type: "text", text: sections.join(` - -`) }]; - } - }); -} -function markdownTable(headers, rows) { - const separator = headers.map(() => "---"); - return [ - `| ${headers.join(" | ")} |`, - `| ${separator.join(" | ")} |`, - ...rows.map((row) => `| ${row.join(" | ")} |`) - ].join(` -`); -} - -// src/skills/bundled/loremIpsum.ts -init_bundledSkills(); -var ONE_TOKEN_WORDS = [ - "the", - "a", - "an", - "I", - "you", - "he", - "she", - "it", - "we", - "they", - "me", - "him", - "her", - "us", - "them", - "my", - "your", - "his", - "its", - "our", - "this", - "that", - "what", - "who", - "is", - "are", - "was", - "were", - "be", - "been", - "have", - "has", - "had", - "do", - "does", - "did", - "will", - "would", - "can", - "could", - "may", - "might", - "must", - "shall", - "should", - "make", - "made", - "get", - "got", - "go", - "went", - "come", - "came", - "see", - "saw", - "know", - "take", - "think", - "look", - "want", - "use", - "find", - "give", - "tell", - "work", - "call", - "try", - "ask", - "need", - "feel", - "seem", - "leave", - "put", - "time", - "year", - "day", - "way", - "man", - "thing", - "life", - "hand", - "part", - "place", - "case", - "point", - "fact", - "good", - "new", - "first", - "last", - "long", - "great", - "little", - "own", - "other", - "old", - "right", - "big", - "high", - "small", - "large", - "next", - "early", - "young", - "few", - "public", - "bad", - "same", - "able", - "in", - "on", - "at", - "to", - "for", - "of", - "with", - "from", - "by", - "about", - "like", - "through", - "over", - "before", - "between", - "under", - "since", - "without", - "and", - "or", - "but", - "if", - "than", - "because", - "as", - "until", - "while", - "so", - "though", - "both", - "each", - "when", - "where", - "why", - "how", - "not", - "now", - "just", - "more", - "also", - "here", - "there", - "then", - "only", - "very", - "well", - "back", - "still", - "even", - "much", - "too", - "such", - "never", - "again", - "most", - "once", - "off", - "away", - "down", - "out", - "up", - "test", - "code", - "data", - "file", - "line", - "text", - "word", - "number", - "system", - "program", - "set", - "run", - "value", - "name", - "type", - "state", - "end", - "start" -]; -function generateLoremIpsum(targetTokens) { - let tokens = 0; - let result = ""; - while (tokens < targetTokens) { - const sentenceLength = 10 + Math.floor(Math.random() * 11); - let wordsInSentence = 0; - for (let i6 = 0;i6 < sentenceLength && tokens < targetTokens; i6++) { - const word = ONE_TOKEN_WORDS[Math.floor(Math.random() * ONE_TOKEN_WORDS.length)]; - result += word; - tokens++; - wordsInSentence++; - if (i6 === sentenceLength - 1 || tokens >= targetTokens) { - result += ". "; - } else { - result += " "; - } - } - if (wordsInSentence > 0 && Math.random() < 0.2 && tokens < targetTokens) { - result += ` - -`; - } - } - return result.trim(); -} -function registerLoremIpsumSkill() { - if (process.env.USER_TYPE !== "ant") { - return; - } - registerBundledSkill({ - name: "lorem-ipsum", - description: "Generate filler text for long context testing. Specify token count as argument (e.g., /lorem-ipsum 50000). Outputs approximately the requested number of tokens. Ant-only.", - argumentHint: "[token_count]", - userInvocable: true, - async getPromptForCommand(args) { - const parsed = parseInt(args); - if (args && (isNaN(parsed) || parsed <= 0)) { - return [ - { - type: "text", - text: "Invalid token count. Please provide a positive number (e.g., /lorem-ipsum 10000)." - } - ]; - } - const targetTokens = parsed || 1e4; - const cappedTokens = Math.min(targetTokens, 500000); - if (cappedTokens < targetTokens) { - return [ - { - type: "text", - text: `Requested ${targetTokens} tokens, but capped at 500,000 for safety. - -${generateLoremIpsum(cappedTokens)}` - } - ]; - } - const loremText = generateLoremIpsum(cappedTokens); - return [ - { - type: "text", - text: loremText - } - ]; - } - }); -} - -// src/skills/bundled/remember.ts -init_paths(); -init_bundledSkills(); -function registerRememberSkill() { - if (process.env.USER_TYPE !== "ant") { - return; - } - const SKILL_PROMPT = `# Memory Review - -## Goal -Review the user's memory landscape and produce a clear report of proposed changes, grouped by action type. Do NOT apply changes \u2014 present proposals for user approval. - -## Steps - -### 1. Gather all memory layers -Read CLAUDE.md and CLAUDE.local.md from the project root (if they exist). Your auto-memory content is already in your system prompt \u2014 review it there. Note which team memory sections exist, if any. - -**Success criteria**: You have the contents of all memory layers and can compare them. - -### 2. Classify each auto-memory entry -For each substantive entry in auto-memory, determine the best destination: - -| Destination | What belongs there | Examples | -|---|---|---| -| **CLAUDE.md** | Project conventions and instructions for Claude that all contributors should follow | "use bun not npm", "API routes use kebab-case", "test command is bun test", "prefer functional style" | -| **CLAUDE.local.md** | Personal instructions for Claude specific to this user, not applicable to other contributors | "I prefer concise responses", "always explain trade-offs", "don't auto-commit", "run tests before committing" | -| **Team memory** | Org-wide knowledge that applies across repositories (only if team memory is configured) | "deploy PRs go through #deploy-queue", "staging is at staging.internal", "platform team owns infra" | -| **Stay in auto-memory** | Working notes, temporary context, or entries that don't clearly fit elsewhere | Session-specific observations, uncertain patterns | - -**Important distinctions:** -- CLAUDE.md and CLAUDE.local.md contain instructions for Claude, not user preferences for external tools (editor theme, IDE keybindings, etc. don't belong in either) -- Workflow practices (PR conventions, merge strategies, branch naming) are ambiguous \u2014 ask the user whether they're personal or team-wide -- When unsure, ask rather than guess - -**Success criteria**: Each entry has a proposed destination or is flagged as ambiguous. - -### 3. Identify cleanup opportunities -Scan across all layers for: -- **Duplicates**: Auto-memory entries already captured in CLAUDE.md or CLAUDE.local.md \u2192 propose removing from auto-memory -- **Outdated**: CLAUDE.md or CLAUDE.local.md entries contradicted by newer auto-memory entries \u2192 propose updating the older layer -- **Conflicts**: Contradictions between any two layers \u2192 propose resolution, noting which is more recent - -**Success criteria**: All cross-layer issues identified. - -### 4. Present the report -Output a structured report grouped by action type: -1. **Promotions** \u2014 entries to move, with destination and rationale -2. **Cleanup** \u2014 duplicates, outdated entries, conflicts to resolve -3. **Ambiguous** \u2014 entries where you need the user's input on destination -4. **No action needed** \u2014 brief note on entries that should stay put - -If auto-memory is empty, say so and offer to review CLAUDE.md for cleanup. - -**Success criteria**: User can review and approve/reject each proposal individually. - -## Rules -- Present ALL proposals before making any changes -- Do NOT modify files without explicit user approval -- Do NOT create new files unless the target doesn't exist yet -- Ask about ambiguous entries \u2014 don't guess -`; - registerBundledSkill({ - name: "remember", - description: "Review auto-memory entries and propose promotions to CLAUDE.md, CLAUDE.local.md, or shared memory. Also detects outdated, conflicting, and duplicate entries across memory layers.", - whenToUse: "Use when the user wants to review, organize, or promote their auto-memory entries. Also useful for cleaning up outdated or conflicting entries across CLAUDE.md, CLAUDE.local.md, and auto-memory.", - userInvocable: true, - isEnabled: () => isAutoMemoryEnabled(), - async getPromptForCommand(args) { - let prompt = SKILL_PROMPT; - if (args) { - prompt += ` -## Additional context from user - -${args}`; - } - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/simplify.ts -init_constants3(); -init_bundledSkills(); -var SIMPLIFY_PROMPT = `# Simplify: Code Review and Cleanup - -Review all changed files for reuse, quality, and efficiency. Fix any issues found. - -## Phase 1: Identify Changes - -Run \`git diff\` (or \`git diff HEAD\` if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation. - -## Phase 2: Launch Three Review Agents in Parallel - -Use the ${AGENT_TOOL_NAME} tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context. - -### Agent 1: Code Reuse Review - -For each change: - -1. **Search for existing utilities and helpers** that could replace newly written code. Look for similar patterns elsewhere in the codebase \u2014 common locations are utility directories, shared modules, and files adjacent to the changed ones. -2. **Flag any new function that duplicates existing functionality.** Suggest the existing function to use instead. -3. **Flag any inline logic that could use an existing utility** \u2014 hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates. - -### Agent 2: Code Quality Review - -Review the same changes for hacky patterns: - -1. **Redundant state**: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls -2. **Parameter sprawl**: adding new parameters to a function instead of generalizing or restructuring existing ones -3. **Copy-paste with slight variation**: near-duplicate code blocks that should be unified with a shared abstraction -4. **Leaky abstractions**: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries -5. **Stringly-typed code**: using raw strings where constants, enums (string unions), or branded types already exist in the codebase -6. **Unnecessary JSX nesting**: wrapper Boxes/elements that add no layout value \u2014 check if inner component props (flexShrink, alignItems, etc.) already provide the needed behavior -7. **Unnecessary comments**: comments explaining WHAT the code does (well-named identifiers already do that), narrating the change, or referencing the task/caller \u2014 delete; keep only non-obvious WHY (hidden constraints, subtle invariants, workarounds) - -### Agent 3: Efficiency Review - -Review the same changes for efficiency: - -1. **Unnecessary work**: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns -2. **Missed concurrency**: independent operations run sequentially when they could run in parallel -3. **Hot-path bloat**: new blocking work added to startup or per-request/per-render hot paths -4. **Recurring no-op updates**: state/store updates inside polling loops, intervals, or event handlers that fire unconditionally \u2014 add a change-detection guard so downstream consumers aren't notified when nothing changed. Also: if a wrapper function takes an updater/reducer callback, verify it honors same-reference returns (or whatever the "no change" signal is) \u2014 otherwise callers' early-return no-ops are silently defeated -5. **Unnecessary existence checks**: pre-checking file/resource existence before operating (TOCTOU anti-pattern) \u2014 operate directly and handle the error -6. **Memory**: unbounded data structures, missing cleanup, event listener leaks -7. **Overly broad operations**: reading entire files when only a portion is needed, loading all items when filtering for one - -## Phase 3: Fix Issues - -Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on \u2014 do not argue with the finding, just skip it. - -When done, briefly summarize what was fixed (or confirm the code was already clean). -`; -function registerSimplifySkill() { - registerBundledSkill({ - name: "simplify", - description: "Review changed code for reuse, quality, and efficiency, then fix any issues found.", - userInvocable: true, - async getPromptForCommand(args) { - let prompt = SIMPLIFY_PROMPT; - if (args) { - prompt += ` - -## Additional Focus - -${args}`; - } - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/skillify.ts -init_sessionMemoryUtils(); -init_messages9(); -init_bundledSkills(); -function extractUserMessages(messages) { - return messages.filter((m4) => m4.type === "user").map((m4) => { - const content = m4.message.content; - if (typeof content === "string") - return content; - return content.filter((b5) => b5.type === "text").map((b5) => b5.text).join(` -`); - }).filter((text) => text.trim().length > 0); -} -var SKILLIFY_PROMPT = `# Skillify {{userDescriptionBlock}} - -You are capturing this session's repeatable process as a reusable skill. - -## Your Session Context - -Here is the session memory summary: -<session_memory> -{{sessionMemory}} -</session_memory> - -Here are the user's messages during this session. Pay attention to how they steered the process, to help capture their detailed preferences in the skill: -<user_messages> -{{userMessages}} -</user_messages> - -## Your Task - -### Step 1: Analyze the Session - -Before asking any questions, analyze the session to identify: -- What repeatable process was performed -- What the inputs/parameters were -- The distinct steps (in order) -- The success artifacts/criteria (e.g. not just "writing code," but "an open PR with CI fully passing") for each step -- Where the user corrected or steered you -- What tools and permissions were needed -- What agents were used -- What the goals and success artifacts were - -### Step 2: Interview the User - -You will use the AskUserQuestion to understand what the user wants to automate. Important notes: -- Use AskUserQuestion for ALL questions! Never ask questions via plain text. -- For each round, iterate as much as needed until the user is happy. -- The user always has a freeform "Other" option to type edits or feedback -- do NOT add your own "Needs tweaking" or "I'll provide edits" option. Just offer the substantive choices. - -**Round 1: High level confirmation** -- Suggest a name and description for the skill based on your analysis. Ask the user to confirm or rename. -- Suggest high-level goal(s) and specific success criteria for the skill. - -**Round 2: More details** -- Present the high-level steps you identified as a numbered list. Tell the user you will dig into the detail in the next round. -- If you think the skill will require arguments, suggest arguments based on what you observed. Make sure you understand what someone would need to provide. -- If it's not clear, ask if this skill should run inline (in the current conversation) or forked (as a sub-agent with its own context). Forked is better for self-contained tasks that don't need mid-process user input; inline is better when the user wants to steer mid-process. -- Ask where the skill should be saved. Suggest a default based on context (repo-specific workflows \u2192 repo, cross-repo personal workflows \u2192 user). Options: - - **This repo** (\`.claude/skills/<name>/SKILL.md\`) \u2014 for workflows specific to this project - - **Personal** (\`~/.claude/skills/<name>/SKILL.md\`) \u2014 follows you across all repos - -**Round 3: Breaking down each step** -For each major step, if it's not glaringly obvious, ask: -- What does this step produce that later steps need? (data, artifacts, IDs) -- What proves that this step succeeded, and that we can move on? -- Should the user be asked to confirm before proceeding? (especially for irreversible actions like merging, sending messages, or destructive operations) -- Are any steps independent and could run in parallel? (e.g., posting to Slack and monitoring CI at the same time) -- How should the skill be executed? (e.g. always use a Task agent to conduct code review, or invoke an agent team for a set of concurrent steps) -- What are the hard constraints or hard preferences? Things that must or must not happen? - -You may do multiple rounds of AskUserQuestion here, one round per step, especially if there are more than 3 steps or many clarification questions. Iterate as much as needed. - -IMPORTANT: Pay special attention to places where the user corrected you during the session, to help inform your design. - -**Round 4: Final questions** -- Confirm when this skill should be invoked, and suggest/confirm trigger phrases too. (e.g. For a cherrypick workflow you could say: Use when the user wants to cherry-pick a PR to a release branch. Examples: 'cherry-pick to release', 'CP this PR', 'hotfix.') -- You can also ask for any other gotchas or things to watch out for, if it's still unclear. - -Stop interviewing once you have enough information. IMPORTANT: Don't over-ask for simple processes! - -### Step 3: Write the SKILL.md - -Create the skill directory and file at the location the user chose in Round 2. - -Use this format: - -\`\`\`markdown ---- -name: {{skill-name}} -description: {{one-line description}} -allowed-tools: - {{list of tool permission patterns observed during session}} -when_to_use: {{detailed description of when Claude should automatically invoke this skill, including trigger phrases and example user messages}} -argument-hint: "{{hint showing argument placeholders}}" -arguments: - {{list of argument names}} -context: {{inline or fork -- omit for inline}} ---- - -# {{Skill Title}} -Description of skill - -## Inputs -- \`$arg_name\`: Description of this input - -## Goal -Clearly stated goal for this workflow. Best if you have clearly defined artifacts or criteria for completion. - -## Steps - -### 1. Step Name -What to do in this step. Be specific and actionable. Include commands when appropriate. - -**Success criteria**: ALWAYS include this! This shows that the step is done and we can move on. Can be a list. - -IMPORTANT: see the next section below for the per-step annotations you can optionally include for each step. - -... -\`\`\` - -**Per-step annotations**: -- **Success criteria** is REQUIRED on every step. This helps the model understand what the user expects from their workflow, and when it should have the confidence to move on. -- **Execution**: \`Direct\` (default), \`Task agent\` (straightforward subagents), \`Teammate\` (agent with true parallelism and inter-agent communication), or \`[human]\` (user does it). Only needs specifying if not Direct. -- **Artifacts**: Data this step produces that later steps need (e.g., PR number, commit SHA). Only include if later steps depend on it. -- **Human checkpoint**: When to pause and ask the user before proceeding. Include for irreversible actions (merging, sending messages), error judgment (merge conflicts), or output review. -- **Rules**: Hard rules for the workflow. User corrections during the reference session can be especially useful here. - -**Step structure tips:** -- Steps that can run concurrently use sub-numbers: 3a, 3b -- Steps requiring the user to act get \`[human]\` in the title -- Keep simple skills simple -- a 2-step skill doesn't need annotations on every step - -**Frontmatter rules:** -- \`allowed-tools\`: Minimum permissions needed (use patterns like \`Bash(gh:*)\` not \`Bash\`) -- \`context\`: Only set \`context: fork\` for self-contained skills that don't need mid-process user input. -- \`when_to_use\` is CRITICAL -- tells the model when to auto-invoke. Start with "Use when..." and include trigger phrases. Example: "Use when the user wants to cherry-pick a PR to a release branch. Examples: 'cherry-pick to release', 'CP this PR', 'hotfix'." -- \`arguments\` and \`argument-hint\`: Only include if the skill takes parameters. Use \`$name\` in the body for substitution. - -### Step 4: Confirm and Save - -Before writing the file, output the complete SKILL.md content as a yaml code block in your response so the user can review it with proper syntax highlighting. Then ask for confirmation using AskUserQuestion with a simple question like "Does this SKILL.md look good to save?" \u2014 do NOT use the body field, keep the question concise. - -After writing, tell the user: -- Where the skill was saved -- How to invoke it: \`/{{skill-name}} [arguments]\` -- That they can edit the SKILL.md directly to refine it -`; -function registerSkillifySkill() { - if (process.env.USER_TYPE !== "ant") { - return; - } - registerBundledSkill({ - name: "skillify", - description: "Capture this session's repeatable process into a skill. Call at end of the process you want to capture with an optional description.", - allowedTools: [ - "Read", - "Write", - "Edit", - "Glob", - "Grep", - "AskUserQuestion", - "Bash(mkdir:*)" - ], - userInvocable: true, - disableModelInvocation: true, - argumentHint: "[description of the process you want to capture]", - async getPromptForCommand(args, context7) { - const sessionMemory = await getSessionMemoryContent() ?? "No session memory available."; - const userMessages = extractUserMessages(getMessagesAfterCompactBoundary(context7.messages)); - const userDescriptionBlock = args ? `The user described this process as: "${args}"` : ""; - const prompt = SKILLIFY_PROMPT.replace("{{sessionMemory}}", sessionMemory).replace("{{userMessages}}", userMessages.join(` - ---- - -`)).replace("{{userDescriptionBlock}}", userDescriptionBlock); - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/stuck.ts -init_bundledSkills(); -var STUCK_PROMPT = `# /stuck \u2014 diagnose frozen/slow Claude Code sessions - -The user thinks another Claude Code session on this machine is frozen, stuck, or very slow. Investigate and post a report to #claude-code-feedback. - -## What to look for - -Scan for other Claude Code processes (excluding the current one \u2014 PID is in \`process.pid\` but for shell commands just exclude the PID you see running this prompt). Process names are typically \`claude\` (installed) or \`cli\` (native dev build). - -Signs of a stuck session: -- **High CPU (\u226590%) sustained** \u2014 likely an infinite loop. Sample twice, 1-2s apart, to confirm it's not a transient spike. -- **Process state \`D\` (uninterruptible sleep)** \u2014 often an I/O hang. The \`state\` column in \`ps\` output; first character matters (ignore modifiers like \`+\`, \`s\`, \`<\`). -- **Process state \`T\` (stopped)** \u2014 user probably hit Ctrl+Z by accident. -- **Process state \`Z\` (zombie)** \u2014 parent isn't reaping. -- **Very high RSS (\u22654GB)** \u2014 possible memory leak making the session sluggish. -- **Stuck child process** \u2014 a hung \`git\`, \`node\`, or shell subprocess can freeze the parent. Check \`pgrep -lP <pid>\` for each session. - -## Investigation steps - -1. **List all Claude Code processes** (macOS/Linux): - \`\`\` - ps -axo pid=,pcpu=,rss=,etime=,state=,comm=,command= | grep -E '(claude|cli)' | grep -v grep - \`\`\` - Filter to rows where \`comm\` is \`claude\` or (\`cli\` AND the command path contains "claude"). - -2. **For anything suspicious**, gather more context: - - Child processes: \`pgrep -lP <pid>\` - - If high CPU: sample again after 1-2s to confirm it's sustained - - If a child looks hung (e.g., a git command), note its full command line with \`ps -p <child_pid> -o command=\` - - Check the session's debug log if you can infer the session ID: \`~/.claude/debug/<session-id>.txt\` (the last few hundred lines often show what it was doing before hanging) - -3. **Consider a stack dump** for a truly frozen process (advanced, optional): - - macOS: \`sample <pid> 3\` gives a 3-second native stack sample - - This is big \u2014 only grab it if the process is clearly hung and you want to know *why* - -## Report - -**Only post to Slack if you actually found something stuck.** If every session looks healthy, tell the user that directly \u2014 do not post an all-clear to the channel. - -If you did find a stuck/slow session, post to **#claude-code-feedback** (channel ID: \`C07VBSHV7EV\`) using the Slack MCP tool. Use ToolSearch to find \`slack_send_message\` if it's not already loaded. - -**Use a two-message structure** to keep the channel scannable: - -1. **Top-level message** \u2014 one short line: hostname, Claude Code version, and a terse symptom (e.g. "session PID 12345 pegged at 100% CPU for 10min" or "git subprocess hung in D state"). No code blocks, no details. -2. **Thread reply** \u2014 the full diagnostic dump. Pass the top-level message's \`ts\` as \`thread_ts\`. Include: - - PID, CPU%, RSS, state, uptime, command line, child processes - - Your diagnosis of what's likely wrong - - Relevant debug log tail or \`sample\` output if you captured it - -If Slack MCP isn't available, format the report as a message the user can copy-paste into #claude-code-feedback (and let them know to thread the details themselves). - -## Notes -- Don't kill or signal any processes \u2014 this is diagnostic only. -- If the user gave an argument (e.g., a specific PID or symptom), focus there first. -`; -function registerStuckSkill() { - if (process.env.USER_TYPE !== "ant") { - return; - } - registerBundledSkill({ - name: "stuck", - description: "[ANT-ONLY] Investigate frozen/stuck/slow Claude Code sessions on this machine and post a diagnostic report to #claude-code-feedback.", - userInvocable: true, - async getPromptForCommand(args) { - let prompt = STUCK_PROMPT; - if (args) { - prompt += ` -## User-provided context - -${args} -`; - } - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/updateConfig.ts -init_v4(); -init_types2(); -init_slowOperations(); -init_bundledSkills(); -function generateSettingsSchema() { - const jsonSchema = toJSONSchema(SettingsSchema(), { io: "input" }); - return jsonStringify(jsonSchema, null, 2); -} -var SETTINGS_EXAMPLES_DOCS = `## Settings File Locations - -Choose the appropriate file based on scope: - -| File | Scope | Git | Use For | -|------|-------|-----|---------| -| \`~/.claude/settings.json\` | Global | N/A | Personal preferences for all projects | -| \`.claude/settings.json\` | Project | Commit | Team-wide hooks, permissions, plugins | -| \`.claude/settings.local.json\` | Project | Gitignore | Personal overrides for this project | - -Settings load in order: user \u2192 project \u2192 local (later overrides earlier). - -## Settings Schema Reference - -### Permissions -\`\`\`json -{ - "permissions": { - "allow": ["Bash(npm:*)", "Edit(.claude)", "Read"], - "deny": ["Bash(rm -rf:*)"], - "ask": ["Write(/etc/*)"], - "defaultMode": "default" | "plan" | "acceptEdits" | "dontAsk", - "additionalDirectories": ["/extra/dir"] - } -} -\`\`\` - -**Permission Rule Syntax:** -- Exact match: \`"Bash(npm run test)"\` -- Prefix wildcard: \`"Bash(git:*)"\` - matches \`git status\`, \`git commit\`, etc. -- Tool only: \`"Read"\` - allows all Read operations - -### Environment Variables -\`\`\`json -{ - "env": { - "DEBUG": "true", - "MY_API_KEY": "value" - } -} -\`\`\` - -### Model & Agent -\`\`\`json -{ - "model": "sonnet", // or "opus", "haiku", full model ID - "agent": "agent-name", - "alwaysThinkingEnabled": true -} -\`\`\` - -### Attribution (Commits & PRs) -\`\`\`json -{ - "attribution": { - "commit": "Custom commit trailer text", - "pr": "Custom PR description text" - } -} -\`\`\` -Set \`commit\` or \`pr\` to empty string \`""\` to hide that attribution. - -### MCP Server Management -\`\`\`json -{ - "enableAllProjectMcpServers": true, - "enabledMcpjsonServers": ["server1", "server2"], - "disabledMcpjsonServers": ["blocked-server"] -} -\`\`\` - -### Plugins -\`\`\`json -{ - "enabledPlugins": { - "formatter@anthropic-tools": true - } -} -\`\`\` -Plugin syntax: \`plugin-name@source\` where source is \`claude-code-marketplace\`, \`claude-plugins-official\`, or \`builtin\`. - -### Other Settings -- \`language\`: Preferred response language (e.g., "japanese") -- \`cleanupPeriodDays\`: Days to keep transcripts (default: 30; 0 disables persistence entirely) -- \`respectGitignore\`: Whether to respect .gitignore (default: true) -- \`spinnerTipsEnabled\`: Show tips in spinner -- \`spinnerVerbs\`: Customize spinner verbs (\`{ "mode": "append" | "replace", "verbs": [...] }\`) -- \`spinnerTipsOverride\`: Override spinner tips (\`{ "excludeDefault": true, "tips": ["Custom tip"] }\`) -- \`syntaxHighlightingDisabled\`: Disable diff highlighting -`; -var HOOKS_DOCS = `## Hooks Configuration - -Hooks run commands at specific points in Claude Code's lifecycle. - -### Hook Structure -\`\`\`json -{ - "hooks": { - "EVENT_NAME": [ - { - "matcher": "ToolName|OtherTool", - "hooks": [ - { - "type": "command", - "command": "your-command-here", - "timeout": 60, - "statusMessage": "Running..." - } - ] - } - ] - } -} -\`\`\` - -### Hook Events - -| Event | Matcher | Purpose | -|-------|---------|---------| -| PermissionRequest | Tool name | Run before permission prompt | -| PreToolUse | Tool name | Run before tool, can block | -| PostToolUse | Tool name | Run after successful tool | -| PostToolUseFailure | Tool name | Run after tool fails | -| Notification | Notification type | Run on notifications | -| Stop | - | Run when Claude stops (including clear, resume, compact) | -| PreCompact | "manual"/"auto" | Before compaction | -| PostCompact | "manual"/"auto" | After compaction (receives summary) | -| UserPromptSubmit | - | When user submits | -| SessionStart | - | When session starts | - -**Common tool matchers:** \`Bash\`, \`Write\`, \`Edit\`, \`Read\`, \`Glob\`, \`Grep\` - -### Hook Types - -**1. Command Hook** - Runs a shell command: -\`\`\`json -{ "type": "command", "command": "prettier --write $FILE", "timeout": 30 } -\`\`\` - -**2. Prompt Hook** - Evaluates a condition with LLM: -\`\`\`json -{ "type": "prompt", "prompt": "Is this safe? $ARGUMENTS" } -\`\`\` -Only available for tool events: PreToolUse, PostToolUse, PermissionRequest. - -**3. Agent Hook** - Runs an agent with tools: -\`\`\`json -{ "type": "agent", "prompt": "Verify tests pass: $ARGUMENTS" } -\`\`\` -Only available for tool events: PreToolUse, PostToolUse, PermissionRequest. - -### Hook Input (stdin JSON) -\`\`\`json -{ - "session_id": "abc123", - "tool_name": "Write", - "tool_input": { "file_path": "/path/to/file.txt", "content": "..." }, - "tool_response": { "success": true } // PostToolUse only -} -\`\`\` - -### Hook JSON Output - -Hooks can return JSON to control behavior: - -\`\`\`json -{ - "systemMessage": "Warning shown to user in UI", - "continue": false, - "stopReason": "Message shown when blocking", - "suppressOutput": false, - "decision": "block", - "reason": "Explanation for decision", - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": "Context injected back to model" - } -} -\`\`\` - -**Fields:** -- \`systemMessage\` - Display a message to the user (all hooks) -- \`continue\` - Set to \`false\` to block/stop (default: true) -- \`stopReason\` - Message shown when \`continue\` is false -- \`suppressOutput\` - Hide stdout from transcript (default: false) -- \`decision\` - "block" for PostToolUse/Stop/UserPromptSubmit hooks (deprecated for PreToolUse, use hookSpecificOutput.permissionDecision instead) -- \`reason\` - Explanation for decision -- \`hookSpecificOutput\` - Event-specific output (must include \`hookEventName\`): - - \`additionalContext\` - Text injected into model context - - \`permissionDecision\` - "allow", "deny", or "ask" (PreToolUse only) - - \`permissionDecisionReason\` - Reason for the permission decision (PreToolUse only) - - \`updatedInput\` - Modified tool input (PreToolUse only) - -### Common Patterns - -**Auto-format after writes:** -\`\`\`json -{ - "hooks": { - "PostToolUse": [{ - "matcher": "Write|Edit", - "hooks": [{ - "type": "command", - "command": "jq -r '.tool_response.filePath // .tool_input.file_path' | { read -r f; prettier --write \\"$f\\"; } 2>/dev/null || true" - }] - }] - } -} -\`\`\` - -**Log all bash commands:** -\`\`\`json -{ - "hooks": { - "PreToolUse": [{ - "matcher": "Bash", - "hooks": [{ - "type": "command", - "command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt" - }] - }] - } -} -\`\`\` - -**Stop hook that displays message to user:** - -Command must output JSON with \`systemMessage\` field: -\`\`\`bash -# Example command that outputs: {"systemMessage": "Session complete!"} -echo '{"systemMessage": "Session complete!"}' -\`\`\` - -**Run tests after code changes:** -\`\`\`json -{ - "hooks": { - "PostToolUse": [{ - "matcher": "Write|Edit", - "hooks": [{ - "type": "command", - "command": "jq -r '.tool_input.file_path // .tool_response.filePath' | grep -E '\\\\.(ts|js)$' && npm test || true" - }] - }] - } -} -\`\`\` -`; -var HOOK_VERIFICATION_FLOW = `## Constructing a Hook (with verification) - -Given an event, matcher, target file, and desired behavior, follow this flow. Each step catches a different failure class \u2014 a hook that silently does nothing is worse than no hook. - -1. **Dedup check.** Read the target file. If a hook already exists on the same event+matcher, show the existing command and ask: keep it, replace it, or add alongside. - -2. **Construct the command for THIS project \u2014 don't assume.** The hook receives JSON on stdin. Build a command that: - - Extracts any needed payload safely \u2014 use \`jq -r\` into a quoted variable or \`{ read -r f; ... "$f"; }\`, NOT unquoted \`| xargs\` (splits on spaces) - - Invokes the underlying tool the way this project runs it (npx/bunx/yarn/pnpm? Makefile target? globally-installed?) - - Skips inputs the tool doesn't handle (formatters often have \`--ignore-unknown\`; if not, guard by extension) - - Stays RAW for now \u2014 no \`|| true\`, no stderr suppression. You'll wrap it after the pipe-test passes. - -3. **Pipe-test the raw command.** Synthesize the stdin payload the hook will receive and pipe it directly: - - \`Pre|PostToolUse\` on \`Write|Edit\`: \`echo '{"tool_name":"Edit","tool_input":{"file_path":"<a real file from this repo>"}}' | <cmd>\` - - \`Pre|PostToolUse\` on \`Bash\`: \`echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | <cmd>\` - - \`Stop\`/\`UserPromptSubmit\`/\`SessionStart\`: most commands don't read stdin, so \`echo '{}' | <cmd>\` suffices - - Check exit code AND side effect (file actually formatted, test actually ran). If it fails you get a real error \u2014 fix (wrong package manager? tool not installed? jq path wrong?) and retest. Once it works, wrap with \`2>/dev/null || true\` (unless the user wants a blocking check). - -4. **Write the JSON.** Merge into the target file (schema shape in the "Hook Structure" section above). If this creates \`.claude/settings.local.json\` for the first time, add it to .gitignore \u2014 the Write tool doesn't auto-gitignore it. - -5. **Validate syntax + schema in one shot:** - - \`jq -e '.hooks.<event>[] | select(.matcher == "<matcher>") | .hooks[] | select(.type == "command") | .command' <target-file>\` - - Exit 0 + prints your command = correct. Exit 4 = matcher doesn't match. Exit 5 = malformed JSON or wrong nesting. A broken settings.json silently disables ALL settings from that file \u2014 fix any pre-existing malformation too. - -6. **Prove the hook fires** \u2014 only for \`Pre|PostToolUse\` on a matcher you can trigger in-turn (\`Write|Edit\` via Edit, \`Bash\` via Bash). \`Stop\`/\`UserPromptSubmit\`/\`SessionStart\` fire outside this turn \u2014 skip to step 7. - - For a **formatter** on \`PostToolUse\`/\`Write|Edit\`: introduce a detectable violation via Edit (two consecutive blank lines, bad indentation, missing semicolon \u2014 something this formatter corrects; NOT trailing whitespace, Edit strips that before writing), re-read, confirm the hook **fixed** it. For **anything else**: temporarily prefix the command in settings.json with \`echo "$(date) hook fired" >> /tmp/claude-hook-check.txt; \`, trigger the matching tool (Edit for \`Write|Edit\`, a harmless \`true\` for \`Bash\`), read the sentinel file. - - **Always clean up** \u2014 revert the violation, strip the sentinel prefix \u2014 whether the proof passed or failed. - - **If proof fails but pipe-test passed and \`jq -e\` passed**: the settings watcher isn't watching \`.claude/\` \u2014 it only watches directories that had a settings file when this session started. The hook is written correctly. Tell the user to open \`/hooks\` once (reloads config) or restart \u2014 you can't do this yourself; \`/hooks\` is a user UI menu and opening it ends this turn. - -7. **Handoff.** Tell the user the hook is live (or needs \`/hooks\`/restart per the watcher caveat). Point them at \`/hooks\` to review, edit, or disable it later. The UI only shows "Ran N hooks" if a hook errors or is slow \u2014 silent success is invisible by design. -`; -var UPDATE_CONFIG_PROMPT = `# Update Config Skill - -Modify Claude Code configuration by updating settings.json files. - -## When Hooks Are Required (Not Memory) - -If the user wants something to happen automatically in response to an EVENT, they need a **hook** configured in settings.json. Memory/preferences cannot trigger automated actions. - -**These require hooks:** -- "Before compacting, ask me what to preserve" \u2192 PreCompact hook -- "After writing files, run prettier" \u2192 PostToolUse hook with Write|Edit matcher -- "When I run bash commands, log them" \u2192 PreToolUse hook with Bash matcher -- "Always run tests after code changes" \u2192 PostToolUse hook - -**Hook events:** PreToolUse, PostToolUse, PreCompact, PostCompact, Stop, Notification, SessionStart - -## CRITICAL: Read Before Write - -**Always read the existing settings file before making changes.** Merge new settings with existing ones - never replace the entire file. - -## CRITICAL: Use AskUserQuestion for Ambiguity - -When the user's request is ambiguous, use AskUserQuestion to clarify: -- Which settings file to modify (user/project/local) -- Whether to add to existing arrays or replace them -- Specific values when multiple options exist - -## Decision: Config Tool vs Direct Edit - -**Use the Config tool** for these simple settings: -- \`theme\`, \`editorMode\`, \`verbose\`, \`model\` -- \`language\`, \`alwaysThinkingEnabled\` -- \`permissions.defaultMode\` - -**Edit settings.json directly** for: -- Hooks (PreToolUse, PostToolUse, etc.) -- Complex permission rules (allow/deny arrays) -- Environment variables -- MCP server configuration -- Plugin configuration - -## Workflow - -1. **Clarify intent** - Ask if the request is ambiguous -2. **Read existing file** - Use Read tool on the target settings file -3. **Merge carefully** - Preserve existing settings, especially arrays -4. **Edit file** - Use Edit tool (if file doesn't exist, ask user to create it first) -5. **Confirm** - Tell user what was changed - -## Merging Arrays (Important!) - -When adding to permission arrays or hook arrays, **merge with existing**, don't replace: - -**WRONG** (replaces existing permissions): -\`\`\`json -{ "permissions": { "allow": ["Bash(npm:*)"] } } -\`\`\` - -**RIGHT** (preserves existing + adds new): -\`\`\`json -{ - "permissions": { - "allow": [ - "Bash(git:*)", // existing - "Edit(.claude)", // existing - "Bash(npm:*)" // new - ] - } -} -\`\`\` - -${SETTINGS_EXAMPLES_DOCS} - -${HOOKS_DOCS} - -${HOOK_VERIFICATION_FLOW} - -## Example Workflows - -### Adding a Hook - -User: "Format my code after Claude writes it" - -1. **Clarify**: Which formatter? (prettier, gofmt, etc.) -2. **Read**: \`.claude/settings.json\` (or create if missing) -3. **Merge**: Add to existing hooks, don't replace -4. **Result**: -\`\`\`json -{ - "hooks": { - "PostToolUse": [{ - "matcher": "Write|Edit", - "hooks": [{ - "type": "command", - "command": "jq -r '.tool_response.filePath // .tool_input.file_path' | { read -r f; prettier --write \\"$f\\"; } 2>/dev/null || true" - }] - }] - } -} -\`\`\` - -### Adding Permissions - -User: "Allow npm commands without prompting" - -1. **Read**: Existing permissions -2. **Merge**: Add \`Bash(npm:*)\` to allow array -3. **Result**: Combined with existing allows - -### Environment Variables - -User: "Set DEBUG=true" - -1. **Decide**: User settings (global) or project settings? -2. **Read**: Target file -3. **Merge**: Add to env object -\`\`\`json -{ "env": { "DEBUG": "true" } } -\`\`\` - -## Common Mistakes to Avoid - -1. **Replacing instead of merging** - Always preserve existing settings -2. **Wrong file** - Ask user if scope is unclear -3. **Invalid JSON** - Validate syntax after changes -4. **Forgetting to read first** - Always read before write - -## Troubleshooting Hooks - -If a hook isn't running: -1. **Check the settings file** - Read ~/.claude/settings.json or .claude/settings.json -2. **Verify JSON syntax** - Invalid JSON silently fails -3. **Check the matcher** - Does it match the tool name? (e.g., "Bash", "Write", "Edit") -4. **Check hook type** - Is it "command", "prompt", or "agent"? -5. **Test the command** - Run the hook command manually to see if it works -6. **Use --debug** - Run \`claude --debug\` to see hook execution logs -`; -function registerUpdateConfigSkill() { - registerBundledSkill({ - name: "update-config", - description: 'Use this skill to configure the Claude Code harness via settings.json. Automated behaviors ("from now on when X", "each time X", "whenever X", "before/after X") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them. Also use for: permissions ("allow X", "add permission", "move permission to"), env vars ("set X=Y"), hook troubleshooting, or any changes to settings.json/settings.local.json files. Examples: "allow npm commands", "add bq permission to global settings", "move permission to user settings", "set DEBUG=true", "when claude stops show X". For simple settings like theme/model, use Config tool.', - allowedTools: ["Read"], - userInvocable: true, - async getPromptForCommand(args) { - if (args.startsWith("[hooks-only]")) { - const req = args.slice("[hooks-only]".length).trim(); - let prompt2 = HOOKS_DOCS + ` - -` + HOOK_VERIFICATION_FLOW; - if (req) { - prompt2 += ` - -## Task - -${req}`; - } - return [{ type: "text", text: prompt2 }]; - } - const jsonSchema = generateSettingsSchema(); - let prompt = UPDATE_CONFIG_PROMPT; - prompt += ` - -## Full Settings JSON Schema - -\`\`\`json -${jsonSchema} -\`\`\``; - if (args) { - prompt += ` - -## User Request - -${args}`; - } - return [{ type: "text", text: prompt }]; - } - }); -} - -// src/skills/bundled/verify.ts -init_frontmatterParser(); -init_bundledSkills(); - -// src/skills/bundled/verify/examples/cli.md -var cli_default = `<h1>CLI Examples</h1> -<p>Stub for compilation.</p> -`; - -// src/skills/bundled/verify/examples/server.md -var server_default = `<h1>Server Examples</h1> -<p>Stub for compilation.</p> -`; - -// src/skills/bundled/verify/SKILL.md -var SKILL_default = `<h1>Verify Skill</h1> -<p>Stub skill for compilation.</p> -`; - -// src/skills/bundled/verifyContent.ts -var SKILL_MD = SKILL_default; -var SKILL_FILES = { - "examples/cli.md": cli_default, - "examples/server.md": server_default -}; - -// src/skills/bundled/verify.ts -var { frontmatter, content: SKILL_BODY } = parseFrontmatter(SKILL_MD); -var DESCRIPTION19 = typeof frontmatter.description === "string" ? frontmatter.description : "Verify a code change does what it should by running the app."; -function registerVerifySkill() { - if (process.env.USER_TYPE !== "ant") { - return; - } - registerBundledSkill({ - name: "verify", - description: DESCRIPTION19, - userInvocable: true, - files: SKILL_FILES, - async getPromptForCommand(args) { - const parts = [SKILL_BODY.trimStart()]; - if (args) { - parts.push(`## User Request - -${args}`); - } - return [{ type: "text", text: parts.join(` - -`) }]; - } - }); -} - -// src/skills/bundled/index.ts -function initBundledSkills() { - registerUpdateConfigSkill(); - registerKeybindingsSkill(); - registerVerifySkill(); - registerDebugSkill(); - registerLoremIpsumSkill(); - registerSkillifySkill(); - registerRememberSkill(); - registerSimplifySkill(); - registerBatchSkill(); - registerStuckSkill(); - if (false) {} - if (false) {} - if (false) {} - if (false) {} - if (false) {} - if (shouldAutoEnableClaudeInChrome()) { - registerClaudeInChromeSkill(); - } - if (false) {} -} - -// src/main.tsx -init_loadAgentsDir(); -init_autoUpdater(); -init_setup2(); -init_context(); -init_conversationRecovery(); - -// src/utils/deepLink/banner.ts -init_format(); -init_gitFilesystem(); -init_git(); -var STALE_FETCH_WARN_MS = 7 * 24 * 60 * 60 * 1000; - -// src/main.tsx -init_envUtils(); -init_exampleCommands(); -init_getWorktreePaths(); -init_git(); - -// src/utils/github/ghAuthStatus.ts -init_execa(); -init_which(); -async function getGhAuthStatus() { - const ghPath = await which("gh"); - if (!ghPath) { - return "not_installed"; - } - const { exitCode } = await execa("gh", ["auth", "token"], { - stdout: "ignore", - stderr: "ignore", - timeout: 5000, - reject: false - }); - return exitCode === 0 ? "authenticated" : "not_authenticated"; -} - -// src/main.tsx -init_json(); -init_log2(); -init_deprecation(); -init_model(); -init_modelStrings(); -init_PermissionMode(); -init_permissionSetup(); -init_cacheUtils(); -init_installedPluginsManager(); -init_managedPlugins(); -init_orphanedPluginFilter(); -init_pluginDirectories(); -init_ripgrep(); -init_sessionStart(); -init_sessionStorage(); -init_settings(); -init_settings2(); -init_settingsCache(); -init_tasks(); -init_pluginTelemetry(); - -// src/utils/telemetry/skillLoadedEvent.ts -init_commands5(); -init_analytics(); -init_prompt9(); -async function logSkillsLoaded(cwd2, contextWindowTokens) { - const skills2 = await getSkillToolCommands(cwd2); - const skillBudget = getCharBudget(contextWindowTokens); - for (const skill of skills2) { - if (skill.type !== "prompt") - continue; - logEvent("tengu_skill_loaded", { - _PROTO_skill_name: skill.name, - skill_source: skill.source, - skill_loaded_from: skill.loadedFrom, - skill_budget: skillBudget, - ...skill.kind && { - skill_kind: skill.kind - } - }); - } -} - -// src/main.tsx -init_tempfile(); -init_uuid(); - -// src/commands/mcp/addCommand.ts -init_analytics(); -init_auth18(); -init_config9(); -init_utils8(); -init_xaaIdpLogin(); -init_envUtils(); -init_slowOperations(); -function registerMcpAddCommand(mcp2) { - mcp2.command("add <name> <commandOrUrl> [args...]").description(`Add an MCP server to Claude Code. - -` + `Examples: -` + ` # Add HTTP server: -` + ` claude mcp add --transport http sentry https://mcp.sentry.dev/mcp - -` + ` # Add HTTP server with headers: -` + ` claude mcp add --transport http corridor https://app.corridor.dev/api/mcp --header "Authorization: Bearer ..." - -` + ` # Add stdio server with environment variables: -` + ` claude mcp add -e API_KEY=xxx my-server -- npx my-mcp-server - -` + ` # Add stdio server with subprocess flags: -` + " claude mcp add my-server -- my-command --some-flag arg1").option("-s, --scope <scope>", "Configuration scope (local, user, or project)", "local").option("-t, --transport <transport>", "Transport type (stdio, sse, http). Defaults to stdio if not specified.").option("-e, --env <env...>", "Set environment variables (e.g. -e KEY=value)").option("-H, --header <header...>", 'Set WebSocket headers (e.g. -H "X-Api-Key: abc123" -H "X-Custom: value")').option("--client-id <clientId>", "OAuth client ID for HTTP/SSE servers").option("--client-secret", "Prompt for OAuth client secret (or set MCP_CLIENT_SECRET env var)").option("--callback-port <port>", "Fixed port for OAuth callback (for servers requiring pre-registered redirect URIs)").helpOption("-h, --help", "Display help for command").addOption(new Option("--xaa", "Enable XAA (SEP-990) for this server. Requires 'claude mcp xaa setup' first. Also requires --client-id and --client-secret (for the MCP server's AS).").hideHelp(!isXaaEnabled())).action(async (name3, commandOrUrl, args, options2) => { - const actualCommand = commandOrUrl; - const actualArgs = args; - if (!name3) { - cliError(`Error: Server name is required. -` + "Usage: claude mcp add <name> <command> [args...]"); - } else if (!actualCommand) { - cliError(`Error: Command is required when server name is provided. -` + "Usage: claude mcp add <name> <command> [args...]"); - } - try { - const scope = ensureConfigScope(options2.scope); - const transport = ensureTransport(options2.transport); - if (options2.xaa && !isXaaEnabled()) { - cliError("Error: --xaa requires CLAUDE_CODE_ENABLE_XAA=1 in your environment"); - } - const xaa = Boolean(options2.xaa); - if (xaa) { - const missing = []; - if (!options2.clientId) - missing.push("--client-id"); - if (!options2.clientSecret) - missing.push("--client-secret"); - if (!getXaaIdpSettings()) { - missing.push("'claude mcp xaa setup' (settings.xaaIdp not configured)"); - } - if (missing.length) { - cliError(`Error: --xaa requires: ${missing.join(", ")}`); - } - } - const transportExplicit = options2.transport !== undefined; - const looksLikeUrl = actualCommand.startsWith("http://") || actualCommand.startsWith("https://") || actualCommand.startsWith("localhost") || actualCommand.endsWith("/sse") || actualCommand.endsWith("/mcp"); - logEvent("tengu_mcp_add", { - type: transport, - scope, - source: "command", - transport, - transportExplicit, - looksLikeUrl - }); - if (transport === "sse") { - if (!actualCommand) { - cliError("Error: URL is required for SSE transport."); - } - const headers = options2.header ? parseHeaders(options2.header) : undefined; - const callbackPort = options2.callbackPort ? parseInt(options2.callbackPort, 10) : undefined; - const oauth = options2.clientId || callbackPort || xaa ? { - ...options2.clientId ? { clientId: options2.clientId } : {}, - ...callbackPort ? { callbackPort } : {}, - ...xaa ? { xaa: true } : {} - } : undefined; - const clientSecret = options2.clientSecret && options2.clientId ? await readClientSecret() : undefined; - const serverConfig = { - type: "sse", - url: actualCommand, - headers, - oauth - }; - await addMcpConfig(name3, serverConfig, scope); - if (clientSecret) { - saveMcpClientSecret(name3, serverConfig, clientSecret); - } - process.stdout.write(`Added SSE MCP server ${name3} with URL: ${actualCommand} to ${scope} config -`); - if (headers) { - process.stdout.write(`Headers: ${jsonStringify(headers, null, 2)} -`); - } - } else if (transport === "http") { - if (!actualCommand) { - cliError("Error: URL is required for HTTP transport."); - } - const headers = options2.header ? parseHeaders(options2.header) : undefined; - const callbackPort = options2.callbackPort ? parseInt(options2.callbackPort, 10) : undefined; - const oauth = options2.clientId || callbackPort || xaa ? { - ...options2.clientId ? { clientId: options2.clientId } : {}, - ...callbackPort ? { callbackPort } : {}, - ...xaa ? { xaa: true } : {} - } : undefined; - const clientSecret = options2.clientSecret && options2.clientId ? await readClientSecret() : undefined; - const serverConfig = { - type: "http", - url: actualCommand, - headers, - oauth - }; - await addMcpConfig(name3, serverConfig, scope); - if (clientSecret) { - saveMcpClientSecret(name3, serverConfig, clientSecret); - } - process.stdout.write(`Added HTTP MCP server ${name3} with URL: ${actualCommand} to ${scope} config -`); - if (headers) { - process.stdout.write(`Headers: ${jsonStringify(headers, null, 2)} -`); - } - } else { - if (options2.clientId || options2.clientSecret || options2.callbackPort || options2.xaa) { - process.stderr.write(`Warning: --client-id, --client-secret, --callback-port, and --xaa are only supported for HTTP/SSE transports and will be ignored for stdio. -`); - } - if (!transportExplicit && looksLikeUrl) { - process.stderr.write(` -Warning: The command "${actualCommand}" looks like a URL, but is being interpreted as a stdio server as --transport was not specified. -`); - process.stderr.write(`If this is an HTTP server, use: claude mcp add --transport http ${name3} ${actualCommand} -`); - process.stderr.write(`If this is an SSE server, use: claude mcp add --transport sse ${name3} ${actualCommand} -`); - } - const env5 = parseEnvVars(options2.env); - await addMcpConfig(name3, { type: "stdio", command: actualCommand, args: actualArgs, env: env5 }, scope); - process.stdout.write(`Added stdio MCP server ${name3} with command: ${actualCommand} ${actualArgs.join(" ")} to ${scope} config -`); - } - cliOk(`File modified: ${describeMcpConfigFilePath(scope)}`); - } catch (error46) { - cliError(error46.message); - } - }); -} - -// src/commands/mcp/xaaIdpCommand.ts -init_xaaIdpLogin(); -init_errors(); -init_settings2(); -function registerMcpXaaIdpCommand(mcp2) { - const xaaIdp = mcp2.command("xaa").description("Manage the XAA (SEP-990) IdP connection"); - xaaIdp.command("setup").description("Configure the IdP connection (one-time setup for all XAA-enabled servers)").requiredOption("--issuer <url>", "IdP issuer URL (OIDC discovery)").requiredOption("--client-id <id>", "Claude Code's client_id at the IdP").option("--client-secret", "Read IdP client secret from MCP_XAA_IDP_CLIENT_SECRET env var").option("--callback-port <port>", "Fixed loopback callback port (only if IdP does not honor RFC 8252 port-any matching)").action((options2) => { - let issuerUrl; - try { - issuerUrl = new URL(options2.issuer); - } catch { - return cliError(`Error: --issuer must be a valid URL (got "${options2.issuer}")`); - } - if (issuerUrl.protocol !== "https:" && !(issuerUrl.protocol === "http:" && (issuerUrl.hostname === "localhost" || issuerUrl.hostname === "127.0.0.1" || issuerUrl.hostname === "[::1]"))) { - return cliError(`Error: --issuer must use https:// (got "${issuerUrl.protocol}//${issuerUrl.host}")`); - } - const callbackPort = options2.callbackPort ? parseInt(options2.callbackPort, 10) : undefined; - if (callbackPort !== undefined && (!Number.isInteger(callbackPort) || callbackPort <= 0)) { - return cliError("Error: --callback-port must be a positive integer"); - } - const secret = options2.clientSecret ? process.env.MCP_XAA_IDP_CLIENT_SECRET : undefined; - if (options2.clientSecret && !secret) { - return cliError("Error: --client-secret requires MCP_XAA_IDP_CLIENT_SECRET env var"); - } - const old = getXaaIdpSettings(); - const oldIssuer = old?.issuer; - const oldClientId = old?.clientId; - const { error: error46 } = updateSettingsForSource("userSettings", { - xaaIdp: { - issuer: options2.issuer, - clientId: options2.clientId, - callbackPort - } - }); - if (error46) { - return cliError(`Error writing settings: ${error46.message}`); - } - if (oldIssuer) { - if (issuerKey(oldIssuer) !== issuerKey(options2.issuer)) { - clearIdpIdToken(oldIssuer); - clearIdpClientSecret(oldIssuer); - } else if (oldClientId !== options2.clientId) { - clearIdpIdToken(oldIssuer); - clearIdpClientSecret(oldIssuer); - } - } - if (secret) { - const { success: success2, warning } = saveIdpClientSecret(options2.issuer, secret); - if (!success2) { - return cliError(`Error: settings written but keychain save failed${warning ? ` \u2014 ${warning}` : ""}. ` + `Re-run with --client-secret once keychain is available.`); - } - } - cliOk(`XAA IdP connection configured for ${options2.issuer}`); - }); - xaaIdp.command("login").description("Cache an IdP id_token so XAA-enabled MCP servers authenticate " + "silently. Default: run the OIDC browser login. With --id-token: " + "write a pre-obtained JWT directly (used by conformance/e2e tests " + "where the mock IdP does not serve /authorize).").option("--force", "Ignore any cached id_token and re-login (useful after IdP-side revocation)").option("--id-token <jwt>", "Write this pre-obtained id_token directly to cache, skipping the OIDC browser login").action(async (options2) => { - const idp = getXaaIdpSettings(); - if (!idp) { - return cliError("Error: no XAA IdP connection. Run 'claude mcp xaa setup' first."); - } - if (options2.idToken) { - const expiresAt = saveIdpIdTokenFromJwt(idp.issuer, options2.idToken); - return cliOk(`id_token cached for ${idp.issuer} (expires ${new Date(expiresAt).toISOString()})`); - } - if (options2.force) { - clearIdpIdToken(idp.issuer); - } - const wasCached = getCachedIdpIdToken(idp.issuer) !== undefined; - if (wasCached) { - return cliOk(`Already logged in to ${idp.issuer} (cached id_token still valid). Use --force to re-login.`); - } - process.stdout.write(`Opening browser for IdP login at ${idp.issuer}\u2026 -`); - try { - await acquireIdpIdToken({ - idpIssuer: idp.issuer, - idpClientId: idp.clientId, - idpClientSecret: getIdpClientSecret(idp.issuer), - callbackPort: idp.callbackPort, - onAuthorizationUrl: (url3) => { - process.stdout.write(`If the browser did not open, visit: - ${url3} -`); - } - }); - cliOk(`Logged in. MCP servers with --xaa will now authenticate silently.`); - } catch (e4) { - cliError(`IdP login failed: ${errorMessage(e4)}`); - } - }); - xaaIdp.command("show").description("Show the current IdP connection config").action(() => { - const idp = getXaaIdpSettings(); - if (!idp) { - return cliOk("No XAA IdP connection configured."); - } - const hasSecret = getIdpClientSecret(idp.issuer) !== undefined; - const hasIdToken = getCachedIdpIdToken(idp.issuer) !== undefined; - process.stdout.write(`Issuer: ${idp.issuer} -`); - process.stdout.write(`Client ID: ${idp.clientId} -`); - if (idp.callbackPort !== undefined) { - process.stdout.write(`Callback port: ${idp.callbackPort} -`); - } - process.stdout.write(`Client secret: ${hasSecret ? "(stored in keychain)" : "(not set \u2014 PKCE-only)"} -`); - process.stdout.write(`Logged in: ${hasIdToken ? "yes (id_token cached)" : "no \u2014 run 'claude mcp xaa login'"} -`); - cliOk(); - }); - xaaIdp.command("clear").description("Clear the IdP connection config and cached id_token").action(() => { - const idp = getXaaIdpSettings(); - const { error: error46 } = updateSettingsForSource("userSettings", { - xaaIdp: undefined - }); - if (error46) { - return cliError(`Error writing settings: ${error46.message}`); - } - if (idp) { - clearIdpIdToken(idp.issuer); - clearIdpClientSecret(idp.issuer); - } - cliOk("XAA IdP connection cleared"); - }); -} - -// src/main.tsx -init_internalLogging(); -init_claudeai(); -init_client22(); -init_config9(); -init_utils8(); -init_xaaIdpLogin(); -init_tipRegistry(); -init_api3(); -init_common3(); -init_cleanupRegistry(); - -// src/utils/cliArgs.ts -function eagerParseCliFlag(flagName, argv = process.argv) { - for (let i6 = 0;i6 < argv.length; i6++) { - const arg = argv[i6]; - if (arg?.startsWith(`${flagName}=`)) { - return arg.slice(flagName.length + 1); - } - if (arg === flagName && i6 + 1 < argv.length) { - return argv[i6 + 1]; - } - } - return; -} - -// src/main.tsx -init_commitAttribution(); -init_concurrentSessions(); -init_cwd(); -init_debug(); -init_errors(); -init_fsOperations(); -init_gracefulShutdown(); -init_hookEvents(); -init_modelCapabilities(); -init_Shell(); -init_sessionRestore(); -init_constants2(); -init_stringUtils(); -init_state(); - -// src/migrations/migrateAutoUpdatesToSettings.ts -init_analytics(); -init_config(); -init_log2(); -init_settings2(); -function migrateAutoUpdatesToSettings() { - const globalConfig2 = getGlobalConfig(); - if (globalConfig2.autoUpdates !== false || globalConfig2.autoUpdatesProtectedForNative === true) { - return; - } - try { - const userSettings = getSettingsForSource("userSettings") || {}; - updateSettingsForSource("userSettings", { - ...userSettings, - env: { - ...userSettings.env, - DISABLE_AUTOUPDATER: "1" - } - }); - logEvent("tengu_migrate_autoupdates_to_settings", { - was_user_preference: true, - already_had_env_var: !!userSettings.env?.DISABLE_AUTOUPDATER - }); - process.env.DISABLE_AUTOUPDATER = "1"; - saveGlobalConfig((current) => { - const { - autoUpdates: _, - autoUpdatesProtectedForNative: __, - ...updatedConfig - } = current; - return updatedConfig; - }); - } catch (error46) { - logError2(new Error(`Failed to migrate auto-updates: ${error46}`)); - logEvent("tengu_migrate_autoupdates_error", { - has_error: true - }); - } -} - -// src/migrations/migrateBypassPermissionsAcceptedToSettings.ts -init_analytics(); -init_config(); -init_log2(); -init_settings2(); -function migrateBypassPermissionsAcceptedToSettings() { - const globalConfig2 = getGlobalConfig(); - if (!globalConfig2.bypassPermissionsModeAccepted) { - return; - } - try { - if (!hasSkipDangerousModePermissionPrompt()) { - updateSettingsForSource("userSettings", { - skipDangerousModePermissionPrompt: true - }); - } - logEvent("tengu_migrate_bypass_permissions_accepted", {}); - saveGlobalConfig((current) => { - if (!("bypassPermissionsModeAccepted" in current)) - return current; - const { bypassPermissionsModeAccepted: _, ...updatedConfig } = current; - return updatedConfig; - }); - } catch (error46) { - logError2(new Error(`Failed to migrate bypass permissions accepted: ${error46}`)); - } -} - -// src/migrations/migrateEnableAllProjectMcpServersToSettings.ts -init_analytics(); -init_config(); -init_log2(); -init_settings2(); -function migrateEnableAllProjectMcpServersToSettings() { - const projectConfig = getCurrentProjectConfig(); - const hasEnableAll = projectConfig.enableAllProjectMcpServers !== undefined; - const hasEnabledServers = projectConfig.enabledMcpjsonServers && projectConfig.enabledMcpjsonServers.length > 0; - const hasDisabledServers = projectConfig.disabledMcpjsonServers && projectConfig.disabledMcpjsonServers.length > 0; - if (!hasEnableAll && !hasEnabledServers && !hasDisabledServers) { - return; - } - try { - const existingSettings = getSettingsForSource("localSettings") || {}; - const updates = {}; - const fieldsToRemove = []; - if (hasEnableAll && existingSettings.enableAllProjectMcpServers === undefined) { - updates.enableAllProjectMcpServers = projectConfig.enableAllProjectMcpServers; - fieldsToRemove.push("enableAllProjectMcpServers"); - } else if (hasEnableAll) { - fieldsToRemove.push("enableAllProjectMcpServers"); - } - if (hasEnabledServers && projectConfig.enabledMcpjsonServers) { - const existingEnabledServers = existingSettings.enabledMcpjsonServers || []; - updates.enabledMcpjsonServers = [ - ...new Set([ - ...existingEnabledServers, - ...projectConfig.enabledMcpjsonServers - ]) - ]; - fieldsToRemove.push("enabledMcpjsonServers"); - } - if (hasDisabledServers && projectConfig.disabledMcpjsonServers) { - const existingDisabledServers = existingSettings.disabledMcpjsonServers || []; - updates.disabledMcpjsonServers = [ - ...new Set([ - ...existingDisabledServers, - ...projectConfig.disabledMcpjsonServers - ]) - ]; - fieldsToRemove.push("disabledMcpjsonServers"); - } - if (Object.keys(updates).length > 0) { - updateSettingsForSource("localSettings", updates); - } - if (fieldsToRemove.includes("enableAllProjectMcpServers") || fieldsToRemove.includes("enabledMcpjsonServers") || fieldsToRemove.includes("disabledMcpjsonServers")) { - saveCurrentProjectConfig((current) => { - const { - enableAllProjectMcpServers: _enableAll, - enabledMcpjsonServers: _enabledServers, - disabledMcpjsonServers: _disabledServers, - ...configWithoutFields - } = current; - return configWithoutFields; - }); - } - logEvent("tengu_migrate_mcp_approval_fields_success", { - migratedCount: fieldsToRemove.length - }); - } catch (e4) { - logError2(e4); - logEvent("tengu_migrate_mcp_approval_fields_error", {}); - } -} - -// src/migrations/migrateFennecToOpus.ts -init_settings2(); - -// src/migrations/migrateLegacyOpusToCurrent.ts -init_analytics(); -init_config(); -init_model(); -init_providers(); -init_settings2(); -function migrateLegacyOpusToCurrent() { - if (getAPIProvider() !== "firstParty") { - return; - } - if (!isLegacyModelRemapEnabled()) { - return; - } - const model = getSettingsForSource("userSettings")?.model; - if (model !== "claude-opus-4-20250514" && model !== "claude-opus-4-1-20250805" && model !== "claude-opus-4-0" && model !== "claude-opus-4-1") { - return; - } - updateSettingsForSource("userSettings", { model: "opus" }); - saveGlobalConfig((current) => ({ - ...current, - legacyOpusMigrationTimestamp: Date.now() - })); - logEvent("tengu_legacy_opus_migration", { - from_model: model - }); -} - -// src/migrations/migrateOpusToOpus1m.ts -init_analytics(); -init_model(); -init_settings2(); -function migrateOpusToOpus1m() { - if (!isOpus1mMergeEnabled()) { - return; - } - const model = getSettingsForSource("userSettings")?.model; - if (model !== "opus") { - return; - } - const migrated = "opus[1m]"; - const modelToSet = parseUserSpecifiedModel(migrated) === parseUserSpecifiedModel(getDefaultMainLoopModelSetting()) ? undefined : migrated; - updateSettingsForSource("userSettings", { model: modelToSet }); - logEvent("tengu_opus_to_opus1m_migration", {}); -} - -// src/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.ts -init_config(); -function migrateReplBridgeEnabledToRemoteControlAtStartup() { - saveGlobalConfig((prev) => { - const oldValue = prev["replBridgeEnabled"]; - if (oldValue === undefined) - return prev; - if (prev.remoteControlAtStartup !== undefined) - return prev; - const next2 = { ...prev, remoteControlAtStartup: Boolean(oldValue) }; - delete next2["replBridgeEnabled"]; - return next2; - }); -} - -// src/migrations/migrateSonnet1mToSonnet45.ts -init_state(); -init_config(); -init_settings2(); -function migrateSonnet1mToSonnet45() { - const config10 = getGlobalConfig(); - if (config10.sonnet1m45MigrationComplete) { - return; - } - const model = getSettingsForSource("userSettings")?.model; - if (model === "sonnet[1m]") { - updateSettingsForSource("userSettings", { - model: "sonnet-4-5-20250929[1m]" - }); - } - const override = getMainLoopModelOverride(); - if (override === "sonnet[1m]") { - setMainLoopModelOverride("sonnet-4-5-20250929[1m]"); - } - saveGlobalConfig((current) => ({ - ...current, - sonnet1m45MigrationComplete: true - })); -} - -// src/migrations/migrateSonnet45ToSonnet46.ts -init_analytics(); -init_auth14(); -init_config(); -init_providers(); -init_settings2(); -function migrateSonnet45ToSonnet46() { - if (getAPIProvider() !== "firstParty") { - return; - } - if (!isProSubscriber() && !isMaxSubscriber() && !isTeamPremiumSubscriber()) { - return; - } - const model = getSettingsForSource("userSettings")?.model; - if (model !== "claude-sonnet-4-5-20250929" && model !== "claude-sonnet-4-5-20250929[1m]" && model !== "sonnet-4-5-20250929" && model !== "sonnet-4-5-20250929[1m]") { - return; - } - const has1m = model.endsWith("[1m]"); - updateSettingsForSource("userSettings", { - model: has1m ? "sonnet[1m]" : "sonnet" - }); - const config10 = getGlobalConfig(); - if (config10.numStartups > 1) { - saveGlobalConfig((current) => ({ - ...current, - sonnet45To46MigrationTimestamp: Date.now() - })); - } - logEvent("tengu_sonnet45_to_46_migration", { - from_model: model, - has_1m: has1m - }); -} - -// src/migrations/resetAutoModeOptInForDefaultOffer.ts -init_analytics(); -init_config(); -init_log2(); -init_permissionSetup(); -init_settings2(); - -// src/migrations/resetProToOpusDefault.ts -init_analytics(); -init_auth14(); -init_config(); -init_providers(); -init_settings2(); -function resetProToOpusDefault() { - const config10 = getGlobalConfig(); - if (config10.opusProMigrationComplete) { - return; - } - const apiProvider = getAPIProvider(); - if (apiProvider !== "firstParty" || !isProSubscriber()) { - saveGlobalConfig((current) => ({ - ...current, - opusProMigrationComplete: true - })); - logEvent("tengu_reset_pro_to_opus_default", { skipped: true }); - return; - } - const settings = getSettings_DEPRECATED(); - if (settings?.model === undefined) { - const opusProMigrationTimestamp = Date.now(); - saveGlobalConfig((current) => ({ - ...current, - opusProMigrationComplete: true, - opusProMigrationTimestamp - })); - logEvent("tengu_reset_pro_to_opus_default", { - skipped: false, - had_custom_model: false - }); - } else { - saveGlobalConfig((current) => ({ - ...current, - opusProMigrationComplete: true - })); - logEvent("tengu_reset_pro_to_opus_default", { - skipped: false, - had_custom_model: true - }); - } -} - -// src/main.tsx -init_RemoteSessionManager(); - -// src/server/createDirectConnectSession.ts -init_errors(); -init_slowOperations(); - -// src/server/types.ts -init_v4(); -var connectResponseSchema = lazySchema(() => exports_external.object({ - session_id: exports_external.string(), - ws_url: exports_external.string(), - work_dir: exports_external.string().optional() -})); - -// src/main.tsx -init_manager7(); -init_promptSuggestion(); -init_AppStateStore(); -init_onChangeAppState(); -init_ids(); -init_betas2(); -init_diagLogs(); -init_githubRepoPathMapping(); -init_pluginLoader(); -init_releaseNotes(); -init_sandbox_adapter(); -init_api2(); -init_teleport(); -init_thinking(); -init_user(); -init_worktree(); -profileCheckpoint("main_tsx_entry"); -startMdmRawRead(); -startKeychainPrefetch(); -var getTeammateUtils = () => (init_teammate(), __toCommonJS(exports_teammate)); -var getTeammatePromptAddendum = () => __toCommonJS(exports_teammatePromptAddendum); -var getTeammateModeSnapshot = () => (init_teammateModeSnapshot(), __toCommonJS(exports_teammateModeSnapshot)); -var coordinatorModeModule = null; -profileCheckpoint("main_tsx_imports_loaded"); -function logManagedSettings() { - try { - const policySettings = getSettingsForSource("policySettings"); - if (policySettings) { - const allKeys = getManagedSettingsKeysForLogging(policySettings); - logEvent("tengu_managed_settings_loaded", { - keyCount: allKeys.length, - keys: allKeys.join(",") - }); - } - } catch {} -} -function isBeingDebugged() { - const isBun2 = isRunningWithBun(); - const hasInspectArg = process.execArgv.some((arg) => { - if (isBun2) { - return /--inspect(-brk)?/.test(arg); - } else { - return /--inspect(-brk)?|--debug(-brk)?/.test(arg); - } - }); - const hasInspectEnv = process.env.NODE_OPTIONS && /--inspect(-brk)?|--debug(-brk)?/.test(process.env.NODE_OPTIONS); - try { - const inspector = global.require("inspector"); - const hasInspectorUrl = !!inspector.url(); - return hasInspectorUrl || hasInspectArg || hasInspectEnv; - } catch { - return hasInspectArg || hasInspectEnv; - } -} -if (isBeingDebugged()) { - process.exit(1); -} -function logSessionTelemetry() { - const model = parseUserSpecifiedModel(getInitialMainLoopModel() ?? getDefaultMainLoopModel()); - logSkillsLoaded(getCwd(), getContextWindowForModel(model, getSdkBetas())); - loadAllPluginsCacheOnly().then(({ - enabled: enabled2, - errors: errors8 - }) => { - const managedNames = getManagedPluginNames(); - logPluginsEnabledForSession(enabled2, managedNames, getPluginSeedDirs()); - logPluginLoadErrors(errors8, managedNames); - }).catch((err2) => logError2(err2)); -} -function getCertEnvVarTelemetry() { - const result = {}; - if (process.env.NODE_EXTRA_CA_CERTS) { - result.has_node_extra_ca_certs = true; - } - if (process.env.CLAUDE_CODE_CLIENT_CERT) { - result.has_client_cert = true; - } - if (hasNodeOption("--use-system-ca")) { - result.has_use_system_ca = true; - } - if (hasNodeOption("--use-openssl-ca")) { - result.has_use_openssl_ca = true; - } - return result; -} -async function logStartupTelemetry() { - if (isAnalyticsDisabled()) - return; - const [isGit, worktreeCount, ghAuthStatus] = await Promise.all([getIsGit(), getWorktreeCount(), getGhAuthStatus()]); - logEvent("tengu_startup_telemetry", { - is_git: isGit, - worktree_count: worktreeCount, - gh_auth_status: ghAuthStatus, - sandbox_enabled: SandboxManager.isSandboxingEnabled(), - are_unsandboxed_commands_allowed: SandboxManager.areUnsandboxedCommandsAllowed(), - is_auto_bash_allowed_if_sandbox_enabled: SandboxManager.isAutoAllowBashIfSandboxedEnabled(), - auto_updater_disabled: isAutoUpdaterDisabled(), - prefers_reduced_motion: getInitialSettings().prefersReducedMotion ?? false, - ...getCertEnvVarTelemetry() - }); -} -var CURRENT_MIGRATION_VERSION = 11; -function runMigrations() { - if (getGlobalConfig().migrationVersion !== CURRENT_MIGRATION_VERSION) { - migrateAutoUpdatesToSettings(); - migrateBypassPermissionsAcceptedToSettings(); - migrateEnableAllProjectMcpServersToSettings(); - resetProToOpusDefault(); - migrateSonnet1mToSonnet45(); - migrateLegacyOpusToCurrent(); - migrateSonnet45ToSonnet46(); - migrateOpusToOpus1m(); - migrateReplBridgeEnabledToRemoteControlAtStartup(); - if (false) {} - if (false) {} - saveGlobalConfig((prev) => prev.migrationVersion === CURRENT_MIGRATION_VERSION ? prev : { - ...prev, - migrationVersion: CURRENT_MIGRATION_VERSION - }); - } - migrateChangelogFromConfig().catch(() => {}); -} -function prefetchSystemContextIfSafe() { - const isNonInteractiveSession = getIsNonInteractiveSession(); - if (isNonInteractiveSession) { - logForDiagnosticsNoPII("info", "prefetch_system_context_non_interactive"); - getSystemContext(); - return; - } - const hasTrust = checkHasTrustDialogAccepted(); - if (hasTrust) { - logForDiagnosticsNoPII("info", "prefetch_system_context_has_trust"); - getSystemContext(); - } else { - logForDiagnosticsNoPII("info", "prefetch_system_context_skipped_no_trust"); - } -} -function startDeferredPrefetches() { - if (isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER) || isBareMode()) { - return; - } - initUser(); - getUserContext(); - prefetchSystemContextIfSafe(); - getRelevantTips(); - if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) && !isEnvTruthy(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH)) { - prefetchAwsCredentialsAndBedRockInfoIfSafe(); - } - if (isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) && !isEnvTruthy(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)) { - prefetchGcpCredentialsIfSafe(); - } - countFilesRoundedRg(getCwd(), AbortSignal.timeout(3000), []); - initializeAnalyticsGates(); - prefetchOfficialMcpUrls(); - refreshModelCapabilities(); - settingsChangeDetector.initialize(); - if (!isBareMode()) { - skillChangeDetector.initialize(); - } - if (false) {} -} -function loadSettingsFromFlag(settingsFile) { - try { - const trimmedSettings = settingsFile.trim(); - const looksLikeJson = trimmedSettings.startsWith("{") && trimmedSettings.endsWith("}"); - let settingsPath; - if (looksLikeJson) { - const parsedJson = safeParseJSON(trimmedSettings); - if (!parsedJson) { - process.stderr.write(source_default.red(`Error: Invalid JSON provided to --settings -`)); - process.exit(1); - } - settingsPath = generateTempFilePath("claude-settings", ".json", { - contentHash: trimmedSettings - }); - writeFileSync_DEPRECATED(settingsPath, trimmedSettings, "utf8"); - } else { - const { - resolvedPath: resolvedSettingsPath - } = safeResolvePath(getFsImplementation(), settingsFile); - try { - readFileSync19(resolvedSettingsPath, "utf8"); - } catch (e4) { - if (isENOENT(e4)) { - process.stderr.write(source_default.red(`Error: Settings file not found: ${resolvedSettingsPath} -`)); - process.exit(1); - } - throw e4; - } - settingsPath = resolvedSettingsPath; - } - setFlagSettingsPath(settingsPath); - resetSettingsCache(); - } catch (error46) { - if (error46 instanceof Error) { - logError2(error46); - } - process.stderr.write(source_default.red(`Error processing settings: ${errorMessage(error46)} -`)); - process.exit(1); - } -} -function loadSettingSourcesFromFlag(settingSourcesArg) { - try { - const sources = parseSettingSourcesFlag(settingSourcesArg); - setAllowedSettingSources(sources); - resetSettingsCache(); - } catch (error46) { - if (error46 instanceof Error) { - logError2(error46); - } - process.stderr.write(source_default.red(`Error processing --setting-sources: ${errorMessage(error46)} -`)); - process.exit(1); - } -} -function eagerLoadSettings() { - profileCheckpoint("eagerLoadSettings_start"); - const settingsFile = eagerParseCliFlag("--settings"); - if (settingsFile) { - loadSettingsFromFlag(settingsFile); - } - const settingSourcesArg = eagerParseCliFlag("--setting-sources"); - if (settingSourcesArg !== undefined) { - loadSettingSourcesFromFlag(settingSourcesArg); - } - profileCheckpoint("eagerLoadSettings_end"); -} -function initializeEntrypoint(isNonInteractive) { - if (process.env.CLAUDE_CODE_ENTRYPOINT) { - return; - } - const cliArgs = process.argv.slice(2); - const mcpIndex = cliArgs.indexOf("mcp"); - if (mcpIndex !== -1 && cliArgs[mcpIndex + 1] === "serve") { - process.env.CLAUDE_CODE_ENTRYPOINT = "mcp"; - return; - } - if (isEnvTruthy(process.env.CLAUDE_CODE_ACTION)) { - process.env.CLAUDE_CODE_ENTRYPOINT = "claude-code-github-action"; - return; - } - process.env.CLAUDE_CODE_ENTRYPOINT = isNonInteractive ? "sdk-cli" : "cli"; -} -async function main() { - profileCheckpoint("main_function_start"); - process.env.NoDefaultCurrentDirectoryInExePath = "1"; - initializeWarningHandler(); - process.on("exit", () => { - resetCursor(); - }); - process.on("SIGINT", () => { - if (process.argv.includes("-p") || process.argv.includes("--print")) { - return; - } - process.exit(0); - }); - profileCheckpoint("main_warning_handler_initialized"); - if (false) {} - if (false) {} - if (false) {} - if (false) {} - const cliArgs = process.argv.slice(2); - const hasPrintFlag = cliArgs.includes("-p") || cliArgs.includes("--print"); - const hasInitOnlyFlag = cliArgs.includes("--init-only"); - const hasSdkUrl = cliArgs.some((arg) => arg.startsWith("--sdk-url")); - const isNonInteractive = hasPrintFlag || hasInitOnlyFlag || hasSdkUrl || !process.stdout.isTTY; - if (isNonInteractive) { - stopCapturingEarlyInput(); - } - const isInteractive = !isNonInteractive; - setIsInteractive(isInteractive); - initializeEntrypoint(isNonInteractive); - const clientType = (() => { - if (isEnvTruthy(process.env.GITHUB_ACTIONS)) - return "github-action"; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "sdk-ts") - return "sdk-typescript"; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "sdk-py") - return "sdk-python"; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "sdk-cli") - return "sdk-cli"; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "claude-vscode") - return "claude-vscode"; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "local-agent") - return "local-agent"; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop") - return "claude-desktop"; - const hasSessionIngressToken = process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN || process.env.CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR; - if (process.env.CLAUDE_CODE_ENTRYPOINT === "remote" || hasSessionIngressToken) { - return "remote"; - } - return "cli"; - })(); - setClientType(clientType); - const previewFormat = process.env.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT; - if (previewFormat === "markdown" || previewFormat === "html") { - setQuestionPreviewFormat(previewFormat); - } else if (!clientType.startsWith("sdk-") && clientType !== "claude-desktop" && clientType !== "local-agent" && clientType !== "remote") { - setQuestionPreviewFormat("markdown"); - } - if (process.env.CLAUDE_CODE_ENVIRONMENT_KIND === "bridge") { - setSessionSource("remote-control"); - } - profileCheckpoint("main_client_type_determined"); - eagerLoadSettings(); - profileCheckpoint("main_before_run"); - await run(); - profileCheckpoint("main_after_run"); -} -async function getInputPrompt(prompt, inputFormat) { - if (!process.stdin.isTTY && !process.argv.includes("mcp")) { - if (inputFormat === "stream-json") { - return process.stdin; - } - process.stdin.setEncoding("utf8"); - let data = ""; - const onData = (chunk2) => { - data += chunk2; - }; - process.stdin.on("data", onData); - const timedOut = await peekForStdinData(process.stdin, 3000); - process.stdin.off("data", onData); - if (timedOut) { - process.stderr.write(`Warning: no stdin data received in 3s, proceeding without it. If piping from a slow command, redirect stdin explicitly: < /dev/null to skip, or wait longer. -`); - } - return [prompt, data].filter(Boolean).join(` -`); - } - return prompt; -} -async function run() { - profileCheckpoint("run_function_start"); - function createSortedHelpConfig() { - const getOptionSortKey = (opt) => opt.long?.replace(/^--/, "") ?? opt.short?.replace(/^-/, "") ?? ""; - return Object.assign({ - sortSubcommands: true, - sortOptions: true - }, { - compareOptions: (a5, b5) => getOptionSortKey(a5).localeCompare(getOptionSortKey(b5)) - }); - } - const program2 = new Command().configureHelp(createSortedHelpConfig()).enablePositionalOptions(); - profileCheckpoint("run_commander_initialized"); - program2.hook("preAction", async (thisCommand) => { - profileCheckpoint("preAction_start"); - await Promise.all([ensureMdmSettingsLoaded(), ensureKeychainPrefetchCompleted()]); - profileCheckpoint("preAction_after_mdm"); - await init2(); - profileCheckpoint("preAction_after_init"); - if (!isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)) { - process.title = "claude"; - } - const { - initSinks: initSinks2 - } = await Promise.resolve().then(() => (init_sinks(), exports_sinks)); - initSinks2(); - profileCheckpoint("preAction_after_sinks"); - const pluginDir = thisCommand.getOptionValue("pluginDir"); - if (Array.isArray(pluginDir) && pluginDir.length > 0 && pluginDir.every((p4) => typeof p4 === "string")) { - setInlinePlugins(pluginDir); - clearPluginCache("preAction: --plugin-dir inline plugins"); - } - runMigrations(); - profileCheckpoint("preAction_after_migrations"); - loadRemoteManagedSettings(); - loadPolicyLimits(); - profileCheckpoint("preAction_after_remote_settings"); - if (false) {} - profileCheckpoint("preAction_after_settings_sync"); - }); - program2.name("claude").description(`Claude Code - starts an interactive session by default, use -p/--print for non-interactive output`).argument("[prompt]", "Your prompt", String).helpOption("-h, --help", "Display help for command").option("-d, --debug [filter]", 'Enable debug mode with optional category filtering (e.g., "api,hooks" or "!1p,!file")', (_value) => { - return true; - }).addOption(new Option("-d2e, --debug-to-stderr", "Enable debug mode (to stderr)").argParser(Boolean).hideHelp()).option("--debug-file <path>", "Write debug logs to a specific file path (implicitly enables debug mode)", () => true).option("--verbose", "Override verbose mode setting from config", () => true).option("-p, --print", "Print response and exit (useful for pipes). Note: The workspace trust dialog is skipped when Claude is run with the -p mode. Only use this flag in directories you trust.", () => true).option("--bare", "Minimal mode: skip hooks, LSP, plugin sync, attribution, auto-memory, background prefetches, keychain reads, and CLAUDE.md auto-discovery. Sets CLAUDE_CODE_SIMPLE=1. Anthropic auth is strictly ANTHROPIC_API_KEY or apiKeyHelper via --settings (OAuth and keychain are never read). 3P providers (Bedrock/Vertex/Foundry) use their own credentials. Skills still resolve via /skill-name. Explicitly provide context via: --system-prompt[-file], --append-system-prompt[-file], --add-dir (CLAUDE.md dirs), --mcp-config, --settings, --agents, --plugin-dir.", () => true).addOption(new Option("--init", "Run Setup hooks with init trigger, then continue").hideHelp()).addOption(new Option("--init-only", "Run Setup and SessionStart:startup hooks, then exit").hideHelp()).addOption(new Option("--maintenance", "Run Setup hooks with maintenance trigger, then continue").hideHelp()).addOption(new Option("--output-format <format>", 'Output format (only works with --print): "text" (default), "json" (single result), or "stream-json" (realtime streaming)').choices(["text", "json", "stream-json"])).addOption(new Option("--json-schema <schema>", 'JSON Schema for structured output validation. Example: {"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}').argParser(String)).option("--include-hook-events", "Include all hook lifecycle events in the output stream (only works with --output-format=stream-json)", () => true).option("--include-partial-messages", "Include partial message chunks as they arrive (only works with --print and --output-format=stream-json)", () => true).addOption(new Option("--input-format <format>", 'Input format (only works with --print): "text" (default), or "stream-json" (realtime streaming input)').choices(["text", "stream-json"])).option("--mcp-debug", "[DEPRECATED. Use --debug instead] Enable MCP debug mode (shows MCP server errors)", () => true).option("--dangerously-skip-permissions", "Bypass all permission checks. Recommended only for sandboxes with no internet access.", () => true).option("--allow-dangerously-skip-permissions", "Enable bypassing all permission checks as an option, without it being enabled by default. Recommended only for sandboxes with no internet access.", () => true).addOption(new Option("--thinking <mode>", "Thinking mode: enabled (equivalent to adaptive), disabled").choices(["enabled", "adaptive", "disabled"]).hideHelp()).addOption(new Option("--max-thinking-tokens <tokens>", "[DEPRECATED. Use --thinking instead for newer models] Maximum number of thinking tokens (only works with --print)").argParser(Number).hideHelp()).addOption(new Option("--max-turns <turns>", "Maximum number of agentic turns in non-interactive mode. This will early exit the conversation after the specified number of turns. (only works with --print)").argParser(Number).hideHelp()).addOption(new Option("--max-budget-usd <amount>", "Maximum dollar amount to spend on API calls (only works with --print)").argParser((value) => { - const amount = Number(value); - if (isNaN(amount) || amount <= 0) { - throw new Error("--max-budget-usd must be a positive number greater than 0"); - } - return amount; - })).addOption(new Option("--task-budget <tokens>", "API-side task budget in tokens (output_config.task_budget)").argParser((value) => { - const tokens = Number(value); - if (isNaN(tokens) || tokens <= 0 || !Number.isInteger(tokens)) { - throw new Error("--task-budget must be a positive integer"); - } - return tokens; - }).hideHelp()).option("--replay-user-messages", "Re-emit user messages from stdin back on stdout for acknowledgment (only works with --input-format=stream-json and --output-format=stream-json)", () => true).addOption(new Option("--enable-auth-status", "Enable auth status messages in SDK mode").default(false).hideHelp()).option("--allowedTools, --allowed-tools <tools...>", 'Comma or space-separated list of tool names to allow (e.g. "Bash(git:*) Edit")').option("--tools <tools...>", 'Specify the list of available tools from the built-in set. Use "" to disable all tools, "default" to use all tools, or specify tool names (e.g. "Bash,Edit,Read").').option("--disallowedTools, --disallowed-tools <tools...>", 'Comma or space-separated list of tool names to deny (e.g. "Bash(git:*) Edit")').option("--mcp-config <configs...>", "Load MCP servers from JSON files or strings (space-separated)").addOption(new Option("--permission-prompt-tool <tool>", "MCP tool to use for permission prompts (only works with --print)").argParser(String).hideHelp()).addOption(new Option("--system-prompt <prompt>", "System prompt to use for the session").argParser(String)).addOption(new Option("--system-prompt-file <file>", "Read system prompt from a file").argParser(String).hideHelp()).addOption(new Option("--append-system-prompt <prompt>", "Append a system prompt to the default system prompt").argParser(String)).addOption(new Option("--append-system-prompt-file <file>", "Read system prompt from a file and append to the default system prompt").argParser(String).hideHelp()).addOption(new Option("--permission-mode <mode>", "Permission mode to use for the session").argParser(String).choices(PERMISSION_MODES)).option("-c, --continue", "Continue the most recent conversation in the current directory", () => true).option("-r, --resume [value]", "Resume a conversation by session ID, or open interactive picker with optional search term", (value) => value || true).option("--fork-session", "When resuming, create a new session ID instead of reusing the original (use with --resume or --continue)", () => true).addOption(new Option("--prefill <text>", "Pre-fill the prompt input with text without submitting it").hideHelp()).addOption(new Option("--deep-link-origin", "Signal that this session was launched from a deep link").hideHelp()).addOption(new Option("--deep-link-repo <slug>", "Repo slug the deep link ?repo= parameter resolved to the current cwd").hideHelp()).addOption(new Option("--deep-link-last-fetch <ms>", "FETCH_HEAD mtime in epoch ms, precomputed by the deep link trampoline").argParser((v6) => { - const n6 = Number(v6); - return Number.isFinite(n6) ? n6 : undefined; - }).hideHelp()).option("--from-pr [value]", "Resume a session linked to a PR by PR number/URL, or open interactive picker with optional search term", (value) => value || true).option("--no-session-persistence", "Disable session persistence - sessions will not be saved to disk and cannot be resumed (only works with --print)").addOption(new Option("--resume-session-at <message id>", "When resuming, only messages up to and including the assistant message with <message.id> (use with --resume in print mode)").argParser(String).hideHelp()).addOption(new Option("--rewind-files <user-message-id>", "Restore files to state at the specified user message and exit (requires --resume)").hideHelp()).option("--model <model>", `Model for the current session. Provide an alias for the latest model (e.g. 'sonnet' or 'opus') or a model's full name (e.g. 'claude-sonnet-4-6').`).addOption(new Option("--effort <level>", `Effort level for the current session (low, medium, high, max)`).argParser((rawValue) => { - const value = rawValue.toLowerCase(); - const allowed = ["low", "medium", "high", "max"]; - if (!allowed.includes(value)) { - throw new InvalidArgumentError(`It must be one of: ${allowed.join(", ")}`); - } - return value; - })).option("--agent <agent>", `Agent for the current session. Overrides the 'agent' setting.`).option("--betas <betas...>", "Beta headers to include in API requests (API key users only)").option("--fallback-model <model>", "Enable automatic fallback to specified model when default model is overloaded (only works with --print)").addOption(new Option("--workload <tag>", "Workload tag for billing-header attribution (cc_workload). Process-scoped; set by SDK daemon callers that spawn subprocesses for cron work. (only works with --print)").hideHelp()).option("--settings <file-or-json>", "Path to a settings JSON file or a JSON string to load additional settings from").option("--add-dir <directories...>", "Additional directories to allow tool access to").option("--ide", "Automatically connect to IDE on startup if exactly one valid IDE is available", () => true).option("--strict-mcp-config", "Only use MCP servers from --mcp-config, ignoring all other MCP configurations", () => true).option("--session-id <uuid>", "Use a specific session ID for the conversation (must be a valid UUID)").option("-n, --name <name>", "Set a display name for this session (shown in /resume and terminal title)").option("--agents <json>", `JSON object defining custom agents (e.g. '{"reviewer": {"description": "Reviews code", "prompt": "You are a code reviewer"}}')`).option("--setting-sources <sources>", "Comma-separated list of setting sources to load (user, project, local).").option("--plugin-dir <path>", "Load plugins from a directory for this session only (repeatable: --plugin-dir A --plugin-dir B)", (val, prev) => [...prev, val], []).option("--disable-slash-commands", "Disable all skills", () => true).option("--chrome", "Enable Claude in Chrome integration").option("--no-chrome", "Disable Claude in Chrome integration").option("--file <specs...>", "File resources to download at startup. Format: file_id:relative_path (e.g., --file file_abc:doc.txt file_def:img.png)").action(async (prompt, options2) => { - profileCheckpoint("action_handler_start"); - if (options2.bare) { - process.env.CLAUDE_CODE_SIMPLE = "1"; - } - if (prompt === "code") { - logEvent("tengu_code_prompt_ignored", {}); - console.warn(source_default.yellow("Tip: You can launch Claude Code with just `claude`")); - prompt = undefined; - } - if (prompt && typeof prompt === "string" && !/\s/.test(prompt) && prompt.length > 0) { - logEvent("tengu_single_word_prompt", { - length: prompt.length - }); - } - let kairosEnabled = false; - let assistantTeamContext; - if (false) {} - if (false) {} - const { - debug: debug3 = false, - debugToStderr = false, - dangerouslySkipPermissions, - allowDangerouslySkipPermissions = false, - tools: baseTools = [], - allowedTools = [], - disallowedTools = [], - mcpConfig = [], - permissionMode: permissionModeCli, - addDir: addDir2 = [], - fallbackModel, - betas = [], - ide: ide2 = false, - sessionId, - includeHookEvents, - includePartialMessages - } = options2; - if (options2.prefill) { - seedEarlyInput(options2.prefill); - } - let fileDownloadPromise; - const agentsJson = options2.agents; - const agentCli = options2.agent; - if (false) {} - let outputFormat = options2.outputFormat; - let inputFormat = options2.inputFormat; - let verbose = options2.verbose ?? getGlobalConfig().verbose; - let print = options2.print; - const init3 = options2.init ?? false; - const initOnly = options2.initOnly ?? false; - const maintenance = options2.maintenance ?? false; - const disableSlashCommands = options2.disableSlashCommands || false; - const tasksOption = false; - const taskListId = tasksOption ? typeof tasksOption === "string" ? tasksOption : DEFAULT_TASKS_MODE_TASK_LIST_ID : undefined; - if (false) {} - const worktreeOption = isWorktreeModeEnabled() ? options2.worktree : undefined; - let worktreeName = typeof worktreeOption === "string" ? worktreeOption : undefined; - const worktreeEnabled = worktreeOption !== undefined; - let worktreePRNumber; - if (worktreeName) { - const prNum = parsePRReference(worktreeName); - if (prNum !== null) { - worktreePRNumber = prNum; - worktreeName = undefined; - } - } - const tmuxEnabled = isWorktreeModeEnabled() && options2.tmux === true; - if (tmuxEnabled) { - if (!worktreeEnabled) { - process.stderr.write(source_default.red(`Error: --tmux requires --worktree -`)); - process.exit(1); - } - if (getPlatform() === "windows") { - process.stderr.write(source_default.red(`Error: --tmux is not supported on Windows -`)); - process.exit(1); - } - if (!await isTmuxAvailable2()) { - process.stderr.write(source_default.red(`Error: tmux is not installed. -${getTmuxInstallInstructions2()} -`)); - process.exit(1); - } - } - let storedTeammateOpts; - if (isAgentSwarmsEnabled()) { - const teammateOpts = extractTeammateOptions(options2); - storedTeammateOpts = teammateOpts; - const hasAnyTeammateOpt = teammateOpts.agentId || teammateOpts.agentName || teammateOpts.teamName; - const hasAllRequiredTeammateOpts = teammateOpts.agentId && teammateOpts.agentName && teammateOpts.teamName; - if (hasAnyTeammateOpt && !hasAllRequiredTeammateOpts) { - process.stderr.write(source_default.red(`Error: --agent-id, --agent-name, and --team-name must all be provided together -`)); - process.exit(1); - } - if (teammateOpts.agentId && teammateOpts.agentName && teammateOpts.teamName) { - getTeammateUtils().setDynamicTeamContext?.({ - agentId: teammateOpts.agentId, - agentName: teammateOpts.agentName, - teamName: teammateOpts.teamName, - color: teammateOpts.agentColor, - planModeRequired: teammateOpts.planModeRequired ?? false, - parentSessionId: teammateOpts.parentSessionId - }); - } - if (teammateOpts.teammateMode) { - getTeammateModeSnapshot().setCliTeammateModeOverride?.(teammateOpts.teammateMode); - } - } - const sdkUrl = options2.sdkUrl ?? undefined; - const effectiveIncludePartialMessages = includePartialMessages || isEnvTruthy(process.env.CLAUDE_CODE_INCLUDE_PARTIAL_MESSAGES); - if (includeHookEvents || isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) { - setAllHookEventsEnabled(true); - } - if (sdkUrl) { - if (!inputFormat) { - inputFormat = "stream-json"; - } - if (!outputFormat) { - outputFormat = "stream-json"; - } - if (options2.verbose === undefined) { - verbose = true; - } - if (!options2.print) { - print = true; - } - } - const teleport = options2.teleport ?? null; - const remoteOption = options2.remote; - const remote = remoteOption === true ? "" : remoteOption ?? null; - const remoteControlOption = options2.remoteControl ?? options2.rc; - let remoteControl = false; - const remoteControlName = typeof remoteControlOption === "string" && remoteControlOption.length > 0 ? remoteControlOption : undefined; - if (sessionId) { - if ((options2.continue || options2.resume) && !options2.forkSession) { - process.stderr.write(source_default.red(`Error: --session-id can only be used with --continue or --resume if --fork-session is also specified. -`)); - process.exit(1); - } - if (!sdkUrl) { - const validatedSessionId = validateUuid2(sessionId); - if (!validatedSessionId) { - process.stderr.write(source_default.red(`Error: Invalid session ID. Must be a valid UUID. -`)); - process.exit(1); - } - if (sessionIdExists(validatedSessionId)) { - process.stderr.write(source_default.red(`Error: Session ID ${validatedSessionId} is already in use. -`)); - process.exit(1); - } - } - } - const fileSpecs = options2.file; - if (fileSpecs && fileSpecs.length > 0) { - const sessionToken = getSessionIngressAuthToken(); - if (!sessionToken) { - process.stderr.write(source_default.red(`Error: Session token required for file downloads. CLAUDE_CODE_SESSION_ACCESS_TOKEN must be set. -`)); - process.exit(1); - } - const fileSessionId = process.env.CLAUDE_CODE_REMOTE_SESSION_ID || getSessionId(); - const files3 = parseFileSpecs(fileSpecs); - if (files3.length > 0) { - const config10 = { - baseUrl: process.env.ANTHROPIC_BASE_URL || getOauthConfig().BASE_API_URL, - oauthToken: sessionToken, - sessionId: fileSessionId - }; - fileDownloadPromise = downloadSessionFiles(files3, config10); - } - } - const isNonInteractiveSession = getIsNonInteractiveSession(); - if (fallbackModel && options2.model && fallbackModel === options2.model) { - process.stderr.write(source_default.red(`Error: Fallback model cannot be the same as the main model. Please specify a different model for --fallback-model. -`)); - process.exit(1); - } - let systemPrompt = options2.systemPrompt; - if (options2.systemPromptFile) { - if (options2.systemPrompt) { - process.stderr.write(source_default.red(`Error: Cannot use both --system-prompt and --system-prompt-file. Please use only one. -`)); - process.exit(1); - } - try { - const filePath = resolve44(options2.systemPromptFile); - systemPrompt = readFileSync19(filePath, "utf8"); - } catch (error46) { - const code = getErrnoCode(error46); - if (code === "ENOENT") { - process.stderr.write(source_default.red(`Error: System prompt file not found: ${resolve44(options2.systemPromptFile)} -`)); - process.exit(1); - } - process.stderr.write(source_default.red(`Error reading system prompt file: ${errorMessage(error46)} -`)); - process.exit(1); - } - } - let appendSystemPrompt = options2.appendSystemPrompt; - if (options2.appendSystemPromptFile) { - if (options2.appendSystemPrompt) { - process.stderr.write(source_default.red(`Error: Cannot use both --append-system-prompt and --append-system-prompt-file. Please use only one. -`)); - process.exit(1); - } - try { - const filePath = resolve44(options2.appendSystemPromptFile); - appendSystemPrompt = readFileSync19(filePath, "utf8"); - } catch (error46) { - const code = getErrnoCode(error46); - if (code === "ENOENT") { - process.stderr.write(source_default.red(`Error: Append system prompt file not found: ${resolve44(options2.appendSystemPromptFile)} -`)); - process.exit(1); - } - process.stderr.write(source_default.red(`Error reading append system prompt file: ${errorMessage(error46)} -`)); - process.exit(1); - } - } - if (isAgentSwarmsEnabled() && storedTeammateOpts?.agentId && storedTeammateOpts?.agentName && storedTeammateOpts?.teamName) { - const addendum = getTeammatePromptAddendum().TEAMMATE_SYSTEM_PROMPT_ADDENDUM; - appendSystemPrompt = appendSystemPrompt ? `${appendSystemPrompt} - -${addendum}` : addendum; - } - const { - mode: permissionMode, - notification: permissionModeNotification - } = initialPermissionModeFromCLI({ - permissionModeCli, - dangerouslySkipPermissions - }); - setSessionBypassPermissionsMode(permissionMode === "bypassPermissions"); - if (false) {} - let dynamicMcpConfig = {}; - if (mcpConfig && mcpConfig.length > 0) { - const processedConfigs = mcpConfig.map((config10) => config10.trim()).filter((config10) => config10.length > 0); - let allConfigs = {}; - const allErrors = []; - for (const configItem of processedConfigs) { - let configs = null; - let errors8 = []; - const parsedJson = safeParseJSON(configItem); - if (parsedJson) { - const result = parseMcpConfig({ - configObject: parsedJson, - filePath: "command line", - expandVars: true, - scope: "dynamic" - }); - if (result.config) { - configs = result.config.mcpServers; - } else { - errors8 = result.errors; - } - } else { - const configPath = resolve44(configItem); - const result = parseMcpConfigFromFilePath({ - filePath: configPath, - expandVars: true, - scope: "dynamic" - }); - if (result.config) { - configs = result.config.mcpServers; - } else { - errors8 = result.errors; - } - } - if (errors8.length > 0) { - allErrors.push(...errors8); - } else if (configs) { - allConfigs = { - ...allConfigs, - ...configs - }; - } - } - if (allErrors.length > 0) { - const formattedErrors = allErrors.map((err2) => `${err2.path ? err2.path + ": " : ""}${err2.message}`).join(` -`); - logForDebugging(`--mcp-config validation failed (${allErrors.length} errors): ${formattedErrors}`, { - level: "error" - }); - process.stderr.write(`Error: Invalid MCP configuration: -${formattedErrors} -`); - process.exit(1); - } - if (Object.keys(allConfigs).length > 0) { - const nonSdkConfigNames = Object.entries(allConfigs).filter(([, config10]) => config10.type !== "sdk").map(([name3]) => name3); - let reservedNameError = null; - if (nonSdkConfigNames.some(isClaudeInChromeMCPServer)) { - reservedNameError = `Invalid MCP configuration: "${CLAUDE_IN_CHROME_MCP_SERVER_NAME}" is a reserved MCP name.`; - } else if (false) {} - if (reservedNameError) { - process.stderr.write(`Error: ${reservedNameError} -`); - process.exit(1); - } - const scopedConfigs = mapValues_default(allConfigs, (config10) => ({ - ...config10, - scope: "dynamic" - })); - const { - allowed, - blocked - } = filterMcpServersByPolicy(scopedConfigs); - if (blocked.length > 0) { - process.stderr.write(`Warning: MCP ${plural(blocked.length, "server")} blocked by enterprise policy: ${blocked.join(", ")} -`); - } - dynamicMcpConfig = { - ...dynamicMcpConfig, - ...allowed - }; - } - } - const chromeOpts = options2; - setChromeFlagOverride(chromeOpts.chrome); - const enableClaudeInChrome = shouldEnableClaudeInChrome(chromeOpts.chrome) && isClaudeAISubscriber(); - const autoEnableClaudeInChrome = !enableClaudeInChrome && shouldAutoEnableClaudeInChrome(); - if (enableClaudeInChrome) { - const platform6 = getPlatform(); - try { - logEvent("tengu_claude_in_chrome_setup", { - platform: platform6 - }); - const { - mcpConfig: chromeMcpConfig, - allowedTools: chromeMcpTools, - systemPrompt: chromeSystemPrompt - } = setupClaudeInChrome(); - dynamicMcpConfig = { - ...dynamicMcpConfig, - ...chromeMcpConfig - }; - allowedTools.push(...chromeMcpTools); - if (chromeSystemPrompt) { - appendSystemPrompt = appendSystemPrompt ? `${chromeSystemPrompt} - -${appendSystemPrompt}` : chromeSystemPrompt; - } - } catch (error46) { - logEvent("tengu_claude_in_chrome_setup_failed", { - platform: platform6 - }); - logForDebugging(`[Claude in Chrome] Error: ${error46}`); - logError2(error46); - console.error(`Error: Failed to run with Claude in Chrome.`); - process.exit(1); - } - } else if (autoEnableClaudeInChrome) { - try { - const { - mcpConfig: chromeMcpConfig - } = setupClaudeInChrome(); - dynamicMcpConfig = { - ...dynamicMcpConfig, - ...chromeMcpConfig - }; - const hint = CLAUDE_IN_CHROME_SKILL_HINT; - appendSystemPrompt = appendSystemPrompt ? `${appendSystemPrompt} - -${hint}` : hint; - } catch (error46) { - logForDebugging(`[Claude in Chrome] Error (auto-enable): ${error46}`); - } - } - const strictMcpConfig = options2.strictMcpConfig || false; - if (doesEnterpriseMcpConfigExist()) { - if (strictMcpConfig) { - process.stderr.write(source_default.red("You cannot use --strict-mcp-config when an enterprise MCP config is present")); - process.exit(1); - } - if (dynamicMcpConfig && !areMcpConfigsAllowedWithEnterpriseMcpConfig(dynamicMcpConfig)) { - process.stderr.write(source_default.red("You cannot dynamically configure MCP servers when an enterprise MCP config is present")); - process.exit(1); - } - } - if (false) {} - setAdditionalDirectoriesForClaudeMd(addDir2); - let devChannels; - if (false) {} - if (false) {} - const initResult = await initializeToolPermissionContext({ - allowedToolsCli: allowedTools, - disallowedToolsCli: disallowedTools, - baseToolsCli: baseTools, - permissionMode, - allowDangerouslySkipPermissions, - addDirs: addDir2 - }); - let toolPermissionContext = initResult.toolPermissionContext; - const { - warnings, - dangerousPermissions, - overlyBroadBashPermissions - } = initResult; - if (false) {} - if (false) {} - warnings.forEach((warning) => { - console.error(warning); - }); - assertMinVersion(); - const claudeaiConfigPromise = isNonInteractiveSession && !strictMcpConfig && !doesEnterpriseMcpConfigExist() && !isBareMode() ? fetchClaudeAIMcpConfigsIfEligible().then((configs) => { - const { - allowed, - blocked - } = filterMcpServersByPolicy(configs); - if (blocked.length > 0) { - process.stderr.write(`Warning: claude.ai MCP ${plural(blocked.length, "server")} blocked by enterprise policy: ${blocked.join(", ")} -`); - } - return allowed; - }) : Promise.resolve({}); - logForDebugging("[STARTUP] Loading MCP configs..."); - const mcpConfigStart = Date.now(); - let mcpConfigResolvedMs; - const mcpConfigPromise = (strictMcpConfig || isBareMode() ? Promise.resolve({ - servers: {} - }) : getClaudeCodeMcpConfigs(dynamicMcpConfig)).then((result) => { - mcpConfigResolvedMs = Date.now() - mcpConfigStart; - return result; - }); - if (inputFormat && inputFormat !== "text" && inputFormat !== "stream-json") { - console.error(`Error: Invalid input format "${inputFormat}".`); - process.exit(1); - } - if (inputFormat === "stream-json" && outputFormat !== "stream-json") { - console.error(`Error: --input-format=stream-json requires output-format=stream-json.`); - process.exit(1); - } - if (sdkUrl) { - if (inputFormat !== "stream-json" || outputFormat !== "stream-json") { - console.error(`Error: --sdk-url requires both --input-format=stream-json and --output-format=stream-json.`); - process.exit(1); - } - } - if (options2.replayUserMessages) { - if (inputFormat !== "stream-json" || outputFormat !== "stream-json") { - console.error(`Error: --replay-user-messages requires both --input-format=stream-json and --output-format=stream-json.`); - process.exit(1); - } - } - if (effectiveIncludePartialMessages) { - if (!isNonInteractiveSession || outputFormat !== "stream-json") { - writeToStderr(`Error: --include-partial-messages requires --print and --output-format=stream-json.`); - process.exit(1); - } - } - if (options2.sessionPersistence === false && !isNonInteractiveSession) { - writeToStderr(`Error: --no-session-persistence can only be used with --print mode.`); - process.exit(1); - } - const effectivePrompt = prompt || ""; - let inputPrompt = await getInputPrompt(effectivePrompt, inputFormat ?? "text"); - profileCheckpoint("action_after_input_prompt"); - maybeActivateProactive(options2); - let tools = getTools(toolPermissionContext); - if (false) {} - profileCheckpoint("action_tools_loaded"); - let jsonSchema; - if (isSyntheticOutputToolEnabled({ - isNonInteractiveSession - }) && options2.jsonSchema) { - jsonSchema = jsonParse(options2.jsonSchema); - } - if (jsonSchema) { - const syntheticOutputResult = createSyntheticOutputTool(jsonSchema); - if ("tool" in syntheticOutputResult) { - tools = [...tools, syntheticOutputResult.tool]; - logEvent("tengu_structured_output_enabled", { - schema_property_count: Object.keys(jsonSchema.properties || {}).length, - has_required_fields: Boolean(jsonSchema.required) - }); - } else { - logEvent("tengu_structured_output_failure", { - error: "Invalid JSON schema" - }); - } - } - profileCheckpoint("action_before_setup"); - logForDebugging("[STARTUP] Running setup()..."); - const setupStart = Date.now(); - const { - setup: setup2 - } = await Promise.resolve().then(() => (init_setup3(), exports_setup)); - const messagingSocketPath = undefined; - const preSetupCwd = getCwd(); - if (process.env.CLAUDE_CODE_ENTRYPOINT !== "local-agent") { - initBuiltinPlugins(); - initBundledSkills(); - } - const setupPromise = setup2(preSetupCwd, permissionMode, allowDangerouslySkipPermissions, worktreeEnabled, worktreeName, tmuxEnabled, sessionId ? validateUuid2(sessionId) : undefined, worktreePRNumber, messagingSocketPath); - const commandsPromise = worktreeEnabled ? null : getCommands(preSetupCwd); - const agentDefsPromise = worktreeEnabled ? null : getAgentDefinitionsWithOverrides(preSetupCwd); - commandsPromise?.catch(() => {}); - agentDefsPromise?.catch(() => {}); - await setupPromise; - logForDebugging(`[STARTUP] setup() completed in ${Date.now() - setupStart}ms`); - profileCheckpoint("action_after_setup"); - let effectiveReplayUserMessages = !!options2.replayUserMessages; - if (false) {} - if (getIsNonInteractiveSession()) { - applyConfigEnvironmentVariables(); - getSystemContext(); - getUserContext(); - ensureModelStringsInitialized(); - } - const sessionNameArg = options2.name?.trim(); - if (sessionNameArg) { - cacheSessionTitle(sessionNameArg); - } - const explicitModel = options2.model || process.env.ANTHROPIC_MODEL; - if (false) {} - const userSpecifiedModel = options2.model === "default" ? getDefaultMainLoopModel() : options2.model; - const userSpecifiedFallbackModel = fallbackModel === "default" ? getDefaultMainLoopModel() : fallbackModel; - const currentCwd2 = worktreeEnabled ? getCwd() : preSetupCwd; - logForDebugging("[STARTUP] Loading commands and agents..."); - const commandsStart = Date.now(); - const [commands7, agentDefinitionsResult] = await Promise.all([commandsPromise ?? getCommands(currentCwd2), agentDefsPromise ?? getAgentDefinitionsWithOverrides(currentCwd2)]); - logForDebugging(`[STARTUP] Commands and agents loaded in ${Date.now() - commandsStart}ms`); - profileCheckpoint("action_commands_loaded"); - let cliAgents = []; - if (agentsJson) { - try { - const parsedAgents = safeParseJSON(agentsJson); - if (parsedAgents) { - cliAgents = parseAgentsFromJson(parsedAgents, "flagSettings"); - } - } catch (error46) { - logError2(error46); - } - } - const allAgents = [...agentDefinitionsResult.allAgents, ...cliAgents]; - const agentDefinitions = { - ...agentDefinitionsResult, - allAgents, - activeAgents: getActiveAgentsFromList(allAgents) - }; - const agentSetting = agentCli ?? getInitialSettings().agent; - let mainThreadAgentDefinition; - if (agentSetting) { - mainThreadAgentDefinition = agentDefinitions.activeAgents.find((agent) => agent.agentType === agentSetting); - if (!mainThreadAgentDefinition) { - logForDebugging(`Warning: agent "${agentSetting}" not found. Available agents: ${agentDefinitions.activeAgents.map((a5) => a5.agentType).join(", ")}. Using default behavior.`); - } - } - setMainThreadAgentType(mainThreadAgentDefinition?.agentType); - if (mainThreadAgentDefinition) { - logEvent("tengu_agent_flag", { - agentType: isBuiltInAgent(mainThreadAgentDefinition) ? mainThreadAgentDefinition.agentType : "custom", - ...agentCli && { - source: "cli" - } - }); - } - if (mainThreadAgentDefinition?.agentType) { - saveAgentSetting(mainThreadAgentDefinition.agentType); - } - if (isNonInteractiveSession && mainThreadAgentDefinition && !systemPrompt && !isBuiltInAgent(mainThreadAgentDefinition)) { - const agentSystemPrompt = mainThreadAgentDefinition.getSystemPrompt(); - if (agentSystemPrompt) { - systemPrompt = agentSystemPrompt; - } - } - if (mainThreadAgentDefinition?.initialPrompt) { - if (typeof inputPrompt === "string") { - inputPrompt = inputPrompt ? `${mainThreadAgentDefinition.initialPrompt} - -${inputPrompt}` : mainThreadAgentDefinition.initialPrompt; - } else if (!inputPrompt) { - inputPrompt = mainThreadAgentDefinition.initialPrompt; - } - } - let effectiveModel = userSpecifiedModel; - if (!effectiveModel && mainThreadAgentDefinition?.model && mainThreadAgentDefinition.model !== "inherit") { - effectiveModel = parseUserSpecifiedModel(mainThreadAgentDefinition.model); - } - setMainLoopModelOverride(effectiveModel); - setInitialMainLoopModel(getUserSpecifiedModelSetting() || null); - const initialMainLoopModel = getInitialMainLoopModel(); - const resolvedInitialModel = parseUserSpecifiedModel(initialMainLoopModel ?? getDefaultMainLoopModel()); - let advisorModel; - if (isAdvisorEnabled()) { - const advisorOption = canUserConfigureAdvisor() ? options2.advisor : undefined; - if (advisorOption) { - logForDebugging(`[AdvisorTool] --advisor ${advisorOption}`); - if (!modelSupportsAdvisor(resolvedInitialModel)) { - process.stderr.write(source_default.red(`Error: The model "${resolvedInitialModel}" does not support the advisor tool. -`)); - process.exit(1); - } - const normalizedAdvisorModel = normalizeModelStringForAPI(parseUserSpecifiedModel(advisorOption)); - if (!isValidAdvisorModel(normalizedAdvisorModel)) { - process.stderr.write(source_default.red(`Error: The model "${advisorOption}" cannot be used as an advisor. -`)); - process.exit(1); - } - } - advisorModel = canUserConfigureAdvisor() ? advisorOption ?? getInitialAdvisorSetting() : advisorOption; - if (advisorModel) { - logForDebugging(`[AdvisorTool] Advisor model: ${advisorModel}`); - } - } - if (isAgentSwarmsEnabled() && storedTeammateOpts?.agentId && storedTeammateOpts?.agentName && storedTeammateOpts?.teamName && storedTeammateOpts?.agentType) { - const customAgent = agentDefinitions.activeAgents.find((a5) => a5.agentType === storedTeammateOpts.agentType); - if (customAgent) { - let customPrompt; - if (customAgent.source === "built-in") { - logForDebugging(`[teammate] Built-in agent ${storedTeammateOpts.agentType} - skipping custom prompt (not supported)`); - } else { - customPrompt = customAgent.getSystemPrompt(); - } - if (customAgent.memory) { - logEvent("tengu_agent_memory_loaded", { - ...false, - scope: customAgent.memory, - source: "teammate" - }); - } - if (customPrompt) { - const customInstructions = ` -# Custom Agent Instructions -${customPrompt}`; - appendSystemPrompt = appendSystemPrompt ? `${appendSystemPrompt} - -${customInstructions}` : customInstructions; - } - } else { - logForDebugging(`[teammate] Custom agent ${storedTeammateOpts.agentType} not found in available agents`); - } - } - maybeActivateBrief(options2); - if (false) {} - if (false) {} - if (false) {} - let root3; - let getFpsMetrics; - let stats2; - if (!isNonInteractiveSession) { - const ctx = getRenderContext(false); - getFpsMetrics = ctx.getFpsMetrics; - stats2 = ctx.stats; - if (false) {} - const { - createRoot: createRoot3 - } = await Promise.resolve().then(() => (init_ink2(), exports_ink)); - root3 = await createRoot3(ctx.renderOptions); - logEvent("tengu_timer", { - event: "startup", - durationMs: Math.round(process.uptime() * 1000) - }); - logForDebugging("[STARTUP] Running showSetupScreens()..."); - const setupScreensStart = Date.now(); - const onboardingShown = await showSetupScreens(root3, permissionMode, allowDangerouslySkipPermissions, commands7, enableClaudeInChrome, devChannels); - logForDebugging(`[STARTUP] showSetupScreens() completed in ${Date.now() - setupScreensStart}ms`); - if (false) {} - if (false) {} - if (onboardingShown && prompt?.trim().toLowerCase() === "/login") { - prompt = ""; - } - if (onboardingShown) { - refreshRemoteManagedSettings(); - refreshPolicyLimits(); - resetUserCache(); - refreshGrowthBookAfterAuthChange(); - Promise.resolve().then(() => (init_trustedDevice(), exports_trustedDevice)).then((m4) => { - m4.clearTrustedDeviceToken(); - return m4.enrollTrustedDevice(); - }); - } - const orgValidation = await validateForceLoginOrg(); - if (!orgValidation.valid) { - await exitWithError(root3, orgValidation.message); - } - } - if (process.exitCode !== undefined) { - logForDebugging("Graceful shutdown initiated, skipping further initialization"); - return; - } - initializeLspServerManager(); - if (!isNonInteractiveSession) { - const { - errors: errors8 - } = getSettingsWithErrors(); - const nonMcpErrors = errors8.filter((e4) => !e4.mcpErrorMetadata); - if (nonMcpErrors.length > 0) { - await launchInvalidSettingsDialog(root3, { - settingsErrors: nonMcpErrors, - onExit: () => gracefulShutdownSync(1) - }); - } - } - const bgRefreshThrottleMs = getFeatureValue_CACHED_MAY_BE_STALE("tengu_cicada_nap_ms", 0); - const lastPrefetched = getGlobalConfig().startupPrefetchedAt ?? 0; - const skipStartupPrefetches = isBareMode() || bgRefreshThrottleMs > 0 && Date.now() - lastPrefetched < bgRefreshThrottleMs; - if (!skipStartupPrefetches) { - const lastPrefetchedInfo = lastPrefetched > 0 ? ` last ran ${Math.round((Date.now() - lastPrefetched) / 1000)}s ago` : ""; - logForDebugging(`Starting background startup prefetches${lastPrefetchedInfo}`); - checkQuotaStatus().catch((error46) => logError2(error46)); - fetchBootstrapData(); - prefetchPassesEligibility(); - if (!getFeatureValue_CACHED_MAY_BE_STALE("tengu_miraculo_the_bard", false)) { - prefetchFastModeStatus(); - } else { - resolveFastModeStatusFromCache(); - } - if (bgRefreshThrottleMs > 0) { - saveGlobalConfig((current) => ({ - ...current, - startupPrefetchedAt: Date.now() - })); - } - } else { - logForDebugging(`Skipping startup prefetches, last ran ${Math.round((Date.now() - lastPrefetched) / 1000)}s ago`); - resolveFastModeStatusFromCache(); - } - if (!isNonInteractiveSession) { - refreshExampleCommands(); - } - const { - servers: existingMcpConfigs - } = await mcpConfigPromise; - logForDebugging(`[STARTUP] MCP configs resolved in ${mcpConfigResolvedMs}ms (awaited at +${Date.now() - mcpConfigStart}ms)`); - const allMcpConfigs = { - ...existingMcpConfigs, - ...dynamicMcpConfig - }; - const sdkMcpConfigs = {}; - const regularMcpConfigs = {}; - for (const [name3, config10] of Object.entries(allMcpConfigs)) { - const typedConfig = config10; - if (typedConfig.type === "sdk") { - sdkMcpConfigs[name3] = typedConfig; - } else { - regularMcpConfigs[name3] = typedConfig; - } - } - profileCheckpoint("action_mcp_configs_loaded"); - const localMcpPromise = isNonInteractiveSession ? Promise.resolve({ - clients: [], - tools: [], - commands: [] - }) : prefetchAllMcpResources(regularMcpConfigs); - const claudeaiMcpPromise = isNonInteractiveSession ? Promise.resolve({ - clients: [], - tools: [], - commands: [] - }) : claudeaiConfigPromise.then((configs) => Object.keys(configs).length > 0 ? prefetchAllMcpResources(configs) : { - clients: [], - tools: [], - commands: [] - }); - const mcpPromise = Promise.all([localMcpPromise, claudeaiMcpPromise]).then(([local, claudeai]) => ({ - clients: [...local.clients, ...claudeai.clients], - tools: uniqBy_default([...local.tools, ...claudeai.tools], "name"), - commands: uniqBy_default([...local.commands, ...claudeai.commands], "name") - })); - const hooksPromise = initOnly || init3 || maintenance || isNonInteractiveSession || options2.continue || options2.resume ? null : processSessionStartHooks("startup", { - agentType: mainThreadAgentDefinition?.agentType, - model: resolvedInitialModel - }); - const hookMessages = []; - mcpPromise.catch(() => {}); - const mcpClients = []; - const mcpTools = []; - const mcpCommands = []; - let thinkingEnabled = shouldEnableThinkingByDefault(); - let thinkingConfig = thinkingEnabled !== false ? { - type: "adaptive" - } : { - type: "disabled" - }; - if (options2.thinking === "adaptive" || options2.thinking === "enabled") { - thinkingEnabled = true; - thinkingConfig = { - type: "adaptive" - }; - } else if (options2.thinking === "disabled") { - thinkingEnabled = false; - thinkingConfig = { - type: "disabled" - }; - } else { - const maxThinkingTokens = process.env.MAX_THINKING_TOKENS ? parseInt(process.env.MAX_THINKING_TOKENS, 10) : options2.maxThinkingTokens; - if (maxThinkingTokens !== undefined) { - if (maxThinkingTokens > 0) { - thinkingEnabled = true; - thinkingConfig = { - type: "enabled", - budgetTokens: maxThinkingTokens - }; - } else if (maxThinkingTokens === 0) { - thinkingEnabled = false; - thinkingConfig = { - type: "disabled" - }; - } - } - } - logForDiagnosticsNoPII("info", "started", { - version: MACRO.VERSION, - is_native_binary: isInBundledMode() - }); - registerCleanup(async () => { - logForDiagnosticsNoPII("info", "exited"); - }); - logTenguInit({ - hasInitialPrompt: Boolean(prompt), - hasStdin: Boolean(inputPrompt), - verbose, - debug: debug3, - debugToStderr, - print: print ?? false, - outputFormat: outputFormat ?? "text", - inputFormat: inputFormat ?? "text", - numAllowedTools: allowedTools.length, - numDisallowedTools: disallowedTools.length, - mcpClientCount: Object.keys(allMcpConfigs).length, - worktreeEnabled, - skipWebFetchPreflight: getInitialSettings().skipWebFetchPreflight, - githubActionInputs: process.env.GITHUB_ACTION_INPUTS, - dangerouslySkipPermissionsPassed: dangerouslySkipPermissions ?? false, - permissionMode, - modeIsBypass: permissionMode === "bypassPermissions", - allowDangerouslySkipPermissionsPassed: allowDangerouslySkipPermissions, - systemPromptFlag: systemPrompt ? options2.systemPromptFile ? "file" : "flag" : undefined, - appendSystemPromptFlag: appendSystemPrompt ? options2.appendSystemPromptFile ? "file" : "flag" : undefined, - thinkingConfig, - assistantActivationPath: undefined - }); - logContextMetrics(regularMcpConfigs, toolPermissionContext); - logPermissionContextForAnts(null, "initialization"); - logManagedSettings(); - registerSession().then((registered) => { - if (!registered) - return; - if (sessionNameArg) { - updateSessionName(sessionNameArg); - } - countConcurrentSessions().then((count4) => { - if (count4 >= 2) { - logEvent("tengu_concurrent_sessions", { - num_sessions: count4 - }); - } - }); - }); - if (isBareMode()) {} else if (isNonInteractiveSession) { - await initializeVersionedPlugins(); - profileCheckpoint("action_after_plugins_init"); - cleanupOrphanedPluginVersionsInBackground().then(() => getGlobExclusionsForPluginCache()); - } else { - initializeVersionedPlugins().then(async () => { - profileCheckpoint("action_after_plugins_init"); - await cleanupOrphanedPluginVersionsInBackground(); - getGlobExclusionsForPluginCache(); - }); - } - const setupTrigger = initOnly || init3 ? "init" : maintenance ? "maintenance" : null; - if (initOnly) { - applyConfigEnvironmentVariables(); - await processSetupHooks("init", { - forceSyncExecution: true - }); - await processSessionStartHooks("startup", { - forceSyncExecution: true - }); - gracefulShutdownSync(0); - return; - } - if (isNonInteractiveSession) { - if (outputFormat === "stream-json" || outputFormat === "json") { - setHasFormattedOutput(true); - } - applyConfigEnvironmentVariables(); - initializeTelemetryAfterTrust(); - const sessionStartHooksPromise = options2.continue || options2.resume || teleport || setupTrigger ? undefined : processSessionStartHooks("startup"); - sessionStartHooksPromise?.catch(() => {}); - profileCheckpoint("before_validateForceLoginOrg"); - const orgValidation = await validateForceLoginOrg(); - if (!orgValidation.valid) { - process.stderr.write(orgValidation.message + ` -`); - process.exit(1); - } - const commandsHeadless = disableSlashCommands ? [] : commands7.filter((command19) => command19.type === "prompt" && !command19.disableNonInteractive || command19.type === "local" && command19.supportsNonInteractive); - const defaultState = getDefaultAppState(); - const headlessInitialState = { - ...defaultState, - mcp: { - ...defaultState.mcp, - clients: mcpClients, - commands: mcpCommands, - tools: mcpTools - }, - toolPermissionContext, - effortValue: parseEffortValue(options2.effort) ?? getInitialEffortSetting(), - ...isFastModeEnabled() && { - fastMode: getInitialFastModeSetting(effectiveModel ?? null) - }, - ...isAdvisorEnabled() && advisorModel && { - advisorModel - }, - ...{} - }; - const headlessStore = createStore2(headlessInitialState, onChangeAppState); - if (toolPermissionContext.mode === "bypassPermissions" || allowDangerouslySkipPermissions) { - checkAndDisableBypassPermissions(toolPermissionContext); - } - if (false) {} - if (options2.sessionPersistence === false) { - setSessionPersistenceDisabled(true); - } - setSdkBetas(filterAllowedSdkBetas(betas)); - const connectMcpBatch = (configs, label) => { - if (Object.keys(configs).length === 0) - return Promise.resolve(); - headlessStore.setState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: [...prev.mcp.clients, ...Object.entries(configs).map(([name3, config10]) => ({ - name: name3, - type: "pending", - config: config10 - }))] - } - })); - return getMcpToolsCommandsAndResources(({ - client: client16, - tools: tools2, - commands: commands8 - }) => { - headlessStore.setState((prev) => ({ - ...prev, - mcp: { - ...prev.mcp, - clients: prev.mcp.clients.some((c9) => c9.name === client16.name) ? prev.mcp.clients.map((c9) => c9.name === client16.name ? client16 : c9) : [...prev.mcp.clients, client16], - tools: uniqBy_default([...prev.mcp.tools, ...tools2], "name"), - commands: uniqBy_default([...prev.mcp.commands, ...commands8], "name") - } - })); - }, configs).catch((err2) => logForDebugging(`[MCP] ${label} connect error: ${err2}`)); - }; - profileCheckpoint("before_connectMcp"); - await connectMcpBatch(regularMcpConfigs, "regular"); - profileCheckpoint("after_connectMcp"); - const CLAUDE_AI_MCP_TIMEOUT_MS = 5000; - const claudeaiConnect = claudeaiConfigPromise.then((claudeaiConfigs) => { - if (Object.keys(claudeaiConfigs).length > 0) { - const claudeaiSigs = new Set; - for (const config10 of Object.values(claudeaiConfigs)) { - const sig = getMcpServerSignature(config10); - if (sig) - claudeaiSigs.add(sig); - } - const suppressed = new Set; - for (const [name3, config10] of Object.entries(regularMcpConfigs)) { - if (!name3.startsWith("plugin:")) - continue; - const sig = getMcpServerSignature(config10); - if (sig && claudeaiSigs.has(sig)) - suppressed.add(name3); - } - if (suppressed.size > 0) { - logForDebugging(`[MCP] Lazy dedup: suppressing ${suppressed.size} plugin server(s) that duplicate claude.ai connectors: ${[...suppressed].join(", ")}`); - for (const c9 of headlessStore.getState().mcp.clients) { - if (!suppressed.has(c9.name) || c9.type !== "connected") - continue; - c9.client.onclose = undefined; - clearServerCache(c9.name, c9.config).catch(() => {}); - } - headlessStore.setState((prev) => { - let { - clients, - tools: tools2, - commands: commands8, - resources - } = prev.mcp; - clients = clients.filter((c9) => !suppressed.has(c9.name)); - tools2 = tools2.filter((t4) => !t4.mcpInfo || !suppressed.has(t4.mcpInfo.serverName)); - for (const name3 of suppressed) { - commands8 = excludeCommandsByServer(commands8, name3); - resources = excludeResourcesByServer(resources, name3); - } - return { - ...prev, - mcp: { - ...prev.mcp, - clients, - tools: tools2, - commands: commands8, - resources - } - }; - }); - } - } - const nonPluginConfigs = pickBy_default(regularMcpConfigs, (_, n6) => !n6.startsWith("plugin:")); - const { - servers: dedupedClaudeAi - } = dedupClaudeAiMcpServers(claudeaiConfigs, nonPluginConfigs); - return connectMcpBatch(dedupedClaudeAi, "claudeai"); - }); - let claudeaiTimer; - const claudeaiTimedOut = await Promise.race([claudeaiConnect.then(() => false), new Promise((resolve45) => { - claudeaiTimer = setTimeout((r4) => r4(true), CLAUDE_AI_MCP_TIMEOUT_MS, resolve45); - })]); - if (claudeaiTimer) - clearTimeout(claudeaiTimer); - if (claudeaiTimedOut) { - logForDebugging(`[MCP] claude.ai connectors not ready after ${CLAUDE_AI_MCP_TIMEOUT_MS}ms \u2014 proceeding; background connection continues`); - } - profileCheckpoint("after_connectMcp_claudeai"); - if (!isBareMode()) { - startDeferredPrefetches(); - Promise.resolve().then(() => (init_backgroundHousekeeping(), exports_backgroundHousekeeping)).then((m4) => m4.startBackgroundHousekeeping()); - if (false) {} - } - logSessionTelemetry(); - profileCheckpoint("before_print_import"); - const { - runHeadless: runHeadless2 - } = await Promise.resolve().then(() => (init_print(), exports_print)); - profileCheckpoint("after_print_import"); - runHeadless2(inputPrompt, () => headlessStore.getState(), headlessStore.setState, commandsHeadless, tools, sdkMcpConfigs, agentDefinitions.activeAgents, { - continue: options2.continue, - resume: options2.resume, - verbose, - outputFormat, - jsonSchema, - permissionPromptToolName: options2.permissionPromptTool, - allowedTools, - thinkingConfig, - maxTurns: options2.maxTurns, - maxBudgetUsd: options2.maxBudgetUsd, - taskBudget: options2.taskBudget ? { - total: options2.taskBudget - } : undefined, - systemPrompt, - appendSystemPrompt, - userSpecifiedModel: effectiveModel, - fallbackModel: userSpecifiedFallbackModel, - teleport, - sdkUrl, - replayUserMessages: effectiveReplayUserMessages, - includePartialMessages: effectiveIncludePartialMessages, - forkSession: options2.forkSession || false, - resumeSessionAt: options2.resumeSessionAt || undefined, - rewindFiles: options2.rewindFiles, - enableAuthStatus: options2.enableAuthStatus, - agent: agentCli, - workload: options2.workload, - setupTrigger: setupTrigger ?? undefined, - sessionStartHooksPromise - }); - return; - } - logEvent("tengu_startup_manual_model_config", { - cli_flag: options2.model, - env_var: process.env.ANTHROPIC_MODEL, - settings_file: (getInitialSettings() || {}).model, - subscriptionType: getSubscriptionType(), - agent: agentSetting - }); - const deprecationWarning = getModelDeprecationWarning(resolvedInitialModel); - const initialNotifications = []; - if (permissionModeNotification) { - initialNotifications.push({ - key: "permission-mode-notification", - text: permissionModeNotification, - priority: "high" - }); - } - if (deprecationWarning) { - initialNotifications.push({ - key: "model-deprecation-warning", - text: deprecationWarning, - color: "warning", - priority: "high" - }); - } - if (overlyBroadBashPermissions.length > 0) { - const displayList = uniq(overlyBroadBashPermissions.map((p4) => p4.ruleDisplay)); - const displays = displayList.join(", "); - const sources = uniq(overlyBroadBashPermissions.map((p4) => p4.sourceDisplay)).join(", "); - const n6 = displayList.length; - initialNotifications.push({ - key: "overly-broad-bash-notification", - text: `${displays} allow ${plural(n6, "rule")} from ${sources} ${plural(n6, "was", "were")} ignored \u2014 not available for Ants, please use auto-mode instead`, - color: "warning", - priority: "high" - }); - } - const effectiveToolPermissionContext = { - ...toolPermissionContext, - mode: isAgentSwarmsEnabled() && getTeammateUtils().isPlanModeRequired() ? "plan" : toolPermissionContext.mode - }; - const initialIsBriefOnly = false; - const fullRemoteControl = remoteControl || getRemoteControlAtStartup() || kairosEnabled; - let ccrMirrorEnabled = false; - if (false) {} - const initialState = { - settings: getInitialSettings(), - tasks: {}, - agentNameRegistry: new Map, - verbose: verbose ?? getGlobalConfig().verbose ?? false, - mainLoopModel: initialMainLoopModel, - mainLoopModelForSession: null, - isBriefOnly: initialIsBriefOnly, - expandedView: getGlobalConfig().showSpinnerTree ? "teammates" : getGlobalConfig().showExpandedTodos ? "tasks" : "none", - showTeammateMessagePreview: isAgentSwarmsEnabled() ? false : undefined, - selectedIPAgentIndex: -1, - coordinatorTaskIndex: -1, - viewSelectionMode: "none", - footerSelection: null, - toolPermissionContext: effectiveToolPermissionContext, - agent: mainThreadAgentDefinition?.agentType, - agentDefinitions, - mcp: { - clients: [], - tools: [], - commands: [], - resources: {}, - pluginReconnectKey: 0 - }, - plugins: { - enabled: [], - disabled: [], - commands: [], - errors: [], - installationStatus: { - marketplaces: [], - plugins: [] - }, - needsRefresh: false - }, - statusLineText: undefined, - kairosEnabled, - remoteSessionUrl: undefined, - remoteConnectionStatus: "connecting", - remoteBackgroundTaskCount: 0, - replBridgeEnabled: fullRemoteControl || ccrMirrorEnabled, - replBridgeExplicit: remoteControl, - replBridgeOutboundOnly: ccrMirrorEnabled, - replBridgeConnected: false, - replBridgeSessionActive: false, - replBridgeReconnecting: false, - replBridgeConnectUrl: undefined, - replBridgeSessionUrl: undefined, - replBridgeEnvironmentId: undefined, - replBridgeSessionId: undefined, - replBridgeError: undefined, - replBridgeInitialName: remoteControlName, - showRemoteCallout: false, - notifications: { - current: null, - queue: initialNotifications - }, - elicitation: { - queue: [] - }, - todos: {}, - remoteAgentTaskSuggestions: [], - fileHistory: { - snapshots: [], - trackedFiles: new Set, - snapshotSequence: 0 - }, - attribution: createEmptyAttributionState(), - thinkingEnabled, - promptSuggestionEnabled: shouldEnablePromptSuggestion(), - sessionHooks: new Map, - inbox: { - messages: [] - }, - promptSuggestion: { - text: null, - promptId: null, - shownAt: 0, - acceptedAt: 0, - generationRequestId: null - }, - speculation: IDLE_SPECULATION_STATE, - speculationSessionTimeSavedMs: 0, - skillImprovement: { - suggestion: null - }, - workerSandboxPermissions: { - queue: [], - selectedIndex: 0 - }, - pendingWorkerRequest: null, - pendingSandboxRequest: null, - authVersion: 0, - initialMessage: inputPrompt ? { - message: createUserMessage({ - content: String(inputPrompt) - }) - } : null, - effortValue: parseEffortValue(options2.effort) ?? getInitialEffortSetting(), - activeOverlays: new Set, - fastMode: getInitialFastModeSetting(resolvedInitialModel), - ...isAdvisorEnabled() && advisorModel && { - advisorModel - }, - teamContext: computeInitialTeamContext?.() - }; - if (inputPrompt) { - addToHistory(String(inputPrompt)); - } - const initialTools = mcpTools; - saveGlobalConfig((current) => ({ - ...current, - numStartups: (current.numStartups ?? 0) + 1 - })); - setImmediate(() => { - logStartupTelemetry(); - logSessionTelemetry(); - }); - const sessionUploaderPromise = null; - const uploaderReady = sessionUploaderPromise ? sessionUploaderPromise.then((mod2) => mod2.createSessionTurnUploader()).catch(() => null) : null; - const sessionConfig = { - debug: debug3 || debugToStderr, - commands: [...commands7, ...mcpCommands], - initialTools, - mcpClients, - autoConnectIdeFlag: ide2, - mainThreadAgentDefinition, - disableSlashCommands, - dynamicMcpConfig, - strictMcpConfig, - systemPrompt, - appendSystemPrompt, - taskListId, - thinkingConfig, - ...uploaderReady && { - onTurnComplete: (messages) => { - uploaderReady.then((uploader) => uploader?.(messages)); - } - } - }; - const resumeContext = { - modeApi: coordinatorModeModule, - mainThreadAgentDefinition, - agentDefinitions, - currentCwd: currentCwd2, - cliAgents, - initialState - }; - if (options2.continue) { - let resumeSucceeded = false; - try { - const resumeStart = performance.now(); - const { - clearSessionCaches: clearSessionCaches2 - } = await Promise.resolve().then(() => (init_caches(), exports_caches)); - clearSessionCaches2(); - const result = await loadConversationForResume(undefined, undefined); - if (!result) { - logEvent("tengu_continue", { - success: false - }); - return await exitWithError(root3, "No conversation found to continue"); - } - const loaded = await processResumedConversation(result, { - forkSession: !!options2.forkSession, - includeAttribution: true, - transcriptPath: result.fullPath - }, resumeContext); - if (loaded.restoredAgentDef) { - mainThreadAgentDefinition = loaded.restoredAgentDef; - } - maybeActivateProactive(options2); - maybeActivateBrief(options2); - logEvent("tengu_continue", { - success: true, - resume_duration_ms: Math.round(performance.now() - resumeStart) - }); - resumeSucceeded = true; - await launchRepl(root3, { - getFpsMetrics, - stats: stats2, - initialState: loaded.initialState - }, { - ...sessionConfig, - mainThreadAgentDefinition: loaded.restoredAgentDef ?? mainThreadAgentDefinition, - initialMessages: loaded.messages, - initialFileHistorySnapshots: loaded.fileHistorySnapshots, - initialContentReplacements: loaded.contentReplacements, - initialAgentName: loaded.agentName, - initialAgentColor: loaded.agentColor - }, renderAndRun); - } catch (error46) { - if (!resumeSucceeded) { - logEvent("tengu_continue", { - success: false - }); - } - logError2(error46); - process.exit(1); - } - } else if (false) {} else if (false) {} else if (false) {} else if (options2.resume || options2.fromPr || teleport || remote !== null) { - const { - clearSessionCaches: clearSessionCaches2 - } = await Promise.resolve().then(() => (init_caches(), exports_caches)); - clearSessionCaches2(); - let messages = null; - let processedResume = undefined; - let maybeSessionId = validateUuid2(options2.resume); - let searchTerm = undefined; - let matchedLog = null; - let filterByPr = undefined; - if (options2.fromPr) { - if (options2.fromPr === true) { - filterByPr = true; - } else if (typeof options2.fromPr === "string") { - filterByPr = options2.fromPr; - } - } - if (options2.resume && typeof options2.resume === "string" && !maybeSessionId) { - const trimmedValue = options2.resume.trim(); - if (trimmedValue) { - const matches = await searchSessionsByCustomTitle(trimmedValue, { - exact: true - }); - if (matches.length === 1) { - matchedLog = matches[0]; - maybeSessionId = getSessionIdFromLog(matchedLog) ?? null; - } else { - searchTerm = trimmedValue; - } - } - } - if (remote !== null || teleport) { - await waitForPolicyLimitsToLoad(); - if (!isPolicyAllowed("allow_remote_sessions")) { - return await exitWithError(root3, "Error: Remote sessions are disabled by your organization's policy.", () => gracefulShutdown(1)); - } - } - if (remote !== null) { - const hasInitialPrompt = remote.length > 0; - const isRemoteTuiEnabled = getFeatureValue_CACHED_MAY_BE_STALE("tengu_remote_backend", false); - if (!isRemoteTuiEnabled && !hasInitialPrompt) { - return await exitWithError(root3, `Error: --remote requires a description. -Usage: claude --remote "your task description"`, () => gracefulShutdown(1)); - } - logEvent("tengu_remote_create_session", { - has_initial_prompt: String(hasInitialPrompt) - }); - const currentBranch = await getBranch(); - const createdSession = await teleportToRemoteWithErrorHandling(root3, hasInitialPrompt ? remote : null, new AbortController().signal, currentBranch || undefined); - if (!createdSession) { - logEvent("tengu_remote_create_session_error", { - error: "unable_to_create_session" - }); - return await exitWithError(root3, "Error: Unable to create remote session", () => gracefulShutdown(1)); - } - logEvent("tengu_remote_create_session_success", { - session_id: createdSession.id - }); - if (!isRemoteTuiEnabled) { - process.stdout.write(`Created remote session: ${createdSession.title} -`); - process.stdout.write(`View: ${getRemoteSessionUrl(createdSession.id)}?m=0 -`); - process.stdout.write(`Resume with: claude --teleport ${createdSession.id} -`); - await gracefulShutdown(0); - process.exit(0); - } - setIsRemoteMode(true); - switchSession(asSessionId(createdSession.id)); - let apiCreds; - try { - apiCreds = await prepareApiRequest(); - } catch (error46) { - logError2(toError(error46)); - return await exitWithError(root3, `Error: ${errorMessage(error46) || "Failed to authenticate"}`, () => gracefulShutdown(1)); - } - const { - getClaudeAIOAuthTokens: getTokensForRemote - } = await Promise.resolve().then(() => (init_auth14(), exports_auth)); - const getAccessTokenForRemote = () => getTokensForRemote()?.accessToken ?? apiCreds.accessToken; - const remoteSessionConfig = createRemoteSessionConfig(createdSession.id, getAccessTokenForRemote, apiCreds.orgUUID, hasInitialPrompt); - const remoteSessionUrl = `${getRemoteSessionUrl(createdSession.id)}?m=0`; - const remoteInfoMessage = createSystemMessage(`/remote-control is active. Code in CLI or at ${remoteSessionUrl}`, "info"); - const initialUserMessage = hasInitialPrompt ? createUserMessage({ - content: remote - }) : null; - const remoteInitialState = { - ...initialState, - remoteSessionUrl - }; - const remoteCommands = filterCommandsForRemoteMode(commands7); - await launchRepl(root3, { - getFpsMetrics, - stats: stats2, - initialState: remoteInitialState - }, { - debug: debug3 || debugToStderr, - commands: remoteCommands, - initialTools: [], - initialMessages: initialUserMessage ? [remoteInfoMessage, initialUserMessage] : [remoteInfoMessage], - mcpClients: [], - autoConnectIdeFlag: ide2, - mainThreadAgentDefinition, - disableSlashCommands, - remoteSessionConfig, - thinkingConfig - }, renderAndRun); - return; - } else if (teleport) { - if (teleport === true || teleport === "") { - logEvent("tengu_teleport_interactive_mode", {}); - logForDebugging("selectAndResumeTeleportTask: Starting teleport flow..."); - const teleportResult = await launchTeleportResumeWrapper(root3); - if (!teleportResult) { - await gracefulShutdown(0); - process.exit(0); - } - const { - branchError - } = await checkOutTeleportedSessionBranch(teleportResult.branch); - messages = processMessagesForTeleportResume(teleportResult.log, branchError); - } else if (typeof teleport === "string") { - logEvent("tengu_teleport_resume_session", { - mode: "direct" - }); - try { - const sessionData = await fetchSession(teleport); - const repoValidation = await validateSessionRepository(sessionData); - if (repoValidation.status === "mismatch" || repoValidation.status === "not_in_repo") { - const sessionRepo = repoValidation.sessionRepo; - if (sessionRepo) { - const knownPaths = getKnownPathsForRepo(sessionRepo); - const existingPaths = await filterExistingPaths(knownPaths); - if (existingPaths.length > 0) { - const selectedPath = await launchTeleportRepoMismatchDialog(root3, { - targetRepo: sessionRepo, - initialPaths: existingPaths - }); - if (selectedPath) { - process.chdir(selectedPath); - setCwd(selectedPath); - setOriginalCwd(selectedPath); - } else { - await gracefulShutdown(0); - } - } else { - throw new TeleportOperationError(`You must run claude --teleport ${teleport} from a checkout of ${sessionRepo}.`, source_default.red(`You must run claude --teleport ${teleport} from a checkout of ${source_default.bold(sessionRepo)}. -`)); - } - } - } else if (repoValidation.status === "error") { - throw new TeleportOperationError(repoValidation.errorMessage || "Failed to validate session", source_default.red(`Error: ${repoValidation.errorMessage || "Failed to validate session"} -`)); - } - await validateGitState(); - const { - teleportWithProgress: teleportWithProgress2 - } = await Promise.resolve().then(() => (init_TeleportProgress(), exports_TeleportProgress)); - const result = await teleportWithProgress2(root3, teleport); - setTeleportedSessionInfo({ - sessionId: teleport - }); - messages = result.messages; - } catch (error46) { - if (error46 instanceof TeleportOperationError) { - process.stderr.write(error46.formattedMessage + ` -`); - } else { - logError2(error46); - process.stderr.write(source_default.red(`Error: ${errorMessage(error46)} -`)); - } - await gracefulShutdown(1); - } - } - } - if (false) {} - if (maybeSessionId) { - const sessionId2 = maybeSessionId; - try { - const resumeStart = performance.now(); - const result = await loadConversationForResume(matchedLog ?? sessionId2, undefined); - if (!result) { - logEvent("tengu_session_resumed", { - entrypoint: "cli_flag", - success: false - }); - return await exitWithError(root3, `No conversation found with session ID: ${sessionId2}`); - } - const fullPath = matchedLog?.fullPath ?? result.fullPath; - processedResume = await processResumedConversation(result, { - forkSession: !!options2.forkSession, - sessionIdOverride: sessionId2, - transcriptPath: fullPath - }, resumeContext); - if (processedResume.restoredAgentDef) { - mainThreadAgentDefinition = processedResume.restoredAgentDef; - } - logEvent("tengu_session_resumed", { - entrypoint: "cli_flag", - success: true, - resume_duration_ms: Math.round(performance.now() - resumeStart) - }); - } catch (error46) { - logEvent("tengu_session_resumed", { - entrypoint: "cli_flag", - success: false - }); - logError2(error46); - await exitWithError(root3, `Failed to resume session ${sessionId2}`); - } - } - if (fileDownloadPromise) { - try { - const results = await fileDownloadPromise; - const failedCount = count2(results, (r4) => !r4.success); - if (failedCount > 0) { - process.stderr.write(source_default.yellow(`Warning: ${failedCount}/${results.length} file(s) failed to download. -`)); - } - } catch (error46) { - return await exitWithError(root3, `Error downloading files: ${errorMessage(error46)}`); - } - } - const resumeData = processedResume ?? (Array.isArray(messages) ? { - messages, - fileHistorySnapshots: undefined, - agentName: undefined, - agentColor: undefined, - restoredAgentDef: mainThreadAgentDefinition, - initialState, - contentReplacements: undefined - } : undefined); - if (resumeData) { - maybeActivateProactive(options2); - maybeActivateBrief(options2); - await launchRepl(root3, { - getFpsMetrics, - stats: stats2, - initialState: resumeData.initialState - }, { - ...sessionConfig, - mainThreadAgentDefinition: resumeData.restoredAgentDef ?? mainThreadAgentDefinition, - initialMessages: resumeData.messages, - initialFileHistorySnapshots: resumeData.fileHistorySnapshots, - initialContentReplacements: resumeData.contentReplacements, - initialAgentName: resumeData.agentName, - initialAgentColor: resumeData.agentColor - }, renderAndRun); - } else { - await launchResumeChooser(root3, { - getFpsMetrics, - stats: stats2, - initialState - }, getWorktreePaths(getOriginalCwd()), { - ...sessionConfig, - initialSearchQuery: searchTerm, - forkSession: options2.forkSession, - filterByPr - }); - } - } else { - const pendingHookMessages = hooksPromise && hookMessages.length === 0 ? hooksPromise : undefined; - profileCheckpoint("action_after_hooks"); - maybeActivateProactive(options2); - maybeActivateBrief(options2); - if (false) {} - let deepLinkBanner = null; - if (false) {} - const initialMessages = deepLinkBanner ? [deepLinkBanner, ...hookMessages] : hookMessages.length > 0 ? hookMessages : undefined; - await launchRepl(root3, { - getFpsMetrics, - stats: stats2, - initialState - }, { - ...sessionConfig, - initialMessages, - pendingHookMessages - }, renderAndRun); - } - }).version(`${MACRO.VERSION} (Claude Code)`, "-v, --version", "Output the version number"); - program2.option("-w, --worktree [name]", "Create a new git worktree for this session (optionally specify a name)"); - program2.option("--tmux", "Create a tmux session for the worktree (requires --worktree). Uses iTerm2 native panes when available; use --tmux=classic for traditional tmux."); - if (canUserConfigureAdvisor()) { - program2.addOption(new Option("--advisor <model>", "Enable the server-side advisor tool with the specified model (alias or full ID).").hideHelp()); - } - if (false) {} - if (false) {} - if (false) {} - if (false) {} - if (false) {} - if (false) {} - if (false) {} - program2.addOption(new Option("--agent-id <id>", "Teammate agent ID").hideHelp()); - program2.addOption(new Option("--agent-name <name>", "Teammate display name").hideHelp()); - program2.addOption(new Option("--team-name <name>", "Team name for swarm coordination").hideHelp()); - program2.addOption(new Option("--agent-color <color>", "Teammate UI color").hideHelp()); - program2.addOption(new Option("--plan-mode-required", "Require plan mode before implementation").hideHelp()); - program2.addOption(new Option("--parent-session-id <id>", "Parent session ID for analytics correlation").hideHelp()); - program2.addOption(new Option("--teammate-mode <mode>", 'How to spawn teammates: "tmux", "in-process", or "auto"').choices(["auto", "tmux", "in-process"]).hideHelp()); - program2.addOption(new Option("--agent-type <type>", "Custom agent type for this teammate").hideHelp()); - program2.addOption(new Option("--sdk-url <url>", "Use remote WebSocket endpoint for SDK I/O streaming (only with -p and stream-json format)").hideHelp()); - program2.addOption(new Option("--teleport [session]", "Resume a teleport session, optionally specify session ID").hideHelp()); - program2.addOption(new Option("--remote [description]", "Create a remote session with the given description").hideHelp()); - if (false) {} - if (false) {} - profileCheckpoint("run_main_options_built"); - const isPrintMode = process.argv.includes("-p") || process.argv.includes("--print"); - const isCcUrl = process.argv.some((a5) => a5.startsWith("cc://") || a5.startsWith("cc+unix://")); - if (isPrintMode && !isCcUrl) { - profileCheckpoint("run_before_parse"); - await program2.parseAsync(process.argv); - profileCheckpoint("run_after_parse"); - return program2; - } - const mcp2 = program2.command("mcp").description("Configure and manage MCP servers").configureHelp(createSortedHelpConfig()).enablePositionalOptions(); - mcp2.command("serve").description(`Start the Claude Code MCP server`).option("-d, --debug", "Enable debug mode", () => true).option("--verbose", "Override verbose mode setting from config", () => true).action(async ({ - debug: debug3, - verbose - }) => { - const { - mcpServeHandler: mcpServeHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpServeHandler2({ - debug: debug3, - verbose - }); - }); - registerMcpAddCommand(mcp2); - if (isXaaEnabled()) { - registerMcpXaaIdpCommand(mcp2); - } - mcp2.command("remove <name>").description("Remove an MCP server").option("-s, --scope <scope>", "Configuration scope (local, user, or project) - if not specified, removes from whichever scope it exists in").action(async (name3, options2) => { - const { - mcpRemoveHandler: mcpRemoveHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpRemoveHandler2(name3, options2); - }); - mcp2.command("list").description("List configured MCP servers. Note: The workspace trust dialog is skipped and stdio servers from .mcp.json are spawned for health checks. Only use this command in directories you trust.").action(async () => { - const { - mcpListHandler: mcpListHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpListHandler2(); - }); - mcp2.command("get <name>").description("Get details about an MCP server. Note: The workspace trust dialog is skipped and stdio servers from .mcp.json are spawned for health checks. Only use this command in directories you trust.").action(async (name3) => { - const { - mcpGetHandler: mcpGetHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpGetHandler2(name3); - }); - mcp2.command("add-json <name> <json>").description("Add an MCP server (stdio or SSE) with a JSON string").option("-s, --scope <scope>", "Configuration scope (local, user, or project)", "local").option("--client-secret", "Prompt for OAuth client secret (or set MCP_CLIENT_SECRET env var)").action(async (name3, json2, options2) => { - const { - mcpAddJsonHandler: mcpAddJsonHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpAddJsonHandler2(name3, json2, options2); - }); - mcp2.command("add-from-claude-desktop").description("Import MCP servers from Claude Desktop (Mac and WSL only)").option("-s, --scope <scope>", "Configuration scope (local, user, or project)", "local").action(async (options2) => { - const { - mcpAddFromDesktopHandler: mcpAddFromDesktopHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpAddFromDesktopHandler2(options2); - }); - mcp2.command("reset-project-choices").description("Reset all approved and rejected project-scoped (.mcp.json) servers within this project").action(async () => { - const { - mcpResetChoicesHandler: mcpResetChoicesHandler2 - } = await Promise.resolve().then(() => (init_mcp5(), exports_mcp3)); - await mcpResetChoicesHandler2(); - }); - if (false) {} - if (false) {} - if (false) {} - const auth14 = program2.command("auth").description("Manage authentication").configureHelp(createSortedHelpConfig()); - auth14.command("login").description("Sign in to your Anthropic account").option("--email <email>", "Pre-populate email address on the login page").option("--sso", "Force SSO login flow").option("--console", "Use Anthropic Console (API usage billing) instead of Claude subscription").option("--claudeai", "Use Claude subscription (default)").action(async ({ - email: email3, - sso, - console: useConsole, - claudeai - }) => { - const { - authLogin: authLogin2 - } = await Promise.resolve().then(() => (init_auth19(), exports_auth2)); - await authLogin2({ - email: email3, - sso, - console: useConsole, - claudeai - }); - }); - auth14.command("status").description("Show authentication status").option("--json", "Output as JSON (default)").option("--text", "Output as human-readable text").action(async (opts) => { - const { - authStatus: authStatus2 - } = await Promise.resolve().then(() => (init_auth19(), exports_auth2)); - await authStatus2(opts); - }); - auth14.command("logout").description("Log out from your Anthropic account").action(async () => { - const { - authLogout: authLogout2 - } = await Promise.resolve().then(() => (init_auth19(), exports_auth2)); - await authLogout2(); - }); - const coworkOption = () => new Option("--cowork", "Use cowork_plugins directory").hideHelp(); - const pluginCmd = program2.command("plugin").alias("plugins").description("Manage Claude Code plugins").configureHelp(createSortedHelpConfig()); - pluginCmd.command("validate <path>").description("Validate a plugin or marketplace manifest").addOption(coworkOption()).action(async (manifestPath, options2) => { - const { - pluginValidateHandler: pluginValidateHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginValidateHandler2(manifestPath, options2); - }); - pluginCmd.command("list").description("List installed plugins").option("--json", "Output as JSON").option("--available", "Include available plugins from marketplaces (requires --json)").addOption(coworkOption()).action(async (options2) => { - const { - pluginListHandler: pluginListHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginListHandler2(options2); - }); - const marketplaceCmd = pluginCmd.command("marketplace").description("Manage Claude Code marketplaces").configureHelp(createSortedHelpConfig()); - marketplaceCmd.command("add <source>").description("Add a marketplace from a URL, path, or GitHub repo").addOption(coworkOption()).option("--sparse <paths...>", "Limit checkout to specific directories via git sparse-checkout (for monorepos). Example: --sparse .claude-plugin plugins").option("--scope <scope>", "Where to declare the marketplace: user (default), project, or local").action(async (source, options2) => { - const { - marketplaceAddHandler: marketplaceAddHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await marketplaceAddHandler2(source, options2); - }); - marketplaceCmd.command("list").description("List all configured marketplaces").option("--json", "Output as JSON").addOption(coworkOption()).action(async (options2) => { - const { - marketplaceListHandler: marketplaceListHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await marketplaceListHandler2(options2); - }); - marketplaceCmd.command("remove <name>").alias("rm").description("Remove a configured marketplace").addOption(coworkOption()).action(async (name3, options2) => { - const { - marketplaceRemoveHandler: marketplaceRemoveHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await marketplaceRemoveHandler2(name3, options2); - }); - marketplaceCmd.command("update [name]").description("Update marketplace(s) from their source - updates all if no name specified").addOption(coworkOption()).action(async (name3, options2) => { - const { - marketplaceUpdateHandler: marketplaceUpdateHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await marketplaceUpdateHandler2(name3, options2); - }); - pluginCmd.command("install <plugin>").alias("i").description("Install a plugin from available marketplaces (use plugin@marketplace for specific marketplace)").option("-s, --scope <scope>", "Installation scope: user, project, or local", "user").addOption(coworkOption()).action(async (plugin2, options2) => { - const { - pluginInstallHandler: pluginInstallHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginInstallHandler2(plugin2, options2); - }); - pluginCmd.command("uninstall <plugin>").alias("remove").alias("rm").description("Uninstall an installed plugin").option("-s, --scope <scope>", "Uninstall from scope: user, project, or local", "user").option("--keep-data", "Preserve the plugin's persistent data directory (~/.claude/plugins/data/{id}/)").addOption(coworkOption()).action(async (plugin2, options2) => { - const { - pluginUninstallHandler: pluginUninstallHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginUninstallHandler2(plugin2, options2); - }); - pluginCmd.command("enable <plugin>").description("Enable a disabled plugin").option("-s, --scope <scope>", `Installation scope: ${VALID_INSTALLABLE_SCOPES.join(", ")} (default: auto-detect)`).addOption(coworkOption()).action(async (plugin2, options2) => { - const { - pluginEnableHandler: pluginEnableHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginEnableHandler2(plugin2, options2); - }); - pluginCmd.command("disable [plugin]").description("Disable an enabled plugin").option("-a, --all", "Disable all enabled plugins").option("-s, --scope <scope>", `Installation scope: ${VALID_INSTALLABLE_SCOPES.join(", ")} (default: auto-detect)`).addOption(coworkOption()).action(async (plugin2, options2) => { - const { - pluginDisableHandler: pluginDisableHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginDisableHandler2(plugin2, options2); - }); - pluginCmd.command("update <plugin>").description("Update a plugin to the latest version (restart required to apply)").option("-s, --scope <scope>", `Installation scope: ${VALID_UPDATE_SCOPES.join(", ")} (default: user)`).addOption(coworkOption()).action(async (plugin2, options2) => { - const { - pluginUpdateHandler: pluginUpdateHandler2 - } = await Promise.resolve().then(() => (init_plugins(), exports_plugins)); - await pluginUpdateHandler2(plugin2, options2); - }); - program2.command("setup-token").description("Set up a long-lived authentication token (requires Claude subscription)").action(async () => { - const [{ - setupTokenHandler: setupTokenHandler2 - }, { - createRoot: createRoot3 - }] = await Promise.all([Promise.resolve().then(() => (init_util10(), exports_util2)), Promise.resolve().then(() => (init_ink2(), exports_ink))]); - const root3 = await createRoot3(getBaseRenderOptions(false)); - await setupTokenHandler2(root3); - }); - program2.command("agents").description("List configured agents").option("--setting-sources <sources>", "Comma-separated list of setting sources to load (user, project, local).").action(async () => { - const { - agentsHandler: agentsHandler2 - } = await Promise.resolve().then(() => (init_agents3(), exports_agents2)); - await agentsHandler2(); - process.exit(0); - }); - if (false) {} - if (false) {} - if (false) {} - program2.command("doctor").description("Check the health of your Claude Code auto-updater. Note: The workspace trust dialog is skipped and stdio servers from .mcp.json are spawned for health checks. Only use this command in directories you trust.").action(async () => { - const [{ - doctorHandler: doctorHandler2 - }, { - createRoot: createRoot3 - }] = await Promise.all([Promise.resolve().then(() => (init_util10(), exports_util2)), Promise.resolve().then(() => (init_ink2(), exports_ink))]); - const root3 = await createRoot3(getBaseRenderOptions(false)); - await doctorHandler2(root3); - }); - program2.command("update").alias("upgrade").description("Check for updates and install if available").action(async () => { - const { - update: update2 - } = await Promise.resolve().then(() => (init_update(), exports_update)); - await update2(); - }); - if (false) {} - if (false) {} - program2.command("install [target]").description("Install Claude Code native build. Use [target] to specify version (stable, latest, or specific version)").option("--force", "Force installation even if already installed").action(async (target, options2) => { - const { - installHandler: installHandler2 - } = await Promise.resolve().then(() => (init_util10(), exports_util2)); - await installHandler2(target, options2); - }); - if (false) {} - profileCheckpoint("run_before_parse"); - await program2.parseAsync(process.argv); - profileCheckpoint("run_after_parse"); - profileCheckpoint("main_after_run"); - profileReport(); - return program2; -} -async function logTenguInit({ - hasInitialPrompt, - hasStdin, - verbose, - debug: debug3, - debugToStderr, - print, - outputFormat, - inputFormat, - numAllowedTools, - numDisallowedTools, - mcpClientCount, - worktreeEnabled, - skipWebFetchPreflight, - githubActionInputs, - dangerouslySkipPermissionsPassed, - permissionMode, - modeIsBypass, - allowDangerouslySkipPermissionsPassed, - systemPromptFlag, - appendSystemPromptFlag, - thinkingConfig, - assistantActivationPath -}) { - try { - logEvent("tengu_init", { - entrypoint: "claude", - hasInitialPrompt, - hasStdin, - verbose, - debug: debug3, - debugToStderr, - print, - outputFormat, - inputFormat, - numAllowedTools, - numDisallowedTools, - mcpClientCount, - worktree: worktreeEnabled, - skipWebFetchPreflight, - ...githubActionInputs && { - githubActionInputs - }, - dangerouslySkipPermissionsPassed, - permissionMode, - modeIsBypass, - inProtectedNamespace: isInProtectedNamespace2(), - allowDangerouslySkipPermissionsPassed, - thinkingType: thinkingConfig.type, - ...systemPromptFlag && { - systemPromptFlag - }, - ...appendSystemPromptFlag && { - appendSystemPromptFlag - }, - is_simple: isBareMode() || undefined, - is_coordinator: undefined, - ...assistantActivationPath && { - assistantActivationPath - }, - autoUpdatesChannel: getInitialSettings().autoUpdatesChannel ?? "latest", - ...{} - }); - } catch (error46) { - logError2(error46); - } -} -function maybeActivateProactive(options2) { - if (false) {} -} -function maybeActivateBrief(options2) { - if (true) - return; - const briefFlag = options2.brief; - const briefEnv = isEnvTruthy(process.env.CLAUDE_CODE_BRIEF); - if (!briefFlag && !briefEnv) - return; - const { - isBriefEntitled: isBriefEntitled2 - } = (init_BriefTool(), __toCommonJS(exports_BriefTool)); - const entitled = isBriefEntitled2(); - if (entitled) { - setUserMsgOptIn(true); - } - logEvent("tengu_brief_mode_enabled", { - enabled: entitled, - gated: !entitled, - source: briefEnv ? "env" : "flag" - }); -} -function resetCursor() { - const terminal = process.stderr.isTTY ? process.stderr : process.stdout.isTTY ? process.stdout : undefined; - terminal?.write(SHOW_CURSOR); -} -function extractTeammateOptions(options2) { - if (typeof options2 !== "object" || options2 === null) { - return {}; - } - const opts = options2; - const teammateMode = opts.teammateMode; - return { - agentId: typeof opts.agentId === "string" ? opts.agentId : undefined, - agentName: typeof opts.agentName === "string" ? opts.agentName : undefined, - teamName: typeof opts.teamName === "string" ? opts.teamName : undefined, - agentColor: typeof opts.agentColor === "string" ? opts.agentColor : undefined, - planModeRequired: typeof opts.planModeRequired === "boolean" ? opts.planModeRequired : undefined, - parentSessionId: typeof opts.parentSessionId === "string" ? opts.parentSessionId : undefined, - teammateMode: teammateMode === "auto" || teammateMode === "tmux" || teammateMode === "in-process" ? teammateMode : undefined, - agentType: typeof opts.agentType === "string" ? opts.agentType : undefined - }; -} -export { - startDeferredPrefetches, - main -};
    -
    At a Glance
    -
    - ${atAGlance.whats_working ? `` : ""} - ${atAGlance.whats_hindering ? `
    What's hindering you: ${escapeHtmlWithBold(atAGlance.whats_hindering)} Where Things Go Wrong \u2192
    ` : ""} - ${atAGlance.quick_wins ? `
    Quick wins to try: ${escapeHtmlWithBold(atAGlance.quick_wins)} Features to Try \u2192
    ` : ""} - ${atAGlance.ambitious_workflows ? `
    Ambitious workflows: ${escapeHtmlWithBold(atAGlance.ambitious_workflows)} On the Horizon \u2192
    ` : ""} -
    -