@wengine-ai/llms 2.0.36 → 2.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
- var R_=Object.create;var pu=Object.defineProperty;var O_=Object.getOwnPropertyDescriptor;var F_=Object.getOwnPropertyNames;var x_=Object.getPrototypeOf,P_=Object.prototype.hasOwnProperty;var Q=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var je=(t,e)=>()=>(t&&(e=t(t=0)),e);var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Df=(t,e)=>{for(var r in e)pu(t,r,{get:e[r],enumerable:!0})},I_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of F_(e))!P_.call(t,s)&&s!==r&&pu(t,s,{get:()=>e[s],enumerable:!(n=O_(e,s))||n.enumerable});return t};var Pr=(t,e,r)=>(r=t!=null?R_(x_(t)):{},I_(e||!t||!t.__esModule?pu(r,"default",{value:t,enumerable:!0}):r,t));var vf=J((CD,Io)=>{Io.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Io.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Io.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var gu=J((wD,Rf)=>{var mu=vf();Rf.exports={isSpaceSeparator(t){return typeof t=="string"&&mu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||mu.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||mu.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var If=J((ED,Pf)=>{var $e=gu(),_u,Ze,pr,Bo,Ir,Nt,ze,wu,bs;Pf.exports=function(e,r){_u=String(e),Ze="start",pr=[],Bo=0,Ir=1,Nt=0,ze=void 0,wu=void 0,bs=void 0;do ze=N_(),L_[Ze]();while(ze.type!=="eof");return typeof r=="function"?bu({"":bs},"",r):bs};function bu(t,e,r){let n=t[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let s=0;s<n.length;s++){let i=String(s),u=bu(n,i,r);u===void 0?delete n[i]:Object.defineProperty(n,i,{value:u,writable:!0,enumerable:!0,configurable:!0})}else for(let s in n){let i=bu(n,s,r);i===void 0?delete n[s]:Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return r.call(t,e,n)}var me,he,_s,hr,Ce;function N_(){for(me="default",he="",_s=!1,hr=1;;){Ce=mr();let t=Ff[me]();if(t)return t}}function mr(){if(_u[Bo])return String.fromCodePoint(_u.codePointAt(Bo))}function H(){let t=mr();return t===`
1
+ var O_=Object.create;var pu=Object.defineProperty;var F_=Object.getOwnPropertyDescriptor;var x_=Object.getOwnPropertyNames;var P_=Object.getPrototypeOf,I_=Object.prototype.hasOwnProperty;var Q=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var je=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Df=(t,e)=>{for(var r in e)pu(t,r,{get:e[r],enumerable:!0})},N_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x_(e))!I_.call(t,s)&&s!==r&&pu(t,s,{get:()=>e[s],enumerable:!(n=F_(e,s))||n.enumerable});return t};var Pr=(t,e,r)=>(r=t!=null?O_(P_(t)):{},N_(e||!t||!t.__esModule?pu(r,"default",{value:t,enumerable:!0}):r,t));var vf=V((ED,Io)=>{Io.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Io.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Io.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var gu=V((AD,Rf)=>{var mu=vf();Rf.exports={isSpaceSeparator(t){return typeof t=="string"&&mu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||mu.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||mu.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var If=V((SD,Pf)=>{var $e=gu(),_u,Ze,pr,Bo,Ir,Nt,ze,wu,bs;Pf.exports=function(e,r){_u=String(e),Ze="start",pr=[],Bo=0,Ir=1,Nt=0,ze=void 0,wu=void 0,bs=void 0;do ze=B_(),M_[Ze]();while(ze.type!=="eof");return typeof r=="function"?bu({"":bs},"",r):bs};function bu(t,e,r){let n=t[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let s=0;s<n.length;s++){let i=String(s),u=bu(n,i,r);u===void 0?delete n[i]:Object.defineProperty(n,i,{value:u,writable:!0,enumerable:!0,configurable:!0})}else for(let s in n){let i=bu(n,s,r);i===void 0?delete n[s]:Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return r.call(t,e,n)}var ge,he,_s,hr,Ce;function B_(){for(ge="default",he="",_s=!1,hr=1;;){Ce=mr();let t=Ff[ge]();if(t)return t}}function mr(){if(_u[Bo])return String.fromCodePoint(_u.codePointAt(Bo))}function H(){let t=mr();return t===`
2
2
  `?(Ir++,Nt=0):t?Nt+=t.length:Nt++,t&&(Bo+=t.length),t}var Ff={default(){switch(Ce){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
3
- `:case"\r":case"\u2028":case"\u2029":H();return;case"/":H(),me="comment";return;case void 0:return H(),Pe("eof")}if($e.isSpaceSeparator(Ce)){H();return}return Ff[Ze]()},comment(){switch(Ce){case"*":H(),me="multiLineComment";return;case"/":H(),me="singleLineComment";return}throw Ie(H())},multiLineComment(){switch(Ce){case"*":H(),me="multiLineCommentAsterisk";return;case void 0:throw Ie(H())}H()},multiLineCommentAsterisk(){switch(Ce){case"*":H();return;case"/":H(),me="default";return;case void 0:throw Ie(H())}H(),me="multiLineComment"},singleLineComment(){switch(Ce){case`
4
- `:case"\r":case"\u2028":case"\u2029":H(),me="default";return;case void 0:return H(),Pe("eof")}H()},value(){switch(Ce){case"{":case"[":return Pe("punctuator",H());case"n":return H(),tn("ull"),Pe("null",null);case"t":return H(),tn("rue"),Pe("boolean",!0);case"f":return H(),tn("alse"),Pe("boolean",!1);case"-":case"+":H()==="-"&&(hr=-1),me="sign";return;case".":he=H(),me="decimalPointLeading";return;case"0":he=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),me="decimalInteger";return;case"I":return H(),tn("nfinity"),Pe("numeric",1/0);case"N":return H(),tn("aN"),Pe("numeric",NaN);case'"':case"'":_s=H()==='"',he="",me="string";return}throw Ie(H())},identifierNameStartEscape(){if(Ce!=="u")throw Ie(H());H();let t=Cu();switch(t){case"$":case"_":break;default:if(!$e.isIdStartChar(t))throw Of();break}he+=t,me="identifierName"},identifierName(){switch(Ce){case"$":case"_":case"\u200C":case"\u200D":he+=H();return;case"\\":H(),me="identifierNameEscape";return}if($e.isIdContinueChar(Ce)){he+=H();return}return Pe("identifier",he)},identifierNameEscape(){if(Ce!=="u")throw Ie(H());H();let t=Cu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!$e.isIdContinueChar(t))throw Of();break}he+=t,me="identifierName"},sign(){switch(Ce){case".":he=H(),me="decimalPointLeading";return;case"0":he=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),me="decimalInteger";return;case"I":return H(),tn("nfinity"),Pe("numeric",hr*(1/0));case"N":return H(),tn("aN"),Pe("numeric",NaN)}throw Ie(H())},zero(){switch(Ce){case".":he+=H(),me="decimalPoint";return;case"e":case"E":he+=H(),me="decimalExponent";return;case"x":case"X":he+=H(),me="hexadecimal";return}return Pe("numeric",hr*0)},decimalInteger(){switch(Ce){case".":he+=H(),me="decimalPoint";return;case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalPointLeading(){if($e.isDigit(Ce)){he+=H(),me="decimalFraction";return}throw Ie(H())},decimalPoint(){switch(Ce){case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H(),me="decimalFraction";return}return Pe("numeric",hr*Number(he))},decimalFraction(){switch(Ce){case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalExponent(){switch(Ce){case"+":case"-":he+=H(),me="decimalExponentSign";return}if($e.isDigit(Ce)){he+=H(),me="decimalExponentInteger";return}throw Ie(H())},decimalExponentSign(){if($e.isDigit(Ce)){he+=H(),me="decimalExponentInteger";return}throw Ie(H())},decimalExponentInteger(){if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},hexadecimal(){if($e.isHexDigit(Ce)){he+=H(),me="hexadecimalInteger";return}throw Ie(H())},hexadecimalInteger(){if($e.isHexDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},string(){switch(Ce){case"\\":H(),he+=B_();return;case'"':if(_s)return H(),Pe("string",he);he+=H();return;case"'":if(!_s)return H(),Pe("string",he);he+=H();return;case`
5
- `:case"\r":throw Ie(H());case"\u2028":case"\u2029":M_(Ce);break;case void 0:throw Ie(H())}he+=H()},start(){switch(Ce){case"{":case"[":return Pe("punctuator",H())}me="value"},beforePropertyName(){switch(Ce){case"$":case"_":he=H(),me="identifierName";return;case"\\":H(),me="identifierNameStartEscape";return;case"}":return Pe("punctuator",H());case'"':case"'":_s=H()==='"',me="string";return}if($e.isIdStartChar(Ce)){he+=H(),me="identifierName";return}throw Ie(H())},afterPropertyName(){if(Ce===":")return Pe("punctuator",H());throw Ie(H())},beforePropertyValue(){me="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Pe("punctuator",H())}throw Ie(H())},beforeArrayValue(){if(Ce==="]")return Pe("punctuator",H());me="value"},afterArrayValue(){switch(Ce){case",":case"]":return Pe("punctuator",H())}throw Ie(H())},end(){throw Ie(H())}};function Pe(t,e){return{type:t,value:e,line:Ir,column:Nt}}function tn(t){for(let e of t){if(mr()!==e)throw Ie(H());H()}}function B_(){switch(mr()){case"b":return H(),"\b";case"f":return H(),"\f";case"n":return H(),`
6
- `;case"r":return H(),"\r";case"t":return H()," ";case"v":return H(),"\v";case"0":if(H(),$e.isDigit(mr()))throw Ie(H());return"\0";case"x":return H(),j_();case"u":return H(),Cu();case`
3
+ `:case"\r":case"\u2028":case"\u2029":H();return;case"/":H(),ge="comment";return;case void 0:return H(),Pe("eof")}if($e.isSpaceSeparator(Ce)){H();return}return Ff[Ze]()},comment(){switch(Ce){case"*":H(),ge="multiLineComment";return;case"/":H(),ge="singleLineComment";return}throw Ie(H())},multiLineComment(){switch(Ce){case"*":H(),ge="multiLineCommentAsterisk";return;case void 0:throw Ie(H())}H()},multiLineCommentAsterisk(){switch(Ce){case"*":H();return;case"/":H(),ge="default";return;case void 0:throw Ie(H())}H(),ge="multiLineComment"},singleLineComment(){switch(Ce){case`
4
+ `:case"\r":case"\u2028":case"\u2029":H(),ge="default";return;case void 0:return H(),Pe("eof")}H()},value(){switch(Ce){case"{":case"[":return Pe("punctuator",H());case"n":return H(),tn("ull"),Pe("null",null);case"t":return H(),tn("rue"),Pe("boolean",!0);case"f":return H(),tn("alse"),Pe("boolean",!1);case"-":case"+":H()==="-"&&(hr=-1),ge="sign";return;case".":he=H(),ge="decimalPointLeading";return;case"0":he=H(),ge="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),ge="decimalInteger";return;case"I":return H(),tn("nfinity"),Pe("numeric",1/0);case"N":return H(),tn("aN"),Pe("numeric",NaN);case'"':case"'":_s=H()==='"',he="",ge="string";return}throw Ie(H())},identifierNameStartEscape(){if(Ce!=="u")throw Ie(H());H();let t=Cu();switch(t){case"$":case"_":break;default:if(!$e.isIdStartChar(t))throw Of();break}he+=t,ge="identifierName"},identifierName(){switch(Ce){case"$":case"_":case"\u200C":case"\u200D":he+=H();return;case"\\":H(),ge="identifierNameEscape";return}if($e.isIdContinueChar(Ce)){he+=H();return}return Pe("identifier",he)},identifierNameEscape(){if(Ce!=="u")throw Ie(H());H();let t=Cu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!$e.isIdContinueChar(t))throw Of();break}he+=t,ge="identifierName"},sign(){switch(Ce){case".":he=H(),ge="decimalPointLeading";return;case"0":he=H(),ge="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),ge="decimalInteger";return;case"I":return H(),tn("nfinity"),Pe("numeric",hr*(1/0));case"N":return H(),tn("aN"),Pe("numeric",NaN)}throw Ie(H())},zero(){switch(Ce){case".":he+=H(),ge="decimalPoint";return;case"e":case"E":he+=H(),ge="decimalExponent";return;case"x":case"X":he+=H(),ge="hexadecimal";return}return Pe("numeric",hr*0)},decimalInteger(){switch(Ce){case".":he+=H(),ge="decimalPoint";return;case"e":case"E":he+=H(),ge="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalPointLeading(){if($e.isDigit(Ce)){he+=H(),ge="decimalFraction";return}throw Ie(H())},decimalPoint(){switch(Ce){case"e":case"E":he+=H(),ge="decimalExponent";return}if($e.isDigit(Ce)){he+=H(),ge="decimalFraction";return}return Pe("numeric",hr*Number(he))},decimalFraction(){switch(Ce){case"e":case"E":he+=H(),ge="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalExponent(){switch(Ce){case"+":case"-":he+=H(),ge="decimalExponentSign";return}if($e.isDigit(Ce)){he+=H(),ge="decimalExponentInteger";return}throw Ie(H())},decimalExponentSign(){if($e.isDigit(Ce)){he+=H(),ge="decimalExponentInteger";return}throw Ie(H())},decimalExponentInteger(){if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},hexadecimal(){if($e.isHexDigit(Ce)){he+=H(),ge="hexadecimalInteger";return}throw Ie(H())},hexadecimalInteger(){if($e.isHexDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},string(){switch(Ce){case"\\":H(),he+=j_();return;case'"':if(_s)return H(),Pe("string",he);he+=H();return;case"'":if(!_s)return H(),Pe("string",he);he+=H();return;case`
5
+ `:case"\r":throw Ie(H());case"\u2028":case"\u2029":U_(Ce);break;case void 0:throw Ie(H())}he+=H()},start(){switch(Ce){case"{":case"[":return Pe("punctuator",H())}ge="value"},beforePropertyName(){switch(Ce){case"$":case"_":he=H(),ge="identifierName";return;case"\\":H(),ge="identifierNameStartEscape";return;case"}":return Pe("punctuator",H());case'"':case"'":_s=H()==='"',ge="string";return}if($e.isIdStartChar(Ce)){he+=H(),ge="identifierName";return}throw Ie(H())},afterPropertyName(){if(Ce===":")return Pe("punctuator",H());throw Ie(H())},beforePropertyValue(){ge="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Pe("punctuator",H())}throw Ie(H())},beforeArrayValue(){if(Ce==="]")return Pe("punctuator",H());ge="value"},afterArrayValue(){switch(Ce){case",":case"]":return Pe("punctuator",H())}throw Ie(H())},end(){throw Ie(H())}};function Pe(t,e){return{type:t,value:e,line:Ir,column:Nt}}function tn(t){for(let e of t){if(mr()!==e)throw Ie(H());H()}}function j_(){switch(mr()){case"b":return H(),"\b";case"f":return H(),"\f";case"n":return H(),`
6
+ `;case"r":return H(),"\r";case"t":return H()," ";case"v":return H(),"\v";case"0":if(H(),$e.isDigit(mr()))throw Ie(H());return"\0";case"x":return H(),L_();case"u":return H(),Cu();case`
7
7
  `:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),mr()===`
8
- `&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ie(H());case void 0:throw Ie(H())}return H()}function j_(){let t="",e=mr();if(!$e.isHexDigit(e)||(t+=H(),e=mr(),!$e.isHexDigit(e)))throw Ie(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function Cu(){let t="",e=4;for(;e-- >0;){let r=mr();if(!$e.isHexDigit(r))throw Ie(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var L_={start(){if(ze.type==="eof")throw rn();yu()},beforePropertyName(){switch(ze.type){case"identifier":case"string":wu=ze.value,Ze="afterPropertyName";return;case"punctuator":No();return;case"eof":throw rn()}},afterPropertyName(){if(ze.type==="eof")throw rn();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw rn();yu()},beforeArrayValue(){if(ze.type==="eof")throw rn();if(ze.type==="punctuator"&&ze.value==="]"){No();return}yu()},afterPropertyValue(){if(ze.type==="eof")throw rn();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":No()}},afterArrayValue(){if(ze.type==="eof")throw rn();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":No()}},end(){}};function yu(){let t;switch(ze.type){case"punctuator":switch(ze.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=ze.value;break}if(bs===void 0)bs=t;else{let e=pr[pr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,wu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")pr.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=pr[pr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function No(){pr.pop();let t=pr[pr.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Ie(t){return jo(t===void 0?`JSON5: invalid end of input at ${Ir}:${Nt}`:`JSON5: invalid character '${xf(t)}' at ${Ir}:${Nt}`)}function rn(){return jo(`JSON5: invalid end of input at ${Ir}:${Nt}`)}function Of(){return Nt-=5,jo(`JSON5: invalid identifier character at ${Ir}:${Nt}`)}function M_(t){console.warn(`JSON5: '${xf(t)}' in strings is not valid ECMAScript; consider escaping`)}function xf(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let r=t.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return t}function jo(t){let e=new SyntaxError(t);return e.lineNumber=Ir,e.columnNumber=Nt,e}});var Bf=J((AD,Nf)=>{var Eu=gu();Nf.exports=function(e,r,n){let s=[],i="",u,c,l="",h;if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&(n=r.space,h=r.quote,r=r.replacer),typeof r=="function")c=r;else if(Array.isArray(r)){u=[];for(let y of r){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&u.indexOf(g)<0&&u.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),f("",{"":e});function f(y,g){let m=g[y];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(y):typeof m.toJSON=="function"&&(m=m.toJSON(y))),c&&(m=c.call(g,y,m)),m instanceof Number?m=Number(m):m instanceof String?m=String(m):m instanceof Boolean&&(m=m.valueOf()),m){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof m=="string")return p(m,!1);if(typeof m=="number")return String(m);if(typeof m=="object")return Array.isArray(m)?E(m):S(m)}function p(y){let g={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},T="";for(let w=0;w<y.length;w++){let O=y[w];switch(O){case"'":case'"':g[O]++,T+=O;continue;case"\0":if(Eu.isDigit(y[w+1])){T+="\\x00";continue}}if(m[O]){T+=m[O];continue}if(O<" "){let x=O.charCodeAt(0).toString(16);T+="\\x"+("00"+x).substring(x.length);continue}T+=O}let b=h||Object.keys(g).reduce((w,O)=>g[w]<g[O]?w:O);return T=T.replace(new RegExp(b,"g"),m[b]),b+T+b}function S(y){if(s.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");s.push(y);let g=i;i=i+l;let m=u||Object.keys(y),T=[];for(let w of m){let O=f(w,y);if(O!==void 0){let x=D(w)+":";l!==""&&(x+=" "),x+=O,T.push(x)}}let b;if(T.length===0)b="{}";else{let w;if(l==="")w=T.join(","),b="{"+w+"}";else{let O=`,
9
- `+i;w=T.join(O),b=`{
10
- `+i+w+`,
11
- `+g+"}"}}return s.pop(),i=g,b}function D(y){if(y.length===0)return p(y,!0);let g=String.fromCodePoint(y.codePointAt(0));if(!Eu.isIdStartChar(g))return p(y,!0);for(let m=g.length;m<y.length;m++)if(!Eu.isIdContinueChar(String.fromCodePoint(y.codePointAt(m))))return p(y,!0);return y}function E(y){if(s.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");s.push(y);let g=i;i=i+l;let m=[];for(let b=0;b<y.length;b++){let w=f(String(b),y);m.push(w!==void 0?w:"null")}let T;if(m.length===0)T="[]";else if(l==="")T="["+m.join(",")+"]";else{let b=`,
12
- `+i,w=m.join(b);T=`[
13
- `+i+w+`,
14
- `+g+"]"}return s.pop(),i=g,T}}});var Au=J((SD,jf)=>{var U_=If(),q_=Bf(),$_={parse:U_,stringify:q_};jf.exports=$_});var vu=J((av,sh)=>{"use strict";var Go=Object.prototype.hasOwnProperty,nh=Object.prototype.toString,Xf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,Zf=function(e){return typeof Array.isArray=="function"?Array.isArray(e):nh.call(e)==="[object Array]"},eh=function(e){if(!e||nh.call(e)!=="[object Object]")return!1;var r=Go.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Go.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var s;for(s in e);return typeof s>"u"||Go.call(e,s)},th=function(e,r){Xf&&r.name==="__proto__"?Xf(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},rh=function(e,r){if(r==="__proto__")if(Go.call(e,r)){if(Qf)return Qf(e,r).value}else return;return e[r]};sh.exports=function t(){var e,r,n,s,i,u,c=arguments[0],l=1,h=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<h;++l)if(e=arguments[l],e!=null)for(r in e)n=rh(c,r),s=rh(e,r),c!==s&&(f&&s&&(eh(s)||(i=Zf(s)))?(i?(i=!1,u=n&&Zf(n)?n:[]):u=n&&eh(n)?n:{},th(c,{name:r,newValue:t(f,u,s)})):typeof s<"u"&&th(c,{name:r,newValue:s}));return c}});var oh=J((uv,nb)=>{nb.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",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:"jsdoc -c .jsdoc.js","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"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.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-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var ah=J((cv,ih)=>{"use strict";var sb=oh();ih.exports={pkg:sb}});var Fu=J(wt=>{"use strict";var ch=wt&&wt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wt,"__esModule",{value:!0});wt.GaxiosError=wt.GAXIOS_ERROR_SYMBOL=void 0;wt.defaultErrorRedactor=lh;var uh=ch(vu()),ob=ch(ah()),Ru=ob.default.pkg;wt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ru.name}-gaxios-error`);var Ou=class t extends Error{config;response;code;status;error;[wt.GAXIOS_ERROR_SYMBOL]=Ru.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&wt.GAXIOS_ERROR_SYMBOL in e&&e[wt.GAXIOS_ERROR_SYMBOL]===Ru.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,s){if(super(e,{cause:s}),this.config=r,this.response=n,this.error=s instanceof Error?s:void 0,this.config=(0,uh.default)(!0,{},r),this.response&&(this.response.config=(0,uh.default)(!0,{},this.response.config)),this.response){try{this.response.data=ib(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}s instanceof DOMException?this.code=s.name:s&&typeof s=="object"&&"code"in s&&(typeof s.code=="string"||typeof s.code=="number")&&(this.code=s.code)}static extractAPIErrorFromResponse(e,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let s="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,i="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let u=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&u.push(c.message);return Object.assign({message:u.join(`
15
- `)||n,code:i,status:s},e.data.error)}return Object.assign({message:n,code:i,status:s},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};wt.GaxiosError=Ou;function ib(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function lh(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(i){i&&i.forEach((u,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&i.set(c,e)})}function n(i,u){if(typeof i=="object"&&i!==null&&typeof i[u]=="string"){let c=i[u];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(i[u]=e)}}function s(i){!i||typeof i!="object"||(i instanceof FormData||i instanceof URLSearchParams||"forEach"in i&&"set"in i?i.forEach((u,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&i.set(c,e)}):("grant_type"in i&&(i.grant_type=e),"assertion"in i&&(i.assertion=e),"client_secret"in i&&(i.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),s(t.config.data),n(t.config,"body"),s(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(lh({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),s(t.response.data))),t}});var fh=J(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.getRetryConfig=ab;async function ab(t){let e=dh(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||ub)(t))return{shouldRetry:!1,config:t.config};let s=cb(e);t.config.retryConfig.currentRetryAttempt+=1;let i=e.retryBackoff?e.retryBackoff(t,s):new Promise(u=>{setTimeout(u,s)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await i,{shouldRetry:!0,config:t.config}}function ub(t){let e=dh(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,s]of e.statusCodesToRetry){let i=t.response.status;if(i>=n&&i<=s){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function dh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function cb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var Iu=J(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.GaxiosInterceptorManager=void 0;var Pu=class extends Set{};Jo.GaxiosInterceptorManager=Pu});var ph=J((hv,hh)=>{var Fn=1e3,xn=Fn*60,Pn=xn*60,nn=Pn*24,lb=nn*7,db=nn*365.25;hh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return fb(t);if(r==="number"&&isFinite(t))return e.long?pb(t):hb(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function fb(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*db;case"weeks":case"week":case"w":return r*lb;case"days":case"day":case"d":return r*nn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pn;case"minutes":case"minute":case"mins":case"min":case"m":return r*xn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Fn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function hb(t){var e=Math.abs(t);return e>=nn?Math.round(t/nn)+"d":e>=Pn?Math.round(t/Pn)+"h":e>=xn?Math.round(t/xn)+"m":e>=Fn?Math.round(t/Fn)+"s":t+"ms"}function pb(t){var e=Math.abs(t);return e>=nn?Vo(t,e,nn,"day"):e>=Pn?Vo(t,e,Pn,"hour"):e>=xn?Vo(t,e,xn,"minute"):e>=Fn?Vo(t,e,Fn,"second"):t+" ms"}function Vo(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var Nu=J((pv,mh)=>{function mb(t){r.debug=r,r.default=r,r.coerce=l,r.disable=u,r.enable=s,r.enabled=c,r.humanize=ph(),r.destroy=h,Object.keys(t).forEach(f=>{r[f]=t[f]}),r.names=[],r.skips=[],r.formatters={};function e(f){let p=0;for(let S=0;S<f.length;S++)p=(p<<5)-p+f.charCodeAt(S),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(f){let p,S=null,D,E;function y(...g){if(!y.enabled)return;let m=y,T=Number(new Date),b=T-(p||T);m.diff=b,m.prev=p,m.curr=T,p=T,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let w=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(x,$)=>{if(x==="%%")return"%";w++;let V=r.formatters[$];if(typeof V=="function"){let U=g[w];x=V.call(m,U),g.splice(w,1),w--}return x}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return y.namespace=f,y.useColors=r.useColors(),y.color=r.selectColor(f),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>S!==null?S:(D!==r.namespaces&&(D=r.namespaces,E=r.enabled(f)),E),set:g=>{S=g}}),typeof r.init=="function"&&r.init(y),y}function n(f,p){let S=r(this.namespace+(typeof p>"u"?":":p)+f);return S.log=this.log,S}function s(f){r.save(f),r.namespaces=f,r.names=[],r.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let S of p)S[0]==="-"?r.skips.push(S.slice(1)):r.names.push(S)}function i(f,p){let S=0,D=0,E=-1,y=0;for(;S<f.length;)if(D<p.length&&(p[D]===f[S]||p[D]==="*"))p[D]==="*"?(E=D,y=S,D++):(S++,D++);else if(E!==-1)D=E+1,y++,S=y;else return!1;for(;D<p.length&&p[D]==="*";)D++;return D===p.length}function u(){let f=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),f}function c(f){for(let p of r.skips)if(i(f,p))return!1;for(let p of r.names)if(i(f,p))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}mh.exports=mb});var gh=J((st,Ko)=>{st.formatArgs=yb;st.save=_b;st.load=bb;st.useColors=gb;st.storage=Cb();st.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();st.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 gb(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function yb(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Ko.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(r++,s==="%c"&&(n=r))}),t.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function _b(t){try{t?st.storage.setItem("debug",t):st.storage.removeItem("debug")}catch{}}function bb(){let t;try{t=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Cb(){try{return localStorage}catch{}}Ko.exports=Nu()(st);var{formatters:wb}=Ko.exports;wb.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var _h=J((mv,yh)=>{"use strict";yh.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var wh=J((gv,Ch)=>{"use strict";var Eb=Q("os"),bh=Q("tty"),Et=_h(),{env:He}=process,Nr;Et("no-color")||Et("no-colors")||Et("color=false")||Et("color=never")?Nr=0:(Et("color")||Et("colors")||Et("color=true")||Et("color=always"))&&(Nr=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?Nr=1:He.FORCE_COLOR==="false"?Nr=0:Nr=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function Bu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function ju(t,e){if(Nr===0)return 0;if(Et("color=16m")||Et("color=full")||Et("color=truecolor"))return 3;if(Et("color=256"))return 2;if(t&&!e&&Nr===void 0)return 0;let r=Nr||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=Eb.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in He)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in He)||He.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in He)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(He.TEAMCITY_VERSION)?1:0;if(He.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in He){let n=parseInt((He.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(He.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(He.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(He.TERM)||"COLORTERM"in He?1:r}function Ab(t){let e=ju(t,t&&t.isTTY);return Bu(e)}Ch.exports={supportsColor:Ab,stdout:Bu(ju(!0,bh.isatty(1))),stderr:Bu(ju(!0,bh.isatty(2)))}});var Ah=J((We,Xo)=>{var Sb=Q("tty"),Yo=Q("util");We.init=Fb;We.log=vb;We.formatArgs=Tb;We.save=Rb;We.load=Ob;We.useColors=kb;We.destroy=Yo.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");We.colors=[6,2,3,4,5,1];try{let t=wh();t&&(t.stderr||t).level>=2&&(We.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{}We.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function kb(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:Sb.isatty(process.stderr.fd)}function Tb(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;t[0]=i+t[0].split(`
8
+ `&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ie(H());case void 0:throw Ie(H())}return H()}function L_(){let t="",e=mr();if(!$e.isHexDigit(e)||(t+=H(),e=mr(),!$e.isHexDigit(e)))throw Ie(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function Cu(){let t="",e=4;for(;e-- >0;){let r=mr();if(!$e.isHexDigit(r))throw Ie(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var M_={start(){if(ze.type==="eof")throw rn();yu()},beforePropertyName(){switch(ze.type){case"identifier":case"string":wu=ze.value,Ze="afterPropertyName";return;case"punctuator":No();return;case"eof":throw rn()}},afterPropertyName(){if(ze.type==="eof")throw rn();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw rn();yu()},beforeArrayValue(){if(ze.type==="eof")throw rn();if(ze.type==="punctuator"&&ze.value==="]"){No();return}yu()},afterPropertyValue(){if(ze.type==="eof")throw rn();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":No()}},afterArrayValue(){if(ze.type==="eof")throw rn();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":No()}},end(){}};function yu(){let t;switch(ze.type){case"punctuator":switch(ze.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=ze.value;break}if(bs===void 0)bs=t;else{let e=pr[pr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,wu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")pr.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=pr[pr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function No(){pr.pop();let t=pr[pr.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Ie(t){return jo(t===void 0?`JSON5: invalid end of input at ${Ir}:${Nt}`:`JSON5: invalid character '${xf(t)}' at ${Ir}:${Nt}`)}function rn(){return jo(`JSON5: invalid end of input at ${Ir}:${Nt}`)}function Of(){return Nt-=5,jo(`JSON5: invalid identifier character at ${Ir}:${Nt}`)}function U_(t){console.warn(`JSON5: '${xf(t)}' in strings is not valid ECMAScript; consider escaping`)}function xf(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let r=t.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return t}function jo(t){let e=new SyntaxError(t);return e.lineNumber=Ir,e.columnNumber=Nt,e}});var Bf=V((kD,Nf)=>{var Eu=gu();Nf.exports=function(e,r,n){let s=[],i="",u,c,l="",h;if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&(n=r.space,h=r.quote,r=r.replacer),typeof r=="function")c=r;else if(Array.isArray(r)){u=[];for(let y of r){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&u.indexOf(g)<0&&u.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),f("",{"":e});function f(y,g){let m=g[y];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(y):typeof m.toJSON=="function"&&(m=m.toJSON(y))),c&&(m=c.call(g,y,m)),m instanceof Number?m=Number(m):m instanceof String?m=String(m):m instanceof Boolean&&(m=m.valueOf()),m){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof m=="string")return p(m,!1);if(typeof m=="number")return String(m);if(typeof m=="object")return Array.isArray(m)?S(m):A(m)}function p(y){let g={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},k="";for(let E=0;E<y.length;E++){let R=y[E];switch(R){case"'":case'"':g[R]++,k+=R;continue;case"\0":if(Eu.isDigit(y[E+1])){k+="\\x00";continue}}if(m[R]){k+=m[R];continue}if(R<" "){let x=R.charCodeAt(0).toString(16);k+="\\x"+("00"+x).substring(x.length);continue}k+=R}let b=h||Object.keys(g).reduce((E,R)=>g[E]<g[R]?E:R);return k=k.replace(new RegExp(b,"g"),m[b]),b+k+b}function A(y){if(s.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");s.push(y);let g=i;i=i+l;let m=u||Object.keys(y),k=[];for(let E of m){let R=f(E,y);if(R!==void 0){let x=v(E)+":";l!==""&&(x+=" "),x+=R,k.push(x)}}let b;if(k.length===0)b="{}";else{let E;if(l==="")E=k.join(","),b="{"+E+"}";else{let R=`,
9
+ `+i;E=k.join(R),b=`{
10
+ `+i+E+`,
11
+ `+g+"}"}}return s.pop(),i=g,b}function v(y){if(y.length===0)return p(y,!0);let g=String.fromCodePoint(y.codePointAt(0));if(!Eu.isIdStartChar(g))return p(y,!0);for(let m=g.length;m<y.length;m++)if(!Eu.isIdContinueChar(String.fromCodePoint(y.codePointAt(m))))return p(y,!0);return y}function S(y){if(s.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");s.push(y);let g=i;i=i+l;let m=[];for(let b=0;b<y.length;b++){let E=f(String(b),y);m.push(E!==void 0?E:"null")}let k;if(m.length===0)k="[]";else if(l==="")k="["+m.join(",")+"]";else{let b=`,
12
+ `+i,E=m.join(b);k=`[
13
+ `+i+E+`,
14
+ `+g+"]"}return s.pop(),i=g,k}}});var Au=V((TD,jf)=>{var q_=If(),$_=Bf(),z_={parse:q_,stringify:$_};jf.exports=z_});var vu=V((cv,sh)=>{"use strict";var Go=Object.prototype.hasOwnProperty,nh=Object.prototype.toString,Xf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,Zf=function(e){return typeof Array.isArray=="function"?Array.isArray(e):nh.call(e)==="[object Array]"},eh=function(e){if(!e||nh.call(e)!=="[object Object]")return!1;var r=Go.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Go.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var s;for(s in e);return typeof s>"u"||Go.call(e,s)},th=function(e,r){Xf&&r.name==="__proto__"?Xf(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},rh=function(e,r){if(r==="__proto__")if(Go.call(e,r)){if(Qf)return Qf(e,r).value}else return;return e[r]};sh.exports=function t(){var e,r,n,s,i,u,c=arguments[0],l=1,h=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<h;++l)if(e=arguments[l],e!=null)for(r in e)n=rh(c,r),s=rh(e,r),c!==s&&(f&&s&&(eh(s)||(i=Zf(s)))?(i?(i=!1,u=n&&Zf(n)?n:[]):u=n&&eh(n)?n:{},th(c,{name:r,newValue:t(f,u,s)})):typeof s<"u"&&th(c,{name:r,newValue:s}));return c}});var oh=V((lv,sb)=>{sb.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",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:"jsdoc -c .jsdoc.js","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"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.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-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var ah=V((dv,ih)=>{"use strict";var ob=oh();ih.exports={pkg:ob}});var Fu=V(wt=>{"use strict";var ch=wt&&wt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wt,"__esModule",{value:!0});wt.GaxiosError=wt.GAXIOS_ERROR_SYMBOL=void 0;wt.defaultErrorRedactor=lh;var uh=ch(vu()),ib=ch(ah()),Ru=ib.default.pkg;wt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ru.name}-gaxios-error`);var Ou=class t extends Error{config;response;code;status;error;[wt.GAXIOS_ERROR_SYMBOL]=Ru.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&wt.GAXIOS_ERROR_SYMBOL in e&&e[wt.GAXIOS_ERROR_SYMBOL]===Ru.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,s){if(super(e,{cause:s}),this.config=r,this.response=n,this.error=s instanceof Error?s:void 0,this.config=(0,uh.default)(!0,{},r),this.response&&(this.response.config=(0,uh.default)(!0,{},this.response.config)),this.response){try{this.response.data=ab(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}s instanceof DOMException?this.code=s.name:s&&typeof s=="object"&&"code"in s&&(typeof s.code=="string"||typeof s.code=="number")&&(this.code=s.code)}static extractAPIErrorFromResponse(e,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let s="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,i="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let u=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&u.push(c.message);return Object.assign({message:u.join(`
15
+ `)||n,code:i,status:s},e.data.error)}return Object.assign({message:n,code:i,status:s},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};wt.GaxiosError=Ou;function ab(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function lh(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(i){i&&i.forEach((u,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&i.set(c,e)})}function n(i,u){if(typeof i=="object"&&i!==null&&typeof i[u]=="string"){let c=i[u];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(i[u]=e)}}function s(i){!i||typeof i!="object"||(i instanceof FormData||i instanceof URLSearchParams||"forEach"in i&&"set"in i?i.forEach((u,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&i.set(c,e)}):("grant_type"in i&&(i.grant_type=e),"assertion"in i&&(i.assertion=e),"client_secret"in i&&(i.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),s(t.config.data),n(t.config,"body"),s(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(lh({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),s(t.response.data))),t}});var fh=V(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.getRetryConfig=ub;async function ub(t){let e=dh(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||cb)(t))return{shouldRetry:!1,config:t.config};let s=lb(e);t.config.retryConfig.currentRetryAttempt+=1;let i=e.retryBackoff?e.retryBackoff(t,s):new Promise(u=>{setTimeout(u,s)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await i,{shouldRetry:!0,config:t.config}}function cb(t){let e=dh(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,s]of e.statusCodesToRetry){let i=t.response.status;if(i>=n&&i<=s){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function dh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function lb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var Iu=V(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.GaxiosInterceptorManager=void 0;var Pu=class extends Set{};Jo.GaxiosInterceptorManager=Pu});var ph=V((mv,hh)=>{var Fn=1e3,xn=Fn*60,Pn=xn*60,nn=Pn*24,db=nn*7,fb=nn*365.25;hh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return hb(t);if(r==="number"&&isFinite(t))return e.long?mb(t):pb(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function hb(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*fb;case"weeks":case"week":case"w":return r*db;case"days":case"day":case"d":return r*nn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pn;case"minutes":case"minute":case"mins":case"min":case"m":return r*xn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Fn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function pb(t){var e=Math.abs(t);return e>=nn?Math.round(t/nn)+"d":e>=Pn?Math.round(t/Pn)+"h":e>=xn?Math.round(t/xn)+"m":e>=Fn?Math.round(t/Fn)+"s":t+"ms"}function mb(t){var e=Math.abs(t);return e>=nn?Vo(t,e,nn,"day"):e>=Pn?Vo(t,e,Pn,"hour"):e>=xn?Vo(t,e,xn,"minute"):e>=Fn?Vo(t,e,Fn,"second"):t+" ms"}function Vo(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var Nu=V((gv,mh)=>{function gb(t){r.debug=r,r.default=r,r.coerce=l,r.disable=u,r.enable=s,r.enabled=c,r.humanize=ph(),r.destroy=h,Object.keys(t).forEach(f=>{r[f]=t[f]}),r.names=[],r.skips=[],r.formatters={};function e(f){let p=0;for(let A=0;A<f.length;A++)p=(p<<5)-p+f.charCodeAt(A),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(f){let p,A=null,v,S;function y(...g){if(!y.enabled)return;let m=y,k=Number(new Date),b=k-(p||k);m.diff=b,m.prev=p,m.curr=k,p=k,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let E=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(x,$)=>{if(x==="%%")return"%";E++;let J=r.formatters[$];if(typeof J=="function"){let M=g[E];x=J.call(m,M),g.splice(E,1),E--}return x}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return y.namespace=f,y.useColors=r.useColors(),y.color=r.selectColor(f),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>A!==null?A:(v!==r.namespaces&&(v=r.namespaces,S=r.enabled(f)),S),set:g=>{A=g}}),typeof r.init=="function"&&r.init(y),y}function n(f,p){let A=r(this.namespace+(typeof p>"u"?":":p)+f);return A.log=this.log,A}function s(f){r.save(f),r.namespaces=f,r.names=[],r.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let A of p)A[0]==="-"?r.skips.push(A.slice(1)):r.names.push(A)}function i(f,p){let A=0,v=0,S=-1,y=0;for(;A<f.length;)if(v<p.length&&(p[v]===f[A]||p[v]==="*"))p[v]==="*"?(S=v,y=A,v++):(A++,v++);else if(S!==-1)v=S+1,y++,A=y;else return!1;for(;v<p.length&&p[v]==="*";)v++;return v===p.length}function u(){let f=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),f}function c(f){for(let p of r.skips)if(i(f,p))return!1;for(let p of r.names)if(i(f,p))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}mh.exports=gb});var gh=V((st,Ko)=>{st.formatArgs=_b;st.save=bb;st.load=Cb;st.useColors=yb;st.storage=wb();st.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();st.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 yb(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function _b(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Ko.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(r++,s==="%c"&&(n=r))}),t.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function bb(t){try{t?st.storage.setItem("debug",t):st.storage.removeItem("debug")}catch{}}function Cb(){let t;try{t=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function wb(){try{return localStorage}catch{}}Ko.exports=Nu()(st);var{formatters:Eb}=Ko.exports;Eb.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var _h=V((yv,yh)=>{"use strict";yh.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var wh=V((_v,Ch)=>{"use strict";var Ab=Q("os"),bh=Q("tty"),Et=_h(),{env:He}=process,Nr;Et("no-color")||Et("no-colors")||Et("color=false")||Et("color=never")?Nr=0:(Et("color")||Et("colors")||Et("color=true")||Et("color=always"))&&(Nr=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?Nr=1:He.FORCE_COLOR==="false"?Nr=0:Nr=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function Bu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function ju(t,e){if(Nr===0)return 0;if(Et("color=16m")||Et("color=full")||Et("color=truecolor"))return 3;if(Et("color=256"))return 2;if(t&&!e&&Nr===void 0)return 0;let r=Nr||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=Ab.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in He)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in He)||He.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in He)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(He.TEAMCITY_VERSION)?1:0;if(He.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in He){let n=parseInt((He.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(He.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(He.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(He.TERM)||"COLORTERM"in He?1:r}function Sb(t){let e=ju(t,t&&t.isTTY);return Bu(e)}Ch.exports={supportsColor:Sb,stdout:Bu(ju(!0,bh.isatty(1))),stderr:Bu(ju(!0,bh.isatty(2)))}});var Ah=V((We,Xo)=>{var kb=Q("tty"),Yo=Q("util");We.init=xb;We.log=Rb;We.formatArgs=Db;We.save=Ob;We.load=Fb;We.useColors=Tb;We.destroy=Yo.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");We.colors=[6,2,3,4,5,1];try{let t=wh();t&&(t.stderr||t).level>=2&&(We.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{}We.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function Tb(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:kb.isatty(process.stderr.fd)}function Db(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;t[0]=i+t[0].split(`
16
16
  `).join(`
17
- `+i),t.push(s+"m+"+Xo.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Db()+e+" "+t[0]}function Db(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function vb(...t){return process.stderr.write(Yo.formatWithOptions(We.inspectOpts,...t)+`
18
- `)}function Rb(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Ob(){return process.env.DEBUG}function Fb(t){t.inspectOpts={};let e=Object.keys(We.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=We.inspectOpts[e[r]]}Xo.exports=Nu()(We);var{formatters:Eh}=Xo.exports;Eh.o=function(t){return this.inspectOpts.colors=this.useColors,Yo.inspect(t,this.inspectOpts).split(`
19
- `).map(e=>e.trim()).join(" ")};Eh.O=function(t){return this.inspectOpts.colors=this.useColors,Yo.inspect(t,this.inspectOpts)}});var Mu=J((yv,Lu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Lu.exports=gh():Lu.exports=Ah()});var Th=J(ot=>{"use strict";var xb=ot&&ot.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Pb=ot&&ot.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Sh=ot&&ot.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&xb(e,t,r);return Pb(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var Ib=Sh(Q("http")),Nb=Sh(Q("https"));async function kh(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}ot.toBuffer=kh;async function Bb(t){let r=(await kh(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let s=n;throw s.message+=` (input: ${r})`,s}}ot.json=Bb;function jb(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?Nb:Ib).request(t,e),s=new Promise((i,u)=>{n.once("response",i).once("error",u).end()});return n.then=s.then.bind(s),n}ot.req=jb});var Oh=J(lt=>{"use strict";var vh=lt&&lt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Lb=lt&&lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Rh=lt&&lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vh(e,t,r);return Lb(e,t),e},Mb=lt&&lt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&vh(e,t,r)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var Ub=Rh(Q("net")),Dh=Rh(Q("http")),qb=Q("https");Mb(Th(),lt);var Jt=Symbol("AgentBaseInternalState"),Uu=class extends Dh.Agent{constructor(e){super(e),this[Jt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
20
- `).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let r=new Ub.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let n=this.sockets[e],s=n.indexOf(r);s!==-1&&(n.splice(s,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?qb.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let s={...r,secureEndpoint:this.isSecureEndpoint(r)},i=this.getName(s),u=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,s)).then(c=>{if(this.decrementSockets(i,u),c instanceof Dh.Agent)try{return c.addRequest(e,s)}catch(l){return n(l)}this[Jt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(i,u),n(c)})}createConnection(){let e=this[Jt].currentSocket;if(this[Jt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Jt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Jt]&&(this[Jt].defaultPort=e)}get protocol(){return this[Jt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Jt]&&(this[Jt].protocol=e)}};lt.Agent=Uu});var Fh=J(In=>{"use strict";var $b=In&&In.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(In,"__esModule",{value:!0});In.parseProxyResponse=void 0;var zb=$b(Mu()),Qo=(0,zb.default)("https-proxy-agent:parse-proxy-response");function Hb(t){return new Promise((e,r)=>{let n=0,s=[];function i(){let f=t.read();f?h(f):t.once("readable",i)}function u(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",i)}function c(){u(),Qo("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(f){u(),Qo("onerror %o",f),r(f)}function h(f){s.push(f),n+=f.length;let p=Buffer.concat(s,n),S=p.indexOf(`\r
17
+ `+i),t.push(s+"m+"+Xo.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=vb()+e+" "+t[0]}function vb(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Rb(...t){return process.stderr.write(Yo.formatWithOptions(We.inspectOpts,...t)+`
18
+ `)}function Ob(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Fb(){return process.env.DEBUG}function xb(t){t.inspectOpts={};let e=Object.keys(We.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=We.inspectOpts[e[r]]}Xo.exports=Nu()(We);var{formatters:Eh}=Xo.exports;Eh.o=function(t){return this.inspectOpts.colors=this.useColors,Yo.inspect(t,this.inspectOpts).split(`
19
+ `).map(e=>e.trim()).join(" ")};Eh.O=function(t){return this.inspectOpts.colors=this.useColors,Yo.inspect(t,this.inspectOpts)}});var Mu=V((bv,Lu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Lu.exports=gh():Lu.exports=Ah()});var Th=V(ot=>{"use strict";var Pb=ot&&ot.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Ib=ot&&ot.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Sh=ot&&ot.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Pb(e,t,r);return Ib(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var Nb=Sh(Q("http")),Bb=Sh(Q("https"));async function kh(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}ot.toBuffer=kh;async function jb(t){let r=(await kh(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let s=n;throw s.message+=` (input: ${r})`,s}}ot.json=jb;function Lb(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?Bb:Nb).request(t,e),s=new Promise((i,u)=>{n.once("response",i).once("error",u).end()});return n.then=s.then.bind(s),n}ot.req=Lb});var Oh=V(lt=>{"use strict";var vh=lt&&lt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Mb=lt&&lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Rh=lt&&lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vh(e,t,r);return Mb(e,t),e},Ub=lt&&lt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&vh(e,t,r)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var qb=Rh(Q("net")),Dh=Rh(Q("http")),$b=Q("https");Ub(Th(),lt);var Jt=Symbol("AgentBaseInternalState"),Uu=class extends Dh.Agent{constructor(e){super(e),this[Jt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
20
+ `).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let r=new qb.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let n=this.sockets[e],s=n.indexOf(r);s!==-1&&(n.splice(s,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?$b.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let s={...r,secureEndpoint:this.isSecureEndpoint(r)},i=this.getName(s),u=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,s)).then(c=>{if(this.decrementSockets(i,u),c instanceof Dh.Agent)try{return c.addRequest(e,s)}catch(l){return n(l)}this[Jt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(i,u),n(c)})}createConnection(){let e=this[Jt].currentSocket;if(this[Jt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Jt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Jt]&&(this[Jt].defaultPort=e)}get protocol(){return this[Jt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Jt]&&(this[Jt].protocol=e)}};lt.Agent=Uu});var Fh=V(In=>{"use strict";var zb=In&&In.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(In,"__esModule",{value:!0});In.parseProxyResponse=void 0;var Hb=zb(Mu()),Qo=(0,Hb.default)("https-proxy-agent:parse-proxy-response");function Wb(t){return new Promise((e,r)=>{let n=0,s=[];function i(){let f=t.read();f?h(f):t.once("readable",i)}function u(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",i)}function c(){u(),Qo("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(f){u(),Qo("onerror %o",f),r(f)}function h(f){s.push(f),n+=f.length;let p=Buffer.concat(s,n),A=p.indexOf(`\r
21
21
  \r
22
- `);if(S===-1){Qo("have not received end of HTTP headers yet..."),i();return}let D=p.slice(0,S).toString("ascii").split(`\r
23
- `),E=D.shift();if(!E)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let y=E.split(" "),g=+y[1],m=y.slice(2).join(" "),T={};for(let b of D){if(!b)continue;let w=b.indexOf(":");if(w===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${b}"`));let O=b.slice(0,w).toLowerCase(),x=b.slice(w+1).trimStart(),$=T[O];typeof $=="string"?T[O]=[$,x]:Array.isArray($)?$.push(x):T[O]=x}Qo("got proxy server response: %o %o",E,T),u(),e({connect:{statusCode:g,statusText:m,headers:T},buffered:p})}t.on("error",l),t.on("end",c),i()})}In.parseProxyResponse=Hb});var jh=J(At=>{"use strict";var Wb=At&&At.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Gb=At&&At.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Nh=At&&At.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wb(e,t,r);return Gb(e,t),e},Bh=At&&At.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(At,"__esModule",{value:!0});At.HttpsProxyAgent=void 0;var Zo=Nh(Q("net")),xh=Nh(Q("tls")),Jb=Bh(Q("assert")),Vb=Bh(Mu()),Kb=Oh(),Yb=Q("url"),Xb=Fh(),ws=(0,Vb.default)("https-proxy-agent"),Ph=t=>t.servername===void 0&&t.host&&!Zo.isIP(t.host)?{...t,servername:t.host}:t,ei=class extends Kb.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new Yb.URL(e):e,this.proxyHeaders=r?.headers??{},ws("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),s=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...r?Ih(r,"headers"):null,host:n,port:s}}async connect(e,r){let{proxy:n}=this;if(!r.host)throw new TypeError('No "host" provided');let s;n.protocol==="https:"?(ws("Creating `tls.Socket`: %o",this.connectOpts),s=xh.connect(Ph(this.connectOpts))):(ws("Creating `net.Socket`: %o",this.connectOpts),s=Zo.connect(this.connectOpts));let i=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=Zo.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${u}:${r.port} HTTP/1.1\r
24
- `;if(n.username||n.password){let S=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(S).toString("base64")}`}i.Host=`${u}:${r.port}`,i["Proxy-Connection"]||(i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let S of Object.keys(i))c+=`${S}: ${i[S]}\r
25
- `;let l=(0,Xb.parseProxyResponse)(s);s.write(`${c}\r
26
- `);let{connect:h,buffered:f}=await l;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",Qb),r.secureEndpoint?(ws("Upgrading socket connection to TLS"),xh.connect({...Ih(Ph(r),"host","path","port"),socket:s})):s;s.destroy();let p=new Zo.Socket({writable:!1});return p.readable=!0,e.once("socket",S=>{ws("Replaying proxy buffer for failed request"),(0,Jb.default)(S.listenerCount("data")>0),S.push(f),S.push(null)}),p}};ei.protocols=["http","https"];At.HttpsProxyAgent=ei;function Qb(t){t.resume()}function Ih(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function Zb(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let r=t.substring(5,e).split(";"),n="",s=!1,i=r[0]||"text/plain",u=i;for(let f=1;f<r.length;f++)r[f]==="base64"?s=!0:r[f]&&(u+=`;${r[f]}`,r[f].indexOf("charset=")===0&&(n=r[f].substring(8)));!r[0]&&!n.length&&(u+=";charset=US-ASCII",n="US-ASCII");let c=s?"base64":"ascii",l=unescape(t.substring(e+1)),h=Buffer.from(l,c);return h.type=i,h.typeFull=u,h.charset=n,h}var Lh,Mh=je(()=>{Lh=Zb});var qh=J((ti,Uh)=>{(function(t,e){typeof ti=="object"&&typeof Uh<"u"?e(ti):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(ti,(function(t){"use strict";function e(){}function r(o){return typeof o=="object"&&o!==null||typeof o=="function"}let n=e;function s(o,a){try{Object.defineProperty(o,"name",{value:a,configurable:!0})}catch{}}let i=Promise,u=Promise.prototype.then,c=Promise.reject.bind(i);function l(o){return new i(o)}function h(o){return l(a=>a(o))}function f(o){return c(o)}function p(o,a,d){return u.call(o,a,d)}function S(o,a,d){p(p(o,a,d),void 0,n)}function D(o,a){S(o,a)}function E(o,a){S(o,void 0,a)}function y(o,a,d){return p(o,a,d)}function g(o){p(o,void 0,n)}let m=o=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let a=h(void 0);m=d=>p(a,d)}return m(o)};function T(o,a,d){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,a,d)}function b(o,a,d){try{return h(T(o,a,d))}catch(C){return f(C)}}let w=16384;class O{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(a){let d=this._back,C=d;d._elements.length===w-1&&(C={_elements:[],_next:void 0}),d._elements.push(a),C!==d&&(this._back=C,d._next=C),++this._size}shift(){let a=this._front,d=a,C=this._cursor,v=C+1,L=a._elements,q=L[C];return v===w&&(d=a._next,v=0),--this._size,this._cursor=v,a!==d&&(this._front=d),L[C]=void 0,q}forEach(a){let d=this._cursor,C=this._front,v=C._elements;for(;(d!==v.length||C._next!==void 0)&&!(d===v.length&&(C=C._next,v=C._elements,d=0,v.length===0));)a(v[d]),++d}peek(){let a=this._front,d=this._cursor;return a._elements[d]}}let x=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),V=Symbol("[[CancelSteps]]"),U=Symbol("[[PullSteps]]"),X=Symbol("[[ReleaseSteps]]");function ne(o,a){o._ownerReadableStream=a,a._reader=o,a._state==="readable"?Ae(o):a._state==="closed"?pe(o):oe(o,a._storedError)}function ae(o,a){let d=o._ownerReadableStream;return Pt(d,a)}function de(o){let a=o._ownerReadableStream;a._state==="readable"?G(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),a._readableStreamController[X](),a._reader=void 0,o._ownerReadableStream=void 0}function ye(o){return new TypeError("Cannot "+o+" a stream using a released reader")}function Ae(o){o._closedPromise=l((a,d)=>{o._closedPromise_resolve=a,o._closedPromise_reject=d})}function oe(o,a){Ae(o),G(o,a)}function pe(o){Ae(o),ue(o)}function G(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function K(o,a){oe(o,a)}function ue(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let qe=Number.isFinite||function(o){return typeof o=="number"&&isFinite(o)},De=Math.trunc||function(o){return o<0?Math.ceil(o):Math.floor(o)};function W(o){return typeof o=="object"||typeof o=="function"}function le(o,a){if(o!==void 0&&!W(o))throw new TypeError(`${a} is not an object.`)}function _e(o,a){if(typeof o!="function")throw new TypeError(`${a} is not a function.`)}function Ft(o){return typeof o=="object"&&o!==null||typeof o=="function"}function Re(o,a){if(!Ft(o))throw new TypeError(`${a} is not an object.`)}function Be(o,a,d){if(o===void 0)throw new TypeError(`Parameter ${a} is required in '${d}'.`)}function _(o,a,d){if(o===void 0)throw new TypeError(`${a} is required in '${d}'.`)}function A(o){return Number(o)}function k(o){return o===0?0:o}function B(o){return k(De(o))}function F(o,a){let C=Number.MAX_SAFE_INTEGER,v=Number(o);if(v=k(v),!qe(v))throw new TypeError(`${a} is not a finite number`);if(v=B(v),v<0||v>C)throw new TypeError(`${a} is outside the accepted range of 0 to ${C}, inclusive`);return!qe(v)||v===0?0:v}function I(o,a){if(!Rr(o))throw new TypeError(`${a} is not a ReadableStream.`)}function M(o){return new z(o)}function R(o,a){o._reader._readRequests.push(a)}function P(o,a,d){let v=o._reader._readRequests.shift();d?v._closeSteps():v._chunkSteps(a)}function j(o){return o._reader._readRequests.length}function N(o){let a=o._reader;return!(a===void 0||!Z(a))}class z{constructor(a){if(Be(a,1,"ReadableStreamDefaultReader"),I(a,"First parameter"),Or(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ne(this,a),this._readRequests=new O}get closed(){return Z(this)?this._closedPromise:f(Ne("closed"))}cancel(a=void 0){return Z(this)?this._ownerReadableStream===void 0?f(ye("cancel")):ae(this,a):f(Ne("cancel"))}read(){if(!Z(this))return f(Ne("read"));if(this._ownerReadableStream===void 0)return f(ye("read from"));let a,d,C=l((L,q)=>{a=L,d=q});return ee(this,{_chunkSteps:L=>a({value:L,done:!1}),_closeSteps:()=>a({value:void 0,done:!0}),_errorSteps:L=>d(L)}),C}releaseLock(){if(!Z(this))throw Ne("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(z.prototype.cancel,"cancel"),s(z.prototype.read,"read"),s(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Z(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readRequests")?!1:o instanceof z}function ee(o,a){let d=o._ownerReadableStream;d._disturbed=!0,d._state==="closed"?a._closeSteps():d._state==="errored"?a._errorSteps(d._storedError):d._readableStreamController[U](a)}function Ee(o){de(o);let a=new TypeError("Reader was released");xe(o,a)}function xe(o,a){let d=o._readRequests;o._readRequests=new O,d.forEach(C=>{C._errorSteps(a)})}function Ne(o){return new TypeError(`ReadableStreamDefaultReader.prototype.${o} can only be used on a ReadableStreamDefaultReader`)}let we=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(a,d){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=a,this._preventCancel=d}next(){let a=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,a,a):a(),this._ongoingPromise}return(a){let d=()=>this._returnSteps(a);return this._ongoingPromise?y(this._ongoingPromise,d,d):d()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let a=this._reader,d,C,v=l((q,Y)=>{d=q,C=Y});return ee(a,{_chunkSteps:q=>{this._ongoingPromise=void 0,m(()=>d({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,de(a),d({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,de(a),C(q)}}),v}_returnSteps(a){if(this._isFinished)return Promise.resolve({value:a,done:!0});this._isFinished=!0;let d=this._reader;if(!this._preventCancel){let C=ae(d,a);return de(d),y(C,()=>({value:a,done:!0}))}return de(d),h({value:a,done:!0})}}let Me={next(){return pn(this)?this._asyncIteratorImpl.next():f(mn("next"))},return(o){return pn(this)?this._asyncIteratorImpl.return(o):f(mn("return"))}};Object.setPrototypeOf(Me,we);function hn(o,a){let d=M(o),C=new Se(d,a),v=Object.create(Me);return v._asyncIteratorImpl=C,v}function pn(o){if(!r(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof Se}catch{return!1}}function mn(o){return new TypeError(`ReadableStreamAsyncIterator.${o} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(o){return o!==o};var ir,Ke,Ue;function ke(o){return o.slice()}function Sd(o,a,d,C,v){new Uint8Array(o).set(new Uint8Array(d,C,v),a)}let ar=o=>(typeof o.transfer=="function"?ar=a=>a.transfer():typeof structuredClone=="function"?ar=a=>structuredClone(a,{transfer:[a]}):ar=a=>a,ar(o)),kr=o=>(typeof o.detached=="boolean"?kr=a=>a.detached:kr=a=>a.byteLength===0,kr(o));function kd(o,a,d){if(o.slice)return o.slice(a,d);let C=d-a,v=new ArrayBuffer(C);return Sd(v,0,o,a,C),v}function io(o,a){let d=o[a];if(d!=null){if(typeof d!="function")throw new TypeError(`${String(a)} is not a function`);return d}}function Vy(o){let a={[Symbol.iterator]:()=>o.iterator},d=(async function*(){return yield*a})(),C=d.next;return{iterator:d,nextMethod:C,done:!1}}let qa=(Ue=(ir=Symbol.asyncIterator)!==null&&ir!==void 0?ir:(Ke=Symbol.for)===null||Ke===void 0?void 0:Ke.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function Td(o,a="sync",d){if(d===void 0)if(a==="async"){if(d=io(o,qa),d===void 0){let L=io(o,Symbol.iterator),q=Td(o,"sync",L);return Vy(q)}}else d=io(o,Symbol.iterator);if(d===void 0)throw new TypeError("The object is not iterable");let C=T(d,o,[]);if(!r(C))throw new TypeError("The iterator method must return an object");let v=C.next;return{iterator:C,nextMethod:v,done:!1}}function Ky(o){let a=T(o.nextMethod,o.iterator,[]);if(!r(a))throw new TypeError("The iterator.next() method must return an object");return a}function Yy(o){return!!o.done}function Xy(o){return o.value}function Qy(o){return!(typeof o!="number"||ut(o)||o<0)}function Dd(o){let a=kd(o.buffer,o.byteOffset,o.byteOffset+o.byteLength);return new Uint8Array(a)}function $a(o){let a=o._queue.shift();return o._queueTotalSize-=a.size,o._queueTotalSize<0&&(o._queueTotalSize=0),a.value}function za(o,a,d){if(!Qy(d)||d===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");o._queue.push({value:a,size:d}),o._queueTotalSize+=d}function Zy(o){return o._queue.peek().value}function Tr(o){o._queue=new O,o._queueTotalSize=0}function vd(o){return o===DataView}function e0(o){return vd(o.constructor)}function t0(o){return vd(o)?1:o.BYTES_PER_ELEMENT}class Jr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ha(this))throw Ka("view");return this._view}respond(a){if(!Ha(this))throw Ka("respond");if(Be(a,1,"respond"),a=F(a,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(kr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");lo(this._associatedReadableByteStreamController,a)}respondWithNewView(a){if(!Ha(this))throw Ka("respondWithNewView");if(Be(a,1,"respondWithNewView"),!ArrayBuffer.isView(a))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(kr(a.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");fo(this._associatedReadableByteStreamController,a)}}Object.defineProperties(Jr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(Jr.prototype.respond,"respond"),s(Jr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Jr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ur{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Vr(this))throw ds("byobRequest");return Va(this)}get desiredSize(){if(!Vr(this))throw ds("desiredSize");return Ld(this)}close(){if(!Vr(this))throw ds("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let a=this._controlledReadableByteStream._state;if(a!=="readable")throw new TypeError(`The stream (in ${a} state) is not in the readable state and cannot be closed`);ls(this)}enqueue(a){if(!Vr(this))throw ds("enqueue");if(Be(a,1,"enqueue"),!ArrayBuffer.isView(a))throw new TypeError("chunk must be an array buffer view");if(a.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(a.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let d=this._controlledReadableByteStream._state;if(d!=="readable")throw new TypeError(`The stream (in ${d} state) is not in the readable state and cannot be enqueued to`);co(this,a)}error(a=void 0){if(!Vr(this))throw ds("error");bt(this,a)}[V](a){Rd(this),Tr(this);let d=this._cancelAlgorithm(a);return uo(this),d}[U](a){let d=this._controlledReadableByteStream;if(this._queueTotalSize>0){jd(this,a);return}let C=this._autoAllocateChunkSize;if(C!==void 0){let v;try{v=new ArrayBuffer(C)}catch(q){a._errorSteps(q);return}let L={buffer:v,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}R(d,a),Kr(this)}[X](){if(this._pendingPullIntos.length>0){let a=this._pendingPullIntos.peek();a.readerType="none",this._pendingPullIntos=new O,this._pendingPullIntos.push(a)}}}Object.defineProperties(ur.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(ur.prototype.close,"close"),s(ur.prototype.enqueue,"enqueue"),s(ur.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ur.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof ur}function Ha(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof Jr}function Kr(o){if(!i0(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let d=o._pullAlgorithm();S(d,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,Kr(o)),null),C=>(bt(o,C),null))}function Rd(o){Ga(o),o._pendingPullIntos=new O}function Wa(o,a){let d=!1;o._state==="closed"&&(d=!0);let C=Od(a);a.readerType==="default"?P(o,C,d):f0(o,C,d)}function Od(o){let a=o.bytesFilled,d=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,a/d)}function ao(o,a,d,C){o._queue.push({buffer:a,byteOffset:d,byteLength:C}),o._queueTotalSize+=C}function Fd(o,a,d,C){let v;try{v=kd(a,d,d+C)}catch(L){throw bt(o,L),L}ao(o,v,0,C)}function xd(o,a){a.bytesFilled>0&&Fd(o,a.buffer,a.byteOffset,a.bytesFilled),gn(o)}function Pd(o,a){let d=Math.min(o._queueTotalSize,a.byteLength-a.bytesFilled),C=a.bytesFilled+d,v=d,L=!1,q=C%a.elementSize,Y=C-q;Y>=a.minimumFill&&(v=Y-a.bytesFilled,L=!0);let ce=o._queue;for(;v>0;){let re=ce.peek(),fe=Math.min(v,re.byteLength),ge=a.byteOffset+a.bytesFilled;Sd(a.buffer,ge,re.buffer,re.byteOffset,fe),re.byteLength===fe?ce.shift():(re.byteOffset+=fe,re.byteLength-=fe),o._queueTotalSize-=fe,Id(o,fe,a),v-=fe}return L}function Id(o,a,d){d.bytesFilled+=a}function Nd(o){o._queueTotalSize===0&&o._closeRequested?(uo(o),ys(o._controlledReadableByteStream)):Kr(o)}function Ga(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function Ja(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let a=o._pendingPullIntos.peek();Pd(o,a)&&(gn(o),Wa(o._controlledReadableByteStream,a))}}function r0(o){let a=o._controlledReadableByteStream._reader;for(;a._readRequests.length>0;){if(o._queueTotalSize===0)return;let d=a._readRequests.shift();jd(o,d)}}function n0(o,a,d,C){let v=o._controlledReadableByteStream,L=a.constructor,q=t0(L),{byteOffset:Y,byteLength:ce}=a,re=d*q,fe;try{fe=ar(a.buffer)}catch(ve){C._errorSteps(ve);return}let ge={buffer:fe,bufferByteLength:fe.byteLength,byteOffset:Y,byteLength:ce,bytesFilled:0,minimumFill:re,elementSize:q,viewConstructor:L,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(ge),qd(v,C);return}if(v._state==="closed"){let ve=new L(ge.buffer,ge.byteOffset,0);C._closeSteps(ve);return}if(o._queueTotalSize>0){if(Pd(o,ge)){let ve=Od(ge);Nd(o),C._chunkSteps(ve);return}if(o._closeRequested){let ve=new TypeError("Insufficient bytes to fill elements in the given buffer");bt(o,ve),C._errorSteps(ve);return}}o._pendingPullIntos.push(ge),qd(v,C),Kr(o)}function s0(o,a){a.readerType==="none"&&gn(o);let d=o._controlledReadableByteStream;if(Ya(d))for(;$d(d)>0;){let C=gn(o);Wa(d,C)}}function o0(o,a,d){if(Id(o,a,d),d.readerType==="none"){xd(o,d),Ja(o);return}if(d.bytesFilled<d.minimumFill)return;gn(o);let C=d.bytesFilled%d.elementSize;if(C>0){let v=d.byteOffset+d.bytesFilled;Fd(o,d.buffer,v-C,C)}d.bytesFilled-=C,Wa(o._controlledReadableByteStream,d),Ja(o)}function Bd(o,a){let d=o._pendingPullIntos.peek();Ga(o),o._controlledReadableByteStream._state==="closed"?s0(o,d):o0(o,a,d),Kr(o)}function gn(o){return o._pendingPullIntos.shift()}function i0(o){let a=o._controlledReadableByteStream;return a._state!=="readable"||o._closeRequested||!o._started?!1:!!(N(a)&&j(a)>0||Ya(a)&&$d(a)>0||Ld(o)>0)}function uo(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function ls(o){let a=o._controlledReadableByteStream;if(!(o._closeRequested||a._state!=="readable")){if(o._queueTotalSize>0){o._closeRequested=!0;return}if(o._pendingPullIntos.length>0){let d=o._pendingPullIntos.peek();if(d.bytesFilled%d.elementSize!==0){let C=new TypeError("Insufficient bytes to fill elements in the given buffer");throw bt(o,C),C}}uo(o),ys(a)}}function co(o,a){let d=o._controlledReadableByteStream;if(o._closeRequested||d._state!=="readable")return;let{buffer:C,byteOffset:v,byteLength:L}=a;if(kr(C))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=ar(C);if(o._pendingPullIntos.length>0){let Y=o._pendingPullIntos.peek();if(kr(Y.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ga(o),Y.buffer=ar(Y.buffer),Y.readerType==="none"&&xd(o,Y)}if(N(d))if(r0(o),j(d)===0)ao(o,q,v,L);else{o._pendingPullIntos.length>0&&gn(o);let Y=new Uint8Array(q,v,L);P(d,Y,!1)}else Ya(d)?(ao(o,q,v,L),Ja(o)):ao(o,q,v,L);Kr(o)}function bt(o,a){let d=o._controlledReadableByteStream;d._state==="readable"&&(Rd(o),Tr(o),uo(o),hf(d,a))}function jd(o,a){let d=o._queue.shift();o._queueTotalSize-=d.byteLength,Nd(o);let C=new Uint8Array(d.buffer,d.byteOffset,d.byteLength);a._chunkSteps(C)}function Va(o){if(o._byobRequest===null&&o._pendingPullIntos.length>0){let a=o._pendingPullIntos.peek(),d=new Uint8Array(a.buffer,a.byteOffset+a.bytesFilled,a.byteLength-a.bytesFilled),C=Object.create(Jr.prototype);u0(C,o,d),o._byobRequest=C}return o._byobRequest}function Ld(o){let a=o._controlledReadableByteStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function lo(o,a){let d=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(a===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(d.bytesFilled+a>d.byteLength)throw new RangeError("bytesWritten out of range")}d.buffer=ar(d.buffer),Bd(o,a)}function fo(o,a){let d=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(a.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(d.byteOffset+d.bytesFilled!==a.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(d.bufferByteLength!==a.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(d.bytesFilled+a.byteLength>d.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let v=a.byteLength;d.buffer=ar(a.buffer),Bd(o,v)}function Md(o,a,d,C,v,L,q){a._controlledReadableByteStream=o,a._pullAgain=!1,a._pulling=!1,a._byobRequest=null,a._queue=a._queueTotalSize=void 0,Tr(a),a._closeRequested=!1,a._started=!1,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=v,a._autoAllocateChunkSize=q,a._pendingPullIntos=new O,o._readableStreamController=a;let Y=d();S(h(Y),()=>(a._started=!0,Kr(a),null),ce=>(bt(a,ce),null))}function a0(o,a,d){let C=Object.create(ur.prototype),v,L,q;a.start!==void 0?v=()=>a.start(C):v=()=>{},a.pull!==void 0?L=()=>a.pull(C):L=()=>h(void 0),a.cancel!==void 0?q=ce=>a.cancel(ce):q=()=>h(void 0);let Y=a.autoAllocateChunkSize;if(Y===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Md(o,C,v,L,q,d,Y)}function u0(o,a,d){o._associatedReadableByteStreamController=a,o._view=d}function Ka(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function ds(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function c0(o,a){le(o,a);let d=o?.mode;return{mode:d===void 0?void 0:l0(d,`${a} has member 'mode' that`)}}function l0(o,a){if(o=`${o}`,o!=="byob")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function d0(o,a){var d;le(o,a);let C=(d=o?.min)!==null&&d!==void 0?d:1;return{min:F(C,`${a} has member 'min' that`)}}function Ud(o){return new Dr(o)}function qd(o,a){o._reader._readIntoRequests.push(a)}function f0(o,a,d){let v=o._reader._readIntoRequests.shift();d?v._closeSteps(a):v._chunkSteps(a)}function $d(o){return o._reader._readIntoRequests.length}function Ya(o){let a=o._reader;return!(a===void 0||!Yr(a))}class Dr{constructor(a){if(Be(a,1,"ReadableStreamBYOBReader"),I(a,"First parameter"),Or(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Vr(a._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ne(this,a),this._readIntoRequests=new O}get closed(){return Yr(this)?this._closedPromise:f(ho("closed"))}cancel(a=void 0){return Yr(this)?this._ownerReadableStream===void 0?f(ye("cancel")):ae(this,a):f(ho("cancel"))}read(a,d={}){if(!Yr(this))return f(ho("read"));if(!ArrayBuffer.isView(a))return f(new TypeError("view must be an array buffer view"));if(a.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(a.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(kr(a.buffer))return f(new TypeError("view's buffer has been detached"));let C;try{C=d0(d,"options")}catch(re){return f(re)}let v=C.min;if(v===0)return f(new TypeError("options.min must be greater than 0"));if(e0(a)){if(v>a.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(v>a.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(ye("read from"));let L,q,Y=l((re,fe)=>{L=re,q=fe});return zd(this,a,v,{_chunkSteps:re=>L({value:re,done:!1}),_closeSteps:re=>L({value:re,done:!0}),_errorSteps:re=>q(re)}),Y}releaseLock(){if(!Yr(this))throw ho("releaseLock");this._ownerReadableStream!==void 0&&h0(this)}}Object.defineProperties(Dr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(Dr.prototype.cancel,"cancel"),s(Dr.prototype.read,"read"),s(Dr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Yr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof Dr}function zd(o,a,d,C){let v=o._ownerReadableStream;v._disturbed=!0,v._state==="errored"?C._errorSteps(v._storedError):n0(v._readableStreamController,a,d,C)}function h0(o){de(o);let a=new TypeError("Reader was released");Hd(o,a)}function Hd(o,a){let d=o._readIntoRequests;o._readIntoRequests=new O,d.forEach(C=>{C._errorSteps(a)})}function ho(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function fs(o,a){let{highWaterMark:d}=o;if(d===void 0)return a;if(ut(d)||d<0)throw new RangeError("Invalid highWaterMark");return d}function po(o){let{size:a}=o;return a||(()=>1)}function mo(o,a){le(o,a);let d=o?.highWaterMark,C=o?.size;return{highWaterMark:d===void 0?void 0:A(d),size:C===void 0?void 0:p0(C,`${a} has member 'size' that`)}}function p0(o,a){return _e(o,a),d=>A(o(d))}function m0(o,a){le(o,a);let d=o?.abort,C=o?.close,v=o?.start,L=o?.type,q=o?.write;return{abort:d===void 0?void 0:g0(d,o,`${a} has member 'abort' that`),close:C===void 0?void 0:y0(C,o,`${a} has member 'close' that`),start:v===void 0?void 0:_0(v,o,`${a} has member 'start' that`),write:q===void 0?void 0:b0(q,o,`${a} has member 'write' that`),type:L}}function g0(o,a,d){return _e(o,d),C=>b(o,a,[C])}function y0(o,a,d){return _e(o,d),()=>b(o,a,[])}function _0(o,a,d){return _e(o,d),C=>T(o,a,[C])}function b0(o,a,d){return _e(o,d),(C,v)=>b(o,a,[C,v])}function Wd(o,a){if(!yn(o))throw new TypeError(`${a} is not a WritableStream.`)}function C0(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let w0=typeof AbortController=="function";function E0(){if(w0)return new AbortController}class vr{constructor(a={},d={}){a===void 0?a=null:Re(a,"First parameter");let C=mo(d,"Second parameter"),v=m0(a,"First parameter");if(Jd(this),v.type!==void 0)throw new RangeError("Invalid type is specified");let q=po(C),Y=fs(C,1);B0(this,v,Y,q)}get locked(){if(!yn(this))throw Co("locked");return _n(this)}abort(a=void 0){return yn(this)?_n(this)?f(new TypeError("Cannot abort a stream that already has a writer")):go(this,a):f(Co("abort"))}close(){return yn(this)?_n(this)?f(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?f(new TypeError("Cannot close an already-closing stream")):Vd(this):f(Co("close"))}getWriter(){if(!yn(this))throw Co("getWriter");return Gd(this)}}Object.defineProperties(vr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(vr.prototype.abort,"abort"),s(vr.prototype.close,"close"),s(vr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Gd(o){return new cr(o)}function A0(o,a,d,C,v=1,L=()=>1){let q=Object.create(vr.prototype);Jd(q);let Y=Object.create(bn.prototype);return ef(q,Y,o,a,d,C,v,L),q}function Jd(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new O,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function yn(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof vr}function _n(o){return o._writer!==void 0}function go(o,a){var d;if(o._state==="closed"||o._state==="errored")return h(void 0);o._writableStreamController._abortReason=a,(d=o._writableStreamController._abortController)===null||d===void 0||d.abort(a);let C=o._state;if(C==="closed"||C==="errored")return h(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let v=!1;C==="erroring"&&(v=!0,a=void 0);let L=l((q,Y)=>{o._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Y,_reason:a,_wasAlreadyErroring:v}});return o._pendingAbortRequest._promise=L,v||Qa(o,a),L}function Vd(o){let a=o._state;if(a==="closed"||a==="errored")return f(new TypeError(`The stream (in ${a} state) is not in the writable state and cannot be closed`));let d=l((v,L)=>{let q={_resolve:v,_reject:L};o._closeRequest=q}),C=o._writer;return C!==void 0&&o._backpressure&&a==="writable"&&iu(C),j0(o._writableStreamController),d}function S0(o){return l((d,C)=>{let v={_resolve:d,_reject:C};o._writeRequests.push(v)})}function Xa(o,a){if(o._state==="writable"){Qa(o,a);return}Za(o)}function Qa(o,a){let d=o._writableStreamController;o._state="erroring",o._storedError=a;let C=o._writer;C!==void 0&&Yd(C,a),!R0(o)&&d._started&&Za(o)}function Za(o){o._state="errored",o._writableStreamController[$]();let a=o._storedError;if(o._writeRequests.forEach(v=>{v._reject(a)}),o._writeRequests=new O,o._pendingAbortRequest===void 0){yo(o);return}let d=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,d._wasAlreadyErroring){d._reject(a),yo(o);return}let C=o._writableStreamController[x](d._reason);S(C,()=>(d._resolve(),yo(o),null),v=>(d._reject(v),yo(o),null))}function k0(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function T0(o,a){o._inFlightWriteRequest._reject(a),o._inFlightWriteRequest=void 0,Xa(o,a)}function D0(o){o._inFlightCloseRequest._resolve(void 0),o._inFlightCloseRequest=void 0,o._state==="erroring"&&(o._storedError=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._resolve(),o._pendingAbortRequest=void 0)),o._state="closed";let d=o._writer;d!==void 0&&sf(d)}function v0(o,a){o._inFlightCloseRequest._reject(a),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(a),o._pendingAbortRequest=void 0),Xa(o,a)}function Wt(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function R0(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function O0(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function F0(o){o._inFlightWriteRequest=o._writeRequests.shift()}function yo(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let a=o._writer;a!==void 0&&su(a,o._storedError)}function eu(o,a){let d=o._writer;d!==void 0&&a!==o._backpressure&&(a?H0(d):iu(d)),o._backpressure=a}class cr{constructor(a){if(Be(a,1,"WritableStreamDefaultWriter"),Wd(a,"First parameter"),_n(a))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=a,a._writer=this;let d=a._state;if(d==="writable")!Wt(a)&&a._backpressure?Eo(this):of(this),wo(this);else if(d==="erroring")ou(this,a._storedError),wo(this);else if(d==="closed")of(this),$0(this);else{let C=a._storedError;ou(this,C),nf(this,C)}}get closed(){return Xr(this)?this._closedPromise:f(Qr("closed"))}get desiredSize(){if(!Xr(this))throw Qr("desiredSize");if(this._ownerWritableStream===void 0)throw ps("desiredSize");return N0(this)}get ready(){return Xr(this)?this._readyPromise:f(Qr("ready"))}abort(a=void 0){return Xr(this)?this._ownerWritableStream===void 0?f(ps("abort")):x0(this,a):f(Qr("abort"))}close(){if(!Xr(this))return f(Qr("close"));let a=this._ownerWritableStream;return a===void 0?f(ps("close")):Wt(a)?f(new TypeError("Cannot close an already-closing stream")):Kd(this)}releaseLock(){if(!Xr(this))throw Qr("releaseLock");this._ownerWritableStream!==void 0&&Xd(this)}write(a=void 0){return Xr(this)?this._ownerWritableStream===void 0?f(ps("write to")):Qd(this,a):f(Qr("write"))}}Object.defineProperties(cr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(cr.prototype.abort,"abort"),s(cr.prototype.close,"close"),s(cr.prototype.releaseLock,"releaseLock"),s(cr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(cr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Xr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof cr}function x0(o,a){let d=o._ownerWritableStream;return go(d,a)}function Kd(o){let a=o._ownerWritableStream;return Vd(a)}function P0(o){let a=o._ownerWritableStream,d=a._state;return Wt(a)||d==="closed"?h(void 0):d==="errored"?f(a._storedError):Kd(o)}function I0(o,a){o._closedPromiseState==="pending"?su(o,a):z0(o,a)}function Yd(o,a){o._readyPromiseState==="pending"?af(o,a):W0(o,a)}function N0(o){let a=o._ownerWritableStream,d=a._state;return d==="errored"||d==="erroring"?null:d==="closed"?0:tf(a._writableStreamController)}function Xd(o){let a=o._ownerWritableStream,d=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Yd(o,d),I0(o,d),a._writer=void 0,o._ownerWritableStream=void 0}function Qd(o,a){let d=o._ownerWritableStream,C=d._writableStreamController,v=L0(C,a);if(d!==o._ownerWritableStream)return f(ps("write to"));let L=d._state;if(L==="errored")return f(d._storedError);if(Wt(d)||L==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return f(d._storedError);let q=S0(d);return M0(C,a,v),q}let Zd={};class bn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!tu(this))throw nu("abortReason");return this._abortReason}get signal(){if(!tu(this))throw nu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(a=void 0){if(!tu(this))throw nu("error");this._controlledWritableStream._state==="writable"&&rf(this,a)}[x](a){let d=this._abortAlgorithm(a);return _o(this),d}[$](){Tr(this)}}Object.defineProperties(bn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function tu(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof bn}function ef(o,a,d,C,v,L,q,Y){a._controlledWritableStream=o,o._writableStreamController=a,a._queue=void 0,a._queueTotalSize=void 0,Tr(a),a._abortReason=void 0,a._abortController=E0(),a._started=!1,a._strategySizeAlgorithm=Y,a._strategyHWM=q,a._writeAlgorithm=C,a._closeAlgorithm=v,a._abortAlgorithm=L;let ce=ru(a);eu(o,ce);let re=d(),fe=h(re);S(fe,()=>(a._started=!0,bo(a),null),ge=>(a._started=!0,Xa(o,ge),null))}function B0(o,a,d,C){let v=Object.create(bn.prototype),L,q,Y,ce;a.start!==void 0?L=()=>a.start(v):L=()=>{},a.write!==void 0?q=re=>a.write(re,v):q=()=>h(void 0),a.close!==void 0?Y=()=>a.close():Y=()=>h(void 0),a.abort!==void 0?ce=re=>a.abort(re):ce=()=>h(void 0),ef(o,v,L,q,Y,ce,d,C)}function _o(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function j0(o){za(o,Zd,0),bo(o)}function L0(o,a){try{return o._strategySizeAlgorithm(a)}catch(d){return hs(o,d),1}}function tf(o){return o._strategyHWM-o._queueTotalSize}function M0(o,a,d){try{za(o,a,d)}catch(v){hs(o,v);return}let C=o._controlledWritableStream;if(!Wt(C)&&C._state==="writable"){let v=ru(o);eu(C,v)}bo(o)}function bo(o){let a=o._controlledWritableStream;if(!o._started||a._inFlightWriteRequest!==void 0)return;if(a._state==="erroring"){Za(a);return}if(o._queue.length===0)return;let C=Zy(o);C===Zd?U0(o):q0(o,C)}function hs(o,a){o._controlledWritableStream._state==="writable"&&rf(o,a)}function U0(o){let a=o._controlledWritableStream;O0(a),$a(o);let d=o._closeAlgorithm();_o(o),S(d,()=>(D0(a),null),C=>(v0(a,C),null))}function q0(o,a){let d=o._controlledWritableStream;F0(d);let C=o._writeAlgorithm(a);S(C,()=>{k0(d);let v=d._state;if($a(o),!Wt(d)&&v==="writable"){let L=ru(o);eu(d,L)}return bo(o),null},v=>(d._state==="writable"&&_o(o),T0(d,v),null))}function ru(o){return tf(o)<=0}function rf(o,a){let d=o._controlledWritableStream;_o(o),Qa(d,a)}function Co(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function nu(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function Qr(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function ps(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function wo(o){o._closedPromise=l((a,d)=>{o._closedPromise_resolve=a,o._closedPromise_reject=d,o._closedPromiseState="pending"})}function nf(o,a){wo(o),su(o,a)}function $0(o){wo(o),sf(o)}function su(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function z0(o,a){nf(o,a)}function sf(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="resolved")}function Eo(o){o._readyPromise=l((a,d)=>{o._readyPromise_resolve=a,o._readyPromise_reject=d}),o._readyPromiseState="pending"}function ou(o,a){Eo(o),af(o,a)}function of(o){Eo(o),iu(o)}function af(o,a){o._readyPromise_reject!==void 0&&(g(o._readyPromise),o._readyPromise_reject(a),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function H0(o){Eo(o)}function W0(o,a){ou(o,a)}function iu(o){o._readyPromise_resolve!==void 0&&(o._readyPromise_resolve(void 0),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="fulfilled")}function G0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let au=G0();function J0(o){if(!(typeof o=="function"||typeof o=="object")||o.name!=="DOMException")return!1;try{return new o,!0}catch{return!1}}function V0(){let o=au?.DOMException;return J0(o)?o:void 0}function K0(){let o=function(d,C){this.message=d||"",this.name=C||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(o,"DOMException"),o.prototype=Object.create(Error.prototype),Object.defineProperty(o.prototype,"constructor",{value:o,writable:!0,configurable:!0}),o}let Y0=V0()||K0();function uf(o,a,d,C,v,L){let q=M(o),Y=Gd(a);o._disturbed=!0;let ce=!1,re=h(void 0);return l((fe,ge)=>{let ve;if(L!==void 0){if(ve=()=>{let se=L.reason!==void 0?L.reason:new Y0("Aborted","AbortError"),be=[];C||be.push(()=>a._state==="writable"?go(a,se):h(void 0)),v||be.push(()=>o._state==="readable"?Pt(o,se):h(void 0)),rt(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},L.aborted){ve();return}L.addEventListener("abort",ve)}function It(){return l((se,be)=>{function Oe(ct){ct?se():p(An(),Oe,be)}Oe(!1)})}function An(){return ce?h(!0):p(Y._readyPromise,()=>l((se,be)=>{ee(q,{_chunkSteps:Oe=>{re=p(Qd(Y,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(dr(o,q._closedPromise,se=>(C?Ct(!0,se):rt(()=>go(a,se),!0,se),null)),dr(a,Y._closedPromise,se=>(v?Ct(!0,se):rt(()=>Pt(o,se),!0,se),null)),Qe(o,q._closedPromise,()=>(d?Ct():rt(()=>P0(Y)),null)),Wt(a)||a._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");v?Ct(!0,se):rt(()=>Pt(o,se),!0,se)}g(It());function xr(){let se=re;return p(re,()=>se!==re?xr():void 0)}function dr(se,be,Oe){se._state==="errored"?Oe(se._storedError):E(be,Oe)}function Qe(se,be,Oe){se._state==="closed"?Oe():D(be,Oe)}function rt(se,be,Oe){if(ce)return;ce=!0,a._state==="writable"&&!Wt(a)?D(xr(),ct):ct();function ct(){return S(se(),()=>fr(be,Oe),Sn=>fr(!0,Sn)),null}}function Ct(se,be){ce||(ce=!0,a._state==="writable"&&!Wt(a)?D(xr(),()=>fr(se,be)):fr(se,be))}function fr(se,be){return Xd(Y),de(q),L!==void 0&&L.removeEventListener("abort",ve),se?ge(be):fe(void 0),null}})}class lr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ao(this))throw ko("desiredSize");return uu(this)}close(){if(!Ao(this))throw ko("close");if(!wn(this))throw new TypeError("The stream is not in a state that permits close");Zr(this)}enqueue(a=void 0){if(!Ao(this))throw ko("enqueue");if(!wn(this))throw new TypeError("The stream is not in a state that permits enqueue");return Cn(this,a)}error(a=void 0){if(!Ao(this))throw ko("error");xt(this,a)}[V](a){Tr(this);let d=this._cancelAlgorithm(a);return So(this),d}[U](a){let d=this._controlledReadableStream;if(this._queue.length>0){let C=$a(this);this._closeRequested&&this._queue.length===0?(So(this),ys(d)):ms(this),a._chunkSteps(C)}else R(d,a),ms(this)}[X](){}}Object.defineProperties(lr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(lr.prototype.close,"close"),s(lr.prototype.enqueue,"enqueue"),s(lr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(lr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ao(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof lr}function ms(o){if(!cf(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let d=o._pullAlgorithm();S(d,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,ms(o)),null),C=>(xt(o,C),null))}function cf(o){let a=o._controlledReadableStream;return!wn(o)||!o._started?!1:!!(Or(a)&&j(a)>0||uu(o)>0)}function So(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function Zr(o){if(!wn(o))return;let a=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(So(o),ys(a))}function Cn(o,a){if(!wn(o))return;let d=o._controlledReadableStream;if(Or(d)&&j(d)>0)P(d,a,!1);else{let C;try{C=o._strategySizeAlgorithm(a)}catch(v){throw xt(o,v),v}try{za(o,a,C)}catch(v){throw xt(o,v),v}}ms(o)}function xt(o,a){let d=o._controlledReadableStream;d._state==="readable"&&(Tr(o),So(o),hf(d,a))}function uu(o){let a=o._controlledReadableStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function X0(o){return!cf(o)}function wn(o){let a=o._controlledReadableStream._state;return!o._closeRequested&&a==="readable"}function lf(o,a,d,C,v,L,q){a._controlledReadableStream=o,a._queue=void 0,a._queueTotalSize=void 0,Tr(a),a._started=!1,a._closeRequested=!1,a._pullAgain=!1,a._pulling=!1,a._strategySizeAlgorithm=q,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=v,o._readableStreamController=a;let Y=d();S(h(Y),()=>(a._started=!0,ms(a),null),ce=>(xt(a,ce),null))}function Q0(o,a,d,C){let v=Object.create(lr.prototype),L,q,Y;a.start!==void 0?L=()=>a.start(v):L=()=>{},a.pull!==void 0?q=()=>a.pull(v):q=()=>h(void 0),a.cancel!==void 0?Y=ce=>a.cancel(ce):Y=()=>h(void 0),lf(o,v,L,q,Y,d,C)}function ko(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function Z0(o,a){return Vr(o._readableStreamController)?t_(o):e_(o)}function e_(o,a){let d=M(o),C=!1,v=!1,L=!1,q=!1,Y,ce,re,fe,ge,ve=l(Qe=>{ge=Qe});function It(){return C?(v=!0,h(void 0)):(C=!0,ee(d,{_chunkSteps:rt=>{m(()=>{v=!1;let Ct=rt,fr=rt;L||Cn(re._readableStreamController,Ct),q||Cn(fe._readableStreamController,fr),C=!1,v&&It()})},_closeSteps:()=>{C=!1,L||Zr(re._readableStreamController),q||Zr(fe._readableStreamController),(!L||!q)&&ge(void 0)},_errorSteps:()=>{C=!1}}),h(void 0))}function An(Qe){if(L=!0,Y=Qe,q){let rt=ke([Y,ce]),Ct=Pt(o,rt);ge(Ct)}return ve}function xr(Qe){if(q=!0,ce=Qe,L){let rt=ke([Y,ce]),Ct=Pt(o,rt);ge(Ct)}return ve}function dr(){}return re=gs(dr,It,An),fe=gs(dr,It,xr),E(d._closedPromise,Qe=>(xt(re._readableStreamController,Qe),xt(fe._readableStreamController,Qe),(!L||!q)&&ge(void 0),null)),[re,fe]}function t_(o){let a=M(o),d=!1,C=!1,v=!1,L=!1,q=!1,Y,ce,re,fe,ge,ve=l(se=>{ge=se});function It(se){E(se._closedPromise,be=>(se!==a||(bt(re._readableStreamController,be),bt(fe._readableStreamController,be),(!L||!q)&&ge(void 0)),null))}function An(){Yr(a)&&(de(a),a=M(o),It(a)),ee(a,{_chunkSteps:be=>{m(()=>{C=!1,v=!1;let Oe=be,ct=be;if(!L&&!q)try{ct=Dd(be)}catch(Sn){bt(re._readableStreamController,Sn),bt(fe._readableStreamController,Sn),ge(Pt(o,Sn));return}L||co(re._readableStreamController,Oe),q||co(fe._readableStreamController,ct),d=!1,C?dr():v&&Qe()})},_closeSteps:()=>{d=!1,L||ls(re._readableStreamController),q||ls(fe._readableStreamController),re._readableStreamController._pendingPullIntos.length>0&&lo(re._readableStreamController,0),fe._readableStreamController._pendingPullIntos.length>0&&lo(fe._readableStreamController,0),(!L||!q)&&ge(void 0)},_errorSteps:()=>{d=!1}})}function xr(se,be){Z(a)&&(de(a),a=Ud(o),It(a));let Oe=be?fe:re,ct=be?re:fe;zd(a,se,1,{_chunkSteps:kn=>{m(()=>{C=!1,v=!1;let Tn=be?q:L;if(be?L:q)Tn||fo(Oe._readableStreamController,kn);else{let Tf;try{Tf=Dd(kn)}catch(hu){bt(Oe._readableStreamController,hu),bt(ct._readableStreamController,hu),ge(Pt(o,hu));return}Tn||fo(Oe._readableStreamController,kn),co(ct._readableStreamController,Tf)}d=!1,C?dr():v&&Qe()})},_closeSteps:kn=>{d=!1;let Tn=be?q:L,Po=be?L:q;Tn||ls(Oe._readableStreamController),Po||ls(ct._readableStreamController),kn!==void 0&&(Tn||fo(Oe._readableStreamController,kn),!Po&&ct._readableStreamController._pendingPullIntos.length>0&&lo(ct._readableStreamController,0)),(!Tn||!Po)&&ge(void 0)},_errorSteps:()=>{d=!1}})}function dr(){if(d)return C=!0,h(void 0);d=!0;let se=Va(re._readableStreamController);return se===null?An():xr(se._view,!1),h(void 0)}function Qe(){if(d)return v=!0,h(void 0);d=!0;let se=Va(fe._readableStreamController);return se===null?An():xr(se._view,!0),h(void 0)}function rt(se){if(L=!0,Y=se,q){let be=ke([Y,ce]),Oe=Pt(o,be);ge(Oe)}return ve}function Ct(se){if(q=!0,ce=se,L){let be=ke([Y,ce]),Oe=Pt(o,be);ge(Oe)}return ve}function fr(){}return re=ff(fr,dr,rt),fe=ff(fr,Qe,Ct),It(a),[re,fe]}function r_(o){return r(o)&&typeof o.getReader<"u"}function n_(o){return r_(o)?o_(o.getReader()):s_(o)}function s_(o){let a,d=Td(o,"async"),C=e;function v(){let q;try{q=Ky(d)}catch(ce){return f(ce)}let Y=h(q);return y(Y,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Yy(ce))Zr(a._readableStreamController);else{let fe=Xy(ce);Cn(a._readableStreamController,fe)}})}function L(q){let Y=d.iterator,ce;try{ce=io(Y,"return")}catch(ge){return f(ge)}if(ce===void 0)return h(void 0);let re;try{re=T(ce,Y,[q])}catch(ge){return f(ge)}let fe=h(re);return y(fe,ge=>{if(!r(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return a=gs(C,v,L,0),a}function o_(o){let a,d=e;function C(){let L;try{L=o.read()}catch(q){return f(q)}return y(L,q=>{if(!r(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)Zr(a._readableStreamController);else{let Y=q.value;Cn(a._readableStreamController,Y)}})}function v(L){try{return h(o.cancel(L))}catch(q){return f(q)}}return a=gs(d,C,v,0),a}function i_(o,a){le(o,a);let d=o,C=d?.autoAllocateChunkSize,v=d?.cancel,L=d?.pull,q=d?.start,Y=d?.type;return{autoAllocateChunkSize:C===void 0?void 0:F(C,`${a} has member 'autoAllocateChunkSize' that`),cancel:v===void 0?void 0:a_(v,d,`${a} has member 'cancel' that`),pull:L===void 0?void 0:u_(L,d,`${a} has member 'pull' that`),start:q===void 0?void 0:c_(q,d,`${a} has member 'start' that`),type:Y===void 0?void 0:l_(Y,`${a} has member 'type' that`)}}function a_(o,a,d){return _e(o,d),C=>b(o,a,[C])}function u_(o,a,d){return _e(o,d),C=>b(o,a,[C])}function c_(o,a,d){return _e(o,d),C=>T(o,a,[C])}function l_(o,a){if(o=`${o}`,o!=="bytes")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function d_(o,a){return le(o,a),{preventCancel:!!o?.preventCancel}}function df(o,a){le(o,a);let d=o?.preventAbort,C=o?.preventCancel,v=o?.preventClose,L=o?.signal;return L!==void 0&&f_(L,`${a} has member 'signal' that`),{preventAbort:!!d,preventCancel:!!C,preventClose:!!v,signal:L}}function f_(o,a){if(!C0(o))throw new TypeError(`${a} is not an AbortSignal.`)}function h_(o,a){le(o,a);let d=o?.readable;_(d,"readable","ReadableWritablePair"),I(d,`${a} has member 'readable' that`);let C=o?.writable;return _(C,"writable","ReadableWritablePair"),Wd(C,`${a} has member 'writable' that`),{readable:d,writable:C}}class Ye{constructor(a={},d={}){a===void 0?a=null:Re(a,"First parameter");let C=mo(d,"Second parameter"),v=i_(a,"First parameter");if(cu(this),v.type==="bytes"){if(C.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=fs(C,0);a0(this,v,L)}else{let L=po(C),q=fs(C,1);Q0(this,v,q,L)}}get locked(){if(!Rr(this))throw en("locked");return Or(this)}cancel(a=void 0){return Rr(this)?Or(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,a):f(en("cancel"))}getReader(a=void 0){if(!Rr(this))throw en("getReader");return c0(a,"First parameter").mode===void 0?M(this):Ud(this)}pipeThrough(a,d={}){if(!Rr(this))throw en("pipeThrough");Be(a,1,"pipeThrough");let C=h_(a,"First parameter"),v=df(d,"Second parameter");if(Or(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(_n(C.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=uf(this,C.writable,v.preventClose,v.preventAbort,v.preventCancel,v.signal);return g(L),C.readable}pipeTo(a,d={}){if(!Rr(this))return f(en("pipeTo"));if(a===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!yn(a))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let C;try{C=df(d,"Second parameter")}catch(v){return f(v)}return Or(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):_n(a)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):uf(this,a,C.preventClose,C.preventAbort,C.preventCancel,C.signal)}tee(){if(!Rr(this))throw en("tee");let a=Z0(this);return ke(a)}values(a=void 0){if(!Rr(this))throw en("values");let d=d_(a,"First parameter");return hn(this,d.preventCancel)}[qa](a){return this.values(a)}static from(a){return n_(a)}}Object.defineProperties(Ye,{from:{enumerable:!0}}),Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Ye.from,"from"),s(Ye.prototype.cancel,"cancel"),s(Ye.prototype.getReader,"getReader"),s(Ye.prototype.pipeThrough,"pipeThrough"),s(Ye.prototype.pipeTo,"pipeTo"),s(Ye.prototype.tee,"tee"),s(Ye.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ye.prototype,qa,{value:Ye.prototype.values,writable:!0,configurable:!0});function gs(o,a,d,C=1,v=()=>1){let L=Object.create(Ye.prototype);cu(L);let q=Object.create(lr.prototype);return lf(L,q,o,a,d,C,v),L}function ff(o,a,d){let C=Object.create(Ye.prototype);cu(C);let v=Object.create(ur.prototype);return Md(C,v,o,a,d,0,void 0),C}function cu(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function Rr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof Ye}function Or(o){return o._reader!==void 0}function Pt(o,a){if(o._disturbed=!0,o._state==="closed")return h(void 0);if(o._state==="errored")return f(o._storedError);ys(o);let d=o._reader;if(d!==void 0&&Yr(d)){let v=d._readIntoRequests;d._readIntoRequests=new O,v.forEach(L=>{L._closeSteps(void 0)})}let C=o._readableStreamController[V](a);return y(C,e)}function ys(o){o._state="closed";let a=o._reader;if(a!==void 0&&(ue(a),Z(a))){let d=a._readRequests;a._readRequests=new O,d.forEach(C=>{C._closeSteps()})}}function hf(o,a){o._state="errored",o._storedError=a;let d=o._reader;d!==void 0&&(G(d,a),Z(d)?xe(d,a):Hd(d,a))}function en(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function pf(o,a){le(o,a);let d=o?.highWaterMark;return _(d,"highWaterMark","QueuingStrategyInit"),{highWaterMark:A(d)}}let mf=o=>o.byteLength;s(mf,"size");class To{constructor(a){Be(a,1,"ByteLengthQueuingStrategy"),a=pf(a,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!yf(this))throw gf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!yf(this))throw gf("size");return mf}}Object.defineProperties(To.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(To.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function gf(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function yf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof To}let _f=()=>1;s(_f,"size");class Do{constructor(a){Be(a,1,"CountQueuingStrategy"),a=pf(a,"First parameter"),this._countQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!Cf(this))throw bf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Cf(this))throw bf("size");return _f}}Object.defineProperties(Do.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Do.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function bf(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function Cf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof Do}function p_(o,a){le(o,a);let d=o?.cancel,C=o?.flush,v=o?.readableType,L=o?.start,q=o?.transform,Y=o?.writableType;return{cancel:d===void 0?void 0:__(d,o,`${a} has member 'cancel' that`),flush:C===void 0?void 0:m_(C,o,`${a} has member 'flush' that`),readableType:v,start:L===void 0?void 0:g_(L,o,`${a} has member 'start' that`),transform:q===void 0?void 0:y_(q,o,`${a} has member 'transform' that`),writableType:Y}}function m_(o,a,d){return _e(o,d),C=>b(o,a,[C])}function g_(o,a,d){return _e(o,d),C=>T(o,a,[C])}function y_(o,a,d){return _e(o,d),(C,v)=>b(o,a,[C,v])}function __(o,a,d){return _e(o,d),C=>b(o,a,[C])}class vo{constructor(a={},d={},C={}){a===void 0&&(a=null);let v=mo(d,"Second parameter"),L=mo(C,"Third parameter"),q=p_(a,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Y=fs(L,0),ce=po(L),re=fs(v,1),fe=po(v),ge,ve=l(It=>{ge=It});b_(this,ve,re,fe,Y,ce),w_(this,q),q.start!==void 0?ge(q.start(this._transformStreamController)):ge(void 0)}get readable(){if(!wf(this))throw kf("readable");return this._readable}get writable(){if(!wf(this))throw kf("writable");return this._writable}}Object.defineProperties(vo.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vo.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function b_(o,a,d,C,v,L){function q(){return a}function Y(ve){return S_(o,ve)}function ce(ve){return k_(o,ve)}function re(){return T_(o)}o._writable=A0(q,Y,re,ce,d,C);function fe(){return D_(o)}function ge(ve){return v_(o,ve)}o._readable=gs(q,fe,ge,v,L),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,Ro(o,!0),o._transformStreamController=void 0}function wf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof vo}function Ef(o,a){xt(o._readable._readableStreamController,a),lu(o,a)}function lu(o,a){Fo(o._transformStreamController),hs(o._writable._writableStreamController,a),du(o)}function du(o){o._backpressure&&Ro(o,!1)}function Ro(o,a){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=l(d=>{o._backpressureChangePromise_resolve=d}),o._backpressure=a}class Fr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Oo(this))throw xo("desiredSize");let a=this._controlledTransformStream._readable._readableStreamController;return uu(a)}enqueue(a=void 0){if(!Oo(this))throw xo("enqueue");Af(this,a)}error(a=void 0){if(!Oo(this))throw xo("error");E_(this,a)}terminate(){if(!Oo(this))throw xo("terminate");A_(this)}}Object.defineProperties(Fr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Fr.prototype.enqueue,"enqueue"),s(Fr.prototype.error,"error"),s(Fr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Oo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof Fr}function C_(o,a,d,C,v){a._controlledTransformStream=o,o._transformStreamController=a,a._transformAlgorithm=d,a._flushAlgorithm=C,a._cancelAlgorithm=v,a._finishPromise=void 0,a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0}function w_(o,a){let d=Object.create(Fr.prototype),C,v,L;a.transform!==void 0?C=q=>a.transform(q,d):C=q=>{try{return Af(d,q),h(void 0)}catch(Y){return f(Y)}},a.flush!==void 0?v=()=>a.flush(d):v=()=>h(void 0),a.cancel!==void 0?L=q=>a.cancel(q):L=()=>h(void 0),C_(o,d,C,v,L)}function Fo(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0,o._cancelAlgorithm=void 0}function Af(o,a){let d=o._controlledTransformStream,C=d._readable._readableStreamController;if(!wn(C))throw new TypeError("Readable side is not in a state that permits enqueue");try{Cn(C,a)}catch(L){throw lu(d,L),d._readable._storedError}X0(C)!==d._backpressure&&Ro(d,!0)}function E_(o,a){Ef(o._controlledTransformStream,a)}function Sf(o,a){let d=o._transformAlgorithm(a);return y(d,void 0,C=>{throw Ef(o._controlledTransformStream,C),C})}function A_(o){let a=o._controlledTransformStream,d=a._readable._readableStreamController;Zr(d);let C=new TypeError("TransformStream terminated");lu(a,C)}function S_(o,a){let d=o._transformStreamController;if(o._backpressure){let C=o._backpressureChangePromise;return y(C,()=>{let v=o._writable;if(v._state==="erroring")throw v._storedError;return Sf(d,a)})}return Sf(d,a)}function k_(o,a){let d=o._transformStreamController;if(d._finishPromise!==void 0)return d._finishPromise;let C=o._readable;d._finishPromise=l((L,q)=>{d._finishPromise_resolve=L,d._finishPromise_reject=q});let v=d._cancelAlgorithm(a);return Fo(d),S(v,()=>(C._state==="errored"?En(d,C._storedError):(xt(C._readableStreamController,a),fu(d)),null),L=>(xt(C._readableStreamController,L),En(d,L),null)),d._finishPromise}function T_(o){let a=o._transformStreamController;if(a._finishPromise!==void 0)return a._finishPromise;let d=o._readable;a._finishPromise=l((v,L)=>{a._finishPromise_resolve=v,a._finishPromise_reject=L});let C=a._flushAlgorithm();return Fo(a),S(C,()=>(d._state==="errored"?En(a,d._storedError):(Zr(d._readableStreamController),fu(a)),null),v=>(xt(d._readableStreamController,v),En(a,v),null)),a._finishPromise}function D_(o){return Ro(o,!1),o._backpressureChangePromise}function v_(o,a){let d=o._transformStreamController;if(d._finishPromise!==void 0)return d._finishPromise;let C=o._writable;d._finishPromise=l((L,q)=>{d._finishPromise_resolve=L,d._finishPromise_reject=q});let v=d._cancelAlgorithm(a);return Fo(d),S(v,()=>(C._state==="errored"?En(d,C._storedError):(hs(C._writableStreamController,a),du(o),fu(d)),null),L=>(hs(C._writableStreamController,L),du(o),En(d,L),null)),d._finishPromise}function xo(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function fu(o){o._finishPromise_resolve!==void 0&&(o._finishPromise_resolve(),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function En(o,a){o._finishPromise_reject!==void 0&&(g(o._finishPromise),o._finishPromise_reject(a),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function kf(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=To,t.CountQueuingStrategy=Do,t.ReadableByteStreamController=ur,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Dr,t.ReadableStreamBYOBRequest=Jr,t.ReadableStreamDefaultController=lr,t.ReadableStreamDefaultReader=z,t.TransformStream=vo,t.TransformStreamDefaultController=Fr,t.WritableStream=vr,t.WritableStreamDefaultController=bn,t.WritableStreamDefaultWriter=cr}))});var $h=J(()=>{if(!globalThis.ReadableStream)try{let t=Q("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,Q("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,qh())}try{let{Blob:t}=Q("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,s=this;return new ReadableStream({type:"bytes",async pull(i){let c=await s.slice(n,Math.min(s.size,n+65536)).arrayBuffer();n+=c.byteLength,i.enqueue(new Uint8Array(c)),n===s.size&&i.close()}})})}catch{}});async function*qu(t,e=!0){for(let r of t)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(e){let n=r.byteOffset,s=r.byteOffset+r.byteLength;for(;n!==s;){let i=Math.min(s-n,zh),u=r.buffer.slice(n,n+i);n+=u.byteLength,yield new Uint8Array(u)}}else yield r;else{let n=0,s=r;for(;n!==s.size;){let u=await s.slice(n,Math.min(s.size,n+zh)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var kv,zh,Hh,eC,Bt,Es=je(()=>{kv=Pr($h(),1);zh=65536;Hh=class $u{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],r={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!="object"&&typeof r!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");r===null&&(r={});let n=new TextEncoder;for(let i of e){let u;ArrayBuffer.isView(i)?u=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)):i instanceof ArrayBuffer?u=new Uint8Array(i.slice(0)):i instanceof $u?u=i:u=n.encode(`${i}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let s=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of qu(this.#e,!1))r+=e.decode(n,{stream:!0});return r+=e.decode(),r}async arrayBuffer(){let e=new Uint8Array(this.size),r=0;for await(let n of qu(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=qu(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await e.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,r=this.size,n=""){let{size:s}=this,i=e<0?Math.max(s+e,0):Math.min(e,s),u=r<0?Math.max(s+r,0):Math.min(r,s),c=Math.max(u-i,0),l=this.#e,h=[],f=0;for(let S of l){if(f>=c)break;let D=ArrayBuffer.isView(S)?S.byteLength:S.size;if(i&&D<=i)i-=D,u-=D;else{let E;ArrayBuffer.isView(S)?(E=S.subarray(i,Math.min(D,u)),f+=E.byteLength):(E=S.slice(i,Math.min(D,u)),f+=E.size),u-=D,h.push(E),i=0}}let p=new $u([],{type:String(n).toLowerCase()});return p.#r=c,p.#e=h,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Hh.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});eC=Hh,Bt=eC});var tC,rC,Br,zu=je(()=>{Es();tC=class extends Bt{#e=0;#t="";constructor(e,r,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let s=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(s)||(this.#e=s),this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Bt&&/^(File)$/.test(e[Symbol.toStringTag])}},rC=tC,Br=rC});function Jh(t,e=Bt){var r=`${Wh()}${Wh()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r
22
+ `);if(A===-1){Qo("have not received end of HTTP headers yet..."),i();return}let v=p.slice(0,A).toString("ascii").split(`\r
23
+ `),S=v.shift();if(!S)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let y=S.split(" "),g=+y[1],m=y.slice(2).join(" "),k={};for(let b of v){if(!b)continue;let E=b.indexOf(":");if(E===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${b}"`));let R=b.slice(0,E).toLowerCase(),x=b.slice(E+1).trimStart(),$=k[R];typeof $=="string"?k[R]=[$,x]:Array.isArray($)?$.push(x):k[R]=x}Qo("got proxy server response: %o %o",S,k),u(),e({connect:{statusCode:g,statusText:m,headers:k},buffered:p})}t.on("error",l),t.on("end",c),i()})}In.parseProxyResponse=Wb});var jh=V(At=>{"use strict";var Gb=At&&At.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Jb=At&&At.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Nh=At&&At.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Gb(e,t,r);return Jb(e,t),e},Bh=At&&At.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(At,"__esModule",{value:!0});At.HttpsProxyAgent=void 0;var Zo=Nh(Q("net")),xh=Nh(Q("tls")),Vb=Bh(Q("assert")),Kb=Bh(Mu()),Yb=Oh(),Xb=Q("url"),Qb=Fh(),ws=(0,Kb.default)("https-proxy-agent"),Ph=t=>t.servername===void 0&&t.host&&!Zo.isIP(t.host)?{...t,servername:t.host}:t,ei=class extends Yb.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new Xb.URL(e):e,this.proxyHeaders=r?.headers??{},ws("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),s=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...r?Ih(r,"headers"):null,host:n,port:s}}async connect(e,r){let{proxy:n}=this;if(!r.host)throw new TypeError('No "host" provided');let s;n.protocol==="https:"?(ws("Creating `tls.Socket`: %o",this.connectOpts),s=xh.connect(Ph(this.connectOpts))):(ws("Creating `net.Socket`: %o",this.connectOpts),s=Zo.connect(this.connectOpts));let i=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=Zo.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${u}:${r.port} HTTP/1.1\r
24
+ `;if(n.username||n.password){let A=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(A).toString("base64")}`}i.Host=`${u}:${r.port}`,i["Proxy-Connection"]||(i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let A of Object.keys(i))c+=`${A}: ${i[A]}\r
25
+ `;let l=(0,Qb.parseProxyResponse)(s);s.write(`${c}\r
26
+ `);let{connect:h,buffered:f}=await l;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",Zb),r.secureEndpoint?(ws("Upgrading socket connection to TLS"),xh.connect({...Ih(Ph(r),"host","path","port"),socket:s})):s;s.destroy();let p=new Zo.Socket({writable:!1});return p.readable=!0,e.once("socket",A=>{ws("Replaying proxy buffer for failed request"),(0,Vb.default)(A.listenerCount("data")>0),A.push(f),A.push(null)}),p}};ei.protocols=["http","https"];At.HttpsProxyAgent=ei;function Zb(t){t.resume()}function Ih(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function eC(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let r=t.substring(5,e).split(";"),n="",s=!1,i=r[0]||"text/plain",u=i;for(let f=1;f<r.length;f++)r[f]==="base64"?s=!0:r[f]&&(u+=`;${r[f]}`,r[f].indexOf("charset=")===0&&(n=r[f].substring(8)));!r[0]&&!n.length&&(u+=";charset=US-ASCII",n="US-ASCII");let c=s?"base64":"ascii",l=unescape(t.substring(e+1)),h=Buffer.from(l,c);return h.type=i,h.typeFull=u,h.charset=n,h}var Lh,Mh=je(()=>{Lh=eC});var qh=V((ti,Uh)=>{(function(t,e){typeof ti=="object"&&typeof Uh<"u"?e(ti):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(ti,(function(t){"use strict";function e(){}function r(o){return typeof o=="object"&&o!==null||typeof o=="function"}let n=e;function s(o,a){try{Object.defineProperty(o,"name",{value:a,configurable:!0})}catch{}}let i=Promise,u=Promise.prototype.then,c=Promise.reject.bind(i);function l(o){return new i(o)}function h(o){return l(a=>a(o))}function f(o){return c(o)}function p(o,a,d){return u.call(o,a,d)}function A(o,a,d){p(p(o,a,d),void 0,n)}function v(o,a){A(o,a)}function S(o,a){A(o,void 0,a)}function y(o,a,d){return p(o,a,d)}function g(o){p(o,void 0,n)}let m=o=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let a=h(void 0);m=d=>p(a,d)}return m(o)};function k(o,a,d){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,a,d)}function b(o,a,d){try{return h(k(o,a,d))}catch(C){return f(C)}}let E=16384;class R{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(a){let d=this._back,C=d;d._elements.length===E-1&&(C={_elements:[],_next:void 0}),d._elements.push(a),C!==d&&(this._back=C,d._next=C),++this._size}shift(){let a=this._front,d=a,C=this._cursor,D=C+1,L=a._elements,q=L[C];return D===E&&(d=a._next,D=0),--this._size,this._cursor=D,a!==d&&(this._front=d),L[C]=void 0,q}forEach(a){let d=this._cursor,C=this._front,D=C._elements;for(;(d!==D.length||C._next!==void 0)&&!(d===D.length&&(C=C._next,D=C._elements,d=0,D.length===0));)a(D[d]),++d}peek(){let a=this._front,d=this._cursor;return a._elements[d]}}let x=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),M=Symbol("[[PullSteps]]"),X=Symbol("[[ReleaseSteps]]");function ue(o,a){o._ownerReadableStream=a,a._reader=o,a._state==="readable"?Ae(o):a._state==="closed"?me(o):oe(o,a._storedError)}function re(o,a){let d=o._ownerReadableStream;return Pt(d,a)}function de(o){let a=o._ownerReadableStream;a._state==="readable"?G(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),a._readableStreamController[X](),a._reader=void 0,o._ownerReadableStream=void 0}function pe(o){return new TypeError("Cannot "+o+" a stream using a released reader")}function Ae(o){o._closedPromise=l((a,d)=>{o._closedPromise_resolve=a,o._closedPromise_reject=d})}function oe(o,a){Ae(o),G(o,a)}function me(o){Ae(o),ae(o)}function G(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function K(o,a){oe(o,a)}function ae(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let qe=Number.isFinite||function(o){return typeof o=="number"&&isFinite(o)},De=Math.trunc||function(o){return o<0?Math.ceil(o):Math.floor(o)};function W(o){return typeof o=="object"||typeof o=="function"}function le(o,a){if(o!==void 0&&!W(o))throw new TypeError(`${a} is not an object.`)}function _e(o,a){if(typeof o!="function")throw new TypeError(`${a} is not a function.`)}function Ft(o){return typeof o=="object"&&o!==null||typeof o=="function"}function Re(o,a){if(!Ft(o))throw new TypeError(`${a} is not an object.`)}function Be(o,a,d){if(o===void 0)throw new TypeError(`Parameter ${a} is required in '${d}'.`)}function _(o,a,d){if(o===void 0)throw new TypeError(`${a} is required in '${d}'.`)}function w(o){return Number(o)}function T(o){return o===0?0:o}function B(o){return T(De(o))}function F(o,a){let C=Number.MAX_SAFE_INTEGER,D=Number(o);if(D=T(D),!qe(D))throw new TypeError(`${a} is not a finite number`);if(D=B(D),D<0||D>C)throw new TypeError(`${a} is outside the accepted range of 0 to ${C}, inclusive`);return!qe(D)||D===0?0:D}function I(o,a){if(!Rr(o))throw new TypeError(`${a} is not a ReadableStream.`)}function U(o){return new z(o)}function O(o,a){o._reader._readRequests.push(a)}function P(o,a,d){let D=o._reader._readRequests.shift();d?D._closeSteps():D._chunkSteps(a)}function j(o){return o._reader._readRequests.length}function N(o){let a=o._reader;return!(a===void 0||!Z(a))}class z{constructor(a){if(Be(a,1,"ReadableStreamDefaultReader"),I(a,"First parameter"),Or(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ue(this,a),this._readRequests=new R}get closed(){return Z(this)?this._closedPromise:f(Ne("closed"))}cancel(a=void 0){return Z(this)?this._ownerReadableStream===void 0?f(pe("cancel")):re(this,a):f(Ne("cancel"))}read(){if(!Z(this))return f(Ne("read"));if(this._ownerReadableStream===void 0)return f(pe("read from"));let a,d,C=l((L,q)=>{a=L,d=q});return ee(this,{_chunkSteps:L=>a({value:L,done:!1}),_closeSteps:()=>a({value:void 0,done:!0}),_errorSteps:L=>d(L)}),C}releaseLock(){if(!Z(this))throw Ne("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(z.prototype.cancel,"cancel"),s(z.prototype.read,"read"),s(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Z(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readRequests")?!1:o instanceof z}function ee(o,a){let d=o._ownerReadableStream;d._disturbed=!0,d._state==="closed"?a._closeSteps():d._state==="errored"?a._errorSteps(d._storedError):d._readableStreamController[M](a)}function Ee(o){de(o);let a=new TypeError("Reader was released");xe(o,a)}function xe(o,a){let d=o._readRequests;o._readRequests=new R,d.forEach(C=>{C._errorSteps(a)})}function Ne(o){return new TypeError(`ReadableStreamDefaultReader.prototype.${o} can only be used on a ReadableStreamDefaultReader`)}let we=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(a,d){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=a,this._preventCancel=d}next(){let a=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,a,a):a(),this._ongoingPromise}return(a){let d=()=>this._returnSteps(a);return this._ongoingPromise?y(this._ongoingPromise,d,d):d()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let a=this._reader,d,C,D=l((q,Y)=>{d=q,C=Y});return ee(a,{_chunkSteps:q=>{this._ongoingPromise=void 0,m(()=>d({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,de(a),d({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,de(a),C(q)}}),D}_returnSteps(a){if(this._isFinished)return Promise.resolve({value:a,done:!0});this._isFinished=!0;let d=this._reader;if(!this._preventCancel){let C=re(d,a);return de(d),y(C,()=>({value:a,done:!0}))}return de(d),h({value:a,done:!0})}}let Me={next(){return pn(this)?this._asyncIteratorImpl.next():f(mn("next"))},return(o){return pn(this)?this._asyncIteratorImpl.return(o):f(mn("return"))}};Object.setPrototypeOf(Me,we);function hn(o,a){let d=U(o),C=new Se(d,a),D=Object.create(Me);return D._asyncIteratorImpl=C,D}function pn(o){if(!r(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof Se}catch{return!1}}function mn(o){return new TypeError(`ReadableStreamAsyncIterator.${o} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(o){return o!==o};var ir,Ke,Ue;function ke(o){return o.slice()}function Sd(o,a,d,C,D){new Uint8Array(o).set(new Uint8Array(d,C,D),a)}let ar=o=>(typeof o.transfer=="function"?ar=a=>a.transfer():typeof structuredClone=="function"?ar=a=>structuredClone(a,{transfer:[a]}):ar=a=>a,ar(o)),kr=o=>(typeof o.detached=="boolean"?kr=a=>a.detached:kr=a=>a.byteLength===0,kr(o));function kd(o,a,d){if(o.slice)return o.slice(a,d);let C=d-a,D=new ArrayBuffer(C);return Sd(D,0,o,a,C),D}function io(o,a){let d=o[a];if(d!=null){if(typeof d!="function")throw new TypeError(`${String(a)} is not a function`);return d}}function Ky(o){let a={[Symbol.iterator]:()=>o.iterator},d=(async function*(){return yield*a})(),C=d.next;return{iterator:d,nextMethod:C,done:!1}}let qa=(Ue=(ir=Symbol.asyncIterator)!==null&&ir!==void 0?ir:(Ke=Symbol.for)===null||Ke===void 0?void 0:Ke.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function Td(o,a="sync",d){if(d===void 0)if(a==="async"){if(d=io(o,qa),d===void 0){let L=io(o,Symbol.iterator),q=Td(o,"sync",L);return Ky(q)}}else d=io(o,Symbol.iterator);if(d===void 0)throw new TypeError("The object is not iterable");let C=k(d,o,[]);if(!r(C))throw new TypeError("The iterator method must return an object");let D=C.next;return{iterator:C,nextMethod:D,done:!1}}function Yy(o){let a=k(o.nextMethod,o.iterator,[]);if(!r(a))throw new TypeError("The iterator.next() method must return an object");return a}function Xy(o){return!!o.done}function Qy(o){return o.value}function Zy(o){return!(typeof o!="number"||ut(o)||o<0)}function Dd(o){let a=kd(o.buffer,o.byteOffset,o.byteOffset+o.byteLength);return new Uint8Array(a)}function $a(o){let a=o._queue.shift();return o._queueTotalSize-=a.size,o._queueTotalSize<0&&(o._queueTotalSize=0),a.value}function za(o,a,d){if(!Zy(d)||d===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");o._queue.push({value:a,size:d}),o._queueTotalSize+=d}function e0(o){return o._queue.peek().value}function Tr(o){o._queue=new R,o._queueTotalSize=0}function vd(o){return o===DataView}function t0(o){return vd(o.constructor)}function r0(o){return vd(o)?1:o.BYTES_PER_ELEMENT}class Jr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ha(this))throw Ka("view");return this._view}respond(a){if(!Ha(this))throw Ka("respond");if(Be(a,1,"respond"),a=F(a,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(kr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");lo(this._associatedReadableByteStreamController,a)}respondWithNewView(a){if(!Ha(this))throw Ka("respondWithNewView");if(Be(a,1,"respondWithNewView"),!ArrayBuffer.isView(a))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(kr(a.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");fo(this._associatedReadableByteStreamController,a)}}Object.defineProperties(Jr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(Jr.prototype.respond,"respond"),s(Jr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Jr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ur{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Vr(this))throw ds("byobRequest");return Va(this)}get desiredSize(){if(!Vr(this))throw ds("desiredSize");return Ld(this)}close(){if(!Vr(this))throw ds("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let a=this._controlledReadableByteStream._state;if(a!=="readable")throw new TypeError(`The stream (in ${a} state) is not in the readable state and cannot be closed`);ls(this)}enqueue(a){if(!Vr(this))throw ds("enqueue");if(Be(a,1,"enqueue"),!ArrayBuffer.isView(a))throw new TypeError("chunk must be an array buffer view");if(a.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(a.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let d=this._controlledReadableByteStream._state;if(d!=="readable")throw new TypeError(`The stream (in ${d} state) is not in the readable state and cannot be enqueued to`);co(this,a)}error(a=void 0){if(!Vr(this))throw ds("error");bt(this,a)}[J](a){Rd(this),Tr(this);let d=this._cancelAlgorithm(a);return uo(this),d}[M](a){let d=this._controlledReadableByteStream;if(this._queueTotalSize>0){jd(this,a);return}let C=this._autoAllocateChunkSize;if(C!==void 0){let D;try{D=new ArrayBuffer(C)}catch(q){a._errorSteps(q);return}let L={buffer:D,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}O(d,a),Kr(this)}[X](){if(this._pendingPullIntos.length>0){let a=this._pendingPullIntos.peek();a.readerType="none",this._pendingPullIntos=new R,this._pendingPullIntos.push(a)}}}Object.defineProperties(ur.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(ur.prototype.close,"close"),s(ur.prototype.enqueue,"enqueue"),s(ur.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ur.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof ur}function Ha(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof Jr}function Kr(o){if(!a0(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let d=o._pullAlgorithm();A(d,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,Kr(o)),null),C=>(bt(o,C),null))}function Rd(o){Ga(o),o._pendingPullIntos=new R}function Wa(o,a){let d=!1;o._state==="closed"&&(d=!0);let C=Od(a);a.readerType==="default"?P(o,C,d):h0(o,C,d)}function Od(o){let a=o.bytesFilled,d=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,a/d)}function ao(o,a,d,C){o._queue.push({buffer:a,byteOffset:d,byteLength:C}),o._queueTotalSize+=C}function Fd(o,a,d,C){let D;try{D=kd(a,d,d+C)}catch(L){throw bt(o,L),L}ao(o,D,0,C)}function xd(o,a){a.bytesFilled>0&&Fd(o,a.buffer,a.byteOffset,a.bytesFilled),gn(o)}function Pd(o,a){let d=Math.min(o._queueTotalSize,a.byteLength-a.bytesFilled),C=a.bytesFilled+d,D=d,L=!1,q=C%a.elementSize,Y=C-q;Y>=a.minimumFill&&(D=Y-a.bytesFilled,L=!0);let ce=o._queue;for(;D>0;){let ne=ce.peek(),fe=Math.min(D,ne.byteLength),ye=a.byteOffset+a.bytesFilled;Sd(a.buffer,ye,ne.buffer,ne.byteOffset,fe),ne.byteLength===fe?ce.shift():(ne.byteOffset+=fe,ne.byteLength-=fe),o._queueTotalSize-=fe,Id(o,fe,a),D-=fe}return L}function Id(o,a,d){d.bytesFilled+=a}function Nd(o){o._queueTotalSize===0&&o._closeRequested?(uo(o),ys(o._controlledReadableByteStream)):Kr(o)}function Ga(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function Ja(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let a=o._pendingPullIntos.peek();Pd(o,a)&&(gn(o),Wa(o._controlledReadableByteStream,a))}}function n0(o){let a=o._controlledReadableByteStream._reader;for(;a._readRequests.length>0;){if(o._queueTotalSize===0)return;let d=a._readRequests.shift();jd(o,d)}}function s0(o,a,d,C){let D=o._controlledReadableByteStream,L=a.constructor,q=r0(L),{byteOffset:Y,byteLength:ce}=a,ne=d*q,fe;try{fe=ar(a.buffer)}catch(ve){C._errorSteps(ve);return}let ye={buffer:fe,bufferByteLength:fe.byteLength,byteOffset:Y,byteLength:ce,bytesFilled:0,minimumFill:ne,elementSize:q,viewConstructor:L,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(ye),qd(D,C);return}if(D._state==="closed"){let ve=new L(ye.buffer,ye.byteOffset,0);C._closeSteps(ve);return}if(o._queueTotalSize>0){if(Pd(o,ye)){let ve=Od(ye);Nd(o),C._chunkSteps(ve);return}if(o._closeRequested){let ve=new TypeError("Insufficient bytes to fill elements in the given buffer");bt(o,ve),C._errorSteps(ve);return}}o._pendingPullIntos.push(ye),qd(D,C),Kr(o)}function o0(o,a){a.readerType==="none"&&gn(o);let d=o._controlledReadableByteStream;if(Ya(d))for(;$d(d)>0;){let C=gn(o);Wa(d,C)}}function i0(o,a,d){if(Id(o,a,d),d.readerType==="none"){xd(o,d),Ja(o);return}if(d.bytesFilled<d.minimumFill)return;gn(o);let C=d.bytesFilled%d.elementSize;if(C>0){let D=d.byteOffset+d.bytesFilled;Fd(o,d.buffer,D-C,C)}d.bytesFilled-=C,Wa(o._controlledReadableByteStream,d),Ja(o)}function Bd(o,a){let d=o._pendingPullIntos.peek();Ga(o),o._controlledReadableByteStream._state==="closed"?o0(o,d):i0(o,a,d),Kr(o)}function gn(o){return o._pendingPullIntos.shift()}function a0(o){let a=o._controlledReadableByteStream;return a._state!=="readable"||o._closeRequested||!o._started?!1:!!(N(a)&&j(a)>0||Ya(a)&&$d(a)>0||Ld(o)>0)}function uo(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function ls(o){let a=o._controlledReadableByteStream;if(!(o._closeRequested||a._state!=="readable")){if(o._queueTotalSize>0){o._closeRequested=!0;return}if(o._pendingPullIntos.length>0){let d=o._pendingPullIntos.peek();if(d.bytesFilled%d.elementSize!==0){let C=new TypeError("Insufficient bytes to fill elements in the given buffer");throw bt(o,C),C}}uo(o),ys(a)}}function co(o,a){let d=o._controlledReadableByteStream;if(o._closeRequested||d._state!=="readable")return;let{buffer:C,byteOffset:D,byteLength:L}=a;if(kr(C))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=ar(C);if(o._pendingPullIntos.length>0){let Y=o._pendingPullIntos.peek();if(kr(Y.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ga(o),Y.buffer=ar(Y.buffer),Y.readerType==="none"&&xd(o,Y)}if(N(d))if(n0(o),j(d)===0)ao(o,q,D,L);else{o._pendingPullIntos.length>0&&gn(o);let Y=new Uint8Array(q,D,L);P(d,Y,!1)}else Ya(d)?(ao(o,q,D,L),Ja(o)):ao(o,q,D,L);Kr(o)}function bt(o,a){let d=o._controlledReadableByteStream;d._state==="readable"&&(Rd(o),Tr(o),uo(o),hf(d,a))}function jd(o,a){let d=o._queue.shift();o._queueTotalSize-=d.byteLength,Nd(o);let C=new Uint8Array(d.buffer,d.byteOffset,d.byteLength);a._chunkSteps(C)}function Va(o){if(o._byobRequest===null&&o._pendingPullIntos.length>0){let a=o._pendingPullIntos.peek(),d=new Uint8Array(a.buffer,a.byteOffset+a.bytesFilled,a.byteLength-a.bytesFilled),C=Object.create(Jr.prototype);c0(C,o,d),o._byobRequest=C}return o._byobRequest}function Ld(o){let a=o._controlledReadableByteStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function lo(o,a){let d=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(a===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(d.bytesFilled+a>d.byteLength)throw new RangeError("bytesWritten out of range")}d.buffer=ar(d.buffer),Bd(o,a)}function fo(o,a){let d=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(a.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(d.byteOffset+d.bytesFilled!==a.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(d.bufferByteLength!==a.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(d.bytesFilled+a.byteLength>d.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let D=a.byteLength;d.buffer=ar(a.buffer),Bd(o,D)}function Md(o,a,d,C,D,L,q){a._controlledReadableByteStream=o,a._pullAgain=!1,a._pulling=!1,a._byobRequest=null,a._queue=a._queueTotalSize=void 0,Tr(a),a._closeRequested=!1,a._started=!1,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=D,a._autoAllocateChunkSize=q,a._pendingPullIntos=new R,o._readableStreamController=a;let Y=d();A(h(Y),()=>(a._started=!0,Kr(a),null),ce=>(bt(a,ce),null))}function u0(o,a,d){let C=Object.create(ur.prototype),D,L,q;a.start!==void 0?D=()=>a.start(C):D=()=>{},a.pull!==void 0?L=()=>a.pull(C):L=()=>h(void 0),a.cancel!==void 0?q=ce=>a.cancel(ce):q=()=>h(void 0);let Y=a.autoAllocateChunkSize;if(Y===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Md(o,C,D,L,q,d,Y)}function c0(o,a,d){o._associatedReadableByteStreamController=a,o._view=d}function Ka(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function ds(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function l0(o,a){le(o,a);let d=o?.mode;return{mode:d===void 0?void 0:d0(d,`${a} has member 'mode' that`)}}function d0(o,a){if(o=`${o}`,o!=="byob")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function f0(o,a){var d;le(o,a);let C=(d=o?.min)!==null&&d!==void 0?d:1;return{min:F(C,`${a} has member 'min' that`)}}function Ud(o){return new Dr(o)}function qd(o,a){o._reader._readIntoRequests.push(a)}function h0(o,a,d){let D=o._reader._readIntoRequests.shift();d?D._closeSteps(a):D._chunkSteps(a)}function $d(o){return o._reader._readIntoRequests.length}function Ya(o){let a=o._reader;return!(a===void 0||!Yr(a))}class Dr{constructor(a){if(Be(a,1,"ReadableStreamBYOBReader"),I(a,"First parameter"),Or(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Vr(a._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ue(this,a),this._readIntoRequests=new R}get closed(){return Yr(this)?this._closedPromise:f(ho("closed"))}cancel(a=void 0){return Yr(this)?this._ownerReadableStream===void 0?f(pe("cancel")):re(this,a):f(ho("cancel"))}read(a,d={}){if(!Yr(this))return f(ho("read"));if(!ArrayBuffer.isView(a))return f(new TypeError("view must be an array buffer view"));if(a.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(a.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(kr(a.buffer))return f(new TypeError("view's buffer has been detached"));let C;try{C=f0(d,"options")}catch(ne){return f(ne)}let D=C.min;if(D===0)return f(new TypeError("options.min must be greater than 0"));if(t0(a)){if(D>a.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(D>a.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(pe("read from"));let L,q,Y=l((ne,fe)=>{L=ne,q=fe});return zd(this,a,D,{_chunkSteps:ne=>L({value:ne,done:!1}),_closeSteps:ne=>L({value:ne,done:!0}),_errorSteps:ne=>q(ne)}),Y}releaseLock(){if(!Yr(this))throw ho("releaseLock");this._ownerReadableStream!==void 0&&p0(this)}}Object.defineProperties(Dr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(Dr.prototype.cancel,"cancel"),s(Dr.prototype.read,"read"),s(Dr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Yr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof Dr}function zd(o,a,d,C){let D=o._ownerReadableStream;D._disturbed=!0,D._state==="errored"?C._errorSteps(D._storedError):s0(D._readableStreamController,a,d,C)}function p0(o){de(o);let a=new TypeError("Reader was released");Hd(o,a)}function Hd(o,a){let d=o._readIntoRequests;o._readIntoRequests=new R,d.forEach(C=>{C._errorSteps(a)})}function ho(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function fs(o,a){let{highWaterMark:d}=o;if(d===void 0)return a;if(ut(d)||d<0)throw new RangeError("Invalid highWaterMark");return d}function po(o){let{size:a}=o;return a||(()=>1)}function mo(o,a){le(o,a);let d=o?.highWaterMark,C=o?.size;return{highWaterMark:d===void 0?void 0:w(d),size:C===void 0?void 0:m0(C,`${a} has member 'size' that`)}}function m0(o,a){return _e(o,a),d=>w(o(d))}function g0(o,a){le(o,a);let d=o?.abort,C=o?.close,D=o?.start,L=o?.type,q=o?.write;return{abort:d===void 0?void 0:y0(d,o,`${a} has member 'abort' that`),close:C===void 0?void 0:_0(C,o,`${a} has member 'close' that`),start:D===void 0?void 0:b0(D,o,`${a} has member 'start' that`),write:q===void 0?void 0:C0(q,o,`${a} has member 'write' that`),type:L}}function y0(o,a,d){return _e(o,d),C=>b(o,a,[C])}function _0(o,a,d){return _e(o,d),()=>b(o,a,[])}function b0(o,a,d){return _e(o,d),C=>k(o,a,[C])}function C0(o,a,d){return _e(o,d),(C,D)=>b(o,a,[C,D])}function Wd(o,a){if(!yn(o))throw new TypeError(`${a} is not a WritableStream.`)}function w0(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let E0=typeof AbortController=="function";function A0(){if(E0)return new AbortController}class vr{constructor(a={},d={}){a===void 0?a=null:Re(a,"First parameter");let C=mo(d,"Second parameter"),D=g0(a,"First parameter");if(Jd(this),D.type!==void 0)throw new RangeError("Invalid type is specified");let q=po(C),Y=fs(C,1);j0(this,D,Y,q)}get locked(){if(!yn(this))throw Co("locked");return _n(this)}abort(a=void 0){return yn(this)?_n(this)?f(new TypeError("Cannot abort a stream that already has a writer")):go(this,a):f(Co("abort"))}close(){return yn(this)?_n(this)?f(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?f(new TypeError("Cannot close an already-closing stream")):Vd(this):f(Co("close"))}getWriter(){if(!yn(this))throw Co("getWriter");return Gd(this)}}Object.defineProperties(vr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(vr.prototype.abort,"abort"),s(vr.prototype.close,"close"),s(vr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Gd(o){return new cr(o)}function S0(o,a,d,C,D=1,L=()=>1){let q=Object.create(vr.prototype);Jd(q);let Y=Object.create(bn.prototype);return ef(q,Y,o,a,d,C,D,L),q}function Jd(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new R,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function yn(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof vr}function _n(o){return o._writer!==void 0}function go(o,a){var d;if(o._state==="closed"||o._state==="errored")return h(void 0);o._writableStreamController._abortReason=a,(d=o._writableStreamController._abortController)===null||d===void 0||d.abort(a);let C=o._state;if(C==="closed"||C==="errored")return h(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let D=!1;C==="erroring"&&(D=!0,a=void 0);let L=l((q,Y)=>{o._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Y,_reason:a,_wasAlreadyErroring:D}});return o._pendingAbortRequest._promise=L,D||Qa(o,a),L}function Vd(o){let a=o._state;if(a==="closed"||a==="errored")return f(new TypeError(`The stream (in ${a} state) is not in the writable state and cannot be closed`));let d=l((D,L)=>{let q={_resolve:D,_reject:L};o._closeRequest=q}),C=o._writer;return C!==void 0&&o._backpressure&&a==="writable"&&iu(C),L0(o._writableStreamController),d}function k0(o){return l((d,C)=>{let D={_resolve:d,_reject:C};o._writeRequests.push(D)})}function Xa(o,a){if(o._state==="writable"){Qa(o,a);return}Za(o)}function Qa(o,a){let d=o._writableStreamController;o._state="erroring",o._storedError=a;let C=o._writer;C!==void 0&&Yd(C,a),!O0(o)&&d._started&&Za(o)}function Za(o){o._state="errored",o._writableStreamController[$]();let a=o._storedError;if(o._writeRequests.forEach(D=>{D._reject(a)}),o._writeRequests=new R,o._pendingAbortRequest===void 0){yo(o);return}let d=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,d._wasAlreadyErroring){d._reject(a),yo(o);return}let C=o._writableStreamController[x](d._reason);A(C,()=>(d._resolve(),yo(o),null),D=>(d._reject(D),yo(o),null))}function T0(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function D0(o,a){o._inFlightWriteRequest._reject(a),o._inFlightWriteRequest=void 0,Xa(o,a)}function v0(o){o._inFlightCloseRequest._resolve(void 0),o._inFlightCloseRequest=void 0,o._state==="erroring"&&(o._storedError=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._resolve(),o._pendingAbortRequest=void 0)),o._state="closed";let d=o._writer;d!==void 0&&sf(d)}function R0(o,a){o._inFlightCloseRequest._reject(a),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(a),o._pendingAbortRequest=void 0),Xa(o,a)}function Wt(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function O0(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function F0(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function x0(o){o._inFlightWriteRequest=o._writeRequests.shift()}function yo(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let a=o._writer;a!==void 0&&su(a,o._storedError)}function eu(o,a){let d=o._writer;d!==void 0&&a!==o._backpressure&&(a?W0(d):iu(d)),o._backpressure=a}class cr{constructor(a){if(Be(a,1,"WritableStreamDefaultWriter"),Wd(a,"First parameter"),_n(a))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=a,a._writer=this;let d=a._state;if(d==="writable")!Wt(a)&&a._backpressure?Eo(this):of(this),wo(this);else if(d==="erroring")ou(this,a._storedError),wo(this);else if(d==="closed")of(this),z0(this);else{let C=a._storedError;ou(this,C),nf(this,C)}}get closed(){return Xr(this)?this._closedPromise:f(Qr("closed"))}get desiredSize(){if(!Xr(this))throw Qr("desiredSize");if(this._ownerWritableStream===void 0)throw ps("desiredSize");return B0(this)}get ready(){return Xr(this)?this._readyPromise:f(Qr("ready"))}abort(a=void 0){return Xr(this)?this._ownerWritableStream===void 0?f(ps("abort")):P0(this,a):f(Qr("abort"))}close(){if(!Xr(this))return f(Qr("close"));let a=this._ownerWritableStream;return a===void 0?f(ps("close")):Wt(a)?f(new TypeError("Cannot close an already-closing stream")):Kd(this)}releaseLock(){if(!Xr(this))throw Qr("releaseLock");this._ownerWritableStream!==void 0&&Xd(this)}write(a=void 0){return Xr(this)?this._ownerWritableStream===void 0?f(ps("write to")):Qd(this,a):f(Qr("write"))}}Object.defineProperties(cr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(cr.prototype.abort,"abort"),s(cr.prototype.close,"close"),s(cr.prototype.releaseLock,"releaseLock"),s(cr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(cr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Xr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof cr}function P0(o,a){let d=o._ownerWritableStream;return go(d,a)}function Kd(o){let a=o._ownerWritableStream;return Vd(a)}function I0(o){let a=o._ownerWritableStream,d=a._state;return Wt(a)||d==="closed"?h(void 0):d==="errored"?f(a._storedError):Kd(o)}function N0(o,a){o._closedPromiseState==="pending"?su(o,a):H0(o,a)}function Yd(o,a){o._readyPromiseState==="pending"?af(o,a):G0(o,a)}function B0(o){let a=o._ownerWritableStream,d=a._state;return d==="errored"||d==="erroring"?null:d==="closed"?0:tf(a._writableStreamController)}function Xd(o){let a=o._ownerWritableStream,d=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Yd(o,d),N0(o,d),a._writer=void 0,o._ownerWritableStream=void 0}function Qd(o,a){let d=o._ownerWritableStream,C=d._writableStreamController,D=M0(C,a);if(d!==o._ownerWritableStream)return f(ps("write to"));let L=d._state;if(L==="errored")return f(d._storedError);if(Wt(d)||L==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return f(d._storedError);let q=k0(d);return U0(C,a,D),q}let Zd={};class bn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!tu(this))throw nu("abortReason");return this._abortReason}get signal(){if(!tu(this))throw nu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(a=void 0){if(!tu(this))throw nu("error");this._controlledWritableStream._state==="writable"&&rf(this,a)}[x](a){let d=this._abortAlgorithm(a);return _o(this),d}[$](){Tr(this)}}Object.defineProperties(bn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function tu(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof bn}function ef(o,a,d,C,D,L,q,Y){a._controlledWritableStream=o,o._writableStreamController=a,a._queue=void 0,a._queueTotalSize=void 0,Tr(a),a._abortReason=void 0,a._abortController=A0(),a._started=!1,a._strategySizeAlgorithm=Y,a._strategyHWM=q,a._writeAlgorithm=C,a._closeAlgorithm=D,a._abortAlgorithm=L;let ce=ru(a);eu(o,ce);let ne=d(),fe=h(ne);A(fe,()=>(a._started=!0,bo(a),null),ye=>(a._started=!0,Xa(o,ye),null))}function j0(o,a,d,C){let D=Object.create(bn.prototype),L,q,Y,ce;a.start!==void 0?L=()=>a.start(D):L=()=>{},a.write!==void 0?q=ne=>a.write(ne,D):q=()=>h(void 0),a.close!==void 0?Y=()=>a.close():Y=()=>h(void 0),a.abort!==void 0?ce=ne=>a.abort(ne):ce=()=>h(void 0),ef(o,D,L,q,Y,ce,d,C)}function _o(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function L0(o){za(o,Zd,0),bo(o)}function M0(o,a){try{return o._strategySizeAlgorithm(a)}catch(d){return hs(o,d),1}}function tf(o){return o._strategyHWM-o._queueTotalSize}function U0(o,a,d){try{za(o,a,d)}catch(D){hs(o,D);return}let C=o._controlledWritableStream;if(!Wt(C)&&C._state==="writable"){let D=ru(o);eu(C,D)}bo(o)}function bo(o){let a=o._controlledWritableStream;if(!o._started||a._inFlightWriteRequest!==void 0)return;if(a._state==="erroring"){Za(a);return}if(o._queue.length===0)return;let C=e0(o);C===Zd?q0(o):$0(o,C)}function hs(o,a){o._controlledWritableStream._state==="writable"&&rf(o,a)}function q0(o){let a=o._controlledWritableStream;F0(a),$a(o);let d=o._closeAlgorithm();_o(o),A(d,()=>(v0(a),null),C=>(R0(a,C),null))}function $0(o,a){let d=o._controlledWritableStream;x0(d);let C=o._writeAlgorithm(a);A(C,()=>{T0(d);let D=d._state;if($a(o),!Wt(d)&&D==="writable"){let L=ru(o);eu(d,L)}return bo(o),null},D=>(d._state==="writable"&&_o(o),D0(d,D),null))}function ru(o){return tf(o)<=0}function rf(o,a){let d=o._controlledWritableStream;_o(o),Qa(d,a)}function Co(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function nu(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function Qr(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function ps(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function wo(o){o._closedPromise=l((a,d)=>{o._closedPromise_resolve=a,o._closedPromise_reject=d,o._closedPromiseState="pending"})}function nf(o,a){wo(o),su(o,a)}function z0(o){wo(o),sf(o)}function su(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function H0(o,a){nf(o,a)}function sf(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="resolved")}function Eo(o){o._readyPromise=l((a,d)=>{o._readyPromise_resolve=a,o._readyPromise_reject=d}),o._readyPromiseState="pending"}function ou(o,a){Eo(o),af(o,a)}function of(o){Eo(o),iu(o)}function af(o,a){o._readyPromise_reject!==void 0&&(g(o._readyPromise),o._readyPromise_reject(a),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function W0(o){Eo(o)}function G0(o,a){ou(o,a)}function iu(o){o._readyPromise_resolve!==void 0&&(o._readyPromise_resolve(void 0),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="fulfilled")}function J0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let au=J0();function V0(o){if(!(typeof o=="function"||typeof o=="object")||o.name!=="DOMException")return!1;try{return new o,!0}catch{return!1}}function K0(){let o=au?.DOMException;return V0(o)?o:void 0}function Y0(){let o=function(d,C){this.message=d||"",this.name=C||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(o,"DOMException"),o.prototype=Object.create(Error.prototype),Object.defineProperty(o.prototype,"constructor",{value:o,writable:!0,configurable:!0}),o}let X0=K0()||Y0();function uf(o,a,d,C,D,L){let q=U(o),Y=Gd(a);o._disturbed=!0;let ce=!1,ne=h(void 0);return l((fe,ye)=>{let ve;if(L!==void 0){if(ve=()=>{let se=L.reason!==void 0?L.reason:new X0("Aborted","AbortError"),be=[];C||be.push(()=>a._state==="writable"?go(a,se):h(void 0)),D||be.push(()=>o._state==="readable"?Pt(o,se):h(void 0)),rt(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},L.aborted){ve();return}L.addEventListener("abort",ve)}function It(){return l((se,be)=>{function Oe(ct){ct?se():p(An(),Oe,be)}Oe(!1)})}function An(){return ce?h(!0):p(Y._readyPromise,()=>l((se,be)=>{ee(q,{_chunkSteps:Oe=>{ne=p(Qd(Y,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(dr(o,q._closedPromise,se=>(C?Ct(!0,se):rt(()=>go(a,se),!0,se),null)),dr(a,Y._closedPromise,se=>(D?Ct(!0,se):rt(()=>Pt(o,se),!0,se),null)),Qe(o,q._closedPromise,()=>(d?Ct():rt(()=>I0(Y)),null)),Wt(a)||a._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");D?Ct(!0,se):rt(()=>Pt(o,se),!0,se)}g(It());function xr(){let se=ne;return p(ne,()=>se!==ne?xr():void 0)}function dr(se,be,Oe){se._state==="errored"?Oe(se._storedError):S(be,Oe)}function Qe(se,be,Oe){se._state==="closed"?Oe():v(be,Oe)}function rt(se,be,Oe){if(ce)return;ce=!0,a._state==="writable"&&!Wt(a)?v(xr(),ct):ct();function ct(){return A(se(),()=>fr(be,Oe),Sn=>fr(!0,Sn)),null}}function Ct(se,be){ce||(ce=!0,a._state==="writable"&&!Wt(a)?v(xr(),()=>fr(se,be)):fr(se,be))}function fr(se,be){return Xd(Y),de(q),L!==void 0&&L.removeEventListener("abort",ve),se?ye(be):fe(void 0),null}})}class lr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ao(this))throw ko("desiredSize");return uu(this)}close(){if(!Ao(this))throw ko("close");if(!wn(this))throw new TypeError("The stream is not in a state that permits close");Zr(this)}enqueue(a=void 0){if(!Ao(this))throw ko("enqueue");if(!wn(this))throw new TypeError("The stream is not in a state that permits enqueue");return Cn(this,a)}error(a=void 0){if(!Ao(this))throw ko("error");xt(this,a)}[J](a){Tr(this);let d=this._cancelAlgorithm(a);return So(this),d}[M](a){let d=this._controlledReadableStream;if(this._queue.length>0){let C=$a(this);this._closeRequested&&this._queue.length===0?(So(this),ys(d)):ms(this),a._chunkSteps(C)}else O(d,a),ms(this)}[X](){}}Object.defineProperties(lr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(lr.prototype.close,"close"),s(lr.prototype.enqueue,"enqueue"),s(lr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(lr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ao(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof lr}function ms(o){if(!cf(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let d=o._pullAlgorithm();A(d,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,ms(o)),null),C=>(xt(o,C),null))}function cf(o){let a=o._controlledReadableStream;return!wn(o)||!o._started?!1:!!(Or(a)&&j(a)>0||uu(o)>0)}function So(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function Zr(o){if(!wn(o))return;let a=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(So(o),ys(a))}function Cn(o,a){if(!wn(o))return;let d=o._controlledReadableStream;if(Or(d)&&j(d)>0)P(d,a,!1);else{let C;try{C=o._strategySizeAlgorithm(a)}catch(D){throw xt(o,D),D}try{za(o,a,C)}catch(D){throw xt(o,D),D}}ms(o)}function xt(o,a){let d=o._controlledReadableStream;d._state==="readable"&&(Tr(o),So(o),hf(d,a))}function uu(o){let a=o._controlledReadableStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function Q0(o){return!cf(o)}function wn(o){let a=o._controlledReadableStream._state;return!o._closeRequested&&a==="readable"}function lf(o,a,d,C,D,L,q){a._controlledReadableStream=o,a._queue=void 0,a._queueTotalSize=void 0,Tr(a),a._started=!1,a._closeRequested=!1,a._pullAgain=!1,a._pulling=!1,a._strategySizeAlgorithm=q,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=D,o._readableStreamController=a;let Y=d();A(h(Y),()=>(a._started=!0,ms(a),null),ce=>(xt(a,ce),null))}function Z0(o,a,d,C){let D=Object.create(lr.prototype),L,q,Y;a.start!==void 0?L=()=>a.start(D):L=()=>{},a.pull!==void 0?q=()=>a.pull(D):q=()=>h(void 0),a.cancel!==void 0?Y=ce=>a.cancel(ce):Y=()=>h(void 0),lf(o,D,L,q,Y,d,C)}function ko(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function e_(o,a){return Vr(o._readableStreamController)?r_(o):t_(o)}function t_(o,a){let d=U(o),C=!1,D=!1,L=!1,q=!1,Y,ce,ne,fe,ye,ve=l(Qe=>{ye=Qe});function It(){return C?(D=!0,h(void 0)):(C=!0,ee(d,{_chunkSteps:rt=>{m(()=>{D=!1;let Ct=rt,fr=rt;L||Cn(ne._readableStreamController,Ct),q||Cn(fe._readableStreamController,fr),C=!1,D&&It()})},_closeSteps:()=>{C=!1,L||Zr(ne._readableStreamController),q||Zr(fe._readableStreamController),(!L||!q)&&ye(void 0)},_errorSteps:()=>{C=!1}}),h(void 0))}function An(Qe){if(L=!0,Y=Qe,q){let rt=ke([Y,ce]),Ct=Pt(o,rt);ye(Ct)}return ve}function xr(Qe){if(q=!0,ce=Qe,L){let rt=ke([Y,ce]),Ct=Pt(o,rt);ye(Ct)}return ve}function dr(){}return ne=gs(dr,It,An),fe=gs(dr,It,xr),S(d._closedPromise,Qe=>(xt(ne._readableStreamController,Qe),xt(fe._readableStreamController,Qe),(!L||!q)&&ye(void 0),null)),[ne,fe]}function r_(o){let a=U(o),d=!1,C=!1,D=!1,L=!1,q=!1,Y,ce,ne,fe,ye,ve=l(se=>{ye=se});function It(se){S(se._closedPromise,be=>(se!==a||(bt(ne._readableStreamController,be),bt(fe._readableStreamController,be),(!L||!q)&&ye(void 0)),null))}function An(){Yr(a)&&(de(a),a=U(o),It(a)),ee(a,{_chunkSteps:be=>{m(()=>{C=!1,D=!1;let Oe=be,ct=be;if(!L&&!q)try{ct=Dd(be)}catch(Sn){bt(ne._readableStreamController,Sn),bt(fe._readableStreamController,Sn),ye(Pt(o,Sn));return}L||co(ne._readableStreamController,Oe),q||co(fe._readableStreamController,ct),d=!1,C?dr():D&&Qe()})},_closeSteps:()=>{d=!1,L||ls(ne._readableStreamController),q||ls(fe._readableStreamController),ne._readableStreamController._pendingPullIntos.length>0&&lo(ne._readableStreamController,0),fe._readableStreamController._pendingPullIntos.length>0&&lo(fe._readableStreamController,0),(!L||!q)&&ye(void 0)},_errorSteps:()=>{d=!1}})}function xr(se,be){Z(a)&&(de(a),a=Ud(o),It(a));let Oe=be?fe:ne,ct=be?ne:fe;zd(a,se,1,{_chunkSteps:kn=>{m(()=>{C=!1,D=!1;let Tn=be?q:L;if(be?L:q)Tn||fo(Oe._readableStreamController,kn);else{let Tf;try{Tf=Dd(kn)}catch(hu){bt(Oe._readableStreamController,hu),bt(ct._readableStreamController,hu),ye(Pt(o,hu));return}Tn||fo(Oe._readableStreamController,kn),co(ct._readableStreamController,Tf)}d=!1,C?dr():D&&Qe()})},_closeSteps:kn=>{d=!1;let Tn=be?q:L,Po=be?L:q;Tn||ls(Oe._readableStreamController),Po||ls(ct._readableStreamController),kn!==void 0&&(Tn||fo(Oe._readableStreamController,kn),!Po&&ct._readableStreamController._pendingPullIntos.length>0&&lo(ct._readableStreamController,0)),(!Tn||!Po)&&ye(void 0)},_errorSteps:()=>{d=!1}})}function dr(){if(d)return C=!0,h(void 0);d=!0;let se=Va(ne._readableStreamController);return se===null?An():xr(se._view,!1),h(void 0)}function Qe(){if(d)return D=!0,h(void 0);d=!0;let se=Va(fe._readableStreamController);return se===null?An():xr(se._view,!0),h(void 0)}function rt(se){if(L=!0,Y=se,q){let be=ke([Y,ce]),Oe=Pt(o,be);ye(Oe)}return ve}function Ct(se){if(q=!0,ce=se,L){let be=ke([Y,ce]),Oe=Pt(o,be);ye(Oe)}return ve}function fr(){}return ne=ff(fr,dr,rt),fe=ff(fr,Qe,Ct),It(a),[ne,fe]}function n_(o){return r(o)&&typeof o.getReader<"u"}function s_(o){return n_(o)?i_(o.getReader()):o_(o)}function o_(o){let a,d=Td(o,"async"),C=e;function D(){let q;try{q=Yy(d)}catch(ce){return f(ce)}let Y=h(q);return y(Y,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Xy(ce))Zr(a._readableStreamController);else{let fe=Qy(ce);Cn(a._readableStreamController,fe)}})}function L(q){let Y=d.iterator,ce;try{ce=io(Y,"return")}catch(ye){return f(ye)}if(ce===void 0)return h(void 0);let ne;try{ne=k(ce,Y,[q])}catch(ye){return f(ye)}let fe=h(ne);return y(fe,ye=>{if(!r(ye))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return a=gs(C,D,L,0),a}function i_(o){let a,d=e;function C(){let L;try{L=o.read()}catch(q){return f(q)}return y(L,q=>{if(!r(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)Zr(a._readableStreamController);else{let Y=q.value;Cn(a._readableStreamController,Y)}})}function D(L){try{return h(o.cancel(L))}catch(q){return f(q)}}return a=gs(d,C,D,0),a}function a_(o,a){le(o,a);let d=o,C=d?.autoAllocateChunkSize,D=d?.cancel,L=d?.pull,q=d?.start,Y=d?.type;return{autoAllocateChunkSize:C===void 0?void 0:F(C,`${a} has member 'autoAllocateChunkSize' that`),cancel:D===void 0?void 0:u_(D,d,`${a} has member 'cancel' that`),pull:L===void 0?void 0:c_(L,d,`${a} has member 'pull' that`),start:q===void 0?void 0:l_(q,d,`${a} has member 'start' that`),type:Y===void 0?void 0:d_(Y,`${a} has member 'type' that`)}}function u_(o,a,d){return _e(o,d),C=>b(o,a,[C])}function c_(o,a,d){return _e(o,d),C=>b(o,a,[C])}function l_(o,a,d){return _e(o,d),C=>k(o,a,[C])}function d_(o,a){if(o=`${o}`,o!=="bytes")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function f_(o,a){return le(o,a),{preventCancel:!!o?.preventCancel}}function df(o,a){le(o,a);let d=o?.preventAbort,C=o?.preventCancel,D=o?.preventClose,L=o?.signal;return L!==void 0&&h_(L,`${a} has member 'signal' that`),{preventAbort:!!d,preventCancel:!!C,preventClose:!!D,signal:L}}function h_(o,a){if(!w0(o))throw new TypeError(`${a} is not an AbortSignal.`)}function p_(o,a){le(o,a);let d=o?.readable;_(d,"readable","ReadableWritablePair"),I(d,`${a} has member 'readable' that`);let C=o?.writable;return _(C,"writable","ReadableWritablePair"),Wd(C,`${a} has member 'writable' that`),{readable:d,writable:C}}class Ye{constructor(a={},d={}){a===void 0?a=null:Re(a,"First parameter");let C=mo(d,"Second parameter"),D=a_(a,"First parameter");if(cu(this),D.type==="bytes"){if(C.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=fs(C,0);u0(this,D,L)}else{let L=po(C),q=fs(C,1);Z0(this,D,q,L)}}get locked(){if(!Rr(this))throw en("locked");return Or(this)}cancel(a=void 0){return Rr(this)?Or(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,a):f(en("cancel"))}getReader(a=void 0){if(!Rr(this))throw en("getReader");return l0(a,"First parameter").mode===void 0?U(this):Ud(this)}pipeThrough(a,d={}){if(!Rr(this))throw en("pipeThrough");Be(a,1,"pipeThrough");let C=p_(a,"First parameter"),D=df(d,"Second parameter");if(Or(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(_n(C.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=uf(this,C.writable,D.preventClose,D.preventAbort,D.preventCancel,D.signal);return g(L),C.readable}pipeTo(a,d={}){if(!Rr(this))return f(en("pipeTo"));if(a===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!yn(a))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let C;try{C=df(d,"Second parameter")}catch(D){return f(D)}return Or(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):_n(a)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):uf(this,a,C.preventClose,C.preventAbort,C.preventCancel,C.signal)}tee(){if(!Rr(this))throw en("tee");let a=e_(this);return ke(a)}values(a=void 0){if(!Rr(this))throw en("values");let d=f_(a,"First parameter");return hn(this,d.preventCancel)}[qa](a){return this.values(a)}static from(a){return s_(a)}}Object.defineProperties(Ye,{from:{enumerable:!0}}),Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Ye.from,"from"),s(Ye.prototype.cancel,"cancel"),s(Ye.prototype.getReader,"getReader"),s(Ye.prototype.pipeThrough,"pipeThrough"),s(Ye.prototype.pipeTo,"pipeTo"),s(Ye.prototype.tee,"tee"),s(Ye.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ye.prototype,qa,{value:Ye.prototype.values,writable:!0,configurable:!0});function gs(o,a,d,C=1,D=()=>1){let L=Object.create(Ye.prototype);cu(L);let q=Object.create(lr.prototype);return lf(L,q,o,a,d,C,D),L}function ff(o,a,d){let C=Object.create(Ye.prototype);cu(C);let D=Object.create(ur.prototype);return Md(C,D,o,a,d,0,void 0),C}function cu(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function Rr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof Ye}function Or(o){return o._reader!==void 0}function Pt(o,a){if(o._disturbed=!0,o._state==="closed")return h(void 0);if(o._state==="errored")return f(o._storedError);ys(o);let d=o._reader;if(d!==void 0&&Yr(d)){let D=d._readIntoRequests;d._readIntoRequests=new R,D.forEach(L=>{L._closeSteps(void 0)})}let C=o._readableStreamController[J](a);return y(C,e)}function ys(o){o._state="closed";let a=o._reader;if(a!==void 0&&(ae(a),Z(a))){let d=a._readRequests;a._readRequests=new R,d.forEach(C=>{C._closeSteps()})}}function hf(o,a){o._state="errored",o._storedError=a;let d=o._reader;d!==void 0&&(G(d,a),Z(d)?xe(d,a):Hd(d,a))}function en(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function pf(o,a){le(o,a);let d=o?.highWaterMark;return _(d,"highWaterMark","QueuingStrategyInit"),{highWaterMark:w(d)}}let mf=o=>o.byteLength;s(mf,"size");class To{constructor(a){Be(a,1,"ByteLengthQueuingStrategy"),a=pf(a,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!yf(this))throw gf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!yf(this))throw gf("size");return mf}}Object.defineProperties(To.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(To.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function gf(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function yf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof To}let _f=()=>1;s(_f,"size");class Do{constructor(a){Be(a,1,"CountQueuingStrategy"),a=pf(a,"First parameter"),this._countQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!Cf(this))throw bf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Cf(this))throw bf("size");return _f}}Object.defineProperties(Do.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Do.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function bf(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function Cf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof Do}function m_(o,a){le(o,a);let d=o?.cancel,C=o?.flush,D=o?.readableType,L=o?.start,q=o?.transform,Y=o?.writableType;return{cancel:d===void 0?void 0:b_(d,o,`${a} has member 'cancel' that`),flush:C===void 0?void 0:g_(C,o,`${a} has member 'flush' that`),readableType:D,start:L===void 0?void 0:y_(L,o,`${a} has member 'start' that`),transform:q===void 0?void 0:__(q,o,`${a} has member 'transform' that`),writableType:Y}}function g_(o,a,d){return _e(o,d),C=>b(o,a,[C])}function y_(o,a,d){return _e(o,d),C=>k(o,a,[C])}function __(o,a,d){return _e(o,d),(C,D)=>b(o,a,[C,D])}function b_(o,a,d){return _e(o,d),C=>b(o,a,[C])}class vo{constructor(a={},d={},C={}){a===void 0&&(a=null);let D=mo(d,"Second parameter"),L=mo(C,"Third parameter"),q=m_(a,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Y=fs(L,0),ce=po(L),ne=fs(D,1),fe=po(D),ye,ve=l(It=>{ye=It});C_(this,ve,ne,fe,Y,ce),E_(this,q),q.start!==void 0?ye(q.start(this._transformStreamController)):ye(void 0)}get readable(){if(!wf(this))throw kf("readable");return this._readable}get writable(){if(!wf(this))throw kf("writable");return this._writable}}Object.defineProperties(vo.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vo.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function C_(o,a,d,C,D,L){function q(){return a}function Y(ve){return k_(o,ve)}function ce(ve){return T_(o,ve)}function ne(){return D_(o)}o._writable=S0(q,Y,ne,ce,d,C);function fe(){return v_(o)}function ye(ve){return R_(o,ve)}o._readable=gs(q,fe,ye,D,L),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,Ro(o,!0),o._transformStreamController=void 0}function wf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof vo}function Ef(o,a){xt(o._readable._readableStreamController,a),lu(o,a)}function lu(o,a){Fo(o._transformStreamController),hs(o._writable._writableStreamController,a),du(o)}function du(o){o._backpressure&&Ro(o,!1)}function Ro(o,a){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=l(d=>{o._backpressureChangePromise_resolve=d}),o._backpressure=a}class Fr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Oo(this))throw xo("desiredSize");let a=this._controlledTransformStream._readable._readableStreamController;return uu(a)}enqueue(a=void 0){if(!Oo(this))throw xo("enqueue");Af(this,a)}error(a=void 0){if(!Oo(this))throw xo("error");A_(this,a)}terminate(){if(!Oo(this))throw xo("terminate");S_(this)}}Object.defineProperties(Fr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Fr.prototype.enqueue,"enqueue"),s(Fr.prototype.error,"error"),s(Fr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Oo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof Fr}function w_(o,a,d,C,D){a._controlledTransformStream=o,o._transformStreamController=a,a._transformAlgorithm=d,a._flushAlgorithm=C,a._cancelAlgorithm=D,a._finishPromise=void 0,a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0}function E_(o,a){let d=Object.create(Fr.prototype),C,D,L;a.transform!==void 0?C=q=>a.transform(q,d):C=q=>{try{return Af(d,q),h(void 0)}catch(Y){return f(Y)}},a.flush!==void 0?D=()=>a.flush(d):D=()=>h(void 0),a.cancel!==void 0?L=q=>a.cancel(q):L=()=>h(void 0),w_(o,d,C,D,L)}function Fo(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0,o._cancelAlgorithm=void 0}function Af(o,a){let d=o._controlledTransformStream,C=d._readable._readableStreamController;if(!wn(C))throw new TypeError("Readable side is not in a state that permits enqueue");try{Cn(C,a)}catch(L){throw lu(d,L),d._readable._storedError}Q0(C)!==d._backpressure&&Ro(d,!0)}function A_(o,a){Ef(o._controlledTransformStream,a)}function Sf(o,a){let d=o._transformAlgorithm(a);return y(d,void 0,C=>{throw Ef(o._controlledTransformStream,C),C})}function S_(o){let a=o._controlledTransformStream,d=a._readable._readableStreamController;Zr(d);let C=new TypeError("TransformStream terminated");lu(a,C)}function k_(o,a){let d=o._transformStreamController;if(o._backpressure){let C=o._backpressureChangePromise;return y(C,()=>{let D=o._writable;if(D._state==="erroring")throw D._storedError;return Sf(d,a)})}return Sf(d,a)}function T_(o,a){let d=o._transformStreamController;if(d._finishPromise!==void 0)return d._finishPromise;let C=o._readable;d._finishPromise=l((L,q)=>{d._finishPromise_resolve=L,d._finishPromise_reject=q});let D=d._cancelAlgorithm(a);return Fo(d),A(D,()=>(C._state==="errored"?En(d,C._storedError):(xt(C._readableStreamController,a),fu(d)),null),L=>(xt(C._readableStreamController,L),En(d,L),null)),d._finishPromise}function D_(o){let a=o._transformStreamController;if(a._finishPromise!==void 0)return a._finishPromise;let d=o._readable;a._finishPromise=l((D,L)=>{a._finishPromise_resolve=D,a._finishPromise_reject=L});let C=a._flushAlgorithm();return Fo(a),A(C,()=>(d._state==="errored"?En(a,d._storedError):(Zr(d._readableStreamController),fu(a)),null),D=>(xt(d._readableStreamController,D),En(a,D),null)),a._finishPromise}function v_(o){return Ro(o,!1),o._backpressureChangePromise}function R_(o,a){let d=o._transformStreamController;if(d._finishPromise!==void 0)return d._finishPromise;let C=o._writable;d._finishPromise=l((L,q)=>{d._finishPromise_resolve=L,d._finishPromise_reject=q});let D=d._cancelAlgorithm(a);return Fo(d),A(D,()=>(C._state==="errored"?En(d,C._storedError):(hs(C._writableStreamController,a),du(o),fu(d)),null),L=>(hs(C._writableStreamController,L),du(o),En(d,L),null)),d._finishPromise}function xo(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function fu(o){o._finishPromise_resolve!==void 0&&(o._finishPromise_resolve(),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function En(o,a){o._finishPromise_reject!==void 0&&(g(o._finishPromise),o._finishPromise_reject(a),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function kf(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=To,t.CountQueuingStrategy=Do,t.ReadableByteStreamController=ur,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Dr,t.ReadableStreamBYOBRequest=Jr,t.ReadableStreamDefaultController=lr,t.ReadableStreamDefaultReader=z,t.TransformStream=vo,t.TransformStreamDefaultController=Fr,t.WritableStream=vr,t.WritableStreamDefaultController=bn,t.WritableStreamDefaultWriter=cr}))});var $h=V(()=>{if(!globalThis.ReadableStream)try{let t=Q("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,Q("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,qh())}try{let{Blob:t}=Q("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,s=this;return new ReadableStream({type:"bytes",async pull(i){let c=await s.slice(n,Math.min(s.size,n+65536)).arrayBuffer();n+=c.byteLength,i.enqueue(new Uint8Array(c)),n===s.size&&i.close()}})})}catch{}});async function*qu(t,e=!0){for(let r of t)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(e){let n=r.byteOffset,s=r.byteOffset+r.byteLength;for(;n!==s;){let i=Math.min(s-n,zh),u=r.buffer.slice(n,n+i);n+=u.byteLength,yield new Uint8Array(u)}}else yield r;else{let n=0,s=r;for(;n!==s.size;){let u=await s.slice(n,Math.min(s.size,n+zh)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var Dv,zh,Hh,tC,Bt,Es=je(()=>{Dv=Pr($h(),1);zh=65536;Hh=class $u{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],r={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!="object"&&typeof r!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");r===null&&(r={});let n=new TextEncoder;for(let i of e){let u;ArrayBuffer.isView(i)?u=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)):i instanceof ArrayBuffer?u=new Uint8Array(i.slice(0)):i instanceof $u?u=i:u=n.encode(`${i}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let s=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of qu(this.#e,!1))r+=e.decode(n,{stream:!0});return r+=e.decode(),r}async arrayBuffer(){let e=new Uint8Array(this.size),r=0;for await(let n of qu(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=qu(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await e.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,r=this.size,n=""){let{size:s}=this,i=e<0?Math.max(s+e,0):Math.min(e,s),u=r<0?Math.max(s+r,0):Math.min(r,s),c=Math.max(u-i,0),l=this.#e,h=[],f=0;for(let A of l){if(f>=c)break;let v=ArrayBuffer.isView(A)?A.byteLength:A.size;if(i&&v<=i)i-=v,u-=v;else{let S;ArrayBuffer.isView(A)?(S=A.subarray(i,Math.min(v,u)),f+=S.byteLength):(S=A.slice(i,Math.min(v,u)),f+=S.size),u-=v,h.push(S),i=0}}let p=new $u([],{type:String(n).toLowerCase()});return p.#r=c,p.#e=h,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Hh.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});tC=Hh,Bt=tC});var rC,nC,Br,zu=je(()=>{Es();rC=class extends Bt{#e=0;#t="";constructor(e,r,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let s=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(s)||(this.#e=s),this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Bt&&/^(File)$/.test(e[Symbol.toStringTag])}},nC=rC,Br=nC});function Jh(t,e=Bt){var r=`${Wh()}${Wh()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r
27
27
  Content-Disposition: form-data; name="`;return t.forEach((i,u)=>typeof i=="string"?n.push(s+Hu(u)+`"\r
28
28
  \r
29
29
  ${i.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
@@ -32,216 +32,216 @@ ${i.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
32
32
  Content-Type: ${i.type||"application/octet-stream"}\r
33
33
  \r
34
34
  `,i,`\r
35
- `)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var As,nC,sC,Wh,oC,Gh,Hu,sn,jr,ri=je(()=>{Es();zu();({toStringTag:As,iterator:nC,hasInstance:sC}=Symbol),Wh=Math.random,oC="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Gh=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[As])?[(r=r!==void 0?r+"":e[As]=="File"?e.name:"blob",t),e.name!==r||e[As]=="blob"?new Br([e],r,e):e]:[t,e+""]),Hu=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),sn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},jr=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[As](){return"FormData"}[nC](){return this.entries()}static[sC](e){return e&&typeof e=="object"&&e[As]==="FormData"&&!oC.some(r=>typeof e[r]!="function")}append(...e){sn("append",arguments,2),this.#e.push(Gh(...e))}delete(e){sn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){sn("get",arguments,1),e+="";for(var r=this.#e,n=r.length,s=0;s<n;s++)if(r[s][0]===e)return r[s][1];return null}getAll(e,r){return sn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return sn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){sn("forEach",arguments,1);for(var[n,s]of this)e.call(r,s,n,this)}set(...e){sn("set",arguments,2);var r=[],n=!0;e=Gh(...e),this.#e.forEach(s=>{s[0]===e[0]?n&&(n=!r.push(e)):r.push(s)}),n&&r.push(e),this.#e=r}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var gr,ni=je(()=>{gr=class extends Error{constructor(e,r){super(e),Error.captureStackTrace(this,this.constructor),this.type=r}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var et,Wu=je(()=>{ni();et=class extends gr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var si,Gu,Ss,Vh,Kh,Yh,oi=je(()=>{si=Symbol.toStringTag,Gu=t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[si]==="URLSearchParams",Ss=t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[si]),Vh=t=>typeof t=="object"&&(t[si]==="AbortSignal"||t[si]==="EventTarget"),Kh=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Yh=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Qh=J((Lv,Xh)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=Q("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Xh.exports=globalThis.DOMException});import{statSync as Zh,createReadStream as iC,promises as aC}from"node:fs";import{basename as uC}from"node:path";var ep,Ju,tp,rp,np,sp,op,ip,ii,Vu=je(()=>{ep=Pr(Qh(),1);zu();Es();({stat:Ju}=aC),tp=(t,e)=>op(Zh(t),t,e),rp=(t,e)=>Ju(t).then(r=>op(r,t,e)),np=(t,e)=>Ju(t).then(r=>ip(r,t,e)),sp=(t,e)=>ip(Zh(t),t,e),op=(t,e,r="")=>new Bt([new ii({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),ip=(t,e,r="")=>new Br([new ii({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],uC(e),{type:r,lastModified:t.mtimeMs}),ii=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#e,lastModified:this.lastModified,size:r-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await Ju(this.#e);if(e>this.lastModified)throw new ep.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*iC(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var up={};Df(up,{toFormData:()=>mC});function pC(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let r=e[2]||e[3]||"",n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(s,i)=>String.fromCharCode(i)),n}async function mC(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new Ku(r[1]||r[2]),s,i,u,c,l,h,f=[],p=new jr,S=m=>{u+=g.decode(m,{stream:!0})},D=m=>{f.push(m)},E=()=>{let m=new Br(f,h,{type:l});p.append(c,m)},y=()=>{p.append(c,u)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=S,n.onPartEnd=y,s="",i="",u="",c="",l="",h=null,f.length=0},n.onHeaderField=function(m){s+=g.decode(m,{stream:!0})},n.onHeaderValue=function(m){i+=g.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(i+=g.decode(),s=s.toLowerCase(),s==="content-disposition"){let m=i.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),h=pC(i),h&&(n.onPartData=D,n.onPartEnd=E)}else s==="content-type"&&(l=i);i="",s=""};for await(let m of t)n.write(m);return n.end(),p}var Vt,Fe,ap,Lr,ai,ui,cC,ks,lC,dC,fC,hC,on,Ku,cp=je(()=>{Vu();ri();Vt=0,Fe={START_BOUNDARY:Vt++,HEADER_FIELD_START:Vt++,HEADER_FIELD:Vt++,HEADER_VALUE_START:Vt++,HEADER_VALUE:Vt++,HEADER_VALUE_ALMOST_DONE:Vt++,HEADERS_ALMOST_DONE:Vt++,PART_DATA_START:Vt++,PART_DATA:Vt++,END:Vt++},ap=1,Lr={PART_BOUNDARY:ap,LAST_BOUNDARY:ap*=2},ai=10,ui=13,cC=32,ks=45,lC=58,dC=97,fC=122,hC=t=>t|32,on=()=>{},Ku=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=on,this.onHeaderField=on,this.onHeadersEnd=on,this.onHeaderValue=on,this.onPartBegin=on,this.onPartData=on,this.onPartEnd=on,this.boundaryChars={},e=`\r
37
- --`+e;let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n),this.boundaryChars[r[n]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let r=0,n=e.length,s=this.index,{lookbehind:i,boundary:u,boundaryChars:c,index:l,state:h,flags:f}=this,p=this.boundary.length,S=p-1,D=e.length,E,y,g=w=>{this[w+"Mark"]=r},m=w=>{delete this[w+"Mark"]},T=(w,O,x,$)=>{(O===void 0||O!==x)&&this[w]($&&$.subarray(O,x))},b=(w,O)=>{let x=w+"Mark";x in this&&(O?(T(w,this[x],r,e),delete this[x]):(T(w,this[x],e.length,e),this[x]=0))};for(r=0;r<n;r++)switch(E=e[r],h){case Fe.START_BOUNDARY:if(l===u.length-2){if(E===ks)f|=Lr.LAST_BOUNDARY;else if(E!==ui)return;l++;break}else if(l-1===u.length-2){if(f&Lr.LAST_BOUNDARY&&E===ks)h=Fe.END,f=0;else if(!(f&Lr.LAST_BOUNDARY)&&E===ai)l=0,T("onPartBegin"),h=Fe.HEADER_FIELD_START;else return;break}E!==u[l+2]&&(l=-2),E===u[l+2]&&l++;break;case Fe.HEADER_FIELD_START:h=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(E===ui){m("onHeaderField"),h=Fe.HEADERS_ALMOST_DONE;break}if(l++,E===ks)break;if(E===lC){if(l===1)return;b("onHeaderField",!0),h=Fe.HEADER_VALUE_START;break}if(y=hC(E),y<dC||y>fC)return;break;case Fe.HEADER_VALUE_START:if(E===cC)break;g("onHeaderValue"),h=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:E===ui&&(b("onHeaderValue",!0),T("onHeaderEnd"),h=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(E!==ai)return;h=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(E!==ai)return;T("onHeadersEnd"),h=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:h=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(s=l,l===0){for(r+=S;r<D&&!(e[r]in c);)r+=p;r-=S,E=e[r]}if(l<u.length)u[l]===E?(l===0&&b("onPartData",!0),l++):l=0;else if(l===u.length)l++,E===ui?f|=Lr.PART_BOUNDARY:E===ks?f|=Lr.LAST_BOUNDARY:l=0;else if(l-1===u.length)if(f&Lr.PART_BOUNDARY){if(l=0,E===ai){f&=~Lr.PART_BOUNDARY,T("onPartEnd"),T("onPartBegin"),h=Fe.HEADER_FIELD_START;break}}else f&Lr.LAST_BOUNDARY&&E===ks?(T("onPartEnd"),h=Fe.END,f=0):l=0;if(l>0)i[l-1]=E;else if(s>0){let w=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);T("onPartData",0,s,w),s=0,g("onPartData"),r--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=l,this.state=h,this.flags=f}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Mr,{PassThrough as lp}from"node:stream";import{types as dp,deprecate as Xu,promisify as gC}from"node:util";import{Buffer as St}from"node:buffer";async function Yu(t){if(t[it].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[it].disturbed=!0,t[it].error)throw t[it].error;let{body:e}=t;if(e===null)return St.alloc(0);if(!(e instanceof Mr))return St.alloc(0);let r=[],n=0;try{for await(let s of e){if(t.size>0&&n+s.length>t.size){let i=new et(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(i),i}n+=s.length,r.push(s)}}catch(s){throw s instanceof gr?s:new et(`Invalid response body while trying to fetch ${t.url}: ${s.message}`,"system",s)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(s=>typeof s=="string")?St.from(r.join("")):St.concat(r,n)}catch(s){throw new et(`Could not create Buffer from response body for ${t.url}: ${s.message}`,"system",s)}else throw new et(`Premature close of server response while trying to fetch ${t.url}`)}var yC,it,Kt,Nn,_C,ci,fp,hp,li=je(()=>{Es();ri();Wu();ni();oi();yC=gC(Mr.pipeline),it=Symbol("Body internals"),Kt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:Gu(e)?e=St.from(e.toString()):Ss(e)||St.isBuffer(e)||(dp.isAnyArrayBuffer(e)?e=St.from(e):ArrayBuffer.isView(e)?e=St.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mr||(e instanceof jr?(e=Jh(e),n=e.type.split("=")[1]):e=St.from(String(e))));let s=e;St.isBuffer(e)?s=Mr.Readable.from(e):Ss(e)&&(s=Mr.Readable.from(e.stream())),this[it]={body:e,stream:s,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Mr&&e.on("error",i=>{let u=i instanceof gr?i:new et(`Invalid response body while trying to fetch ${this.url}: ${i.message}`,"system",i);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:n}=await Yu(this);return e.slice(r,r+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new jr,s=new URLSearchParams(await this.text());for(let[i,u]of s)n.append(i,u);return n}let{toFormData:r}=await Promise.resolve().then(()=>(cp(),up));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",r=await this.arrayBuffer();return new Bt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Yu(this);return new TextDecoder().decode(e)}buffer(){return Yu(this)}};Kt.prototype.buffer=Xu(Kt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Kt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Xu(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Nn=(t,e)=>{let r,n,{body:s}=t[it];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return s instanceof Mr&&typeof s.getBoundary!="function"&&(r=new lp({highWaterMark:e}),n=new lp({highWaterMark:e}),s.pipe(r),s.pipe(n),t[it].stream=r,s=n),s},_C=Xu(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ci=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Gu(t)?"application/x-www-form-urlencoded;charset=UTF-8":Ss(t)?t.type||null:St.isBuffer(t)||dp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof jr?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${_C(t)}`:t instanceof Mr?null:"text/plain;charset=UTF-8",fp=t=>{let{body:e}=t[it];return e===null?0:Ss(e)?e.size:St.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},hp=async(t,{body:e})=>{e===null?t.end():await yC(e,t)}});import{types as pp}from"node:util";import fi from"node:http";function mp(t=[]){return new at(t.reduce((e,r,n,s)=>(n%2===0&&e.push(s.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return di(e),Qu(e,String(r)),!0}catch{return!1}}))}var di,Qu,at,hi=je(()=>{di=typeof fi.validateHeaderName=="function"?fi.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Qu=typeof fi.validateHeaderValue=="function"?fi.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let r=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}},at=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[s,i]of Object.entries(n))r.push(...i.map(u=>[s,u]))}else if(e!=null)if(typeof e=="object"&&!pp.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)r.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");r=[...e].map(s=>{if(typeof s!="object"||pp.isBoxedPrimitive(s))throw new TypeError("Each header pair must be an iterable object");return[...s]}).map(s=>{if(s.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...s]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return r=r.length>0?r.map(([n,s])=>(di(n),Qu(n,String(s)),[String(n).toLowerCase(),String(s)])):void 0,super(r),new Proxy(this,{get(n,s,i){switch(s){case"append":case"set":return(u,c)=>(di(u),Qu(u,String(c)),URLSearchParams.prototype[s].call(n,String(u).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return u=>(di(u),URLSearchParams.prototype[s].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,s,i)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let n=r.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,r=void 0){for(let n of this.keys())Reflect.apply(e,r,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let n=this.getAll(r);return r==="host"?e[r]=n[0]:e[r]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var bC,Ts,Zu=je(()=>{bC=new Set([301,302,303,307,308]),Ts=t=>bC.has(t)});var jt,dt,gp=je(()=>{hi();li();Zu();jt=Symbol("Response internals"),dt=class t extends Kt{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,s=new at(r.headers);if(e!==null&&!s.has("Content-Type")){let i=ci(e,this);i&&s.append("Content-Type",i)}this[jt]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:s,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[jt].type}get url(){return this[jt].url||""}get status(){return this[jt].status}get ok(){return this[jt].status>=200&&this[jt].status<300}get redirected(){return this[jt].counter>0}get statusText(){return this[jt].statusText}get headers(){return this[jt].headers}get highWaterMark(){return this[jt].highWaterMark}clone(){return new t(Nn(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,r=302){if(!Ts(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new t(null,{status:0,statusText:""});return e[jt].type="error",e}static json(e=void 0,r={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let s=new at(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new t(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(dt.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var yp,_p=je(()=>{yp=t=>{if(t.search)return t.search;let e=t.href.length-1,r=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-r.length]==="?"?"?":""}});import{isIP as CC}from"node:net";function bp(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function Ep(t){if(!Cp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function wC(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=CC(e);return r===4&&/^127\./.test(e)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Bn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:wC(t)}function Ap(t,{referrerURLCallback:e,referrerOriginCallback:r}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let n=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let s=t.referrer,i=bp(s),u=bp(s,!0);i.toString().length>4096&&(i=u),e&&(i=e(i)),r&&(u=r(u));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return i;case"strict-origin":return Bn(i)&&!Bn(c)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return i.origin===c.origin?i:Bn(i)&&!Bn(c)?"no-referrer":u;case"same-origin":return i.origin===c.origin?i:"no-referrer";case"origin-when-cross-origin":return i.origin===c.origin?i:u;case"no-referrer-when-downgrade":return Bn(i)&&!Bn(c)?"no-referrer":i;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function Sp(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&Cp.has(n)&&(r=n);return r}var Cp,wp,ec=je(()=>{Cp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),wp="strict-origin-when-cross-origin"});import{format as EC}from"node:url";import{deprecate as AC}from"node:util";var Ge,Ds,SC,Ur,kp,Tp=je(()=>{hi();li();oi();_p();ec();Ge=Symbol("Request internals"),Ds=t=>typeof t=="object"&&typeof t[Ge]=="object",SC=AC(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Ur=class t extends Kt{constructor(e,r={}){let n;if(Ds(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let s=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(s)&&(s=s.toUpperCase()),!Ds(r)&&"data"in r&&SC(),(r.body!=null||Ds(e)&&e.body!==null)&&(s==="GET"||s==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let i=r.body?r.body:Ds(e)&&e.body!==null?Nn(e):null;super(i,{size:r.size||e.size||0});let u=new at(r.headers||e.headers||{});if(i!==null&&!u.has("Content-Type")){let h=ci(i,this);h&&u.set("Content-Type",h)}let c=Ds(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Vh(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=r.referrer==null?e.referrer:r.referrer;if(l==="")l="no-referrer";else if(l){let h=new URL(l);l=/^about:(\/\/)?client$/.test(h)?"client":h}else l=void 0;this[Ge]={method:s,redirect:r.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:c,referrer:l},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ge].method}get url(){return EC(this[Ge].parsedURL)}get headers(){return this[Ge].headers}get redirect(){return this[Ge].redirect}get signal(){return this[Ge].signal}get referrer(){if(this[Ge].referrer==="no-referrer")return"";if(this[Ge].referrer==="client")return"about:client";if(this[Ge].referrer)return this[Ge].referrer.toString()}get referrerPolicy(){return this[Ge].referrerPolicy}set referrerPolicy(e){this[Ge].referrerPolicy=Ep(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Ur.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});kp=t=>{let{parsedURL:e}=t[Ge],r=new at(t[Ge].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(n="0"),t.body!==null){let c=fp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=wp),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=Ap(t):t[Ge].referrer="no-referrer",t[Ge].referrer instanceof URL&&r.set("Referer",t.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),t.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=t;typeof s=="function"&&(s=s(e));let i=yp(e),u={path:e.pathname+i,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:s};return{parsedURL:e,options:u}}});var vs,Dp=je(()=>{ni();vs=class extends gr{constructor(e,r="aborted"){super(e,r)}}});var Op={};Df(Op,{AbortError:()=>vs,Blob:()=>Bt,FetchError:()=>et,File:()=>Br,FormData:()=>jr,Headers:()=>at,Request:()=>Ur,Response:()=>dt,blobFrom:()=>rp,blobFromSync:()=>tp,default:()=>tc,fileFrom:()=>np,fileFromSync:()=>sp,isRedirect:()=>Ts});import kC from"node:http";import TC from"node:https";import jn from"node:zlib";import vp,{PassThrough as Rp,pipeline as Ln}from"node:stream";import{Buffer as pi}from"node:buffer";async function tc(t,e){return new Promise((r,n)=>{let s=new Ur(t,e),{parsedURL:i,options:u}=kp(s);if(!DC.has(i.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let E=Lh(s.url),y=new dt(E,{headers:{"Content-Type":E.typeFull}});r(y);return}let c=(i.protocol==="https:"?TC:kC).request,{signal:l}=s,h=null,f=()=>{let E=new vs("The operation was aborted.");n(E),s.body&&s.body instanceof vp.Readable&&s.body.destroy(E),!(!h||!h.body)&&h.body.emit("error",E)};if(l&&l.aborted){f();return}let p=()=>{f(),D()},S=c(i.toString(),u);l&&l.addEventListener("abort",p);let D=()=>{S.abort(),l&&l.removeEventListener("abort",p)};S.on("error",E=>{n(new et(`request to ${s.url} failed, reason: ${E.message}`,"system",E)),D()}),vC(S,E=>{h&&h.body&&h.body.destroy(E)}),process.version<"v14"&&S.on("socket",E=>{let y;E.prependListener("end",()=>{y=E._eventsCount}),E.prependListener("close",g=>{if(h&&y<E._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",h.body.emit("error",m)}})}),S.on("response",E=>{S.setTimeout(0);let y=mp(E.rawHeaders);if(Ts(E.statusCode)){let w=y.get("Location"),O=null;try{O=w===null?null:new URL(w,s.url)}catch{if(s.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${w}`,"invalid-redirect")),D();return}}switch(s.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${s.url}`,"no-redirect")),D();return;case"manual":break;case"follow":{if(O===null)break;if(s.counter>=s.follow){n(new et(`maximum redirect reached at: ${s.url}`,"max-redirect")),D();return}let x={headers:new at(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:Nn(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!Kh(s.url,O)||!Yh(s.url,O))for(let V of["authorization","www-authenticate","cookie","cookie2"])x.headers.delete(V);if(E.statusCode!==303&&s.body&&e.body instanceof vp.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),D();return}(E.statusCode===303||(E.statusCode===301||E.statusCode===302)&&s.method==="POST")&&(x.method="GET",x.body=void 0,x.headers.delete("content-length"));let $=Sp(y);$&&(x.referrerPolicy=$),r(tc(new Ur(O,x))),D();return}default:return n(new TypeError(`Redirect option '${s.redirect}' is not a valid value of RequestRedirect`))}}l&&E.once("end",()=>{l.removeEventListener("abort",p)});let g=Ln(E,new Rp,w=>{w&&n(w)});process.version<"v12.10"&&E.on("aborted",p);let m={url:s.url,status:E.statusCode,statusText:E.statusMessage,headers:y,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},T=y.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||T===null||E.statusCode===204||E.statusCode===304){h=new dt(g,m),r(h);return}let b={flush:jn.Z_SYNC_FLUSH,finishFlush:jn.Z_SYNC_FLUSH};if(T==="gzip"||T==="x-gzip"){g=Ln(g,jn.createGunzip(b),w=>{w&&n(w)}),h=new dt(g,m),r(h);return}if(T==="deflate"||T==="x-deflate"){let w=Ln(E,new Rp,O=>{O&&n(O)});w.once("data",O=>{(O[0]&15)===8?g=Ln(g,jn.createInflate(),x=>{x&&n(x)}):g=Ln(g,jn.createInflateRaw(),x=>{x&&n(x)}),h=new dt(g,m),r(h)}),w.once("end",()=>{h||(h=new dt(g,m),r(h))});return}if(T==="br"){g=Ln(g,jn.createBrotliDecompress(),w=>{w&&n(w)}),h=new dt(g,m),r(h);return}h=new dt(g,m),r(h)}),hp(S,s).catch(n)})}function vC(t,e){let r=pi.from(`0\r
35
+ `)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var As,sC,oC,Wh,iC,Gh,Hu,sn,jr,ri=je(()=>{Es();zu();({toStringTag:As,iterator:sC,hasInstance:oC}=Symbol),Wh=Math.random,iC="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Gh=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[As])?[(r=r!==void 0?r+"":e[As]=="File"?e.name:"blob",t),e.name!==r||e[As]=="blob"?new Br([e],r,e):e]:[t,e+""]),Hu=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),sn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},jr=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[As](){return"FormData"}[sC](){return this.entries()}static[oC](e){return e&&typeof e=="object"&&e[As]==="FormData"&&!iC.some(r=>typeof e[r]!="function")}append(...e){sn("append",arguments,2),this.#e.push(Gh(...e))}delete(e){sn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){sn("get",arguments,1),e+="";for(var r=this.#e,n=r.length,s=0;s<n;s++)if(r[s][0]===e)return r[s][1];return null}getAll(e,r){return sn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return sn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){sn("forEach",arguments,1);for(var[n,s]of this)e.call(r,s,n,this)}set(...e){sn("set",arguments,2);var r=[],n=!0;e=Gh(...e),this.#e.forEach(s=>{s[0]===e[0]?n&&(n=!r.push(e)):r.push(s)}),n&&r.push(e),this.#e=r}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var gr,ni=je(()=>{gr=class extends Error{constructor(e,r){super(e),Error.captureStackTrace(this,this.constructor),this.type=r}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var et,Wu=je(()=>{ni();et=class extends gr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var si,Gu,Ss,Vh,Kh,Yh,oi=je(()=>{si=Symbol.toStringTag,Gu=t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[si]==="URLSearchParams",Ss=t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[si]),Vh=t=>typeof t=="object"&&(t[si]==="AbortSignal"||t[si]==="EventTarget"),Kh=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Yh=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Qh=V((Uv,Xh)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=Q("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Xh.exports=globalThis.DOMException});import{statSync as Zh,createReadStream as aC,promises as uC}from"node:fs";import{basename as cC}from"node:path";var ep,Ju,tp,rp,np,sp,op,ip,ii,Vu=je(()=>{ep=Pr(Qh(),1);zu();Es();({stat:Ju}=uC),tp=(t,e)=>op(Zh(t),t,e),rp=(t,e)=>Ju(t).then(r=>op(r,t,e)),np=(t,e)=>Ju(t).then(r=>ip(r,t,e)),sp=(t,e)=>ip(Zh(t),t,e),op=(t,e,r="")=>new Bt([new ii({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),ip=(t,e,r="")=>new Br([new ii({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],cC(e),{type:r,lastModified:t.mtimeMs}),ii=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#e,lastModified:this.lastModified,size:r-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await Ju(this.#e);if(e>this.lastModified)throw new ep.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*aC(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var up={};Df(up,{toFormData:()=>gC});function mC(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let r=e[2]||e[3]||"",n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(s,i)=>String.fromCharCode(i)),n}async function gC(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new Ku(r[1]||r[2]),s,i,u,c,l,h,f=[],p=new jr,A=m=>{u+=g.decode(m,{stream:!0})},v=m=>{f.push(m)},S=()=>{let m=new Br(f,h,{type:l});p.append(c,m)},y=()=>{p.append(c,u)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=A,n.onPartEnd=y,s="",i="",u="",c="",l="",h=null,f.length=0},n.onHeaderField=function(m){s+=g.decode(m,{stream:!0})},n.onHeaderValue=function(m){i+=g.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(i+=g.decode(),s=s.toLowerCase(),s==="content-disposition"){let m=i.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),h=mC(i),h&&(n.onPartData=v,n.onPartEnd=S)}else s==="content-type"&&(l=i);i="",s=""};for await(let m of t)n.write(m);return n.end(),p}var Vt,Fe,ap,Lr,ai,ui,lC,ks,dC,fC,hC,pC,on,Ku,cp=je(()=>{Vu();ri();Vt=0,Fe={START_BOUNDARY:Vt++,HEADER_FIELD_START:Vt++,HEADER_FIELD:Vt++,HEADER_VALUE_START:Vt++,HEADER_VALUE:Vt++,HEADER_VALUE_ALMOST_DONE:Vt++,HEADERS_ALMOST_DONE:Vt++,PART_DATA_START:Vt++,PART_DATA:Vt++,END:Vt++},ap=1,Lr={PART_BOUNDARY:ap,LAST_BOUNDARY:ap*=2},ai=10,ui=13,lC=32,ks=45,dC=58,fC=97,hC=122,pC=t=>t|32,on=()=>{},Ku=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=on,this.onHeaderField=on,this.onHeadersEnd=on,this.onHeaderValue=on,this.onPartBegin=on,this.onPartData=on,this.onPartEnd=on,this.boundaryChars={},e=`\r
37
+ --`+e;let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n),this.boundaryChars[r[n]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let r=0,n=e.length,s=this.index,{lookbehind:i,boundary:u,boundaryChars:c,index:l,state:h,flags:f}=this,p=this.boundary.length,A=p-1,v=e.length,S,y,g=E=>{this[E+"Mark"]=r},m=E=>{delete this[E+"Mark"]},k=(E,R,x,$)=>{(R===void 0||R!==x)&&this[E]($&&$.subarray(R,x))},b=(E,R)=>{let x=E+"Mark";x in this&&(R?(k(E,this[x],r,e),delete this[x]):(k(E,this[x],e.length,e),this[x]=0))};for(r=0;r<n;r++)switch(S=e[r],h){case Fe.START_BOUNDARY:if(l===u.length-2){if(S===ks)f|=Lr.LAST_BOUNDARY;else if(S!==ui)return;l++;break}else if(l-1===u.length-2){if(f&Lr.LAST_BOUNDARY&&S===ks)h=Fe.END,f=0;else if(!(f&Lr.LAST_BOUNDARY)&&S===ai)l=0,k("onPartBegin"),h=Fe.HEADER_FIELD_START;else return;break}S!==u[l+2]&&(l=-2),S===u[l+2]&&l++;break;case Fe.HEADER_FIELD_START:h=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(S===ui){m("onHeaderField"),h=Fe.HEADERS_ALMOST_DONE;break}if(l++,S===ks)break;if(S===dC){if(l===1)return;b("onHeaderField",!0),h=Fe.HEADER_VALUE_START;break}if(y=pC(S),y<fC||y>hC)return;break;case Fe.HEADER_VALUE_START:if(S===lC)break;g("onHeaderValue"),h=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:S===ui&&(b("onHeaderValue",!0),k("onHeaderEnd"),h=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(S!==ai)return;h=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(S!==ai)return;k("onHeadersEnd"),h=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:h=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(s=l,l===0){for(r+=A;r<v&&!(e[r]in c);)r+=p;r-=A,S=e[r]}if(l<u.length)u[l]===S?(l===0&&b("onPartData",!0),l++):l=0;else if(l===u.length)l++,S===ui?f|=Lr.PART_BOUNDARY:S===ks?f|=Lr.LAST_BOUNDARY:l=0;else if(l-1===u.length)if(f&Lr.PART_BOUNDARY){if(l=0,S===ai){f&=~Lr.PART_BOUNDARY,k("onPartEnd"),k("onPartBegin"),h=Fe.HEADER_FIELD_START;break}}else f&Lr.LAST_BOUNDARY&&S===ks?(k("onPartEnd"),h=Fe.END,f=0):l=0;if(l>0)i[l-1]=S;else if(s>0){let E=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);k("onPartData",0,s,E),s=0,g("onPartData"),r--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=l,this.state=h,this.flags=f}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Mr,{PassThrough as lp}from"node:stream";import{types as dp,deprecate as Xu,promisify as yC}from"node:util";import{Buffer as St}from"node:buffer";async function Yu(t){if(t[it].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[it].disturbed=!0,t[it].error)throw t[it].error;let{body:e}=t;if(e===null)return St.alloc(0);if(!(e instanceof Mr))return St.alloc(0);let r=[],n=0;try{for await(let s of e){if(t.size>0&&n+s.length>t.size){let i=new et(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(i),i}n+=s.length,r.push(s)}}catch(s){throw s instanceof gr?s:new et(`Invalid response body while trying to fetch ${t.url}: ${s.message}`,"system",s)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(s=>typeof s=="string")?St.from(r.join("")):St.concat(r,n)}catch(s){throw new et(`Could not create Buffer from response body for ${t.url}: ${s.message}`,"system",s)}else throw new et(`Premature close of server response while trying to fetch ${t.url}`)}var _C,it,Kt,Nn,bC,ci,fp,hp,li=je(()=>{Es();ri();Wu();ni();oi();_C=yC(Mr.pipeline),it=Symbol("Body internals"),Kt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:Gu(e)?e=St.from(e.toString()):Ss(e)||St.isBuffer(e)||(dp.isAnyArrayBuffer(e)?e=St.from(e):ArrayBuffer.isView(e)?e=St.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mr||(e instanceof jr?(e=Jh(e),n=e.type.split("=")[1]):e=St.from(String(e))));let s=e;St.isBuffer(e)?s=Mr.Readable.from(e):Ss(e)&&(s=Mr.Readable.from(e.stream())),this[it]={body:e,stream:s,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Mr&&e.on("error",i=>{let u=i instanceof gr?i:new et(`Invalid response body while trying to fetch ${this.url}: ${i.message}`,"system",i);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:n}=await Yu(this);return e.slice(r,r+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new jr,s=new URLSearchParams(await this.text());for(let[i,u]of s)n.append(i,u);return n}let{toFormData:r}=await Promise.resolve().then(()=>(cp(),up));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",r=await this.arrayBuffer();return new Bt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Yu(this);return new TextDecoder().decode(e)}buffer(){return Yu(this)}};Kt.prototype.buffer=Xu(Kt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Kt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Xu(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Nn=(t,e)=>{let r,n,{body:s}=t[it];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return s instanceof Mr&&typeof s.getBoundary!="function"&&(r=new lp({highWaterMark:e}),n=new lp({highWaterMark:e}),s.pipe(r),s.pipe(n),t[it].stream=r,s=n),s},bC=Xu(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ci=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Gu(t)?"application/x-www-form-urlencoded;charset=UTF-8":Ss(t)?t.type||null:St.isBuffer(t)||dp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof jr?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${bC(t)}`:t instanceof Mr?null:"text/plain;charset=UTF-8",fp=t=>{let{body:e}=t[it];return e===null?0:Ss(e)?e.size:St.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},hp=async(t,{body:e})=>{e===null?t.end():await _C(e,t)}});import{types as pp}from"node:util";import fi from"node:http";function mp(t=[]){return new at(t.reduce((e,r,n,s)=>(n%2===0&&e.push(s.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return di(e),Qu(e,String(r)),!0}catch{return!1}}))}var di,Qu,at,hi=je(()=>{di=typeof fi.validateHeaderName=="function"?fi.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Qu=typeof fi.validateHeaderValue=="function"?fi.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let r=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}},at=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[s,i]of Object.entries(n))r.push(...i.map(u=>[s,u]))}else if(e!=null)if(typeof e=="object"&&!pp.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)r.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");r=[...e].map(s=>{if(typeof s!="object"||pp.isBoxedPrimitive(s))throw new TypeError("Each header pair must be an iterable object");return[...s]}).map(s=>{if(s.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...s]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return r=r.length>0?r.map(([n,s])=>(di(n),Qu(n,String(s)),[String(n).toLowerCase(),String(s)])):void 0,super(r),new Proxy(this,{get(n,s,i){switch(s){case"append":case"set":return(u,c)=>(di(u),Qu(u,String(c)),URLSearchParams.prototype[s].call(n,String(u).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return u=>(di(u),URLSearchParams.prototype[s].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,s,i)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let n=r.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,r=void 0){for(let n of this.keys())Reflect.apply(e,r,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let n=this.getAll(r);return r==="host"?e[r]=n[0]:e[r]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var CC,Ts,Zu=je(()=>{CC=new Set([301,302,303,307,308]),Ts=t=>CC.has(t)});var jt,dt,gp=je(()=>{hi();li();Zu();jt=Symbol("Response internals"),dt=class t extends Kt{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,s=new at(r.headers);if(e!==null&&!s.has("Content-Type")){let i=ci(e,this);i&&s.append("Content-Type",i)}this[jt]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:s,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[jt].type}get url(){return this[jt].url||""}get status(){return this[jt].status}get ok(){return this[jt].status>=200&&this[jt].status<300}get redirected(){return this[jt].counter>0}get statusText(){return this[jt].statusText}get headers(){return this[jt].headers}get highWaterMark(){return this[jt].highWaterMark}clone(){return new t(Nn(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,r=302){if(!Ts(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new t(null,{status:0,statusText:""});return e[jt].type="error",e}static json(e=void 0,r={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let s=new at(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new t(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(dt.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var yp,_p=je(()=>{yp=t=>{if(t.search)return t.search;let e=t.href.length-1,r=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-r.length]==="?"?"?":""}});import{isIP as wC}from"node:net";function bp(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function Ep(t){if(!Cp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function EC(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=wC(e);return r===4&&/^127\./.test(e)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Bn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:EC(t)}function Ap(t,{referrerURLCallback:e,referrerOriginCallback:r}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let n=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let s=t.referrer,i=bp(s),u=bp(s,!0);i.toString().length>4096&&(i=u),e&&(i=e(i)),r&&(u=r(u));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return i;case"strict-origin":return Bn(i)&&!Bn(c)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return i.origin===c.origin?i:Bn(i)&&!Bn(c)?"no-referrer":u;case"same-origin":return i.origin===c.origin?i:"no-referrer";case"origin-when-cross-origin":return i.origin===c.origin?i:u;case"no-referrer-when-downgrade":return Bn(i)&&!Bn(c)?"no-referrer":i;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function Sp(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&Cp.has(n)&&(r=n);return r}var Cp,wp,ec=je(()=>{Cp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),wp="strict-origin-when-cross-origin"});import{format as AC}from"node:url";import{deprecate as SC}from"node:util";var Ge,Ds,kC,Ur,kp,Tp=je(()=>{hi();li();oi();_p();ec();Ge=Symbol("Request internals"),Ds=t=>typeof t=="object"&&typeof t[Ge]=="object",kC=SC(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Ur=class t extends Kt{constructor(e,r={}){let n;if(Ds(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let s=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(s)&&(s=s.toUpperCase()),!Ds(r)&&"data"in r&&kC(),(r.body!=null||Ds(e)&&e.body!==null)&&(s==="GET"||s==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let i=r.body?r.body:Ds(e)&&e.body!==null?Nn(e):null;super(i,{size:r.size||e.size||0});let u=new at(r.headers||e.headers||{});if(i!==null&&!u.has("Content-Type")){let h=ci(i,this);h&&u.set("Content-Type",h)}let c=Ds(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Vh(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=r.referrer==null?e.referrer:r.referrer;if(l==="")l="no-referrer";else if(l){let h=new URL(l);l=/^about:(\/\/)?client$/.test(h)?"client":h}else l=void 0;this[Ge]={method:s,redirect:r.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:c,referrer:l},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ge].method}get url(){return AC(this[Ge].parsedURL)}get headers(){return this[Ge].headers}get redirect(){return this[Ge].redirect}get signal(){return this[Ge].signal}get referrer(){if(this[Ge].referrer==="no-referrer")return"";if(this[Ge].referrer==="client")return"about:client";if(this[Ge].referrer)return this[Ge].referrer.toString()}get referrerPolicy(){return this[Ge].referrerPolicy}set referrerPolicy(e){this[Ge].referrerPolicy=Ep(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Ur.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});kp=t=>{let{parsedURL:e}=t[Ge],r=new at(t[Ge].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(n="0"),t.body!==null){let c=fp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=wp),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=Ap(t):t[Ge].referrer="no-referrer",t[Ge].referrer instanceof URL&&r.set("Referer",t.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),t.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=t;typeof s=="function"&&(s=s(e));let i=yp(e),u={path:e.pathname+i,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:s};return{parsedURL:e,options:u}}});var vs,Dp=je(()=>{ni();vs=class extends gr{constructor(e,r="aborted"){super(e,r)}}});var Op={};Df(Op,{AbortError:()=>vs,Blob:()=>Bt,FetchError:()=>et,File:()=>Br,FormData:()=>jr,Headers:()=>at,Request:()=>Ur,Response:()=>dt,blobFrom:()=>rp,blobFromSync:()=>tp,default:()=>tc,fileFrom:()=>np,fileFromSync:()=>sp,isRedirect:()=>Ts});import TC from"node:http";import DC from"node:https";import jn from"node:zlib";import vp,{PassThrough as Rp,pipeline as Ln}from"node:stream";import{Buffer as pi}from"node:buffer";async function tc(t,e){return new Promise((r,n)=>{let s=new Ur(t,e),{parsedURL:i,options:u}=kp(s);if(!vC.has(i.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let S=Lh(s.url),y=new dt(S,{headers:{"Content-Type":S.typeFull}});r(y);return}let c=(i.protocol==="https:"?DC:TC).request,{signal:l}=s,h=null,f=()=>{let S=new vs("The operation was aborted.");n(S),s.body&&s.body instanceof vp.Readable&&s.body.destroy(S),!(!h||!h.body)&&h.body.emit("error",S)};if(l&&l.aborted){f();return}let p=()=>{f(),v()},A=c(i.toString(),u);l&&l.addEventListener("abort",p);let v=()=>{A.abort(),l&&l.removeEventListener("abort",p)};A.on("error",S=>{n(new et(`request to ${s.url} failed, reason: ${S.message}`,"system",S)),v()}),RC(A,S=>{h&&h.body&&h.body.destroy(S)}),process.version<"v14"&&A.on("socket",S=>{let y;S.prependListener("end",()=>{y=S._eventsCount}),S.prependListener("close",g=>{if(h&&y<S._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",h.body.emit("error",m)}})}),A.on("response",S=>{A.setTimeout(0);let y=mp(S.rawHeaders);if(Ts(S.statusCode)){let E=y.get("Location"),R=null;try{R=E===null?null:new URL(E,s.url)}catch{if(s.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),v();return}}switch(s.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${s.url}`,"no-redirect")),v();return;case"manual":break;case"follow":{if(R===null)break;if(s.counter>=s.follow){n(new et(`maximum redirect reached at: ${s.url}`,"max-redirect")),v();return}let x={headers:new at(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:Nn(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!Kh(s.url,R)||!Yh(s.url,R))for(let J of["authorization","www-authenticate","cookie","cookie2"])x.headers.delete(J);if(S.statusCode!==303&&s.body&&e.body instanceof vp.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),v();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&s.method==="POST")&&(x.method="GET",x.body=void 0,x.headers.delete("content-length"));let $=Sp(y);$&&(x.referrerPolicy=$),r(tc(new Ur(R,x))),v();return}default:return n(new TypeError(`Redirect option '${s.redirect}' is not a valid value of RequestRedirect`))}}l&&S.once("end",()=>{l.removeEventListener("abort",p)});let g=Ln(S,new Rp,E=>{E&&n(E)});process.version<"v12.10"&&S.on("aborted",p);let m={url:s.url,status:S.statusCode,statusText:S.statusMessage,headers:y,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},k=y.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||k===null||S.statusCode===204||S.statusCode===304){h=new dt(g,m),r(h);return}let b={flush:jn.Z_SYNC_FLUSH,finishFlush:jn.Z_SYNC_FLUSH};if(k==="gzip"||k==="x-gzip"){g=Ln(g,jn.createGunzip(b),E=>{E&&n(E)}),h=new dt(g,m),r(h);return}if(k==="deflate"||k==="x-deflate"){let E=Ln(S,new Rp,R=>{R&&n(R)});E.once("data",R=>{(R[0]&15)===8?g=Ln(g,jn.createInflate(),x=>{x&&n(x)}):g=Ln(g,jn.createInflateRaw(),x=>{x&&n(x)}),h=new dt(g,m),r(h)}),E.once("end",()=>{h||(h=new dt(g,m),r(h))});return}if(k==="br"){g=Ln(g,jn.createBrotliDecompress(),E=>{E&&n(E)}),h=new dt(g,m),r(h);return}h=new dt(g,m),r(h)}),hp(A,s).catch(n)})}function RC(t,e){let r=pi.from(`0\r
38
38
  \r
39
- `),n=!1,s=!1,i;t.on("response",u=>{let{headers:c}=u;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",u=>{let c=()=>{if(n&&!s){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},l=h=>{s=pi.compare(h.slice(-5),r)===0,!s&&i&&(s=pi.compare(i.slice(-3),r.slice(0,3))===0&&pi.compare(h.slice(-2),r.slice(3))===0),i=h};u.prependListener("close",c),u.on("data",l),t.on("close",()=>{u.removeListener("close",c),u.removeListener("data",l)})})}var DC,Fp=je(()=>{Mh();li();gp();hi();Tp();Wu();Dp();Zu();ri();oi();ec();Vu();DC=new Set(["data:","http:","https:"])});var Ip=J(Un=>{"use strict";var RC=Un&&Un.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Mn;Object.defineProperty(Un,"__esModule",{value:!0});Un.Gaxios=void 0;var OC=RC(vu()),FC=Q("https"),an=Fu(),xC=fh(),xp=Q("stream"),Pp=Iu(),PC=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),mi=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Pp.GaxiosInterceptorManager,response:new Pp.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Mn.mergeHeaders(i,r.headers),n&&Mn.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await Mn.#u(),n={...e};delete n.data;let s=await r(e.url,n),i=await this.getResponseData(e,s);return Object.getOwnPropertyDescriptor(s,"data")?.configurable||Object.defineProperties(s,{data:{configurable:!0,writable:!0,enumerable:!0,value:i}}),Object.assign(s,{config:e,data:i})}async _request(e){try{let r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let s=[];for await(let i of r.data)s.push(i);r.data=s.toString()}let n=an.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new an.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof an.GaxiosError?n=r:r instanceof Error?n=new an.GaxiosError(r.message,e,void 0,r):n=new an.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:s,config:i}=await(0,xC.getRetryConfig)(n);if(s&&i)return n.config.retryConfig.currentRetryAttempt=i.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new an.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":return r.json();case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),s=[...r],i=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let u of i)s.push(u.trim());for(let u of s)if(u instanceof RegExp){if(u.test(n.toString()))return!1}else if(u instanceof URL){if(u.origin===n.origin)return!1}else if(u.startsWith("*.")||u.startsWith(".")){let c=u.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(u===n.origin||u===n.hostname||u===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);Mn.mergeHeaders(r,e.headers);let n=(0,OC.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let u=n.paramsSerializer(n.params);u.startsWith("?")&&(u=u.slice(1));let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+u}else{let u=n.url instanceof URL?n.url:new URL(n.url);for(let[c,l]of new URLSearchParams(n.params))u.searchParams.append(c,l);n.url=u}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let s=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof xp.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let u=await PC();r.set("content-type",`multipart/related; boundary=${u}`),n.body=xp.Readable.from(this.getMultipartRequest(n.multipart,u))}else s?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let i=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(i&&this.#e(n.url,n.noProxy)){let u=await Mn.#a();this.agentCache.has(i)?n.agent=this.agentCache.get(i):(n.agent=new u(i,{cert:n.cert,key:n.key}),this.agentCache.set(i,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new FC.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=an.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#s(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#s(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let s of e){let i=s.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
39
+ `),n=!1,s=!1,i;t.on("response",u=>{let{headers:c}=u;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",u=>{let c=()=>{if(n&&!s){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},l=h=>{s=pi.compare(h.slice(-5),r)===0,!s&&i&&(s=pi.compare(i.slice(-3),r.slice(0,3))===0&&pi.compare(h.slice(-2),r.slice(3))===0),i=h};u.prependListener("close",c),u.on("data",l),t.on("close",()=>{u.removeListener("close",c),u.removeListener("data",l)})})}var vC,Fp=je(()=>{Mh();li();gp();hi();Tp();Wu();Dp();Zu();ri();oi();ec();Vu();vC=new Set(["data:","http:","https:"])});var Ip=V(Un=>{"use strict";var OC=Un&&Un.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Mn;Object.defineProperty(Un,"__esModule",{value:!0});Un.Gaxios=void 0;var FC=OC(vu()),xC=Q("https"),an=Fu(),PC=fh(),xp=Q("stream"),Pp=Iu(),IC=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),mi=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Pp.GaxiosInterceptorManager,response:new Pp.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Mn.mergeHeaders(i,r.headers),n&&Mn.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await Mn.#u(),n={...e};delete n.data;let s=await r(e.url,n),i=await this.getResponseData(e,s);return Object.getOwnPropertyDescriptor(s,"data")?.configurable||Object.defineProperties(s,{data:{configurable:!0,writable:!0,enumerable:!0,value:i}}),Object.assign(s,{config:e,data:i})}async _request(e){try{let r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let s=[];for await(let i of r.data)s.push(i);r.data=s.toString()}let n=an.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new an.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof an.GaxiosError?n=r:r instanceof Error?n=new an.GaxiosError(r.message,e,void 0,r):n=new an.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:s,config:i}=await(0,PC.getRetryConfig)(n);if(s&&i)return n.config.retryConfig.currentRetryAttempt=i.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new an.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":return r.json();case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),s=[...r],i=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let u of i)s.push(u.trim());for(let u of s)if(u instanceof RegExp){if(u.test(n.toString()))return!1}else if(u instanceof URL){if(u.origin===n.origin)return!1}else if(u.startsWith("*.")||u.startsWith(".")){let c=u.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(u===n.origin||u===n.hostname||u===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);Mn.mergeHeaders(r,e.headers);let n=(0,FC.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let u=n.paramsSerializer(n.params);u.startsWith("?")&&(u=u.slice(1));let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+u}else{let u=n.url instanceof URL?n.url:new URL(n.url);for(let[c,l]of new URLSearchParams(n.params))u.searchParams.append(c,l);n.url=u}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let s=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof xp.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let u=await IC();r.set("content-type",`multipart/related; boundary=${u}`),n.body=xp.Readable.from(this.getMultipartRequest(n.multipart,u))}else s?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let i=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(i&&this.#e(n.url,n.noProxy)){let u=await Mn.#a();this.agentCache.has(i)?n.agent=this.agentCache.get(i):(n.agent=new u(i,{cert:n.cert,key:n.key}),this.agentCache.set(i,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new xC.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=an.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#s(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#s(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let s of e){let i=s.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
40
40
  Content-Type: ${i}\r
41
41
  \r
42
42
  `,typeof s.content=="string"?yield s.content:yield*s.content,yield`\r
43
- `}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Pr(jh()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Fp(),Op))).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((i,u)=>{u==="set-cookie"?e.append(u,i):e.set(u,i)});return e}};Un.Gaxios=mi;Mn=mi});var Ve=J(tt=>{"use strict";var IC=tt&&tt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),NC=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&IC(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=jC;var Np=Ip();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return Np.Gaxios}});var BC=Fu();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return BC.GaxiosError}});NC(Iu(),tt);tt.instance=new Np.Gaxios;async function jC(t){return tt.instance.request(t)}});var rc=J((Bp,gi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,s=Math.floor,i="[BigNumber Error] ",u=i+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,h=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,S=1e9;function D(O){var x,$,V,U=W.prototype={constructor:W,toString:null,valueOf:null},X=new W(1),ne=20,ae=4,de=-7,ye=21,Ae=-1e7,oe=1e7,pe=!1,G=1,K=0,ue={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",De=!0;function W(_,A){var k,B,F,I,M,R,P,j,N=this;if(!(N instanceof W))return new W(_,A);if(A==null){if(_&&_._isBigNumber===!0){N.s=_.s,!_.c||_.e>oe?N.c=N.e=null:_.e<Ae?N.c=[N.e=0]:(N.e=_.e,N.c=_.c.slice());return}if((R=typeof _=="number")&&_*0==0){if(N.s=1/_<0?(_=-_,-1):1,_===~~_){for(I=0,M=_;M>=10;M/=10,I++);I>oe?N.c=N.e=null:(N.e=I,N.c=[_]);return}j=String(_)}else{if(!r.test(j=String(_)))return V(N,j,R);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(M=j.search(/e/i))>0?(I<0&&(I=M),I+=+j.slice(M+1),j=j.substring(0,M)):I<0&&(I=j.length)}else{if(m(A,2,qe.length,"Base"),A==10&&De)return N=new W(_),Re(N,ne+N.e+1,ae);if(j=String(_),R=typeof _=="number"){if(_*0!=0)return V(N,j,R,A);if(N.s=1/_<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(u+_)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(k=qe.slice(0,A),I=M=0,P=j.length;M<P;M++)if(k.indexOf(B=j.charAt(M))<0){if(B=="."){if(M>I){I=P;continue}}else if(!F&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){F=!0,M=-1,I=0;continue}return V(N,String(_),R,A)}R=!1,j=$(j,A,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(M=0;j.charCodeAt(M)===48;M++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(M,++P)){if(P-=M,R&&W.DEBUG&&P>15&&(_>h||_!==s(_)))throw Error(u+N.s*_);if((I=I-M-1)>oe)N.c=N.e=null;else if(I<Ae)N.c=[N.e=0];else{if(N.e=I,N.c=[],M=(I+1)%l,I<0&&(M+=l),M<P){for(M&&N.c.push(+j.slice(0,M)),P-=l;M<P;)N.c.push(+j.slice(M,M+=l));M=l-(j=j.slice(M)).length}else M-=P;for(;M--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=D,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(_){var A,k;if(_!=null)if(typeof _=="object"){if(_.hasOwnProperty(A="DECIMAL_PLACES")&&(k=_[A],m(k,0,S,A),ne=k),_.hasOwnProperty(A="ROUNDING_MODE")&&(k=_[A],m(k,0,8,A),ae=k),_.hasOwnProperty(A="EXPONENTIAL_AT")&&(k=_[A],k&&k.pop?(m(k[0],-S,0,A),m(k[1],0,S,A),de=k[0],ye=k[1]):(m(k,-S,S,A),de=-(ye=k<0?-k:k))),_.hasOwnProperty(A="RANGE"))if(k=_[A],k&&k.pop)m(k[0],-S,-1,A),m(k[1],1,S,A),Ae=k[0],oe=k[1];else if(m(k,-S,S,A),k)Ae=-(oe=k<0?-k:k);else throw Error(i+A+" cannot be zero: "+k);if(_.hasOwnProperty(A="CRYPTO"))if(k=_[A],k===!!k)if(k)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=k;else throw pe=!k,Error(i+"crypto unavailable");else pe=k;else throw Error(i+A+" not true or false: "+k);if(_.hasOwnProperty(A="MODULO_MODE")&&(k=_[A],m(k,0,9,A),G=k),_.hasOwnProperty(A="POW_PRECISION")&&(k=_[A],m(k,0,S,A),K=k),_.hasOwnProperty(A="FORMAT"))if(k=_[A],typeof k=="object")ue=k;else throw Error(i+A+" not an object: "+k);if(_.hasOwnProperty(A="ALPHABET"))if(k=_[A],typeof k=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(k))De=k.slice(0,10)=="0123456789",qe=k;else throw Error(i+A+" invalid: "+k)}else throw Error(i+"Object expected: "+_);return{DECIMAL_PLACES:ne,ROUNDING_MODE:ae,EXPONENTIAL_AT:[de,ye],RANGE:[Ae,oe],CRYPTO:pe,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ue,ALPHABET:qe}},W.isBigNumber=function(_){if(!_||_._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var A,k,B=_.c,F=_.e,I=_.s;e:if({}.toString.call(B)=="[object Array]"){if((I===1||I===-1)&&F>=-S&&F<=S&&F===s(F)){if(B[0]===0){if(F===0&&B.length===1)return!0;break e}if(A=(F+1)%l,A<1&&(A+=l),String(B[0]).length==A){for(A=0;A<B.length;A++)if(k=B[A],k<0||k>=c||k!==s(k))break e;if(k!==0)return!0}}}else if(B===null&&F===null&&(I===null||I===1||I===-1))return!0;throw Error(i+"Invalid BigNumber: "+_)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var _=9007199254740992,A=Math.random()*_&2097151?function(){return s(Math.random()*_)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(k){var B,F,I,M,R,P=0,j=[],N=new W(X);if(k==null?k=ne:m(k,0,S),M=n(k/l),pe)if(crypto.getRandomValues){for(B=crypto.getRandomValues(new Uint32Array(M*=2));P<M;)R=B[P]*131072+(B[P+1]>>>11),R>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),B[P]=F[0],B[P+1]=F[1]):(j.push(R%1e14),P+=2);P=M/2}else if(crypto.randomBytes){for(B=crypto.randomBytes(M*=7);P<M;)R=(B[P]&31)*281474976710656+B[P+1]*1099511627776+B[P+2]*4294967296+B[P+3]*16777216+(B[P+4]<<16)+(B[P+5]<<8)+B[P+6],R>=9e15?crypto.randomBytes(7).copy(B,P):(j.push(R%1e14),P+=7);P=M/7}else throw pe=!1,Error(i+"crypto unavailable");if(!pe)for(;P<M;)R=A(),R<9e15&&(j[P++]=R%1e14);for(M=j[--P],k%=l,M&&k&&(R=f[l-k],j[P]=s(M/R)*R);j[P]===0;j.pop(),P--);if(P<0)j=[I=0];else{for(I=-1;j[0]===0;j.splice(0,1),I-=l);for(P=1,R=j[0];R>=10;R/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var _=1,A=arguments,k=new W(A[0]);_<A.length;)k=k.plus(A[_++]);return k},$=(function(){var _="0123456789";function A(k,B,F,I){for(var M,R=[0],P,j=0,N=k.length;j<N;){for(P=R.length;P--;R[P]*=B);for(R[0]+=I.indexOf(k.charAt(j++)),M=0;M<R.length;M++)R[M]>F-1&&(R[M+1]==null&&(R[M+1]=0),R[M+1]+=R[M]/F|0,R[M]%=F)}return R.reverse()}return function(k,B,F,I,M){var R,P,j,N,z,Z,ee,Ee,xe=k.indexOf("."),Ne=ne,we=ae;for(xe>=0&&(N=K,K=0,k=k.replace(".",""),Ee=new W(B),Z=Ee.pow(k.length-xe),K=N,Ee.c=A(w(y(Z.c),Z.e,"0"),10,F,_),Ee.e=Ee.c.length),ee=A(k,B,F,M?(R=qe,_):(R=_,qe)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return R.charAt(0);if(xe<0?--j:(Z.c=ee,Z.e=j,Z.s=I,Z=x(Z,Ee,Ne,we,F),ee=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,xe=ee[P],N=F/2,z=z||P<0||ee[P+1]!=null,z=we<4?(xe!=null||z)&&(we==0||we==(Z.s<0?3:2)):xe>N||xe==N&&(we==4||z||we==6&&ee[P-1]&1||we==(Z.s<0?8:7)),P<1||!ee[0])k=z?w(R.charAt(1),-Ne,R.charAt(0)):R.charAt(0);else{if(ee.length=P,z)for(--F;++ee[--P]>F;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(xe=0,k="";xe<=N;k+=R.charAt(ee[xe++]));k=w(k,j,R.charAt(0))}return k}})(),x=(function(){function _(B,F,I){var M,R,P,j,N=0,z=B.length,Z=F%p,ee=F/p|0;for(B=B.slice();z--;)P=B[z]%p,j=B[z]/p|0,M=ee*P+j*Z,R=Z*P+M%p*p+N,N=(R/I|0)+(M/p|0)+ee*j,B[z]=R%I;return N&&(B=[N].concat(B)),B}function A(B,F,I,M){var R,P;if(I!=M)P=I>M?1:-1;else for(R=P=0;R<I;R++)if(B[R]!=F[R]){P=B[R]>F[R]?1:-1;break}return P}function k(B,F,I,M){for(var R=0;I--;)B[I]-=R,R=B[I]<F[I]?1:0,B[I]=R*M+B[I]-F[I];for(;!B[0]&&B.length>1;B.splice(0,1));}return function(B,F,I,M,R){var P,j,N,z,Z,ee,Ee,xe,Ne,we,Se,Me,hn,pn,mn,ut,ir,Ke=B.s==F.s?1:-1,Ue=B.c,ke=F.c;if(!Ue||!Ue[0]||!ke||!ke[0])return new W(!B.s||!F.s||(Ue?ke&&Ue[0]==ke[0]:!ke)?NaN:Ue&&Ue[0]==0||!ke?Ke*0:Ke/0);for(xe=new W(Ke),Ne=xe.c=[],j=B.e-F.e,Ke=I+j+1,R||(R=c,j=E(B.e/l)-E(F.e/l),Ke=Ke/l|0),N=0;ke[N]==(Ue[N]||0);N++);if(ke[N]>(Ue[N]||0)&&j--,Ke<0)Ne.push(1),z=!0;else{for(pn=Ue.length,ut=ke.length,N=0,Ke+=2,Z=s(R/(ke[0]+1)),Z>1&&(ke=_(ke,Z,R),Ue=_(Ue,Z,R),ut=ke.length,pn=Ue.length),hn=ut,we=Ue.slice(0,ut),Se=we.length;Se<ut;we[Se++]=0);ir=ke.slice(),ir=[0].concat(ir),mn=ke[0],ke[1]>=R/2&&mn++;do{if(Z=0,P=A(ke,we,ut,Se),P<0){if(Me=we[0],ut!=Se&&(Me=Me*R+(we[1]||0)),Z=s(Me/mn),Z>1)for(Z>=R&&(Z=R-1),ee=_(ke,Z,R),Ee=ee.length,Se=we.length;A(ee,we,Ee,Se)==1;)Z--,k(ee,ut<Ee?ir:ke,Ee,R),Ee=ee.length,P=1;else Z==0&&(P=Z=1),ee=ke.slice(),Ee=ee.length;if(Ee<Se&&(ee=[0].concat(ee)),k(we,ee,Se,R),Se=we.length,P==-1)for(;A(ke,we,ut,Se)<1;)Z++,k(we,ut<Se?ir:ke,Se,R),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=Ue[hn]||0:(we=[Ue[hn]],Se=1)}while((hn++<pn||we[0]!=null)&&Ke--);z=we[0]!=null,Ne[0]||Ne.splice(0,1)}if(R==c){for(N=1,Ke=Ne[0];Ke>=10;Ke/=10,N++);Re(xe,I+(xe.e=N+j*l-1)+1,M,z)}else xe.e=j,xe.r=+z;return xe}})();function le(_,A,k,B){var F,I,M,R,P;if(k==null?k=ae:m(k,0,8),!_.c)return _.toString();if(F=_.c[0],M=_.e,A==null)P=y(_.c),P=B==1||B==2&&(M<=de||M>=ye)?b(P,M):w(P,M,"0");else if(_=Re(new W(_),A,k),I=_.e,P=y(_.c),R=P.length,B==1||B==2&&(A<=I||I<=de)){for(;R<A;P+="0",R++);P=b(P,I)}else if(A-=M+(B===2&&I>M),P=w(P,I,"0"),I+1>R){if(--A>0)for(P+=".";A--;P+="0");}else if(A+=I-R,A>0)for(I+1==R&&(P+=".");A--;P+="0");return _.s<0&&F?"-"+P:P}function _e(_,A){for(var k,B,F=1,I=new W(_[0]);F<_.length;F++)B=new W(_[F]),(!B.s||(k=g(I,B))===A||k===0&&I.s===A)&&(I=B);return I}function Ft(_,A,k){for(var B=1,F=A.length;!A[--F];A.pop());for(F=A[0];F>=10;F/=10,B++);return(k=B+k*l-1)>oe?_.c=_.e=null:k<Ae?_.c=[_.e=0]:(_.e=k,_.c=A),_}V=(function(){var _=/^(-?)0([xbo])(?=\w[\w.]*$)/i,A=/^([^.]+)\.$/,k=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,M,R,P){var j,N=R?M:M.replace(F,"");if(B.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!R&&(N=N.replace(_,function(z,Z,ee){return j=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!P||P==j?Z:z}),P&&(j=P,N=N.replace(A,"$1").replace(k,"0.$1")),M!=N))return new W(N,j);if(W.DEBUG)throw Error(i+"Not a"+(P?" base "+P:"")+" number: "+M);I.s=null}I.c=I.e=null}})();function Re(_,A,k,B){var F,I,M,R,P,j,N,z=_.c,Z=f;if(z){e:{for(F=1,R=z[0];R>=10;R/=10,F++);if(I=A-F,I<0)I+=l,M=A,P=z[j=0],N=s(P/Z[F-M-1]%10);else if(j=n((I+1)/l),j>=z.length)if(B){for(;z.length<=j;z.push(0));P=N=0,F=1,I%=l,M=I-l+1}else break e;else{for(P=R=z[j],F=1;R>=10;R/=10,F++);I%=l,M=I-l+F,N=M<0?0:s(P/Z[F-M-1]%10)}if(B=B||A<0||z[j+1]!=null||(M<0?P:P%Z[F-M-1]),B=k<4?(N||B)&&(k==0||k==(_.s<0?3:2)):N>5||N==5&&(k==4||B||k==6&&(I>0?M>0?P/Z[F-M]:0:z[j-1])%10&1||k==(_.s<0?8:7)),A<1||!z[0])return z.length=0,B?(A-=_.e+1,z[0]=Z[(l-A%l)%l],_.e=-A||0):z[0]=_.e=0,_;if(I==0?(z.length=j,R=1,j--):(z.length=j+1,R=Z[l-I],z[j]=M>0?s(P/Z[F-M]%Z[M])*R:0),B)for(;;)if(j==0){for(I=1,M=z[0];M>=10;M/=10,I++);for(M=z[0]+=R,R=1;M>=10;M/=10,R++);I!=R&&(_.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=R,z[j]!=c)break;z[j--]=0,R=1}for(I=z.length;z[--I]===0;z.pop());}_.e>oe?_.c=_.e=null:_.e<Ae&&(_.c=[_.e=0])}return _}function Be(_){var A,k=_.e;return k===null?_.toString():(A=y(_.c),A=k<=de||k>=ye?b(A,k):w(A,k,"0"),_.s<0?"-"+A:A)}return U.absoluteValue=U.abs=function(){var _=new W(this);return _.s<0&&(_.s=1),_},U.comparedTo=function(_,A){return g(this,new W(_,A))},U.decimalPlaces=U.dp=function(_,A){var k,B,F,I=this;if(_!=null)return m(_,0,S),A==null?A=ae:m(A,0,8),Re(new W(I),_+I.e+1,A);if(!(k=I.c))return null;if(B=((F=k.length-1)-E(this.e/l))*l,F=k[F])for(;F%10==0;F/=10,B--);return B<0&&(B=0),B},U.dividedBy=U.div=function(_,A){return x(this,new W(_,A),ne,ae)},U.dividedToIntegerBy=U.idiv=function(_,A){return x(this,new W(_,A),0,1)},U.exponentiatedBy=U.pow=function(_,A){var k,B,F,I,M,R,P,j,N,z=this;if(_=new W(_),_.c&&!_.isInteger())throw Error(i+"Exponent not an integer: "+Be(_));if(A!=null&&(A=new W(A)),R=_.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!_.c||!_.c[0])return N=new W(Math.pow(+Be(z),R?_.s*(2-T(_)):+Be(_))),A?N.mod(A):N;if(P=_.s<0,A){if(A.c?!A.c[0]:!A.s)return new W(NaN);B=!P&&z.isInteger()&&A.isInteger(),B&&(z=z.mod(A))}else{if(_.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||R&&z.c[1]>=24e7:z.c[0]<8e13||R&&z.c[0]<=9999975e7)))return I=z.s<0&&T(_)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(R?(k=new W(.5),P&&(_.s=1),j=T(_)):(F=Math.abs(+Be(_)),j=F%2),N=new W(X);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):B&&(N=N.mod(A))}if(F){if(F=s(F/2),F===0)break;j=F%2}else if(_=_.times(k),Re(_,_.e+1,1),_.e>14)j=T(_);else{if(F=+Be(_),F===0)break;j=F%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):B&&(z=z.mod(A))}return B?N:(P&&(N=X.div(N)),A?N.mod(A):I?Re(N,K,ae,M):N)},U.integerValue=function(_){var A=new W(this);return _==null?_=ae:m(_,0,8),Re(A,A.e+1,_)},U.isEqualTo=U.eq=function(_,A){return g(this,new W(_,A))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(_,A){return g(this,new W(_,A))>0},U.isGreaterThanOrEqualTo=U.gte=function(_,A){return(A=g(this,new W(_,A)))===1||A===0},U.isInteger=function(){return!!this.c&&E(this.e/l)>this.c.length-2},U.isLessThan=U.lt=function(_,A){return g(this,new W(_,A))<0},U.isLessThanOrEqualTo=U.lte=function(_,A){return(A=g(this,new W(_,A)))===-1||A===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(_,A){var k,B,F,I,M=this,R=M.s;if(_=new W(_,A),A=_.s,!R||!A)return new W(NaN);if(R!=A)return _.s=-A,M.plus(_);var P=M.e/l,j=_.e/l,N=M.c,z=_.c;if(!P||!j){if(!N||!z)return N?(_.s=-A,_):new W(z?M:NaN);if(!N[0]||!z[0])return z[0]?(_.s=-A,_):new W(N[0]?M:ae==3?-0:0)}if(P=E(P),j=E(j),N=N.slice(),R=P-j){for((I=R<0)?(R=-R,F=N):(j=P,F=z),F.reverse(),A=R;A--;F.push(0));F.reverse()}else for(B=(I=(R=N.length)<(A=z.length))?R:A,R=A=0;A<B;A++)if(N[A]!=z[A]){I=N[A]<z[A];break}if(I&&(F=N,N=z,z=F,_.s=-_.s),A=(B=z.length)-(k=N.length),A>0)for(;A--;N[k++]=0);for(A=c-1;B>R;){if(N[--B]<z[B]){for(k=B;k&&!N[--k];N[k]=A);--N[k],N[B]+=c}N[B]-=z[B]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?Ft(_,N,j):(_.s=ae==3?-1:1,_.c=[_.e=0],_)},U.modulo=U.mod=function(_,A){var k,B,F=this;return _=new W(_,A),!F.c||!_.s||_.c&&!_.c[0]?new W(NaN):!_.c||F.c&&!F.c[0]?new W(F):(G==9?(B=_.s,_.s=1,k=x(F,_,0,3),_.s=B,k.s*=B):k=x(F,_,0,G),_=F.minus(k.times(_)),!_.c[0]&&G==1&&(_.s=F.s),_)},U.multipliedBy=U.times=function(_,A){var k,B,F,I,M,R,P,j,N,z,Z,ee,Ee,xe,Ne,we=this,Se=we.c,Me=(_=new W(_,A)).c;if(!Se||!Me||!Se[0]||!Me[0])return!we.s||!_.s||Se&&!Se[0]&&!Me||Me&&!Me[0]&&!Se?_.c=_.e=_.s=null:(_.s*=we.s,!Se||!Me?_.c=_.e=null:(_.c=[0],_.e=0)),_;for(B=E(we.e/l)+E(_.e/l),_.s*=we.s,P=Se.length,z=Me.length,P<z&&(Ee=Se,Se=Me,Me=Ee,F=P,P=z,z=F),F=P+z,Ee=[];F--;Ee.push(0));for(xe=c,Ne=p,F=z;--F>=0;){for(k=0,Z=Me[F]%Ne,ee=Me[F]/Ne|0,M=P,I=F+M;I>F;)j=Se[--M]%Ne,N=Se[M]/Ne|0,R=ee*j+N*Z,j=Z*j+R%Ne*Ne+Ee[I]+k,k=(j/xe|0)+(R/Ne|0)+ee*N,Ee[I--]=j%xe;Ee[I]=k}return k?++B:Ee.splice(0,1),Ft(_,Ee,B)},U.negated=function(){var _=new W(this);return _.s=-_.s||null,_},U.plus=function(_,A){var k,B=this,F=B.s;if(_=new W(_,A),A=_.s,!F||!A)return new W(NaN);if(F!=A)return _.s=-A,B.minus(_);var I=B.e/l,M=_.e/l,R=B.c,P=_.c;if(!I||!M){if(!R||!P)return new W(F/0);if(!R[0]||!P[0])return P[0]?_:new W(R[0]?B:F*0)}if(I=E(I),M=E(M),R=R.slice(),F=I-M){for(F>0?(M=I,k=P):(F=-F,k=R),k.reverse();F--;k.push(0));k.reverse()}for(F=R.length,A=P.length,F-A<0&&(k=P,P=R,R=k,A=F),F=0;A;)F=(R[--A]=R[A]+P[A]+F)/c|0,R[A]=c===R[A]?0:R[A]%c;return F&&(R=[F].concat(R),++M),Ft(_,R,M)},U.precision=U.sd=function(_,A){var k,B,F,I=this;if(_!=null&&_!==!!_)return m(_,1,S),A==null?A=ae:m(A,0,8),Re(new W(I),_,A);if(!(k=I.c))return null;if(F=k.length-1,B=F*l+1,F=k[F]){for(;F%10==0;F/=10,B--);for(F=k[0];F>=10;F/=10,B++);}return _&&I.e+1>B&&(B=I.e+1),B},U.shiftedBy=function(_){return m(_,-h,h),this.times("1e"+_)},U.squareRoot=U.sqrt=function(){var _,A,k,B,F,I=this,M=I.c,R=I.s,P=I.e,j=ne+4,N=new W("0.5");if(R!==1||!M||!M[0])return new W(!R||R<0&&(!M||M[0])?NaN:M?I:1/0);if(R=Math.sqrt(+Be(I)),R==0||R==1/0?(A=y(M),(A.length+P)%2==0&&(A+="0"),R=Math.sqrt(+A),P=E((P+1)/2)-(P<0||P%2),R==1/0?A="5e"+P:(A=R.toExponential(),A=A.slice(0,A.indexOf("e")+1)+P),k=new W(A)):k=new W(R+""),k.c[0]){for(P=k.e,R=P+j,R<3&&(R=0);;)if(F=k,k=N.times(F.plus(x(I,F,j,1))),y(F.c).slice(0,R)===(A=y(k.c)).slice(0,R))if(k.e<P&&--R,A=A.slice(R-3,R+1),A=="9999"||!B&&A=="4999"){if(!B&&(Re(F,F.e+ne+2,0),F.times(F).eq(I))){k=F;break}j+=4,R+=4,B=1}else{(!+A||!+A.slice(1)&&A.charAt(0)=="5")&&(Re(k,k.e+ne+2,1),_=!k.times(k).eq(I));break}}return Re(k,k.e+ne+1,ae,_)},U.toExponential=function(_,A){return _!=null&&(m(_,0,S),_++),le(this,_,A,1)},U.toFixed=function(_,A){return _!=null&&(m(_,0,S),_=_+this.e+1),le(this,_,A)},U.toFormat=function(_,A,k){var B,F=this;if(k==null)_!=null&&A&&typeof A=="object"?(k=A,A=null):_&&typeof _=="object"?(k=_,_=A=null):k=ue;else if(typeof k!="object")throw Error(i+"Argument not an object: "+k);if(B=F.toFixed(_,A),F.c){var I,M=B.split("."),R=+k.groupSize,P=+k.secondaryGroupSize,j=k.groupSeparator||"",N=M[0],z=M[1],Z=F.s<0,ee=Z?N.slice(1):N,Ee=ee.length;if(P&&(I=R,R=P,P=I,Ee-=I),R>0&&Ee>0){for(I=Ee%R||R,N=ee.substr(0,I);I<Ee;I+=R)N+=j+ee.substr(I,R);P>0&&(N+=j+ee.slice(I)),Z&&(N="-"+N)}B=z?N+(k.decimalSeparator||"")+((P=+k.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(k.fractionGroupSeparator||"")):z):N}return(k.prefix||"")+B+(k.suffix||"")},U.toFraction=function(_){var A,k,B,F,I,M,R,P,j,N,z,Z,ee=this,Ee=ee.c;if(_!=null&&(R=new W(_),!R.isInteger()&&(R.c||R.s!==1)||R.lt(X)))throw Error(i+"Argument "+(R.isInteger()?"out of range: ":"not an integer: ")+Be(R));if(!Ee)return new W(ee);for(A=new W(X),j=k=new W(X),B=P=new W(X),Z=y(Ee),I=A.e=Z.length-ee.e-1,A.c[0]=f[(M=I%l)<0?l+M:M],_=!_||R.comparedTo(A)>0?I>0?A:j:R,M=oe,oe=1/0,R=new W(Z),P.c[0]=0;N=x(R,A,0,1),F=k.plus(N.times(B)),F.comparedTo(_)!=1;)k=B,B=F,j=P.plus(N.times(F=j)),P=F,A=R.minus(N.times(F=A)),R=F;return F=x(_.minus(k),B,0,1),P=P.plus(F.times(j)),k=k.plus(F.times(B)),P.s=j.s=ee.s,I=I*2,z=x(j,B,I,ae).minus(ee).abs().comparedTo(x(P,k,I,ae).minus(ee).abs())<1?[j,B]:[P,k],oe=M,z},U.toNumber=function(){return+Be(this)},U.toPrecision=function(_,A){return _!=null&&m(_,1,S),le(this,_,A,2)},U.toString=function(_){var A,k=this,B=k.s,F=k.e;return F===null?B?(A="Infinity",B<0&&(A="-"+A)):A="NaN":(_==null?A=F<=de||F>=ye?b(y(k.c),F):w(y(k.c),F,"0"):_===10&&De?(k=Re(new W(k),ne+F+1,ae),A=w(y(k.c),k.e,"0")):(m(_,2,qe.length,"Base"),A=$(w(y(k.c),F,"0"),10,_,B,!0)),B<0&&k.c[0]&&(A="-"+A)),A},U.valueOf=U.toJSON=function(){return Be(this)},U._isBigNumber=!0,O!=null&&W.set(O),W}function E(O){var x=O|0;return O>0||O===x?x:x-1}function y(O){for(var x,$,V=1,U=O.length,X=O[0]+"";V<U;){for(x=O[V++]+"",$=l-x.length;$--;x="0"+x);X+=x}for(U=X.length;X.charCodeAt(--U)===48;);return X.slice(0,U+1||1)}function g(O,x){var $,V,U=O.c,X=x.c,ne=O.s,ae=x.s,de=O.e,ye=x.e;if(!ne||!ae)return null;if($=U&&!U[0],V=X&&!X[0],$||V)return $?V?0:-ae:ne;if(ne!=ae)return ne;if($=ne<0,V=de==ye,!U||!X)return V?0:!U^$?1:-1;if(!V)return de>ye^$?1:-1;for(ae=(de=U.length)<(ye=X.length)?de:ye,ne=0;ne<ae;ne++)if(U[ne]!=X[ne])return U[ne]>X[ne]^$?1:-1;return de==ye?0:de>ye^$?1:-1}function m(O,x,$,V){if(O<x||O>$||O!==s(O))throw Error(i+(V||"Argument")+(typeof O=="number"?O<x||O>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(O))}function T(O){var x=O.c.length-1;return E(O.e/l)==x&&O.c[x]%2!=0}function b(O,x){return(O.length>1?O.charAt(0)+"."+O.slice(1):O)+(x<0?"e":"e+")+x}function w(O,x,$){var V,U;if(x<0){for(U=$+".";++x;U+=$);O=U+O}else if(V=O.length,++x>V){for(U=$,x-=V;--x;U+=$);O+=U}else x<V&&(O=O.slice(0,x)+"."+O.slice(x));return O}e=D(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof gi<"u"&&gi.exports?gi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Bp)});var Up=J((qR,Mp)=>{var jp=rc(),Lp=Mp.exports;(function(){"use strict";function t(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,s,i={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function c(h){return r.lastIndex=0,r.test(h)?'"'+h.replace(r,function(f){var p=i[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function l(h,f){var p,S,D,E,y=n,g,m=f[h],T=m!=null&&(m instanceof jp||jp.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(h)),typeof u=="function"&&(m=u.call(f,h,m)),typeof m){case"string":return T?m:c(m);case"number":return isFinite(m)?String(m):"null";case"boolean":case"null":case"bigint":return String(m);case"object":if(!m)return"null";if(n+=s,g=[],Object.prototype.toString.apply(m)==="[object Array]"){for(E=m.length,p=0;p<E;p+=1)g[p]=l(p,m)||"null";return D=g.length===0?"[]":n?`[
43
+ `}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Pr(jh()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Fp(),Op))).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((i,u)=>{u==="set-cookie"?e.append(u,i):e.set(u,i)});return e}};Un.Gaxios=mi;Mn=mi});var Ve=V(tt=>{"use strict";var NC=tt&&tt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),BC=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&NC(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=LC;var Np=Ip();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return Np.Gaxios}});var jC=Fu();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return jC.GaxiosError}});BC(Iu(),tt);tt.instance=new Np.Gaxios;async function LC(t){return tt.instance.request(t)}});var rc=V((Bp,gi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,s=Math.floor,i="[BigNumber Error] ",u=i+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,h=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,A=1e9;function v(R){var x,$,J,M=W.prototype={constructor:W,toString:null,valueOf:null},X=new W(1),ue=20,re=4,de=-7,pe=21,Ae=-1e7,oe=1e7,me=!1,G=1,K=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",De=!0;function W(_,w){var T,B,F,I,U,O,P,j,N=this;if(!(N instanceof W))return new W(_,w);if(w==null){if(_&&_._isBigNumber===!0){N.s=_.s,!_.c||_.e>oe?N.c=N.e=null:_.e<Ae?N.c=[N.e=0]:(N.e=_.e,N.c=_.c.slice());return}if((O=typeof _=="number")&&_*0==0){if(N.s=1/_<0?(_=-_,-1):1,_===~~_){for(I=0,U=_;U>=10;U/=10,I++);I>oe?N.c=N.e=null:(N.e=I,N.c=[_]);return}j=String(_)}else{if(!r.test(j=String(_)))return J(N,j,O);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(U=j.search(/e/i))>0?(I<0&&(I=U),I+=+j.slice(U+1),j=j.substring(0,U)):I<0&&(I=j.length)}else{if(m(w,2,qe.length,"Base"),w==10&&De)return N=new W(_),Re(N,ue+N.e+1,re);if(j=String(_),O=typeof _=="number"){if(_*0!=0)return J(N,j,O,w);if(N.s=1/_<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(u+_)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(T=qe.slice(0,w),I=U=0,P=j.length;U<P;U++)if(T.indexOf(B=j.charAt(U))<0){if(B=="."){if(U>I){I=P;continue}}else if(!F&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){F=!0,U=-1,I=0;continue}return J(N,String(_),O,w)}O=!1,j=$(j,w,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(U=0;j.charCodeAt(U)===48;U++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(U,++P)){if(P-=U,O&&W.DEBUG&&P>15&&(_>h||_!==s(_)))throw Error(u+N.s*_);if((I=I-U-1)>oe)N.c=N.e=null;else if(I<Ae)N.c=[N.e=0];else{if(N.e=I,N.c=[],U=(I+1)%l,I<0&&(U+=l),U<P){for(U&&N.c.push(+j.slice(0,U)),P-=l;U<P;)N.c.push(+j.slice(U,U+=l));U=l-(j=j.slice(U)).length}else U-=P;for(;U--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=v,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(_){var w,T;if(_!=null)if(typeof _=="object"){if(_.hasOwnProperty(w="DECIMAL_PLACES")&&(T=_[w],m(T,0,A,w),ue=T),_.hasOwnProperty(w="ROUNDING_MODE")&&(T=_[w],m(T,0,8,w),re=T),_.hasOwnProperty(w="EXPONENTIAL_AT")&&(T=_[w],T&&T.pop?(m(T[0],-A,0,w),m(T[1],0,A,w),de=T[0],pe=T[1]):(m(T,-A,A,w),de=-(pe=T<0?-T:T))),_.hasOwnProperty(w="RANGE"))if(T=_[w],T&&T.pop)m(T[0],-A,-1,w),m(T[1],1,A,w),Ae=T[0],oe=T[1];else if(m(T,-A,A,w),T)Ae=-(oe=T<0?-T:T);else throw Error(i+w+" cannot be zero: "+T);if(_.hasOwnProperty(w="CRYPTO"))if(T=_[w],T===!!T)if(T)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=T;else throw me=!T,Error(i+"crypto unavailable");else me=T;else throw Error(i+w+" not true or false: "+T);if(_.hasOwnProperty(w="MODULO_MODE")&&(T=_[w],m(T,0,9,w),G=T),_.hasOwnProperty(w="POW_PRECISION")&&(T=_[w],m(T,0,A,w),K=T),_.hasOwnProperty(w="FORMAT"))if(T=_[w],typeof T=="object")ae=T;else throw Error(i+w+" not an object: "+T);if(_.hasOwnProperty(w="ALPHABET"))if(T=_[w],typeof T=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(T))De=T.slice(0,10)=="0123456789",qe=T;else throw Error(i+w+" invalid: "+T)}else throw Error(i+"Object expected: "+_);return{DECIMAL_PLACES:ue,ROUNDING_MODE:re,EXPONENTIAL_AT:[de,pe],RANGE:[Ae,oe],CRYPTO:me,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ae,ALPHABET:qe}},W.isBigNumber=function(_){if(!_||_._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var w,T,B=_.c,F=_.e,I=_.s;e:if({}.toString.call(B)=="[object Array]"){if((I===1||I===-1)&&F>=-A&&F<=A&&F===s(F)){if(B[0]===0){if(F===0&&B.length===1)return!0;break e}if(w=(F+1)%l,w<1&&(w+=l),String(B[0]).length==w){for(w=0;w<B.length;w++)if(T=B[w],T<0||T>=c||T!==s(T))break e;if(T!==0)return!0}}}else if(B===null&&F===null&&(I===null||I===1||I===-1))return!0;throw Error(i+"Invalid BigNumber: "+_)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var _=9007199254740992,w=Math.random()*_&2097151?function(){return s(Math.random()*_)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(T){var B,F,I,U,O,P=0,j=[],N=new W(X);if(T==null?T=ue:m(T,0,A),U=n(T/l),me)if(crypto.getRandomValues){for(B=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)O=B[P]*131072+(B[P+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),B[P]=F[0],B[P+1]=F[1]):(j.push(O%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(B=crypto.randomBytes(U*=7);P<U;)O=(B[P]&31)*281474976710656+B[P+1]*1099511627776+B[P+2]*4294967296+B[P+3]*16777216+(B[P+4]<<16)+(B[P+5]<<8)+B[P+6],O>=9e15?crypto.randomBytes(7).copy(B,P):(j.push(O%1e14),P+=7);P=U/7}else throw me=!1,Error(i+"crypto unavailable");if(!me)for(;P<U;)O=w(),O<9e15&&(j[P++]=O%1e14);for(U=j[--P],T%=l,U&&T&&(O=f[l-T],j[P]=s(U/O)*O);j[P]===0;j.pop(),P--);if(P<0)j=[I=0];else{for(I=-1;j[0]===0;j.splice(0,1),I-=l);for(P=1,O=j[0];O>=10;O/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var _=1,w=arguments,T=new W(w[0]);_<w.length;)T=T.plus(w[_++]);return T},$=(function(){var _="0123456789";function w(T,B,F,I){for(var U,O=[0],P,j=0,N=T.length;j<N;){for(P=O.length;P--;O[P]*=B);for(O[0]+=I.indexOf(T.charAt(j++)),U=0;U<O.length;U++)O[U]>F-1&&(O[U+1]==null&&(O[U+1]=0),O[U+1]+=O[U]/F|0,O[U]%=F)}return O.reverse()}return function(T,B,F,I,U){var O,P,j,N,z,Z,ee,Ee,xe=T.indexOf("."),Ne=ue,we=re;for(xe>=0&&(N=K,K=0,T=T.replace(".",""),Ee=new W(B),Z=Ee.pow(T.length-xe),K=N,Ee.c=w(E(y(Z.c),Z.e,"0"),10,F,_),Ee.e=Ee.c.length),ee=w(T,B,F,U?(O=qe,_):(O=_,qe)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return O.charAt(0);if(xe<0?--j:(Z.c=ee,Z.e=j,Z.s=I,Z=x(Z,Ee,Ne,we,F),ee=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,xe=ee[P],N=F/2,z=z||P<0||ee[P+1]!=null,z=we<4?(xe!=null||z)&&(we==0||we==(Z.s<0?3:2)):xe>N||xe==N&&(we==4||z||we==6&&ee[P-1]&1||we==(Z.s<0?8:7)),P<1||!ee[0])T=z?E(O.charAt(1),-Ne,O.charAt(0)):O.charAt(0);else{if(ee.length=P,z)for(--F;++ee[--P]>F;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(xe=0,T="";xe<=N;T+=O.charAt(ee[xe++]));T=E(T,j,O.charAt(0))}return T}})(),x=(function(){function _(B,F,I){var U,O,P,j,N=0,z=B.length,Z=F%p,ee=F/p|0;for(B=B.slice();z--;)P=B[z]%p,j=B[z]/p|0,U=ee*P+j*Z,O=Z*P+U%p*p+N,N=(O/I|0)+(U/p|0)+ee*j,B[z]=O%I;return N&&(B=[N].concat(B)),B}function w(B,F,I,U){var O,P;if(I!=U)P=I>U?1:-1;else for(O=P=0;O<I;O++)if(B[O]!=F[O]){P=B[O]>F[O]?1:-1;break}return P}function T(B,F,I,U){for(var O=0;I--;)B[I]-=O,O=B[I]<F[I]?1:0,B[I]=O*U+B[I]-F[I];for(;!B[0]&&B.length>1;B.splice(0,1));}return function(B,F,I,U,O){var P,j,N,z,Z,ee,Ee,xe,Ne,we,Se,Me,hn,pn,mn,ut,ir,Ke=B.s==F.s?1:-1,Ue=B.c,ke=F.c;if(!Ue||!Ue[0]||!ke||!ke[0])return new W(!B.s||!F.s||(Ue?ke&&Ue[0]==ke[0]:!ke)?NaN:Ue&&Ue[0]==0||!ke?Ke*0:Ke/0);for(xe=new W(Ke),Ne=xe.c=[],j=B.e-F.e,Ke=I+j+1,O||(O=c,j=S(B.e/l)-S(F.e/l),Ke=Ke/l|0),N=0;ke[N]==(Ue[N]||0);N++);if(ke[N]>(Ue[N]||0)&&j--,Ke<0)Ne.push(1),z=!0;else{for(pn=Ue.length,ut=ke.length,N=0,Ke+=2,Z=s(O/(ke[0]+1)),Z>1&&(ke=_(ke,Z,O),Ue=_(Ue,Z,O),ut=ke.length,pn=Ue.length),hn=ut,we=Ue.slice(0,ut),Se=we.length;Se<ut;we[Se++]=0);ir=ke.slice(),ir=[0].concat(ir),mn=ke[0],ke[1]>=O/2&&mn++;do{if(Z=0,P=w(ke,we,ut,Se),P<0){if(Me=we[0],ut!=Se&&(Me=Me*O+(we[1]||0)),Z=s(Me/mn),Z>1)for(Z>=O&&(Z=O-1),ee=_(ke,Z,O),Ee=ee.length,Se=we.length;w(ee,we,Ee,Se)==1;)Z--,T(ee,ut<Ee?ir:ke,Ee,O),Ee=ee.length,P=1;else Z==0&&(P=Z=1),ee=ke.slice(),Ee=ee.length;if(Ee<Se&&(ee=[0].concat(ee)),T(we,ee,Se,O),Se=we.length,P==-1)for(;w(ke,we,ut,Se)<1;)Z++,T(we,ut<Se?ir:ke,Se,O),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=Ue[hn]||0:(we=[Ue[hn]],Se=1)}while((hn++<pn||we[0]!=null)&&Ke--);z=we[0]!=null,Ne[0]||Ne.splice(0,1)}if(O==c){for(N=1,Ke=Ne[0];Ke>=10;Ke/=10,N++);Re(xe,I+(xe.e=N+j*l-1)+1,U,z)}else xe.e=j,xe.r=+z;return xe}})();function le(_,w,T,B){var F,I,U,O,P;if(T==null?T=re:m(T,0,8),!_.c)return _.toString();if(F=_.c[0],U=_.e,w==null)P=y(_.c),P=B==1||B==2&&(U<=de||U>=pe)?b(P,U):E(P,U,"0");else if(_=Re(new W(_),w,T),I=_.e,P=y(_.c),O=P.length,B==1||B==2&&(w<=I||I<=de)){for(;O<w;P+="0",O++);P=b(P,I)}else if(w-=U+(B===2&&I>U),P=E(P,I,"0"),I+1>O){if(--w>0)for(P+=".";w--;P+="0");}else if(w+=I-O,w>0)for(I+1==O&&(P+=".");w--;P+="0");return _.s<0&&F?"-"+P:P}function _e(_,w){for(var T,B,F=1,I=new W(_[0]);F<_.length;F++)B=new W(_[F]),(!B.s||(T=g(I,B))===w||T===0&&I.s===w)&&(I=B);return I}function Ft(_,w,T){for(var B=1,F=w.length;!w[--F];w.pop());for(F=w[0];F>=10;F/=10,B++);return(T=B+T*l-1)>oe?_.c=_.e=null:T<Ae?_.c=[_.e=0]:(_.e=T,_.c=w),_}J=(function(){var _=/^(-?)0([xbo])(?=\w[\w.]*$)/i,w=/^([^.]+)\.$/,T=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,O,P){var j,N=O?U:U.replace(F,"");if(B.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!O&&(N=N.replace(_,function(z,Z,ee){return j=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!P||P==j?Z:z}),P&&(j=P,N=N.replace(w,"$1").replace(T,"0.$1")),U!=N))return new W(N,j);if(W.DEBUG)throw Error(i+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function Re(_,w,T,B){var F,I,U,O,P,j,N,z=_.c,Z=f;if(z){e:{for(F=1,O=z[0];O>=10;O/=10,F++);if(I=w-F,I<0)I+=l,U=w,P=z[j=0],N=s(P/Z[F-U-1]%10);else if(j=n((I+1)/l),j>=z.length)if(B){for(;z.length<=j;z.push(0));P=N=0,F=1,I%=l,U=I-l+1}else break e;else{for(P=O=z[j],F=1;O>=10;O/=10,F++);I%=l,U=I-l+F,N=U<0?0:s(P/Z[F-U-1]%10)}if(B=B||w<0||z[j+1]!=null||(U<0?P:P%Z[F-U-1]),B=T<4?(N||B)&&(T==0||T==(_.s<0?3:2)):N>5||N==5&&(T==4||B||T==6&&(I>0?U>0?P/Z[F-U]:0:z[j-1])%10&1||T==(_.s<0?8:7)),w<1||!z[0])return z.length=0,B?(w-=_.e+1,z[0]=Z[(l-w%l)%l],_.e=-w||0):z[0]=_.e=0,_;if(I==0?(z.length=j,O=1,j--):(z.length=j+1,O=Z[l-I],z[j]=U>0?s(P/Z[F-U]%Z[U])*O:0),B)for(;;)if(j==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=O,O=1;U>=10;U/=10,O++);I!=O&&(_.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=O,z[j]!=c)break;z[j--]=0,O=1}for(I=z.length;z[--I]===0;z.pop());}_.e>oe?_.c=_.e=null:_.e<Ae&&(_.c=[_.e=0])}return _}function Be(_){var w,T=_.e;return T===null?_.toString():(w=y(_.c),w=T<=de||T>=pe?b(w,T):E(w,T,"0"),_.s<0?"-"+w:w)}return M.absoluteValue=M.abs=function(){var _=new W(this);return _.s<0&&(_.s=1),_},M.comparedTo=function(_,w){return g(this,new W(_,w))},M.decimalPlaces=M.dp=function(_,w){var T,B,F,I=this;if(_!=null)return m(_,0,A),w==null?w=re:m(w,0,8),Re(new W(I),_+I.e+1,w);if(!(T=I.c))return null;if(B=((F=T.length-1)-S(this.e/l))*l,F=T[F])for(;F%10==0;F/=10,B--);return B<0&&(B=0),B},M.dividedBy=M.div=function(_,w){return x(this,new W(_,w),ue,re)},M.dividedToIntegerBy=M.idiv=function(_,w){return x(this,new W(_,w),0,1)},M.exponentiatedBy=M.pow=function(_,w){var T,B,F,I,U,O,P,j,N,z=this;if(_=new W(_),_.c&&!_.isInteger())throw Error(i+"Exponent not an integer: "+Be(_));if(w!=null&&(w=new W(w)),O=_.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!_.c||!_.c[0])return N=new W(Math.pow(+Be(z),O?_.s*(2-k(_)):+Be(_))),w?N.mod(w):N;if(P=_.s<0,w){if(w.c?!w.c[0]:!w.s)return new W(NaN);B=!P&&z.isInteger()&&w.isInteger(),B&&(z=z.mod(w))}else{if(_.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||O&&z.c[1]>=24e7:z.c[0]<8e13||O&&z.c[0]<=9999975e7)))return I=z.s<0&&k(_)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(O?(T=new W(.5),P&&(_.s=1),j=k(_)):(F=Math.abs(+Be(_)),j=F%2),N=new W(X);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):B&&(N=N.mod(w))}if(F){if(F=s(F/2),F===0)break;j=F%2}else if(_=_.times(T),Re(_,_.e+1,1),_.e>14)j=k(_);else{if(F=+Be(_),F===0)break;j=F%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):B&&(z=z.mod(w))}return B?N:(P&&(N=X.div(N)),w?N.mod(w):I?Re(N,K,re,U):N)},M.integerValue=function(_){var w=new W(this);return _==null?_=re:m(_,0,8),Re(w,w.e+1,_)},M.isEqualTo=M.eq=function(_,w){return g(this,new W(_,w))===0},M.isFinite=function(){return!!this.c},M.isGreaterThan=M.gt=function(_,w){return g(this,new W(_,w))>0},M.isGreaterThanOrEqualTo=M.gte=function(_,w){return(w=g(this,new W(_,w)))===1||w===0},M.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},M.isLessThan=M.lt=function(_,w){return g(this,new W(_,w))<0},M.isLessThanOrEqualTo=M.lte=function(_,w){return(w=g(this,new W(_,w)))===-1||w===0},M.isNaN=function(){return!this.s},M.isNegative=function(){return this.s<0},M.isPositive=function(){return this.s>0},M.isZero=function(){return!!this.c&&this.c[0]==0},M.minus=function(_,w){var T,B,F,I,U=this,O=U.s;if(_=new W(_,w),w=_.s,!O||!w)return new W(NaN);if(O!=w)return _.s=-w,U.plus(_);var P=U.e/l,j=_.e/l,N=U.c,z=_.c;if(!P||!j){if(!N||!z)return N?(_.s=-w,_):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(_.s=-w,_):new W(N[0]?U:re==3?-0:0)}if(P=S(P),j=S(j),N=N.slice(),O=P-j){for((I=O<0)?(O=-O,F=N):(j=P,F=z),F.reverse(),w=O;w--;F.push(0));F.reverse()}else for(B=(I=(O=N.length)<(w=z.length))?O:w,O=w=0;w<B;w++)if(N[w]!=z[w]){I=N[w]<z[w];break}if(I&&(F=N,N=z,z=F,_.s=-_.s),w=(B=z.length)-(T=N.length),w>0)for(;w--;N[T++]=0);for(w=c-1;B>O;){if(N[--B]<z[B]){for(T=B;T&&!N[--T];N[T]=w);--N[T],N[B]+=c}N[B]-=z[B]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?Ft(_,N,j):(_.s=re==3?-1:1,_.c=[_.e=0],_)},M.modulo=M.mod=function(_,w){var T,B,F=this;return _=new W(_,w),!F.c||!_.s||_.c&&!_.c[0]?new W(NaN):!_.c||F.c&&!F.c[0]?new W(F):(G==9?(B=_.s,_.s=1,T=x(F,_,0,3),_.s=B,T.s*=B):T=x(F,_,0,G),_=F.minus(T.times(_)),!_.c[0]&&G==1&&(_.s=F.s),_)},M.multipliedBy=M.times=function(_,w){var T,B,F,I,U,O,P,j,N,z,Z,ee,Ee,xe,Ne,we=this,Se=we.c,Me=(_=new W(_,w)).c;if(!Se||!Me||!Se[0]||!Me[0])return!we.s||!_.s||Se&&!Se[0]&&!Me||Me&&!Me[0]&&!Se?_.c=_.e=_.s=null:(_.s*=we.s,!Se||!Me?_.c=_.e=null:(_.c=[0],_.e=0)),_;for(B=S(we.e/l)+S(_.e/l),_.s*=we.s,P=Se.length,z=Me.length,P<z&&(Ee=Se,Se=Me,Me=Ee,F=P,P=z,z=F),F=P+z,Ee=[];F--;Ee.push(0));for(xe=c,Ne=p,F=z;--F>=0;){for(T=0,Z=Me[F]%Ne,ee=Me[F]/Ne|0,U=P,I=F+U;I>F;)j=Se[--U]%Ne,N=Se[U]/Ne|0,O=ee*j+N*Z,j=Z*j+O%Ne*Ne+Ee[I]+T,T=(j/xe|0)+(O/Ne|0)+ee*N,Ee[I--]=j%xe;Ee[I]=T}return T?++B:Ee.splice(0,1),Ft(_,Ee,B)},M.negated=function(){var _=new W(this);return _.s=-_.s||null,_},M.plus=function(_,w){var T,B=this,F=B.s;if(_=new W(_,w),w=_.s,!F||!w)return new W(NaN);if(F!=w)return _.s=-w,B.minus(_);var I=B.e/l,U=_.e/l,O=B.c,P=_.c;if(!I||!U){if(!O||!P)return new W(F/0);if(!O[0]||!P[0])return P[0]?_:new W(O[0]?B:F*0)}if(I=S(I),U=S(U),O=O.slice(),F=I-U){for(F>0?(U=I,T=P):(F=-F,T=O),T.reverse();F--;T.push(0));T.reverse()}for(F=O.length,w=P.length,F-w<0&&(T=P,P=O,O=T,w=F),F=0;w;)F=(O[--w]=O[w]+P[w]+F)/c|0,O[w]=c===O[w]?0:O[w]%c;return F&&(O=[F].concat(O),++U),Ft(_,O,U)},M.precision=M.sd=function(_,w){var T,B,F,I=this;if(_!=null&&_!==!!_)return m(_,1,A),w==null?w=re:m(w,0,8),Re(new W(I),_,w);if(!(T=I.c))return null;if(F=T.length-1,B=F*l+1,F=T[F]){for(;F%10==0;F/=10,B--);for(F=T[0];F>=10;F/=10,B++);}return _&&I.e+1>B&&(B=I.e+1),B},M.shiftedBy=function(_){return m(_,-h,h),this.times("1e"+_)},M.squareRoot=M.sqrt=function(){var _,w,T,B,F,I=this,U=I.c,O=I.s,P=I.e,j=ue+4,N=new W("0.5");if(O!==1||!U||!U[0])return new W(!O||O<0&&(!U||U[0])?NaN:U?I:1/0);if(O=Math.sqrt(+Be(I)),O==0||O==1/0?(w=y(U),(w.length+P)%2==0&&(w+="0"),O=Math.sqrt(+w),P=S((P+1)/2)-(P<0||P%2),O==1/0?w="5e"+P:(w=O.toExponential(),w=w.slice(0,w.indexOf("e")+1)+P),T=new W(w)):T=new W(O+""),T.c[0]){for(P=T.e,O=P+j,O<3&&(O=0);;)if(F=T,T=N.times(F.plus(x(I,F,j,1))),y(F.c).slice(0,O)===(w=y(T.c)).slice(0,O))if(T.e<P&&--O,w=w.slice(O-3,O+1),w=="9999"||!B&&w=="4999"){if(!B&&(Re(F,F.e+ue+2,0),F.times(F).eq(I))){T=F;break}j+=4,O+=4,B=1}else{(!+w||!+w.slice(1)&&w.charAt(0)=="5")&&(Re(T,T.e+ue+2,1),_=!T.times(T).eq(I));break}}return Re(T,T.e+ue+1,re,_)},M.toExponential=function(_,w){return _!=null&&(m(_,0,A),_++),le(this,_,w,1)},M.toFixed=function(_,w){return _!=null&&(m(_,0,A),_=_+this.e+1),le(this,_,w)},M.toFormat=function(_,w,T){var B,F=this;if(T==null)_!=null&&w&&typeof w=="object"?(T=w,w=null):_&&typeof _=="object"?(T=_,_=w=null):T=ae;else if(typeof T!="object")throw Error(i+"Argument not an object: "+T);if(B=F.toFixed(_,w),F.c){var I,U=B.split("."),O=+T.groupSize,P=+T.secondaryGroupSize,j=T.groupSeparator||"",N=U[0],z=U[1],Z=F.s<0,ee=Z?N.slice(1):N,Ee=ee.length;if(P&&(I=O,O=P,P=I,Ee-=I),O>0&&Ee>0){for(I=Ee%O||O,N=ee.substr(0,I);I<Ee;I+=O)N+=j+ee.substr(I,O);P>0&&(N+=j+ee.slice(I)),Z&&(N="-"+N)}B=z?N+(T.decimalSeparator||"")+((P=+T.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(T.fractionGroupSeparator||"")):z):N}return(T.prefix||"")+B+(T.suffix||"")},M.toFraction=function(_){var w,T,B,F,I,U,O,P,j,N,z,Z,ee=this,Ee=ee.c;if(_!=null&&(O=new W(_),!O.isInteger()&&(O.c||O.s!==1)||O.lt(X)))throw Error(i+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Be(O));if(!Ee)return new W(ee);for(w=new W(X),j=T=new W(X),B=P=new W(X),Z=y(Ee),I=w.e=Z.length-ee.e-1,w.c[0]=f[(U=I%l)<0?l+U:U],_=!_||O.comparedTo(w)>0?I>0?w:j:O,U=oe,oe=1/0,O=new W(Z),P.c[0]=0;N=x(O,w,0,1),F=T.plus(N.times(B)),F.comparedTo(_)!=1;)T=B,B=F,j=P.plus(N.times(F=j)),P=F,w=O.minus(N.times(F=w)),O=F;return F=x(_.minus(T),B,0,1),P=P.plus(F.times(j)),T=T.plus(F.times(B)),P.s=j.s=ee.s,I=I*2,z=x(j,B,I,re).minus(ee).abs().comparedTo(x(P,T,I,re).minus(ee).abs())<1?[j,B]:[P,T],oe=U,z},M.toNumber=function(){return+Be(this)},M.toPrecision=function(_,w){return _!=null&&m(_,1,A),le(this,_,w,2)},M.toString=function(_){var w,T=this,B=T.s,F=T.e;return F===null?B?(w="Infinity",B<0&&(w="-"+w)):w="NaN":(_==null?w=F<=de||F>=pe?b(y(T.c),F):E(y(T.c),F,"0"):_===10&&De?(T=Re(new W(T),ue+F+1,re),w=E(y(T.c),T.e,"0")):(m(_,2,qe.length,"Base"),w=$(E(y(T.c),F,"0"),10,_,B,!0)),B<0&&T.c[0]&&(w="-"+w)),w},M.valueOf=M.toJSON=function(){return Be(this)},M._isBigNumber=!0,R!=null&&W.set(R),W}function S(R){var x=R|0;return R>0||R===x?x:x-1}function y(R){for(var x,$,J=1,M=R.length,X=R[0]+"";J<M;){for(x=R[J++]+"",$=l-x.length;$--;x="0"+x);X+=x}for(M=X.length;X.charCodeAt(--M)===48;);return X.slice(0,M+1||1)}function g(R,x){var $,J,M=R.c,X=x.c,ue=R.s,re=x.s,de=R.e,pe=x.e;if(!ue||!re)return null;if($=M&&!M[0],J=X&&!X[0],$||J)return $?J?0:-re:ue;if(ue!=re)return ue;if($=ue<0,J=de==pe,!M||!X)return J?0:!M^$?1:-1;if(!J)return de>pe^$?1:-1;for(re=(de=M.length)<(pe=X.length)?de:pe,ue=0;ue<re;ue++)if(M[ue]!=X[ue])return M[ue]>X[ue]^$?1:-1;return de==pe?0:de>pe^$?1:-1}function m(R,x,$,J){if(R<x||R>$||R!==s(R))throw Error(i+(J||"Argument")+(typeof R=="number"?R<x||R>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(R))}function k(R){var x=R.c.length-1;return S(R.e/l)==x&&R.c[x]%2!=0}function b(R,x){return(R.length>1?R.charAt(0)+"."+R.slice(1):R)+(x<0?"e":"e+")+x}function E(R,x,$){var J,M;if(x<0){for(M=$+".";++x;M+=$);R=M+R}else if(J=R.length,++x>J){for(M=$,x-=J;--x;M+=$);R+=M}else x<J&&(R=R.slice(0,x)+"."+R.slice(x));return R}e=v(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof gi<"u"&&gi.exports?gi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Bp)});var Up=V((zR,Mp)=>{var jp=rc(),Lp=Mp.exports;(function(){"use strict";function t(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,s,i={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function c(h){return r.lastIndex=0,r.test(h)?'"'+h.replace(r,function(f){var p=i[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function l(h,f){var p,A,v,S,y=n,g,m=f[h],k=m!=null&&(m instanceof jp||jp.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(h)),typeof u=="function"&&(m=u.call(f,h,m)),typeof m){case"string":return k?m:c(m);case"number":return isFinite(m)?String(m):"null";case"boolean":case"null":case"bigint":return String(m);case"object":if(!m)return"null";if(n+=s,g=[],Object.prototype.toString.apply(m)==="[object Array]"){for(S=m.length,p=0;p<S;p+=1)g[p]=l(p,m)||"null";return v=g.length===0?"[]":n?`[
44
44
  `+n+g.join(`,
45
45
  `+n)+`
46
- `+y+"]":"["+g.join(",")+"]",n=y,D}if(u&&typeof u=="object")for(E=u.length,p=0;p<E;p+=1)typeof u[p]=="string"&&(S=u[p],D=l(S,m),D&&g.push(c(S)+(n?": ":":")+D));else Object.keys(m).forEach(function(b){var w=l(b,m);w&&g.push(c(b)+(n?": ":":")+w)});return D=g.length===0?"{}":n?`{
46
+ `+y+"]":"["+g.join(",")+"]",n=y,v}if(u&&typeof u=="object")for(S=u.length,p=0;p<S;p+=1)typeof u[p]=="string"&&(A=u[p],v=l(A,m),v&&g.push(c(A)+(n?": ":":")+v));else Object.keys(m).forEach(function(b){var E=l(b,m);E&&g.push(c(b)+(n?": ":":")+E)});return v=g.length===0?"{}":n?`{
47
47
  `+n+g.join(`,
48
48
  `+n)+`
49
- `+y+"}":"{"+g.join(",")+"}",n=y,D}}typeof Lp.stringify!="function"&&(Lp.stringify=function(h,f,p){var S;if(n="",s="",typeof p=="number")for(S=0;S<p;S+=1)s+=" ";else typeof p=="string"&&(s=p);if(u=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return l("",{"":h})})})()});var $p=J(($R,qp)=>{var yi=null,LC=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,MC=/(?: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)/,UC=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
- `,r:"\r",t:" "},i,u=function(y){throw{name:"SyntaxError",message:y,at:r,text:i}},c=function(y){return y&&y!==n&&u("Expected '"+y+"' instead of '"+n+"'"),n=i.charAt(r),r+=1,n},l=function(){var y,g="";for(n==="-"&&(g="-",c("-"));n>="0"&&n<="9";)g+=n,c();if(n===".")for(g+=".";c()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,c(),(n==="-"||n==="+")&&(g+=n,c());n>="0"&&n<="9";)g+=n,c();if(y=+g,!isFinite(y))u("Bad number");else return yi==null&&(yi=rc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new yi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new yi(y):y},h=function(){var y,g,m="",T;if(n==='"')for(var b=r;c();){if(n==='"')return r-1>b&&(m+=i.substring(b,r-1)),c(),m;if(n==="\\"){if(r-1>b&&(m+=i.substring(b,r-1)),c(),n==="u"){for(T=0,g=0;g<4&&(y=parseInt(c(),16),!!isFinite(y));g+=1)T=T*16+y;m+=String.fromCharCode(T)}else if(typeof s[n]=="string")m+=s[n];else break;b=r}}u("Bad string")},f=function(){for(;n&&n<=" ";)c()},p=function(){switch(n){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+n+"'")},S,D=function(){var y=[];if(n==="["){if(c("["),f(),n==="]")return c("]"),y;for(;n;){if(y.push(S()),f(),n==="]")return c("]"),y;c(","),f()}}u("Bad array")},E=function(){var y,g=Object.create(null);if(n==="{"){if(c("{"),f(),n==="}")return c("}"),g;for(;n;){if(y=h(),f(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&u('Duplicate key "'+y+'"'),LC.test(y)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?S():g[y]=S():MC.test(y)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?S():g[y]=S():g[y]=S(),f(),n==="}")return c("}"),g;c(","),f()}}u("Bad object")};return S=function(){switch(f(),n){case"{":return E();case"[":return D();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(y,g){var m;return i=y+"",r=0,n=" ",m=S(),f(),n&&u("Syntax error"),typeof g=="function"?(function T(b,w){var O,x,$=b[w];return $&&typeof $=="object"&&Object.keys($).forEach(function(V){x=T($,V),x!==void 0?$[V]=x:delete $[V]}),g.call(b,w,$)})({"":m},""):m}};qp.exports=UC});var Wp=J((zR,_i)=>{var zp=Up().stringify,Hp=$p();_i.exports=function(t){return{parse:Hp(t),stringify:zp}};_i.exports.parse=Hp();_i.exports.stringify=zp});var nc=J(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.GCE_LINUX_BIOS_PATHS=void 0;Lt.isGoogleCloudServerless=Vp;Lt.isGoogleComputeEngineLinux=Kp;Lt.isGoogleComputeEngineMACAddress=Yp;Lt.isGoogleComputeEngine=Xp;Lt.detectGCPResidency=$C;var Gp=Q("fs"),Jp=Q("os");Lt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var qC=/^42:01/;function Vp(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Kp(){if((0,Jp.platform)()!=="linux")return!1;try{(0,Gp.statSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Gp.readFileSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Yp(){let t=(0,Jp.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(qC.test(r))return!0}return!1}function Xp(){return Kp()||Yp()}function $C(){return Vp()||Xp()}});var Qp=J(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.Colours=void 0;var Xe=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};bi.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var rm=J(Te=>{"use strict";var zC=Te&&Te.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),HC=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Zp=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&zC(r,e,n[s]);return HC(r,e),r}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=oc;Te.getDebugBackend=GC;Te.getStructuredBackend=JC;Te.setBackend=VC;Te.log=tm;var WC=Q("events"),Rs=Zp(Q("process")),em=Zp(Q("util")),ft=Qp(),Mt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Mt||(Te.LogSeverity=Mt={}));var Os=class extends WC.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,s)=>this.on(n,s)}),this.func.debug=(...n)=>this.invokeSeverity(Mt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Mt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Mt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Mt.ERROR,...n),this.func.sublog=n=>tm(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};Te.AdhocDebugLogger=Os;Te.placeholder=new Os("",()=>{}).func;var qn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Rs.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let s=this.cached.get(e);s||(s=this.makeLogger(e),this.cached.set(e,s)),s(r,...n)}catch(s){console.error(s)}}};Te.DebugLogBackendBase=qn;var sc=class extends qn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var s;let i=`${ft.Colours.green}${e}${ft.Colours.reset}`,u=`${ft.Colours.yellow}${Rs.pid}${ft.Colours.reset}`,c;switch(r.severity){case Mt.ERROR:c=`${ft.Colours.red}${r.severity}${ft.Colours.reset}`;break;case Mt.INFO:c=`${ft.Colours.magenta}${r.severity}${ft.Colours.reset}`;break;case Mt.WARNING:c=`${ft.Colours.yellow}${r.severity}${ft.Colours.reset}`;break;default:c=(s=r.severity)!==null&&s!==void 0?s:Mt.DEFAULT;break}let l=em.formatWithOptions({colors:ft.Colours.enabled},...n),h=Object.assign({},r);delete h.severity;let f=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=f?`${ft.Colours.grey}${f}${ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,i,c,l,f?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function oc(){return new sc}var ic=class extends qn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...s)=>{r(s[0],...s.slice(1))}}setFilters(){var e;let r=(e=Rs.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Rs.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function GC(t){return new ic(t)}var ac=class extends qn{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(s,...i)=>{var u;let c=(u=s.severity)!==null&&u!==void 0?u:Mt.INFO,l=Object.assign({severity:c,message:em.format(...i)},s),h=JSON.stringify(l);n?n(s,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function JC(t){return new ac(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var uc=new Map,ht;function VC(t){ht=t,uc.clear()}function tm(t,e){if(!ht&&!Rs.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=uc.get(t);if(r)return r.func;if(ht===null)return Te.placeholder;ht===void 0&&(ht=oc());let n=(()=>{let s;return new Os(t,(u,...c)=>{if(s!==ht){if(ht===null)return;ht===void 0&&(ht=oc()),s=ht}ht?.log(t,u,...c)})})();return uc.set(t,n),n.func}});var cc=J(un=>{"use strict";var KC=un&&un.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),YC=un&&un.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&KC(e,t,r)};Object.defineProperty(un,"__esModule",{value:!0});YC(rm(),un)});var xs=J(ie=>{"use strict";var sm=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),XC=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),QC=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&sm(r,e,n[s]);return XC(r,e),r}})(),ZC=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&sm(e,t,r)};Object.defineProperty(ie,"__esModule",{value:!0});ie.gcpResidencyCache=ie.METADATA_SERVER_DETECTION=ie.HEADERS=ie.HEADER_VALUE=ie.HEADER_NAME=ie.SECONDARY_HOST_ADDRESS=ie.HOST_ADDRESS=ie.BASE_PATH=void 0;ie.instance=ow;ie.project=iw;ie.universe=aw;ie.bulk=uw;ie.isAvailable=lw;ie.resetIsAvailableCache=dw;ie.getGCPResidency=fc;ie.setGCPResidency=om;ie.requestTimeout=im;var lc=Ve(),ew=Wp(),tw=nc(),rw=QC(cc());ie.BASE_PATH="/computeMetadata/v1";ie.HOST_ADDRESS="http://169.254.169.254";ie.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ie.HEADER_NAME="Metadata-Flavor";ie.HEADER_VALUE="Google";ie.HEADERS=Object.freeze({[ie.HEADER_NAME]:ie.HEADER_VALUE});var nm=rw.log("gcp-metadata");ie.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 dc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ie.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ie.BASE_PATH,t).href}function nw(t){Object.keys(t).forEach(e=>{switch(e){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(`'${e}' is not a valid configuration option.`)}})}async function Fs(t,e={},r=3,n=!1){let s=new Headers(ie.HEADERS),i="",u={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((S,D)=>s.set(D,S)),i=p.metadataKey,u=p.params||u,r=p.noResponseRetries||r,n=p.fastFail||n}else i=t;typeof e=="string"?i+=`/${e}`:(nw(e),e.property&&(i+=`/${e.property}`),new Headers(e.headers).forEach((p,S)=>s.set(S,p)),u=e.params||u);let c=n?sw:lc.request,l={url:`${dc()}/${i}`,headers:s,retryConfig:{noResponseRetries:r},params:u,responseType:"text",timeout:im()};nm.info("instance request %j",l);let h=await c(l);nm.info("instance metadata is %s",h.data);let f=h.headers.get(ie.HEADER_NAME);if(f!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof h.data=="string")try{return ew.parse(h.data)}catch{}return h.data}async function sw(t){let e={...t,url:t.url?.toString().replace(dc(),dc(ie.SECONDARY_HOST_ADDRESS))},r=(0,lc.request)(t),n=(0,lc.request)(e);return Promise.any([r,n])}function ow(t){return Fs("instance",t)}function iw(t){return Fs("project",t)}function aw(t){return Fs("universe",t)}async function uw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Fs(r),s=r.metadataKey;e[s]=n})())),e}function cw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Ci;async function lw(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ie.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ie.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return fc();case"ping-only":}}try{return Ci===void 0&&(Ci=Fs("instance",void 0,cw(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Ci,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function dw(){Ci=void 0}ie.gcpResidencyCache=null;function fc(){return ie.gcpResidencyCache===null&&om(),ie.gcpResidencyCache}function om(t=null){ie.gcpResidencyCache=t!==null?t:(0,tw.detectGCPResidency)()}function im(){return fc()?0:3e3}ZC(nc(),ie)});var cm=J(wi=>{"use strict";wi.byteLength=hw;wi.toByteArray=mw;wi.fromByteArray=_w;var Yt=[],kt=[],fw=typeof Uint8Array<"u"?Uint8Array:Array,hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(cn=0,am=hc.length;cn<am;++cn)Yt[cn]=hc[cn],kt[hc.charCodeAt(cn)]=cn;var cn,am;kt[45]=62;kt[95]=63;function um(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function hw(t){var e=um(t),r=e[0],n=e[1];return(r+n)*3/4-n}function pw(t,e,r){return(e+r)*3/4-r}function mw(t){var e,r=um(t),n=r[0],s=r[1],i=new fw(pw(t,n,s)),u=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=kt[t.charCodeAt(l)]<<18|kt[t.charCodeAt(l+1)]<<12|kt[t.charCodeAt(l+2)]<<6|kt[t.charCodeAt(l+3)],i[u++]=e>>16&255,i[u++]=e>>8&255,i[u++]=e&255;return s===2&&(e=kt[t.charCodeAt(l)]<<2|kt[t.charCodeAt(l+1)]>>4,i[u++]=e&255),s===1&&(e=kt[t.charCodeAt(l)]<<10|kt[t.charCodeAt(l+1)]<<4|kt[t.charCodeAt(l+2)]>>2,i[u++]=e>>8&255,i[u++]=e&255),i}function gw(t){return Yt[t>>18&63]+Yt[t>>12&63]+Yt[t>>6&63]+Yt[t&63]}function yw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(gw(n));return s.join("")}function _w(t){for(var e,r=t.length,n=r%3,s=[],i=16383,u=0,c=r-n;u<c;u+=i)s.push(yw(t,u,u+i>c?c:u+i));return n===1?(e=t[r-1],s.push(Yt[e>>2]+Yt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Yt[e>>10]+Yt[e>>4&63]+Yt[e<<2&63]+"=")),s.join("")}});var mc=J(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.fromArrayBufferToHex=bw;function bw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var lm=J(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.BrowserCrypto=void 0;var $n=cm(),Cw=mc(),gc=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return $n.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),$n.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let s={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(r),u=$n.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,s,!0,["verify"]);return await window.crypto.subtle.verify(s,c,u,i)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),i=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,i,s);return $n.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let r=$n.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return $n.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,Cw.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),s=new TextEncoder,i=await window.crypto.subtle.importKey("raw",s.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,s.encode(r))}};Ei.BrowserCrypto=gc});var dm=J(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.NodeCrypto=void 0;var zn=Q("crypto"),yc=class{async sha256DigestBase64(e){return zn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return zn.randomBytes(e).toString("base64")}async verify(e,r,n){let s=zn.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){let n=zn.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return zn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:Ew(e);return ww(zn.createHmac("sha256",n).update(r).digest())}};Ai.NodeCrypto=yc;function ww(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Ew(t){return Buffer.from(t)}});var Ps=J(yr=>{"use strict";var Aw=yr&&yr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Sw=yr&&yr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Aw(e,t,r)};Object.defineProperty(yr,"__esModule",{value:!0});yr.createCrypto=Dw;yr.hasBrowserCrypto=fm;var kw=lm(),Tw=dm();Sw(mc(),yr);function Dw(){return fm()?new kw.BrowserCrypto:new Tw.NodeCrypto}function fm(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Hn=J((_c,pm)=>{var Si=Q("buffer"),Xt=Si.Buffer;function hm(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?pm.exports=Si:(hm(Si,_c),_c.Buffer=ln);function ln(t,e,r){return Xt(t,e,r)}ln.prototype=Object.create(Xt.prototype);hm(Xt,ln);ln.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};ln.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Xt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};ln.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};ln.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Si.SlowBuffer(t)}});var gm=J((e1,mm)=>{"use strict";function bc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var vw={ES256:bc(256),ES384:bc(384),ES512:bc(521)};function Rw(t){var e=vw[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}mm.exports=Rw});var Cc=J((t1,Em)=>{"use strict";var ki=Hn().Buffer,_m=gm(),Ti=128,bm=0,Ow=32,Fw=16,xw=2,Cm=Fw|Ow|bm<<6,Di=xw|bm<<6;function Pw(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function wm(t){if(ki.isBuffer(t))return t;if(typeof t=="string")return ki.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Iw(t,e){t=wm(t);var r=_m(e),n=r+1,s=t.length,i=0;if(t[i++]!==Cm)throw new Error('Could not find expected "seq"');var u=t[i++];if(u===(Ti|1)&&(u=t[i++]),s-i<u)throw new Error('"seq" specified length of "'+u+'", only "'+(s-i)+'" remaining');if(t[i++]!==Di)throw new Error('Could not find expected "int" for "r"');var c=t[i++];if(s-i-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(s-i-2)+'" available');if(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=i;if(i+=c,t[i++]!==Di)throw new Error('Could not find expected "int" for "s"');var h=t[i++];if(s-i!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(s-i)+'"');if(n<h)throw new Error('"s" specified length of "'+h+'", max of "'+n+'" is acceptable');var f=i;if(i+=h,i!==s)throw new Error('Expected to consume entire buffer, but "'+(s-i)+'" bytes remain');var p=r-c,S=r-h,D=ki.allocUnsafe(p+c+S+h);for(i=0;i<p;++i)D[i]=0;t.copy(D,i,l+Math.max(-p,0),l+c),i=r;for(var E=i;i<E+S;++i)D[i]=0;return t.copy(D,i,f+Math.max(-S,0),f+h),D=D.toString("base64"),D=Pw(D),D}function ym(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var s=t[e+n]>=Ti;return s&&--n,n}function Nw(t,e){t=wm(t);var r=_m(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var s=ym(t,0,r),i=ym(t,r,t.length),u=r-s,c=r-i,l=2+u+1+1+c,h=l<Ti,f=ki.allocUnsafe((h?2:3)+l),p=0;return f[p++]=Cm,h?f[p++]=l:(f[p++]=Ti|1,f[p++]=l&255),f[p++]=Di,f[p++]=u,s<0?(f[p++]=0,p+=t.copy(f,p,0,r)):p+=t.copy(f,p,s,r),f[p++]=Di,f[p++]=c,i<0?(f[p++]=0,t.copy(f,p,r)):t.copy(f,p,r+i),f}Em.exports={derToJose:Iw,joseToDer:Nw}});var Ut=J(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.LRUCache=void 0;_r.snakeToCamel=Sm;_r.originalOrCamelOptions=Mw;_r.removeUndefinedValuesInObject=Uw;_r.isValidFile=qw;_r.getWellKnownCertificateConfigFileLocation=$w;var Bw=Q("fs"),jw=Q("os"),wc=Q("path"),Lw="certificate_config.json",Am="gcloud";function Sm(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Mw(t){function e(r){let n=t||{};return n[r]??n[Sm(r)]}return{get:e}}var Ec=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};_r.LRUCache=Ec;function Uw(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function qw(t){try{return(await Bw.promises.lstat(t)).isFile()}catch{return!1}}function $w(){let t=process.env.CLOUDSDK_CONFIG||(zw()?wc.join(process.env.APPDATA||"",Am):wc.join(process.env.HOME||"",".config",Am));return wc.join(t,Lw)}function zw(){return jw.platform().startsWith("win")}});var km=J((n1,Hw)=>{Hw.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},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:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.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.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",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 --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","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"},license:"Apache-2.0"}});var Ac=J(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.USER_AGENT=qr.PRODUCT_NAME=qr.pkg=void 0;var Tm=km();qr.pkg=Tm;var Dm="google-api-nodejs-client";qr.PRODUCT_NAME=Dm;var Ww=`${Dm}/${Tm.version}`;qr.USER_AGENT=Ww});var pt=J(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.AuthClient=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=qt.DEFAULT_UNIVERSE=void 0;var Gw=Q("events"),Sc=Ve(),Jw=Ut(),Vw=cc(),kc=Ac();qt.DEFAULT_UNIVERSE="googleapis.com";qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Tc=class t extends Gw.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=qt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,Jw.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??qt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Sc.Gaxios(e.transporterOptions),r.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Sc.Gaxios.mergeHeaders(i,r.headers),n&&Sc.Gaxios.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,r){let n=r.get("x-goog-user-project"),s=r.get("authorization");return n&&e.set("x-goog-user-project",n),s&&e.set("authorization",s),e}static log=(0,Vw.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${kc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${kc.USER_AGENT}`):e.headers.set("User-Agent",kc.USER_AGENT);try{let n=e,s=n[t.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=i;let u={url:e.url,headers:e.headers};s?t.log.info("%s [%s] request %j",s,i,u):t.log.info("[%s] request %j",i,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,s,e.data):t.log.info("[%s] response %j",s,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,s,e.response?.data):t.log.error("[%s] error %j",s,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};qt.AuthClient=Tc});var vc=J(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.LoginTicket=void 0;var Dc=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};vi.LoginTicket=Dc});var dn=J(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.OAuth2Client=Qt.ClientAuthentication=Qt.CertificateFormat=Qt.CodeChallengeMethod=void 0;var vm=Ve(),Kw=Q("querystring"),Yw=Q("stream"),Xw=Cc(),Rm=Ut(),Rc=Ps(),Wn=pt(),Qw=vc(),Om;(function(t){t.Plain="plain",t.S256="S256"})(Om||(Qt.CodeChallengeMethod=Om={}));var br;(function(t){t.PEM="PEM",t.JWK="JWK"})(br||(Qt.CertificateFormat=br={}));var Is;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Is||(Qt.ClientAuthentication=Is={}));var Oc=class t extends Wn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=br.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],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",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Is.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+Kw.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Rc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),i=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:i}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(s=>r(null,s.tokens,s.res),s=>r(s,null,s.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,s={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Is.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Is.ClientSecretPost&&(s.client_secret=this._clientSecret);let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Rm.removeUndefinedValuesInObject)(s)),headers:n};Wn.AuthClient.setMethodName(i,"getTokenAsync");let u=await this.transporter.request(i),c=u.data;return u.data&&u.data.expires_in&&(c.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},s;try{let u={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Rm.removeUndefinedValuesInObject)(n))};Wn.AuthClient.setMethodName(u,"refreshTokenNoCache"),s=await this.transporter.request(u)}catch(u){throw u instanceof vm.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let i=s.data;return s.data&&s.data.expires_in&&(i.expiry_date=new Date().getTime()+s.data.expires_in*1e3,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:s}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let c=new Headers({authorization:r.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,s=null;try{n=await this.refreshToken(r.refresh_token),s=n.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let i=this.credentials;i.token_type=i.token_type||"Bearer",s.refresh_token=i.refresh_token,this.credentials=s;let u=new Headers({authorization:i.token_type+" "+s.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Wn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(s=>r(null,s),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=vm.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let s=n.response;if(s){let i=s.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=s.config.data instanceof Yw.Readable,h=i===401||i===403;if(!r&&h&&!l&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&h&&!l&&c){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,Rc.hasBrowserCrypto)()?br.JWK:br.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,s;switch(r){case br.PEM:s=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case br.JWK:s=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let h={...t.RETRY_CONFIG,url:s};Wn.AuthClient.setMethodName(h,"getFederatedSignonCertsAsync"),n=await this.transporter.request(h)}catch(h){throw h instanceof Error&&(h.message=`Failed to retrieve verification certificates: ${h.message}`),h}let i=n?.headers.get("cache-control"),u=-1;if(i){let h=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let c={};switch(r){case br.PEM:c=n.data;break;case br.JWK:for(let h of n.data.keys)c[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=u===-1?null:new Date(l.getTime()+u),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};Wn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,s,i){let u=(0,Rc.createCrypto)();i||(i=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],h=c[2],f,p;try{f=JSON.parse(u.decodeBase64StringUtf8(c[0]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token envelope: ${c[0]}': ${b.message}`),b}if(!f)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(u.decodeBase64StringUtf8(c[1]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token payload '${c[0]}`),b}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let S=r[f.kid];if(f.alg==="ES256"&&(h=Xw.joseToDer(h,"ES256").toString("base64")),!await u.verify(S,l,h))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let E=Number(p.iat);if(isNaN(E))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(y>=g+i)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=E-t.CLOCK_SKEW_SECS_,T=y+t.CLOCK_SKEW_SECS_;if(g<m)throw new Error("Token used too early, "+g+" < "+m+": "+JSON.stringify(p));if(g>T)throw new Error("Token used too late, "+g+" > "+T+": "+JSON.stringify(p));if(s&&s.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+s+"], but got "+p.iss);if(typeof n<"u"&&n!==null){let b=p.aud,w=!1;if(n.constructor===Array?w=n.indexOf(b)>-1:w=b===n,!w)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new Qw.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Qt.OAuth2Client=Oc});var xc=J(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Compute=void 0;var Zw=Ve(),Fm=xs(),eE=dn(),Fc=class extends eE.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let s={property:e};this.scopes.length>0&&(s.params={scopes:this.scopes.join(",")}),r=await Fm.instance(s)}catch(s){throw s instanceof Zw.GaxiosError&&(s.message=`Could not refresh access token: ${s.message}`,this.wrapError(s)),s}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let s={property:r};n=await Fm.instance(s)}catch(s){throw s instanceof Error&&(s.message=`Could not fetch ID token: ${s.message}`),s}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.status===403?e.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: "+e.message:r.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Ri.Compute=Fc});var Ic=J(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.IdTokenClient=void 0;var tE=dn(),Pc=class extends tE.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Oi.IdTokenClient=Pc});var Nc=J(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.GCPEnv=void 0;Gn.clear=rE;Gn.getEnv=nE;var xm=xs(),Zt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Zt||(Gn.GCPEnv=Zt={}));var Ns;function rE(){Ns=void 0}async function nE(){return Ns||(Ns=sE(),Ns)}async function sE(){let t=Zt.NONE;return oE()?t=Zt.APP_ENGINE:iE()?t=Zt.CLOUD_FUNCTIONS:await lE()?await cE()?t=Zt.KUBERNETES_ENGINE:aE()?t=Zt.CLOUD_RUN:uE()?t=Zt.CLOUD_RUN_JOBS:t=Zt.COMPUTE_ENGINE:t=Zt.NONE,t}function oE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function iE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function aE(){return!!process.env.K_CONFIGURATION}function uE(){return!!process.env.CLOUD_RUN_JOB}async function cE(){try{return await xm.instance("attributes/cluster-name"),!0}catch{return!1}}async function lE(){return xm.isAvailable()}});var Bc=J((d1,Pm)=>{var Fi=Hn().Buffer,dE=Q("stream"),fE=Q("util");function xi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Fi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Fi.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}fE.inherits(xi,dE);xi.prototype.write=function(e){this.buffer=Fi.concat([this.buffer,Fi.from(e)]),this.emit("data",e)};xi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Pm.exports=xi});var Nm=J((f1,Im)=>{"use strict";var Bs=Q("buffer").Buffer,jc=Q("buffer").SlowBuffer;Im.exports=Pi;function Pi(t,e){if(!Bs.isBuffer(t)||!Bs.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}Pi.install=function(){Bs.prototype.equal=jc.prototype.equal=function(e){return Pi(this,e)}};var hE=Bs.prototype.equal,pE=jc.prototype.equal;Pi.restore=function(){Bs.prototype.equal=hE,jc.prototype.equal=pE}});var qc=J((h1,Hm)=>{var Vn=Hn().Buffer,Tt=Q("crypto"),jm=Cc(),Bm=Q("util"),mE=`"%s" is not a valid algorithm.
49
+ `+y+"}":"{"+g.join(",")+"}",n=y,v}}typeof Lp.stringify!="function"&&(Lp.stringify=function(h,f,p){var A;if(n="",s="",typeof p=="number")for(A=0;A<p;A+=1)s+=" ";else typeof p=="string"&&(s=p);if(u=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return l("",{"":h})})})()});var $p=V((HR,qp)=>{var yi=null,MC=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,UC=/(?: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)/,qC=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
+ `,r:"\r",t:" "},i,u=function(y){throw{name:"SyntaxError",message:y,at:r,text:i}},c=function(y){return y&&y!==n&&u("Expected '"+y+"' instead of '"+n+"'"),n=i.charAt(r),r+=1,n},l=function(){var y,g="";for(n==="-"&&(g="-",c("-"));n>="0"&&n<="9";)g+=n,c();if(n===".")for(g+=".";c()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,c(),(n==="-"||n==="+")&&(g+=n,c());n>="0"&&n<="9";)g+=n,c();if(y=+g,!isFinite(y))u("Bad number");else return yi==null&&(yi=rc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new yi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new yi(y):y},h=function(){var y,g,m="",k;if(n==='"')for(var b=r;c();){if(n==='"')return r-1>b&&(m+=i.substring(b,r-1)),c(),m;if(n==="\\"){if(r-1>b&&(m+=i.substring(b,r-1)),c(),n==="u"){for(k=0,g=0;g<4&&(y=parseInt(c(),16),!!isFinite(y));g+=1)k=k*16+y;m+=String.fromCharCode(k)}else if(typeof s[n]=="string")m+=s[n];else break;b=r}}u("Bad string")},f=function(){for(;n&&n<=" ";)c()},p=function(){switch(n){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+n+"'")},A,v=function(){var y=[];if(n==="["){if(c("["),f(),n==="]")return c("]"),y;for(;n;){if(y.push(A()),f(),n==="]")return c("]"),y;c(","),f()}}u("Bad array")},S=function(){var y,g=Object.create(null);if(n==="{"){if(c("{"),f(),n==="}")return c("}"),g;for(;n;){if(y=h(),f(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&u('Duplicate key "'+y+'"'),MC.test(y)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?A():g[y]=A():UC.test(y)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?A():g[y]=A():g[y]=A(),f(),n==="}")return c("}"),g;c(","),f()}}u("Bad object")};return A=function(){switch(f(),n){case"{":return S();case"[":return v();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(y,g){var m;return i=y+"",r=0,n=" ",m=A(),f(),n&&u("Syntax error"),typeof g=="function"?(function k(b,E){var R,x,$=b[E];return $&&typeof $=="object"&&Object.keys($).forEach(function(J){x=k($,J),x!==void 0?$[J]=x:delete $[J]}),g.call(b,E,$)})({"":m},""):m}};qp.exports=qC});var Wp=V((WR,_i)=>{var zp=Up().stringify,Hp=$p();_i.exports=function(t){return{parse:Hp(t),stringify:zp}};_i.exports.parse=Hp();_i.exports.stringify=zp});var nc=V(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.GCE_LINUX_BIOS_PATHS=void 0;Lt.isGoogleCloudServerless=Vp;Lt.isGoogleComputeEngineLinux=Kp;Lt.isGoogleComputeEngineMACAddress=Yp;Lt.isGoogleComputeEngine=Xp;Lt.detectGCPResidency=zC;var Gp=Q("fs"),Jp=Q("os");Lt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var $C=/^42:01/;function Vp(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Kp(){if((0,Jp.platform)()!=="linux")return!1;try{(0,Gp.statSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Gp.readFileSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Yp(){let t=(0,Jp.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if($C.test(r))return!0}return!1}function Xp(){return Kp()||Yp()}function zC(){return Vp()||Xp()}});var Qp=V(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.Colours=void 0;var Xe=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};bi.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var rm=V(Te=>{"use strict";var HC=Te&&Te.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),WC=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Zp=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&HC(r,e,n[s]);return WC(r,e),r}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=oc;Te.getDebugBackend=JC;Te.getStructuredBackend=VC;Te.setBackend=KC;Te.log=tm;var GC=Q("events"),Rs=Zp(Q("process")),em=Zp(Q("util")),ft=Qp(),Mt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Mt||(Te.LogSeverity=Mt={}));var Os=class extends GC.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,s)=>this.on(n,s)}),this.func.debug=(...n)=>this.invokeSeverity(Mt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Mt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Mt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Mt.ERROR,...n),this.func.sublog=n=>tm(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};Te.AdhocDebugLogger=Os;Te.placeholder=new Os("",()=>{}).func;var qn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Rs.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let s=this.cached.get(e);s||(s=this.makeLogger(e),this.cached.set(e,s)),s(r,...n)}catch(s){console.error(s)}}};Te.DebugLogBackendBase=qn;var sc=class extends qn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var s;let i=`${ft.Colours.green}${e}${ft.Colours.reset}`,u=`${ft.Colours.yellow}${Rs.pid}${ft.Colours.reset}`,c;switch(r.severity){case Mt.ERROR:c=`${ft.Colours.red}${r.severity}${ft.Colours.reset}`;break;case Mt.INFO:c=`${ft.Colours.magenta}${r.severity}${ft.Colours.reset}`;break;case Mt.WARNING:c=`${ft.Colours.yellow}${r.severity}${ft.Colours.reset}`;break;default:c=(s=r.severity)!==null&&s!==void 0?s:Mt.DEFAULT;break}let l=em.formatWithOptions({colors:ft.Colours.enabled},...n),h=Object.assign({},r);delete h.severity;let f=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=f?`${ft.Colours.grey}${f}${ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,i,c,l,f?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function oc(){return new sc}var ic=class extends qn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...s)=>{r(s[0],...s.slice(1))}}setFilters(){var e;let r=(e=Rs.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Rs.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function JC(t){return new ic(t)}var ac=class extends qn{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(s,...i)=>{var u;let c=(u=s.severity)!==null&&u!==void 0?u:Mt.INFO,l=Object.assign({severity:c,message:em.format(...i)},s),h=JSON.stringify(l);n?n(s,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function VC(t){return new ac(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var uc=new Map,ht;function KC(t){ht=t,uc.clear()}function tm(t,e){if(!ht&&!Rs.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=uc.get(t);if(r)return r.func;if(ht===null)return Te.placeholder;ht===void 0&&(ht=oc());let n=(()=>{let s;return new Os(t,(u,...c)=>{if(s!==ht){if(ht===null)return;ht===void 0&&(ht=oc()),s=ht}ht?.log(t,u,...c)})})();return uc.set(t,n),n.func}});var cc=V(un=>{"use strict";var YC=un&&un.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),XC=un&&un.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&YC(e,t,r)};Object.defineProperty(un,"__esModule",{value:!0});XC(rm(),un)});var xs=V(ie=>{"use strict";var sm=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),QC=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ZC=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&sm(r,e,n[s]);return QC(r,e),r}})(),ew=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&sm(e,t,r)};Object.defineProperty(ie,"__esModule",{value:!0});ie.gcpResidencyCache=ie.METADATA_SERVER_DETECTION=ie.HEADERS=ie.HEADER_VALUE=ie.HEADER_NAME=ie.SECONDARY_HOST_ADDRESS=ie.HOST_ADDRESS=ie.BASE_PATH=void 0;ie.instance=iw;ie.project=aw;ie.universe=uw;ie.bulk=cw;ie.isAvailable=dw;ie.resetIsAvailableCache=fw;ie.getGCPResidency=fc;ie.setGCPResidency=om;ie.requestTimeout=im;var lc=Ve(),tw=Wp(),rw=nc(),nw=ZC(cc());ie.BASE_PATH="/computeMetadata/v1";ie.HOST_ADDRESS="http://169.254.169.254";ie.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ie.HEADER_NAME="Metadata-Flavor";ie.HEADER_VALUE="Google";ie.HEADERS=Object.freeze({[ie.HEADER_NAME]:ie.HEADER_VALUE});var nm=nw.log("gcp-metadata");ie.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 dc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ie.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ie.BASE_PATH,t).href}function sw(t){Object.keys(t).forEach(e=>{switch(e){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(`'${e}' is not a valid configuration option.`)}})}async function Fs(t,e={},r=3,n=!1){let s=new Headers(ie.HEADERS),i="",u={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((A,v)=>s.set(v,A)),i=p.metadataKey,u=p.params||u,r=p.noResponseRetries||r,n=p.fastFail||n}else i=t;typeof e=="string"?i+=`/${e}`:(sw(e),e.property&&(i+=`/${e.property}`),new Headers(e.headers).forEach((p,A)=>s.set(A,p)),u=e.params||u);let c=n?ow:lc.request,l={url:`${dc()}/${i}`,headers:s,retryConfig:{noResponseRetries:r},params:u,responseType:"text",timeout:im()};nm.info("instance request %j",l);let h=await c(l);nm.info("instance metadata is %s",h.data);let f=h.headers.get(ie.HEADER_NAME);if(f!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof h.data=="string")try{return tw.parse(h.data)}catch{}return h.data}async function ow(t){let e={...t,url:t.url?.toString().replace(dc(),dc(ie.SECONDARY_HOST_ADDRESS))},r=(0,lc.request)(t),n=(0,lc.request)(e);return Promise.any([r,n])}function iw(t){return Fs("instance",t)}function aw(t){return Fs("project",t)}function uw(t){return Fs("universe",t)}async function cw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Fs(r),s=r.metadataKey;e[s]=n})())),e}function lw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Ci;async function dw(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ie.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ie.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return fc();case"ping-only":}}try{return Ci===void 0&&(Ci=Fs("instance",void 0,lw(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Ci,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function fw(){Ci=void 0}ie.gcpResidencyCache=null;function fc(){return ie.gcpResidencyCache===null&&om(),ie.gcpResidencyCache}function om(t=null){ie.gcpResidencyCache=t!==null?t:(0,rw.detectGCPResidency)()}function im(){return fc()?0:3e3}ew(nc(),ie)});var cm=V(wi=>{"use strict";wi.byteLength=pw;wi.toByteArray=gw;wi.fromByteArray=bw;var Yt=[],kt=[],hw=typeof Uint8Array<"u"?Uint8Array:Array,hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(cn=0,am=hc.length;cn<am;++cn)Yt[cn]=hc[cn],kt[hc.charCodeAt(cn)]=cn;var cn,am;kt[45]=62;kt[95]=63;function um(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function pw(t){var e=um(t),r=e[0],n=e[1];return(r+n)*3/4-n}function mw(t,e,r){return(e+r)*3/4-r}function gw(t){var e,r=um(t),n=r[0],s=r[1],i=new hw(mw(t,n,s)),u=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=kt[t.charCodeAt(l)]<<18|kt[t.charCodeAt(l+1)]<<12|kt[t.charCodeAt(l+2)]<<6|kt[t.charCodeAt(l+3)],i[u++]=e>>16&255,i[u++]=e>>8&255,i[u++]=e&255;return s===2&&(e=kt[t.charCodeAt(l)]<<2|kt[t.charCodeAt(l+1)]>>4,i[u++]=e&255),s===1&&(e=kt[t.charCodeAt(l)]<<10|kt[t.charCodeAt(l+1)]<<4|kt[t.charCodeAt(l+2)]>>2,i[u++]=e>>8&255,i[u++]=e&255),i}function yw(t){return Yt[t>>18&63]+Yt[t>>12&63]+Yt[t>>6&63]+Yt[t&63]}function _w(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(yw(n));return s.join("")}function bw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,u=0,c=r-n;u<c;u+=i)s.push(_w(t,u,u+i>c?c:u+i));return n===1?(e=t[r-1],s.push(Yt[e>>2]+Yt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Yt[e>>10]+Yt[e>>4&63]+Yt[e<<2&63]+"=")),s.join("")}});var mc=V(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.fromArrayBufferToHex=Cw;function Cw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var lm=V(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.BrowserCrypto=void 0;var $n=cm(),ww=mc(),gc=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return $n.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),$n.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let s={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(r),u=$n.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,s,!0,["verify"]);return await window.crypto.subtle.verify(s,c,u,i)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),i=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,i,s);return $n.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let r=$n.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return $n.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,ww.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),s=new TextEncoder,i=await window.crypto.subtle.importKey("raw",s.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,s.encode(r))}};Ei.BrowserCrypto=gc});var dm=V(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.NodeCrypto=void 0;var zn=Q("crypto"),yc=class{async sha256DigestBase64(e){return zn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return zn.randomBytes(e).toString("base64")}async verify(e,r,n){let s=zn.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){let n=zn.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return zn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:Aw(e);return Ew(zn.createHmac("sha256",n).update(r).digest())}};Ai.NodeCrypto=yc;function Ew(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Aw(t){return Buffer.from(t)}});var Ps=V(yr=>{"use strict";var Sw=yr&&yr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),kw=yr&&yr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Sw(e,t,r)};Object.defineProperty(yr,"__esModule",{value:!0});yr.createCrypto=vw;yr.hasBrowserCrypto=fm;var Tw=lm(),Dw=dm();kw(mc(),yr);function vw(){return fm()?new Tw.BrowserCrypto:new Dw.NodeCrypto}function fm(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Hn=V((_c,pm)=>{var Si=Q("buffer"),Xt=Si.Buffer;function hm(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?pm.exports=Si:(hm(Si,_c),_c.Buffer=ln);function ln(t,e,r){return Xt(t,e,r)}ln.prototype=Object.create(Xt.prototype);hm(Xt,ln);ln.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};ln.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Xt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};ln.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};ln.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Si.SlowBuffer(t)}});var gm=V((r1,mm)=>{"use strict";function bc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Rw={ES256:bc(256),ES384:bc(384),ES512:bc(521)};function Ow(t){var e=Rw[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}mm.exports=Ow});var Cc=V((n1,Em)=>{"use strict";var ki=Hn().Buffer,_m=gm(),Ti=128,bm=0,Fw=32,xw=16,Pw=2,Cm=xw|Fw|bm<<6,Di=Pw|bm<<6;function Iw(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function wm(t){if(ki.isBuffer(t))return t;if(typeof t=="string")return ki.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Nw(t,e){t=wm(t);var r=_m(e),n=r+1,s=t.length,i=0;if(t[i++]!==Cm)throw new Error('Could not find expected "seq"');var u=t[i++];if(u===(Ti|1)&&(u=t[i++]),s-i<u)throw new Error('"seq" specified length of "'+u+'", only "'+(s-i)+'" remaining');if(t[i++]!==Di)throw new Error('Could not find expected "int" for "r"');var c=t[i++];if(s-i-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(s-i-2)+'" available');if(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=i;if(i+=c,t[i++]!==Di)throw new Error('Could not find expected "int" for "s"');var h=t[i++];if(s-i!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(s-i)+'"');if(n<h)throw new Error('"s" specified length of "'+h+'", max of "'+n+'" is acceptable');var f=i;if(i+=h,i!==s)throw new Error('Expected to consume entire buffer, but "'+(s-i)+'" bytes remain');var p=r-c,A=r-h,v=ki.allocUnsafe(p+c+A+h);for(i=0;i<p;++i)v[i]=0;t.copy(v,i,l+Math.max(-p,0),l+c),i=r;for(var S=i;i<S+A;++i)v[i]=0;return t.copy(v,i,f+Math.max(-A,0),f+h),v=v.toString("base64"),v=Iw(v),v}function ym(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var s=t[e+n]>=Ti;return s&&--n,n}function Bw(t,e){t=wm(t);var r=_m(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var s=ym(t,0,r),i=ym(t,r,t.length),u=r-s,c=r-i,l=2+u+1+1+c,h=l<Ti,f=ki.allocUnsafe((h?2:3)+l),p=0;return f[p++]=Cm,h?f[p++]=l:(f[p++]=Ti|1,f[p++]=l&255),f[p++]=Di,f[p++]=u,s<0?(f[p++]=0,p+=t.copy(f,p,0,r)):p+=t.copy(f,p,s,r),f[p++]=Di,f[p++]=c,i<0?(f[p++]=0,t.copy(f,p,r)):t.copy(f,p,r+i),f}Em.exports={derToJose:Nw,joseToDer:Bw}});var Ut=V(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.LRUCache=void 0;_r.snakeToCamel=Sm;_r.originalOrCamelOptions=Uw;_r.removeUndefinedValuesInObject=qw;_r.isValidFile=$w;_r.getWellKnownCertificateConfigFileLocation=zw;var jw=Q("fs"),Lw=Q("os"),wc=Q("path"),Mw="certificate_config.json",Am="gcloud";function Sm(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Uw(t){function e(r){let n=t||{};return n[r]??n[Sm(r)]}return{get:e}}var Ec=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};_r.LRUCache=Ec;function qw(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function $w(t){try{return(await jw.promises.lstat(t)).isFile()}catch{return!1}}function zw(){let t=process.env.CLOUDSDK_CONFIG||(Hw()?wc.join(process.env.APPDATA||"",Am):wc.join(process.env.HOME||"",".config",Am));return wc.join(t,Mw)}function Hw(){return Lw.platform().startsWith("win")}});var km=V((o1,Ww)=>{Ww.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},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:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.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.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",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 --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","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"},license:"Apache-2.0"}});var Ac=V(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.USER_AGENT=qr.PRODUCT_NAME=qr.pkg=void 0;var Tm=km();qr.pkg=Tm;var Dm="google-api-nodejs-client";qr.PRODUCT_NAME=Dm;var Gw=`${Dm}/${Tm.version}`;qr.USER_AGENT=Gw});var pt=V(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.AuthClient=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=qt.DEFAULT_UNIVERSE=void 0;var Jw=Q("events"),Sc=Ve(),Vw=Ut(),Kw=cc(),kc=Ac();qt.DEFAULT_UNIVERSE="googleapis.com";qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Tc=class t extends Jw.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=qt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,Vw.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??qt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Sc.Gaxios(e.transporterOptions),r.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Sc.Gaxios.mergeHeaders(i,r.headers),n&&Sc.Gaxios.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,r){let n=r.get("x-goog-user-project"),s=r.get("authorization");return n&&e.set("x-goog-user-project",n),s&&e.set("authorization",s),e}static log=(0,Kw.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${kc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${kc.USER_AGENT}`):e.headers.set("User-Agent",kc.USER_AGENT);try{let n=e,s=n[t.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=i;let u={url:e.url,headers:e.headers};s?t.log.info("%s [%s] request %j",s,i,u):t.log.info("[%s] request %j",i,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,s,e.data):t.log.info("[%s] response %j",s,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,s,e.response?.data):t.log.error("[%s] error %j",s,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};qt.AuthClient=Tc});var vc=V(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.LoginTicket=void 0;var Dc=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};vi.LoginTicket=Dc});var dn=V(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.OAuth2Client=Qt.ClientAuthentication=Qt.CertificateFormat=Qt.CodeChallengeMethod=void 0;var vm=Ve(),Yw=Q("querystring"),Xw=Q("stream"),Qw=Cc(),Rm=Ut(),Rc=Ps(),Wn=pt(),Zw=vc(),Om;(function(t){t.Plain="plain",t.S256="S256"})(Om||(Qt.CodeChallengeMethod=Om={}));var br;(function(t){t.PEM="PEM",t.JWK="JWK"})(br||(Qt.CertificateFormat=br={}));var Is;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Is||(Qt.ClientAuthentication=Is={}));var Oc=class t extends Wn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=br.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],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",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Is.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+Yw.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Rc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),i=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:i}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(s=>r(null,s.tokens,s.res),s=>r(s,null,s.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,s={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Is.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Is.ClientSecretPost&&(s.client_secret=this._clientSecret);let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Rm.removeUndefinedValuesInObject)(s)),headers:n};Wn.AuthClient.setMethodName(i,"getTokenAsync");let u=await this.transporter.request(i),c=u.data;return u.data&&u.data.expires_in&&(c.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},s;try{let u={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Rm.removeUndefinedValuesInObject)(n))};Wn.AuthClient.setMethodName(u,"refreshTokenNoCache"),s=await this.transporter.request(u)}catch(u){throw u instanceof vm.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let i=s.data;return s.data&&s.data.expires_in&&(i.expiry_date=new Date().getTime()+s.data.expires_in*1e3,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:s}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let c=new Headers({authorization:r.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,s=null;try{n=await this.refreshToken(r.refresh_token),s=n.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let i=this.credentials;i.token_type=i.token_type||"Bearer",s.refresh_token=i.refresh_token,this.credentials=s;let u=new Headers({authorization:i.token_type+" "+s.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Wn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(s=>r(null,s),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=vm.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let s=n.response;if(s){let i=s.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=s.config.data instanceof Xw.Readable,h=i===401||i===403;if(!r&&h&&!l&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&h&&!l&&c){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,Rc.hasBrowserCrypto)()?br.JWK:br.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,s;switch(r){case br.PEM:s=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case br.JWK:s=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let h={...t.RETRY_CONFIG,url:s};Wn.AuthClient.setMethodName(h,"getFederatedSignonCertsAsync"),n=await this.transporter.request(h)}catch(h){throw h instanceof Error&&(h.message=`Failed to retrieve verification certificates: ${h.message}`),h}let i=n?.headers.get("cache-control"),u=-1;if(i){let h=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let c={};switch(r){case br.PEM:c=n.data;break;case br.JWK:for(let h of n.data.keys)c[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=u===-1?null:new Date(l.getTime()+u),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};Wn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,s,i){let u=(0,Rc.createCrypto)();i||(i=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],h=c[2],f,p;try{f=JSON.parse(u.decodeBase64StringUtf8(c[0]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token envelope: ${c[0]}': ${b.message}`),b}if(!f)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(u.decodeBase64StringUtf8(c[1]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token payload '${c[0]}`),b}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let A=r[f.kid];if(f.alg==="ES256"&&(h=Qw.joseToDer(h,"ES256").toString("base64")),!await u.verify(A,l,h))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let S=Number(p.iat);if(isNaN(S))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(y>=g+i)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=S-t.CLOCK_SKEW_SECS_,k=y+t.CLOCK_SKEW_SECS_;if(g<m)throw new Error("Token used too early, "+g+" < "+m+": "+JSON.stringify(p));if(g>k)throw new Error("Token used too late, "+g+" > "+k+": "+JSON.stringify(p));if(s&&s.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+s+"], but got "+p.iss);if(typeof n<"u"&&n!==null){let b=p.aud,E=!1;if(n.constructor===Array?E=n.indexOf(b)>-1:E=b===n,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new Zw.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Qt.OAuth2Client=Oc});var xc=V(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Compute=void 0;var eE=Ve(),Fm=xs(),tE=dn(),Fc=class extends tE.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let s={property:e};this.scopes.length>0&&(s.params={scopes:this.scopes.join(",")}),r=await Fm.instance(s)}catch(s){throw s instanceof eE.GaxiosError&&(s.message=`Could not refresh access token: ${s.message}`,this.wrapError(s)),s}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let s={property:r};n=await Fm.instance(s)}catch(s){throw s instanceof Error&&(s.message=`Could not fetch ID token: ${s.message}`),s}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.status===403?e.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: "+e.message:r.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Ri.Compute=Fc});var Ic=V(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.IdTokenClient=void 0;var rE=dn(),Pc=class extends rE.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Oi.IdTokenClient=Pc});var Nc=V(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.GCPEnv=void 0;Gn.clear=nE;Gn.getEnv=sE;var xm=xs(),Zt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Zt||(Gn.GCPEnv=Zt={}));var Ns;function nE(){Ns=void 0}async function sE(){return Ns||(Ns=oE(),Ns)}async function oE(){let t=Zt.NONE;return iE()?t=Zt.APP_ENGINE:aE()?t=Zt.CLOUD_FUNCTIONS:await dE()?await lE()?t=Zt.KUBERNETES_ENGINE:uE()?t=Zt.CLOUD_RUN:cE()?t=Zt.CLOUD_RUN_JOBS:t=Zt.COMPUTE_ENGINE:t=Zt.NONE,t}function iE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function aE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function uE(){return!!process.env.K_CONFIGURATION}function cE(){return!!process.env.CLOUD_RUN_JOB}async function lE(){try{return await xm.instance("attributes/cluster-name"),!0}catch{return!1}}async function dE(){return xm.isAvailable()}});var Bc=V((h1,Pm)=>{var Fi=Hn().Buffer,fE=Q("stream"),hE=Q("util");function xi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Fi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Fi.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}hE.inherits(xi,fE);xi.prototype.write=function(e){this.buffer=Fi.concat([this.buffer,Fi.from(e)]),this.emit("data",e)};xi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Pm.exports=xi});var Nm=V((p1,Im)=>{"use strict";var Bs=Q("buffer").Buffer,jc=Q("buffer").SlowBuffer;Im.exports=Pi;function Pi(t,e){if(!Bs.isBuffer(t)||!Bs.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}Pi.install=function(){Bs.prototype.equal=jc.prototype.equal=function(e){return Pi(this,e)}};var pE=Bs.prototype.equal,mE=jc.prototype.equal;Pi.restore=function(){Bs.prototype.equal=pE,jc.prototype.equal=mE}});var qc=V((m1,Hm)=>{var Vn=Hn().Buffer,Tt=Q("crypto"),jm=Cc(),Bm=Q("util"),gE=`"%s" is not a valid algorithm.
51
51
  Supported algorithms are:
52
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,js="secret must be a string or buffer",Jn="key must be a string or a buffer",gE="key must be a string, a buffer or an object",Mc=typeof Tt.createPublicKey=="function";Mc&&(Jn+=" or a KeyObject",js+="or a KeyObject");function Lm(t){if(!Vn.isBuffer(t)&&typeof t!="string"&&(!Mc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw $t(Jn)}function Mm(t){if(!Vn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw $t(gE)}function yE(t){if(!Vn.isBuffer(t)){if(typeof t=="string")return t;if(!Mc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw $t(js)}}function Uc(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Um(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function $t(t){var e=[].slice.call(arguments,1),r=Bm.format.bind(Bm,t).apply(null,e);return new TypeError(r)}function _E(t){return Vn.isBuffer(t)||typeof t=="string"}function Ls(t){return _E(t)||(t=JSON.stringify(t)),t}function qm(t){return function(r,n){yE(n),r=Ls(r);var s=Tt.createHmac("sha"+t,n),i=(s.update(r),s.digest("base64"));return Uc(i)}}var Lc,bE="timingSafeEqual"in Tt?function(e,r){return e.byteLength!==r.byteLength?!1:Tt.timingSafeEqual(e,r)}:function(e,r){return Lc||(Lc=Nm()),Lc(e,r)};function CE(t){return function(r,n,s){var i=qm(t)(r,s);return bE(Vn.from(n),Vn.from(i))}}function $m(t){return function(r,n){Mm(n),r=Ls(r);var s=Tt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign(n,"base64"));return Uc(i)}}function zm(t){return function(r,n,s){Lm(s),r=Ls(r),n=Um(n);var i=Tt.createVerify("RSA-SHA"+t);return i.update(r),i.verify(s,n,"base64")}}function wE(t){return function(r,n){Mm(n),r=Ls(r);var s=Tt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign({key:n,padding:Tt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Tt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Uc(i)}}function EE(t){return function(r,n,s){Lm(s),r=Ls(r),n=Um(n);var i=Tt.createVerify("RSA-SHA"+t);return i.update(r),i.verify({key:s,padding:Tt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Tt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function AE(t){var e=$m(t);return function(){var n=e.apply(null,arguments);return n=jm.derToJose(n,"ES"+t),n}}function SE(t){var e=zm(t);return function(n,s,i){s=jm.joseToDer(s,"ES"+t).toString("base64");var u=e(n,s,i);return u}}function kE(){return function(){return""}}function TE(){return function(e,r){return r===""}}Hm.exports=function(e){var r={hs:qm,rs:$m,ps:wE,es:AE,none:kE},n={hs:CE,rs:zm,ps:EE,es:SE,none:TE},s=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw $t(mE,e);var i=(s[1]||s[3]).toLowerCase(),u=s[2];return{sign:r[i](u),verify:n[i](u)}}});var $c=J((p1,Wm)=>{var DE=Q("buffer").Buffer;Wm.exports=function(e){return typeof e=="string"?e:typeof e=="number"||DE.isBuffer(e)?e.toString():JSON.stringify(e)}});var Xm=J((m1,Ym)=>{var vE=Hn().Buffer,Gm=Bc(),RE=qc(),OE=Q("stream"),Jm=$c(),zc=Q("util");function Vm(t,e){return vE.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function FE(t,e,r){r=r||"utf8";var n=Vm(Jm(t),"binary"),s=Vm(Jm(e),r);return zc.format("%s.%s",n,s)}function Km(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,s=t.encoding,i=RE(e.alg),u=FE(e,r,s),c=i.sign(u,n);return zc.format("%s.%s",u,c)}function Ii(t){var e=t.secret||t.privateKey||t.key,r=new Gm(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Gm(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}zc.inherits(Ii,OE);Ii.prototype.sign=function(){try{var e=Km({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Ii.sign=Km;Ym.exports=Ii});var ag=J((g1,ig)=>{var Zm=Hn().Buffer,Qm=Bc(),xE=qc(),PE=Q("stream"),eg=$c(),IE=Q("util"),NE=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function BE(t){return Object.prototype.toString.call(t)==="[object Object]"}function jE(t){if(BE(t))return t;try{return JSON.parse(t)}catch{return}}function tg(t){var e=t.split(".",1)[0];return jE(Zm.from(e,"base64").toString("binary"))}function LE(t){return t.split(".",2).join(".")}function rg(t){return t.split(".")[2]}function ME(t,e){e=e||"utf8";var r=t.split(".")[1];return Zm.from(r,"base64").toString(e)}function ng(t){return NE.test(t)&&!!tg(t)}function sg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=eg(t);var s=rg(t),i=LE(t),u=xE(e);return u.verify(i,s,r)}function og(t,e){if(e=e||{},t=eg(t),!ng(t))return null;var r=tg(t);if(!r)return null;var n=ME(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:rg(t)}}function Kn(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Qm(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Qm(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}IE.inherits(Kn,PE);Kn.prototype.verify=function(){try{var e=sg(this.signature.buffer,this.algorithm,this.key.buffer),r=og(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Kn.decode=og;Kn.isValid=ng;Kn.verify=sg;ig.exports=Kn});var Hc=J($r=>{var ug=Xm(),Ni=ag(),UE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];$r.ALGORITHMS=UE;$r.sign=ug.sign;$r.verify=Ni.verify;$r.decode=Ni.decode;$r.isValid=Ni.isValid;$r.createSign=function(e){return new ug(e)};$r.createVerify=function(e){return new Ni(e)}});var Ag=J(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.GoogleToken=void 0;var cg=Bi(Q("fs")),qE=Ve(),$E=Bi(Hc()),zE=Bi(Q("path")),HE=Q("util");function Bi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Bi=function(i,u){if(!u&&i&&i.__esModule)return i;var c,l,h={__proto__:null,default:i};if(i===null||Cr(i)!="object"&&typeof i!="function")return h;if(c=u?n:r){if(c.has(i))return c.get(i);c.set(i,h)}for(var f in i)f!=="default"&&{}.hasOwnProperty.call(i,f)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(i,f))&&(l.get||l.set)?c(h,f,l):h[f]=i[f]);return h})(t,e)}function Cr(t){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(t)}function WE(t,e){_g(t,e),e.add(t)}function GE(t,e,r){_g(t,e),e.set(t,r)}function _g(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function lg(t,e,r){return t.set(zt(t,e),r),r}function dg(t,e){return t.get(zt(t,e))}function zt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function fg(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,wg(n.key),n)}}function bg(t,e,r){return e&&fg(t.prototype,e),r&&fg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Cg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function JE(t,e,r){return e=$s(e),VE(t,Yc()?Reflect.construct(e,r||[],$s(t).constructor):e.apply(t,r))}function VE(t,e){if(e&&(Cr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return KE(t)}function KE(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function YE(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&qs(t,e)}function Wc(t){var e=typeof Map=="function"?new Map:void 0;return Wc=function(n){if(n===null||!QE(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,s)}function s(){return XE(n,arguments,$s(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),qs(s,n)},Wc(t)}function XE(t,e,r){if(Yc())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var s=new(t.bind.apply(t,n));return r&&qs(s,r.prototype),s}function Yc(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Yc=function(){return!!t})()}function QE(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function qs(t,e){return qs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},qs(t,e)}function $s(t){return $s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},$s(t)}function mt(t,e,r){return(e=wg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function wg(t){var e=ZE(t,"string");return Cr(e)=="symbol"?e:e+""}function ZE(t,e){if(Cr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Cr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",s=r.toStringTag||"@@toStringTag";function i(D,E,y,g){var m=E&&E.prototype instanceof c?E:c,T=Object.create(m.prototype);return gt(T,"_invoke",(function(b,w,O){var x,$,V,U=0,X=O||[],ne=!1,ae={p:0,n:0,v:t,a:de,f:de.bind(t,4),d:function(Ae,oe){return x=Ae,$=0,V=t,ae.n=oe,u}};function de(ye,Ae){for($=ye,V=Ae,e=0;!ne&&U&&!oe&&e<X.length;e++){var oe,pe=X[e],G=ae.p,K=pe[2];ye>3?(oe=K===Ae)&&(V=pe[($=pe[4])?5:($=3,3)],pe[4]=pe[5]=t):pe[0]<=G&&((oe=ye<2&&G<pe[1])?($=0,ae.v=Ae,ae.n=pe[1]):G<K&&(oe=ye<3||pe[0]>Ae||Ae>K)&&(pe[4]=ye,pe[5]=Ae,ae.n=K,$=0))}if(oe||ye>1)return u;throw ne=!0,Ae}return function(ye,Ae,oe){if(U>1)throw TypeError("Generator is already running");for(ne&&Ae===1&&de(Ae,oe),$=Ae,V=oe;(e=$<2?t:V)||!ne;){x||($?$<3?($>1&&(ae.n=-1),de($,V)):ae.n=V:ae.v=V);try{if(U=2,x){if($||(ye="next"),e=x[ye]){if(!(e=e.call(x,V)))throw TypeError("iterator result is not an object");if(!e.done)return e;V=e.value,$<2&&($=0)}else $===1&&(e=x.return)&&e.call(x),$<2&&(V=TypeError("The iterator does not provide a '"+ye+"' method"),$=1);x=t}else if((e=(ne=ae.n<0)?V:b.call(w,ae))!==u)break}catch(pe){x=t,$=1,V=pe}finally{U=1}}return{value:e,done:ne}}})(D,y,g),!0),T}var u={};function c(){}function l(){}function h(){}e=Object.getPrototypeOf;var f=[][n]?e(e([][n]())):(gt(e={},n,function(){return this}),e),p=h.prototype=c.prototype=Object.create(f);function S(D){return Object.setPrototypeOf?Object.setPrototypeOf(D,h):(D.__proto__=h,gt(D,s,"GeneratorFunction")),D.prototype=Object.create(p),D}return l.prototype=h,gt(p,"constructor",h),gt(h,"constructor",l),l.displayName="GeneratorFunction",gt(h,s,"GeneratorFunction"),gt(p),gt(p,s,"Generator"),gt(p,n,function(){return this}),gt(p,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:i,m:S}})()}function gt(t,e,r,n){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}gt=function(u,c,l,h){if(c)s?s(u,c,{value:l,enumerable:!h,configurable:!h,writable:!h}):u[c]=l;else{var f=function(S,D){gt(u,S,function(E){return this._invoke(S,D,E)})};f("next",0),f("throw",1),f("return",2)}},gt(t,e,r,n)}function hg(t,e,r,n,s,i,u){try{var c=t[i](u),l=c.value}catch(h){return void r(h)}c.done?e(l):Promise.resolve(l).then(n,s)}function Yn(t){return function(){var e=this,r=arguments;return new Promise(function(n,s){var i=t.apply(e,r);function u(l){hg(i,n,s,u,c,"next",l)}function c(l){hg(i,n,s,u,c,"throw",l)}u(void 0)})}}var pg=cg.readFile?(0,HE.promisify)(cg.readFile):Yn(yt().m(function t(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new Us("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),mg="https://oauth2.googleapis.com/token",eA="https://oauth2.googleapis.com/revoke?token=",Us=(function(t){function e(r,n){var s;return Cg(this,e),s=JE(this,e,[r]),mt(s,"code",void 0),s.code=n,s}return YE(e,t),bg(e)})(Wc(Error)),Ms=new WeakMap,er=new WeakSet,_1=ji.GoogleToken=(function(){function t(e){Cg(this,t),WE(this,er),mt(this,"expiresAt",void 0),mt(this,"key",void 0),mt(this,"keyFile",void 0),mt(this,"iss",void 0),mt(this,"sub",void 0),mt(this,"scope",void 0),mt(this,"rawToken",void 0),mt(this,"tokenExpires",void 0),mt(this,"email",void 0),mt(this,"additionalClaims",void 0),mt(this,"eagerRefreshThresholdMillis",void 0),mt(this,"transporter",{request:function(n){return(0,qE.request)(n)}}),GE(this,Ms,void 0),zt(er,this,Eg).call(this,e)}return bg(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),s=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+s:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Cr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var s=r;zt(er,this,gg).call(this,n).then(function(i){return s(null,i)},r);return}return zt(er,this,gg).call(this,n)}},{key:"getCredentials",value:(function(){var e=Yn(yt().m(function n(s){var i,u,c,l,h,f,p;return yt().w(function(S){for(;;)switch(S.n){case 0:i=zE.extname(s),p=i,S.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return S.n=2,pg(s,"utf8");case 2:if(u=S.v,c=JSON.parse(u),l=c.private_key,h=c.client_email,!(!l||!h)){S.n=3;break}throw new Us("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return S.a(2,{privateKey:l,clientEmail:h});case 4:return S.n=5,pg(s,"utf8");case 5:return f=S.v,S.a(2,{privateKey:f});case 6:throw new Us("*.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");case 7:throw new Us("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return S.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){zt(er,this,yg).call(this).then(function(){return r()},r);return}return zt(er,this,yg).call(this)}}])})();function gg(t){return Gc.apply(this,arguments)}function Gc(){return Gc=Yn(yt().m(function t(e){return yt().w(function(r){for(;;)switch(r.n){case 0:if(!(dg(Ms,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,dg(Ms,this));case 1:return r.p=1,r.n=2,lg(Ms,this,zt(er,this,tA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,lg(Ms,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),Gc.apply(this,arguments)}function tA(t){return Jc.apply(this,arguments)}function Jc(){return Jc=Yn(yt().m(function t(e){var r;return yt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||zt(er,this,rA).call(this);case 4:return n.a(2,zt(er,this,nA).call(this))}},t,this)})),Jc.apply(this,arguments)}function rA(){if(!this.iss)throw new Us("email is required.","MISSING_CREDENTIALS")}function yg(){return Vc.apply(this,arguments)}function Vc(){return Vc=Yn(yt().m(function t(){var e;return yt().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=eA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:zt(er,this,Eg).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),Vc.apply(this,arguments)}function Eg(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,Cr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function nA(){return Kc.apply(this,arguments)}function Kc(){return Kc=Yn(yt().m(function t(){var e,r,n,s,i,u,c,l,h,f;return yt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:mg,exp:e+3600,iat:e,sub:this.sub},r),s=$E.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:mg,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return i=p.v,this.rawToken=i.data,this.expiresAt=i.data.expires_in===null||i.data.expires_in===void 0?void 0:(e+i.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,f=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=f.response&&(u=f.response)!==null&&u!==void 0&&u.data?(c=f.response)===null||c===void 0?void 0:c.data:{},l.error&&(h=l.error_description?": ".concat(l.error_description):"",f.message="".concat(l.error).concat(h)),f;case 4:return p.a(2)}},t,this,[[1,3]])})),Kc.apply(this,arguments)}});var Qc=J(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.JWTAccess=void 0;var sA=Hc(),oA=Ut(),Sg={alg:"RS256",typ:"JWT"},Xc=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new oA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,s){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=s??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let s=this.getCachedKey(e,n),i=this.cache.get(s),u=Date.now();if(i&&i.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(i.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:h={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let E in h)if(r[E])throw new Error(`The '${E}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Sg,kid:this.keyId}:Sg,p=Object.assign(h,r),S=sA.sign({header:f,payload:p,secret:this.key}),D=new Headers({authorization:`Bearer ${S}`});return this.cache.set(s,{expiration:l*1e3,headers:D}),D}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let s="";e.setEncoding("utf8").on("data",i=>s+=i).on("error",n).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}};Li.JWTAccess=Xc});var el=J(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.JWT=void 0;var kg=Ag(),iA=Qc(),aA=dn(),Mi=pt(),Zc=class t extends aA.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Mi.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Mi.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Mi.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new iA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let s=this.useJWTAccessWithScope||this.universeDomain!==Mi.DEFAULT_UNIVERSE,i=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,s?n:void 0);return{headers:this.addSharedMetadataHeaders(i)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new kg.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(r=>e(null,r),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new kg.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Ui.JWT=Zc});var rl=J(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.UserRefreshClient=Xn.USER_REFRESH_ACCOUNT_TYPE=void 0;var uA=dn(),cA=pt();Xn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var tl=class t extends uA.OAuth2Client{_refreshToken;constructor(e,r,n,s,i){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:s,forceRefreshOnFailure:i};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let r={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return cA.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);return this.fromJSON(i),r()}catch(i){return n(i)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};Xn.UserRefreshClient=tl});var sl=J(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.Impersonated=Qn.IMPERSONATED_ACCOUNT_TYPE=void 0;var Tg=dn(),lA=Ve(),dA=Ut();Qn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var nl=class t extends Tg.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Tg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,dA.originalOrCamelOptions)(e).get("universe_domain"))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=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,s={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:s,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},s=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),i=s.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:s}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof lA.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,s=`${this.endpoint}/v1/${n}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:s,data:i,method:"POST"})).data.token}};Qn.Impersonated=nl});var il=J(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.OAuthClientAuthHandler=void 0;zs.getErrorFromOAuthErrorResponse=pA;var Zn=Ve(),fA=Ps(),hA=["PUT","POST","PATCH"],ol=class{#e=(0,fA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Zn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Zn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=Zn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=Zn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Zn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,s=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${n}:${s}`);Zn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!hA.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let s=new Headers(e.headers).get("content-type");if(s?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let i=new URLSearchParams(e.data??"");i.append("client_id",this.#t.clientId),i.append("client_secret",this.#t.clientSecret||""),e.data=i}else if(s?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${s} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};zs.OAuthClientAuthHandler=ol;function pA(t,e){let r=t.error,n=t.error_description,s=t.error_uri,i=`Error code ${r}`;typeof n<"u"&&(i+=`: ${n}`),typeof s<"u"&&(i+=` - ${s}`);let u=new Error(i);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(u,l,{value:e[l],writable:!1,enumerable:!0})})}return u}});var $i=J(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.StsCredentials=void 0;var mA=Ve(),gA=pt(),Dg=il(),yA=Ut(),al=class t extends Dg.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){let s={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},i={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,yA.removeUndefinedValuesInObject)(s))};gA.AuthClient.setMethodName(i,"exchangeToken"),this.applyClientAuthenticationOptions(i);try{let u=await this.transporter.request(i),c=u.data;return c.res=u,c}catch(u){throw u instanceof mA.GaxiosError&&u.response?(0,Dg.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};qi.StsCredentials=al});var zr=J(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.BaseExternalAccountClient=Dt.CLOUD_RESOURCE_MANAGER=Dt.EXTERNAL_ACCOUNT_TYPE=Dt.EXPIRATION_TIME_OFFSET=void 0;var _A=Ve(),bA=Q("stream"),ul=pt(),CA=$i(),vg=Ut(),wA=Ac(),EA="urn:ietf:params:oauth:grant-type:token-exchange",AA="urn:ietf:params:oauth:token-type:access_token",cl="https://www.googleapis.com/auth/cloud-platform",SA=3600;Dt.EXPIRATION_TIME_OFFSET=300*1e3;Dt.EXTERNAL_ACCOUNT_TYPE="external_account";Dt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var kA="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",TA="https://sts.{universeDomain}/v1/token",ll=class t extends ul.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,vg.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Dt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Dt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let s=r.get("client_id"),i=r.get("client_secret");this.tokenUrl=r.get("token_url")??TA.replace("{universeDomain}",this.universeDomain);let u=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),h=r.get("service_account_impersonation"),f=(0,vg.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),s&&(this.clientAuth={confidentialClientType:"basic",clientId:s,clientSecret:i}),this.stsCredential=new CA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[cl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=c;let p=new RegExp(kA);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=SA),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};ul.AuthClient.setMethodName(n,"getProjectId");let s=await this.transporter.request(n);return this.projectId=s.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=_A.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof bA.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:EA,audience:this.audience,requestedTokenType:AA,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[cl]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,s=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(r,s,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+i.expires_in*1e3,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.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}),this.cachedAccessToken}getProjectNumber(e){let r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};ul.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),s=n.data;return{access_token:s.accessToken,expiry_date:new Date(s.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[cl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${wA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Dt.BaseExternalAccountClient=ll});var Rg=J(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.FileSubjectTokenSupplier=void 0;var fl=Q("util"),hl=Q("fs"),DA=(0,fl.promisify)(hl.readFile??(()=>{})),vA=(0,fl.promisify)(hl.realpath??(()=>{})),RA=(0,fl.promisify)(hl.lstat??(()=>{})),dl=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await vA(e),!(await RA(e)).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let r,n=await DA(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};zi.FileSubjectTokenSupplier=dl});var Og=J(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.UrlSubjectTokenSupplier=void 0;var OA=pt(),pl=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};OA.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};Hi.UrlSubjectTokenSupplier=pl});var Fg=J(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Wi=Ut(),Gi=Q("fs"),Ji=Q("crypto"),FA=Q("https");_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var tr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};_t.CertificateSourceUnavailableError=tr;var vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};_t.InvalidConfigurationError=vt;var ml=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new vt("Cannot create mTLS Agent with missing certificate or key");return new FA.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Wi.isValidFile)(e))return e;throw new tr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,Wi.isValidFile)(r))return r;throw new tr(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,Wi.getWellKnownCertificateConfigFileLocation)();if(await(0,Wi.isValidFile)(n))return n;throw new tr(`Could not find certificate configuration file. Searched override path, the "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await Gi.promises.readFile(e,"utf8")}catch{throw new tr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),s=n?.cert_configs?.workload?.cert_path,i=n?.cert_configs?.workload?.key_path;if(!s||!i)throw new vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:s,keyPath:i}}catch(n){throw n instanceof vt?n:new vt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,s;try{n=await Gi.promises.readFile(e),new Ji.X509Certificate(n)}catch(i){let u=i instanceof Error?i.message:String(i);throw new tr(`Failed to read certificate file at ${e}: ${u}`)}try{s=await Gi.promises.readFile(r),(0,Ji.createPrivateKey)(s)}catch(i){let u=i instanceof Error?i.message:String(i);throw new tr(`Failed to read private key file at ${r}: ${u}`)}return{cert:n,key:s}}async#n(e){let r=new Ji.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let i=((await Gi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new Ji.X509Certificate(l)}catch(f){let p=f instanceof Error?f.message:String(f);throw new vt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${p}`)}}),u=i.findIndex(l=>r.raw.equals(l.raw)),c;if(u===-1)c=[r,...i];else if(u===0)c=i;else throw new vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof vt)throw n;let s=n instanceof Error?n.message:String(n);throw new tr(`Failed to process certificate chain from ${this.trustChainPath}: ${s}`)}}};_t.CertificateSubjectTokenSupplier=ml});var _l=J(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.IdentityPoolClient=void 0;var xA=zr(),gl=Ut(),PA=Rg(),IA=Og(),xg=Fg(),NA=$i(),Pg=Ve(),yl=class t extends xA.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,gl.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("subject_token_supplier");if(!n&&!s)throw new Error("A credential source or subject token supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or subject token supplier can be specified.");if(s)this.subjectTokenSupplier=s,this.credentialSourceType="programmatic";else{let i=(0,gl.originalOrCamelOptions)(n),u=(0,gl.originalOrCamelOptions)(i.get("format")),c=u.get("type")||"text",l=u.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=i.get("file"),f=i.get("url"),p=i.get("certificate"),S=i.get("headers");if(h&&f||f&&p||h&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new PA.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new IA.UrlSubjectTokenSupplier({url:f,formatType:c,subjectTokenFieldName:l,headers:S,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let D=new xg.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=D}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof xg.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new NA.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Pg.Gaxios({agent:r})}),this.transporter=new Pg.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};Vi.IdentityPoolClient=yl});var Cl=J(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.AwsRequestSigner=void 0;var Ki=Ve(),Ng=Ps(),Ig="AWS4-HMAC-SHA256",BA="aws4_request",bl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,Ng.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,s=e.method||"GET",i=e.body||r,u=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof i!="string"&&i!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${i}`);let h=await LA({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:s,region:this.region,securityCredentials:c,requestPayload:i,additionalAmzHeaders:u}),f=Ki.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},u||{});c.token&&Ki.Gaxios.mergeHeaders(f,{"x-amz-security-token":c.token});let p={url:n,method:s,headers:f};return i!==void 0&&(p.body=i),p}};Yi.AwsRequestSigner=bl;async function Hs(t,e,r){return await t.signWithHmacSha256(e,r)}async function jA(t,e,r,n,s){let i=await Hs(t,`AWS4${e}`,r),u=await Hs(t,i,n),c=await Hs(t,u,s);return await Hs(t,c,"aws4_request")}async function LA(t){let e=Ki.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],s=new Date,i=s.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=s.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Ki.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":i},e),l="",h=[...c.keys()].sort();h.forEach(T=>{l+=`${T}:${c.get(T)}
53
- `});let f=h.join(";"),p=await t.crypto.sha256DigestHex(r),S=`${t.method.toUpperCase()}
52
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,js="secret must be a string or buffer",Jn="key must be a string or a buffer",yE="key must be a string, a buffer or an object",Mc=typeof Tt.createPublicKey=="function";Mc&&(Jn+=" or a KeyObject",js+="or a KeyObject");function Lm(t){if(!Vn.isBuffer(t)&&typeof t!="string"&&(!Mc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw $t(Jn)}function Mm(t){if(!Vn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw $t(yE)}function _E(t){if(!Vn.isBuffer(t)){if(typeof t=="string")return t;if(!Mc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw $t(js)}}function Uc(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Um(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function $t(t){var e=[].slice.call(arguments,1),r=Bm.format.bind(Bm,t).apply(null,e);return new TypeError(r)}function bE(t){return Vn.isBuffer(t)||typeof t=="string"}function Ls(t){return bE(t)||(t=JSON.stringify(t)),t}function qm(t){return function(r,n){_E(n),r=Ls(r);var s=Tt.createHmac("sha"+t,n),i=(s.update(r),s.digest("base64"));return Uc(i)}}var Lc,CE="timingSafeEqual"in Tt?function(e,r){return e.byteLength!==r.byteLength?!1:Tt.timingSafeEqual(e,r)}:function(e,r){return Lc||(Lc=Nm()),Lc(e,r)};function wE(t){return function(r,n,s){var i=qm(t)(r,s);return CE(Vn.from(n),Vn.from(i))}}function $m(t){return function(r,n){Mm(n),r=Ls(r);var s=Tt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign(n,"base64"));return Uc(i)}}function zm(t){return function(r,n,s){Lm(s),r=Ls(r),n=Um(n);var i=Tt.createVerify("RSA-SHA"+t);return i.update(r),i.verify(s,n,"base64")}}function EE(t){return function(r,n){Mm(n),r=Ls(r);var s=Tt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign({key:n,padding:Tt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Tt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Uc(i)}}function AE(t){return function(r,n,s){Lm(s),r=Ls(r),n=Um(n);var i=Tt.createVerify("RSA-SHA"+t);return i.update(r),i.verify({key:s,padding:Tt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Tt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function SE(t){var e=$m(t);return function(){var n=e.apply(null,arguments);return n=jm.derToJose(n,"ES"+t),n}}function kE(t){var e=zm(t);return function(n,s,i){s=jm.joseToDer(s,"ES"+t).toString("base64");var u=e(n,s,i);return u}}function TE(){return function(){return""}}function DE(){return function(e,r){return r===""}}Hm.exports=function(e){var r={hs:qm,rs:$m,ps:EE,es:SE,none:TE},n={hs:wE,rs:zm,ps:AE,es:kE,none:DE},s=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw $t(gE,e);var i=(s[1]||s[3]).toLowerCase(),u=s[2];return{sign:r[i](u),verify:n[i](u)}}});var $c=V((g1,Wm)=>{var vE=Q("buffer").Buffer;Wm.exports=function(e){return typeof e=="string"?e:typeof e=="number"||vE.isBuffer(e)?e.toString():JSON.stringify(e)}});var Xm=V((y1,Ym)=>{var RE=Hn().Buffer,Gm=Bc(),OE=qc(),FE=Q("stream"),Jm=$c(),zc=Q("util");function Vm(t,e){return RE.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function xE(t,e,r){r=r||"utf8";var n=Vm(Jm(t),"binary"),s=Vm(Jm(e),r);return zc.format("%s.%s",n,s)}function Km(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,s=t.encoding,i=OE(e.alg),u=xE(e,r,s),c=i.sign(u,n);return zc.format("%s.%s",u,c)}function Ii(t){var e=t.secret||t.privateKey||t.key,r=new Gm(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Gm(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}zc.inherits(Ii,FE);Ii.prototype.sign=function(){try{var e=Km({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Ii.sign=Km;Ym.exports=Ii});var ag=V((_1,ig)=>{var Zm=Hn().Buffer,Qm=Bc(),PE=qc(),IE=Q("stream"),eg=$c(),NE=Q("util"),BE=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function jE(t){return Object.prototype.toString.call(t)==="[object Object]"}function LE(t){if(jE(t))return t;try{return JSON.parse(t)}catch{return}}function tg(t){var e=t.split(".",1)[0];return LE(Zm.from(e,"base64").toString("binary"))}function ME(t){return t.split(".",2).join(".")}function rg(t){return t.split(".")[2]}function UE(t,e){e=e||"utf8";var r=t.split(".")[1];return Zm.from(r,"base64").toString(e)}function ng(t){return BE.test(t)&&!!tg(t)}function sg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=eg(t);var s=rg(t),i=ME(t),u=PE(e);return u.verify(i,s,r)}function og(t,e){if(e=e||{},t=eg(t),!ng(t))return null;var r=tg(t);if(!r)return null;var n=UE(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:rg(t)}}function Kn(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Qm(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Qm(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}NE.inherits(Kn,IE);Kn.prototype.verify=function(){try{var e=sg(this.signature.buffer,this.algorithm,this.key.buffer),r=og(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Kn.decode=og;Kn.isValid=ng;Kn.verify=sg;ig.exports=Kn});var Hc=V($r=>{var ug=Xm(),Ni=ag(),qE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];$r.ALGORITHMS=qE;$r.sign=ug.sign;$r.verify=Ni.verify;$r.decode=Ni.decode;$r.isValid=Ni.isValid;$r.createSign=function(e){return new ug(e)};$r.createVerify=function(e){return new Ni(e)}});var Ag=V(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.GoogleToken=void 0;var cg=Bi(Q("fs")),$E=Ve(),zE=Bi(Hc()),HE=Bi(Q("path")),WE=Q("util");function Bi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Bi=function(i,u){if(!u&&i&&i.__esModule)return i;var c,l,h={__proto__:null,default:i};if(i===null||Cr(i)!="object"&&typeof i!="function")return h;if(c=u?n:r){if(c.has(i))return c.get(i);c.set(i,h)}for(var f in i)f!=="default"&&{}.hasOwnProperty.call(i,f)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(i,f))&&(l.get||l.set)?c(h,f,l):h[f]=i[f]);return h})(t,e)}function Cr(t){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(t)}function GE(t,e){_g(t,e),e.add(t)}function JE(t,e,r){_g(t,e),e.set(t,r)}function _g(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function lg(t,e,r){return t.set(zt(t,e),r),r}function dg(t,e){return t.get(zt(t,e))}function zt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function fg(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,wg(n.key),n)}}function bg(t,e,r){return e&&fg(t.prototype,e),r&&fg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Cg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function VE(t,e,r){return e=$s(e),KE(t,Yc()?Reflect.construct(e,r||[],$s(t).constructor):e.apply(t,r))}function KE(t,e){if(e&&(Cr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return YE(t)}function YE(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function XE(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&qs(t,e)}function Wc(t){var e=typeof Map=="function"?new Map:void 0;return Wc=function(n){if(n===null||!ZE(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,s)}function s(){return QE(n,arguments,$s(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),qs(s,n)},Wc(t)}function QE(t,e,r){if(Yc())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var s=new(t.bind.apply(t,n));return r&&qs(s,r.prototype),s}function Yc(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Yc=function(){return!!t})()}function ZE(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function qs(t,e){return qs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},qs(t,e)}function $s(t){return $s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},$s(t)}function mt(t,e,r){return(e=wg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function wg(t){var e=eA(t,"string");return Cr(e)=="symbol"?e:e+""}function eA(t,e){if(Cr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Cr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",s=r.toStringTag||"@@toStringTag";function i(v,S,y,g){var m=S&&S.prototype instanceof c?S:c,k=Object.create(m.prototype);return gt(k,"_invoke",(function(b,E,R){var x,$,J,M=0,X=R||[],ue=!1,re={p:0,n:0,v:t,a:de,f:de.bind(t,4),d:function(Ae,oe){return x=Ae,$=0,J=t,re.n=oe,u}};function de(pe,Ae){for($=pe,J=Ae,e=0;!ue&&M&&!oe&&e<X.length;e++){var oe,me=X[e],G=re.p,K=me[2];pe>3?(oe=K===Ae)&&(J=me[($=me[4])?5:($=3,3)],me[4]=me[5]=t):me[0]<=G&&((oe=pe<2&&G<me[1])?($=0,re.v=Ae,re.n=me[1]):G<K&&(oe=pe<3||me[0]>Ae||Ae>K)&&(me[4]=pe,me[5]=Ae,re.n=K,$=0))}if(oe||pe>1)return u;throw ue=!0,Ae}return function(pe,Ae,oe){if(M>1)throw TypeError("Generator is already running");for(ue&&Ae===1&&de(Ae,oe),$=Ae,J=oe;(e=$<2?t:J)||!ue;){x||($?$<3?($>1&&(re.n=-1),de($,J)):re.n=J:re.v=J);try{if(M=2,x){if($||(pe="next"),e=x[pe]){if(!(e=e.call(x,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,$<2&&($=0)}else $===1&&(e=x.return)&&e.call(x),$<2&&(J=TypeError("The iterator does not provide a '"+pe+"' method"),$=1);x=t}else if((e=(ue=re.n<0)?J:b.call(E,re))!==u)break}catch(me){x=t,$=1,J=me}finally{M=1}}return{value:e,done:ue}}})(v,y,g),!0),k}var u={};function c(){}function l(){}function h(){}e=Object.getPrototypeOf;var f=[][n]?e(e([][n]())):(gt(e={},n,function(){return this}),e),p=h.prototype=c.prototype=Object.create(f);function A(v){return Object.setPrototypeOf?Object.setPrototypeOf(v,h):(v.__proto__=h,gt(v,s,"GeneratorFunction")),v.prototype=Object.create(p),v}return l.prototype=h,gt(p,"constructor",h),gt(h,"constructor",l),l.displayName="GeneratorFunction",gt(h,s,"GeneratorFunction"),gt(p),gt(p,s,"Generator"),gt(p,n,function(){return this}),gt(p,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:i,m:A}})()}function gt(t,e,r,n){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}gt=function(u,c,l,h){if(c)s?s(u,c,{value:l,enumerable:!h,configurable:!h,writable:!h}):u[c]=l;else{var f=function(A,v){gt(u,A,function(S){return this._invoke(A,v,S)})};f("next",0),f("throw",1),f("return",2)}},gt(t,e,r,n)}function hg(t,e,r,n,s,i,u){try{var c=t[i](u),l=c.value}catch(h){return void r(h)}c.done?e(l):Promise.resolve(l).then(n,s)}function Yn(t){return function(){var e=this,r=arguments;return new Promise(function(n,s){var i=t.apply(e,r);function u(l){hg(i,n,s,u,c,"next",l)}function c(l){hg(i,n,s,u,c,"throw",l)}u(void 0)})}}var pg=cg.readFile?(0,WE.promisify)(cg.readFile):Yn(yt().m(function t(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new Us("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),mg="https://oauth2.googleapis.com/token",tA="https://oauth2.googleapis.com/revoke?token=",Us=(function(t){function e(r,n){var s;return Cg(this,e),s=VE(this,e,[r]),mt(s,"code",void 0),s.code=n,s}return XE(e,t),bg(e)})(Wc(Error)),Ms=new WeakMap,er=new WeakSet,C1=ji.GoogleToken=(function(){function t(e){Cg(this,t),GE(this,er),mt(this,"expiresAt",void 0),mt(this,"key",void 0),mt(this,"keyFile",void 0),mt(this,"iss",void 0),mt(this,"sub",void 0),mt(this,"scope",void 0),mt(this,"rawToken",void 0),mt(this,"tokenExpires",void 0),mt(this,"email",void 0),mt(this,"additionalClaims",void 0),mt(this,"eagerRefreshThresholdMillis",void 0),mt(this,"transporter",{request:function(n){return(0,$E.request)(n)}}),JE(this,Ms,void 0),zt(er,this,Eg).call(this,e)}return bg(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),s=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+s:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Cr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var s=r;zt(er,this,gg).call(this,n).then(function(i){return s(null,i)},r);return}return zt(er,this,gg).call(this,n)}},{key:"getCredentials",value:(function(){var e=Yn(yt().m(function n(s){var i,u,c,l,h,f,p;return yt().w(function(A){for(;;)switch(A.n){case 0:i=HE.extname(s),p=i,A.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return A.n=2,pg(s,"utf8");case 2:if(u=A.v,c=JSON.parse(u),l=c.private_key,h=c.client_email,!(!l||!h)){A.n=3;break}throw new Us("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return A.a(2,{privateKey:l,clientEmail:h});case 4:return A.n=5,pg(s,"utf8");case 5:return f=A.v,A.a(2,{privateKey:f});case 6:throw new Us("*.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");case 7:throw new Us("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return A.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){zt(er,this,yg).call(this).then(function(){return r()},r);return}return zt(er,this,yg).call(this)}}])})();function gg(t){return Gc.apply(this,arguments)}function Gc(){return Gc=Yn(yt().m(function t(e){return yt().w(function(r){for(;;)switch(r.n){case 0:if(!(dg(Ms,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,dg(Ms,this));case 1:return r.p=1,r.n=2,lg(Ms,this,zt(er,this,rA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,lg(Ms,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),Gc.apply(this,arguments)}function rA(t){return Jc.apply(this,arguments)}function Jc(){return Jc=Yn(yt().m(function t(e){var r;return yt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||zt(er,this,nA).call(this);case 4:return n.a(2,zt(er,this,sA).call(this))}},t,this)})),Jc.apply(this,arguments)}function nA(){if(!this.iss)throw new Us("email is required.","MISSING_CREDENTIALS")}function yg(){return Vc.apply(this,arguments)}function Vc(){return Vc=Yn(yt().m(function t(){var e;return yt().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=tA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:zt(er,this,Eg).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),Vc.apply(this,arguments)}function Eg(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,Cr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function sA(){return Kc.apply(this,arguments)}function Kc(){return Kc=Yn(yt().m(function t(){var e,r,n,s,i,u,c,l,h,f;return yt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:mg,exp:e+3600,iat:e,sub:this.sub},r),s=zE.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:mg,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return i=p.v,this.rawToken=i.data,this.expiresAt=i.data.expires_in===null||i.data.expires_in===void 0?void 0:(e+i.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,f=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=f.response&&(u=f.response)!==null&&u!==void 0&&u.data?(c=f.response)===null||c===void 0?void 0:c.data:{},l.error&&(h=l.error_description?": ".concat(l.error_description):"",f.message="".concat(l.error).concat(h)),f;case 4:return p.a(2)}},t,this,[[1,3]])})),Kc.apply(this,arguments)}});var Qc=V(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.JWTAccess=void 0;var oA=Hc(),iA=Ut(),Sg={alg:"RS256",typ:"JWT"},Xc=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new iA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,s){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=s??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let s=this.getCachedKey(e,n),i=this.cache.get(s),u=Date.now();if(i&&i.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(i.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:h={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let S in h)if(r[S])throw new Error(`The '${S}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Sg,kid:this.keyId}:Sg,p=Object.assign(h,r),A=oA.sign({header:f,payload:p,secret:this.key}),v=new Headers({authorization:`Bearer ${A}`});return this.cache.set(s,{expiration:l*1e3,headers:v}),v}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let s="";e.setEncoding("utf8").on("data",i=>s+=i).on("error",n).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}};Li.JWTAccess=Xc});var el=V(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.JWT=void 0;var kg=Ag(),aA=Qc(),uA=dn(),Mi=pt(),Zc=class t extends uA.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Mi.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Mi.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Mi.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new aA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let s=this.useJWTAccessWithScope||this.universeDomain!==Mi.DEFAULT_UNIVERSE,i=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,s?n:void 0);return{headers:this.addSharedMetadataHeaders(i)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new kg.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(r=>e(null,r),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new kg.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Ui.JWT=Zc});var rl=V(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.UserRefreshClient=Xn.USER_REFRESH_ACCOUNT_TYPE=void 0;var cA=dn(),lA=pt();Xn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var tl=class t extends cA.OAuth2Client{_refreshToken;constructor(e,r,n,s,i){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:s,forceRefreshOnFailure:i};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let r={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return lA.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);return this.fromJSON(i),r()}catch(i){return n(i)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};Xn.UserRefreshClient=tl});var sl=V(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.Impersonated=Qn.IMPERSONATED_ACCOUNT_TYPE=void 0;var Tg=dn(),dA=Ve(),fA=Ut();Qn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var nl=class t extends Tg.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Tg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,fA.originalOrCamelOptions)(e).get("universe_domain"))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=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,s={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:s,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},s=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),i=s.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:s}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof dA.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,s=`${this.endpoint}/v1/${n}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:s,data:i,method:"POST"})).data.token}};Qn.Impersonated=nl});var il=V(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.OAuthClientAuthHandler=void 0;zs.getErrorFromOAuthErrorResponse=mA;var Zn=Ve(),hA=Ps(),pA=["PUT","POST","PATCH"],ol=class{#e=(0,hA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Zn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Zn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=Zn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=Zn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Zn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,s=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${n}:${s}`);Zn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!pA.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let s=new Headers(e.headers).get("content-type");if(s?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let i=new URLSearchParams(e.data??"");i.append("client_id",this.#t.clientId),i.append("client_secret",this.#t.clientSecret||""),e.data=i}else if(s?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${s} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};zs.OAuthClientAuthHandler=ol;function mA(t,e){let r=t.error,n=t.error_description,s=t.error_uri,i=`Error code ${r}`;typeof n<"u"&&(i+=`: ${n}`),typeof s<"u"&&(i+=` - ${s}`);let u=new Error(i);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(u,l,{value:e[l],writable:!1,enumerable:!0})})}return u}});var $i=V(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.StsCredentials=void 0;var gA=Ve(),yA=pt(),Dg=il(),_A=Ut(),al=class t extends Dg.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){let s={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},i={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,_A.removeUndefinedValuesInObject)(s))};yA.AuthClient.setMethodName(i,"exchangeToken"),this.applyClientAuthenticationOptions(i);try{let u=await this.transporter.request(i),c=u.data;return c.res=u,c}catch(u){throw u instanceof gA.GaxiosError&&u.response?(0,Dg.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};qi.StsCredentials=al});var zr=V(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.BaseExternalAccountClient=Dt.CLOUD_RESOURCE_MANAGER=Dt.EXTERNAL_ACCOUNT_TYPE=Dt.EXPIRATION_TIME_OFFSET=void 0;var bA=Ve(),CA=Q("stream"),ul=pt(),wA=$i(),vg=Ut(),EA=Ac(),AA="urn:ietf:params:oauth:grant-type:token-exchange",SA="urn:ietf:params:oauth:token-type:access_token",cl="https://www.googleapis.com/auth/cloud-platform",kA=3600;Dt.EXPIRATION_TIME_OFFSET=300*1e3;Dt.EXTERNAL_ACCOUNT_TYPE="external_account";Dt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var TA="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",DA="https://sts.{universeDomain}/v1/token",ll=class t extends ul.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,vg.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Dt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Dt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let s=r.get("client_id"),i=r.get("client_secret");this.tokenUrl=r.get("token_url")??DA.replace("{universeDomain}",this.universeDomain);let u=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),h=r.get("service_account_impersonation"),f=(0,vg.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),s&&(this.clientAuth={confidentialClientType:"basic",clientId:s,clientSecret:i}),this.stsCredential=new wA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[cl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=c;let p=new RegExp(TA);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=kA),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};ul.AuthClient.setMethodName(n,"getProjectId");let s=await this.transporter.request(n);return this.projectId=s.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=bA.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof CA.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:AA,audience:this.audience,requestedTokenType:SA,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[cl]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,s=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(r,s,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+i.expires_in*1e3,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.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}),this.cachedAccessToken}getProjectNumber(e){let r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};ul.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),s=n.data;return{access_token:s.accessToken,expiry_date:new Date(s.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[cl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${EA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Dt.BaseExternalAccountClient=ll});var Rg=V(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.FileSubjectTokenSupplier=void 0;var fl=Q("util"),hl=Q("fs"),vA=(0,fl.promisify)(hl.readFile??(()=>{})),RA=(0,fl.promisify)(hl.realpath??(()=>{})),OA=(0,fl.promisify)(hl.lstat??(()=>{})),dl=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await RA(e),!(await OA(e)).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let r,n=await vA(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};zi.FileSubjectTokenSupplier=dl});var Og=V(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.UrlSubjectTokenSupplier=void 0;var FA=pt(),pl=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};FA.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};Hi.UrlSubjectTokenSupplier=pl});var Fg=V(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Wi=Ut(),Gi=Q("fs"),Ji=Q("crypto"),xA=Q("https");_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var tr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};_t.CertificateSourceUnavailableError=tr;var vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};_t.InvalidConfigurationError=vt;var ml=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new vt("Cannot create mTLS Agent with missing certificate or key");return new xA.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Wi.isValidFile)(e))return e;throw new tr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,Wi.isValidFile)(r))return r;throw new tr(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,Wi.getWellKnownCertificateConfigFileLocation)();if(await(0,Wi.isValidFile)(n))return n;throw new tr(`Could not find certificate configuration file. Searched override path, the "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await Gi.promises.readFile(e,"utf8")}catch{throw new tr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),s=n?.cert_configs?.workload?.cert_path,i=n?.cert_configs?.workload?.key_path;if(!s||!i)throw new vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:s,keyPath:i}}catch(n){throw n instanceof vt?n:new vt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,s;try{n=await Gi.promises.readFile(e),new Ji.X509Certificate(n)}catch(i){let u=i instanceof Error?i.message:String(i);throw new tr(`Failed to read certificate file at ${e}: ${u}`)}try{s=await Gi.promises.readFile(r),(0,Ji.createPrivateKey)(s)}catch(i){let u=i instanceof Error?i.message:String(i);throw new tr(`Failed to read private key file at ${r}: ${u}`)}return{cert:n,key:s}}async#n(e){let r=new Ji.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let i=((await Gi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new Ji.X509Certificate(l)}catch(f){let p=f instanceof Error?f.message:String(f);throw new vt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${p}`)}}),u=i.findIndex(l=>r.raw.equals(l.raw)),c;if(u===-1)c=[r,...i];else if(u===0)c=i;else throw new vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof vt)throw n;let s=n instanceof Error?n.message:String(n);throw new tr(`Failed to process certificate chain from ${this.trustChainPath}: ${s}`)}}};_t.CertificateSubjectTokenSupplier=ml});var _l=V(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.IdentityPoolClient=void 0;var PA=zr(),gl=Ut(),IA=Rg(),NA=Og(),xg=Fg(),BA=$i(),Pg=Ve(),yl=class t extends PA.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,gl.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("subject_token_supplier");if(!n&&!s)throw new Error("A credential source or subject token supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or subject token supplier can be specified.");if(s)this.subjectTokenSupplier=s,this.credentialSourceType="programmatic";else{let i=(0,gl.originalOrCamelOptions)(n),u=(0,gl.originalOrCamelOptions)(i.get("format")),c=u.get("type")||"text",l=u.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=i.get("file"),f=i.get("url"),p=i.get("certificate"),A=i.get("headers");if(h&&f||f&&p||h&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new IA.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new NA.UrlSubjectTokenSupplier({url:f,formatType:c,subjectTokenFieldName:l,headers:A,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let v=new xg.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=v}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof xg.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new BA.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Pg.Gaxios({agent:r})}),this.transporter=new Pg.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};Vi.IdentityPoolClient=yl});var Cl=V(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.AwsRequestSigner=void 0;var Ki=Ve(),Ng=Ps(),Ig="AWS4-HMAC-SHA256",jA="aws4_request",bl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,Ng.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,s=e.method||"GET",i=e.body||r,u=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof i!="string"&&i!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${i}`);let h=await MA({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:s,region:this.region,securityCredentials:c,requestPayload:i,additionalAmzHeaders:u}),f=Ki.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},u||{});c.token&&Ki.Gaxios.mergeHeaders(f,{"x-amz-security-token":c.token});let p={url:n,method:s,headers:f};return i!==void 0&&(p.body=i),p}};Yi.AwsRequestSigner=bl;async function Hs(t,e,r){return await t.signWithHmacSha256(e,r)}async function LA(t,e,r,n,s){let i=await Hs(t,`AWS4${e}`,r),u=await Hs(t,i,n),c=await Hs(t,u,s);return await Hs(t,c,"aws4_request")}async function MA(t){let e=Ki.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],s=new Date,i=s.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=s.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Ki.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":i},e),l="",h=[...c.keys()].sort();h.forEach(k=>{l+=`${k}:${c.get(k)}
53
+ `});let f=h.join(";"),p=await t.crypto.sha256DigestHex(r),A=`${t.method.toUpperCase()}
54
54
  ${t.canonicalUri}
55
55
  ${t.canonicalQuerystring}
56
56
  ${l}
57
57
  ${f}
58
- ${p}`,D=`${u}/${t.region}/${n}/${BA}`,E=`${Ig}
58
+ ${p}`,v=`${u}/${t.region}/${n}/${jA}`,S=`${Ig}
59
59
  ${i}
60
- ${D}
61
- `+await t.crypto.sha256DigestHex(S),y=await jA(t.crypto,t.securityCredentials.secretAccessKey,u,t.region,n),g=await Hs(t.crypto,y,E),m=`${Ig} Credential=${t.securityCredentials.accessKeyId}/${D}, SignedHeaders=${f}, Signature=${(0,Ng.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:i,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var Bg=J(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.DefaultAwsSecurityCredentialsSupplier=void 0;var Xi=pt(),wl=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};Xi.AuthClient.setMethodName(n,"getAwsRegion");let s=await e.transporter.request(n);return s.data.substr(0,s.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),s=await this.#r(n,r,e.transporter);return{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,token:s.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Xi.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Xi.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let s={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return Xi.AuthClient.setMethodName(s,"#retrieveAwsSecurityCredentials"),(await n.request(s)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Qi.DefaultAwsSecurityCredentialsSupplier=wl});var Al=J(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.AwsClient=void 0;var MA=Cl(),UA=zr(),qA=Bg(),jg=Ut(),$A=Ve(),El=class t extends UA.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let r=(0,jg.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("aws_security_credentials_supplier");if(!n&&!s)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(s)this.awsSecurityCredentialsSupplier=s,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let i=(0,jg.originalOrCamelOptions)(n);this.environmentId=i.get("environment_id");let u=i.get("region_url"),c=i.get("url"),l=i.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new qA.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=i.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new MA.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),r=[];return $A.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((s,i)=>r.push({key:i,value:s})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};Zi.AwsClient=El});var vl=J(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.InvalidSubjectTokenError=Le.InvalidMessageFieldError=Le.InvalidCodeFieldError=Le.InvalidTokenTypeFieldError=Le.InvalidExpirationTimeFieldError=Le.InvalidSuccessFieldError=Le.InvalidVersionFieldError=Le.ExecutableResponseError=Le.ExecutableResponse=void 0;var ea="urn:ietf:params:oauth:token-type:saml2",Sl="urn:ietf:params:oauth:token-type:id_token",kl="urn:ietf:params:oauth:token-type:jwt",Tl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new ta("Executable response must contain a 'version' field.");if(e.success===void 0)throw new ra("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==ea&&this.tokenType!==Sl&&this.tokenType!==kl)throw new na(`Executable response must contain a 'token_type' field when successful and it must be one of ${Sl}, ${kl}, or ${ea}.`);if(this.tokenType===ea){if(!e.saml_response)throw new Ws(`Executable response must contain a 'saml_response' field when token_type=${ea}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Ws(`Executable response must contain a 'id_token' field when token_type=${Sl} or ${kl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new sa("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new oa("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Le.ExecutableResponse=Tl;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=rr;var ta=class extends rr{};Le.InvalidVersionFieldError=ta;var ra=class extends rr{};Le.InvalidSuccessFieldError=ra;var Dl=class extends rr{};Le.InvalidExpirationTimeFieldError=Dl;var na=class extends rr{};Le.InvalidTokenTypeFieldError=na;var sa=class extends rr{};Le.InvalidCodeFieldError=sa;var oa=class extends rr{};Le.InvalidMessageFieldError=oa;var Ws=class extends rr{};Le.InvalidSubjectTokenError=Ws});var Fl=J(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.PluggableAuthHandler=es.ExecutableError=void 0;var fn=vl(),zA=Q("child_process"),Rl=Q("fs"),ia=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};es.ExecutableError=ia;var Ol=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((r,n)=>{let s=zA.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),i="";s.stdout.on("data",c=>{i+=c}),s.stderr.on("data",c=>{i+=c});let u=setTimeout(()=>(s.removeAllListeners(),s.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);s.on("close",c=>{if(clearTimeout(u),c===0)try{let l=JSON.parse(i),h=new fn.ExecutableResponse(l);return r(h)}catch(l){return l instanceof fn.ExecutableResponseError?n(l):n(new fn.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return n(new ia(i,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Rl.promises.realpath(this.outputFile)}catch{return}if(!(await Rl.promises.lstat(e)).isFile())return;let r=await Rl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new fn.ExecutableResponse(n).isValid()?new fn.ExecutableResponse(n):void 0}catch(n){throw n instanceof fn.ExecutableResponseError?n:new fn.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};es.PluggableAuthHandler=Ol});var Pl=J(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.PluggableAuthClient=ts.ExecutableError=void 0;var HA=zr(),WA=vl(),Lg=Fl(),GA=Fl();Object.defineProperty(ts,"ExecutableError",{enumerable:!0,get:function(){return GA.ExecutableError}});var JA=30*1e3,Mg=5*1e3,Ug=120*1e3,VA="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",qg=1,xl=class extends HA.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=JA;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Mg||this.timeoutMillis>Ug)throw new Error(`Timeout must be between ${Mg} and ${Ug} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Lg.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[VA]!=="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 e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>qg)throw new Error(`Version of executable is not currently supported, maximum supported version is ${qg}.`);if(!e.success)throw new Lg.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new WA.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};ts.PluggableAuthClient=xl});var Nl=J(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.ExternalAccountClient=void 0;var KA=zr(),YA=_l(),XA=Al(),QA=Pl(),Il=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===KA.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new XA.AwsClient(e):e.credential_source?.executable?new QA.PluggableAuthClient(e):new YA.IdentityPoolClient(e):null}};aa.ExternalAccountClient=Il});var Wg=J(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.ExternalAccountAuthorizedUserClient=rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var zg=pt(),$g=il(),Hg=Ve(),ZA=Q("stream"),eS=zr();rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var tS="https://sts.{universeDomain}/v1/oauthtoken",Bl=class t extends $g.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};zg.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let s=await this.transporter.request(n),i=s.data;return i.res=s,i}catch(s){throw s instanceof Hg.GaxiosError&&s.response?(0,$g.getErrorFromOAuthErrorResponse)(s.response.data,s):s}}},jl=class extends zg.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Bl({tokenRefreshEndpoint:e.token_url??tS.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=eS.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=Hg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof ZA.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};rs.ExternalAccountAuthorizedUserClient=jl});var Kg=J(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleAuth=Ht.GoogleAuthExceptionMessages=void 0;var rS=Q("child_process"),Gs=Q("fs"),nS=Ve(),Js=xs(),sS=Q("os"),Ll=Q("path"),oS=Ps(),iS=xc(),aS=Ic(),uS=Nc(),ns=el(),Gg=rl(),ss=sl(),cS=Nl(),Vs=zr(),Ml=pt(),Jg=Wg(),Vg=Ut();Ht.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.
60
+ ${v}
61
+ `+await t.crypto.sha256DigestHex(A),y=await LA(t.crypto,t.securityCredentials.secretAccessKey,u,t.region,n),g=await Hs(t.crypto,y,S),m=`${Ig} Credential=${t.securityCredentials.accessKeyId}/${v}, SignedHeaders=${f}, Signature=${(0,Ng.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:i,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var Bg=V(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.DefaultAwsSecurityCredentialsSupplier=void 0;var Xi=pt(),wl=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};Xi.AuthClient.setMethodName(n,"getAwsRegion");let s=await e.transporter.request(n);return s.data.substr(0,s.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),s=await this.#r(n,r,e.transporter);return{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,token:s.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Xi.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Xi.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let s={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return Xi.AuthClient.setMethodName(s,"#retrieveAwsSecurityCredentials"),(await n.request(s)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Qi.DefaultAwsSecurityCredentialsSupplier=wl});var Al=V(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.AwsClient=void 0;var UA=Cl(),qA=zr(),$A=Bg(),jg=Ut(),zA=Ve(),El=class t extends qA.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let r=(0,jg.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("aws_security_credentials_supplier");if(!n&&!s)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(s)this.awsSecurityCredentialsSupplier=s,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let i=(0,jg.originalOrCamelOptions)(n);this.environmentId=i.get("environment_id");let u=i.get("region_url"),c=i.get("url"),l=i.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new $A.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=i.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new UA.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),r=[];return zA.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((s,i)=>r.push({key:i,value:s})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};Zi.AwsClient=El});var vl=V(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.InvalidSubjectTokenError=Le.InvalidMessageFieldError=Le.InvalidCodeFieldError=Le.InvalidTokenTypeFieldError=Le.InvalidExpirationTimeFieldError=Le.InvalidSuccessFieldError=Le.InvalidVersionFieldError=Le.ExecutableResponseError=Le.ExecutableResponse=void 0;var ea="urn:ietf:params:oauth:token-type:saml2",Sl="urn:ietf:params:oauth:token-type:id_token",kl="urn:ietf:params:oauth:token-type:jwt",Tl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new ta("Executable response must contain a 'version' field.");if(e.success===void 0)throw new ra("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==ea&&this.tokenType!==Sl&&this.tokenType!==kl)throw new na(`Executable response must contain a 'token_type' field when successful and it must be one of ${Sl}, ${kl}, or ${ea}.`);if(this.tokenType===ea){if(!e.saml_response)throw new Ws(`Executable response must contain a 'saml_response' field when token_type=${ea}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Ws(`Executable response must contain a 'id_token' field when token_type=${Sl} or ${kl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new sa("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new oa("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Le.ExecutableResponse=Tl;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=rr;var ta=class extends rr{};Le.InvalidVersionFieldError=ta;var ra=class extends rr{};Le.InvalidSuccessFieldError=ra;var Dl=class extends rr{};Le.InvalidExpirationTimeFieldError=Dl;var na=class extends rr{};Le.InvalidTokenTypeFieldError=na;var sa=class extends rr{};Le.InvalidCodeFieldError=sa;var oa=class extends rr{};Le.InvalidMessageFieldError=oa;var Ws=class extends rr{};Le.InvalidSubjectTokenError=Ws});var Fl=V(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.PluggableAuthHandler=es.ExecutableError=void 0;var fn=vl(),HA=Q("child_process"),Rl=Q("fs"),ia=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};es.ExecutableError=ia;var Ol=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((r,n)=>{let s=HA.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),i="";s.stdout.on("data",c=>{i+=c}),s.stderr.on("data",c=>{i+=c});let u=setTimeout(()=>(s.removeAllListeners(),s.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);s.on("close",c=>{if(clearTimeout(u),c===0)try{let l=JSON.parse(i),h=new fn.ExecutableResponse(l);return r(h)}catch(l){return l instanceof fn.ExecutableResponseError?n(l):n(new fn.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return n(new ia(i,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Rl.promises.realpath(this.outputFile)}catch{return}if(!(await Rl.promises.lstat(e)).isFile())return;let r=await Rl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new fn.ExecutableResponse(n).isValid()?new fn.ExecutableResponse(n):void 0}catch(n){throw n instanceof fn.ExecutableResponseError?n:new fn.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};es.PluggableAuthHandler=Ol});var Pl=V(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.PluggableAuthClient=ts.ExecutableError=void 0;var WA=zr(),GA=vl(),Lg=Fl(),JA=Fl();Object.defineProperty(ts,"ExecutableError",{enumerable:!0,get:function(){return JA.ExecutableError}});var VA=30*1e3,Mg=5*1e3,Ug=120*1e3,KA="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",qg=1,xl=class extends WA.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=VA;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Mg||this.timeoutMillis>Ug)throw new Error(`Timeout must be between ${Mg} and ${Ug} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Lg.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[KA]!=="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 e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>qg)throw new Error(`Version of executable is not currently supported, maximum supported version is ${qg}.`);if(!e.success)throw new Lg.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new GA.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};ts.PluggableAuthClient=xl});var Nl=V(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.ExternalAccountClient=void 0;var YA=zr(),XA=_l(),QA=Al(),ZA=Pl(),Il=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===YA.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new QA.AwsClient(e):e.credential_source?.executable?new ZA.PluggableAuthClient(e):new XA.IdentityPoolClient(e):null}};aa.ExternalAccountClient=Il});var Wg=V(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.ExternalAccountAuthorizedUserClient=rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var zg=pt(),$g=il(),Hg=Ve(),eS=Q("stream"),tS=zr();rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var rS="https://sts.{universeDomain}/v1/oauthtoken",Bl=class t extends $g.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};zg.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let s=await this.transporter.request(n),i=s.data;return i.res=s,i}catch(s){throw s instanceof Hg.GaxiosError&&s.response?(0,$g.getErrorFromOAuthErrorResponse)(s.response.data,s):s}}},jl=class extends zg.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Bl({tokenRefreshEndpoint:e.token_url??rS.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=tS.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=Hg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof eS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};rs.ExternalAccountAuthorizedUserClient=jl});var Kg=V(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleAuth=Ht.GoogleAuthExceptionMessages=void 0;var nS=Q("child_process"),Gs=Q("fs"),sS=Ve(),Js=xs(),oS=Q("os"),Ll=Q("path"),iS=Ps(),aS=xc(),uS=Ic(),cS=Nc(),ns=el(),Gg=rl(),ss=sl(),lS=Nl(),Vs=zr(),Ml=pt(),Jg=Wg(),Vg=Ut();Ht.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.
62
62
  To learn more about authentication and Google APIs, visit:
63
63
  https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
64
64
  To learn more about authentication and Google APIs, visit:
65
65
  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.
66
66
  To learn more about Universe Domain retrieval, visit:
67
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Ul=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.keyFilename&&console.warn("The `keyFilename` option is deprecated. Please use the `credentials` option instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.jsonContent&&console.warn("The `credentials` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(Ht.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(r=>e(null,r),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Js.universe("universe-domain"),e||=Ml.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Ml.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,Vg.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ml.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},r){let n;if(typeof e=="function"?r=e:n=e,r)this.getApplicationDefaultAsync(n).then(s=>r(null,s.credential,s.projectId),r);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),r)return r instanceof ns.JWT?r.scopes=this.scopes:r instanceof Vs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof ns.JWT?r.scopes=this.scopes:r instanceof Vs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new iS.Compute(e));throw new Error(Ht.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,r=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return r&&(e.quotaProjectId=r),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Js.getGCPResidency()||await Js.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let r=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!r||r.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(r,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let r=null;if(this._isWindows())r=process.env.APPDATA;else{let s=process.env.HOME;s&&(r=Ll.join(s,".config"))}return r&&(r=Ll.join(r,"gcloud","application_default_credentials.json"),Gs.existsSync(r)||(r=null)),r?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,r={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Gs.realpathSync(e),!Gs.lstatSync(e).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let n=Gs.createReadStream(e);return this.fromStream(n,r)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==ss.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ss.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let r=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let s=this.getAnyScopes()??[];return new ss.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(s)?s:[s]})}fromJSON(e,r={}){console.warn("The `fromJSON` method is deprecated. Please use the `JWT` constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let n,s=(0,Vg.originalOrCamelOptions)(r).get("universe_domain");return e.type===Gg.USER_REFRESH_ACCOUNT_TYPE?(n=new Gg.UserRefreshClient(r),n.fromJSON(e)):e.type===ss.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Vs.EXTERNAL_ACCOUNT_TYPE?(n=cS.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===Jg.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new Jg.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new ns.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),s&&(n.universeDomain=s),n}_cacheClientFromJSON(e,r){let n=this.fromJSON(e,r);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,r={},n){console.warn("The `fromStream` method is deprecated. Please use the `JWT` constructor with a parsed stream instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let s={};if(typeof r=="function"?n=r:s=r,n)this.fromStreamAsync(e,s).then(i=>n(null,i),n);else return this.fromStreamAsync(e,s)}fromStreamAsync(e,r){return new Promise((n,s)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",s).on("data",u=>i.push(u)).on("end",()=>{try{try{let u=JSON.parse(i.join("")),c=this._cacheClientFromJSON(u,r);return n(c)}catch(u){if(!this.keyFilename)throw u;let c=new ns.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(u){return s(u)}})})}fromAPIKey(e,r={}){return new ns.JWT({...r,apiKey:e})}_isWindows(){let e=sS.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,rS.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let s=JSON.parse(n).configuration.properties.core.project;e(s);return}catch{}e(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){let r=await this.getClient();if(r&&r.projectId)return r.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Vs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Js.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(r=>e(null,r),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof ss.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Vs.BaseExternalAccountClient){let r=e.getServiceAccountEmail();if(r)return{client_email:r,universe_domain:e.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()){let[r,n]=await Promise.all([Js.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(Ht.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Ll.resolve(this.keyFilename),r=Gs.createReadStream(e);return await this.fromStreamAsync(r,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:r}=await this.#t(e);return r}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let r=await this.getClient();if(!("fetchIdToken"in r))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 aS.IdTokenClient({targetAudience:e,idTokenProvider:r})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let r=e.url,s=await(await this.getClient()).getRequestHeaders(r);return e.headers=nS.Gaxios.mergeHeaders(e.headers,s),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,uS.getEnv)()}async sign(e,r){let n=await this.getClient(),s=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${s}/v1/projects/-/serviceAccounts/`,n instanceof ss.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,oS.createCrypto)();if(n instanceof ns.JWT&&n.key)return await i.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(i,u.client_email,e,r)}async signBlob(e,r,n,s){let i=new URL(s+`${r}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Ht.GoogleAuth=Ul});var Yg=J(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.IAMAuth=void 0;var ql=class{selector;token;constructor(e,r){this.selector=e,this.token=r,this.selector=e,this.token=r}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};ua.IAMAuth=ql});var Xg=J(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var lS=Ve(),dS=Q("stream"),$l=pt(),fS=$i(),hS="urn:ietf:params:oauth:grant-type:token-exchange",pS="urn:ietf:params:oauth:token-type:access_token",mS="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var zl=class extends $l.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof $l.AuthClient?{}:e),e instanceof $l.AuthClient?(this.authClient=e,this.credentialAccessBoundary=r):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>nr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${nr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new fS.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=lS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof dS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:hS,requestedTokenType:pS,subjectToken:e,subjectTokenType:mS},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),s=this.authClient.credentials?.expiry_date||null,i=n.expires_in?new Date().getTime()+n.expires_in*1e3:s;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:i,res:n.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}),this.cachedDownscopedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};nr.DownscopedClient=zl});var Qg=J(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.PassThroughClient=void 0;var gS=pt(),Hl=class extends gS.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ca.PassThroughClient=Hl});var Gl=J(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.GoogleAuth=te.auth=te.PassThroughClient=te.ExecutableError=te.PluggableAuthClient=te.DownscopedClient=te.BaseExternalAccountClient=te.ExternalAccountClient=te.IdentityPoolClient=te.AwsRequestSigner=te.AwsClient=te.UserRefreshClient=te.LoginTicket=te.ClientAuthentication=te.OAuth2Client=te.CodeChallengeMethod=te.Impersonated=te.JWT=te.JWTAccess=te.IdTokenClient=te.IAMAuth=te.GCPEnv=te.Compute=te.DEFAULT_UNIVERSE=te.AuthClient=te.gaxios=te.gcpMetadata=void 0;var Zg=Kg();Object.defineProperty(te,"GoogleAuth",{enumerable:!0,get:function(){return Zg.GoogleAuth}});te.gcpMetadata=xs();te.gaxios=Ve();var ey=pt();Object.defineProperty(te,"AuthClient",{enumerable:!0,get:function(){return ey.AuthClient}});Object.defineProperty(te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return ey.DEFAULT_UNIVERSE}});var yS=xc();Object.defineProperty(te,"Compute",{enumerable:!0,get:function(){return yS.Compute}});var _S=Nc();Object.defineProperty(te,"GCPEnv",{enumerable:!0,get:function(){return _S.GCPEnv}});var bS=Yg();Object.defineProperty(te,"IAMAuth",{enumerable:!0,get:function(){return bS.IAMAuth}});var CS=Ic();Object.defineProperty(te,"IdTokenClient",{enumerable:!0,get:function(){return CS.IdTokenClient}});var wS=Qc();Object.defineProperty(te,"JWTAccess",{enumerable:!0,get:function(){return wS.JWTAccess}});var ES=el();Object.defineProperty(te,"JWT",{enumerable:!0,get:function(){return ES.JWT}});var AS=sl();Object.defineProperty(te,"Impersonated",{enumerable:!0,get:function(){return AS.Impersonated}});var Wl=dn();Object.defineProperty(te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Wl.CodeChallengeMethod}});Object.defineProperty(te,"OAuth2Client",{enumerable:!0,get:function(){return Wl.OAuth2Client}});Object.defineProperty(te,"ClientAuthentication",{enumerable:!0,get:function(){return Wl.ClientAuthentication}});var SS=vc();Object.defineProperty(te,"LoginTicket",{enumerable:!0,get:function(){return SS.LoginTicket}});var kS=rl();Object.defineProperty(te,"UserRefreshClient",{enumerable:!0,get:function(){return kS.UserRefreshClient}});var TS=Al();Object.defineProperty(te,"AwsClient",{enumerable:!0,get:function(){return TS.AwsClient}});var DS=Cl();Object.defineProperty(te,"AwsRequestSigner",{enumerable:!0,get:function(){return DS.AwsRequestSigner}});var vS=_l();Object.defineProperty(te,"IdentityPoolClient",{enumerable:!0,get:function(){return vS.IdentityPoolClient}});var RS=Nl();Object.defineProperty(te,"ExternalAccountClient",{enumerable:!0,get:function(){return RS.ExternalAccountClient}});var OS=zr();Object.defineProperty(te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return OS.BaseExternalAccountClient}});var FS=Xg();Object.defineProperty(te,"DownscopedClient",{enumerable:!0,get:function(){return FS.DownscopedClient}});var ty=Pl();Object.defineProperty(te,"PluggableAuthClient",{enumerable:!0,get:function(){return ty.PluggableAuthClient}});Object.defineProperty(te,"ExecutableError",{enumerable:!0,get:function(){return ty.ExecutableError}});var xS=Qg();Object.defineProperty(te,"PassThroughClient",{enumerable:!0,get:function(){return xS.PassThroughClient}});var PS=new Zg.GoogleAuth;te.auth=PS});var Ly=J((vx,gd)=>{"use strict";var aD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,uD=/(\w*(\.\w*)*)\..*/;gd.exports=function(e){if(e.name.length>0)return e.name;let r=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(n){return Error.stackTraceLimit=r,jy(n.stack)}};function jy(t){let e=t.match(aD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(uD)[1]:"anonymous"}gd.exports.extractPluginName=jy});var Uy=J((Rx,My)=>{"use strict";My.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var qy=J((Ox,Ma)=>{"use strict";var cD=Ly(),lD=Uy(),dD=0;function yd(t,e={}){let r=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(r=!0,e.name=cD(t)+"-auto-"+dD++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let n=lD(e.name);return!r&&!t[n]&&(t[n]=t),t}Ma.exports=yd;Ma.exports.default=yd;Ma.exports.fastifyPlugin=yd});var to,_d=je(()=>{"use strict";to=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,r){let{format:n="text",timestamp:s=!0,prefix:i,metadata:u}=r||{},c="";if(s){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(i&&(c+=this.config.colors?`${this.colors.bright}${i}${this.colors.reset} `:`${i} `),n){case"json":c+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?c+=this.toMarkdown(e):c+=String(e);break;case"text":default:typeof e=="object"?c+=JSON.stringify(e,null,2):c+=String(e);break}return u&&Object.keys(u).length>0&&(c+=`
67
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Ul=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.keyFilename&&console.warn("The `keyFilename` option is deprecated. Please use the `credentials` option instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.jsonContent&&console.warn("The `credentials` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(Ht.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(r=>e(null,r),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Js.universe("universe-domain"),e||=Ml.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Ml.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,Vg.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ml.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},r){let n;if(typeof e=="function"?r=e:n=e,r)this.getApplicationDefaultAsync(n).then(s=>r(null,s.credential,s.projectId),r);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),r)return r instanceof ns.JWT?r.scopes=this.scopes:r instanceof Vs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof ns.JWT?r.scopes=this.scopes:r instanceof Vs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new aS.Compute(e));throw new Error(Ht.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,r=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return r&&(e.quotaProjectId=r),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Js.getGCPResidency()||await Js.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let r=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!r||r.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(r,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let r=null;if(this._isWindows())r=process.env.APPDATA;else{let s=process.env.HOME;s&&(r=Ll.join(s,".config"))}return r&&(r=Ll.join(r,"gcloud","application_default_credentials.json"),Gs.existsSync(r)||(r=null)),r?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,r={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Gs.realpathSync(e),!Gs.lstatSync(e).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let n=Gs.createReadStream(e);return this.fromStream(n,r)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==ss.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ss.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let r=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let s=this.getAnyScopes()??[];return new ss.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(s)?s:[s]})}fromJSON(e,r={}){console.warn("The `fromJSON` method is deprecated. Please use the `JWT` constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let n,s=(0,Vg.originalOrCamelOptions)(r).get("universe_domain");return e.type===Gg.USER_REFRESH_ACCOUNT_TYPE?(n=new Gg.UserRefreshClient(r),n.fromJSON(e)):e.type===ss.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Vs.EXTERNAL_ACCOUNT_TYPE?(n=lS.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===Jg.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new Jg.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new ns.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),s&&(n.universeDomain=s),n}_cacheClientFromJSON(e,r){let n=this.fromJSON(e,r);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,r={},n){console.warn("The `fromStream` method is deprecated. Please use the `JWT` constructor with a parsed stream instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let s={};if(typeof r=="function"?n=r:s=r,n)this.fromStreamAsync(e,s).then(i=>n(null,i),n);else return this.fromStreamAsync(e,s)}fromStreamAsync(e,r){return new Promise((n,s)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",s).on("data",u=>i.push(u)).on("end",()=>{try{try{let u=JSON.parse(i.join("")),c=this._cacheClientFromJSON(u,r);return n(c)}catch(u){if(!this.keyFilename)throw u;let c=new ns.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(u){return s(u)}})})}fromAPIKey(e,r={}){return new ns.JWT({...r,apiKey:e})}_isWindows(){let e=oS.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,nS.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let s=JSON.parse(n).configuration.properties.core.project;e(s);return}catch{}e(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){let r=await this.getClient();if(r&&r.projectId)return r.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Vs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Js.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(r=>e(null,r),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof ss.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Vs.BaseExternalAccountClient){let r=e.getServiceAccountEmail();if(r)return{client_email:r,universe_domain:e.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()){let[r,n]=await Promise.all([Js.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(Ht.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Ll.resolve(this.keyFilename),r=Gs.createReadStream(e);return await this.fromStreamAsync(r,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:r}=await this.#t(e);return r}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let r=await this.getClient();if(!("fetchIdToken"in r))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 uS.IdTokenClient({targetAudience:e,idTokenProvider:r})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let r=e.url,s=await(await this.getClient()).getRequestHeaders(r);return e.headers=sS.Gaxios.mergeHeaders(e.headers,s),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,cS.getEnv)()}async sign(e,r){let n=await this.getClient(),s=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${s}/v1/projects/-/serviceAccounts/`,n instanceof ss.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,iS.createCrypto)();if(n instanceof ns.JWT&&n.key)return await i.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(i,u.client_email,e,r)}async signBlob(e,r,n,s){let i=new URL(s+`${r}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Ht.GoogleAuth=Ul});var Yg=V(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.IAMAuth=void 0;var ql=class{selector;token;constructor(e,r){this.selector=e,this.token=r,this.selector=e,this.token=r}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};ua.IAMAuth=ql});var Xg=V(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var dS=Ve(),fS=Q("stream"),$l=pt(),hS=$i(),pS="urn:ietf:params:oauth:grant-type:token-exchange",mS="urn:ietf:params:oauth:token-type:access_token",gS="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var zl=class extends $l.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof $l.AuthClient?{}:e),e instanceof $l.AuthClient?(this.authClient=e,this.credentialAccessBoundary=r):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>nr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${nr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new hS.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=dS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof fS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:pS,requestedTokenType:mS,subjectToken:e,subjectTokenType:gS},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),s=this.authClient.credentials?.expiry_date||null,i=n.expires_in?new Date().getTime()+n.expires_in*1e3:s;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:i,res:n.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}),this.cachedDownscopedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};nr.DownscopedClient=zl});var Qg=V(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.PassThroughClient=void 0;var yS=pt(),Hl=class extends yS.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ca.PassThroughClient=Hl});var Gl=V(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.GoogleAuth=te.auth=te.PassThroughClient=te.ExecutableError=te.PluggableAuthClient=te.DownscopedClient=te.BaseExternalAccountClient=te.ExternalAccountClient=te.IdentityPoolClient=te.AwsRequestSigner=te.AwsClient=te.UserRefreshClient=te.LoginTicket=te.ClientAuthentication=te.OAuth2Client=te.CodeChallengeMethod=te.Impersonated=te.JWT=te.JWTAccess=te.IdTokenClient=te.IAMAuth=te.GCPEnv=te.Compute=te.DEFAULT_UNIVERSE=te.AuthClient=te.gaxios=te.gcpMetadata=void 0;var Zg=Kg();Object.defineProperty(te,"GoogleAuth",{enumerable:!0,get:function(){return Zg.GoogleAuth}});te.gcpMetadata=xs();te.gaxios=Ve();var ey=pt();Object.defineProperty(te,"AuthClient",{enumerable:!0,get:function(){return ey.AuthClient}});Object.defineProperty(te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return ey.DEFAULT_UNIVERSE}});var _S=xc();Object.defineProperty(te,"Compute",{enumerable:!0,get:function(){return _S.Compute}});var bS=Nc();Object.defineProperty(te,"GCPEnv",{enumerable:!0,get:function(){return bS.GCPEnv}});var CS=Yg();Object.defineProperty(te,"IAMAuth",{enumerable:!0,get:function(){return CS.IAMAuth}});var wS=Ic();Object.defineProperty(te,"IdTokenClient",{enumerable:!0,get:function(){return wS.IdTokenClient}});var ES=Qc();Object.defineProperty(te,"JWTAccess",{enumerable:!0,get:function(){return ES.JWTAccess}});var AS=el();Object.defineProperty(te,"JWT",{enumerable:!0,get:function(){return AS.JWT}});var SS=sl();Object.defineProperty(te,"Impersonated",{enumerable:!0,get:function(){return SS.Impersonated}});var Wl=dn();Object.defineProperty(te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Wl.CodeChallengeMethod}});Object.defineProperty(te,"OAuth2Client",{enumerable:!0,get:function(){return Wl.OAuth2Client}});Object.defineProperty(te,"ClientAuthentication",{enumerable:!0,get:function(){return Wl.ClientAuthentication}});var kS=vc();Object.defineProperty(te,"LoginTicket",{enumerable:!0,get:function(){return kS.LoginTicket}});var TS=rl();Object.defineProperty(te,"UserRefreshClient",{enumerable:!0,get:function(){return TS.UserRefreshClient}});var DS=Al();Object.defineProperty(te,"AwsClient",{enumerable:!0,get:function(){return DS.AwsClient}});var vS=Cl();Object.defineProperty(te,"AwsRequestSigner",{enumerable:!0,get:function(){return vS.AwsRequestSigner}});var RS=_l();Object.defineProperty(te,"IdentityPoolClient",{enumerable:!0,get:function(){return RS.IdentityPoolClient}});var OS=Nl();Object.defineProperty(te,"ExternalAccountClient",{enumerable:!0,get:function(){return OS.ExternalAccountClient}});var FS=zr();Object.defineProperty(te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return FS.BaseExternalAccountClient}});var xS=Xg();Object.defineProperty(te,"DownscopedClient",{enumerable:!0,get:function(){return xS.DownscopedClient}});var ty=Pl();Object.defineProperty(te,"PluggableAuthClient",{enumerable:!0,get:function(){return ty.PluggableAuthClient}});Object.defineProperty(te,"ExecutableError",{enumerable:!0,get:function(){return ty.ExecutableError}});var PS=Qg();Object.defineProperty(te,"PassThroughClient",{enumerable:!0,get:function(){return PS.PassThroughClient}});var IS=new Zg.GoogleAuth;te.auth=IS});var Ly=V((Ox,gd)=>{"use strict";var uD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,cD=/(\w*(\.\w*)*)\..*/;gd.exports=function(e){if(e.name.length>0)return e.name;let r=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(n){return Error.stackTraceLimit=r,jy(n.stack)}};function jy(t){let e=t.match(uD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(cD)[1]:"anonymous"}gd.exports.extractPluginName=jy});var Uy=V((Fx,My)=>{"use strict";My.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var qy=V((xx,Ma)=>{"use strict";var lD=Ly(),dD=Uy(),fD=0;function yd(t,e={}){let r=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(r=!0,e.name=lD(t)+"-auto-"+fD++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let n=dD(e.name);return!r&&!t[n]&&(t[n]=t),t}Ma.exports=yd;Ma.exports.default=yd;Ma.exports.fastifyPlugin=yd});var to,_d=je(()=>{"use strict";to=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,r){let{format:n="text",timestamp:s=!0,prefix:i,metadata:u}=r||{},c="";if(s){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(i&&(c+=this.config.colors?`${this.colors.bright}${i}${this.colors.reset} `:`${i} `),n){case"json":c+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?c+=this.toMarkdown(e):c+=String(e);break;case"text":default:typeof e=="object"?c+=JSON.stringify(e,null,2):c+=String(e);break}return u&&Object.keys(u).length>0&&(c+=`
68
68
  `+(this.config.colors?`${this.colors.dim}`:""),c+="Metadata: "+JSON.stringify(u,null,2),this.config.colors&&(c+=this.colors.reset)),c}toMarkdown(e,r=0){let n=" ".repeat(r);return Array.isArray(e)?e.map(s=>typeof s=="object"?`${n}-
69
69
  ${this.toMarkdown(s,r+1)}`:`${n}- ${s}`).join(`
70
70
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([s,i])=>typeof i=="object"&&i!==null?`${n}${s}:
71
71
  ${this.toMarkdown(i,r+1)}`:`${n}${s}: ${i}`).join(`
72
- `):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var ro,bd=je(()=>{"use strict";ro=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:s=!0,prefix:i,metadata:u}=r||{},c={data:e};return s&&(c.timestamp=new Date().toISOString()),i&&(c.prefix=i),u&&Object.keys(u).length>0&&(c.metadata=u),c}async sendRequest(e,r,n,s,i){let u=new AbortController,c=setTimeout(()=>u.abort(),i);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(s),signal:u.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,s,i,u){let c=null;for(let l=1;l<=u.maxAttempts;l++)try{return await this.sendRequest(e,r,n,s,i)}catch(h){if(c=h,l===u.maxAttempts)break;let f=u.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${u.maxAttempts}), retrying in ${f}ms...`,h.message),await this.delay(f)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let s=this.buildHeaders(),i=this.buildBody(e,r),u=await this.sendWithRetry(this.config.url,this.config.method,s,i,n,this.config.retry);return!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}});import{writeFileSync as fD,existsSync as hD,mkdirSync as pD}from"fs";import{join as zy}from"path";import{tmpdir as mD}from"os";var no,Cd=je(()=>{"use strict";no=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=mD();this.baseDir=zy(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{hD(this.baseDir)||pD(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",s;if(this.config.includeTimestamp){let i=Date.now();s=`${r}-${e}-${i}${n}`}else s=`${r}-${e}${n}`;return zy(this.baseDir,s)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let s={...e,timestamp:Date.now(),sessionId:n},i=this.getFilePath(n);return fD(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var wd,cs,Hy=je(()=>{"use strict";_d();bd();Cd();wd=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),s=r.type+"_"+Date.now();this.registerHandler(s,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new to(e.config);case"webhook":return new ro(e.config);case"temp-file":return new no(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([u,c])=>{try{await c.output(e,n)?s.success.push(u):s.failed.push(u)}catch(l){console.error(`[OutputManager] Handler ${u} failed:`,l),s.failed.push(u)}});return await Promise.all(i),s}async outputTo(e,r,n){let s={...this.defaultOptions,...n},i={success:[],failed:[]},u=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),i.failed.push(c);return}try{await l.output(r,s)?i.success.push(c):i.failed.push(c)}catch(h){console.error(`[OutputManager] Handler ${c} failed:`,h),i.failed.push(c)}});return await Promise.all(u),i}async outputToType(e,r,n){let s=Array.from(this.handlers.entries()).filter(([i,u])=>u.type===e).map(([i])=>i);return this.outputTo(s,r,n)}},cs=new wd});import gD from"fastify";import yD from"@fastify/cors";var Uf=Pr(Au(),1);import{readFileSync as z_,existsSync as Lf}from"fs";import{join as Mf}from"path";import{config as H_}from"dotenv";var Dn=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Mf(process.cwd(),this.options.jsonPath);if(Lf(e))try{let r=z_(e,"utf-8"),n=Uf.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Mf(process.cwd(),this.options.envPath);if(Lf(e))try{let r=H_({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,r){this.config[e]=r}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(t,e=500,r="internal_error",n="api_error"){let s=new Error(t);return s.statusCode=e,s.code=r,s.type=n,s}async function qf(t,e,r){e.log.error(t);let n=t.statusCode||500,s={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(s)}import{ProxyAgent as W_}from"undici";function $f(t,e,r,n,s){let i=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([h,f])=>{f&&i.set(h,f)});let u,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let h=new AbortController,f=()=>h.abort();r.signal.addEventListener("abort",f),c.addEventListener("abort",f),u=h.signal}else u=c;let l={method:"POST",headers:i,body:JSON.stringify(e),signal:u};return r.httpsProxy&&(l.dispatcher=new W_(new URL(r.httpsProxy).toString())),s?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(i.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var zf="2.0.36";var J_={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},Lo=class{states=new Map;config;probeTimer;constructor(e){this.config={...J_,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),s=this.states.get(n);s&&(s.successCount++,s.status==="half-open"?s.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(n):s.status==="open"&&(s.status="half-open",s.successCount=1,s.failureCount=0))}isRateLimitError(e){if(!e)return!1;let r=e.toLowerCase();return r.includes("429")||r.includes("rate_limit")||r.includes("ratelimit")||r.includes("rate limit")||r.includes("overloaded")||r.includes("quota")}recordFailure(e,r,n){if(!this.config.enabled)return;let s=this.getKey(e,r),i=this.states.get(s);i||(i={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(s,i)),i.failureCount++,i.lastFailureTime=Date.now(),i.lastError=n;let c=this.isRateLimitError(n)?this.config.rateLimitThreshold:this.config.failureThreshold;i.status==="half-open"?(i.status="open",i.successCount=0,i.lastProbeTime=0):i.status==="closed"&&i.failureCount>=c&&(i.status="open",i.lastProbeTime=0)}getState(e,r){return this.states.get(this.getKey(e,r))}isAvailable(e,r){if(!this.config.enabled)return!0;let n=this.getState(e,r);return n?n.status!=="open":!0}getPriority(e,r){if(!this.config.enabled)return 0;let n=this.getState(e,r);if(!n)return 0;switch(n.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[r,n]of this.states)n.status==="open"&&e.push(r);return e}getHalfOpenModels(){let e=[];for(let[r,n]of this.states)n.status==="half-open"&&e.push(r);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,r){let n=this.getKey(e,r),s=this.states.get(n);s&&s.status==="open"&&(s.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Su=null;function vn(t){return Su||(Su=new Lo(t)),Su}async function V_(t,e,r,n){let s=t.body,i=t.provider,u=r.providerService.getProvider(i);if(!u)throw nt(`Provider '${i}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:h}=await Hf(s,u,n,t.headers,{req:t}),f=await Wf(c,l,u,r,h,n,{req:t}),p=await Gf(c,f,u,n,h,{req:t});return Jf(p,e,s)}catch(c){let l=await K_(t,e,r,n,c);if(l)return l;throw c}}async function K_(t,e,r,n,s){let i=t.scenarioType||"default",u=t.familyFallback,c=r.configService.get("fallback"),l=vn(),h=[];if(u?.[i]?h=u[i]:c?.[i]&&(h=c[i]),!Array.isArray(h)||h.length===0)return null;let f=t.provider||"",p=t.body.model||"";l.recordFailure(f,p,s?.message),t.log.warn(`Request failed for ${t.scenarioType}, trying ${h.length} fallback models`);let S=h.sort((D,E)=>{let[y,g]=D.split(","),[m,T]=E.split(",");return l.getPriority(y,g)-l.getPriority(m,T)});for(let D of S)try{let[E,...y]=D.split(","),g=y.join(",");if(!l.isAvailable(E,g)){t.log.warn(`Fallback model ${D} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${D}`);let m={...t.body};m.model=g;let T={...t,provider:E,body:m},b=r.providerService.getProvider(E);if(!b){t.log.warn(`Fallback provider '${E}' not found, skipping`);continue}let{requestBody:w,config:O,bypass:x}=await Hf(m,b,n,t.headers,{req:T}),$=await Wf(w,O,b,r,x,n,{req:T}),V=await Gf(w,$,b,n,x,{req:T});return t.log.info(`Fallback model ${D} succeeded`),l.recordSuccess(E,g),Jf(V,e,m)}catch(E){let[y,...g]=D.split(","),m=g.join(",");l.recordFailure(y,m,E.message),t.log.warn(`Fallback model ${D} failed: ${E.message}`);continue}return t.log.error(`All fallback models failed for ${i}`),null}async function Hf(t,e,r,n,s){let i=JSON.parse(JSON.stringify(t)),u={},c=!1;if(c=Y_(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],u.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(i);l.body?(i=l.body,u=l.config||{}):i=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let h=await l.transformRequestIn(i,e,s);h.body?(i=h.body,u={...u,...h.config}):i=h}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(i=await l.transformRequestIn(i,e,s));return{requestBody:i,config:u,bypass:c}}function Y_(t,e,r){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r.model]?.use.length||t.transformer?.[r.model]?.use.length===1&&t.transformer?.[r.model]?.use[0].name===e.name)}async function Wf(t,e,r,n,s,i,u){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let f=n.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(s&&typeof i.auth=="function"){let f=await i.auth(t,r);if(f.body){t=f.body;let p=e.headers||{};f.config?.headers&&(p={...p,...f.config.headers},delete p.host,delete f.config.headers),e={...e,...f.config,headers:p}}else t=f}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];let h=await $f(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},u,n.log);if(!h.ok){let f=await h.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${h.status}): ${f}`),nt(`Error from provider(${r.name},${t.model}: ${h.status}): ${f}`,h.status,"provider_response_error")}return h}async function Gf(t,e,r,n,s,i){let u=e;if(!s&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));if(!s&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));return!s&&n.transformResponseIn&&(u=await n.transformResponseIn(u,i)),u}function Jf(t,e,r){return t.ok||e.code(t.status),r.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(t.body)):t.json()}var ku=async t=>{t.get("/",async()=>({message:"LLMs API",version:zf})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:vn().getAllStates().map(s=>({provider:s.provider,model:s.model,status:s.status,failureCount:s.failureCount,successCount:s.successCount,lastFailureTime:s.lastFailureTime,lastError:s.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,s)=>V_(n,s,t,r));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(r,n)=>{let{name:s,baseUrl:i,apiKey:u,models:c}=r.body;if(!s?.trim())throw nt("Provider name is required",400,"invalid_request");if(!i||!X_(i))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw nt("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw nt(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(r.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=t.providerService.getProvider(r.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(r,n)=>{let s=t.providerService.updateProvider(r.params.id,r.body);if(!s)throw nt("Provider not found",404,"provider_not_found");return s}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(r,n)=>{if(!t.providerService.toggleProvider(r.params.id,r.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function X_(t){try{return new URL(t),!0}catch{return!1}}var Rn=class{constructor(e,r,n){this.configService=e;this.transformerService=r;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(r=>{try{if(!r.name||!r.api_base_url||!r.api_key)return;let n={};r.transformer&&Object.keys(r.transformer).forEach(s=>{s==="use"?Array.isArray(r.transformer.use)&&(n.use=r.transformer.use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")):Array.isArray(r.transformer[s]?.use)&&(n[s]={use:r.transformer[s].use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")})}),this.registerProvider({name:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],transformer:r.transformer?n:void 0}),this.logger.info(`${r.name} provider registered`)}catch(n){this.logger.error(`${r.name} provider registered error: ${n}`)}})}registerProvider(e){let r={...e};return this.providers.set(r.name,r),e.models.forEach(n=>{let s=`${r.name},${n}`,i={provider:r.name,model:n,fullModel:s};this.modelRoutes.set(s,i),this.modelRoutes.has(n)||this.modelRoutes.set(n,i)}),r}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,r){let n=this.providers.get(e);if(!n)return null;let s={...n,...r,updatedAt:new Date};return this.providers.set(e,s),r.models&&(n.models.forEach(i=>{let u=`${n.name},${i}`;this.modelRoutes.delete(u),this.modelRoutes.delete(i)}),r.models.forEach(i=>{let u=`${n.name},${i}`,c={provider:n.name,model:i,fullModel:u};this.modelRoutes.set(u,c),this.modelRoutes.has(i)||this.modelRoutes.set(i,c)})),s}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let s=`${r.name},${n}`;this.modelRoutes.delete(s),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,r){return!!this.providers.get(e)}resolveModelRoute(e){let r=this.modelRoutes.get(e);if(!r)return null;let n=this.providers.get(r.provider);return n?{provider:n,originalModel:e,targetModel:r.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push(n),e.push(`${r.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((r,n)=>{if(Array.isArray(n)){let[s,i={}]=n;r[s]=i}else r[n]={};return r},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push({id:n,object:"model",owned_by:r.name,provider:r.name}),e.push({id:`${r.name},${n}`,object:"model",owned_by:r.name,provider:r.name})})}),{object:"list",data:e}}};var Je=[];for(let t=0;t<256;++t)Je.push((t+256).toString(16).slice(1));function Vf(t,e=0){return(Je[t[e+0]]+Je[t[e+1]]+Je[t[e+2]]+Je[t[e+3]]+"-"+Je[t[e+4]]+Je[t[e+5]]+"-"+Je[t[e+6]]+Je[t[e+7]]+"-"+Je[t[e+8]]+Je[t[e+9]]+"-"+Je[t[e+10]]+Je[t[e+11]]+Je[t[e+12]]+Je[t[e+13]]+Je[t[e+14]]+Je[t[e+15]]).toLowerCase()}import{randomFillSync as Q_}from"crypto";var Uo=new Uint8Array(256),Mo=Uo.length;function Tu(){return Mo>Uo.length-16&&(Q_(Uo),Mo=0),Uo.slice(Mo,Mo+=16)}import{randomUUID as Z_}from"crypto";var Du={randomUUID:Z_};function eb(t,e,r){if(Du.randomUUID&&!e&&!t)return Du.randomUUID();t=t||{};let n=t.random??t.rng?.()??Tu();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Vf(n)}var Gt=eb;var Kf=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Yf=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var qo=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,r){let n={};return this.useBearer?(n.authorization=`Bearer ${r.apiKey}`,n["x-api-key"]=void 0):(n["x-api-key"]=r.apiKey,n.authorization=void 0),{body:e,config:{headers:n}}}async transformRequestOut(e){let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));r.push({role:"system",content:i})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(i=>{if(i.role==="user"||i.role==="assistant"){if(typeof i.content=="string"){r.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let u=i.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);u.length&&u.forEach(l=>{let h={role:"tool",content:typeof l.content=="string"?l.content:JSON.stringify(l.content),tool_call_id:l.tool_use_id,cache_control:l.cache_control};r.push(h)});let c=i.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&r.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Yf(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(i.role==="assistant"){let u={role:"assistant",content:""},c=i.content.filter(f=>f.type==="text"&&f.text);c.length&&(u.content=c.map(f=>f.text).join(`
73
- `));let l=i.content.filter(f=>f.type==="tool_use"&&f.id);l.length&&(u.tool_calls=l.map(f=>({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input||{})}})));let h=i.content.find(f=>f.type==="thinking"&&f.signature);h&&(u.thinking={content:h.thinking,signature:h.signature}),r.push(u)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(s.reasoning={effort:Kf(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:s.tool_choice=e.tool_choice.type),s}async transformResponseIn(e,r){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let s=await this.convertOpenAIStreamToAnthropic(e.body,r);return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let s=await e.json(),i=this.convertOpenAIResponseToAnthropic(s,r);return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(r=>({type:"function",function:{name:r.name,description:r.description||"",parameters:r.input_schema}}))}async convertOpenAIStreamToAnthropic(e,r){return new ReadableStream({start:async s=>{let i=new TextEncoder,u=`msg_${Date.now()}`,c=null,l="unknown",h=!1,f=!1,p=!1,S=new Map,D=new Map,E=0,y=0,g=0,m=!1,T=!1,b=0,w=-1,O=()=>{let U=b;return b++,U},x=U=>{if(!m)try{s.enqueue(U);let X=new TextDecoder().decode(U);this.logger.debug({reqId:r.req.id,data:X,type:"send data"})}catch(X){if(X instanceof TypeError&&X.message.includes("Controller is already closed"))m=!0;else throw this.logger.debug({reqId:r.req.id,error:X instanceof Error?X.message:String(X),type:"send data error"}),X}},$=()=>{if(!m)try{if(w>=0){let X={type:"content_block_stop",index:w};x(i.encode(`event: content_block_stop
72
+ `):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var ro,bd=je(()=>{"use strict";ro=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:s=!0,prefix:i,metadata:u}=r||{},c={data:e};return s&&(c.timestamp=new Date().toISOString()),i&&(c.prefix=i),u&&Object.keys(u).length>0&&(c.metadata=u),c}async sendRequest(e,r,n,s,i){let u=new AbortController,c=setTimeout(()=>u.abort(),i);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(s),signal:u.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,s,i,u){let c=null;for(let l=1;l<=u.maxAttempts;l++)try{return await this.sendRequest(e,r,n,s,i)}catch(h){if(c=h,l===u.maxAttempts)break;let f=u.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${u.maxAttempts}), retrying in ${f}ms...`,h.message),await this.delay(f)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let s=this.buildHeaders(),i=this.buildBody(e,r),u=await this.sendWithRetry(this.config.url,this.config.method,s,i,n,this.config.retry);return!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}});import{writeFileSync as hD,existsSync as pD,mkdirSync as mD}from"fs";import{join as zy}from"path";import{tmpdir as gD}from"os";var no,Cd=je(()=>{"use strict";no=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=gD();this.baseDir=zy(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{pD(this.baseDir)||mD(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",s;if(this.config.includeTimestamp){let i=Date.now();s=`${r}-${e}-${i}${n}`}else s=`${r}-${e}${n}`;return zy(this.baseDir,s)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let s={...e,timestamp:Date.now(),sessionId:n},i=this.getFilePath(n);return hD(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var wd,cs,Hy=je(()=>{"use strict";_d();bd();Cd();wd=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),s=r.type+"_"+Date.now();this.registerHandler(s,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new to(e.config);case"webhook":return new ro(e.config);case"temp-file":return new no(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([u,c])=>{try{await c.output(e,n)?s.success.push(u):s.failed.push(u)}catch(l){console.error(`[OutputManager] Handler ${u} failed:`,l),s.failed.push(u)}});return await Promise.all(i),s}async outputTo(e,r,n){let s={...this.defaultOptions,...n},i={success:[],failed:[]},u=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),i.failed.push(c);return}try{await l.output(r,s)?i.success.push(c):i.failed.push(c)}catch(h){console.error(`[OutputManager] Handler ${c} failed:`,h),i.failed.push(c)}});return await Promise.all(u),i}async outputToType(e,r,n){let s=Array.from(this.handlers.entries()).filter(([i,u])=>u.type===e).map(([i])=>i);return this.outputTo(s,r,n)}},cs=new wd});import _D from"fastify";import bD from"@fastify/cors";var Uf=Pr(Au(),1);import{readFileSync as H_,existsSync as Lf}from"fs";import{join as Mf}from"path";import{config as W_}from"dotenv";var Dn=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Mf(process.cwd(),this.options.jsonPath);if(Lf(e))try{let r=H_(e,"utf-8"),n=Uf.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Mf(process.cwd(),this.options.envPath);if(Lf(e))try{let r=W_({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,r){this.config[e]=r}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(t,e=500,r="internal_error",n="api_error"){let s=new Error(t);return s.statusCode=e,s.code=r,s.type=n,s}async function qf(t,e,r){e.log.error(t);let n=t.statusCode||500,s={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(s)}import{ProxyAgent as G_}from"undici";function $f(t,e,r,n,s){let i=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([h,f])=>{f&&i.set(h,f)});let u,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let h=new AbortController,f=()=>h.abort();r.signal.addEventListener("abort",f),c.addEventListener("abort",f),u=h.signal}else u=c;let l={method:"POST",headers:i,body:JSON.stringify(e),signal:u};return r.httpsProxy&&(l.dispatcher=new G_(new URL(r.httpsProxy).toString())),s?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(i.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var zf="2.0.38";var V_={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},Lo=class{states=new Map;config;probeTimer;constructor(e){this.config={...V_,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),s=this.states.get(n);s&&(s.successCount++,s.status==="half-open"?s.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(n):s.status==="open"&&(s.status="half-open",s.successCount=1,s.failureCount=0))}isRateLimitError(e){if(!e)return!1;let r=e.toLowerCase();return r.includes("429")||r.includes("rate_limit")||r.includes("ratelimit")||r.includes("rate limit")||r.includes("overloaded")||r.includes("quota")}recordFailure(e,r,n){if(!this.config.enabled)return;let s=this.getKey(e,r),i=this.states.get(s);i||(i={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(s,i)),i.failureCount++,i.lastFailureTime=Date.now(),i.lastError=n;let c=this.isRateLimitError(n)?this.config.rateLimitThreshold:this.config.failureThreshold;i.status==="half-open"?(i.status="open",i.successCount=0,i.lastProbeTime=0):i.status==="closed"&&i.failureCount>=c&&(i.status="open",i.lastProbeTime=0)}getState(e,r){return this.states.get(this.getKey(e,r))}isAvailable(e,r){if(!this.config.enabled)return!0;let n=this.getState(e,r);return n?n.status!=="open":!0}getPriority(e,r){if(!this.config.enabled)return 0;let n=this.getState(e,r);if(!n)return 0;switch(n.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[r,n]of this.states)n.status==="open"&&e.push(r);return e}getHalfOpenModels(){let e=[];for(let[r,n]of this.states)n.status==="half-open"&&e.push(r);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,r){let n=this.getKey(e,r),s=this.states.get(n);s&&s.status==="open"&&(s.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Su=null;function vn(t){return Su||(Su=new Lo(t)),Su}async function K_(t,e,r,n){let s=t.body,i=t.provider,u=r.providerService.getProvider(i);if(!u)throw nt(`Provider '${i}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:h}=await Hf(s,u,n,t.headers,{req:t}),f=await Wf(c,l,u,r,h,n,{req:t}),p=await Gf(c,f,u,n,h,{req:t});return Jf(p,e,s)}catch(c){let l=await Y_(t,e,r,n,c);if(l)return l;throw c}}async function Y_(t,e,r,n,s){let i=t.scenarioType||"default",u=t.familyFallback,c=r.configService.get("fallback"),l=vn(),h=[];if(u?.[i]?h=u[i]:c?.[i]&&(h=c[i]),!Array.isArray(h)||h.length===0)return null;let f=t.provider||"",p=t.body.model||"";l.recordFailure(f,p,s?.message),t.log.warn(`Request failed for ${t.scenarioType}, trying ${h.length} fallback models`);let A=h.sort((v,S)=>{let[y,g]=v.split(","),[m,k]=S.split(",");return l.getPriority(y,g)-l.getPriority(m,k)});for(let v of A)try{let[S,...y]=v.split(","),g=y.join(",");if(!l.isAvailable(S,g)){t.log.warn(`Fallback model ${v} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${v}`);let m={...t.body};m.model=g;let k={...t,provider:S,body:m},b=r.providerService.getProvider(S);if(!b){t.log.warn(`Fallback provider '${S}' not found, skipping`);continue}let{requestBody:E,config:R,bypass:x}=await Hf(m,b,n,t.headers,{req:k}),$=await Wf(E,R,b,r,x,n,{req:k}),J=await Gf(E,$,b,n,x,{req:k});return t.log.info(`Fallback model ${v} succeeded`),l.recordSuccess(S,g),Jf(J,e,m)}catch(S){let[y,...g]=v.split(","),m=g.join(",");l.recordFailure(y,m,S.message),t.log.warn(`Fallback model ${v} failed: ${S.message}`);continue}return t.log.error(`All fallback models failed for ${i}`),null}async function Hf(t,e,r,n,s){let i=JSON.parse(JSON.stringify(t)),u={},c=!1;if(c=X_(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],u.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(i);l.body?(i=l.body,u=l.config||{}):i=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let h=await l.transformRequestIn(i,e,s);h.body?(i=h.body,u={...u,...h.config}):i=h}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(i=await l.transformRequestIn(i,e,s));return{requestBody:i,config:u,bypass:c}}function X_(t,e,r){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r.model]?.use.length||t.transformer?.[r.model]?.use.length===1&&t.transformer?.[r.model]?.use[0].name===e.name)}async function Wf(t,e,r,n,s,i,u){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let f=n.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(s&&typeof i.auth=="function"){let f=await i.auth(t,r);if(f.body){t=f.body;let p=e.headers||{};f.config?.headers&&(p={...p,...f.config.headers},delete p.host,delete f.config.headers),e={...e,...f.config,headers:p}}else t=f}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];let h=await $f(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},u,n.log);if(!h.ok){let f=await h.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${h.status}): ${f}`),nt(`Error from provider(${r.name},${t.model}: ${h.status}): ${f}`,h.status,"provider_response_error")}return h}async function Gf(t,e,r,n,s,i){let u=e;if(!s&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));if(!s&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));return!s&&n.transformResponseIn&&(u=await n.transformResponseIn(u,i)),u}function Jf(t,e,r){return t.ok||e.code(t.status),r.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(t.body)):t.json()}var ku=async t=>{t.get("/",async()=>({message:"LLMs API",version:zf})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:vn().getAllStates().map(s=>({provider:s.provider,model:s.model,status:s.status,failureCount:s.failureCount,successCount:s.successCount,lastFailureTime:s.lastFailureTime,lastError:s.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,s)=>K_(n,s,t,r));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(r,n)=>{let{name:s,baseUrl:i,apiKey:u,models:c}=r.body;if(!s?.trim())throw nt("Provider name is required",400,"invalid_request");if(!i||!Q_(i))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw nt("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw nt(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(r.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=t.providerService.getProvider(r.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(r,n)=>{let s=t.providerService.updateProvider(r.params.id,r.body);if(!s)throw nt("Provider not found",404,"provider_not_found");return s}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(r,n)=>{if(!t.providerService.toggleProvider(r.params.id,r.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function Q_(t){try{return new URL(t),!0}catch{return!1}}var Rn=class{constructor(e,r,n){this.configService=e;this.transformerService=r;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(r=>{try{if(!r.name||!r.api_base_url||!r.api_key)return;let n={};r.transformer&&Object.keys(r.transformer).forEach(s=>{s==="use"?Array.isArray(r.transformer.use)&&(n.use=r.transformer.use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")):Array.isArray(r.transformer[s]?.use)&&(n[s]={use:r.transformer[s].use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")})}),this.registerProvider({name:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],transformer:r.transformer?n:void 0}),this.logger.info(`${r.name} provider registered`)}catch(n){this.logger.error(`${r.name} provider registered error: ${n}`)}})}registerProvider(e){let r={...e};return this.providers.set(r.name,r),e.models.forEach(n=>{let s=`${r.name},${n}`,i={provider:r.name,model:n,fullModel:s};this.modelRoutes.set(s,i),this.modelRoutes.has(n)||this.modelRoutes.set(n,i)}),r}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,r){let n=this.providers.get(e);if(!n)return null;let s={...n,...r,updatedAt:new Date};return this.providers.set(e,s),r.models&&(n.models.forEach(i=>{let u=`${n.name},${i}`;this.modelRoutes.delete(u),this.modelRoutes.delete(i)}),r.models.forEach(i=>{let u=`${n.name},${i}`,c={provider:n.name,model:i,fullModel:u};this.modelRoutes.set(u,c),this.modelRoutes.has(i)||this.modelRoutes.set(i,c)})),s}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let s=`${r.name},${n}`;this.modelRoutes.delete(s),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,r){return!!this.providers.get(e)}resolveModelRoute(e){let r=this.modelRoutes.get(e);if(!r)return null;let n=this.providers.get(r.provider);return n?{provider:n,originalModel:e,targetModel:r.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push(n),e.push(`${r.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((r,n)=>{if(Array.isArray(n)){let[s,i={}]=n;r[s]=i}else r[n]={};return r},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push({id:n,object:"model",owned_by:r.name,provider:r.name}),e.push({id:`${r.name},${n}`,object:"model",owned_by:r.name,provider:r.name})})}),{object:"list",data:e}}};var Je=[];for(let t=0;t<256;++t)Je.push((t+256).toString(16).slice(1));function Vf(t,e=0){return(Je[t[e+0]]+Je[t[e+1]]+Je[t[e+2]]+Je[t[e+3]]+"-"+Je[t[e+4]]+Je[t[e+5]]+"-"+Je[t[e+6]]+Je[t[e+7]]+"-"+Je[t[e+8]]+Je[t[e+9]]+"-"+Je[t[e+10]]+Je[t[e+11]]+Je[t[e+12]]+Je[t[e+13]]+Je[t[e+14]]+Je[t[e+15]]).toLowerCase()}import{randomFillSync as Z_}from"crypto";var Uo=new Uint8Array(256),Mo=Uo.length;function Tu(){return Mo>Uo.length-16&&(Z_(Uo),Mo=0),Uo.slice(Mo,Mo+=16)}import{randomUUID as eb}from"crypto";var Du={randomUUID:eb};function tb(t,e,r){if(Du.randomUUID&&!e&&!t)return Du.randomUUID();t=t||{};let n=t.random??t.rng?.()??Tu();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Vf(n)}var Gt=tb;var Kf=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Yf=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var qo=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,r){let n={};return this.useBearer?(n.authorization=`Bearer ${r.apiKey}`,n["x-api-key"]=void 0):(n["x-api-key"]=r.apiKey,n.authorization=void 0),{body:e,config:{headers:n}}}async transformRequestOut(e){let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));r.push({role:"system",content:i})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(i=>{if(i.role==="user"||i.role==="assistant"){if(typeof i.content=="string"){r.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let u=i.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);u.length&&u.forEach(l=>{let h={role:"tool",content:typeof l.content=="string"?l.content:JSON.stringify(l.content),tool_call_id:l.tool_use_id,cache_control:l.cache_control};r.push(h)});let c=i.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&r.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Yf(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(i.role==="assistant"){let u={role:"assistant",content:""},c=i.content.filter(f=>f.type==="text"&&f.text);c.length&&(u.content=c.map(f=>f.text).join(`
73
+ `));let l=i.content.filter(f=>f.type==="tool_use"&&f.id);l.length&&(u.tool_calls=l.map(f=>({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input||{})}})));let h=i.content.find(f=>f.type==="thinking"&&f.signature);h&&(u.thinking={content:h.thinking,signature:h.signature}),r.push(u)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(s.reasoning={effort:Kf(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:s.tool_choice=e.tool_choice.type),s}async transformResponseIn(e,r){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let s=await this.convertOpenAIStreamToAnthropic(e.body,r);return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let s=await e.json(),i=this.convertOpenAIResponseToAnthropic(s,r);return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(r=>({type:"function",function:{name:r.name,description:r.description||"",parameters:r.input_schema}}))}async convertOpenAIStreamToAnthropic(e,r){return new ReadableStream({start:async s=>{let i=new TextEncoder,u=`msg_${Date.now()}`,c=null,l="unknown",h=!1,f=!1,p=!1,A=new Map,v=new Map,S=0,y=0,g=0,m=!1,k=!1,b=0,E=-1,R=()=>{let M=b;return b++,M},x=M=>{if(!m)try{s.enqueue(M);let X=new TextDecoder().decode(M);this.logger.debug({reqId:r.req.id,data:X,type:"send data"})}catch(X){if(X instanceof TypeError&&X.message.includes("Controller is already closed"))m=!0;else throw this.logger.debug({reqId:r.req.id,error:X instanceof Error?X.message:String(X),type:"send data error"}),X}},$=()=>{if(!m)try{if(E>=0){let X={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
74
74
  data: ${JSON.stringify(X)}
75
75
 
76
- `)),w=-1}c?(x(i.encode(`event: message_delta
76
+ `)),E=-1}c?(x(i.encode(`event: message_delta
77
77
  data: ${JSON.stringify(c)}
78
78
 
79
79
  `)),c=null):x(i.encode(`event: message_delta
80
80
  data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}})}
81
81
 
82
- `));let U={type:"message_stop"};x(i.encode(`event: message_stop
83
- data: ${JSON.stringify(U)}
82
+ `));let M={type:"message_stop"};x(i.encode(`event: message_stop
83
+ data: ${JSON.stringify(M)}
84
84
 
85
- `)),s.close(),m=!0}catch(U){if(U instanceof TypeError&&U.message.includes("Controller is already closed"))m=!0;else throw U}},V=null;try{V=e.getReader();let U=new TextDecoder,X="";for(;!m;){let{done:ne,value:ae}=await V.read();if(ne)break;X+=U.decode(ae,{stream:!0});let de=X.split(`
86
- `);X=de.pop()||"";for(let ye of de){if(m||p)break;if(!ye.startsWith("data:"))continue;let Ae=ye.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:Ae}),Ae!=="[DONE]")try{let oe=JSON.parse(Ae);if(E++,this.logger.debug({reqId:r.req.id,response:oe,tppe:"Original Response"}),oe.error){let G={type:"error",message:{type:"api_error",message:JSON.stringify(oe.error)}};x(i.encode(`event: error
85
+ `)),s.close(),m=!0}catch(M){if(M instanceof TypeError&&M.message.includes("Controller is already closed"))m=!0;else throw M}},J=null;try{J=e.getReader();let M=new TextDecoder,X="";for(;!m;){let{done:ue,value:re}=await J.read();if(ue)break;X+=M.decode(re,{stream:!0});let de=X.split(`
86
+ `);X=de.pop()||"";for(let pe of de){if(m||p)break;if(!pe.startsWith("data:"))continue;let Ae=pe.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:Ae}),Ae!=="[DONE]")try{let oe=JSON.parse(Ae);if(S++,this.logger.debug({reqId:r.req.id,response:oe,tppe:"Original Response"}),oe.error){let G={type:"error",message:{type:"api_error",message:JSON.stringify(oe.error)}};x(i.encode(`event: error
87
87
  data: ${JSON.stringify(G)}
88
88
 
89
89
  `));continue}if(l=oe.model||l,!h&&!m&&!p){h=!0;let G={type:"message_start",message:{id:u,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};x(i.encode(`event: message_start
90
90
  data: ${JSON.stringify(G)}
91
91
 
92
- `))}let pe=oe.choices?.[0];if(oe.usage&&(c?c.usage={input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}}),!pe)continue;if(pe?.delta?.thinking&&!m&&!p){if(!T){let G=O(),K={type:"content_block_start",index:G,content_block:{type:"thinking",thinking:""}};x(i.encode(`event: content_block_start
92
+ `))}let me=oe.choices?.[0];if(oe.usage&&(c?c.usage={input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}}),!me)continue;if(me?.delta?.thinking&&!m&&!p){if(!k){let G=R(),K={type:"content_block_start",index:G,content_block:{type:"thinking",thinking:""}};x(i.encode(`event: content_block_start
93
93
  data: ${JSON.stringify(K)}
94
94
 
95
- `)),w=G,T=!0}if(pe.delta.thinking.signature){let G={type:"content_block_delta",index:w,delta:{type:"signature_delta",signature:pe.delta.thinking.signature}};x(i.encode(`event: content_block_delta
95
+ `)),E=G,k=!0}if(me.delta.thinking.signature){let G={type:"content_block_delta",index:E,delta:{type:"signature_delta",signature:me.delta.thinking.signature}};x(i.encode(`event: content_block_delta
96
96
  data: ${JSON.stringify(G)}
97
97
 
98
- `));let K={type:"content_block_stop",index:w};x(i.encode(`event: content_block_stop
98
+ `));let K={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
99
99
  data: ${JSON.stringify(K)}
100
100
 
101
- `)),w=-1}else if(pe.delta.thinking.content){let G={type:"content_block_delta",index:w,delta:{type:"thinking_delta",thinking:pe.delta.thinking.content||""}};x(i.encode(`event: content_block_delta
101
+ `)),E=-1}else if(me.delta.thinking.content){let G={type:"content_block_delta",index:E,delta:{type:"thinking_delta",thinking:me.delta.thinking.content||""}};x(i.encode(`event: content_block_delta
102
102
  data: ${JSON.stringify(G)}
103
103
 
104
- `))}}if(pe?.delta?.content&&!m&&!p){if(y++,w>=0&&!f){let K={type:"content_block_stop",index:w};x(i.encode(`event: content_block_stop
104
+ `))}}if(me?.delta?.content&&!m&&!p){if(y++,E>=0&&!f){let K={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
105
105
  data: ${JSON.stringify(K)}
106
106
 
107
- `)),w=-1}if(!f&&!p){f=!0;let G=O(),K={type:"content_block_start",index:G,content_block:{type:"text",text:""}};x(i.encode(`event: content_block_start
107
+ `)),E=-1}if(!f&&!p){f=!0;let G=R(),K={type:"content_block_start",index:G,content_block:{type:"text",text:""}};x(i.encode(`event: content_block_start
108
108
  data: ${JSON.stringify(K)}
109
109
 
110
- `)),w=G}if(!m&&!p){let G={type:"content_block_delta",index:w,delta:{type:"text_delta",text:pe.delta.content}};x(i.encode(`event: content_block_delta
110
+ `)),E=G}if(!m&&!p){let G={type:"content_block_delta",index:E,delta:{type:"text_delta",text:me.delta.content}};x(i.encode(`event: content_block_delta
111
111
  data: ${JSON.stringify(G)}
112
112
 
113
- `))}}if(pe?.delta?.annotations?.length&&!m&&!p){if(w>=0&&f){let G={type:"content_block_stop",index:w};x(i.encode(`event: content_block_stop
113
+ `))}}if(me?.delta?.annotations?.length&&!m&&!p){if(E>=0&&f){let G={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
114
114
  data: ${JSON.stringify(G)}
115
115
 
116
- `)),w=-1,f=!1}pe?.delta?.annotations.forEach(G=>{let K=O(),ue={type:"content_block_start",index:K,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Gt()}`,content:[{type:"web_search_result",title:G.url_citation.title,url:G.url_citation.url}]}};x(i.encode(`event: content_block_start
117
- data: ${JSON.stringify(ue)}
116
+ `)),E=-1,f=!1}me?.delta?.annotations.forEach(G=>{let K=R(),ae={type:"content_block_start",index:K,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Gt()}`,content:[{type:"web_search_result",title:G.url_citation.title,url:G.url_citation.url}]}};x(i.encode(`event: content_block_start
117
+ data: ${JSON.stringify(ae)}
118
118
 
119
119
  `));let qe={type:"content_block_stop",index:K};x(i.encode(`event: content_block_stop
120
120
  data: ${JSON.stringify(qe)}
121
121
 
122
- `)),w=-1})}if(pe?.delta?.tool_calls&&!m&&!p){g++;let G=new Set;for(let K of pe.delta.tool_calls){if(m)break;let ue=K.index??0;if(G.has(ue))continue;if(G.add(ue),!D.has(ue)){if(w>=0){let Re={type:"content_block_stop",index:w};x(i.encode(`event: content_block_stop
122
+ `)),E=-1})}if(me?.delta?.tool_calls&&!m&&!p){g++;let G=new Set;for(let K of me.delta.tool_calls){if(m)break;let ae=K.index??0;if(G.has(ae))continue;if(G.add(ae),!v.has(ae)){if(E>=0){let Re={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
123
123
  data: ${JSON.stringify(Re)}
124
124
 
125
- `)),w=-1}let De=O();D.set(ue,De);let W=K.id||`call_${Date.now()}_${ue}`,le=K.function?.name||`tool_${ue}`,_e={type:"content_block_start",index:De,content_block:{type:"tool_use",id:W,name:le,input:{}}};x(i.encode(`event: content_block_start
125
+ `)),E=-1}let De=R();v.set(ae,De);let W=K.id||`call_${Date.now()}_${ae}`,le=K.function?.name||`tool_${ae}`,_e={type:"content_block_start",index:De,content_block:{type:"tool_use",id:W,name:le,input:{}}};x(i.encode(`event: content_block_start
126
126
  data: ${JSON.stringify(_e)}
127
127
 
128
- `)),w=De;let Ft={id:W,name:le,arguments:"",contentBlockIndex:De};S.set(ue,Ft)}else if(K.id&&K.function?.name){let De=S.get(ue);De.id.startsWith("call_")&&De.name.startsWith("tool_")&&(De.id=K.id,De.name=K.function.name)}if(K.function?.arguments&&!m&&!p){let De=D.get(ue);if(De===void 0)continue;let W=S.get(ue);W&&(W.arguments+=K.function.arguments);try{let le={type:"content_block_delta",index:De,delta:{type:"input_json_delta",partial_json:K.function.arguments}};x(i.encode(`event: content_block_delta
128
+ `)),E=De;let Ft={id:W,name:le,arguments:"",contentBlockIndex:De};A.set(ae,Ft)}else if(K.id&&K.function?.name){let De=A.get(ae);De.id.startsWith("call_")&&De.name.startsWith("tool_")&&(De.id=K.id,De.name=K.function.name)}if(K.function?.arguments&&!m&&!p){let De=v.get(ae);if(De===void 0)continue;let W=A.get(ae);W&&(W.arguments+=K.function.arguments);try{let le={type:"content_block_delta",index:De,delta:{type:"input_json_delta",partial_json:K.function.arguments}};x(i.encode(`event: content_block_delta
129
129
  data: ${JSON.stringify(le)}
130
130
 
131
131
  `))}catch{try{let le=K.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),_e={type:"content_block_delta",index:De,delta:{type:"input_json_delta",partial_json:le}};x(i.encode(`event: content_block_delta
132
132
  data: ${JSON.stringify(_e)}
133
133
 
134
- `))}catch(le){console.error(le)}}}}}if(pe?.finish_reason&&!m&&!p){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),w>=0){let G={type:"content_block_stop",index:w};x(i.encode(`event: content_block_stop
134
+ `))}catch(le){console.error(le)}}}}}if(me?.finish_reason&&!m&&!p){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),E>=0){let G={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
135
135
  data: ${JSON.stringify(G)}
136
136
 
137
- `)),w=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[pe.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(oe){this.logger?.error(`parseError: ${oe.name} message: ${oe.message} stack: ${oe.stack} data: ${Ae}`)}}}$()}catch(U){if(!m)try{s.error(U)}catch(X){console.error(X)}}finally{if(V)try{V.releaseLock()}catch(U){console.error(U)}}},cancel:s=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${s}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let s=[];if(n.message.annotations){let u=`srvtoolu_${Gt()}`;s.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),s.push({type:"web_search_tool_result",tool_use_id:u,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&s.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(u=>{let c={};try{let l=u.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:u.function.arguments||""}}s.push({type:"tool_use",id:u.id,name:u.function.name,input:c})}),n.message?.thinking?.content&&s.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let i={id:e.id,type:"message",role:"assistant",model:e.model,content:s,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var On={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function tb(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(On).includes(n)?n:On.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(On).includes(s)?s:On.TYPE_UNSPECIFIED})}}}function Cs(t){let e={},r=["items"],n=["anyOf"],s=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let i=t.anyOf;i!=null&&Array.isArray(i)&&i.length==2&&(i[0]&&i[0].type==="null"?(e.nullable=!0,t=i[1]):i[1]&&i[1].type==="null"&&(e.nullable=!0,t=i[0])),t.type&&Array.isArray(t.type)&&tb(t.type,e);for(let[u,c]of Object.entries(t))if(c!=null)if(u=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(On).includes(l)?l:On.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=Cs(c);else if(n.includes(u)){let l=[];for(let h of c){if(h.type=="null"){e.nullable=!0;continue}l.push(Cs(h))}e[u]=l}else if(s.includes(u)){let l={};for(let[h,f]of Object.entries(c))l[h]=Cs(f);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function rb(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Cs(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Cs(e.response));return t}function $o(t){let e=[],r=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));r?.length&&e.push(rb({functionDeclarations:r})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let s=[],i=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let h;l.role==="assistant"?h="model":(["user","system"].includes(l.role),h="user");let f=[];if(typeof l.content=="string"){let p={text:l.content};l?.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),f.push(p)}else Array.isArray(l.content)?f.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?f.push({text:l.content.text}):f.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&f.push(...l.tool_calls.map((p,S)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:S===0&&l.thinking?.signature?l.thinking?.signature:void 0}))),f.length===0&&f.push({text:""}),s.push({role:h,parts:f}),h==="model"&&l.tool_calls){let p=l.tool_calls.map(S=>{let D=i.find(E=>E.tool_call_id===S.id);return{functionResponse:{name:S?.function?.name,response:{result:D?.content}}}});s.push({role:"user",parts:p})}});let u={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(u.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))u.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],h,f=t.reasoning.max_tokens;typeof f<"u"&&(f>=l[0]&&f<=l[1]?h=f:f<l[0]?h=l[0]:f>l[1]&&(h=l[1]),u.thinkingConfig.thinkingBudget=h)}let c={contents:s,tools:e.length?e:void 0,generationConfig:u};if(t.tool_choice){let l={functionCallingConfig:{}};t.tool_choice==="auto"?l.functionCallingConfig.mode="auto":t.tool_choice==="none"?l.functionCallingConfig.mode="none":t.tool_choice==="required"?l.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),c.toolConfig=l}return c}function zo(t){let e=t.contents,r=t.tools,n=t.model,s=t.max_tokens,i=t.temperature,u=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:s,temperature:i,stream:u,tool_choice:c};return Array.isArray(e)&&e.forEach(h=>{typeof h=="string"?l.messages.push({role:"user",content:h}):typeof h.text=="string"?l.messages.push({role:"user",content:h.text||null}):h.role==="user"?l.messages.push({role:"user",content:h?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):h.role==="model"&&l.messages.push({role:"assistant",content:h?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(f=>{l.tools.push({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})})})),l}async function Ho(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let s="",i="",u=n.candidates[0]?.content?.parts||[],c=[];for(let p of u)p.text&&p.thought===!0?s+=p.text:c.push(p);i=u.find(p=>p.thoughtSignature)?.thoughtSignature;let l=c?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],h=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
138
- `)||"",f={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:h,role:"assistant",tool_calls:l.length>0?l:void 0,...i&&{thinking:{content:s||"(no content)",signature:i}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(f),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=!1,u=!1,c=!1,l="",h=0,f=-1,p=new ReadableStream({async start(S){let D=async(g,m)=>{if(g.startsWith("data: ")){let T=g.slice(6).trim();if(T){r?.debug({chunkStr:T},`${e} chunk:`);try{let b=JSON.parse(T);if(!b.candidates||!b.candidates[0]){r?.debug({chunkStr:T},"Invalid chunk structure");return}let w=b.candidates[0],O=w.content?.parts||[];O.filter(U=>U.text&&U.thought===!0).forEach(U=>{c||(c=!0);let X={choices:[{delta:{role:"assistant",content:null,thinking:{content:U.text}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(X)}
137
+ `)),E=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[me.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(oe){this.logger?.error(`parseError: ${oe.name} message: ${oe.message} stack: ${oe.stack} data: ${Ae}`)}}}$()}catch(M){if(!m)try{s.error(M)}catch(X){console.error(X)}}finally{if(J)try{J.releaseLock()}catch(M){console.error(M)}}},cancel:s=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${s}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let s=[];if(n.message.annotations){let u=`srvtoolu_${Gt()}`;s.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),s.push({type:"web_search_tool_result",tool_use_id:u,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&s.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(u=>{let c={};try{let l=u.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:u.function.arguments||""}}s.push({type:"tool_use",id:u.id,name:u.function.name,input:c})}),n.message?.thinking?.content&&s.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let i={id:e.id,type:"message",role:"assistant",model:e.model,content:s,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var On={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function rb(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(On).includes(n)?n:On.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(On).includes(s)?s:On.TYPE_UNSPECIFIED})}}}function Cs(t){let e={},r=["items"],n=["anyOf"],s=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let i=t.anyOf;i!=null&&Array.isArray(i)&&i.length==2&&(i[0]&&i[0].type==="null"?(e.nullable=!0,t=i[1]):i[1]&&i[1].type==="null"&&(e.nullable=!0,t=i[0])),t.type&&Array.isArray(t.type)&&rb(t.type,e);for(let[u,c]of Object.entries(t))if(c!=null)if(u=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(On).includes(l)?l:On.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=Cs(c);else if(n.includes(u)){let l=[];for(let h of c){if(h.type=="null"){e.nullable=!0;continue}l.push(Cs(h))}e[u]=l}else if(s.includes(u)){let l={};for(let[h,f]of Object.entries(c))l[h]=Cs(f);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function nb(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Cs(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Cs(e.response));return t}function $o(t){let e=[],r=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));r?.length&&e.push(nb({functionDeclarations:r})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let s=[],i=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let h;l.role==="assistant"?h="model":(["user","system"].includes(l.role),h="user");let f=[];if(typeof l.content=="string"){let p={text:l.content};l?.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),f.push(p)}else Array.isArray(l.content)?f.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?f.push({text:l.content.text}):f.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&f.push(...l.tool_calls.map((p,A)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:A===0&&l.thinking?.signature?l.thinking?.signature:void 0}))),f.length===0&&f.push({text:""}),s.push({role:h,parts:f}),h==="model"&&l.tool_calls){let p=l.tool_calls.map(A=>{let v=i.find(S=>S.tool_call_id===A.id);return{functionResponse:{name:A?.function?.name,response:{result:v?.content}}}});s.push({role:"user",parts:p})}});let u={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(u.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))u.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],h,f=t.reasoning.max_tokens;typeof f<"u"&&(f>=l[0]&&f<=l[1]?h=f:f<l[0]?h=l[0]:f>l[1]&&(h=l[1]),u.thinkingConfig.thinkingBudget=h)}let c={contents:s,tools:e.length?e:void 0,generationConfig:u};if(t.tool_choice){let l={functionCallingConfig:{}};t.tool_choice==="auto"?l.functionCallingConfig.mode="auto":t.tool_choice==="none"?l.functionCallingConfig.mode="none":t.tool_choice==="required"?l.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),c.toolConfig=l}return c}function zo(t){let e=t.contents,r=t.tools,n=t.model,s=t.max_tokens,i=t.temperature,u=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:s,temperature:i,stream:u,tool_choice:c};return Array.isArray(e)&&e.forEach(h=>{typeof h=="string"?l.messages.push({role:"user",content:h}):typeof h.text=="string"?l.messages.push({role:"user",content:h.text||null}):h.role==="user"?l.messages.push({role:"user",content:h?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):h.role==="model"&&l.messages.push({role:"assistant",content:h?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(f=>{l.tools.push({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})})})),l}async function Ho(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let s="",i="",u=n.candidates[0]?.content?.parts||[],c=[];for(let p of u)p.text&&p.thought===!0?s+=p.text:c.push(p);i=u.find(p=>p.thoughtSignature)?.thoughtSignature;let l=c?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],h=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
138
+ `)||"",f={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:h,role:"assistant",tool_calls:l.length>0?l:void 0,...i&&{thinking:{content:s||"(no content)",signature:i}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(f),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=!1,u=!1,c=!1,l="",h=0,f=-1,p=new ReadableStream({async start(A){let v=async(g,m)=>{if(g.startsWith("data: ")){let k=g.slice(6).trim();if(k){r?.debug({chunkStr:k},`${e} chunk:`);try{let b=JSON.parse(k);if(!b.candidates||!b.candidates[0]){r?.debug({chunkStr:k},"Invalid chunk structure");return}let E=b.candidates[0],R=E.content?.parts||[];R.filter(M=>M.text&&M.thought===!0).forEach(M=>{c||(c=!0);let X={choices:[{delta:{role:"assistant",content:null,thinking:{content:M.text}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(X)}
139
139
 
140
- `))});let x=O.find(U=>U.thoughtSignature)?.thoughtSignature;if(x&&!i){if(!c){let X={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(X)}
140
+ `))});let x=R.find(M=>M.thoughtSignature)?.thoughtSignature;if(x&&!i){if(!c){let X={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(X)}
141
141
 
142
- `))}let U={choices:[{delta:{role:"assistant",content:null,thinking:{signature:x}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(s.encode(`data: ${JSON.stringify(U)}
142
+ `))}let M={choices:[{delta:{role:"assistant",content:null,thinking:{signature:x}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(s.encode(`data: ${JSON.stringify(M)}
143
143
 
144
144
  `)),i=!0,h++,l){let X={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(X)}
145
145
 
146
- `)),l="",u||(u=!0)}}let $=O.filter(U=>U.functionCall).map(U=>({id:U.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:U.functionCall?.name,arguments:JSON.stringify(U.functionCall?.args||{})}})),V=O.filter(U=>U.text&&U.thought!==!0).map(U=>U.text).join(`
147
- `);if(!V&&i&&!u){let U={choices:[{delta:{role:"assistant",content:"(no content)"},index:h,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(U)}
146
+ `)),l="",u||(u=!0)}}let $=R.filter(M=>M.functionCall).map(M=>({id:M.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:M.functionCall?.name,arguments:JSON.stringify(M.functionCall?.args||{})}})),J=R.filter(M=>M.text&&M.thought!==!0).map(M=>M.text).join(`
147
+ `);if(!J&&i&&!u){let M={choices:[{delta:{role:"assistant",content:"(no content)"},index:h,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(M)}
148
148
 
149
- `)),u||(u=!0)}if(c&&V&&!i)if(b.modelVersion.includes("3")){l+=V;return}else{let U={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(U)}
149
+ `)),u||(u=!0)}if(c&&J&&!i)if(b.modelVersion.includes("3")){l+=J;return}else{let M={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(M)}
150
150
 
151
- `)),i=!0}if(V){l||h++;let U={choices:[{delta:{role:"assistant",content:V},finish_reason:w.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};w?.groundingMetadata?.groundingChunks?.length&&(U.choices[0].delta.annotations=w.groundingMetadata.groundingChunks.map((X,ne)=>{let ae=w?.groundingMetadata?.groundingSupports?.filter(de=>de.groundingChunkIndices?.includes(ne));return{type:"url_citation",url_citation:{url:X?.web?.uri||"",title:X?.web?.title||"",content:ae?.[0]?.segment?.text||"",start_index:ae?.[0]?.segment?.startIndex||0,end_index:ae?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(U)}
151
+ `)),i=!0}if(J){l||h++;let M={choices:[{delta:{role:"assistant",content:J},finish_reason:E.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(M.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((X,ue)=>{let re=E?.groundingMetadata?.groundingSupports?.filter(de=>de.groundingChunkIndices?.includes(ue));return{type:"url_citation",url_citation:{url:X?.web?.uri||"",title:X?.web?.title||"",content:re?.[0]?.segment?.text||"",start_index:re?.[0]?.segment?.startIndex||0,end_index:re?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(M)}
152
152
 
153
- `)),!u&&V&&(u=!0)}$.length>0&&($.forEach(U=>{h++,f++;let X={choices:[{delta:{role:"assistant",tool_calls:[{...U,index:f}]},finish_reason:w.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};w?.groundingMetadata?.groundingChunks?.length&&(X.choices[0].delta.annotations=w.groundingMetadata.groundingChunks.map((ne,ae)=>{let de=w?.groundingMetadata?.groundingSupports?.filter(ye=>ye.groundingChunkIndices?.includes(ae));return{type:"url_citation",url_citation:{url:ne?.web?.uri||"",title:ne?.web?.title||"",content:de?.[0]?.segment?.text||"",start_index:de?.[0]?.segment?.startIndex||0,end_index:de?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(X)}
153
+ `)),!u&&J&&(u=!0)}$.length>0&&($.forEach(M=>{h++,f++;let X={choices:[{delta:{role:"assistant",tool_calls:[{...M,index:f}]},finish_reason:E.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(X.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((ue,re)=>{let de=E?.groundingMetadata?.groundingSupports?.filter(pe=>pe.groundingChunkIndices?.includes(re));return{type:"url_citation",url_citation:{url:ue?.web?.uri||"",title:ue?.web?.title||"",content:de?.[0]?.segment?.text||"",start_index:de?.[0]?.segment?.startIndex||0,end_index:de?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(X)}
154
154
 
155
- `))}),!u&&V&&(u=!0))}catch(b){r?.error(`Error parsing ${e} stream chunk`,T,b.message)}}}},E=t.body.getReader(),y="";try{for(;;){let{done:g,value:m}=await E.read();if(g){y&&await D(y,S);break}y+=n.decode(m,{stream:!0});let T=y.split(`
156
- `);y=T.pop()||"";for(let b of T)await D(b,S)}}catch(g){S.error(g)}finally{S.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var Wo=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:$o(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,r.baseUrl),headers:{"x-goog-api-key":r.apiKey,Authorization:void 0}}}}transformRequestOut=zo;async transformResponseOut(e){return Ho(e,this.name,this.logger)}};async function IS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Pr(Gl(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
155
+ `))}),!u&&J&&(u=!0))}catch(b){r?.error(`Error parsing ${e} stream chunk`,k,b.message)}}}},S=t.body.getReader(),y="";try{for(;;){let{done:g,value:m}=await S.read();if(g){y&&await v(y,A);break}y+=n.decode(m,{stream:!0});let k=y.split(`
156
+ `);y=k.pop()||"";for(let b of k)await v(b,A)}}catch(g){A.error(g)}finally{A.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var Wo=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:$o(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,r.baseUrl),headers:{"x-goog-api-key":r.apiKey,Authorization:void 0}}}}transformRequestOut=zo;async transformResponseOut(e){return Ho(e,this.name,this.logger)}};async function NS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Pr(Gl(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
157
157
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
158
158
  2. Run "gcloud auth application-default login"
159
- 3. Use Google Cloud environment with default service account`)}}var la=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(n=l.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await IS();return{body:$o(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${s}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return zo(e)}async transformResponseOut(e){return Ho(e,this.name)}};var da=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages.forEach(r=>{if(r.role==="assistant"){let n=r.thinking?.content,s=r.thinking?.signature;n&&typeof n=="string"&&n.trim()&&(r.reasoning_content=n,s&&(r.reasoning_content_signature=s)),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s="",i=!1,u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),f=(S,D,E)=>{let y=S.split(`
160
- `);for(let g of y)g.trim()&&D.enqueue(E.encode(g+`
161
- `))},p=(S,D)=>{let{controller:E,encoder:y}=D;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]")try{let g=JSON.parse(S.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){D.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let T=`data: ${JSON.stringify(m)}
159
+ 3. Use Google Cloud environment with default service account`)}}var la=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(n=l.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await NS();return{body:$o(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${s}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return zo(e)}async transformResponseOut(e){return Ho(e,this.name)}};var da=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages.forEach(r=>{if(r.role==="assistant"){let n=r.thinking?.content,s=r.thinking?.signature;n&&typeof n=="string"&&n.trim()&&(r.reasoning_content=n,s&&(r.reasoning_content_signature=s)),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s="",i=!1,u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),f=(A,v,S)=>{let y=A.split(`
160
+ `);for(let g of y)g.trim()&&v.enqueue(S.encode(g+`
161
+ `))},p=(A,v)=>{let{controller:S,encoder:y}=v;if(A.startsWith("data: ")&&A.trim()!=="data: [DONE]")try{let g=JSON.parse(A.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){v.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(m)}
162
162
 
163
- `;E.enqueue(y.encode(T));return}if(g.choices?.[0]?.delta?.content&&D.reasoningContent()&&!D.isReasoningComplete()){D.setReasoningComplete(!0);let m=Date.now().toString(),T={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:D.reasoningContent(),signature:m}}}]};delete T.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(T)}
163
+ `;S.enqueue(y.encode(k));return}if(g.choices?.[0]?.delta?.content&&v.reasoningContent()&&!v.isReasoningComplete()){v.setReasoningComplete(!0);let m=Date.now().toString(),k={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:v.reasoningContent(),signature:m}}}]};delete k.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(k)}
164
164
 
165
- `;E.enqueue(y.encode(b))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){D.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
165
+ `;S.enqueue(y.encode(b))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){v.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
166
166
 
167
- `;E.enqueue(y.encode(m))}}catch{E.enqueue(y.encode(S+`
168
- `))}else E.enqueue(y.encode(S+`
169
- `))};try{for(;;){let{done:S,value:D}=await h.read();if(S){u.trim()&&f(u,l,n);break}let E=r.decode(D,{stream:!0});u+=E;let y=u.split(`
167
+ `;S.enqueue(y.encode(m))}}catch{S.enqueue(y.encode(A+`
168
+ `))}else S.enqueue(y.encode(A+`
169
+ `))};try{for(;;){let{done:A,value:v}=await h.read();if(A){u.trim()&&f(u,l,n);break}let S=r.decode(v,{stream:!0});u+=S;let y=u.split(`
170
170
  `);u=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>s,appendReasoningContent:m=>s+=m,isReasoningComplete:()=>i,setReasoningComplete:m=>i=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
171
- `))}}}catch(S){console.error("Stream error:",S),l.error(S)}finally{try{h.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var fa=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
171
+ `))}}}catch(A){console.error("Stream error:",A),l.error(A)}finally{try{h.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var fa=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
172
172
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
173
173
  Examples:
174
174
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
175
- 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message.tool_calls?.length&&r?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=r?.choices[0]?.message.tool_calls[0],s=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=s.response||"",delete r.choices[0].message.tool_calls}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=-1,i="",u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),f=(S,D,E)=>{let y=S.split(`
176
- `);for(let g of y)g.trim()&&D.enqueue(E.encode(g+`
177
- `))},p=(S,D)=>{let{controller:E,encoder:y,exitToolIndex:g,setExitToolIndex:m,appendExitToolResponse:T}=D;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]")try{let b=JSON.parse(S.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let w=b.choices[0].delta.tool_calls[0];if(w.function?.name==="ExitTool"){m(w.index);return}else if(g()>-1&&w.index===g()&&w.function.arguments){T(w.function.arguments);try{let O=JSON.parse(D.exitToolResponse());b.choices=[{delta:{role:"assistant",content:O.response||""}}];let x=`data: ${JSON.stringify(b)}
175
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message.tool_calls?.length&&r?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=r?.choices[0]?.message.tool_calls[0],s=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=s.response||"",delete r.choices[0].message.tool_calls}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=-1,i="",u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),f=(A,v,S)=>{let y=A.split(`
176
+ `);for(let g of y)g.trim()&&v.enqueue(S.encode(g+`
177
+ `))},p=(A,v)=>{let{controller:S,encoder:y,exitToolIndex:g,setExitToolIndex:m,appendExitToolResponse:k}=v;if(A.startsWith("data: ")&&A.trim()!=="data: [DONE]")try{let b=JSON.parse(A.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let E=b.choices[0].delta.tool_calls[0];if(E.function?.name==="ExitTool"){m(E.index);return}else if(g()>-1&&E.index===g()&&E.function.arguments){k(E.function.arguments);try{let R=JSON.parse(v.exitToolResponse());b.choices=[{delta:{role:"assistant",content:R.response||""}}];let x=`data: ${JSON.stringify(b)}
178
178
 
179
- `;E.enqueue(y.encode(x))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let w=`data: ${JSON.stringify(b)}
179
+ `;S.enqueue(y.encode(x))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let E=`data: ${JSON.stringify(b)}
180
180
 
181
- `;E.enqueue(y.encode(w))}}catch{E.enqueue(y.encode(S+`
182
- `))}else E.enqueue(y.encode(S+`
183
- `))};try{for(;;){let{done:S,value:D}=await h.read();if(S){u.trim()&&f(u,l,n);break}let E=r.decode(D,{stream:!0});u+=E;let y=u.split(`
181
+ `;S.enqueue(y.encode(E))}}catch{S.enqueue(y.encode(A+`
182
+ `))}else S.enqueue(y.encode(A+`
183
+ `))};try{for(;;){let{done:A,value:v}=await h.read();if(A){u.trim()&&f(u,l,n);break}let S=r.decode(v,{stream:!0});u+=S;let y=u.split(`
184
184
  `);u=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,exitToolIndex:()=>s,setExitToolIndex:m=>s=m,exitToolResponse:()=>i,appendExitToolResponse:m=>i+=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
185
- `))}}}catch(S){console.error("Stream error:",S),l.error(S)}finally{try{h.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ha=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c=!1,l="",h=new ReadableStream({async start(f){let p=e.body.getReader(),S=(E,y,g)=>{let m=E.split(`
186
- `);for(let T of m)T.trim()&&y.enqueue(g.encode(T+`
187
- `))},D=(E,y)=>{let{controller:g,encoder:m}=y;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]"){let T=E.slice(6);try{let b=JSON.parse(T);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
185
+ `))}}}catch(A){console.error("Stream error:",A),l.error(A)}finally{try{h.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ha=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c=!1,l="",h=new ReadableStream({async start(f){let p=e.body.getReader(),A=(S,y,g)=>{let m=S.split(`
186
+ `);for(let k of m)k.trim()&&y.enqueue(g.encode(k+`
187
+ `))},v=(S,y)=>{let{controller:g,encoder:m}=y;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let k=S.slice(6);try{let b=JSON.parse(k);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
188
188
 
189
- `));return}if(b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let V={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};V.choices?.[0]?.delta&&delete V.choices[0].delta.reasoning;let U=`data: ${JSON.stringify(V)}
189
+ `));return}if(b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let J={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};J.choices?.[0]?.delta&&delete J.choices[0].delta.reasoning;let M=`data: ${JSON.stringify(J)}
190
190
 
191
- `;g.enqueue(m.encode(U));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let V=Date.now().toString(),U={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:V}}}]};U.choices?.[0]?.delta&&delete U.choices[0].delta.reasoning;let X=`data: ${JSON.stringify(U)}
191
+ `;g.enqueue(m.encode(M));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let J=Date.now().toString(),M={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:J}}}]};M.choices?.[0]?.delta&&delete M.choices[0].delta.reasoning;let X=`data: ${JSON.stringify(M)}
192
192
 
193
- `;g.enqueue(m.encode(X))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(V=>{V.id=`call_${Gt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let w=b.choices?.[0]?.delta,O=w&&Object.keys(w).length>0,x=b.choices?.[0]?.finish_reason,$=b.usage;if(O||x||$){let V=`data: ${JSON.stringify(b)}
193
+ `;g.enqueue(m.encode(X))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(J=>{J.id=`call_${Gt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let E=b.choices?.[0]?.delta,R=E&&Object.keys(E).length>0,x=b.choices?.[0]?.finish_reason,$=b.usage;if(R||x||$){let J=`data: ${JSON.stringify(b)}
194
194
 
195
- `;g.enqueue(m.encode(V))}}catch{g.enqueue(m.encode(E+`
196
- `))}}else g.enqueue(m.encode(E+`
197
- `))};try{for(;;){let{done:E,value:y}=await p.read();if(E){l.trim()&&S(l,f,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(T){console.warn("Failed to decode chunk",T);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let T=l.split(`
198
- `);l=T.pop()||"";for(let b of T)if(b.trim())try{D(b,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:w=>s=w,reasoningContent:()=>i,appendReasoningContent:w=>i+=w,isReasoningComplete:()=>u,setReasoningComplete:w=>u=w})}catch(w){console.error("Error processing line:",b,w),f.enqueue(n.encode(b+`
195
+ `;g.enqueue(m.encode(J))}}catch{g.enqueue(m.encode(S+`
196
+ `))}}else g.enqueue(m.encode(S+`
197
+ `))};try{for(;;){let{done:S,value:y}=await p.read();if(S){l.trim()&&A(l,f,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
198
+ `);l=k.pop()||"";for(let b of k)if(b.trim())try{v(b,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:E=>s=E,reasoningContent:()=>i,appendReasoningContent:E=>i+=E,isReasoningComplete:()=>u,setReasoningComplete:E=>u=E})}catch(E){console.error("Error processing line:",b,E),f.enqueue(n.encode(b+`
199
199
  `))}continue}let m=l.split(`
200
- `);l=m.pop()||"";for(let T of m)if(T.trim())try{D(T,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",T,b),f.enqueue(n.encode(T+`
201
- `))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{p.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var pa=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var ma=class{name="groq";async transformRequestIn(e){return e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(r=>{delete r.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c="",l=new ReadableStream({async start(h){let f=e.body.getReader(),p=(D,E,y)=>{let g=D.split(`
202
- `);for(let m of g)m.trim()&&E.enqueue(y.encode(m+`
203
- `))},S=(D,E)=>{let{controller:y,encoder:g}=E;if(D.startsWith("data: ")&&D.trim()!=="data: [DONE]"){let m=D.slice(6);try{let T=JSON.parse(m);if(T.error)throw new Error(JSON.stringify(T));T.choices?.[0]?.delta?.content&&!E.hasTextContent()&&E.setHasTextContent(!0),T.choices?.[0]?.delta?.tool_calls?.length&&T.choices?.[0]?.delta?.tool_calls.forEach(w=>{w.id=`call_${Gt()}`}),T.choices?.[0]?.delta?.tool_calls?.length&&E.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let b=`data: ${JSON.stringify(T)}
204
-
205
- `;y.enqueue(g.encode(b))}catch{y.enqueue(g.encode(D+`
206
- `))}}else y.enqueue(g.encode(D+`
207
- `))};try{for(;;){let{done:D,value:E}=await f.read();if(D){c.trim()&&p(c,h,n);break}if(!E||E.length===0)continue;let y;try{y=r.decode(E,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=c.split(`
208
- `);c=m.pop()||"";for(let T of m)if(T.trim())try{S(T,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",T,b),h.enqueue(n.encode(T+`
200
+ `);l=m.pop()||"";for(let k of m)if(k.trim())try{v(k,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",k,b),f.enqueue(n.encode(k+`
201
+ `))}}}catch(S){console.error("Stream error:",S),f.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}f.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var pa=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var ma=class{name="groq";async transformRequestIn(e){return e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(r=>{delete r.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c="",l=new ReadableStream({async start(h){let f=e.body.getReader(),p=(v,S,y)=>{let g=v.split(`
202
+ `);for(let m of g)m.trim()&&S.enqueue(y.encode(m+`
203
+ `))},A=(v,S)=>{let{controller:y,encoder:g}=S;if(v.startsWith("data: ")&&v.trim()!=="data: [DONE]"){let m=v.slice(6);try{let k=JSON.parse(m);if(k.error)throw new Error(JSON.stringify(k));k.choices?.[0]?.delta?.content&&!S.hasTextContent()&&S.setHasTextContent(!0),k.choices?.[0]?.delta?.tool_calls?.length&&k.choices?.[0]?.delta?.tool_calls.forEach(E=>{E.id=`call_${Gt()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&S.hasTextContent()&&(typeof k.choices[0].index=="number"?k.choices[0].index+=1:k.choices[0].index=1);let b=`data: ${JSON.stringify(k)}
204
+
205
+ `;y.enqueue(g.encode(b))}catch{y.enqueue(g.encode(v+`
206
+ `))}}else y.enqueue(g.encode(v+`
207
+ `))};try{for(;;){let{done:v,value:S}=await f.read();if(v){c.trim()&&p(c,h,n);break}if(!S||S.length===0)continue;let y;try{y=r.decode(S,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=c.split(`
208
+ `);c=m.pop()||"";for(let k of m)if(k.trim())try{A(k,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",k,b),h.enqueue(n.encode(k+`
209
209
  `))}continue}let g=c.split(`
210
- `);c=g.pop()||"";for(let m of g)if(m.trim())try{S(m,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>i,appendReasoningContent:T=>i+=T,isReasoningComplete:()=>u,setReasoningComplete:T=>u=T})}catch(T){console.error("Error processing line:",m,T),h.enqueue(n.encode(m+`
211
- `))}}}catch(D){console.error("Stream error:",D),h.error(D)}finally{try{f.releaseLock()}catch(D){console.error("Error releasing reader lock:",D)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ga=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),e}};var cy=Pr(Au());var wr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function ry(t){return/^[0-9A-Fa-f]$/.test(t)}function Wr(t){return t>="0"&&t<="9"}function ny(t){return t>=" "}function Ks(t){return`,:[]/{}()
210
+ `);c=g.pop()||"";for(let m of g)if(m.trim())try{A(m,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:k=>s=k,reasoningContent:()=>i,appendReasoningContent:k=>i+=k,isReasoningComplete:()=>u,setReasoningComplete:k=>u=k})}catch(k){console.error("Error processing line:",m,k),h.enqueue(n.encode(m+`
211
+ `))}}}catch(v){console.error("Stream error:",v),h.error(v)}finally{try{f.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ga=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),e}};var cy=Pr(Au());var wr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function ry(t){return/^[0-9A-Fa-f]$/.test(t)}function Wr(t){return t>="0"&&t<="9"}function ny(t){return t>=" "}function Ks(t){return`,:[]/{}()
212
212
  +`.includes(t)}function Jl(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Vl(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Kl=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Yl=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Xl(t){return`,[]/{}
213
- +`.includes(t)}function Ql(t){return Ys(t)||NS.test(t)}var NS=/^[[{\w-]$/;function sy(t){return t===`
214
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Hr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function oy(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function iy(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function Ys(t){return Zl(t)||ya(t)}function Zl(t){return t==='"'||t==="\u201C"||t==="\u201D"}function ed(t){return t==='"'}function ya(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function td(t){return t==="'"}function os(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=t.lastIndexOf(e);return n!==-1?t.substring(0,n)+(r?"":t.substring(n+1)):t}function Rt(t,e){let r=t.length;if(!Hr(t,r-1))return t+e;for(;Hr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function ay(t,e,r){return t.substring(0,e)+t.substring(e+r)}function uy(t){return/[,\n][ \t\r]*$/.test(t)}var BS={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},jS={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
215
- `,r:"\r",t:" "};function rd(t){let e=0,r="";h(["```","[```","{```"]),i()||ye(),h(["```","```]","```}"]);let s=p(",");for(s&&u(),Ql(t[e])&&uy(r)?(s||(r=Rt(r,",")),m()):s&&(r=os(r,","));t[e]==="}"||t[e]==="]";)e++,u();if(e>=t.length)return r;de();function i(){u();let G=y()||g()||T()||w()||O()||$(!1)||V();return u(),G}function u(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,K=e,ue=c(G);do ue=l(),ue&&(ue=c(G));while(ue);return e>K}function c(G){let K=G?Hr:oy,ue="";for(;;)if(K(t,e))ue+=t[e],e++;else if(iy(t,e))ue+=" ",e++;else break;return ue.length>0?(r+=ue,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!LS(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
216
- `;)e++;return!0}return!1}function h(G){if(f(G)){if(Jl(t[e]))for(;e<t.length&&Vl(t[e]);)e++;return u(),!0}return!1}function f(G){c(!0);for(let K of G){let ue=e+K.length;if(t.slice(e,ue)===K)return e=ue,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function S(G){return t[e]===G?(e++,!0):!1}function D(){return S("\\")}function E(){return u(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,u(),S(","),!0):!1}function y(){if(t[e]==="{"){r+="{",e++,u(),S(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="}";){let K;if(G?(K=!0,G=!1):(K=p(","),K||(r=Rt(r,",")),u()),E(),!(T()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=os(r,","):Ae();break}u();let qe=p(":"),De=e>=t.length;qe||(Ql(t[e])||De?r=Rt(r,":"):oe()),i()||(qe||De?r+="null":oe())}return t[e]==="}"?(r+="}",e++):r=Rt(r,"}"),!0}return!1}function g(){if(t[e]==="["){r+="[",e++,u(),S(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Rt(r,",")),E(),!i()){r=os(r,",");break}return t[e]==="]"?(r+="]",e++):r=Rt(r,"]"),!0}return!1}function m(){let G=!0,K=!0;for(;K;)G?G=!1:p(",")||(r=Rt(r,",")),K=i();K||(r=os(r,",")),r=`[
213
+ +`.includes(t)}function Ql(t){return Ys(t)||BS.test(t)}var BS=/^[[{\w-]$/;function sy(t){return t===`
214
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Hr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function oy(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function iy(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function Ys(t){return Zl(t)||ya(t)}function Zl(t){return t==='"'||t==="\u201C"||t==="\u201D"}function ed(t){return t==='"'}function ya(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function td(t){return t==="'"}function os(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=t.lastIndexOf(e);return n!==-1?t.substring(0,n)+(r?"":t.substring(n+1)):t}function Rt(t,e){let r=t.length;if(!Hr(t,r-1))return t+e;for(;Hr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function ay(t,e,r){return t.substring(0,e)+t.substring(e+r)}function uy(t){return/[,\n][ \t\r]*$/.test(t)}var jS={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},LS={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
215
+ `,r:"\r",t:" "};function rd(t){let e=0,r="";h(["```","[```","{```"]),i()||pe(),h(["```","```]","```}"]);let s=p(",");for(s&&u(),Ql(t[e])&&uy(r)?(s||(r=Rt(r,",")),m()):s&&(r=os(r,","));t[e]==="}"||t[e]==="]";)e++,u();if(e>=t.length)return r;de();function i(){u();let G=y()||g()||k()||E()||R()||$(!1)||J();return u(),G}function u(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,K=e,ae=c(G);do ae=l(),ae&&(ae=c(G));while(ae);return e>K}function c(G){let K=G?Hr:oy,ae="";for(;;)if(K(t,e))ae+=t[e],e++;else if(iy(t,e))ae+=" ",e++;else break;return ae.length>0?(r+=ae,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!MS(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
216
+ `;)e++;return!0}return!1}function h(G){if(f(G)){if(Jl(t[e]))for(;e<t.length&&Vl(t[e]);)e++;return u(),!0}return!1}function f(G){c(!0);for(let K of G){let ae=e+K.length;if(t.slice(e,ae)===K)return e=ae,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function A(G){return t[e]===G?(e++,!0):!1}function v(){return A("\\")}function S(){return u(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,u(),A(","),!0):!1}function y(){if(t[e]==="{"){r+="{",e++,u(),A(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="}";){let K;if(G?(K=!0,G=!1):(K=p(","),K||(r=Rt(r,",")),u()),S(),!(k()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=os(r,","):Ae();break}u();let qe=p(":"),De=e>=t.length;qe||(Ql(t[e])||De?r=Rt(r,":"):oe()),i()||(qe||De?r+="null":oe())}return t[e]==="}"?(r+="}",e++):r=Rt(r,"}"),!0}return!1}function g(){if(t[e]==="["){r+="[",e++,u(),A(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Rt(r,",")),S(),!i()){r=os(r,",");break}return t[e]==="]"?(r+="]",e++):r=Rt(r,"]"),!0}return!1}function m(){let G=!0,K=!0;for(;K;)G?G=!1:p(",")||(r=Rt(r,",")),K=i();K||(r=os(r,",")),r=`[
217
217
  ${r}
218
- ]`}function T(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ue=t[e]==="\\";if(ue&&(e++,ue=!0),Ys(t[e])){let qe=ed(t[e])?ed:td(t[e])?td:ya(t[e])?ya:Zl,De=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let _e=U(e-1);return!G&&Ks(t.charAt(_e))?(e=De,r=r.substring(0,W),T(!0)):(le=Rt(le,'"'),r+=le,!0)}if(e===K)return le=Rt(le,'"'),r+=le,!0;if(qe(t[e])){let _e=e,Ft=le.length;if(le+='"',e++,r+=le,u(!1),G||e>=t.length||Ks(t[e])||Ys(t[e])||Wr(t[e]))return b(),!0;let Re=U(_e-1),Be=t.charAt(Re);if(Be===",")return e=De,r=r.substring(0,W),T(!1,Re);if(Ks(Be))return e=De,r=r.substring(0,W),T(!0);r=r.substring(0,W),e=_e+1,le=`${le.substring(0,Ft)}\\${le.substring(Ft)}`}else if(G&&Xl(t[e])){if(t[e-1]===":"&&Kl.test(t.substring(De+1,e+2)))for(;e<t.length&&Yl.test(t[e]);)le+=t[e],e++;return le=Rt(le,'"'),r+=le,b(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(jS[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&ry(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:pe()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):sy(_e)?(le+=BS[_e],e++):(ny(_e)||ae(_e),le+=_e,e++)}ue&&D()}}return!1}function b(){let G=!1;for(u();t[e]==="+";){G=!0,e++,u(),r=os(r,'"',!0);let K=r.length;T()?r=ay(r,K,1):r=Rt(r,'"')}return G}function w(){let G=e;if(t[e]==="-"){if(e++,X())return ne(G),!0;if(!Wr(t[e]))return e=G,!1}for(;Wr(t[e]);)e++;if(t[e]==="."){if(e++,X())return ne(G),!0;if(!Wr(t[e]))return e=G,!1;for(;Wr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,X())return ne(G),!0;if(!Wr(t[e]))return e=G,!1;for(;Wr(t[e]);)e++}if(!X())return e=G,!1;if(e>G){let K=t.slice(G,e),ue=/^0\d/.test(K);return r+=ue?`"${K}"`:K,!0}return!1}function O(){return x("true","true")||x("false","false")||x("null","null")||x("True","true")||x("False","false")||x("None","null")}function x(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function $(G){let K=e;if(Jl(t[e])){for(;e<t.length&&Vl(t[e]);)e++;let ue=e;for(;Hr(t,ue);)ue++;if(t[ue]==="(")return e=ue+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Xl(t[e])&&!Ys(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&Kl.test(t.substring(K,e+2)))for(;e<t.length&&Yl.test(t[e]);)e++;if(e>K){for(;Hr(t,e-1)&&e>0;)e--;let ue=t.slice(K,e);return r+=ue==="undefined"?"null":JSON.stringify(ue),t[e]==='"'&&e++,!0}}function V(){if(t[e]==="/"){let G=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,r+=`"${t.substring(G,e)}"`,!0}}function U(G){let K=G;for(;K>0&&Hr(t,K);)K--;return K}function X(){return e>=t.length||Ks(t[e])||Hr(t,e)}function ne(G){r+=`${t.slice(G,e)}0`}function ae(G){throw new wr(`Invalid character ${JSON.stringify(G)}`,e)}function de(){throw new wr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ye(){throw new wr("Unexpected end of json string",t.length)}function Ae(){throw new wr("Object key expected",e)}function oe(){throw new wr("Colon expected",e)}function pe(){let G=t.slice(e,e+6);throw new wr(`Invalid unicode character "${G}"`,e)}}function LS(t,e){return t[e]==="*"&&t[e+1]==="/"}function nd(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),t}catch(r){try{let n=cy.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let s=rd(t);return e?.debug("Tool arguments safely repaired"),s}catch(s){return e?.error(`JSON parsing failed: ${r.message}. JSON5 parsing failed: ${n.message}. JSON repair failed: ${s.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var _a=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message?.tool_calls?.length)for(let n of r.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=nd(n.function.arguments,this.logger));return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s={},i=!1,u="",c=!1,l=!1,h="",f=new ReadableStream({async start(p){let S=e.body.getReader(),D=(g,m,T)=>{let b=g.split(`
219
- `);for(let w of b)w.trim()&&m.enqueue(T.encode(w+`
220
- `))},E=(g,m,T)=>{let b="";try{b=nd(s.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(s)}`),b=s.arguments||""}let w={role:"assistant",tool_calls:[{function:{name:s.name,arguments:b},id:s.id,index:s.index,type:"function"}]},O={...g,choices:[{...g.choices[0],delta:w}]};O.choices[0].delta.content!==void 0&&delete O.choices[0].delta.content;let x=`data: ${JSON.stringify(O)}
218
+ ]`}function k(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ae=t[e]==="\\";if(ae&&(e++,ae=!0),Ys(t[e])){let qe=ed(t[e])?ed:td(t[e])?td:ya(t[e])?ya:Zl,De=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let _e=M(e-1);return!G&&Ks(t.charAt(_e))?(e=De,r=r.substring(0,W),k(!0)):(le=Rt(le,'"'),r+=le,!0)}if(e===K)return le=Rt(le,'"'),r+=le,!0;if(qe(t[e])){let _e=e,Ft=le.length;if(le+='"',e++,r+=le,u(!1),G||e>=t.length||Ks(t[e])||Ys(t[e])||Wr(t[e]))return b(),!0;let Re=M(_e-1),Be=t.charAt(Re);if(Be===",")return e=De,r=r.substring(0,W),k(!1,Re);if(Ks(Be))return e=De,r=r.substring(0,W),k(!0);r=r.substring(0,W),e=_e+1,le=`${le.substring(0,Ft)}\\${le.substring(Ft)}`}else if(G&&Xl(t[e])){if(t[e-1]===":"&&Kl.test(t.substring(De+1,e+2)))for(;e<t.length&&Yl.test(t[e]);)le+=t[e],e++;return le=Rt(le,'"'),r+=le,b(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(LS[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&ry(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:me()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):sy(_e)?(le+=jS[_e],e++):(ny(_e)||re(_e),le+=_e,e++)}ae&&v()}}return!1}function b(){let G=!1;for(u();t[e]==="+";){G=!0,e++,u(),r=os(r,'"',!0);let K=r.length;k()?r=ay(r,K,1):r=Rt(r,'"')}return G}function E(){let G=e;if(t[e]==="-"){if(e++,X())return ue(G),!0;if(!Wr(t[e]))return e=G,!1}for(;Wr(t[e]);)e++;if(t[e]==="."){if(e++,X())return ue(G),!0;if(!Wr(t[e]))return e=G,!1;for(;Wr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,X())return ue(G),!0;if(!Wr(t[e]))return e=G,!1;for(;Wr(t[e]);)e++}if(!X())return e=G,!1;if(e>G){let K=t.slice(G,e),ae=/^0\d/.test(K);return r+=ae?`"${K}"`:K,!0}return!1}function R(){return x("true","true")||x("false","false")||x("null","null")||x("True","true")||x("False","false")||x("None","null")}function x(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function $(G){let K=e;if(Jl(t[e])){for(;e<t.length&&Vl(t[e]);)e++;let ae=e;for(;Hr(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Xl(t[e])&&!Ys(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&Kl.test(t.substring(K,e+2)))for(;e<t.length&&Yl.test(t[e]);)e++;if(e>K){for(;Hr(t,e-1)&&e>0;)e--;let ae=t.slice(K,e);return r+=ae==="undefined"?"null":JSON.stringify(ae),t[e]==='"'&&e++,!0}}function J(){if(t[e]==="/"){let G=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,r+=`"${t.substring(G,e)}"`,!0}}function M(G){let K=G;for(;K>0&&Hr(t,K);)K--;return K}function X(){return e>=t.length||Ks(t[e])||Hr(t,e)}function ue(G){r+=`${t.slice(G,e)}0`}function re(G){throw new wr(`Invalid character ${JSON.stringify(G)}`,e)}function de(){throw new wr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function pe(){throw new wr("Unexpected end of json string",t.length)}function Ae(){throw new wr("Object key expected",e)}function oe(){throw new wr("Colon expected",e)}function me(){let G=t.slice(e,e+6);throw new wr(`Invalid unicode character "${G}"`,e)}}function MS(t,e){return t[e]==="*"&&t[e+1]==="/"}function nd(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),t}catch(r){try{let n=cy.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let s=rd(t);return e?.debug("Tool arguments safely repaired"),s}catch(s){return e?.error(`JSON parsing failed: ${r.message}. JSON5 parsing failed: ${n.message}. JSON repair failed: ${s.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var _a=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message?.tool_calls?.length)for(let n of r.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=nd(n.function.arguments,this.logger));return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s={},i=!1,u="",c=!1,l=!1,h="",f=new ReadableStream({async start(p){let A=e.body.getReader(),v=(g,m,k)=>{let b=g.split(`
219
+ `);for(let E of b)E.trim()&&m.enqueue(k.encode(E+`
220
+ `))},S=(g,m,k)=>{let b="";try{b=nd(s.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(s)}`),b=s.arguments||""}let E={role:"assistant",tool_calls:[{function:{name:s.name,arguments:b},id:s.id,index:s.index,type:"function"}]},R={...g,choices:[{...g.choices[0],delta:E}]};R.choices[0].delta.content!==void 0&&delete R.choices[0].delta.content;let x=`data: ${JSON.stringify(R)}
221
221
 
222
- `;m.enqueue(T.encode(x))},y=(g,m)=>{let{controller:T,encoder:b}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let w=g.slice(6);try{let O=JSON.parse(w);if(O.choices?.[0]?.delta?.tool_calls?.length){let $=O.choices[0].delta.tool_calls[0];if(typeof s.index>"u"){s={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""},$.function?.arguments&&($.function.arguments="");let V=`data: ${JSON.stringify(O)}
222
+ `;m.enqueue(k.encode(x))},y=(g,m)=>{let{controller:k,encoder:b}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let E=g.slice(6);try{let R=JSON.parse(E);if(R.choices?.[0]?.delta?.tool_calls?.length){let $=R.choices[0].delta.tool_calls[0];if(typeof s.index>"u"){s={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""},$.function?.arguments&&($.function.arguments="");let J=`data: ${JSON.stringify(R)}
223
223
 
224
- `;T.enqueue(b.encode(V));return}else if(s.index===$.index){$.function?.arguments&&(s.arguments+=$.function.arguments);return}else{E(O,T,b),s={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(O.choices?.[0]?.finish_reason==="tool_calls"&&s.index!==void 0){E(O,T,b),s={};return}O.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof O.choices[0].index=="number"?O.choices[0].index+=1:O.choices[0].index=1);let x=`data: ${JSON.stringify(O)}
224
+ `;k.enqueue(b.encode(J));return}else if(s.index===$.index){$.function?.arguments&&(s.arguments+=$.function.arguments);return}else{S(R,k,b),s={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(R.choices?.[0]?.finish_reason==="tool_calls"&&s.index!==void 0){S(R,k,b),s={};return}R.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof R.choices[0].index=="number"?R.choices[0].index+=1:R.choices[0].index=1);let x=`data: ${JSON.stringify(R)}
225
225
 
226
- `;T.enqueue(b.encode(x))}catch{T.enqueue(b.encode(g+`
227
- `))}}else T.enqueue(b.encode(g+`
228
- `))};try{for(;;){let{done:g,value:m}=await S.read();if(g){h.trim()&&D(h,p,n);break}if(!m||m.length===0)continue;let T;try{T=r.decode(m,{stream:!0})}catch(w){console.warn("Failed to decode chunk",w);continue}if(T.length===0)continue;if(h+=T,h.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let w=h.split(`
229
- `);h=w.pop()||"";for(let O of w)if(O.trim())try{y(O,{controller:p,encoder:n,hasTextContent:()=>i,setHasTextContent:x=>i=x,reasoningContent:()=>u,appendReasoningContent:x=>u+=x,isReasoningComplete:()=>c,setReasoningComplete:x=>c=x})}catch(x){console.error("Error processing line:",O,x),p.enqueue(n.encode(O+`
226
+ `;k.enqueue(b.encode(x))}catch{k.enqueue(b.encode(g+`
227
+ `))}}else k.enqueue(b.encode(g+`
228
+ `))};try{for(;;){let{done:g,value:m}=await A.read();if(g){h.trim()&&v(h,p,n);break}if(!m||m.length===0)continue;let k;try{k=r.decode(m,{stream:!0})}catch(E){console.warn("Failed to decode chunk",E);continue}if(k.length===0)continue;if(h+=k,h.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let E=h.split(`
229
+ `);h=E.pop()||"";for(let R of E)if(R.trim())try{y(R,{controller:p,encoder:n,hasTextContent:()=>i,setHasTextContent:x=>i=x,reasoningContent:()=>u,appendReasoningContent:x=>u+=x,isReasoningComplete:()=>c,setReasoningComplete:x=>c=x})}catch(x){console.error("Error processing line:",R,x),p.enqueue(n.encode(R+`
230
230
  `))}continue}let b=h.split(`
231
- `);h=b.pop()||"";for(let w of b)if(w.trim())try{y(w,{controller:p,encoder:n,hasTextContent:()=>i,setHasTextContent:O=>i=O,reasoningContent:()=>u,appendReasoningContent:O=>u+=O,isReasoningComplete:()=>c,setReasoningComplete:O=>c=O})}catch(O){console.error("Error processing line:",w,O),p.enqueue(n.encode(w+`
232
- `))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{S.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ba=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return r.choices[0]?.message.reasoning_content&&(r.thinking={content:r.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s="",i=!1,u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),f=(S,D,E)=>{let y=S.split(`
233
- `);for(let g of y)g.trim()&&D.enqueue(E.encode(g+`
234
- `))},p=(S,D)=>{let{controller:E,encoder:y}=D;if(this.logger?.debug({line:S},"Processing reason line"),S.startsWith("data: ")&&S.trim()!=="data: [DONE]")try{let g=JSON.parse(S.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){D.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let T=`data: ${JSON.stringify(m)}
231
+ `);h=b.pop()||"";for(let E of b)if(E.trim())try{y(E,{controller:p,encoder:n,hasTextContent:()=>i,setHasTextContent:R=>i=R,reasoningContent:()=>u,appendReasoningContent:R=>u+=R,isReasoningComplete:()=>c,setReasoningComplete:R=>c=R})}catch(R){console.error("Error processing line:",E,R),p.enqueue(n.encode(E+`
232
+ `))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{A.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ba=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return r.choices[0]?.message.reasoning_content&&(r.thinking={content:r.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s="",i=!1,u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),f=(A,v,S)=>{let y=A.split(`
233
+ `);for(let g of y)g.trim()&&v.enqueue(S.encode(g+`
234
+ `))},p=(A,v)=>{let{controller:S,encoder:y}=v;if(this.logger?.debug({line:A},"Processing reason line"),A.startsWith("data: ")&&A.trim()!=="data: [DONE]")try{let g=JSON.parse(A.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){v.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(m)}
235
235
 
236
- `;E.enqueue(y.encode(T));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&D.reasoningContent()&&!D.isReasoningComplete()){D.setReasoningComplete(!0);let m=Date.now().toString(),T={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:D.reasoningContent(),signature:m}}}]};delete T.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(T)}
236
+ `;S.enqueue(y.encode(k));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&v.reasoningContent()&&!v.isReasoningComplete()){v.setReasoningComplete(!0);let m=Date.now().toString(),k={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:v.reasoningContent(),signature:m}}}]};delete k.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(k)}
237
237
 
238
- `;E.enqueue(y.encode(b))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){D.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
238
+ `;S.enqueue(y.encode(b))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){v.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
239
239
 
240
- `;E.enqueue(y.encode(m))}}catch{E.enqueue(y.encode(S+`
241
- `))}else E.enqueue(y.encode(S+`
242
- `))};try{for(;;){let{done:S,value:D}=await h.read();if(S){u.trim()&&f(u,l,n);break}let E=r.decode(D,{stream:!0});u+=E;let y=u.split(`
240
+ `;S.enqueue(y.encode(m))}}catch{S.enqueue(y.encode(A+`
241
+ `))}else S.enqueue(y.encode(A+`
242
+ `))};try{for(;;){let{done:A,value:v}=await h.read();if(A){u.trim()&&f(u,l,n);break}let S=r.decode(v,{stream:!0});u+=S;let y=u.split(`
243
243
  `);u=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>s,appendReasoningContent:m=>s+=m,isReasoningComplete:()=>i,setReasoningComplete:m=>i=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
244
- `))}}}catch(S){console.error("Stream error:",S),l.error(S)}finally{try{h.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ca=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var wa=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function ly(t){let e=[];for(let n=0;n<t.messages.length;n++){let s=t.messages[n],i=n===t.messages.length-1,u=s.role==="assistant",c=[];typeof s.content=="string"?c.push({type:"text",text:s.content}):Array.isArray(s.content)&&s.content.forEach(l=>{l.type==="text"?c.push({type:"text",text:l.text||""}):l.type==="image_url"&&c.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!i&&c.length===0&&!s.tool_calls&&!s.content)&&(i&&u&&c.length===0&&s.tool_calls&&c.push({type:"text",text:""}),e.push({role:s.role==="assistant"?"assistant":"user",content:c}))}let r={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),r}function dy(t){let e=t,n={messages:e.messages.map(s=>{let i=s.content.map(u=>u.type==="text"?{type:"text",text:u.text||""}:u.type==="image"&&u.source?{type:"image_url",image_url:{url:u.source.data},media_type:u.source.media_type}:{type:"text",text:""});return{role:s.role,content:i}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(n.tools=e.tools.map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:{type:"object",properties:s.input_schema.properties,required:s.input_schema.required,additionalProperties:s.input_schema.additionalProperties,$schema:s.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function fy(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json(),s;n.tool_use&&n.tool_use.length>0&&(s=n.tool_use.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input)}})));let i={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...s&&{tool_calls:s}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.usage.output_tokens}};return new Response(JSON.stringify(i),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=(c,l)=>{if(c.startsWith("data: ")){let h=c.slice(6).trim();if(h){r?.debug({chunkStr:h},`${e} chunk:`);try{let f=JSON.parse(h);if(f.type==="content_block_delta"&&f.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:f.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
244
+ `))}}}catch(A){console.error("Stream error:",A),l.error(A)}finally{try{h.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ca=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var wa=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function ly(t){let e=[];for(let n=0;n<t.messages.length;n++){let s=t.messages[n],i=n===t.messages.length-1,u=s.role==="assistant",c=[];typeof s.content=="string"?c.push({type:"text",text:s.content}):Array.isArray(s.content)&&s.content.forEach(l=>{l.type==="text"?c.push({type:"text",text:l.text||""}):l.type==="image_url"&&c.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!i&&c.length===0&&!s.tool_calls&&!s.content)&&(i&&u&&c.length===0&&s.tool_calls&&c.push({type:"text",text:""}),e.push({role:s.role==="assistant"?"assistant":"user",content:c}))}let r={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),r}function dy(t){let e=t,n={messages:e.messages.map(s=>{let i=s.content.map(u=>u.type==="text"?{type:"text",text:u.text||""}:u.type==="image"&&u.source?{type:"image_url",image_url:{url:u.source.data},media_type:u.source.media_type}:{type:"text",text:""});return{role:s.role,content:i}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(n.tools=e.tools.map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:{type:"object",properties:s.input_schema.properties,required:s.input_schema.required,additionalProperties:s.input_schema.additionalProperties,$schema:s.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function fy(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json(),s;n.tool_use&&n.tool_use.length>0&&(s=n.tool_use.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input)}})));let i={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...s&&{tool_calls:s}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.usage.output_tokens}};return new Response(JSON.stringify(i),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=(c,l)=>{if(c.startsWith("data: ")){let h=c.slice(6).trim();if(h){r?.debug({chunkStr:h},`${e} chunk:`);try{let f=JSON.parse(h);if(f.type==="content_block_delta"&&f.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:f.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
245
245
 
246
246
  `))}else if(f.type==="content_block_delta"&&f.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:f.index||0,function:{arguments:f.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
247
247
 
@@ -253,98 +253,98 @@ ${r}
253
253
 
254
254
  `));else{let p={choices:[{delta:{role:"assistant",content:f.content?.[0]?.text||""},finish_reason:f.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
255
255
 
256
- `))}}catch(f){r?.error(`Error parsing ${e} stream chunk`,h,f.message)}}}},u=new ReadableStream({async start(c){let l=t.body.getReader(),h="";try{for(;;){let{done:f,value:p}=await l.read();if(f){h&&i(h,c);break}h+=n.decode(p,{stream:!0});let S=h.split(`
257
- `);h=S.pop()||"";for(let D of S)i(D,c)}}catch(f){c.error(f)}finally{c.close()}}});return new Response(u,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function MS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Pr(Gl(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
256
+ `))}}catch(f){r?.error(`Error parsing ${e} stream chunk`,h,f.message)}}}},u=new ReadableStream({async start(c){let l=t.body.getReader(),h="";try{for(;;){let{done:f,value:p}=await l.read();if(f){h&&i(h,c);break}h+=n.decode(p,{stream:!0});let A=h.split(`
257
+ `);h=A.pop()||"";for(let v of A)i(v,c)}}catch(f){c.error(f)}finally{c.close()}}});return new Response(u,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function US(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Pr(Gl(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
258
258
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
259
259
  2. Run "gcloud auth application-default login"
260
- 3. Use Google Cloud environment with default service account`)}}var Ea=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(n=l.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await MS();return{body:ly(e),config:{url:new URL(`/v1/projects/${n}/locations/${s}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${s}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return dy(e)}async transformResponseOut(e){return fy(e,this.name,this.logger)}};var Aa=class{name="cerebras";async transformRequestIn(e,r){let n=JSON.parse(JSON.stringify(e));return n.reasoning?delete n.reasoning:n.disable_reasoning=!1,{body:n,config:{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Sa=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var ka=class{name="OpenAI";endPoint="/v1/chat/completions"};var Ta=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[s,i]of n)if(s in r)if(typeof r[s]=="object"&&typeof i=="object"&&!Array.isArray(r[s])&&!Array.isArray(i)&&r[s]!==null&&i!==null)r[s]=this.deepMergeObjects(r[s],i);else continue;else r[s]=this.cloneValue(i);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[s,i]of Object.entries(r))s in n&&typeof n[s]=="object"&&typeof i=="object"&&!Array.isArray(n[s])&&!Array.isArray(i)&&n[s]!==null&&i!==null?n[s]=this.deepMergeObjects(n[s],i):n[s]=this.cloneValue(i);return n}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.cloneValue(n));let r={};for(let[n,s]of Object.entries(e))r[n]=this.cloneValue(s);return r}};var Da=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c=!1,l="",h=new ReadableStream({async start(f){let p=e.body.getReader(),S=(E,y,g)=>{let m=E.split(`
261
- `);for(let T of m)T.trim()&&y.enqueue(g.encode(T+`
262
- `))},D=(E,y)=>{let{controller:g,encoder:m}=y;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]"){let T=E.slice(6);try{let b=JSON.parse(T);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
260
+ 3. Use Google Cloud environment with default service account`)}}var Ea=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(n=l.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await US();return{body:ly(e),config:{url:new URL(`/v1/projects/${n}/locations/${s}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${s}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return dy(e)}async transformResponseOut(e){return fy(e,this.name,this.logger)}};var Aa=class{name="cerebras";async transformRequestIn(e,r){let n=JSON.parse(JSON.stringify(e));return n.reasoning?delete n.reasoning:n.disable_reasoning=!1,{body:n,config:{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Sa=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var ka=class{name="OpenAI";endPoint="/v1/chat/completions"};var Ta=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[s,i]of n)if(s in r)if(typeof r[s]=="object"&&typeof i=="object"&&!Array.isArray(r[s])&&!Array.isArray(i)&&r[s]!==null&&i!==null)r[s]=this.deepMergeObjects(r[s],i);else continue;else r[s]=this.cloneValue(i);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[s,i]of Object.entries(r))s in n&&typeof n[s]=="object"&&typeof i=="object"&&!Array.isArray(n[s])&&!Array.isArray(i)&&n[s]!==null&&i!==null?n[s]=this.deepMergeObjects(n[s],i):n[s]=this.cloneValue(i);return n}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.cloneValue(n));let r={};for(let[n,s]of Object.entries(e))r[n]=this.cloneValue(s);return r}};var Da=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c=!1,l="",h=new ReadableStream({async start(f){let p=e.body.getReader(),A=(S,y,g)=>{let m=S.split(`
261
+ `);for(let k of m)k.trim()&&y.enqueue(g.encode(k+`
262
+ `))},v=(S,y)=>{let{controller:g,encoder:m}=y;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let k=S.slice(6);try{let b=JSON.parse(k);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
263
263
 
264
- `)),b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let O={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};O.choices?.[0]?.delta&&delete O.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(O)}
264
+ `)),b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(R)}
265
265
 
266
- `;g.enqueue(m.encode(x));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let O=Date.now().toString(),x={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:O}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(x)}
266
+ `;g.enqueue(m.encode(x));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let R=Date.now().toString(),x={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:R}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(x)}
267
267
 
268
- `;g.enqueue(m.encode($))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(O=>{O.id=`call_${Gt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let w=`data: ${JSON.stringify(b)}
268
+ `;g.enqueue(m.encode($))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${Gt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let E=`data: ${JSON.stringify(b)}
269
269
 
270
- `;g.enqueue(m.encode(w))}catch{g.enqueue(m.encode(E+`
271
- `))}}else g.enqueue(m.encode(E+`
272
- `))};try{for(;;){let{done:E,value:y}=await p.read();if(E){l.trim()&&S(l,f,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(T){console.warn("Failed to decode chunk",T);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let T=l.split(`
273
- `);l=T.pop()||"";for(let b of T)if(b.trim())try{D(b,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:w=>s=w,reasoningContent:()=>i,appendReasoningContent:w=>i+=w,isReasoningComplete:()=>u,setReasoningComplete:w=>u=w})}catch(w){console.error("Error processing line:",b,w),f.enqueue(n.encode(b+`
270
+ `;g.enqueue(m.encode(E))}catch{g.enqueue(m.encode(S+`
271
+ `))}}else g.enqueue(m.encode(S+`
272
+ `))};try{for(;;){let{done:S,value:y}=await p.read();if(S){l.trim()&&A(l,f,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
273
+ `);l=k.pop()||"";for(let b of k)if(b.trim())try{v(b,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:E=>s=E,reasoningContent:()=>i,appendReasoningContent:E=>i+=E,isReasoningComplete:()=>u,setReasoningComplete:E=>u=E})}catch(E){console.error("Error processing line:",b,E),f.enqueue(n.encode(b+`
274
274
  `))}continue}let m=l.split(`
275
- `);l=m.pop()||"";for(let T of m)if(T.trim())try{D(T,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",T,b),f.enqueue(n.encode(T+`
276
- `))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{p.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var va=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let r=[],n=e.messages.filter(s=>s.role==="system");if(n.length>0){let s=n[0];Array.isArray(s.content)?s.content.forEach(i=>{let u="";typeof i=="string"?u=i:i&&typeof i=="object"&&"text"in i&&(u=i.text),r.push({role:"system",content:u})}):e.instructions=s.content}if(e.messages.forEach(s=>{if(s.role!=="system"){if(Array.isArray(s.content)){let i=s.content.map(u=>this.normalizeRequestContent(u,s.role)).filter(u=>u!==null);i.length>0?s.content=i:delete s.content}if(s.role==="tool"){let i={...s};i.type="function_call_output",i.call_id=s.tool_call_id,i.output=s.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,r.push(i);return}if(s.role==="assistant"&&Array.isArray(s.tool_calls)){s.tool_calls.forEach(i=>{r.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}r.push(s)}}),e.input=r,delete e.messages,Array.isArray(e.tools)){let s=e.tools.find(i=>i.function.name==="web_search");e.tools=e.tools.filter(i=>i.function.name!=="web_search").map(i=>(i.function.name==="WebSearch"&&delete i.function.parameters.properties.allowed_domains,i.function.name==="Edit"?{type:i.type,name:i.function.name,description:i.function.description,parameters:{...i.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:i.type,name:i.function.name,description:i.function.description,parameters:i.function.parameters})),s&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let r=e.headers.get("Content-Type")||"";if(r.includes("application/json")){let n=await e.json();if(n.object==="response"&&n.output){let s=this.convertResponseToChat(n);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(r.includes("text/event-stream")){if(!e.body)return e;let n=new TextDecoder,s=new TextEncoder,i="",u=!1,c=this,l=new ReadableStream({async start(h){let f=e.body.getReader(),p=-1,S="",D=E=>(E!==S&&(p++,S=E),p);try{for(;;){let{done:E,value:y}=await f.read();if(E){u||h.enqueue(s.encode(`data: [DONE]
275
+ `);l=m.pop()||"";for(let k of m)if(k.trim())try{v(k,{controller:f,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",k,b),f.enqueue(n.encode(k+`
276
+ `))}}}catch(S){console.error("Stream error:",S),f.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}f.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var va=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let r=[],n=e.messages.filter(s=>s.role==="system");if(n.length>0){let s=n[0];Array.isArray(s.content)?s.content.forEach(i=>{let u="";typeof i=="string"?u=i:i&&typeof i=="object"&&"text"in i&&(u=i.text),r.push({role:"system",content:u})}):e.instructions=s.content}if(e.messages.forEach(s=>{if(s.role!=="system"){if(Array.isArray(s.content)){let i=s.content.map(u=>this.normalizeRequestContent(u,s.role)).filter(u=>u!==null);i.length>0?s.content=i:delete s.content}if(s.role==="tool"){let i={...s};i.type="function_call_output",i.call_id=s.tool_call_id,i.output=s.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,r.push(i);return}if(s.role==="assistant"&&Array.isArray(s.tool_calls)){s.tool_calls.forEach(i=>{r.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}r.push(s)}}),e.input=r,delete e.messages,Array.isArray(e.tools)){let s=e.tools.find(i=>i.function.name==="web_search");e.tools=e.tools.filter(i=>i.function.name!=="web_search").map(i=>(i.function.name==="WebSearch"&&delete i.function.parameters.properties.allowed_domains,i.function.name==="Edit"?{type:i.type,name:i.function.name,description:i.function.description,parameters:{...i.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:i.type,name:i.function.name,description:i.function.description,parameters:i.function.parameters})),s&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let r=e.headers.get("Content-Type")||"";if(r.includes("application/json")){let n=await e.json();if(n.object==="response"&&n.output){let s=this.convertResponseToChat(n);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(r.includes("text/event-stream")){if(!e.body)return e;let n=new TextDecoder,s=new TextEncoder,i="",u=!1,c=this,l=new ReadableStream({async start(h){let f=e.body.getReader(),p=-1,A="",v=S=>(S!==A&&(p++,A=S),p);try{for(;;){let{done:S,value:y}=await f.read();if(S){u||h.enqueue(s.encode(`data: [DONE]
277
277
 
278
- `));break}let g=n.decode(y,{stream:!0});i+=g;let m=i.split(/\r?\n/);i=m.pop()||"";for(let T of m)if(T.trim())try{if(T.startsWith("event: "))continue;if(T.startsWith("data: ")){let b=T.slice(5).trim();if(b==="[DONE]"){u=!0,h.enqueue(s.encode(`data: [DONE]
278
+ `));break}let g=n.decode(y,{stream:!0});i+=g;let m=i.split(/\r?\n/);i=m.pop()||"";for(let k of m)if(k.trim())try{if(k.startsWith("event: "))continue;if(k.startsWith("data: ")){let b=k.slice(5).trim();if(b==="[DONE]"){u=!0,h.enqueue(s.encode(`data: [DONE]
279
279
 
280
- `));continue}try{let w=JSON.parse(b);if(w.type==="response.output_text.delta"){let O={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:D(w.type),delta:{content:w.delta||""},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(O)}
280
+ `));continue}try{let E=JSON.parse(b);if(E.type==="response.output_text.delta"){let R={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:v(E.type),delta:{content:E.delta||""},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
281
281
 
282
- `))}else if(w.type==="response.output_item.added"&&w.item?.type==="function_call"){let O={id:w.item.call_id||w.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex-",choices:[{index:D(w.type),delta:{role:"assistant",tool_calls:[{index:0,id:w.item.call_id||w.item.id,function:{name:w.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(O)}
282
+ `))}else if(E.type==="response.output_item.added"&&E.item?.type==="function_call"){let R={id:E.item.call_id||E.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex-",choices:[{index:v(E.type),delta:{role:"assistant",tool_calls:[{index:0,id:E.item.call_id||E.item.id,function:{name:E.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
283
283
 
284
- `))}else if(w.type==="response.output_item.added"&&w.item?.type==="message"){let O=[];(w.item.content||[]).forEach($=>{$.type==="output_text"&&O.push({type:"text",text:$.text||""})});let x={role:"assistant"};if(O.length===1&&O[0].type==="text"?x.content=O[0].text:O.length>0&&(x.content=O),x.content){let $={id:w.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:D(w.type),delta:x,finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify($)}
284
+ `))}else if(E.type==="response.output_item.added"&&E.item?.type==="message"){let R=[];(E.item.content||[]).forEach($=>{$.type==="output_text"&&R.push({type:"text",text:$.text||""})});let x={role:"assistant"};if(R.length===1&&R[0].type==="text"?x.content=R[0].text:R.length>0&&(x.content=R),x.content){let $={id:E.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:v(E.type),delta:x,finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify($)}
285
285
 
286
- `))}}else if(w.type==="response.output_text.annotation.added"){let O={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex",choices:[{index:D(w.type),delta:{annotations:[{type:"url_citation",url_citation:{url:w.annotation?.url||"",title:w.annotation?.title||"",content:"",start_index:w.annotation?.start_index||0,end_index:w.annotation?.end_index||0}}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(O)}
286
+ `))}}else if(E.type==="response.output_text.annotation.added"){let R={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex",choices:[{index:v(E.type),delta:{annotations:[{type:"url_citation",url_citation:{url:E.annotation?.url||"",title:E.annotation?.title||"",content:"",start_index:E.annotation?.start_index||0,end_index:E.annotation?.end_index||0}}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
287
287
 
288
- `))}else if(w.type==="response.function_call_arguments.delta"){let O={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex-",choices:[{index:D(w.type),delta:{tool_calls:[{index:0,function:{arguments:w.delta||""}}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(O)}
288
+ `))}else if(E.type==="response.function_call_arguments.delta"){let R={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex-",choices:[{index:v(E.type),delta:{tool_calls:[{index:0,function:{arguments:E.delta||""}}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
289
289
 
290
- `))}else if(w.type==="response.completed"){let O=w.response?.output?.some($=>$.type==="function_call")?"tool_calls":"stop",x={id:w.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:O}]};h.enqueue(s.encode(`data: ${JSON.stringify(x)}
290
+ `))}else if(E.type==="response.completed"){let R=E.response?.output?.some($=>$.type==="function_call")?"tool_calls":"stop",x={id:E.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:R}]};h.enqueue(s.encode(`data: ${JSON.stringify(x)}
291
291
 
292
- `)),u=!0}else if(w.type==="response.reasoning_summary_text.delta"){let O={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:D(w.type),delta:{thinking:{content:w.delta||""}},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(O)}
292
+ `)),u=!0}else if(E.type==="response.reasoning_summary_text.delta"){let R={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:v(E.type),delta:{thinking:{content:E.delta||""}},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
293
293
 
294
- `))}else if(w.type==="response.reasoning_summary_part.done"&&w.part){let O={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:p,delta:{thinking:{signature:w.item_id}},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(O)}
294
+ `))}else if(E.type==="response.reasoning_summary_part.done"&&E.part){let R={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:p,delta:{thinking:{signature:E.item_id}},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
295
295
 
296
- `))}}catch{h.enqueue(s.encode(T+`
297
- `))}}else h.enqueue(s.encode(T+`
298
- `))}catch(b){console.error("Error processing line:",T,b),h.enqueue(s.encode(T+`
296
+ `))}}catch{h.enqueue(s.encode(k+`
297
+ `))}}else h.enqueue(s.encode(k+`
298
+ `))}catch(b){console.error("Error processing line:",k,b),h.enqueue(s.encode(k+`
299
299
  `))}}i.trim()&&h.enqueue(s.encode(i+`
300
300
  `)),u||h.enqueue(s.encode(`data: [DONE]
301
301
 
302
- `))}catch(E){console.error("Stream error:",E),h.error(E)}finally{try{f.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,r){let n={...e};if(delete n.cache_control,e.type==="text")return{type:r==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let s={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(s.image_url=e.image_url.url),s}return null}convertResponseToChat(e){let r=e.output?.find(h=>h.type==="message"),n=e.output?.find(h=>h.type==="function_call"),s;r?.content?.length&&r?.content[0].annotations&&(s=r.content[0].annotations.map(h=>({type:"url_citation",url_citation:{url:h.url||"",title:h.title||"",content:"",start_index:h.start_index||0,end_index:h.end_index||0}}))),this.logger.debug({data:s,type:"url_citation"});let i=null,u=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let h=[],f=[];if(r.content.forEach(p=>{if(p.type==="output_text")h.push(p.text||"");else if(p.type==="output_image"){let S=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});S&&f.push(S)}else if(p.type==="output_image_base64"){let S=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});S&&f.push(S)}}),f.length>0){let p=[];h.length>0&&p.push({type:"text",text:h.join("")}),p.push(...f),i=p}else i=h.join("")}return n&&(u=[{id:n.call_id||n.id,function:{name:n.name,arguments:n.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:u,thinking:c,annotations:s},logprobs:null,finish_reason:u?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var sd=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
302
+ `))}catch(S){console.error("Stream error:",S),h.error(S)}finally{try{f.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,r){let n={...e};if(delete n.cache_control,e.type==="text")return{type:r==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let s={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(s.image_url=e.image_url.url),s}return null}convertResponseToChat(e){let r=e.output?.find(h=>h.type==="message"),n=e.output?.find(h=>h.type==="function_call"),s;r?.content?.length&&r?.content[0].annotations&&(s=r.content[0].annotations.map(h=>({type:"url_citation",url_citation:{url:h.url||"",title:h.title||"",content:"",start_index:h.start_index||0,end_index:h.end_index||0}}))),this.logger.debug({data:s,type:"url_citation"});let i=null,u=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let h=[],f=[];if(r.content.forEach(p=>{if(p.type==="output_text")h.push(p.text||"");else if(p.type==="output_image"){let A=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});A&&f.push(A)}else if(p.type==="output_image_base64"){let A=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});A&&f.push(A)}}),f.length>0){let p=[];h.length>0&&p.push({type:"text",text:h.join("")}),p.push(...f),i=p}else i=h.join("")}return n&&(u=[{id:n.call_id||n.id,function:{name:n.name,arguments:n.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:u,thinking:c,annotations:s},logprobs:null,finish_reason:u?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var sd=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
303
303
 
304
304
  Output format:
305
305
  <reasoning_content>
306
306
  Your detailed thinking process goes here
307
307
  </reasoning_content>
308
- Your final answer must follow after the closing tag above.`,US=10,Ra=class{name="forcereasoning";async transformRequestIn(e){let r=0;e.messages.filter(s=>s.role==="assistant").reverse().forEach(s=>{s.thinking&&(s.thinking.content&&(!s.content||r<US)&&(r++,s.content=`<reasoning_content>${s.thinking.content}</reasoning_content>
309
- ${s.content}`),delete s.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:sd}):n.content=[{type:"text",text:sd},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:sd}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let s=await e.json();if(s.choices[0]?.message.content){let i=/<reasoning_content>(.*?)<\/reasoning_content>/s,u=s.choices[0]?.message.content.match(i);u&&u[1]&&(s.thinking={content:u[1]})}return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let s=0,i=new TextDecoder,u=new TextEncoder,c=new ReadableStream({async start(l){let h=e.body.getReader(),f="",p="SEARCHING",S="",D="",E=(y,g)=>{if(typeof g!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=s,l.enqueue(u.encode(`data: ${JSON.stringify(y)}
308
+ Your final answer must follow after the closing tag above.`,qS=10,Ra=class{name="forcereasoning";async transformRequestIn(e){let r=0;e.messages.filter(s=>s.role==="assistant").reverse().forEach(s=>{s.thinking&&(s.thinking.content&&(!s.content||r<qS)&&(r++,s.content=`<reasoning_content>${s.thinking.content}</reasoning_content>
309
+ ${s.content}`),delete s.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:sd}):n.content=[{type:"text",text:sd},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:sd}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let s=await e.json();if(s.choices[0]?.message.content){let i=/<reasoning_content>(.*?)<\/reasoning_content>/s,u=s.choices[0]?.message.content.match(i);u&&u[1]&&(s.thinking={content:u[1]})}return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let s=0,i=new TextDecoder,u=new TextEncoder,c=new ReadableStream({async start(l){let h=e.body.getReader(),f="",p="SEARCHING",A="",v="",S=(y,g)=>{if(typeof g!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=s,l.enqueue(u.encode(`data: ${JSON.stringify(y)}
310
310
 
311
- `)));return}let m=S+g;for(S="";m.length>0;)if(p==="SEARCHING"){let T=m.indexOf(r);if(T!==-1)m=m.substring(T+r.length),p="REASONING";else{for(let b=r.length-1;b>0;b--)if(m.endsWith(r.substring(0,b))){S=m.substring(m.length-b);break}m=""}}else if(p==="REASONING"){let T=m.indexOf(n);if(T!==-1){let b=m.substring(0,T);if(b.length>0){let x={...y.choices[0].delta,thinking:{content:b}};delete x.content;let $={...y,choices:[{...y.choices[0],delta:x,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify($)}
311
+ `)));return}let m=A+g;for(A="";m.length>0;)if(p==="SEARCHING"){let k=m.indexOf(r);if(k!==-1)m=m.substring(k+r.length),p="REASONING";else{for(let b=r.length-1;b>0;b--)if(m.endsWith(r.substring(0,b))){A=m.substring(m.length-b);break}m=""}}else if(p==="REASONING"){let k=m.indexOf(n);if(k!==-1){let b=m.substring(0,k);if(b.length>0){let x={...y.choices[0].delta,thinking:{content:b}};delete x.content;let $={...y,choices:[{...y.choices[0],delta:x,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify($)}
312
312
 
313
- `))}let w={...y.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete w.content;let O={...y,choices:[{...y.choices[0],delta:w,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify(O)}
313
+ `))}let E={...y.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete E.content;let R={...y,choices:[{...y.choices[0],delta:E,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify(R)}
314
314
 
315
- `)),s++,m=m.substring(T+n.length),p="FINAL"}else{let b=m;for(let w=n.length-1;w>0;w--)if(m.endsWith(n.substring(0,w))){S=m.substring(m.length-w),b=m.substring(0,m.length-w);break}if(b.length>0){let w={...y.choices[0].delta,thinking:{content:b}};delete w.content;let O={...y,choices:[{...y.choices[0],delta:w,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify(O)}
315
+ `)),s++,m=m.substring(k+n.length),p="FINAL"}else{let b=m;for(let E=n.length-1;E>0;E--)if(m.endsWith(n.substring(0,E))){A=m.substring(m.length-E),b=m.substring(0,m.length-E);break}if(b.length>0){let E={...y.choices[0].delta,thinking:{content:b}};delete E.content;let R={...y,choices:[{...y.choices[0],delta:E,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify(R)}
316
316
 
317
- `))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))D+=m;else{let b=D+m,w={...y.choices[0].delta,content:b};w.thinking&&delete w.thinking;let O={...y,choices:[{...y.choices[0],delta:w}]};l.enqueue(u.encode(`data: ${JSON.stringify(O)}
317
+ `))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))v+=m;else{let b=v+m,E={...y.choices[0].delta,content:b};E.thinking&&delete E.thinking;let R={...y,choices:[{...y.choices[0],delta:E}]};l.enqueue(u.encode(`data: ${JSON.stringify(R)}
318
318
 
319
- `)),D=""}s++,m=""}};try{for(;;){let{done:y,value:g}=await h.read();if(y)break;let m=i.decode(g,{stream:!0});f+=m;let T=f.split(`
320
- `);f=T.pop()||"";for(let b of T)if(b.trim()){if(b.trim()==="data: [DONE]"){l.enqueue(u.encode(b+`
319
+ `)),v=""}s++,m=""}};try{for(;;){let{done:y,value:g}=await h.read();if(y)break;let m=i.decode(g,{stream:!0});f+=m;let k=f.split(`
320
+ `);f=k.pop()||"";for(let b of k)if(b.trim()){if(b.trim()==="data: [DONE]"){l.enqueue(u.encode(b+`
321
321
 
322
- `));break}if(b.startsWith("data:"))try{let w=JSON.parse(b.slice(5));E(w,w.choices?.[0]?.delta?.content)}catch{l.enqueue(u.encode(b+`
322
+ `));break}if(b.startsWith("data:"))try{let E=JSON.parse(b.slice(5));S(E,E.choices?.[0]?.delta?.content)}catch{l.enqueue(u.encode(b+`
323
323
  `))}else l.enqueue(u.encode(b+`
324
324
  `))}}}catch(y){console.error("Stream error:",y),l.error(y)}finally{try{h.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}if(p==="REASONING"){let g={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(u.encode(`data: ${JSON.stringify(g)}
325
325
 
326
326
  `))}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Oa=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(n=>n.thinking?.content))&&e.messages.forEach(n=>{if(n.role==="assistant"){let s=n.thinking?.content,i=n.thinking?.signature;s&&typeof s=="string"&&s.trim()&&(n.reasoning_content=s,i&&(n.reasoning_content_signature=i)),n.tool_calls&&n.tool_calls.length>0&&(n.reasoning_content||(n.reasoning_content="")),n.thinking&&delete n.thinking}}),e}async transformResponseOut(e){let r=e.headers.get("Content-Type");if(r?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,s=new TextEncoder,i="",u="",c=new ReadableStream({async start(l){let h=e.body.getReader();try{for(;;){let{done:f,value:p}=await h.read();if(f){u.trim()&&l.enqueue(s.encode(u+`
327
- `));break}let S=n.decode(p,{stream:!0});u+=S;let D=u.split(`
328
- `);u=D.pop()||"";for(let E of D)if(E.trim())if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let y=JSON.parse(E.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){i+=y.choices[0].delta.reasoning_content;let g={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(s.encode(`data: ${JSON.stringify(g)}
327
+ `));break}let A=n.decode(p,{stream:!0});u+=A;let v=u.split(`
328
+ `);u=v.pop()||"";for(let S of v)if(S.trim())if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]")try{let y=JSON.parse(S.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){i+=y.choices[0].delta.reasoning_content;let g={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(s.encode(`data: ${JSON.stringify(g)}
329
329
 
330
330
  `));continue}if(y.choices?.[0]?.delta?.content&&i&&!y.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),m={...y,choices:[{...y.choices[0],delta:{content:null,thinking:{content:i,signature:g}}}]};l.enqueue(s.encode(`data: ${JSON.stringify(m)}
331
331
 
332
332
  `)),i=""}y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&l.enqueue(s.encode(`data: ${JSON.stringify(y)}
333
333
 
334
- `))}catch{l.enqueue(s.encode(E+`
335
- `))}else l.enqueue(s.encode(E+`
334
+ `))}catch{l.enqueue(s.encode(S+`
335
+ `))}else l.enqueue(s.encode(S+`
336
336
  `))}}catch(f){l.error(f)}finally{try{h.releaseLock()}catch{}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":r||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(r?.includes("application/json")){let n=await e.json();return n.choices?.[0]?.message?.reasoning_content&&(n.choices[0].message.thinking={content:n.choices[0].message.reasoning_content},delete n.choices[0].message.reasoning_content),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var hy={AnthropicTransformer:qo,GeminiTransformer:Wo,VertexGeminiTransformer:la,VertexClaudeTransformer:Ea,DeepseekTransformer:da,TooluseTransformer:fa,OpenrouterTransformer:ha,OpenAITransformer:ka,MaxTokenTransformer:pa,GroqTransformer:ma,CleancacheTransformer:ga,EnhanceToolTransformer:_a,ReasoningTransformer:ba,SamplingTransformer:Ca,MaxCompletionTokens:wa,CerebrasTransformer:Aa,StreamOptionsTransformer:Sa,CustomParamsTransformer:Ta,VercelTransformer:Da,OpenAIResponsesTransformer:va,ForceReasoningTransformer:Ra,KimiTransformer:Oa};var is=class{constructor(e,r){this.configService=e;this.logger=r}transformers=new Map;registerTransformer(e,r){this.transformers.set(e,r),this.logger.info(`register transformer: ${e}${r.endPoint?` (endpoint: ${r.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((r,n)=>{typeof r=="object"&&r.endPoint&&e.push({name:n,transformer:r})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((r,n)=>{typeof r=="object"&&!r.endPoint&&e.push({name:n,transformer:r})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let r=Q(Q.resolve(e.path));if(r){let n=new r(e.options);if(n&&typeof n=="object"&&(n.logger=this.logger),!n.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(n.name,n),!0}}return!1}catch(r){return this.logger.error(`load transformer (${e.path})
337
337
  error: ${r.message}
338
338
  stack: ${r.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
339
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(hy).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let r=new e;r&&typeof r=="object"&&(r.logger=this.logger),this.registerTransformer(r.name,r)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let r of e)await this.registerTransformerFromConfig(r)}};import{get_encoding as qS}from"tiktoken";var Xs=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=qS(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");let n=0,{messages:s,system:i,tools:u}=e;return Array.isArray(s)&&s.forEach(c=>{typeof c.content=="string"?n+=r.encode(c.content).length:Array.isArray(c.content)&&c.content.forEach(l=>{if(l.type==="text")n+=r.encode(l.text).length;else if(l.type==="tool_use")n+=r.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let h=typeof l.content=="string"?l.content:JSON.stringify(l.content);n+=r.encode(h).length}})}),typeof i=="string"?n+=r.encode(i).length:Array.isArray(i)&&i.forEach(c=>{c.type==="text"&&(typeof c.text=="string"?n+=r.encode(c.text).length:Array.isArray(c.text)&&c.text.forEach(l=>{n+=r.encode(l||"").length}))}),u&&u.forEach(c=>{c.description&&(n+=r.encode(c.name+c.description).length),c.input_schema&&(n+=r.encode(JSON.stringify(c.input_schema)).length)}),n}isInitialized(){return this.encoding!==void 0}encodeText(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");return Array.from(r.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Ia}from"path";import{homedir as XT}from"os";import{existsSync as ud,mkdirSync as QT}from"fs";import{promises as Na}from"fs";var $S=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let n=e;for(let s=0;s<r.length;++s){let i=r[s];n=n[i]??=Object.create(null)}n.end=r}return e}split(t){let e=[],r=t.length,n=0,s=0;for(;s<r;){let i=this.trie,u=null,c=s;for(;c<r&&(i=i[t[c]]);)i.end&&(u=i.end),++c;u?(s>n&&e.push(t.slice(n,s)),e.push(u),s+=u.length,n=s):++s}return n<r&&e.push(t.slice(n)),e}},zS=$S,HS=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??null}},WS=HS,Cy=(()=>{let t=[...Array.from({length:94},(s,i)=>i+33),...Array.from({length:12},(s,i)=>i+161),...Array.from({length:82},(s,i)=>i+174)],e=t.slice(),r=0;for(let s=0;s<256;++s)t.includes(s)||(t.push(s),e.push(256+r),r+=1);let n=e.map(s=>String.fromCharCode(s));return Object.fromEntries(t.map((s,i)=>[s,n[i]]))})(),GS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),JS=GS(Cy),py=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",VS=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${py}])]+`,` ?[^\\s${py}]+`]]),Qs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",rF=new RegExp(`^[${Qs}]+$`,"gu"),id=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),Fa=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,s]of VS)r=r.replaceAll(n,s);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=KS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},KS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),YS=(t,e,r)=>{let n=[],s=0;for(;s<t.length;){if(n.push(t[s]),(e.get(t[s])??r)!==r){++s;continue}for(;++s<t.length&&(e.get(t[s])??r)===r;)e.get(n.at(-1))!==r&&(n[n.length-1]+=t[s])}return n},XS=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,QS=t=>Number.isInteger(t)||typeof t=="bigint",ZS=t=>{let e=0;for(let r of t)++e;return e},ek=t=>wy(t.toLowerCase()),Ot=(...t)=>Array.prototype.concat.apply([],t),ad=t=>new Map(Object.entries(t)),tk=(t,e)=>{let r=[],n=0;for(let s of t.matchAll(e)){let i=s[0];n<s.index&&r.push(t.slice(n,s.index)),i.length>0&&r.push(i),n=s.index+i.length}return n<t.length&&r.push(t.slice(n)),r},wy=t=>t.replace(new RegExp("\\p{M}","gu"),""),my=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let n of r)if(!(n in t))return`${e} must contain a "${n}" property`;return null},rk=t=>t.match(/\S+/g)||[],nk=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Zs=nk,sk=class extends Zs{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Er=sk,ok=class extends Er{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],s=n.charCodeAt(0);XS(s)?(e.push(" "),e.push(n),e.push(" ")):e.push(n)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
340
- `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let r of t){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},ik=ok,ak=class extends Er{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},uk=ak,ck=class extends Er{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Ey(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},lk=ck,dk=class extends Er{normalize(t){let e=Fa(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},fk=dk,hk=class extends Er{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},xa=hk,pk=class extends xa{constructor(){super(...arguments),this.form="NFC"}},mk=pk,gk=class extends xa{constructor(){super(...arguments),this.form="NFD"}},yk=gk,_k=class extends xa{constructor(){super(...arguments),this.form="NFKC"}},bk=_k,Ck=class extends xa{constructor(){super(...arguments),this.form="NFKD"}},wk=Ck,Ek=class extends Er{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},Ak=Ek,Sk=class extends Er{normalize(t){return wy(t)}},kk=Sk,Tk=class extends Er{normalize(t){return t.toLowerCase()}},Dk=Tk,vk=class extends Er{normalize(t){return t=this.config.prepend+t,t}},Rk=vk;function Ok(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new ik(t);case"Precompiled":return new uk(t);case"Sequence":return new lk(t);case"Replace":return new fk(t);case"NFC":return new mk(t);case"NFD":return new yk(t);case"NFKC":return new bk(t);case"NFKD":return new wk(t);case"Strip":return new Ak(t);case"StripAccents":return new kk(t);case"Lowercase":return new Dk(t);case"Prepend":return new Rk(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Ey=Ok,Fk=class extends Zs{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},sr=Fk,xk=class extends sr{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Cy,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},Pk=xk,Ik=class extends sr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Nk=Ik,Bk=class extends sr{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},n=t.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},jk=Bk,Lk=class extends sr{constructor(t){super(),this.config=t,this.pattern=Fa(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):tk(t,this.pattern)}},Mk=Lk,Uk=class extends sr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Qs}]+|[${Qs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},qk=Uk,$k=class extends sr{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},zk=$k,Hk=class extends sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${Qs}]+|[${Qs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Wk=Hk,Gk=class extends sr{constructor(t){super(),this.config=t,this.pattern=Fa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Jk=Gk,Vk=class extends sr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Ay(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Kk=Vk,Yk=class extends sr{pre_tokenize_text(t){return rk(t)}},Xk=Yk;function Qk(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Wk;case"Sequence":return new Kk(t);case"Whitespace":return new Nk;case"WhitespaceSplit":return new Xk;case"Metaspace":return new jk(t);case"ByteLevel":return new Pk(t);case"Split":return new Mk(t);case"Punctuation":return new qk(t);case"Digits":return new zk(t);case"Replace":return new Jk(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Ay=Qk,Zk=class extends Zs{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=YS(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},Pa=Zk,eT=class extends Pa{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=ad(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let n=[...r];if(n.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let s=!1,i=0,u=[];for(;i<n.length;){let c=n.length,l=null;for(;i<c;){let h=n.slice(i,c).join("");if(i>0&&(h=this.config.continuing_subword_prefix+h),this.tokens_to_ids.has(h)){l=h;break}--c}if(l===null){s=!0;break}u.push(l),i=c}s?e.push(this.unk_token):e.push(...u)}return e}},gy=eT,yy=class Sy{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new Sy(!1,new Map)}},tT=class{constructor(){this.root=yy.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let n=e.children.get(r);n===void 0&&(n=yy.default(),e.children.set(r,n)),e=n}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let n of t){if(r+=n,e=e.children.get(n),e===void 0)return;e.is_leaf&&(yield r)}}},rT=tT,od=class ky{constructor(e,r,n,s,i){this.token_id=e,this.node_id=r,this.pos=n,this.length=s,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let e=new ky(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},nT=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new od(this.bos_token_id??0,0,0,0,0),s=new od(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(t,e,r,n){let s=this.nodes.length,i=new od(n,s,t,e,r);this.begin_nodes[t].push(i),this.end_nodes[t+e].push(i),this.nodes.push(i)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let u=0,c=null;for(let l of this.end_nodes[e]){let h=l.backtrace_score+i.score;(c===null||h>u)&&(c=l.clone(),u=h)}if(c!==null)i.prev=c,i.backtrace_score=u;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let s=n.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},sT=nT;function oT(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let n=1;n<t.length;++n)t[n]<e&&(e=t[n],r=n);return[e,r]}var iT=class extends Pa{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=t.vocab[n];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=oT(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new rT,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,n=0;for(;n<e.length;){let s=!1,i=[],u=e.slice(n).join(""),c=this.trie.common_prefix_search(u);for(let l of c){i.push(l);let h=this.tokens_to_ids.get(l),f=this.scores[h],p=ZS(l);t.insert(n,p,f,h),!s&&p===r&&(s=!0)}s||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new sT(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let n=this.tokenize(r);e.push(...n)}return e}},_y=iT,aT=class{constructor(t=(r,n)=>r>n,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},uT=aT,cT=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},lT=cT,dT=class extends Pa{constructor(t){super(t),this.tokens_to_ids=ad(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new lT(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let s=new uT((c,l)=>c.score<l.score),i={token:r[0],bias:0,prev:null,next:null},u=i;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[c],prev:u,next:null};u.next=l,this.add_node(s,u),u=l}for(;!s.is_empty();){let c=s.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let h={...c.prev};c.prev.deleted=!0,c.prev=h,h.prev?h.prev.next=h:i=h}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):i=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let c=i;c!==null;c=c.next)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,n),n}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let n=this.bpe(r);for(let s of n)if(this.tokens_to_ids.has(s))e.push(s);else if(this.byte_fallback){let i=Array.from(this.text_encoder.encode(s)).map(u=>`<0x${u.toString(16).toUpperCase().padStart(2,"0")}>`);i.every(u=>this.tokens_to_ids.has(u))?e.push(...i):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},by=dT,fT=class extends Pa{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=ad(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(t){return t}},hT=fT;function pT(t,e){switch(t.type){case"WordPiece":return new gy(t);case"Unigram":return new _y(t,e.eos_token);case"BPE":return new by(t);default:if(t.vocab)return Array.isArray(t.vocab)?new _y(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new by(t):new gy(t):new hT(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var mT=pT,gT=class extends Zs{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},eo=gT,yT=class extends eo{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,s=[],i=[];for(let u of n)"SpecialToken"in u?r&&(s.push(u.SpecialToken.id),i.push(u.SpecialToken.type_id)):"Sequence"in u&&(u.Sequence.id==="A"?(s=Ot(s,t),i=Ot(i,new Array(t.length).fill(u.Sequence.type_id))):u.Sequence.id==="B"&&(s=Ot(s,e),i=Ot(i,new Array(e.length).fill(u.Sequence.type_id))));return{tokens:s,token_type_ids:i}}},_T=yT,bT=class extends eo{post_process(t,e=null){return{tokens:e?Ot(t,e):t}}},CT=bT,wT=class extends eo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Ot([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=[],i=r?[this.sep[0]]:[];t=Ot(t,s,e,i),n=Ot(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},ET=wT,AT=class extends eo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Ot([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=r?[this.sep[0]]:[],i=r?[this.sep[0]]:[];t=Ot(t,s,e,i),n=Ot(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},ST=AT,kT=class extends eo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Ty(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let s of this.processors)n=s.post_process(n.tokens,e,r);return n}},TT=kT;function DT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new _T(t);case"ByteLevel":return new CT(t);case"BertProcessing":return new ET(t);case"RobertaProcessing":return new ST(t);case"Sequence":return new TT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Ty=DT,vT=class extends Zs{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},or=vT,RT=class extends or{constructor(t){super(t),this.byte_decoder=JS,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let n of t)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(n)):r.push(n);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},OT=RT,FT=class extends or{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let n=this.config.prefix;n&&e.startsWith(n)?e=e.replace(n,""):e=" "+e}return this.cleanup&&(e=id(e)),e})}},xT=FT,PT=class extends or{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),e.push(n)}return e}},IT=PT,NT=class extends or{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},BT=NT,jT=class extends or{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let r=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=id(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},LT=jT,MT=class extends or{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Dy(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},UT=MT,qT=class extends or{decode_chain(t){let e=Fa(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},$T=qT,zT=class extends or{decode_chain(t){return[t.join("")]}},HT=zT,WT=class extends or{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let s=0;s<this.start&&e[s]===this.content;++s)r=s+1;let n=e.length;for(let s=0;s<this.stop;++s){let i=e.length-s-1;if(e[i]===this.content){n=i;continue}else break}return e.slice(r,n)})}},GT=WT,JT=class extends or{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let i=parseInt(n.slice(3,5),16);isNaN(i)||(s=i)}if(s!==null)r.push(s);else{if(r.length>0){let i=this.text_decoder.decode(Uint8Array.from(r));e.push(i),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},VT=JT;function KT(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new OT(t);case"WordPiece":return new xT(t);case"Metaspace":return new IT(t);case"BPEDecoder":return new BT(t);case"CTC":return new LT(t);case"Sequence":return new UT(t);case"Replace":return new $T(t);case"Fuse":return new HT(t);case"Strip":return new GT(t);case"ByteFallback":return new VT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Dy=KT,YT=class{constructor(t,e){let r=my(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=my(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=Ey(this.tokenizer.normalizer),this.pre_tokenizer=Ay(this.tokenizer.pre_tokenizer),this.model=mT(this.tokenizer.model,this.config),this.post_processor=Ty(this.tokenizer.post_processor),this.decoder=Dy(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(s=>{let i=new WS(s);this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id))}),(this.config.additional_special_tokens??[]).forEach(s=>{this.special_tokens.includes(s)||this.special_tokens.push(s)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new zS(this.added_tokens.map(s=>s.content)),this.added_tokens_map=new Map(this.added_tokens.map(s=>[s.content,s])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:s,token_type_ids:i}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),u=this.model.convert_tokens_to_ids(s),c={ids:u,tokens:s,attention_mask:new Array(u.length).fill(1)};return n&&i&&(c.token_type_ids=i),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!QS(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(n=n.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=id(n)),n}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((r,n)=>{let s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),s.rstrip&&n<e.length-1&&(e[n+1]=e[n+1].trimStart()))}),e.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=ek(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let s=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(s)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),s=this.encode_text(e||null);return this.post_processor?this.post_processor(n,s,r):{tokens:Ot(n??[],s??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},vy=YT;var Ba=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,r,n={}){this.modelId=e,this.logger=r,this.options=n,this.cacheDir=n.cacheDir||Ia(XT(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Ia(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Ia(e,"tokenizer.json"),tokenizerConfig:Ia(e,"tokenizer_config.json")}}ensureDir(e){ud(e)||QT(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!ud(e.tokenizerJson)||!ud(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Na.readFile(e.tokenizerJson,"utf-8"),Na.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(r),tokenizerConfig:JSON.parse(n)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),r={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let n=new AbortController,s=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[i,u]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.signal})]);if(!i.ok)throw new Error(`Failed to fetch tokenizer.json: ${i.statusText}`);let[c,l]=await Promise.all([i.json(),u.ok?u.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Na.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Na.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(s)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let r=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new vy(r.tokenizerJson,r.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let r=this.extractTextFromRequest(e);return this.tokenizer.encode(r).ids.length}catch(r){throw this.logger?.error(`Error counting tokens: ${r.message}`),r}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let r=[],{messages:n,system:s,tools:i}=e;if(Array.isArray(n)){for(let u of n)if(typeof u.content=="string")r.push(u.content);else if(Array.isArray(u.content))for(let c of u.content)c.type==="text"&&c.text?r.push(c.text):c.type==="tool_use"&&c.input?r.push(JSON.stringify(c.input)):c.type==="tool_result"&&r.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof s=="string")r.push(s);else if(Array.isArray(s)){for(let u of s)if(u.type==="text"){if(typeof u.text=="string")r.push(u.text);else if(Array.isArray(u.text))for(let c of u.text)c&&r.push(c)}}if(i)for(let u of i)u.name&&r.push(u.name),u.description&&r.push(u.description),u.input_schema&&r.push(JSON.stringify(u.input_schema));return r.join(" ")}};var ja=class{type="api";name;config;logger;options;constructor(e,r,n={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=r,this.options=n;try{let s=new URL(e.url);this.name=`api-${s.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let r=this.formatRequestBody(e),n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},s=new AbortController,i=setTimeout(()=>s.abort(),this.options.timeout||3e4),u=await fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(r),signal:s.signal});if(clearTimeout(i),!u.ok)throw new Error(`API tokenizer request failed: ${u.status} ${u.statusText}`);let c=await u.json();return this.extractTokenCount(c)}catch(r){throw r.name==="AbortError"?new Error("API tokenizer request timed out"):r}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(r=>({role:r.role,content:this.extractTextFromMessage(r)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(r=>r.type==="text"&&r.text?r.text:r.type==="tool_use"&&r.input?JSON.stringify(r.input):r.type==="tool_result"?typeof r.content=="string"?r.content:JSON.stringify(r.content):"").join(" "):""}extractConcatenatedText(e){let r=[];return e.messages&&e.messages.forEach(n=>{r.push(this.extractTextFromMessage(n))}),typeof e.system=="string"?r.push(e.system):Array.isArray(e.system)&&e.system.forEach(n=>{n.type==="text"&&(typeof n.text=="string"?r.push(n.text):Array.isArray(n.text)&&n.text.forEach(s=>{s&&r.push(s)}))}),e.tools&&e.tools.forEach(n=>{n.name&&r.push(n.name),n.description&&r.push(n.description),n.input_schema&&r.push(JSON.stringify(n.input_schema))}),r.join(" ")}extractTokenCount(e){try{let r=this.config.responseField,n=r.split("."),s=e;for(let i of n){if(s==null)throw new Error(`Field path '${r}' not found in response`);s=s[i]}if(typeof s!="number")throw new Error(`Expected number at field path '${r}', got ${typeof s}`);return s}catch(r){throw this.logger?.error(`Failed to extract token count from API response: ${r.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${r.message}`)}}};var as=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,r,n={}){this.configService=e,this.logger=r,this.options={timeout:n.timeout??3e4,...n}}async initialize(){try{this.fallbackTokenizer=new Xs("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let r=this.getCacheKey(e);if(this.tokenizers.has(r))return this.tokenizers.get(r);let n;try{switch(e.type){case"tiktoken":n=new Xs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ba(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new ja(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await n.initialize(),this.tokenizers.set(r,n),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${r})`),n}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,r){let n=r?await this.getTokenizer(r):this.fallbackTokenizer;return{tokenCount:await n.countTokens(e),tokenizerUsed:n.name,cached:!1}}getTokenizerConfigForModel(e,r){let s=(this.configService.get("providers")||[]).find(i=>i.name===e);if(s?.tokenizer)return s.tokenizer.models?.[r]?s.tokenizer.models[r]:s.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(r){this.logger?.error(`Error disposing tokenizer: ${r}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};import{get_encoding as ZT}from"tiktoken";var cd=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}values(){return Array.from(this.cache.values())}},ld=new cd(100);import{readFile as fd}from"fs/promises";import{opendir as eD,stat as tD}from"fs/promises";import{join as hd}from"path";import{CLAUDE_PROJECTS_DIR as Ry,HOME_DIR as Oy}from"@wengine-ai/claude-code-router-shared";var Ar=ZT("cl100k_base"),xy=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(s=>{typeof s.content=="string"?n+=Ar.encode(s.content).length:Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="text"?n+=Ar.encode(i.text).length:i.type==="tool_use"?n+=Ar.encode(JSON.stringify(i.input)).length:i.type==="tool_result"&&(n+=Ar.encode(typeof i.content=="string"?i.content:JSON.stringify(i.content)).length)})}),typeof e=="string"?n+=Ar.encode(e).length:Array.isArray(e)&&e.forEach(s=>{s.type==="text"&&(typeof s.text=="string"?n+=Ar.encode(s.text).length:Array.isArray(s.text)&&s.text.forEach(i=>{n+=Ar.encode(i||"").length}))}),r&&r.forEach(s=>{s.description&&(n+=Ar.encode(s.name+s.description).length),s.input_schema&&(n+=Ar.encode(JSON.stringify(s.input_schema)).length)}),n},Py=async(t,e)=>{if(t.sessionId){let r=await Ny(t.sessionId);if(r){let n=hd(Oy,r,"config.json"),s=hd(Oy,r,`${t.sessionId}.json`);try{let i=JSON.parse(await fd(s,"utf8"));if(i&&i.Router)return i.Router}catch{}try{let i=JSON.parse(await fd(n,"utf8"));if(i&&i.Router)return i.Router}catch{}}}};function La(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function Iy(t){let e=La(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),s=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(s)return{family:s[1].toLowerCase(),extended:r};let i=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return i?{family:i[1].toLowerCase(),extended:r}:{family:null,extended:r}}function rD(t,e){if(!e||!t)return null;let r=La(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=Iy(t);if(n&&e[n])return e[n];for(let[s,i]of Object.entries(e)){let u=La(s);if(u&&r.includes(u))return i}return null}function Gr(t,e,r){if(!t?.includes(","))return t;let[n,...s]=t.split(","),i=n.trim(),u=s.join(",").trim();if(!r&&!vn().isAvailable(i,u))return null;let c=e.find(h=>h.name.toLowerCase()===i.toLowerCase()),l=c?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return c&&l?`${c.name},${l}`:t}function nD(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function sD(t){let e=La(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(n=>n.test(e))}function oD(t,e,r,n,s,i){let u=r.longContextThreshold||6e4;if((i||e>2e5)&&r.extendedContext){let p=Gr(r.extendedContext,n);if(p)return t.log.info(`Family: using extended context model (1M+), tokens: ${e}, explicit: ${i}`),{model:p,scenarioType:"extendedContext"};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}let h=s&&s.input_tokens>u&&e>2e4,f=e>u;if((h||f)&&r.longContext){let p=Gr(r.longContext,n);if(p)return t.log.info(`Family: using long context model, tokens: ${e}`),{model:p,scenarioType:"longContext"};t.log.warn("Family: longContext model unavailable (fail pool), skipping")}if(Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.type?.startsWith("web_search"))&&r.webSearch){let p=Gr(r.webSearch,n);if(p)return{model:p,scenarioType:"webSearch"};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let p=Gr(r.think,n);if(p)return{model:p,scenarioType:"think"};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let p=Gr(r.default,n);if(p)return{model:p,scenarioType:"default"};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var iD=async(t,e,r,n)=>{let s=await Py(t,r),i=r.get("providers")||[],u=s||r.get("Router");if(t.body.model.includes(",")){let g=Gr(t.body.model,i);if(g)return{model:g,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying alternatives`)}let{family:c,extended:l}=Iy(t.body.model),h=u?.families?.[c||""];if(h){t.log.info(`Using model family routing for: ${c}${l?" (1M)":""}`),t.modelFamily=c,t.familyFallback=h.fallback;let g=oD(t,e,h,i,n,l);if(g)return g}let f=rD(t.body.model,u?.models);if(f){let g=Gr(f,i);if(g)return t.log.info(`Using mapped model for ${t.body.model}: ${f}`),{model:g,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${f} unavailable (fail pool), skipping`)}let p=u?.extendedContextThreshold||2e5;if(e>p&&u?.extendedContext)return t.log.info(`Using extended context (1M) model due to token count: ${e}, threshold: ${p}`),{model:u.extendedContext,scenarioType:"extendedContext"};let S=u?.longContextThreshold||6e4,D=n&&n.input_tokens>S&&e>2e4,E=e>S;if((D||E)&&u?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${S}`),{model:u.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let g=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(g)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${g[1]}</CCR-SUBAGENT-MODEL>`,""),{model:g[1],scenarioType:"default"}}let y=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&y?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:y.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(g=>g.type?.startsWith("web_search"))&&u?.webSearch?{model:u.webSearch,scenarioType:"webSearch"}:t.body.thinking&&u?.think?(t.log.info(`Using think model for ${t.body.thinking}`),{model:u.think,scenarioType:"think"}):{model:u?.default,scenarioType:"default"}},pd=async(t,e,r)=>{let{configService:n,event:s}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let D=t.body.metadata.user_id.split("_session_");D.length>1&&(t.sessionId=D[1])}let u=await Py(t,n)||n.get("Router"),c=n.get("providers")||[],l=ld.get(t.sessionId),{messages:h,system:f=[],tools:p}=t.body,S=n.get("REWRITE_SYSTEM_PROMPT");if(S&&f.length>1&&f[1]?.text?.includes("<env>")){let D=await fd(S,"utf-8");f[1].text=`${D}<env>${f[1].text.split("<env>").pop()}`}try{let[D,E]=t.body.model.split(","),y=r.tokenizerService?.getTokenizerConfigForModel(D,E),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:h,system:f,tools:p},y)).tokenCount:g=xy(h,f,p),t.tokenCount=g;let m,T=n.get("CUSTOM_ROUTER_PATH");if(T)try{m=await Q(T)(t,n.getAll(),{event:s})}catch(b){t.log.error(`failed to load custom router: ${b.message}`)}if(m)t.scenarioType="default";else{let b=await iD(t,g,n,l);m=b.model,t.scenarioType=b.scenarioType}if(u?.image&&m!==u.image&&nD(t)&&!sD(m)){let b=Gr(u.image,c);b?(t.log.info(`Using image model fallback for ${m}`),m=b,t.scenarioType="image"):t.log.warn(`Image model ${u.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(D){t.log.error(`Error in router middleware: ${D.message}`),t.body.model=u?.default,t.scenarioType="default"}},Sr=new Map,Fy=1e3;function dd(){if(Sr.size<=Fy)return;let t=[...Sr.keys()].slice(0,Sr.size-Fy);for(let e of t)Sr.delete(e)}var Ny=async t=>{if(Sr.has(t)){let e=Sr.get(t);return!e||e===""?null:e}try{let e=await eD(Ry),r=[];for await(let i of e)i.isDirectory()&&r.push(i.name);let n=r.map(async i=>{let u=hd(Ry,i,`${t}.jsonl`);try{return(await tD(u)).isFile()?i:null}catch{return null}}),s=await Promise.all(n);for(let i of s)if(i)return Sr.set(t,i),dd(),i;return Sr.set(t,""),dd(),null}catch(e){return console.error("Error searching for project by session:",e),Sr.set(t,""),dd(),null}};var md=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,r={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:r.enabled!==!1,options:r})}async enablePlugin(e,r){let n=this.plugins.get(e),s=this.pluginInstances.get(e);if(!n||!s)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(s.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(s){let i=s instanceof Error?s.message:String(s);e.log?.error(`Failed to enable plugin ${r}: ${i}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,r){let n=this.plugins.get(e);n&&(n.enabled=r)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},By=new md;var Gy=Pr(qy(),1);var us=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
339
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(hy).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let r=new e;r&&typeof r=="object"&&(r.logger=this.logger),this.registerTransformer(r.name,r)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let r of e)await this.registerTransformerFromConfig(r)}};import{get_encoding as $S}from"tiktoken";var Xs=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=$S(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");let n=0,{messages:s,system:i,tools:u}=e;return Array.isArray(s)&&s.forEach(c=>{typeof c.content=="string"?n+=r.encode(c.content).length:Array.isArray(c.content)&&c.content.forEach(l=>{if(l.type==="text")n+=r.encode(l.text).length;else if(l.type==="tool_use")n+=r.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let h=typeof l.content=="string"?l.content:JSON.stringify(l.content);n+=r.encode(h).length}})}),typeof i=="string"?n+=r.encode(i).length:Array.isArray(i)&&i.forEach(c=>{c.type==="text"&&(typeof c.text=="string"?n+=r.encode(c.text).length:Array.isArray(c.text)&&c.text.forEach(l=>{n+=r.encode(l||"").length}))}),u&&u.forEach(c=>{c.description&&(n+=r.encode(c.name+c.description).length),c.input_schema&&(n+=r.encode(JSON.stringify(c.input_schema)).length)}),n}isInitialized(){return this.encoding!==void 0}encodeText(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");return Array.from(r.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Ia}from"path";import{homedir as QT}from"os";import{existsSync as ud,mkdirSync as ZT}from"fs";import{promises as Na}from"fs";var zS=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let n=e;for(let s=0;s<r.length;++s){let i=r[s];n=n[i]??=Object.create(null)}n.end=r}return e}split(t){let e=[],r=t.length,n=0,s=0;for(;s<r;){let i=this.trie,u=null,c=s;for(;c<r&&(i=i[t[c]]);)i.end&&(u=i.end),++c;u?(s>n&&e.push(t.slice(n,s)),e.push(u),s+=u.length,n=s):++s}return n<r&&e.push(t.slice(n)),e}},HS=zS,WS=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??null}},GS=WS,Cy=(()=>{let t=[...Array.from({length:94},(s,i)=>i+33),...Array.from({length:12},(s,i)=>i+161),...Array.from({length:82},(s,i)=>i+174)],e=t.slice(),r=0;for(let s=0;s<256;++s)t.includes(s)||(t.push(s),e.push(256+r),r+=1);let n=e.map(s=>String.fromCharCode(s));return Object.fromEntries(t.map((s,i)=>[s,n[i]]))})(),JS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),VS=JS(Cy),py=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",KS=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${py}])]+`,` ?[^\\s${py}]+`]]),Qs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",sF=new RegExp(`^[${Qs}]+$`,"gu"),id=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),Fa=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,s]of KS)r=r.replaceAll(n,s);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=YS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},YS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),XS=(t,e,r)=>{let n=[],s=0;for(;s<t.length;){if(n.push(t[s]),(e.get(t[s])??r)!==r){++s;continue}for(;++s<t.length&&(e.get(t[s])??r)===r;)e.get(n.at(-1))!==r&&(n[n.length-1]+=t[s])}return n},QS=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,ZS=t=>Number.isInteger(t)||typeof t=="bigint",ek=t=>{let e=0;for(let r of t)++e;return e},tk=t=>wy(t.toLowerCase()),Ot=(...t)=>Array.prototype.concat.apply([],t),ad=t=>new Map(Object.entries(t)),rk=(t,e)=>{let r=[],n=0;for(let s of t.matchAll(e)){let i=s[0];n<s.index&&r.push(t.slice(n,s.index)),i.length>0&&r.push(i),n=s.index+i.length}return n<t.length&&r.push(t.slice(n)),r},wy=t=>t.replace(new RegExp("\\p{M}","gu"),""),my=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let n of r)if(!(n in t))return`${e} must contain a "${n}" property`;return null},nk=t=>t.match(/\S+/g)||[],sk=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Zs=sk,ok=class extends Zs{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Er=ok,ik=class extends Er{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],s=n.charCodeAt(0);QS(s)?(e.push(" "),e.push(n),e.push(" ")):e.push(n)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
340
+ `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let r of t){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},ak=ik,uk=class extends Er{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},ck=uk,lk=class extends Er{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Ey(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},dk=lk,fk=class extends Er{normalize(t){let e=Fa(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},hk=fk,pk=class extends Er{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},xa=pk,mk=class extends xa{constructor(){super(...arguments),this.form="NFC"}},gk=mk,yk=class extends xa{constructor(){super(...arguments),this.form="NFD"}},_k=yk,bk=class extends xa{constructor(){super(...arguments),this.form="NFKC"}},Ck=bk,wk=class extends xa{constructor(){super(...arguments),this.form="NFKD"}},Ek=wk,Ak=class extends Er{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},Sk=Ak,kk=class extends Er{normalize(t){return wy(t)}},Tk=kk,Dk=class extends Er{normalize(t){return t.toLowerCase()}},vk=Dk,Rk=class extends Er{normalize(t){return t=this.config.prepend+t,t}},Ok=Rk;function Fk(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new ak(t);case"Precompiled":return new ck(t);case"Sequence":return new dk(t);case"Replace":return new hk(t);case"NFC":return new gk(t);case"NFD":return new _k(t);case"NFKC":return new Ck(t);case"NFKD":return new Ek(t);case"Strip":return new Sk(t);case"StripAccents":return new Tk(t);case"Lowercase":return new vk(t);case"Prepend":return new Ok(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Ey=Fk,xk=class extends Zs{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},sr=xk,Pk=class extends sr{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Cy,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},Ik=Pk,Nk=class extends sr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Bk=Nk,jk=class extends sr{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},n=t.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},Lk=jk,Mk=class extends sr{constructor(t){super(),this.config=t,this.pattern=Fa(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):rk(t,this.pattern)}},Uk=Mk,qk=class extends sr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Qs}]+|[${Qs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},$k=qk,zk=class extends sr{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Hk=zk,Wk=class extends sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${Qs}]+|[${Qs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Gk=Wk,Jk=class extends sr{constructor(t){super(),this.config=t,this.pattern=Fa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Vk=Jk,Kk=class extends sr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Ay(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Yk=Kk,Xk=class extends sr{pre_tokenize_text(t){return nk(t)}},Qk=Xk;function Zk(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Gk;case"Sequence":return new Yk(t);case"Whitespace":return new Bk;case"WhitespaceSplit":return new Qk;case"Metaspace":return new Lk(t);case"ByteLevel":return new Ik(t);case"Split":return new Uk(t);case"Punctuation":return new $k(t);case"Digits":return new Hk(t);case"Replace":return new Vk(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Ay=Zk,eT=class extends Zs{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=XS(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},Pa=eT,tT=class extends Pa{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=ad(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let n=[...r];if(n.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let s=!1,i=0,u=[];for(;i<n.length;){let c=n.length,l=null;for(;i<c;){let h=n.slice(i,c).join("");if(i>0&&(h=this.config.continuing_subword_prefix+h),this.tokens_to_ids.has(h)){l=h;break}--c}if(l===null){s=!0;break}u.push(l),i=c}s?e.push(this.unk_token):e.push(...u)}return e}},gy=tT,yy=class Sy{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new Sy(!1,new Map)}},rT=class{constructor(){this.root=yy.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let n=e.children.get(r);n===void 0&&(n=yy.default(),e.children.set(r,n)),e=n}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let n of t){if(r+=n,e=e.children.get(n),e===void 0)return;e.is_leaf&&(yield r)}}},nT=rT,od=class ky{constructor(e,r,n,s,i){this.token_id=e,this.node_id=r,this.pos=n,this.length=s,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let e=new ky(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},sT=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new od(this.bos_token_id??0,0,0,0,0),s=new od(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(t,e,r,n){let s=this.nodes.length,i=new od(n,s,t,e,r);this.begin_nodes[t].push(i),this.end_nodes[t+e].push(i),this.nodes.push(i)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let u=0,c=null;for(let l of this.end_nodes[e]){let h=l.backtrace_score+i.score;(c===null||h>u)&&(c=l.clone(),u=h)}if(c!==null)i.prev=c,i.backtrace_score=u;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let s=n.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},oT=sT;function iT(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let n=1;n<t.length;++n)t[n]<e&&(e=t[n],r=n);return[e,r]}var aT=class extends Pa{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=t.vocab[n];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=iT(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new nT,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,n=0;for(;n<e.length;){let s=!1,i=[],u=e.slice(n).join(""),c=this.trie.common_prefix_search(u);for(let l of c){i.push(l);let h=this.tokens_to_ids.get(l),f=this.scores[h],p=ek(l);t.insert(n,p,f,h),!s&&p===r&&(s=!0)}s||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new oT(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let n=this.tokenize(r);e.push(...n)}return e}},_y=aT,uT=class{constructor(t=(r,n)=>r>n,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},cT=uT,lT=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},dT=lT,fT=class extends Pa{constructor(t){super(t),this.tokens_to_ids=ad(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new dT(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let s=new cT((c,l)=>c.score<l.score),i={token:r[0],bias:0,prev:null,next:null},u=i;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[c],prev:u,next:null};u.next=l,this.add_node(s,u),u=l}for(;!s.is_empty();){let c=s.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let h={...c.prev};c.prev.deleted=!0,c.prev=h,h.prev?h.prev.next=h:i=h}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):i=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let c=i;c!==null;c=c.next)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,n),n}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let n=this.bpe(r);for(let s of n)if(this.tokens_to_ids.has(s))e.push(s);else if(this.byte_fallback){let i=Array.from(this.text_encoder.encode(s)).map(u=>`<0x${u.toString(16).toUpperCase().padStart(2,"0")}>`);i.every(u=>this.tokens_to_ids.has(u))?e.push(...i):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},by=fT,hT=class extends Pa{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=ad(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(t){return t}},pT=hT;function mT(t,e){switch(t.type){case"WordPiece":return new gy(t);case"Unigram":return new _y(t,e.eos_token);case"BPE":return new by(t);default:if(t.vocab)return Array.isArray(t.vocab)?new _y(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new by(t):new gy(t):new pT(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var gT=mT,yT=class extends Zs{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},eo=yT,_T=class extends eo{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,s=[],i=[];for(let u of n)"SpecialToken"in u?r&&(s.push(u.SpecialToken.id),i.push(u.SpecialToken.type_id)):"Sequence"in u&&(u.Sequence.id==="A"?(s=Ot(s,t),i=Ot(i,new Array(t.length).fill(u.Sequence.type_id))):u.Sequence.id==="B"&&(s=Ot(s,e),i=Ot(i,new Array(e.length).fill(u.Sequence.type_id))));return{tokens:s,token_type_ids:i}}},bT=_T,CT=class extends eo{post_process(t,e=null){return{tokens:e?Ot(t,e):t}}},wT=CT,ET=class extends eo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Ot([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=[],i=r?[this.sep[0]]:[];t=Ot(t,s,e,i),n=Ot(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},AT=ET,ST=class extends eo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Ot([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=r?[this.sep[0]]:[],i=r?[this.sep[0]]:[];t=Ot(t,s,e,i),n=Ot(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},kT=ST,TT=class extends eo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Ty(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let s of this.processors)n=s.post_process(n.tokens,e,r);return n}},DT=TT;function vT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new bT(t);case"ByteLevel":return new wT(t);case"BertProcessing":return new AT(t);case"RobertaProcessing":return new kT(t);case"Sequence":return new DT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Ty=vT,RT=class extends Zs{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},or=RT,OT=class extends or{constructor(t){super(t),this.byte_decoder=VS,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let n of t)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(n)):r.push(n);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},FT=OT,xT=class extends or{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let n=this.config.prefix;n&&e.startsWith(n)?e=e.replace(n,""):e=" "+e}return this.cleanup&&(e=id(e)),e})}},PT=xT,IT=class extends or{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),e.push(n)}return e}},NT=IT,BT=class extends or{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},jT=BT,LT=class extends or{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let r=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=id(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},MT=LT,UT=class extends or{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Dy(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},qT=UT,$T=class extends or{decode_chain(t){let e=Fa(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},zT=$T,HT=class extends or{decode_chain(t){return[t.join("")]}},WT=HT,GT=class extends or{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let s=0;s<this.start&&e[s]===this.content;++s)r=s+1;let n=e.length;for(let s=0;s<this.stop;++s){let i=e.length-s-1;if(e[i]===this.content){n=i;continue}else break}return e.slice(r,n)})}},JT=GT,VT=class extends or{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let i=parseInt(n.slice(3,5),16);isNaN(i)||(s=i)}if(s!==null)r.push(s);else{if(r.length>0){let i=this.text_decoder.decode(Uint8Array.from(r));e.push(i),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},KT=VT;function YT(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new FT(t);case"WordPiece":return new PT(t);case"Metaspace":return new NT(t);case"BPEDecoder":return new jT(t);case"CTC":return new MT(t);case"Sequence":return new qT(t);case"Replace":return new zT(t);case"Fuse":return new WT(t);case"Strip":return new JT(t);case"ByteFallback":return new KT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Dy=YT,XT=class{constructor(t,e){let r=my(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=my(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=Ey(this.tokenizer.normalizer),this.pre_tokenizer=Ay(this.tokenizer.pre_tokenizer),this.model=gT(this.tokenizer.model,this.config),this.post_processor=Ty(this.tokenizer.post_processor),this.decoder=Dy(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(s=>{let i=new GS(s);this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id))}),(this.config.additional_special_tokens??[]).forEach(s=>{this.special_tokens.includes(s)||this.special_tokens.push(s)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new HS(this.added_tokens.map(s=>s.content)),this.added_tokens_map=new Map(this.added_tokens.map(s=>[s.content,s])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:s,token_type_ids:i}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),u=this.model.convert_tokens_to_ids(s),c={ids:u,tokens:s,attention_mask:new Array(u.length).fill(1)};return n&&i&&(c.token_type_ids=i),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!ZS(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(n=n.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=id(n)),n}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((r,n)=>{let s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),s.rstrip&&n<e.length-1&&(e[n+1]=e[n+1].trimStart()))}),e.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=tk(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let s=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(s)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),s=this.encode_text(e||null);return this.post_processor?this.post_processor(n,s,r):{tokens:Ot(n??[],s??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},vy=XT;var Ba=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,r,n={}){this.modelId=e,this.logger=r,this.options=n,this.cacheDir=n.cacheDir||Ia(QT(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Ia(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Ia(e,"tokenizer.json"),tokenizerConfig:Ia(e,"tokenizer_config.json")}}ensureDir(e){ud(e)||ZT(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!ud(e.tokenizerJson)||!ud(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Na.readFile(e.tokenizerJson,"utf-8"),Na.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(r),tokenizerConfig:JSON.parse(n)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),r={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let n=new AbortController,s=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[i,u]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.signal})]);if(!i.ok)throw new Error(`Failed to fetch tokenizer.json: ${i.statusText}`);let[c,l]=await Promise.all([i.json(),u.ok?u.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Na.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Na.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(s)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let r=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new vy(r.tokenizerJson,r.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let r=this.extractTextFromRequest(e);return this.tokenizer.encode(r).ids.length}catch(r){throw this.logger?.error(`Error counting tokens: ${r.message}`),r}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let r=[],{messages:n,system:s,tools:i}=e;if(Array.isArray(n)){for(let u of n)if(typeof u.content=="string")r.push(u.content);else if(Array.isArray(u.content))for(let c of u.content)c.type==="text"&&c.text?r.push(c.text):c.type==="tool_use"&&c.input?r.push(JSON.stringify(c.input)):c.type==="tool_result"&&r.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof s=="string")r.push(s);else if(Array.isArray(s)){for(let u of s)if(u.type==="text"){if(typeof u.text=="string")r.push(u.text);else if(Array.isArray(u.text))for(let c of u.text)c&&r.push(c)}}if(i)for(let u of i)u.name&&r.push(u.name),u.description&&r.push(u.description),u.input_schema&&r.push(JSON.stringify(u.input_schema));return r.join(" ")}};var ja=class{type="api";name;config;logger;options;constructor(e,r,n={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=r,this.options=n;try{let s=new URL(e.url);this.name=`api-${s.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let r=this.formatRequestBody(e),n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},s=new AbortController,i=setTimeout(()=>s.abort(),this.options.timeout||3e4),u=await fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(r),signal:s.signal});if(clearTimeout(i),!u.ok)throw new Error(`API tokenizer request failed: ${u.status} ${u.statusText}`);let c=await u.json();return this.extractTokenCount(c)}catch(r){throw r.name==="AbortError"?new Error("API tokenizer request timed out"):r}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(r=>({role:r.role,content:this.extractTextFromMessage(r)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(r=>r.type==="text"&&r.text?r.text:r.type==="tool_use"&&r.input?JSON.stringify(r.input):r.type==="tool_result"?typeof r.content=="string"?r.content:JSON.stringify(r.content):"").join(" "):""}extractConcatenatedText(e){let r=[];return e.messages&&e.messages.forEach(n=>{r.push(this.extractTextFromMessage(n))}),typeof e.system=="string"?r.push(e.system):Array.isArray(e.system)&&e.system.forEach(n=>{n.type==="text"&&(typeof n.text=="string"?r.push(n.text):Array.isArray(n.text)&&n.text.forEach(s=>{s&&r.push(s)}))}),e.tools&&e.tools.forEach(n=>{n.name&&r.push(n.name),n.description&&r.push(n.description),n.input_schema&&r.push(JSON.stringify(n.input_schema))}),r.join(" ")}extractTokenCount(e){try{let r=this.config.responseField,n=r.split("."),s=e;for(let i of n){if(s==null)throw new Error(`Field path '${r}' not found in response`);s=s[i]}if(typeof s!="number")throw new Error(`Expected number at field path '${r}', got ${typeof s}`);return s}catch(r){throw this.logger?.error(`Failed to extract token count from API response: ${r.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${r.message}`)}}};var as=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,r,n={}){this.configService=e,this.logger=r,this.options={timeout:n.timeout??3e4,...n}}async initialize(){try{this.fallbackTokenizer=new Xs("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let r=this.getCacheKey(e);if(this.tokenizers.has(r))return this.tokenizers.get(r);let n;try{switch(e.type){case"tiktoken":n=new Xs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ba(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new ja(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await n.initialize(),this.tokenizers.set(r,n),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${r})`),n}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,r){let n=r?await this.getTokenizer(r):this.fallbackTokenizer;return{tokenCount:await n.countTokens(e),tokenizerUsed:n.name,cached:!1}}getTokenizerConfigForModel(e,r){let s=(this.configService.get("providers")||[]).find(i=>i.name===e);if(s?.tokenizer)return s.tokenizer.models?.[r]?s.tokenizer.models[r]:s.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(r){this.logger?.error(`Error disposing tokenizer: ${r}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};import{get_encoding as eD}from"tiktoken";var cd=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}values(){return Array.from(this.cache.values())}},ld=new cd(100);import{readFile as fd}from"fs/promises";import{opendir as tD,stat as rD}from"fs/promises";import{join as hd}from"path";import{CLAUDE_PROJECTS_DIR as Ry,HOME_DIR as Oy}from"@wengine-ai/claude-code-router-shared";var Ar=eD("cl100k_base"),xy=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(s=>{typeof s.content=="string"?n+=Ar.encode(s.content).length:Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="text"?n+=Ar.encode(i.text).length:i.type==="tool_use"?n+=Ar.encode(JSON.stringify(i.input)).length:i.type==="tool_result"&&(n+=Ar.encode(typeof i.content=="string"?i.content:JSON.stringify(i.content)).length)})}),typeof e=="string"?n+=Ar.encode(e).length:Array.isArray(e)&&e.forEach(s=>{s.type==="text"&&(typeof s.text=="string"?n+=Ar.encode(s.text).length:Array.isArray(s.text)&&s.text.forEach(i=>{n+=Ar.encode(i||"").length}))}),r&&r.forEach(s=>{s.description&&(n+=Ar.encode(s.name+s.description).length),s.input_schema&&(n+=Ar.encode(JSON.stringify(s.input_schema)).length)}),n},Py=async(t,e)=>{if(t.sessionId){let r=await Ny(t.sessionId);if(r){let n=hd(Oy,r,"config.json"),s=hd(Oy,r,`${t.sessionId}.json`);try{let i=JSON.parse(await fd(s,"utf8"));if(i&&i.Router)return i.Router}catch{}try{let i=JSON.parse(await fd(n,"utf8"));if(i&&i.Router)return i.Router}catch{}}}};function La(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function Iy(t){let e=La(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),s=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(s)return{family:s[1].toLowerCase(),extended:r};let i=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return i?{family:i[1].toLowerCase(),extended:r}:{family:null,extended:r}}function nD(t,e){if(!e||!t)return null;let r=La(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=Iy(t);if(n&&e[n])return e[n];for(let[s,i]of Object.entries(e)){let u=La(s);if(u&&r.includes(u))return i}return null}function Gr(t,e,r){if(!t?.includes(","))return t;let[n,...s]=t.split(","),i=n.trim(),u=s.join(",").trim();if(!r&&!vn().isAvailable(i,u))return null;let c=e.find(h=>h.name.toLowerCase()===i.toLowerCase()),l=c?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return c&&l?`${c.name},${l}`:t}function sD(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function oD(t){let e=La(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(n=>n.test(e))}function iD(t,e,r,n,s,i){let u=r.longContextThreshold||6e4;if((i||e>2e5)&&r.extendedContext){let p=Gr(r.extendedContext,n);if(p)return t.log.info(`Family: using extended context model (1M+), tokens: ${e}, explicit: ${i}`),{model:p,scenarioType:"extendedContext"};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}let h=s&&s.input_tokens>u&&e>2e4,f=e>u;if((h||f)&&r.longContext){let p=Gr(r.longContext,n);if(p)return t.log.info(`Family: using long context model, tokens: ${e}`),{model:p,scenarioType:"longContext"};t.log.warn("Family: longContext model unavailable (fail pool), skipping")}if(Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.type?.startsWith("web_search"))&&r.webSearch){let p=Gr(r.webSearch,n);if(p)return{model:p,scenarioType:"webSearch"};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let p=Gr(r.think,n);if(p)return{model:p,scenarioType:"think"};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let p=Gr(r.default,n);if(p)return{model:p,scenarioType:"default"};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var aD=async(t,e,r,n)=>{let s=await Py(t,r),i=r.get("providers")||[],u=s||r.get("Router");if(t.body.model.includes(",")){let g=Gr(t.body.model,i);if(g)return{model:g,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying alternatives`)}let{family:c,extended:l}=Iy(t.body.model),h=u?.families?.[c||""];if(h){t.log.info(`Using model family routing for: ${c}${l?" (1M)":""}`),t.modelFamily=c,t.familyFallback=h.fallback;let g=iD(t,e,h,i,n,l);if(g)return g}let f=nD(t.body.model,u?.models);if(f){let g=Gr(f,i);if(g)return t.log.info(`Using mapped model for ${t.body.model}: ${f}`),{model:g,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${f} unavailable (fail pool), skipping`)}let p=u?.extendedContextThreshold||2e5;if(e>p&&u?.extendedContext)return t.log.info(`Using extended context (1M) model due to token count: ${e}, threshold: ${p}`),{model:u.extendedContext,scenarioType:"extendedContext"};let A=u?.longContextThreshold||6e4,v=n&&n.input_tokens>A&&e>2e4,S=e>A;if((v||S)&&u?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${A}`),{model:u.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let g=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(g)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${g[1]}</CCR-SUBAGENT-MODEL>`,""),{model:g[1],scenarioType:"default"}}let y=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&y?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:y.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(g=>g.type?.startsWith("web_search"))&&u?.webSearch?{model:u.webSearch,scenarioType:"webSearch"}:t.body.thinking&&u?.think?(t.log.info(`Using think model for ${t.body.thinking}`),{model:u.think,scenarioType:"think"}):{model:u?.default,scenarioType:"default"}},pd=async(t,e,r)=>{let{configService:n,event:s}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let v=t.body.metadata.user_id.split("_session_");v.length>1&&(t.sessionId=v[1])}let u=await Py(t,n)||n.get("Router"),c=n.get("providers")||[],l=ld.get(t.sessionId),{messages:h,system:f=[],tools:p}=t.body,A=n.get("REWRITE_SYSTEM_PROMPT");if(A&&f.length>1&&f[1]?.text?.includes("<env>")){let v=await fd(A,"utf-8");f[1].text=`${v}<env>${f[1].text.split("<env>").pop()}`}try{let[v,S]=t.body.model.split(","),y=r.tokenizerService?.getTokenizerConfigForModel(v,S),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:h,system:f,tools:p},y)).tokenCount:g=xy(h,f,p),t.tokenCount=g;let m,k=n.get("CUSTOM_ROUTER_PATH");if(k)try{m=await Q(k)(t,n.getAll(),{event:s})}catch(b){t.log.error(`failed to load custom router: ${b.message}`)}if(m)t.scenarioType="default";else{let b=await aD(t,g,n,l);m=b.model,t.scenarioType=b.scenarioType}if(u?.image&&m!==u.image&&sD(t)&&!oD(m)){let b=Gr(u.image,c);b?(t.log.info(`Using image model fallback for ${m}`),m=b,t.scenarioType="image"):t.log.warn(`Image model ${u.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(v){t.log.error(`Error in router middleware: ${v.message}`),t.body.model=u?.default,t.scenarioType="default"}},Sr=new Map,Fy=1e3;function dd(){if(Sr.size<=Fy)return;let t=[...Sr.keys()].slice(0,Sr.size-Fy);for(let e of t)Sr.delete(e)}var Ny=async t=>{if(Sr.has(t)){let e=Sr.get(t);return!e||e===""?null:e}try{let e=await tD(Ry),r=[];for await(let i of e)i.isDirectory()&&r.push(i.name);let n=r.map(async i=>{let u=hd(Ry,i,`${t}.jsonl`);try{return(await rD(u)).isFile()?i:null}catch{return null}}),s=await Promise.all(n);for(let i of s)if(i)return Sr.set(t,i),dd(),i;return Sr.set(t,""),dd(),null}catch(e){return console.error("Error searching for project by session:",e),Sr.set(t,""),dd(),null}};var md=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,r={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:r.enabled!==!1,options:r})}async enablePlugin(e,r){let n=this.plugins.get(e),s=this.pluginInstances.get(e);if(!n||!s)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(s.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(s){let i=s instanceof Error?s.message:String(s);e.log?.error(`Failed to enable plugin ${r}: ${i}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,r){let n=this.plugins.get(e);n&&(n.enabled=r)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},By=new md;var Jy=Pr(qy(),1);var us=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
341
341
  `);this.buffer=n.pop()||"";for(let s of n){let i=this.processLine(s);i&&r.enqueue(i)}},flush:e=>{if(this.buffer.trim()){let r=[];this.processLine(this.buffer.trim(),r),r.forEach(n=>e.enqueue(n))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,r){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let n={...this.currentEvent};return this.currentEvent={},r?(r.push(n),null):n}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let n=e.slice(5).trim();if(n==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(n)}catch{this.currentEvent.data={raw:n,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var Ua=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
342
342
  `),e.id&&(n+=`id: ${e.id}
343
343
  `),e.retry&&(n+=`retry: ${e.retry}
344
344
  `),e.data&&(e.data.type==="done"?n+=`data: [DONE]
345
345
  `:n+=`data: ${JSON.stringify(e.data)}
346
346
  `),n+=`
347
- `,r.enqueue(n)}})}};var $y=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:s,value:i}=await r.read();if(s){n.close();break}let u=await e(i,n);u!==void 0&&n.enqueue(u)}}catch(s){n.error(s)}finally{r.releaseLock()}}})};_d();bd();Cd();Hy();var so=new Map,Ed=new Map,Jy={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,Gy.default)(async(t,e)=>{let r={reporter:["console","temp-file"],...e},n=Array.isArray(r.reporter)?r.reporter:[r.reporter];if(r.outputHandlers&&r.outputHandlers.length>0)cs.registerHandlers(r.outputHandlers);else{let i=[];for(let u of n)u==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):u==="temp-file"?i.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):u==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&cs.registerHandlers(i)}r.outputOptions&&cs.setDefaultOptions(r.outputOptions);let s=async i=>{let u=t.tokenizerService;if(!u)return t.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let c=i.provider,l=i.model,h=`${c}:${l}`;if(Ed.has(h))return Ed.get(h);let f=u.getTokenizerConfigForModel(c,l);if(!f)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await u.getTokenizer(f);return Ed.set(h,p),t.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}};t.addHook("onRequest",async i=>{new URL(`http://127.0.0.1${i.url}`).pathname.endsWith("/v1/messages")&&(i.requestStartTime=performance.now())}),t.addHook("onSend",async(i,u,c)=>{let l=i.requestStartTime;if(!l)return;let h=i.id||Date.now().toString(),f;try{let E=i.body?.metadata?.user_id;if(E&&typeof E=="string")try{let y=JSON.parse(E);y.session_id&&(f=y.session_id)}catch{let y=E.match(/_session_([a-f0-9-]+)/i);f=y?y[1]:void 0}}catch{}if(!f)return;let p=await s(i);if(c instanceof ReadableStream){so.set(h,{requestId:h,sessionId:f,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[E,y]=c.tee();return(async()=>{let m=null,T=async b=>{let w=so.get(h);if(!w)return;let O=performance.now();if(b){let x=(w.lastTokenTime-w.startTime)/1e3;x>0&&(w.tokensPerSecond=Math.round(w.tokenCount/x))}else{let x=O-1e3;w.tokenTimestamps=w.tokenTimestamps.filter($=>$>x),w.tokensPerSecond=w.tokenTimestamps.length}await Wy(w,n,r.outputOptions,b).catch(x=>{t.log?.warn(`Failed to output streaming stats: ${x.message}`)})};try{let w=y.pipeThrough(new TextDecoderStream).pipeThrough(new us).getReader();for(m=setInterval(async()=>{so.get(h)&&await T(!1)},1e3);;){let{done:O,value:x}=await w.read();if(O)break;let $=x,V=so.get(h);if(!V)continue;let U=performance.now();if(!V.firstTokenTime&&($.event==="content_block_start"||$.event==="content_block_delta"||$.event==="text_block"||$.event==="content_block")&&(V.firstTokenTime=U,V.timeToFirstToken=Math.round(U-V.startTime)),$.event==="content_block_delta"&&$.data?.delta){let X=$.data.delta.type,ne="";if(X==="text_delta"?ne=$.data.delta.text||"":X==="input_json_delta"?ne=$.data.delta.partial_json||"":X==="thinking_delta"&&(ne=$.data.delta.thinking||""),ne){let ae=p&&p.encodeText?p.encodeText(ne).length:oo(ne);V.tokenCount+=ae,V.lastTokenTime=U;for(let de=0;de<ae;de++)V.tokenTimestamps.push(U)}}$.event==="message_stop"&&(m&&(clearInterval(m),m=null),await T(!0),so.delete(h))}}catch(b){m&&clearInterval(m),b.name!=="AbortError"&&b.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${b.message}`)}})().catch(m=>{console.log(m),t.log?.warn(`Background stats processing failed: ${m.message}`)}),E}let S=performance.now(),D=0;if(c&&typeof c=="string")try{let E=JSON.parse(c);if(E.usage?.output_tokens)D=E.usage.output_tokens;else{let y=E.content||E.message?.content||"";if(p)Array.isArray(y)?D=y.reduce((g,m)=>{if(m.type==="text"){let T=m.text||"";return g+(p.encodeText?p.encodeText(T).length:oo(T))}return g},0):typeof y=="string"&&(D=p.encodeText?p.encodeText(y).length:oo(y));else{let g=Array.isArray(y)?y.map(m=>m.text).join(""):y;D=oo(g)}}}catch{}if(D>0){let E=(S-l)/1e3,y={requestId:h,sessionId:f,startTime:l,lastTokenTime:S,tokenCount:D,tokensPerSecond:E>0?Math.round(D/E):0,timeToFirstToken:Math.round(S-l),stream:!1,tokenTimestamps:[]};await Wy(y,n,r.outputOptions,!0)}return c})})};function oo(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function Wy(t,e,r,n=!1){let s=n?"[Token Speed Final]":"[Token Speed]",i={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},u={prefix:s,metadata:{sessionId:t.sessionId},...r};for(let c of e)try{await cs.outputToType(c,i,u)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}function _D(t={}){let e=gD({bodyLimit:52428800,...t});return e.setErrorHandler(qf),e.register(yD),e}var Ad=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:r,...n}=e;this.app=_D({...n,logger:n.logger??!0}),this.configService=new Dn(e),this.transformerService=new is(this.configService,this.app.log),this.tokenizerService=new as(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Rn(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(s=>{this.app.log.error(`Failed to initialize TokenizerService: ${s}`)})}async register(e,r){await this.app.register(e,r)}addHook(e,r){this.app.addHook(e,r)}async registerNamespace(e,r){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await pd(l,h,{configService:this.configService,tokenizerService:this.tokenizerService})}),await ku(c)});return}if(!r)throw new Error("options is required");let n=new Dn({initialConfig:{providers:r.Providers,Router:r.Router}}),s=new is(n,this.app.log);await s.initialize();let i=new Rn(n,s,this.app.log),u=new as(n,this.app.log);await u.initialize(),await this.app.register(async c=>{c.decorate("configService",n),c.decorate("transformerService",s),c.decorate("providerService",i),c.decorate("tokenizerService",u),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await pd(l,h,{configService:n,tokenizerService:u})}),await ku(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,s,i)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body){let c=n.body;n.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}i()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(n,s)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body)try{let u=n.body;if(!u||!u.model)return s.code(400).send({error:"Missing model in request body"});let[c,...l]=u.model.split(",");u.model=l.join(","),n.provider=c,n.model=l;return}catch(u){return n.log.error({error:u},"Error in modelProviderMiddleware:"),s.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},KP=Ad;export{Dn as ConfigService,Lo as ProviderHealthStore,Rn as ProviderService,us as SSEParserTransform,Ua as SSESerializerTransform,as as TokenizerService,is as TransformerService,xy as calculateTokenCount,KP as default,vn as getHealthStore,By as pluginManager,$y as rewriteStream,pd as router,Ny as searchProjectBySession,ld as sessionUsageCache,Jy as tokenSpeedPlugin};
347
+ `,r.enqueue(n)}})}};var $y=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:s,value:i}=await r.read();if(s){n.close();break}let u=await e(i,n);u!==void 0&&n.enqueue(u)}}catch(s){n.error(s)}finally{r.releaseLock()}}})};_d();bd();Cd();Hy();var so=new Map,Ed=new Map,yD=1,Vy={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,Jy.default)(async(t,e)=>{let r={reporter:["console","temp-file"],...e},n=Array.isArray(r.reporter)?r.reporter:[r.reporter];if(r.outputHandlers&&r.outputHandlers.length>0)cs.registerHandlers(r.outputHandlers);else{let i=[];for(let u of n)u==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):u==="temp-file"?i.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):u==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&cs.registerHandlers(i)}r.outputOptions&&cs.setDefaultOptions(r.outputOptions);let s=async i=>{let u=t.tokenizerService;if(!u)return t.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let c=i.provider,l=i.model,h=`${c}:${l}`;if(Ed.has(h))return Ed.get(h);let f=u.getTokenizerConfigForModel(c,l);if(!f)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await u.getTokenizer(f);return Ed.set(h,p),t.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}};t.addHook("onRequest",async i=>{new URL(`http://127.0.0.1${i.url}`).pathname.endsWith("/v1/messages")&&(i.requestStartTime=performance.now())}),t.addHook("onSend",async(i,u,c)=>{let l=i.requestStartTime;if(!l)return;let h=i.id||Date.now().toString(),f;try{let y=i.body?.metadata?.user_id;if(y&&typeof y=="string")try{let g=JSON.parse(y);g.session_id&&(f=g.session_id)}catch{let g=y.match(/_session_([a-f0-9-]+)/i);f=g?g[1]:void 0}}catch{}if(!f)return;let p=await s(i);if(c instanceof ReadableStream){so.set(h,{requestId:h,sessionId:f,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,g]=c.tee();return(async()=>{let k=null,b=async E=>{let R=so.get(h);if(!R)return;let x=performance.now();if(E){let $=R.firstTokenTime?R.firstTokenTime-R.startTime:0,J=R.lastTokenTime-R.startTime;R.tokensPerSecond=Wy(R.tokenCount,J,$)}else{let $=x-1e3;R.tokenTimestamps=R.tokenTimestamps.filter(J=>J>$),R.tokensPerSecond=R.tokenTimestamps.length}await Gy(R,n,r.outputOptions,E).catch($=>{t.log?.warn(`Failed to output streaming stats: ${$.message}`)})};try{let R=g.pipeThrough(new TextDecoderStream).pipeThrough(new us).getReader();for(k=setInterval(async()=>{so.get(h)&&await b(!1)},1e3);;){let{done:x,value:$}=await R.read();if(x)break;let J=$,M=so.get(h);if(!M)continue;let X=performance.now();if(!M.firstTokenTime&&(J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="text_block"||J.event==="content_block")&&(M.firstTokenTime=X,M.timeToFirstToken=Math.round(X-M.startTime)),J.event==="content_block_delta"&&J.data?.delta){let ue=J.data.delta.type,re="";if(ue==="text_delta"?re=J.data.delta.text||"":ue==="input_json_delta"?re=J.data.delta.partial_json||"":ue==="thinking_delta"&&(re=J.data.delta.thinking||""),re){let de=p&&p.encodeText?p.encodeText(re).length:oo(re);M.tokenCount+=de,M.lastTokenTime=X;for(let pe=0;pe<de;pe++)M.tokenTimestamps.push(X)}}J.event==="message_stop"&&(k&&(clearInterval(k),k=null),await b(!0),so.delete(h))}}catch(E){k&&clearInterval(k),E.name!=="AbortError"&&E.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${E.message}`)}})().catch(k=>{console.log(k),t.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let A=performance.now(),v=0,S=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")v=y.usage.output_tokens,S=!0;else{let g=y.content??y.message?.content;if(g!==void 0)if(S=!0,p)Array.isArray(g)?v=g.reduce((m,k)=>{if(k.type==="text"){let b=k.text||"";return m+(p.encodeText?p.encodeText(b).length:oo(b))}return m},0):typeof g=="string"&&(v=p.encodeText?p.encodeText(g).length:oo(g));else{let m=Array.isArray(g)?g.map(k=>k.text).join(""):typeof g=="string"?g:"";v=oo(m)}}}catch{}if(S){let y=Math.round(A-l),g=A-l,m={requestId:h,sessionId:f,startTime:l,lastTokenTime:A,tokenCount:v,tokensPerSecond:Wy(v,g),timeToFirstToken:y,stream:!1,tokenTimestamps:[]};await Gy(m,n,r.outputOptions,!0)}return c})})};function Wy(t,e,r=0){if(t<=0)return 0;let n=Math.max((e-r)/1e3,yD);return Math.round(t/n)}function oo(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function Gy(t,e,r,n=!1){let s=n?"[Token Speed Final]":"[Token Speed]",i={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},u={prefix:s,metadata:{sessionId:t.sessionId},...r};for(let c of e)try{await cs.outputToType(c,i,u)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}function CD(t={}){let e=_D({bodyLimit:52428800,...t});return e.setErrorHandler(qf),e.register(bD),e}var Ad=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:r,...n}=e;this.app=CD({...n,logger:n.logger??!0}),this.configService=new Dn(e),this.transformerService=new is(this.configService,this.app.log),this.tokenizerService=new as(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Rn(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(s=>{this.app.log.error(`Failed to initialize TokenizerService: ${s}`)})}async register(e,r){await this.app.register(e,r)}addHook(e,r){this.app.addHook(e,r)}async registerNamespace(e,r){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await pd(l,h,{configService:this.configService,tokenizerService:this.tokenizerService})}),await ku(c)});return}if(!r)throw new Error("options is required");let n=new Dn({initialConfig:{providers:r.Providers,Router:r.Router}}),s=new is(n,this.app.log);await s.initialize();let i=new Rn(n,s,this.app.log),u=new as(n,this.app.log);await u.initialize(),await this.app.register(async c=>{c.decorate("configService",n),c.decorate("transformerService",s),c.decorate("providerService",i),c.decorate("tokenizerService",u),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await pd(l,h,{configService:n,tokenizerService:u})}),await ku(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,s,i)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body){let c=n.body;n.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}i()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(n,s)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body)try{let u=n.body;if(!u||!u.model)return s.code(400).send({error:"Missing model in request body"});let[c,...l]=u.model.split(",");u.model=l.join(","),n.provider=c,n.model=l;return}catch(u){return n.log.error({error:u},"Error in modelProviderMiddleware:"),s.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},XP=Ad;export{Dn as ConfigService,Lo as ProviderHealthStore,Rn as ProviderService,us as SSEParserTransform,Ua as SSESerializerTransform,as as TokenizerService,is as TransformerService,xy as calculateTokenCount,XP as default,vn as getHealthStore,By as pluginManager,$y as rewriteStream,pd as router,Ny as searchProjectBySession,ld as sessionUsageCache,Vy as tokenSpeedPlugin};
348
348
  /*! Bundled license information:
349
349
 
350
350
  web-streams-polyfill/dist/ponyfill.es2018.js: