@wengine-ai/llms 2.0.70 → 2.0.72

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,76 +1,76 @@
1
- "use strict";var gb=Object.create;var Qs=Object.defineProperty;var yb=Object.getOwnPropertyDescriptor;var _b=Object.getOwnPropertyNames;var bb=Object.getPrototypeOf,Cb=Object.prototype.hasOwnProperty;var Be=(t,e)=>()=>(t&&(e=t(t=0)),e);var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Nu=(t,e)=>{for(var r in e)Qs(t,r,{get:e[r],enumerable:!0})},sh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _b(e))!Cb.call(t,o)&&o!==r&&Qs(t,o,{get:()=>e[o],enumerable:!(n=yb(e,o))||n.enumerable});return t};var je=(t,e,r)=>(r=t!=null?gb(bb(t)):{},sh(e||!t||!t.__esModule?Qs(r,"default",{value:t,enumerable:!0}):r,t)),wb=t=>sh(Qs({},"__esModule",{value:!0}),t);var ih=J((XT,Xs)=>{Xs.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Xs.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]/;Xs.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 ju=J((ZT,ah)=>{var Bu=ih();ah.exports={isSpaceSeparator(t){return typeof t=="string"&&Bu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Bu.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"||Bu.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 fh=J((eD,dh)=>{var $e=ju(),Mu,Ze,br,ei,Mr,Lt,ze,$u,Do;dh.exports=function(e,r){Mu=String(e),Ze="start",br=[],ei=0,Mr=1,Lt=0,ze=void 0,$u=void 0,Do=void 0;do ze=Eb(),kb[Ze]();while(ze.type!=="eof");return typeof r=="function"?Uu({"":Do},"",r):Do};function Uu(t,e,r){let n=t[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=String(o),a=Uu(n,s,r);a===void 0?delete n[s]:Object.defineProperty(n,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in n){let s=Uu(n,o,r);s===void 0?delete n[o]:Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return r.call(t,e,n)}var me,fe,To,_r,be;function Eb(){for(me="default",fe="",To=!1,_r=1;;){be=Cr();let t=ch[me]();if(t)return t}}function Cr(){if(Mu[ei])return String.fromCodePoint(Mu.codePointAt(ei))}function H(){let t=Cr();return t===`
2
- `?(Mr++,Lt=0):t?Lt+=t.length:Lt++,t&&(ei+=t.length),t}var ch={default(){switch(be){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(),Fe("eof")}if($e.isSpaceSeparator(be)){H();return}return ch[Ze]()},comment(){switch(be){case"*":H(),me="multiLineComment";return;case"/":H(),me="singleLineComment";return}throw Pe(H())},multiLineComment(){switch(be){case"*":H(),me="multiLineCommentAsterisk";return;case void 0:throw Pe(H())}H()},multiLineCommentAsterisk(){switch(be){case"*":H();return;case"/":H(),me="default";return;case void 0:throw Pe(H())}H(),me="multiLineComment"},singleLineComment(){switch(be){case`
4
- `:case"\r":case"\u2028":case"\u2029":H(),me="default";return;case void 0:return H(),Fe("eof")}H()},value(){switch(be){case"{":case"[":return Fe("punctuator",H());case"n":return H(),sn("ull"),Fe("null",null);case"t":return H(),sn("rue"),Fe("boolean",!0);case"f":return H(),sn("alse"),Fe("boolean",!1);case"-":case"+":H()==="-"&&(_r=-1),me="sign";return;case".":fe=H(),me="decimalPointLeading";return;case"0":fe=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":fe=H(),me="decimalInteger";return;case"I":return H(),sn("nfinity"),Fe("numeric",1/0);case"N":return H(),sn("aN"),Fe("numeric",NaN);case'"':case"'":To=H()==='"',fe="",me="string";return}throw Pe(H())},identifierNameStartEscape(){if(be!=="u")throw Pe(H());H();let t=qu();switch(t){case"$":case"_":break;default:if(!$e.isIdStartChar(t))throw uh();break}fe+=t,me="identifierName"},identifierName(){switch(be){case"$":case"_":case"\u200C":case"\u200D":fe+=H();return;case"\\":H(),me="identifierNameEscape";return}if($e.isIdContinueChar(be)){fe+=H();return}return Fe("identifier",fe)},identifierNameEscape(){if(be!=="u")throw Pe(H());H();let t=qu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!$e.isIdContinueChar(t))throw uh();break}fe+=t,me="identifierName"},sign(){switch(be){case".":fe=H(),me="decimalPointLeading";return;case"0":fe=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":fe=H(),me="decimalInteger";return;case"I":return H(),sn("nfinity"),Fe("numeric",_r*(1/0));case"N":return H(),sn("aN"),Fe("numeric",NaN)}throw Pe(H())},zero(){switch(be){case".":fe+=H(),me="decimalPoint";return;case"e":case"E":fe+=H(),me="decimalExponent";return;case"x":case"X":fe+=H(),me="hexadecimal";return}return Fe("numeric",_r*0)},decimalInteger(){switch(be){case".":fe+=H(),me="decimalPoint";return;case"e":case"E":fe+=H(),me="decimalExponent";return}if($e.isDigit(be)){fe+=H();return}return Fe("numeric",_r*Number(fe))},decimalPointLeading(){if($e.isDigit(be)){fe+=H(),me="decimalFraction";return}throw Pe(H())},decimalPoint(){switch(be){case"e":case"E":fe+=H(),me="decimalExponent";return}if($e.isDigit(be)){fe+=H(),me="decimalFraction";return}return Fe("numeric",_r*Number(fe))},decimalFraction(){switch(be){case"e":case"E":fe+=H(),me="decimalExponent";return}if($e.isDigit(be)){fe+=H();return}return Fe("numeric",_r*Number(fe))},decimalExponent(){switch(be){case"+":case"-":fe+=H(),me="decimalExponentSign";return}if($e.isDigit(be)){fe+=H(),me="decimalExponentInteger";return}throw Pe(H())},decimalExponentSign(){if($e.isDigit(be)){fe+=H(),me="decimalExponentInteger";return}throw Pe(H())},decimalExponentInteger(){if($e.isDigit(be)){fe+=H();return}return Fe("numeric",_r*Number(fe))},hexadecimal(){if($e.isHexDigit(be)){fe+=H(),me="hexadecimalInteger";return}throw Pe(H())},hexadecimalInteger(){if($e.isHexDigit(be)){fe+=H();return}return Fe("numeric",_r*Number(fe))},string(){switch(be){case"\\":H(),fe+=Ab();return;case'"':if(To)return H(),Fe("string",fe);fe+=H();return;case"'":if(!To)return H(),Fe("string",fe);fe+=H();return;case`
5
- `:case"\r":throw Pe(H());case"\u2028":case"\u2029":vb(be);break;case void 0:throw Pe(H())}fe+=H()},start(){switch(be){case"{":case"[":return Fe("punctuator",H())}me="value"},beforePropertyName(){switch(be){case"$":case"_":fe=H(),me="identifierName";return;case"\\":H(),me="identifierNameStartEscape";return;case"}":return Fe("punctuator",H());case'"':case"'":To=H()==='"',me="string";return}if($e.isIdStartChar(be)){fe+=H(),me="identifierName";return}throw Pe(H())},afterPropertyName(){if(be===":")return Fe("punctuator",H());throw Pe(H())},beforePropertyValue(){me="value"},afterPropertyValue(){switch(be){case",":case"}":return Fe("punctuator",H())}throw Pe(H())},beforeArrayValue(){if(be==="]")return Fe("punctuator",H());me="value"},afterArrayValue(){switch(be){case",":case"]":return Fe("punctuator",H())}throw Pe(H())},end(){throw Pe(H())}};function Fe(t,e){return{type:t,value:e,line:Mr,column:Lt}}function sn(t){for(let e of t){if(Cr()!==e)throw Pe(H());H()}}function Ab(){switch(Cr()){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(Cr()))throw Pe(H());return"\0";case"x":return H(),Sb();case"u":return H(),qu();case`
7
- `:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),Cr()===`
8
- `&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Pe(H());case void 0:throw Pe(H())}return H()}function Sb(){let t="",e=Cr();if(!$e.isHexDigit(e)||(t+=H(),e=Cr(),!$e.isHexDigit(e)))throw Pe(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function qu(){let t="",e=4;for(;e-- >0;){let r=Cr();if(!$e.isHexDigit(r))throw Pe(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var kb={start(){if(ze.type==="eof")throw an();Lu()},beforePropertyName(){switch(ze.type){case"identifier":case"string":$u=ze.value,Ze="afterPropertyName";return;case"punctuator":Zs();return;case"eof":throw an()}},afterPropertyName(){if(ze.type==="eof")throw an();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw an();Lu()},beforeArrayValue(){if(ze.type==="eof")throw an();if(ze.type==="punctuator"&&ze.value==="]"){Zs();return}Lu()},afterPropertyValue(){if(ze.type==="eof")throw an();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":Zs()}},afterArrayValue(){if(ze.type==="eof")throw an();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":Zs()}},end(){}};function Lu(){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(Do===void 0)Do=t;else{let e=br[br.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,$u,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")br.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=br[br.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function Zs(){br.pop();let t=br[br.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Pe(t){return ti(t===void 0?`JSON5: invalid end of input at ${Mr}:${Lt}`:`JSON5: invalid character '${lh(t)}' at ${Mr}:${Lt}`)}function an(){return ti(`JSON5: invalid end of input at ${Mr}:${Lt}`)}function uh(){return Lt-=5,ti(`JSON5: invalid identifier character at ${Mr}:${Lt}`)}function vb(t){console.warn(`JSON5: '${lh(t)}' in strings is not valid ECMAScript; consider escaping`)}function lh(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 ti(t){let e=new SyntaxError(t);return e.lineNumber=Mr,e.columnNumber=Lt,e}});var ph=J((tD,hh)=>{var zu=ju();hh.exports=function(e,r,n){let o=[],s="",a,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)){a=[];for(let _ of r){let g;typeof _=="string"?g=_:(typeof _=="number"||_ instanceof String||_ instanceof Number)&&(g=String(_)),g!==void 0&&a.indexOf(g)<0&&a.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)),d("",{"":e});function d(_,g){let m=g[_];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(_):typeof m.toJSON=="function"&&(m=m.toJSON(_))),c&&(m=c.call(g,_,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):w(m)}function p(_){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<_.length;E++){let D=_[E];switch(D){case"'":case'"':g[D]++,k+=D;continue;case"\0":if(zu.isDigit(_[E+1])){k+="\\x00";continue}}if(m[D]){k+=m[D];continue}if(D<" "){let F=D.charCodeAt(0).toString(16);k+="\\x"+("00"+F).substring(F.length);continue}k+=D}let y=h||Object.keys(g).reduce((E,D)=>g[E]<g[D]?E:D);return k=k.replace(new RegExp(y,"g"),m[y]),y+k+y}function w(_){if(o.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");o.push(_);let g=s;s=s+l;let m=a||Object.keys(_),k=[];for(let E of m){let D=d(E,_);if(D!==void 0){let F=T(E)+":";l!==""&&(F+=" "),F+=D,k.push(F)}}let y;if(k.length===0)y="{}";else{let E;if(l==="")E=k.join(","),y="{"+E+"}";else{let D=`,
1
+ "use strict";var Sb=Object.create;var ei=Object.defineProperty;var kb=Object.getOwnPropertyDescriptor;var vb=Object.getOwnPropertyNames;var Tb=Object.getPrototypeOf,Db=Object.prototype.hasOwnProperty;var Ne=(t,e)=>()=>(t&&(e=t(t=0)),e);var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ti=(t,e)=>{for(var r in e)ei(t,r,{get:e[r],enumerable:!0})},lh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vb(e))!Db.call(t,o)&&o!==r&&ei(t,o,{get:()=>e[o],enumerable:!(n=kb(e,o))||n.enumerable});return t};var Me=(t,e,r)=>(r=t!=null?Sb(Tb(t)):{},lh(e||!t||!t.__esModule?ei(r,"default",{value:t,enumerable:!0}):r,t)),dh=t=>lh(ei({},"__esModule",{value:!0}),t);var fh=J((iD,ri)=>{ri.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;ri.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]/;ri.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 $u=J((aD,hh)=>{var Uu=fh();hh.exports={isSpaceSeparator(t){return typeof t=="string"&&Uu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Uu.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"||Uu.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 _h=J((uD,yh)=>{var qe=$u(),zu,Ze,Cr,oi,Ur,Ut,ze,Gu,xo;yh.exports=function(e,r){zu=String(e),Ze="start",Cr=[],oi=0,Ur=1,Ut=0,ze=void 0,Gu=void 0,xo=void 0;do ze=Rb(),Fb[Ze]();while(ze.type!=="eof");return typeof r=="function"?Hu({"":xo},"",r):xo};function Hu(t,e,r){let n=t[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=String(o),a=Hu(n,s,r);a===void 0?delete n[s]:Object.defineProperty(n,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in n){let s=Hu(n,o,r);s===void 0?delete n[o]:Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return r.call(t,e,n)}var me,fe,Ro,br,be;function Rb(){for(me="default",fe="",Ro=!1,br=1;;){be=wr();let t=mh[me]();if(t)return t}}function wr(){if(zu[oi])return String.fromCodePoint(zu.codePointAt(oi))}function H(){let t=wr();return t===`
2
+ `?(Ur++,Ut=0):t?Ut+=t.length:Ut++,t&&(oi+=t.length),t}var mh={default(){switch(be){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(),Fe("eof")}if(qe.isSpaceSeparator(be)){H();return}return mh[Ze]()},comment(){switch(be){case"*":H(),me="multiLineComment";return;case"/":H(),me="singleLineComment";return}throw Pe(H())},multiLineComment(){switch(be){case"*":H(),me="multiLineCommentAsterisk";return;case void 0:throw Pe(H())}H()},multiLineCommentAsterisk(){switch(be){case"*":H();return;case"/":H(),me="default";return;case void 0:throw Pe(H())}H(),me="multiLineComment"},singleLineComment(){switch(be){case`
4
+ `:case"\r":case"\u2028":case"\u2029":H(),me="default";return;case void 0:return H(),Fe("eof")}H()},value(){switch(be){case"{":case"[":return Fe("punctuator",H());case"n":return H(),an("ull"),Fe("null",null);case"t":return H(),an("rue"),Fe("boolean",!0);case"f":return H(),an("alse"),Fe("boolean",!1);case"-":case"+":H()==="-"&&(br=-1),me="sign";return;case".":fe=H(),me="decimalPointLeading";return;case"0":fe=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":fe=H(),me="decimalInteger";return;case"I":return H(),an("nfinity"),Fe("numeric",1/0);case"N":return H(),an("aN"),Fe("numeric",NaN);case'"':case"'":Ro=H()==='"',fe="",me="string";return}throw Pe(H())},identifierNameStartEscape(){if(be!=="u")throw Pe(H());H();let t=Wu();switch(t){case"$":case"_":break;default:if(!qe.isIdStartChar(t))throw ph();break}fe+=t,me="identifierName"},identifierName(){switch(be){case"$":case"_":case"\u200C":case"\u200D":fe+=H();return;case"\\":H(),me="identifierNameEscape";return}if(qe.isIdContinueChar(be)){fe+=H();return}return Fe("identifier",fe)},identifierNameEscape(){if(be!=="u")throw Pe(H());H();let t=Wu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!qe.isIdContinueChar(t))throw ph();break}fe+=t,me="identifierName"},sign(){switch(be){case".":fe=H(),me="decimalPointLeading";return;case"0":fe=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":fe=H(),me="decimalInteger";return;case"I":return H(),an("nfinity"),Fe("numeric",br*(1/0));case"N":return H(),an("aN"),Fe("numeric",NaN)}throw Pe(H())},zero(){switch(be){case".":fe+=H(),me="decimalPoint";return;case"e":case"E":fe+=H(),me="decimalExponent";return;case"x":case"X":fe+=H(),me="hexadecimal";return}return Fe("numeric",br*0)},decimalInteger(){switch(be){case".":fe+=H(),me="decimalPoint";return;case"e":case"E":fe+=H(),me="decimalExponent";return}if(qe.isDigit(be)){fe+=H();return}return Fe("numeric",br*Number(fe))},decimalPointLeading(){if(qe.isDigit(be)){fe+=H(),me="decimalFraction";return}throw Pe(H())},decimalPoint(){switch(be){case"e":case"E":fe+=H(),me="decimalExponent";return}if(qe.isDigit(be)){fe+=H(),me="decimalFraction";return}return Fe("numeric",br*Number(fe))},decimalFraction(){switch(be){case"e":case"E":fe+=H(),me="decimalExponent";return}if(qe.isDigit(be)){fe+=H();return}return Fe("numeric",br*Number(fe))},decimalExponent(){switch(be){case"+":case"-":fe+=H(),me="decimalExponentSign";return}if(qe.isDigit(be)){fe+=H(),me="decimalExponentInteger";return}throw Pe(H())},decimalExponentSign(){if(qe.isDigit(be)){fe+=H(),me="decimalExponentInteger";return}throw Pe(H())},decimalExponentInteger(){if(qe.isDigit(be)){fe+=H();return}return Fe("numeric",br*Number(fe))},hexadecimal(){if(qe.isHexDigit(be)){fe+=H(),me="hexadecimalInteger";return}throw Pe(H())},hexadecimalInteger(){if(qe.isHexDigit(be)){fe+=H();return}return Fe("numeric",br*Number(fe))},string(){switch(be){case"\\":H(),fe+=xb();return;case'"':if(Ro)return H(),Fe("string",fe);fe+=H();return;case"'":if(!Ro)return H(),Fe("string",fe);fe+=H();return;case`
5
+ `:case"\r":throw Pe(H());case"\u2028":case"\u2029":Pb(be);break;case void 0:throw Pe(H())}fe+=H()},start(){switch(be){case"{":case"[":return Fe("punctuator",H())}me="value"},beforePropertyName(){switch(be){case"$":case"_":fe=H(),me="identifierName";return;case"\\":H(),me="identifierNameStartEscape";return;case"}":return Fe("punctuator",H());case'"':case"'":Ro=H()==='"',me="string";return}if(qe.isIdStartChar(be)){fe+=H(),me="identifierName";return}throw Pe(H())},afterPropertyName(){if(be===":")return Fe("punctuator",H());throw Pe(H())},beforePropertyValue(){me="value"},afterPropertyValue(){switch(be){case",":case"}":return Fe("punctuator",H())}throw Pe(H())},beforeArrayValue(){if(be==="]")return Fe("punctuator",H());me="value"},afterArrayValue(){switch(be){case",":case"]":return Fe("punctuator",H())}throw Pe(H())},end(){throw Pe(H())}};function Fe(t,e){return{type:t,value:e,line:Ur,column:Ut}}function an(t){for(let e of t){if(wr()!==e)throw Pe(H());H()}}function xb(){switch(wr()){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(),qe.isDigit(wr()))throw Pe(H());return"\0";case"x":return H(),Ob();case"u":return H(),Wu();case`
7
+ `:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),wr()===`
8
+ `&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Pe(H());case void 0:throw Pe(H())}return H()}function Ob(){let t="",e=wr();if(!qe.isHexDigit(e)||(t+=H(),e=wr(),!qe.isHexDigit(e)))throw Pe(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function Wu(){let t="",e=4;for(;e-- >0;){let r=wr();if(!qe.isHexDigit(r))throw Pe(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var Fb={start(){if(ze.type==="eof")throw un();qu()},beforePropertyName(){switch(ze.type){case"identifier":case"string":Gu=ze.value,Ze="afterPropertyName";return;case"punctuator":ni();return;case"eof":throw un()}},afterPropertyName(){if(ze.type==="eof")throw un();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw un();qu()},beforeArrayValue(){if(ze.type==="eof")throw un();if(ze.type==="punctuator"&&ze.value==="]"){ni();return}qu()},afterPropertyValue(){if(ze.type==="eof")throw un();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":ni()}},afterArrayValue(){if(ze.type==="eof")throw un();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":ni()}},end(){}};function qu(){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(xo===void 0)xo=t;else{let e=Cr[Cr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,Gu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")Cr.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=Cr[Cr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function ni(){Cr.pop();let t=Cr[Cr.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Pe(t){return si(t===void 0?`JSON5: invalid end of input at ${Ur}:${Ut}`:`JSON5: invalid character '${gh(t)}' at ${Ur}:${Ut}`)}function un(){return si(`JSON5: invalid end of input at ${Ur}:${Ut}`)}function ph(){return Ut-=5,si(`JSON5: invalid identifier character at ${Ur}:${Ut}`)}function Pb(t){console.warn(`JSON5: '${gh(t)}' in strings is not valid ECMAScript; consider escaping`)}function gh(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 si(t){let e=new SyntaxError(t);return e.lineNumber=Ur,e.columnNumber=Ut,e}});var Ch=J((cD,bh)=>{var Ju=$u();bh.exports=function(e,r,n){let o=[],s="",a,c,l="",f;if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&(n=r.space,f=r.quote,r=r.replacer),typeof r=="function")c=r;else if(Array.isArray(r)){a=[];for(let b of r){let g;typeof b=="string"?g=b:(typeof b=="number"||b instanceof String||b instanceof Number)&&(g=String(b)),g!==void 0&&a.indexOf(g)<0&&a.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)),d("",{"":e});function d(b,g){let p=g[b];switch(p!=null&&(typeof p.toJSON5=="function"?p=p.toJSON5(b):typeof p.toJSON=="function"&&(p=p.toJSON(b))),c&&(p=c.call(g,b,p)),p instanceof Number?p=Number(p):p instanceof String?p=String(p):p instanceof Boolean&&(p=p.valueOf()),p){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof p=="string")return m(p,!1);if(typeof p=="number")return String(p);if(typeof p=="object")return Array.isArray(p)?A(p):C(p)}function m(b){let g={"'":.1,'"':.2},p={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},k="";for(let E=0;E<b.length;E++){let D=b[E];switch(D){case"'":case'"':g[D]++,k+=D;continue;case"\0":if(Ju.isDigit(b[E+1])){k+="\\x00";continue}}if(p[D]){k+=p[D];continue}if(D<" "){let F=D.charCodeAt(0).toString(16);k+="\\x"+("00"+F).substring(F.length);continue}k+=D}let y=f||Object.keys(g).reduce((E,D)=>g[E]<g[D]?E:D);return k=k.replace(new RegExp(y,"g"),p[y]),y+k+y}function C(b){if(o.indexOf(b)>=0)throw TypeError("Converting circular structure to JSON5");o.push(b);let g=s;s=s+l;let p=a||Object.keys(b),k=[];for(let E of p){let D=d(E,b);if(D!==void 0){let F=v(E)+":";l!==""&&(F+=" "),F+=D,k.push(F)}}let y;if(k.length===0)y="{}";else{let E;if(l==="")E=k.join(","),y="{"+E+"}";else{let D=`,
9
9
  `+s;E=k.join(D),y=`{
10
10
  `+s+E+`,
11
- `+g+"}"}}return o.pop(),s=g,y}function T(_){if(_.length===0)return p(_,!0);let g=String.fromCodePoint(_.codePointAt(0));if(!zu.isIdStartChar(g))return p(_,!0);for(let m=g.length;m<_.length;m++)if(!zu.isIdContinueChar(String.fromCodePoint(_.codePointAt(m))))return p(_,!0);return _}function S(_){if(o.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");o.push(_);let g=s;s=s+l;let m=[];for(let y=0;y<_.length;y++){let E=d(String(y),_);m.push(E!==void 0?E:"null")}let k;if(m.length===0)k="[]";else if(l==="")k="["+m.join(",")+"]";else{let y=`,
12
- `+s,E=m.join(y);k=`[
11
+ `+g+"}"}}return o.pop(),s=g,y}function v(b){if(b.length===0)return m(b,!0);let g=String.fromCodePoint(b.codePointAt(0));if(!Ju.isIdStartChar(g))return m(b,!0);for(let p=g.length;p<b.length;p++)if(!Ju.isIdContinueChar(String.fromCodePoint(b.codePointAt(p))))return m(b,!0);return b}function A(b){if(o.indexOf(b)>=0)throw TypeError("Converting circular structure to JSON5");o.push(b);let g=s;s=s+l;let p=[];for(let y=0;y<b.length;y++){let E=d(String(y),b);p.push(E!==void 0?E:"null")}let k;if(p.length===0)k="[]";else if(l==="")k="["+p.join(",")+"]";else{let y=`,
12
+ `+s,E=p.join(y);k=`[
13
13
  `+s+E+`,
14
- `+g+"]"}return o.pop(),s=g,k}}});var Hu=J((rD,mh)=>{var Tb=fh(),Db=ph(),Rb={parse:Tb,stringify:Db};mh.exports=Rb});var Xu=J((ND,qh)=>{"use strict";var ci=Object.prototype.hasOwnProperty,Uh=Object.prototype.toString,Ih=Object.defineProperty,Nh=Object.getOwnPropertyDescriptor,Bh=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Uh.call(e)==="[object Array]"},jh=function(e){if(!e||Uh.call(e)!=="[object Object]")return!1;var r=ci.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&ci.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var o;for(o in e);return typeof o>"u"||ci.call(e,o)},Lh=function(e,r){Ih&&r.name==="__proto__"?Ih(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Mh=function(e,r){if(r==="__proto__")if(ci.call(e,r)){if(Nh)return Nh(e,r).value}else return;return e[r]};qh.exports=function t(){var e,r,n,o,s,a,c=arguments[0],l=1,h=arguments.length,d=!1;for(typeof c=="boolean"&&(d=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=Mh(c,r),o=Mh(e,r),c!==o&&(d&&o&&(jh(o)||(s=Bh(o)))?(s?(s=!1,a=n&&Bh(n)?n:[]):a=n&&jh(n)?n:{},Lh(c,{name:r,newValue:t(d,a,o)})):typeof o<"u"&&Lh(c,{name:r,newValue:o}));return c}});var $h=J((BD,Hb)=>{Hb.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 Hh=J((jD,zh)=>{"use strict";var Wb=$h();zh.exports={pkg:Wb}});var tc=J(St=>{"use strict";var Gh=St&&St.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(St,"__esModule",{value:!0});St.GaxiosError=St.GAXIOS_ERROR_SYMBOL=void 0;St.defaultErrorRedactor=Jh;var Wh=Gh(Xu()),Gb=Gh(Hh()),Zu=Gb.default.pkg;St.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Zu.name}-gaxios-error`);var ec=class t extends Error{config;response;code;status;error;[St.GAXIOS_ERROR_SYMBOL]=Zu.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&St.GAXIOS_ERROR_SYMBOL in e&&e[St.GAXIOS_ERROR_SYMBOL]===Zu.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,o){if(super(e,{cause:o}),this.config=r,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Wh.default)(!0,{},r),this.response&&(this.response.config=(0,Wh.default)(!0,{},this.response.config)),this.response){try{this.response.data=Jb(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.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 o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="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 a=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&a.push(c.message);return Object.assign({message:a.join(`
15
- `)||n,code:s,status:o},e.data.error)}return Object.assign({message:n,code:s,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};St.GaxiosError=ec;function Jb(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 Jh(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function n(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let c=s[a];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&s.set(c,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(t.config,"body"),o(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&&(Jh({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var Kh=J(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.getRetryConfig=Vb;async function Vb(t){let e=Vh(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||Kb)(t))return{shouldRetry:!1,config:t.config};let o=Yb(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function Kb(t){let e=Vh(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,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=n&&s<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Vh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Yb(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 oc=J(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.GaxiosInterceptorManager=void 0;var nc=class extends Set{};li.GaxiosInterceptorManager=nc});var Qh=J((qD,Yh)=>{var Mn=1e3,Un=Mn*60,qn=Un*60,ln=qn*24,Qb=ln*7,Xb=ln*365.25;Yh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return Zb(t);if(r==="number"&&isFinite(t))return e.long?tC(t):eC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Zb(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*Xb;case"weeks":case"week":case"w":return r*Qb;case"days":case"day":case"d":return r*ln;case"hours":case"hour":case"hrs":case"hr":case"h":return r*qn;case"minutes":case"minute":case"mins":case"min":case"m":return r*Un;case"seconds":case"second":case"secs":case"sec":case"s":return r*Mn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function eC(t){var e=Math.abs(t);return e>=ln?Math.round(t/ln)+"d":e>=qn?Math.round(t/qn)+"h":e>=Un?Math.round(t/Un)+"m":e>=Mn?Math.round(t/Mn)+"s":t+"ms"}function tC(t){var e=Math.abs(t);return e>=ln?di(t,e,ln,"day"):e>=qn?di(t,e,qn,"hour"):e>=Un?di(t,e,Un,"minute"):e>=Mn?di(t,e,Mn,"second"):t+" ms"}function di(t,e,r,n){var o=e>=r*1.5;return Math.round(t/r)+" "+n+(o?"s":"")}});var sc=J(($D,Xh)=>{function rC(t){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=o,r.enabled=c,r.humanize=Qh(),r.destroy=h,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let p=0;for(let w=0;w<d.length;w++)p=(p<<5)-p+d.charCodeAt(w),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(d){let p,w=null,T,S;function _(...g){if(!_.enabled)return;let m=_,k=Number(new Date),y=k-(p||k);m.diff=y,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,(F,$)=>{if(F==="%%")return"%";E++;let V=r.formatters[$];if(typeof V=="function"){let B=g[E];F=V.call(m,B),g.splice(E,1),E--}return F}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return _.namespace=d,_.useColors=r.useColors(),_.color=r.selectColor(d),_.extend=n,_.destroy=r.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>w!==null?w:(T!==r.namespaces&&(T=r.namespaces,S=r.enabled(d)),S),set:g=>{w=g}}),typeof r.init=="function"&&r.init(_),_}function n(d,p){let w=r(this.namespace+(typeof p>"u"?":":p)+d);return w.log=this.log,w}function o(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let w of p)w[0]==="-"?r.skips.push(w.slice(1)):r.names.push(w)}function s(d,p){let w=0,T=0,S=-1,_=0;for(;w<d.length;)if(T<p.length&&(p[T]===d[w]||p[T]==="*"))p[T]==="*"?(S=T,_=w,T++):(w++,T++);else if(S!==-1)T=S+1,_++,w=_;else return!1;for(;T<p.length&&p[T]==="*";)T++;return T===p.length}function a(){let d=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),d}function c(d){for(let p of r.skips)if(s(d,p))return!1;for(let p of r.names)if(s(d,p))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}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}Xh.exports=rC});var Zh=J((ot,fi)=>{ot.formatArgs=oC;ot.save=sC;ot.load=iC;ot.useColors=nC;ot.storage=aC();ot.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`."))}})();ot.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 nC(){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 oC(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+fi.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,o=>{o!=="%%"&&(r++,o==="%c"&&(n=r))}),t.splice(n,0,e)}ot.log=console.debug||console.log||(()=>{});function sC(t){try{t?ot.storage.setItem("debug",t):ot.storage.removeItem("debug")}catch{}}function iC(){let t;try{t=ot.storage.getItem("debug")||ot.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function aC(){try{return localStorage}catch{}}fi.exports=sc()(ot);var{formatters:uC}=fi.exports;uC.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var tp=J((zD,ep)=>{"use strict";ep.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}});var op=J((HD,np)=>{"use strict";var cC=require("os"),rp=require("tty"),kt=tp(),{env:He}=process,Ur;kt("no-color")||kt("no-colors")||kt("color=false")||kt("color=never")?Ur=0:(kt("color")||kt("colors")||kt("color=true")||kt("color=always"))&&(Ur=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?Ur=1:He.FORCE_COLOR==="false"?Ur=0:Ur=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function ic(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function ac(t,e){if(Ur===0)return 0;if(kt("color=16m")||kt("color=full")||kt("color=truecolor"))return 3;if(kt("color=256"))return 2;if(t&&!e&&Ur===void 0)return 0;let r=Ur||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=cC.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 lC(t){let e=ac(t,t&&t.isTTY);return ic(e)}np.exports={supportsColor:lC,stdout:ic(ac(!0,rp.isatty(1))),stderr:ic(ac(!0,rp.isatty(2)))}});var ip=J((We,pi)=>{var dC=require("tty"),hi=require("util");We.init=_C;We.log=mC;We.formatArgs=hC;We.save=gC;We.load=yC;We.useColors=fC;We.destroy=hi.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=op();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,(o,s)=>s.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 fC(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:dC.isatty(process.stderr.fd)}function hC(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
14
+ `+g+"]"}return o.pop(),s=g,k}}});var Vu=J((lD,wh)=>{var Ib=_h(),Nb=Ch(),Bb={parse:Ib,stringify:Nb};wh.exports=Bb});var Dh={};ti(Dh,{getFallbackPromotionStore:()=>Fo,resetFallbackPromotionStore:()=>Lb});function Fo(t){return ln||(ln=new Yu,t&&ln.configure(t)),ln}function Lb(){ln&&(ln.clearAll(),ln=null)}var jb,Yu,ln,ii=Ne(()=>{"use strict";Un();jb=600*1e3,Yu=class{promotions=new Map;enabled=!0;ttlMs=jb;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,r,n){return`${e},${r}:${n}`}promote(e,r,n,o,s,a){if(!this.enabled)return;let c=this.getKey(e,r,n),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,r,n,o){if(!this.enabled)return null;let s=this.getKey(e,r,n),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...f]=a.promotedModel.split(","),d=f.join(",");if(!st().isAvailable(l,d))return this.promotions.delete(s),null;let C=o.find(A=>A.name.toLowerCase()===l.toLowerCase()),v=C?.models?.find(A=>String(A).toLowerCase()===d.toLowerCase());return!C||!v?(this.promotions.delete(s),null):`${C.name},${v}`}clear(e,r,n){let o=this.getKey(e,r,n);this.promotions.delete(o)}clearByPrimary(e,r){let n=`${e},${r}:`,o=0;for(let s of this.promotions.keys())s.startsWith(n)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[r,n]of this.promotions)e-n.timestamp>=n.ttlMs&&this.promotions.delete(r)}getAllPromotions(){let e=Date.now(),r=[];for(let[n,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&r.push({key:n,promotedModel:o.promotedModel,remainingMs:s})}return r}},ln=null});function st(t){return Qu||(Qu=new Po(t)),Qu}var Ub,Po,Qu,Un=Ne(()=>{"use strict";Ub={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},Po=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ub,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),o=this.states.get(n);o&&(o.successCount++,o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,r),this.states.delete(n)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0))}clearPromotionsForPrimary(e,r){try{let{getFallbackPromotionStore:n}=(ii(),dh(Dh));n().clearByPrimary(e,r)}catch{}}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 o=this.getKey(e,r),s=this.states.get(o);s||(s={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=n;let c=this.isRateLimitError(n)?this.config.rateLimitThreshold:this.config.failureThreshold;s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=c&&(s.status="open",s.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}forceOpen(e,r,n){if(!this.config.enabled)return;let o=this.getKey(e,r),s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=n,s.lastProbeTime=0):(s={provider:e,model:r,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:n},this.states.set(o,s))}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,r){let n=this.getKey(e,r),o=this.states.get(n);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Qu=null});var nc=J((WD,Vh)=>{"use strict";var pi=Object.prototype.hasOwnProperty,Jh=Object.prototype.toString,$h=Object.defineProperty,qh=Object.getOwnPropertyDescriptor,zh=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Jh.call(e)==="[object Array]"},Hh=function(e){if(!e||Jh.call(e)!=="[object Object]")return!1;var r=pi.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&pi.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var o;for(o in e);return typeof o>"u"||pi.call(e,o)},Wh=function(e,r){$h&&r.name==="__proto__"?$h(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Gh=function(e,r){if(r==="__proto__")if(pi.call(e,r)){if(qh)return qh(e,r).value}else return;return e[r]};Vh.exports=function t(){var e,r,n,o,s,a,c=arguments[0],l=1,f=arguments.length,d=!1;for(typeof c=="boolean"&&(d=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<f;++l)if(e=arguments[l],e!=null)for(r in e)n=Gh(c,r),o=Gh(e,r),c!==o&&(d&&o&&(Hh(o)||(s=zh(o)))?(s?(s=!1,a=n&&zh(n)?n:[]):a=n&&Hh(n)?n:{},Wh(c,{name:r,newValue:t(d,a,o)})):typeof o<"u"&&Wh(c,{name:r,newValue:o}));return c}});var Kh=J((GD,Zb)=>{Zb.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 Qh=J((JD,Yh)=>{"use strict";var eC=Kh();Yh.exports={pkg:eC}});var ic=J(vt=>{"use strict";var Zh=vt&&vt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vt,"__esModule",{value:!0});vt.GaxiosError=vt.GAXIOS_ERROR_SYMBOL=void 0;vt.defaultErrorRedactor=ep;var Xh=Zh(nc()),tC=Zh(Qh()),oc=tC.default.pkg;vt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${oc.name}-gaxios-error`);var sc=class t extends Error{config;response;code;status;error;[vt.GAXIOS_ERROR_SYMBOL]=oc.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&vt.GAXIOS_ERROR_SYMBOL in e&&e[vt.GAXIOS_ERROR_SYMBOL]===oc.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,o){if(super(e,{cause:o}),this.config=r,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Xh.default)(!0,{},r),this.response&&(this.response.config=(0,Xh.default)(!0,{},this.response.config)),this.response){try{this.response.data=rC(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.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 o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="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 a=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&a.push(c.message);return Object.assign({message:a.join(`
15
+ `)||n,code:s,status:o},e.data.error)}return Object.assign({message:n,code:s,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};vt.GaxiosError=sc;function rC(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 ep(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function n(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let c=s[a];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&s.set(c,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(t.config,"body"),o(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&&(ep({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var rp=J(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.getRetryConfig=nC;async function nC(t){let e=tp(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||oC)(t))return{shouldRetry:!1,config:t.config};let o=sC(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function oC(t){let e=tp(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,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=n&&s<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function tp(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function sC(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 cc=J(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.GaxiosInterceptorManager=void 0;var uc=class extends Set{};mi.GaxiosInterceptorManager=uc});var op=J((QD,np)=>{var qn=1e3,zn=qn*60,Hn=zn*60,fn=Hn*24,iC=fn*7,aC=fn*365.25;np.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return uC(t);if(r==="number"&&isFinite(t))return e.long?lC(t):cC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function uC(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*aC;case"weeks":case"week":case"w":return r*iC;case"days":case"day":case"d":return r*fn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Hn;case"minutes":case"minute":case"mins":case"min":case"m":return r*zn;case"seconds":case"second":case"secs":case"sec":case"s":return r*qn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function cC(t){var e=Math.abs(t);return e>=fn?Math.round(t/fn)+"d":e>=Hn?Math.round(t/Hn)+"h":e>=zn?Math.round(t/zn)+"m":e>=qn?Math.round(t/qn)+"s":t+"ms"}function lC(t){var e=Math.abs(t);return e>=fn?gi(t,e,fn,"day"):e>=Hn?gi(t,e,Hn,"hour"):e>=zn?gi(t,e,zn,"minute"):e>=qn?gi(t,e,qn,"second"):t+" ms"}function gi(t,e,r,n){var o=e>=r*1.5;return Math.round(t/r)+" "+n+(o?"s":"")}});var lc=J((XD,sp)=>{function dC(t){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=o,r.enabled=c,r.humanize=op(),r.destroy=f,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let m=0;for(let C=0;C<d.length;C++)m=(m<<5)-m+d.charCodeAt(C),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=e;function r(d){let m,C=null,v,A;function b(...g){if(!b.enabled)return;let p=b,k=Number(new Date),y=k-(m||k);p.diff=y,p.prev=m,p.curr=k,m=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,(F,q)=>{if(F==="%%")return"%";E++;let V=r.formatters[q];if(typeof V=="function"){let B=g[E];F=V.call(p,B),g.splice(E,1),E--}return F}),r.formatArgs.call(p,g),(p.log||r.log).apply(p,g)}return b.namespace=d,b.useColors=r.useColors(),b.color=r.selectColor(d),b.extend=n,b.destroy=r.destroy,Object.defineProperty(b,"enabled",{enumerable:!0,configurable:!1,get:()=>C!==null?C:(v!==r.namespaces&&(v=r.namespaces,A=r.enabled(d)),A),set:g=>{C=g}}),typeof r.init=="function"&&r.init(b),b}function n(d,m){let C=r(this.namespace+(typeof m>"u"?":":m)+d);return C.log=this.log,C}function o(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let m=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let C of m)C[0]==="-"?r.skips.push(C.slice(1)):r.names.push(C)}function s(d,m){let C=0,v=0,A=-1,b=0;for(;C<d.length;)if(v<m.length&&(m[v]===d[C]||m[v]==="*"))m[v]==="*"?(A=v,b=C,v++):(C++,v++);else if(A!==-1)v=A+1,b++,C=b;else return!1;for(;v<m.length&&m[v]==="*";)v++;return v===m.length}function a(){let d=[...r.names,...r.skips.map(m=>"-"+m)].join(",");return r.enable(""),d}function c(d){for(let m of r.skips)if(s(d,m))return!1;for(let m of r.names)if(s(d,m))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function f(){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}sp.exports=dC});var ip=J((it,yi)=>{it.formatArgs=hC;it.save=pC;it.load=mC;it.useColors=fC;it.storage=gC();it.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`."))}})();it.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 fC(){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 hC(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+yi.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,o=>{o!=="%%"&&(r++,o==="%c"&&(n=r))}),t.splice(n,0,e)}it.log=console.debug||console.log||(()=>{});function pC(t){try{t?it.storage.setItem("debug",t):it.storage.removeItem("debug")}catch{}}function mC(){let t;try{t=it.storage.getItem("debug")||it.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function gC(){try{return localStorage}catch{}}yi.exports=lc()(it);var{formatters:yC}=yi.exports;yC.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var up=J((ZD,ap)=>{"use strict";ap.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}});var dp=J((eR,lp)=>{"use strict";var _C=require("os"),cp=require("tty"),Tt=up(),{env:He}=process,$r;Tt("no-color")||Tt("no-colors")||Tt("color=false")||Tt("color=never")?$r=0:(Tt("color")||Tt("colors")||Tt("color=true")||Tt("color=always"))&&($r=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?$r=1:He.FORCE_COLOR==="false"?$r=0:$r=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function dc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function fc(t,e){if($r===0)return 0;if(Tt("color=16m")||Tt("color=full")||Tt("color=truecolor"))return 3;if(Tt("color=256"))return 2;if(t&&!e&&$r===void 0)return 0;let r=$r||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=_C.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 bC(t){let e=fc(t,t&&t.isTTY);return dc(e)}lp.exports={supportsColor:bC,stdout:dc(fc(!0,cp.isatty(1))),stderr:dc(fc(!0,cp.isatty(2)))}});var hp=J((We,bi)=>{var CC=require("tty"),_i=require("util");We.init=TC;We.log=SC;We.formatArgs=EC;We.save=kC;We.load=vC;We.useColors=wC;We.destroy=_i.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=dp();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,(o,s)=>s.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 wC(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:CC.isatty(process.stderr.fd)}function EC(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
16
16
  `).join(`
17
- `+s),t.push(o+"m+"+pi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=pC()+e+" "+t[0]}function pC(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function mC(...t){return process.stderr.write(hi.formatWithOptions(We.inspectOpts,...t)+`
18
- `)}function gC(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function yC(){return process.env.DEBUG}function _C(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]]}pi.exports=sc()(We);var{formatters:sp}=pi.exports;sp.o=function(t){return this.inspectOpts.colors=this.useColors,hi.inspect(t,this.inspectOpts).split(`
19
- `).map(e=>e.trim()).join(" ")};sp.O=function(t){return this.inspectOpts.colors=this.useColors,hi.inspect(t,this.inspectOpts)}});var cc=J((WD,uc)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?uc.exports=Zh():uc.exports=ip()});var cp=J(st=>{"use strict";var bC=st&&st.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),CC=st&&st.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ap=st&&st.__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)&&bC(e,t,r);return CC(e,t),e};Object.defineProperty(st,"__esModule",{value:!0});st.req=st.json=st.toBuffer=void 0;var wC=ap(require("http")),EC=ap(require("https"));async function up(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}st.toBuffer=up;async function AC(t){let r=(await up(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let o=n;throw o.message+=` (input: ${r})`,o}}st.json=AC;function SC(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?EC:wC).request(t,e),o=new Promise((s,a)=>{n.once("response",s).once("error",a).end()});return n.then=o.then.bind(o),n}st.req=SC});var hp=J(lt=>{"use strict";var dp=lt&&lt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),kC=lt&&lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fp=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)&&dp(e,t,r);return kC(e,t),e},vC=lt&&lt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&dp(e,t,r)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var TC=fp(require("net")),lp=fp(require("http")),DC=require("https");vC(cp(),lt);var Xt=Symbol("AgentBaseInternalState"),lc=class extends lp.Agent{constructor(e){super(e),this[Xt]={}}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 TC.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],o=n.indexOf(r);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?DC.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let o={...r,secureEndpoint:this.isSecureEndpoint(r)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof lp.Agent)try{return c.addRequest(e,o)}catch(l){return n(l)}this[Xt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(s,a),n(c)})}createConnection(){let e=this[Xt].currentSocket;if(this[Xt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Xt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Xt]&&(this[Xt].defaultPort=e)}get protocol(){return this[Xt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Xt]&&(this[Xt].protocol=e)}};lt.Agent=lc});var pp=J($n=>{"use strict";var RC=$n&&$n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty($n,"__esModule",{value:!0});$n.parseProxyResponse=void 0;var xC=RC(cc()),mi=(0,xC.default)("https-proxy-agent:parse-proxy-response");function OC(t){return new Promise((e,r)=>{let n=0,o=[];function s(){let d=t.read();d?h(d):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),mi("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),mi("onerror %o",d),r(d)}function h(d){o.push(d),n+=d.length;let p=Buffer.concat(o,n),w=p.indexOf(`\r
17
+ `+s),t.push(o+"m+"+bi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=AC()+e+" "+t[0]}function AC(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function SC(...t){return process.stderr.write(_i.formatWithOptions(We.inspectOpts,...t)+`
18
+ `)}function kC(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function vC(){return process.env.DEBUG}function TC(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]]}bi.exports=lc()(We);var{formatters:fp}=bi.exports;fp.o=function(t){return this.inspectOpts.colors=this.useColors,_i.inspect(t,this.inspectOpts).split(`
19
+ `).map(e=>e.trim()).join(" ")};fp.O=function(t){return this.inspectOpts.colors=this.useColors,_i.inspect(t,this.inspectOpts)}});var pc=J((tR,hc)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?hc.exports=ip():hc.exports=hp()});var gp=J(at=>{"use strict";var DC=at&&at.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),RC=at&&at.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pp=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)&&DC(e,t,r);return RC(e,t),e};Object.defineProperty(at,"__esModule",{value:!0});at.req=at.json=at.toBuffer=void 0;var xC=pp(require("http")),OC=pp(require("https"));async function mp(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}at.toBuffer=mp;async function FC(t){let r=(await mp(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let o=n;throw o.message+=` (input: ${r})`,o}}at.json=FC;function PC(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?OC:xC).request(t,e),o=new Promise((s,a)=>{n.once("response",s).once("error",a).end()});return n.then=o.then.bind(o),n}at.req=PC});var Cp=J(ht=>{"use strict";var _p=ht&&ht.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),IC=ht&&ht.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),bp=ht&&ht.__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)&&_p(e,t,r);return IC(e,t),e},NC=ht&&ht.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_p(e,t,r)};Object.defineProperty(ht,"__esModule",{value:!0});ht.Agent=void 0;var BC=bp(require("net")),yp=bp(require("http")),MC=require("https");NC(gp(),ht);var Zt=Symbol("AgentBaseInternalState"),mc=class extends yp.Agent{constructor(e){super(e),this[Zt]={}}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 BC.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],o=n.indexOf(r);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?MC.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let o={...r,secureEndpoint:this.isSecureEndpoint(r)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof yp.Agent)try{return c.addRequest(e,o)}catch(l){return n(l)}this[Zt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(s,a),n(c)})}createConnection(){let e=this[Zt].currentSocket;if(this[Zt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Zt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Zt]&&(this[Zt].defaultPort=e)}get protocol(){return this[Zt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Zt]&&(this[Zt].protocol=e)}};ht.Agent=mc});var wp=J(Wn=>{"use strict";var jC=Wn&&Wn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Wn,"__esModule",{value:!0});Wn.parseProxyResponse=void 0;var LC=jC(pc()),Ci=(0,LC.default)("https-proxy-agent:parse-proxy-response");function UC(t){return new Promise((e,r)=>{let n=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),Ci("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),Ci("onerror %o",d),r(d)}function f(d){o.push(d),n+=d.length;let m=Buffer.concat(o,n),C=m.indexOf(`\r
21
21
  \r
22
- `);if(w===-1){mi("have not received end of HTTP headers yet..."),s();return}let T=p.slice(0,w).toString("ascii").split(`\r
23
- `),S=T.shift();if(!S)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let _=S.split(" "),g=+_[1],m=_.slice(2).join(" "),k={};for(let y of T){if(!y)continue;let E=y.indexOf(":");if(E===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${y}"`));let D=y.slice(0,E).toLowerCase(),F=y.slice(E+1).trimStart(),$=k[D];typeof $=="string"?k[D]=[$,F]:Array.isArray($)?$.push(F):k[D]=F}mi("got proxy server response: %o %o",S,k),a(),e({connect:{statusCode:g,statusText:m,headers:k},buffered:p})}t.on("error",l),t.on("end",c),s()})}$n.parseProxyResponse=OC});var Cp=J(vt=>{"use strict";var FC=vt&&vt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),PC=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_p=vt&&vt.__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)&&FC(e,t,r);return PC(e,t),e},bp=vt&&vt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vt,"__esModule",{value:!0});vt.HttpsProxyAgent=void 0;var gi=_p(require("net")),mp=_p(require("tls")),IC=bp(require("assert")),NC=bp(cc()),BC=hp(),jC=require("url"),LC=pp(),Po=(0,NC.default)("https-proxy-agent"),gp=t=>t.servername===void 0&&t.host&&!gi.isIP(t.host)?{...t,servername:t.host}:t,yi=class extends BC.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new jC.URL(e):e,this.proxyHeaders=r?.headers??{},Po("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...r?yp(r,"headers"):null,host:n,port:o}}async connect(e,r){let{proxy:n}=this;if(!r.host)throw new TypeError('No "host" provided');let o;n.protocol==="https:"?(Po("Creating `tls.Socket`: %o",this.connectOpts),o=mp.connect(gp(this.connectOpts))):(Po("Creating `net.Socket`: %o",this.connectOpts),o=gi.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=gi.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${a}:${r.port} HTTP/1.1\r
24
- `;if(n.username||n.password){let w=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(w).toString("base64")}`}s.Host=`${a}:${r.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let w of Object.keys(s))c+=`${w}: ${s[w]}\r
25
- `;let l=(0,LC.parseProxyResponse)(o);o.write(`${c}\r
26
- `);let{connect:h,buffered:d}=await l;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",MC),r.secureEndpoint?(Po("Upgrading socket connection to TLS"),mp.connect({...yp(gp(r),"host","path","port"),socket:o})):o;o.destroy();let p=new gi.Socket({writable:!1});return p.readable=!0,e.once("socket",w=>{Po("Replaying proxy buffer for failed request"),(0,IC.default)(w.listenerCount("data")>0),w.push(d),w.push(null)}),p}};yi.protocols=["http","https"];vt.HttpsProxyAgent=yi;function MC(t){t.resume()}function yp(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function UC(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="",o=!1,s=r[0]||"text/plain",a=s;for(let d=1;d<r.length;d++)r[d]==="base64"?o=!0:r[d]&&(a+=`;${r[d]}`,r[d].indexOf("charset=")===0&&(n=r[d].substring(8)));!r[0]&&!n.length&&(a+=";charset=US-ASCII",n="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),h=Buffer.from(l,c);return h.type=s,h.typeFull=a,h.charset=n,h}var wp,Ep=Be(()=>{wp=UC});var Sp=J((_i,Ap)=>{(function(t,e){typeof _i=="object"&&typeof Ap<"u"?e(_i):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(_i,(function(t){"use strict";function e(){}function r(i){return typeof i=="object"&&i!==null||typeof i=="function"}let n=e;function o(i,u){try{Object.defineProperty(i,"name",{value:u,configurable:!0})}catch{}}let s=Promise,a=Promise.prototype.then,c=Promise.reject.bind(s);function l(i){return new s(i)}function h(i){return l(u=>u(i))}function d(i){return c(i)}function p(i,u,f){return a.call(i,u,f)}function w(i,u,f){p(p(i,u,f),void 0,n)}function T(i,u){w(i,u)}function S(i,u){w(i,void 0,u)}function _(i,u,f){return p(i,u,f)}function g(i){p(i,void 0,n)}let m=i=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let u=h(void 0);m=f=>p(u,f)}return m(i)};function k(i,u,f){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,f)}function y(i,u,f){try{return h(k(i,u,f))}catch(C){return d(C)}}let E=16384;class D{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(u){let f=this._back,C=f;f._elements.length===E-1&&(C={_elements:[],_next:void 0}),f._elements.push(u),C!==f&&(this._back=C,f._next=C),++this._size}shift(){let u=this._front,f=u,C=this._cursor,R=C+1,M=u._elements,q=M[C];return R===E&&(f=u._next,R=0),--this._size,this._cursor=R,u!==f&&(this._front=f),M[C]=void 0,q}forEach(u){let f=this._cursor,C=this._front,R=C._elements;for(;(f!==R.length||C._next!==void 0)&&!(f===R.length&&(C=C._next,R=C._elements,f=0,R.length===0));)u(R[f]),++f}peek(){let u=this._front,f=this._cursor;return u._elements[f]}}let F=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),V=Symbol("[[CancelSteps]]"),B=Symbol("[[PullSteps]]"),Y=Symbol("[[ReleaseSteps]]");function te(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?Ee(i):u._state==="closed"?pe(i):se(i,u._storedError)}function Z(i,u){let f=i._ownerReadableStream;return Bt(f,u)}function ue(i){let u=i._ownerReadableStream;u._state==="readable"?G(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[Y](),u._reader=void 0,i._ownerReadableStream=void 0}function he(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function Ee(i){i._closedPromise=l((u,f)=>{i._closedPromise_resolve=u,i._closedPromise_reject=f})}function se(i,u){Ee(i),G(i,u)}function pe(i){Ee(i),ae(i)}function G(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function K(i,u){se(i,u)}function ae(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let qe=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},ve=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function W(i){return typeof i=="object"||typeof i=="function"}function le(i,u){if(i!==void 0&&!W(i))throw new TypeError(`${u} is not an object.`)}function ye(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}function It(i){return typeof i=="object"&&i!==null||typeof i=="function"}function De(i,u){if(!It(i))throw new TypeError(`${u} is not an object.`)}function Ne(i,u,f){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${f}'.`)}function b(i,u,f){if(i===void 0)throw new TypeError(`${u} is required in '${f}'.`)}function A(i){return Number(i)}function v(i){return i===0?0:i}function j(i){return v(ve(i))}function O(i,u){let C=Number.MAX_SAFE_INTEGER,R=Number(i);if(R=v(R),!qe(R))throw new TypeError(`${u} is not a finite number`);if(R=j(R),R<0||R>C)throw new TypeError(`${u} is outside the accepted range of 0 to ${C}, inclusive`);return!qe(R)||R===0?0:R}function I(i,u){if(!Nr(i))throw new TypeError(`${u} is not a ReadableStream.`)}function U(i){return new z(i)}function x(i,u){i._reader._readRequests.push(u)}function P(i,u,f){let R=i._reader._readRequests.shift();f?R._closeSteps():R._chunkSteps(u)}function L(i){return i._reader._readRequests.length}function N(i){let u=i._reader;return!(u===void 0||!X(u))}class z{constructor(u){if(Ne(u,1,"ReadableStreamDefaultReader"),I(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");te(this,u),this._readRequests=new D}get closed(){return X(this)?this._closedPromise:d(Ie("closed"))}cancel(u=void 0){return X(this)?this._ownerReadableStream===void 0?d(he("cancel")):Z(this,u):d(Ie("cancel"))}read(){if(!X(this))return d(Ie("read"));if(this._ownerReadableStream===void 0)return d(he("read from"));let u,f,C=l((M,q)=>{u=M,f=q});return ee(this,{_chunkSteps:M=>u({value:M,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:M=>f(M)}),C}releaseLock(){if(!X(this))throw Ie("releaseLock");this._ownerReadableStream!==void 0&&we(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(z.prototype.cancel,"cancel"),o(z.prototype.read,"read"),o(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function X(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof z}function ee(i,u){let f=i._ownerReadableStream;f._disturbed=!0,f._state==="closed"?u._closeSteps():f._state==="errored"?u._errorSteps(f._storedError):f._readableStreamController[B](u)}function we(i){ue(i);let u=new TypeError("Reader was released");Oe(i,u)}function Oe(i,u){let f=i._readRequests;i._readRequests=new D,f.forEach(C=>{C._errorSteps(u)})}function Ie(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let Ce=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Ae{constructor(u,f){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=f}next(){let u=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?_(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let f=()=>this._returnSteps(u);return this._ongoingPromise?_(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,f,C,R=l((q,Q)=>{f=q,C=Q});return ee(u,{_chunkSteps:q=>{this._ongoingPromise=void 0,m(()=>f({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),f({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),C(q)}}),R}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let C=Z(f,u);return ue(f),_(C,()=>({value:u,done:!0}))}return ue(f),h({value:u,done:!0})}}let Me={next(){return kn(this)?this._asyncIteratorImpl.next():d(vn("next"))},return(i){return kn(this)?this._asyncIteratorImpl.return(i):d(vn("return"))}};Object.setPrototypeOf(Me,Ce);function Sn(i,u){let f=U(i),C=new Ae(f,u),R=Object.create(Me);return R._asyncIteratorImpl=C,R}function kn(i){if(!r(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Ae}catch{return!1}}function vn(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(i){return i!==i};var dr,Ke,Ue;function Se(i){return i.slice()}function rf(i,u,f,C,R){new Uint8Array(i).set(new Uint8Array(f,C,R),u)}let fr=i=>(typeof i.transfer=="function"?fr=u=>u.transfer():typeof structuredClone=="function"?fr=u=>structuredClone(u,{transfer:[u]}):fr=u=>u,fr(i)),Or=i=>(typeof i.detached=="boolean"?Or=u=>u.detached:Or=u=>u.byteLength===0,Or(i));function nf(i,u,f){if(i.slice)return i.slice(u,f);let C=f-u,R=new ArrayBuffer(C);return rf(R,0,i,u,C),R}function Ss(i,u){let f=i[u];if(f!=null){if(typeof f!="function")throw new TypeError(`${String(u)} is not a function`);return f}}function N0(i){let u={[Symbol.iterator]:()=>i.iterator},f=(async function*(){return yield*u})(),C=f.next;return{iterator:f,nextMethod:C,done:!1}}let uu=(Ue=(dr=Symbol.asyncIterator)!==null&&dr!==void 0?dr:(Ke=Symbol.for)===null||Ke===void 0?void 0:Ke.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function of(i,u="sync",f){if(f===void 0)if(u==="async"){if(f=Ss(i,uu),f===void 0){let M=Ss(i,Symbol.iterator),q=of(i,"sync",M);return N0(q)}}else f=Ss(i,Symbol.iterator);if(f===void 0)throw new TypeError("The object is not iterable");let C=k(f,i,[]);if(!r(C))throw new TypeError("The iterator method must return an object");let R=C.next;return{iterator:C,nextMethod:R,done:!1}}function B0(i){let u=k(i.nextMethod,i.iterator,[]);if(!r(u))throw new TypeError("The iterator.next() method must return an object");return u}function j0(i){return!!i.done}function L0(i){return i.value}function M0(i){return!(typeof i!="number"||ut(i)||i<0)}function sf(i){let u=nf(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function cu(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function lu(i,u,f){if(!M0(f)||f===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:u,size:f}),i._queueTotalSize+=f}function U0(i){return i._queue.peek().value}function Fr(i){i._queue=new D,i._queueTotalSize=0}function af(i){return i===DataView}function q0(i){return af(i.constructor)}function $0(i){return af(i)?1:i.BYTES_PER_ELEMENT}class Qr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!du(this))throw gu("view");return this._view}respond(u){if(!du(this))throw gu("respond");if(Ne(u,1,"respond"),u=O(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Or(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ds(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!du(this))throw gu("respondWithNewView");if(Ne(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))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(Or(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Rs(this._associatedReadableByteStreamController,u)}}Object.defineProperties(Qr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(Qr.prototype.respond,"respond"),o(Qr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Qr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class hr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Xr(this))throw Co("byobRequest");return mu(this)}get desiredSize(){if(!Xr(this))throw Co("desiredSize");return yf(this)}close(){if(!Xr(this))throw Co("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw new TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);bo(this)}enqueue(u){if(!Xr(this))throw Co("enqueue");if(Ne(u,1,"enqueue"),!ArrayBuffer.isView(u))throw new TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(u.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 f=this._controlledReadableByteStream._state;if(f!=="readable")throw new TypeError(`The stream (in ${f} state) is not in the readable state and cannot be enqueued to`);Ts(this,u)}error(u=void 0){if(!Xr(this))throw Co("error");wt(this,u)}[V](u){uf(this),Fr(this);let f=this._cancelAlgorithm(u);return vs(this),f}[B](u){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){gf(this,u);return}let C=this._autoAllocateChunkSize;if(C!==void 0){let R;try{R=new ArrayBuffer(C)}catch(q){u._errorSteps(q);return}let M={buffer:R,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(M)}x(f,u),Zr(this)}[Y](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new D,this._pendingPullIntos.push(u)}}}Object.defineProperties(hr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(hr.prototype.close,"close"),o(hr.prototype.enqueue,"enqueue"),o(hr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Xr(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof hr}function du(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof Qr}function Zr(i){if(!J0(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let f=i._pullAlgorithm();w(f,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Zr(i)),null),C=>(wt(i,C),null))}function uf(i){hu(i),i._pendingPullIntos=new D}function fu(i,u){let f=!1;i._state==="closed"&&(f=!0);let C=cf(u);u.readerType==="default"?P(i,C,f):Z0(i,C,f)}function cf(i){let u=i.bytesFilled,f=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/f)}function ks(i,u,f,C){i._queue.push({buffer:u,byteOffset:f,byteLength:C}),i._queueTotalSize+=C}function lf(i,u,f,C){let R;try{R=nf(u,f,f+C)}catch(M){throw wt(i,M),M}ks(i,R,0,C)}function df(i,u){u.bytesFilled>0&&lf(i,u.buffer,u.byteOffset,u.bytesFilled),Tn(i)}function ff(i,u){let f=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),C=u.bytesFilled+f,R=f,M=!1,q=C%u.elementSize,Q=C-q;Q>=u.minimumFill&&(R=Q-u.bytesFilled,M=!0);let ce=i._queue;for(;R>0;){let ne=ce.peek(),de=Math.min(R,ne.byteLength),ge=u.byteOffset+u.bytesFilled;rf(u.buffer,ge,ne.buffer,ne.byteOffset,de),ne.byteLength===de?ce.shift():(ne.byteOffset+=de,ne.byteLength-=de),i._queueTotalSize-=de,hf(i,de,u),R-=de}return M}function hf(i,u,f){f.bytesFilled+=u}function pf(i){i._queueTotalSize===0&&i._closeRequested?(vs(i),vo(i._controlledReadableByteStream)):Zr(i)}function hu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function pu(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();ff(i,u)&&(Tn(i),fu(i._controlledReadableByteStream,u))}}function z0(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let f=u._readRequests.shift();gf(i,f)}}function H0(i,u,f,C){let R=i._controlledReadableByteStream,M=u.constructor,q=$0(M),{byteOffset:Q,byteLength:ce}=u,ne=f*q,de;try{de=fr(u.buffer)}catch(Te){C._errorSteps(Te);return}let ge={buffer:de,bufferByteLength:de.byteLength,byteOffset:Q,byteLength:ce,bytesFilled:0,minimumFill:ne,elementSize:q,viewConstructor:M,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ge),Cf(R,C);return}if(R._state==="closed"){let Te=new M(ge.buffer,ge.byteOffset,0);C._closeSteps(Te);return}if(i._queueTotalSize>0){if(ff(i,ge)){let Te=cf(ge);pf(i),C._chunkSteps(Te);return}if(i._closeRequested){let Te=new TypeError("Insufficient bytes to fill elements in the given buffer");wt(i,Te),C._errorSteps(Te);return}}i._pendingPullIntos.push(ge),Cf(R,C),Zr(i)}function W0(i,u){u.readerType==="none"&&Tn(i);let f=i._controlledReadableByteStream;if(yu(f))for(;wf(f)>0;){let C=Tn(i);fu(f,C)}}function G0(i,u,f){if(hf(i,u,f),f.readerType==="none"){df(i,f),pu(i);return}if(f.bytesFilled<f.minimumFill)return;Tn(i);let C=f.bytesFilled%f.elementSize;if(C>0){let R=f.byteOffset+f.bytesFilled;lf(i,f.buffer,R-C,C)}f.bytesFilled-=C,fu(i._controlledReadableByteStream,f),pu(i)}function mf(i,u){let f=i._pendingPullIntos.peek();hu(i),i._controlledReadableByteStream._state==="closed"?W0(i,f):G0(i,u,f),Zr(i)}function Tn(i){return i._pendingPullIntos.shift()}function J0(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(N(u)&&L(u)>0||yu(u)&&wf(u)>0||yf(i)>0)}function vs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function bo(i){let u=i._controlledReadableByteStream;if(!(i._closeRequested||u._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let f=i._pendingPullIntos.peek();if(f.bytesFilled%f.elementSize!==0){let C=new TypeError("Insufficient bytes to fill elements in the given buffer");throw wt(i,C),C}}vs(i),vo(u)}}function Ts(i,u){let f=i._controlledReadableByteStream;if(i._closeRequested||f._state!=="readable")return;let{buffer:C,byteOffset:R,byteLength:M}=u;if(Or(C))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=fr(C);if(i._pendingPullIntos.length>0){let Q=i._pendingPullIntos.peek();if(Or(Q.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");hu(i),Q.buffer=fr(Q.buffer),Q.readerType==="none"&&df(i,Q)}if(N(f))if(z0(i),L(f)===0)ks(i,q,R,M);else{i._pendingPullIntos.length>0&&Tn(i);let Q=new Uint8Array(q,R,M);P(f,Q,!1)}else yu(f)?(ks(i,q,R,M),pu(i)):ks(i,q,R,M);Zr(i)}function wt(i,u){let f=i._controlledReadableByteStream;f._state==="readable"&&(uf(i),Fr(i),vs(i),Wf(f,u))}function gf(i,u){let f=i._queue.shift();i._queueTotalSize-=f.byteLength,pf(i);let C=new Uint8Array(f.buffer,f.byteOffset,f.byteLength);u._chunkSteps(C)}function mu(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let u=i._pendingPullIntos.peek(),f=new Uint8Array(u.buffer,u.byteOffset+u.bytesFilled,u.byteLength-u.bytesFilled),C=Object.create(Qr.prototype);K0(C,i,f),i._byobRequest=C}return i._byobRequest}function yf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function Ds(i,u){let f=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(u===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(f.bytesFilled+u>f.byteLength)throw new RangeError("bytesWritten out of range")}f.buffer=fr(f.buffer),mf(i,u)}function Rs(i,u){let f=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(u.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(f.byteOffset+f.bytesFilled!==u.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(f.bufferByteLength!==u.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(f.bytesFilled+u.byteLength>f.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let R=u.byteLength;f.buffer=fr(u.buffer),mf(i,R)}function _f(i,u,f,C,R,M,q){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Fr(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=M,u._pullAlgorithm=C,u._cancelAlgorithm=R,u._autoAllocateChunkSize=q,u._pendingPullIntos=new D,i._readableStreamController=u;let Q=f();w(h(Q),()=>(u._started=!0,Zr(u),null),ce=>(wt(u,ce),null))}function V0(i,u,f){let C=Object.create(hr.prototype),R,M,q;u.start!==void 0?R=()=>u.start(C):R=()=>{},u.pull!==void 0?M=()=>u.pull(C):M=()=>h(void 0),u.cancel!==void 0?q=ce=>u.cancel(ce):q=()=>h(void 0);let Q=u.autoAllocateChunkSize;if(Q===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");_f(i,C,R,M,q,f,Q)}function K0(i,u,f){i._associatedReadableByteStreamController=u,i._view=f}function gu(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function Co(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function Y0(i,u){le(i,u);let f=i?.mode;return{mode:f===void 0?void 0:Q0(f,`${u} has member 'mode' that`)}}function Q0(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function X0(i,u){var f;le(i,u);let C=(f=i?.min)!==null&&f!==void 0?f:1;return{min:O(C,`${u} has member 'min' that`)}}function bf(i){return new Pr(i)}function Cf(i,u){i._reader._readIntoRequests.push(u)}function Z0(i,u,f){let R=i._reader._readIntoRequests.shift();f?R._closeSteps(u):R._chunkSteps(u)}function wf(i){return i._reader._readIntoRequests.length}function yu(i){let u=i._reader;return!(u===void 0||!en(u))}class Pr{constructor(u){if(Ne(u,1,"ReadableStreamBYOBReader"),I(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Xr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");te(this,u),this._readIntoRequests=new D}get closed(){return en(this)?this._closedPromise:d(xs("closed"))}cancel(u=void 0){return en(this)?this._ownerReadableStream===void 0?d(he("cancel")):Z(this,u):d(xs("cancel"))}read(u,f={}){if(!en(this))return d(xs("read"));if(!ArrayBuffer.isView(u))return d(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(Or(u.buffer))return d(new TypeError("view's buffer has been detached"));let C;try{C=X0(f,"options")}catch(ne){return d(ne)}let R=C.min;if(R===0)return d(new TypeError("options.min must be greater than 0"));if(q0(u)){if(R>u.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(R>u.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(he("read from"));let M,q,Q=l((ne,de)=>{M=ne,q=de});return Ef(this,u,R,{_chunkSteps:ne=>M({value:ne,done:!1}),_closeSteps:ne=>M({value:ne,done:!0}),_errorSteps:ne=>q(ne)}),Q}releaseLock(){if(!en(this))throw xs("releaseLock");this._ownerReadableStream!==void 0&&e_(this)}}Object.defineProperties(Pr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Pr.prototype.cancel,"cancel"),o(Pr.prototype.read,"read"),o(Pr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Pr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function en(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Pr}function Ef(i,u,f,C){let R=i._ownerReadableStream;R._disturbed=!0,R._state==="errored"?C._errorSteps(R._storedError):H0(R._readableStreamController,u,f,C)}function e_(i){ue(i);let u=new TypeError("Reader was released");Af(i,u)}function Af(i,u){let f=i._readIntoRequests;i._readIntoRequests=new D,f.forEach(C=>{C._errorSteps(u)})}function xs(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function wo(i,u){let{highWaterMark:f}=i;if(f===void 0)return u;if(ut(f)||f<0)throw new RangeError("Invalid highWaterMark");return f}function Os(i){let{size:u}=i;return u||(()=>1)}function Fs(i,u){le(i,u);let f=i?.highWaterMark,C=i?.size;return{highWaterMark:f===void 0?void 0:A(f),size:C===void 0?void 0:t_(C,`${u} has member 'size' that`)}}function t_(i,u){return ye(i,u),f=>A(i(f))}function r_(i,u){le(i,u);let f=i?.abort,C=i?.close,R=i?.start,M=i?.type,q=i?.write;return{abort:f===void 0?void 0:n_(f,i,`${u} has member 'abort' that`),close:C===void 0?void 0:o_(C,i,`${u} has member 'close' that`),start:R===void 0?void 0:s_(R,i,`${u} has member 'start' that`),write:q===void 0?void 0:i_(q,i,`${u} has member 'write' that`),type:M}}function n_(i,u,f){return ye(i,f),C=>y(i,u,[C])}function o_(i,u,f){return ye(i,f),()=>y(i,u,[])}function s_(i,u,f){return ye(i,f),C=>k(i,u,[C])}function i_(i,u,f){return ye(i,f),(C,R)=>y(i,u,[C,R])}function Sf(i,u){if(!Dn(i))throw new TypeError(`${u} is not a WritableStream.`)}function a_(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let u_=typeof AbortController=="function";function c_(){if(u_)return new AbortController}class Ir{constructor(u={},f={}){u===void 0?u=null:De(u,"First parameter");let C=Fs(f,"Second parameter"),R=r_(u,"First parameter");if(vf(this),R.type!==void 0)throw new RangeError("Invalid type is specified");let q=Os(C),Q=wo(C,1);A_(this,R,Q,q)}get locked(){if(!Dn(this))throw js("locked");return Rn(this)}abort(u=void 0){return Dn(this)?Rn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Ps(this,u):d(js("abort"))}close(){return Dn(this)?Rn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Yt(this)?d(new TypeError("Cannot close an already-closing stream")):Tf(this):d(js("close"))}getWriter(){if(!Dn(this))throw js("getWriter");return kf(this)}}Object.defineProperties(Ir.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Ir.prototype.abort,"abort"),o(Ir.prototype.close,"close"),o(Ir.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ir.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function kf(i){return new pr(i)}function l_(i,u,f,C,R=1,M=()=>1){let q=Object.create(Ir.prototype);vf(q);let Q=Object.create(xn.prototype);return Pf(q,Q,i,u,f,C,R,M),q}function vf(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new D,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Dn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof Ir}function Rn(i){return i._writer!==void 0}function Ps(i,u){var f;if(i._state==="closed"||i._state==="errored")return h(void 0);i._writableStreamController._abortReason=u,(f=i._writableStreamController._abortController)===null||f===void 0||f.abort(u);let C=i._state;if(C==="closed"||C==="errored")return h(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let R=!1;C==="erroring"&&(R=!0,u=void 0);let M=l((q,Q)=>{i._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Q,_reason:u,_wasAlreadyErroring:R}});return i._pendingAbortRequest._promise=M,R||bu(i,u),M}function Tf(i){let u=i._state;if(u==="closed"||u==="errored")return d(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let f=l((R,M)=>{let q={_resolve:R,_reject:M};i._closeRequest=q}),C=i._writer;return C!==void 0&&i._backpressure&&u==="writable"&&Tu(C),S_(i._writableStreamController),f}function d_(i){return l((f,C)=>{let R={_resolve:f,_reject:C};i._writeRequests.push(R)})}function _u(i,u){if(i._state==="writable"){bu(i,u);return}Cu(i)}function bu(i,u){let f=i._writableStreamController;i._state="erroring",i._storedError=u;let C=i._writer;C!==void 0&&Rf(C,u),!g_(i)&&f._started&&Cu(i)}function Cu(i){i._state="errored",i._writableStreamController[$]();let u=i._storedError;if(i._writeRequests.forEach(R=>{R._reject(u)}),i._writeRequests=new D,i._pendingAbortRequest===void 0){Is(i);return}let f=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,f._wasAlreadyErroring){f._reject(u),Is(i);return}let C=i._writableStreamController[F](f._reason);w(C,()=>(f._resolve(),Is(i),null),R=>(f._reject(R),Is(i),null))}function f_(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function h_(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,_u(i,u)}function p_(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let f=i._writer;f!==void 0&&jf(f)}function m_(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),_u(i,u)}function Yt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function g_(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function y_(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function __(i){i._inFlightWriteRequest=i._writeRequests.shift()}function Is(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&ku(u,i._storedError)}function wu(i,u){let f=i._writer;f!==void 0&&u!==i._backpressure&&(u?O_(f):Tu(f)),i._backpressure=u}class pr{constructor(u){if(Ne(u,1,"WritableStreamDefaultWriter"),Sf(u,"First parameter"),Rn(u))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let f=u._state;if(f==="writable")!Yt(u)&&u._backpressure?Ms(this):Lf(this),Ls(this);else if(f==="erroring")vu(this,u._storedError),Ls(this);else if(f==="closed")Lf(this),R_(this);else{let C=u._storedError;vu(this,C),Bf(this,C)}}get closed(){return tn(this)?this._closedPromise:d(rn("closed"))}get desiredSize(){if(!tn(this))throw rn("desiredSize");if(this._ownerWritableStream===void 0)throw Ao("desiredSize");return E_(this)}get ready(){return tn(this)?this._readyPromise:d(rn("ready"))}abort(u=void 0){return tn(this)?this._ownerWritableStream===void 0?d(Ao("abort")):b_(this,u):d(rn("abort"))}close(){if(!tn(this))return d(rn("close"));let u=this._ownerWritableStream;return u===void 0?d(Ao("close")):Yt(u)?d(new TypeError("Cannot close an already-closing stream")):Df(this)}releaseLock(){if(!tn(this))throw rn("releaseLock");this._ownerWritableStream!==void 0&&xf(this)}write(u=void 0){return tn(this)?this._ownerWritableStream===void 0?d(Ao("write to")):Of(this,u):d(rn("write"))}}Object.defineProperties(pr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(pr.prototype.abort,"abort"),o(pr.prototype.close,"close"),o(pr.prototype.releaseLock,"releaseLock"),o(pr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function tn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof pr}function b_(i,u){let f=i._ownerWritableStream;return Ps(f,u)}function Df(i){let u=i._ownerWritableStream;return Tf(u)}function C_(i){let u=i._ownerWritableStream,f=u._state;return Yt(u)||f==="closed"?h(void 0):f==="errored"?d(u._storedError):Df(i)}function w_(i,u){i._closedPromiseState==="pending"?ku(i,u):x_(i,u)}function Rf(i,u){i._readyPromiseState==="pending"?Mf(i,u):F_(i,u)}function E_(i){let u=i._ownerWritableStream,f=u._state;return f==="errored"||f==="erroring"?null:f==="closed"?0:If(u._writableStreamController)}function xf(i){let u=i._ownerWritableStream,f=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Rf(i,f),w_(i,f),u._writer=void 0,i._ownerWritableStream=void 0}function Of(i,u){let f=i._ownerWritableStream,C=f._writableStreamController,R=k_(C,u);if(f!==i._ownerWritableStream)return d(Ao("write to"));let M=f._state;if(M==="errored")return d(f._storedError);if(Yt(f)||M==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(M==="erroring")return d(f._storedError);let q=d_(f);return v_(C,u,R),q}let Ff={};class xn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Eu(this))throw Su("abortReason");return this._abortReason}get signal(){if(!Eu(this))throw Su("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!Eu(this))throw Su("error");this._controlledWritableStream._state==="writable"&&Nf(this,u)}[F](u){let f=this._abortAlgorithm(u);return Ns(this),f}[$](){Fr(this)}}Object.defineProperties(xn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Eu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof xn}function Pf(i,u,f,C,R,M,q,Q){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Fr(u),u._abortReason=void 0,u._abortController=c_(),u._started=!1,u._strategySizeAlgorithm=Q,u._strategyHWM=q,u._writeAlgorithm=C,u._closeAlgorithm=R,u._abortAlgorithm=M;let ce=Au(u);wu(i,ce);let ne=f(),de=h(ne);w(de,()=>(u._started=!0,Bs(u),null),ge=>(u._started=!0,_u(i,ge),null))}function A_(i,u,f,C){let R=Object.create(xn.prototype),M,q,Q,ce;u.start!==void 0?M=()=>u.start(R):M=()=>{},u.write!==void 0?q=ne=>u.write(ne,R):q=()=>h(void 0),u.close!==void 0?Q=()=>u.close():Q=()=>h(void 0),u.abort!==void 0?ce=ne=>u.abort(ne):ce=()=>h(void 0),Pf(i,R,M,q,Q,ce,f,C)}function Ns(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function S_(i){lu(i,Ff,0),Bs(i)}function k_(i,u){try{return i._strategySizeAlgorithm(u)}catch(f){return Eo(i,f),1}}function If(i){return i._strategyHWM-i._queueTotalSize}function v_(i,u,f){try{lu(i,u,f)}catch(R){Eo(i,R);return}let C=i._controlledWritableStream;if(!Yt(C)&&C._state==="writable"){let R=Au(i);wu(C,R)}Bs(i)}function Bs(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){Cu(u);return}if(i._queue.length===0)return;let C=U0(i);C===Ff?T_(i):D_(i,C)}function Eo(i,u){i._controlledWritableStream._state==="writable"&&Nf(i,u)}function T_(i){let u=i._controlledWritableStream;y_(u),cu(i);let f=i._closeAlgorithm();Ns(i),w(f,()=>(p_(u),null),C=>(m_(u,C),null))}function D_(i,u){let f=i._controlledWritableStream;__(f);let C=i._writeAlgorithm(u);w(C,()=>{f_(f);let R=f._state;if(cu(i),!Yt(f)&&R==="writable"){let M=Au(i);wu(f,M)}return Bs(i),null},R=>(f._state==="writable"&&Ns(i),h_(f,R),null))}function Au(i){return If(i)<=0}function Nf(i,u){let f=i._controlledWritableStream;Ns(i),bu(f,u)}function js(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function Su(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function rn(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function Ao(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Ls(i){i._closedPromise=l((u,f)=>{i._closedPromise_resolve=u,i._closedPromise_reject=f,i._closedPromiseState="pending"})}function Bf(i,u){Ls(i),ku(i,u)}function R_(i){Ls(i),jf(i)}function ku(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function x_(i,u){Bf(i,u)}function jf(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}function Ms(i){i._readyPromise=l((u,f)=>{i._readyPromise_resolve=u,i._readyPromise_reject=f}),i._readyPromiseState="pending"}function vu(i,u){Ms(i),Mf(i,u)}function Lf(i){Ms(i),Tu(i)}function Mf(i,u){i._readyPromise_reject!==void 0&&(g(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function O_(i){Ms(i)}function F_(i,u){vu(i,u)}function Tu(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}function P_(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Du=P_();function I_(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function N_(){let i=Du?.DOMException;return I_(i)?i:void 0}function B_(){let i=function(f,C){this.message=f||"",this.name=C||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}let j_=N_()||B_();function Uf(i,u,f,C,R,M){let q=U(i),Q=kf(u);i._disturbed=!0;let ce=!1,ne=h(void 0);return l((de,ge)=>{let Te;if(M!==void 0){if(Te=()=>{let oe=M.reason!==void 0?M.reason:new j_("Aborted","AbortError"),_e=[];C||_e.push(()=>u._state==="writable"?Ps(u,oe):h(void 0)),R||_e.push(()=>i._state==="readable"?Bt(i,oe):h(void 0)),rt(()=>Promise.all(_e.map(Re=>Re())),!0,oe)},M.aborted){Te();return}M.addEventListener("abort",Te)}function jt(){return l((oe,_e)=>{function Re(ct){ct?oe():p(In(),Re,_e)}Re(!1)})}function In(){return ce?h(!0):p(Q._readyPromise,()=>l((oe,_e)=>{ee(q,{_chunkSteps:Re=>{ne=p(Of(Q,Re),void 0,e),oe(!1)},_closeSteps:()=>oe(!0),_errorSteps:_e})}))}if(gr(i,q._closedPromise,oe=>(C?Et(!0,oe):rt(()=>Ps(u,oe),!0,oe),null)),gr(u,Q._closedPromise,oe=>(R?Et(!0,oe):rt(()=>Bt(i,oe),!0,oe),null)),Xe(i,q._closedPromise,()=>(f?Et():rt(()=>C_(Q)),null)),Yt(u)||u._state==="closed"){let oe=new TypeError("the destination writable stream closed before all data could be piped to it");R?Et(!0,oe):rt(()=>Bt(i,oe),!0,oe)}g(jt());function Lr(){let oe=ne;return p(ne,()=>oe!==ne?Lr():void 0)}function gr(oe,_e,Re){oe._state==="errored"?Re(oe._storedError):S(_e,Re)}function Xe(oe,_e,Re){oe._state==="closed"?Re():T(_e,Re)}function rt(oe,_e,Re){if(ce)return;ce=!0,u._state==="writable"&&!Yt(u)?T(Lr(),ct):ct();function ct(){return w(oe(),()=>yr(_e,Re),Nn=>yr(!0,Nn)),null}}function Et(oe,_e){ce||(ce=!0,u._state==="writable"&&!Yt(u)?T(Lr(),()=>yr(oe,_e)):yr(oe,_e))}function yr(oe,_e){return xf(Q),ue(q),M!==void 0&&M.removeEventListener("abort",Te),oe?ge(_e):de(void 0),null}})}class mr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Us(this))throw $s("desiredSize");return Ru(this)}close(){if(!Us(this))throw $s("close");if(!Fn(this))throw new TypeError("The stream is not in a state that permits close");nn(this)}enqueue(u=void 0){if(!Us(this))throw $s("enqueue");if(!Fn(this))throw new TypeError("The stream is not in a state that permits enqueue");return On(this,u)}error(u=void 0){if(!Us(this))throw $s("error");Nt(this,u)}[V](u){Fr(this);let f=this._cancelAlgorithm(u);return qs(this),f}[B](u){let f=this._controlledReadableStream;if(this._queue.length>0){let C=cu(this);this._closeRequested&&this._queue.length===0?(qs(this),vo(f)):So(this),u._chunkSteps(C)}else x(f,u),So(this)}[Y](){}}Object.defineProperties(mr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(mr.prototype.close,"close"),o(mr.prototype.enqueue,"enqueue"),o(mr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Us(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof mr}function So(i){if(!qf(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let f=i._pullAlgorithm();w(f,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,So(i)),null),C=>(Nt(i,C),null))}function qf(i){let u=i._controlledReadableStream;return!Fn(i)||!i._started?!1:!!(Br(u)&&L(u)>0||Ru(i)>0)}function qs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function nn(i){if(!Fn(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(qs(i),vo(u))}function On(i,u){if(!Fn(i))return;let f=i._controlledReadableStream;if(Br(f)&&L(f)>0)P(f,u,!1);else{let C;try{C=i._strategySizeAlgorithm(u)}catch(R){throw Nt(i,R),R}try{lu(i,u,C)}catch(R){throw Nt(i,R),R}}So(i)}function Nt(i,u){let f=i._controlledReadableStream;f._state==="readable"&&(Fr(i),qs(i),Wf(f,u))}function Ru(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function L_(i){return!qf(i)}function Fn(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function $f(i,u,f,C,R,M,q){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Fr(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=q,u._strategyHWM=M,u._pullAlgorithm=C,u._cancelAlgorithm=R,i._readableStreamController=u;let Q=f();w(h(Q),()=>(u._started=!0,So(u),null),ce=>(Nt(u,ce),null))}function M_(i,u,f,C){let R=Object.create(mr.prototype),M,q,Q;u.start!==void 0?M=()=>u.start(R):M=()=>{},u.pull!==void 0?q=()=>u.pull(R):q=()=>h(void 0),u.cancel!==void 0?Q=ce=>u.cancel(ce):Q=()=>h(void 0),$f(i,R,M,q,Q,f,C)}function $s(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function U_(i,u){return Xr(i._readableStreamController)?$_(i):q_(i)}function q_(i,u){let f=U(i),C=!1,R=!1,M=!1,q=!1,Q,ce,ne,de,ge,Te=l(Xe=>{ge=Xe});function jt(){return C?(R=!0,h(void 0)):(C=!0,ee(f,{_chunkSteps:rt=>{m(()=>{R=!1;let Et=rt,yr=rt;M||On(ne._readableStreamController,Et),q||On(de._readableStreamController,yr),C=!1,R&&jt()})},_closeSteps:()=>{C=!1,M||nn(ne._readableStreamController),q||nn(de._readableStreamController),(!M||!q)&&ge(void 0)},_errorSteps:()=>{C=!1}}),h(void 0))}function In(Xe){if(M=!0,Q=Xe,q){let rt=Se([Q,ce]),Et=Bt(i,rt);ge(Et)}return Te}function Lr(Xe){if(q=!0,ce=Xe,M){let rt=Se([Q,ce]),Et=Bt(i,rt);ge(Et)}return Te}function gr(){}return ne=ko(gr,jt,In),de=ko(gr,jt,Lr),S(f._closedPromise,Xe=>(Nt(ne._readableStreamController,Xe),Nt(de._readableStreamController,Xe),(!M||!q)&&ge(void 0),null)),[ne,de]}function $_(i){let u=U(i),f=!1,C=!1,R=!1,M=!1,q=!1,Q,ce,ne,de,ge,Te=l(oe=>{ge=oe});function jt(oe){S(oe._closedPromise,_e=>(oe!==u||(wt(ne._readableStreamController,_e),wt(de._readableStreamController,_e),(!M||!q)&&ge(void 0)),null))}function In(){en(u)&&(ue(u),u=U(i),jt(u)),ee(u,{_chunkSteps:_e=>{m(()=>{C=!1,R=!1;let Re=_e,ct=_e;if(!M&&!q)try{ct=sf(_e)}catch(Nn){wt(ne._readableStreamController,Nn),wt(de._readableStreamController,Nn),ge(Bt(i,Nn));return}M||Ts(ne._readableStreamController,Re),q||Ts(de._readableStreamController,ct),f=!1,C?gr():R&&Xe()})},_closeSteps:()=>{f=!1,M||bo(ne._readableStreamController),q||bo(de._readableStreamController),ne._readableStreamController._pendingPullIntos.length>0&&Ds(ne._readableStreamController,0),de._readableStreamController._pendingPullIntos.length>0&&Ds(de._readableStreamController,0),(!M||!q)&&ge(void 0)},_errorSteps:()=>{f=!1}})}function Lr(oe,_e){X(u)&&(ue(u),u=bf(i),jt(u));let Re=_e?de:ne,ct=_e?ne:de;Ef(u,oe,1,{_chunkSteps:Bn=>{m(()=>{C=!1,R=!1;let jn=_e?q:M;if(_e?M:q)jn||Rs(Re._readableStreamController,Bn);else{let oh;try{oh=sf(Bn)}catch(Iu){wt(Re._readableStreamController,Iu),wt(ct._readableStreamController,Iu),ge(Bt(i,Iu));return}jn||Rs(Re._readableStreamController,Bn),Ts(ct._readableStreamController,oh)}f=!1,C?gr():R&&Xe()})},_closeSteps:Bn=>{f=!1;let jn=_e?q:M,Ys=_e?M:q;jn||bo(Re._readableStreamController),Ys||bo(ct._readableStreamController),Bn!==void 0&&(jn||Rs(Re._readableStreamController,Bn),!Ys&&ct._readableStreamController._pendingPullIntos.length>0&&Ds(ct._readableStreamController,0)),(!jn||!Ys)&&ge(void 0)},_errorSteps:()=>{f=!1}})}function gr(){if(f)return C=!0,h(void 0);f=!0;let oe=mu(ne._readableStreamController);return oe===null?In():Lr(oe._view,!1),h(void 0)}function Xe(){if(f)return R=!0,h(void 0);f=!0;let oe=mu(de._readableStreamController);return oe===null?In():Lr(oe._view,!0),h(void 0)}function rt(oe){if(M=!0,Q=oe,q){let _e=Se([Q,ce]),Re=Bt(i,_e);ge(Re)}return Te}function Et(oe){if(q=!0,ce=oe,M){let _e=Se([Q,ce]),Re=Bt(i,_e);ge(Re)}return Te}function yr(){}return ne=Hf(yr,gr,rt),de=Hf(yr,Xe,Et),jt(u),[ne,de]}function z_(i){return r(i)&&typeof i.getReader<"u"}function H_(i){return z_(i)?G_(i.getReader()):W_(i)}function W_(i){let u,f=of(i,"async"),C=e;function R(){let q;try{q=B0(f)}catch(ce){return d(ce)}let Q=h(q);return _(Q,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(j0(ce))nn(u._readableStreamController);else{let de=L0(ce);On(u._readableStreamController,de)}})}function M(q){let Q=f.iterator,ce;try{ce=Ss(Q,"return")}catch(ge){return d(ge)}if(ce===void 0)return h(void 0);let ne;try{ne=k(ce,Q,[q])}catch(ge){return d(ge)}let de=h(ne);return _(de,ge=>{if(!r(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=ko(C,R,M,0),u}function G_(i){let u,f=e;function C(){let M;try{M=i.read()}catch(q){return d(q)}return _(M,q=>{if(!r(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)nn(u._readableStreamController);else{let Q=q.value;On(u._readableStreamController,Q)}})}function R(M){try{return h(i.cancel(M))}catch(q){return d(q)}}return u=ko(f,C,R,0),u}function J_(i,u){le(i,u);let f=i,C=f?.autoAllocateChunkSize,R=f?.cancel,M=f?.pull,q=f?.start,Q=f?.type;return{autoAllocateChunkSize:C===void 0?void 0:O(C,`${u} has member 'autoAllocateChunkSize' that`),cancel:R===void 0?void 0:V_(R,f,`${u} has member 'cancel' that`),pull:M===void 0?void 0:K_(M,f,`${u} has member 'pull' that`),start:q===void 0?void 0:Y_(q,f,`${u} has member 'start' that`),type:Q===void 0?void 0:Q_(Q,`${u} has member 'type' that`)}}function V_(i,u,f){return ye(i,f),C=>y(i,u,[C])}function K_(i,u,f){return ye(i,f),C=>y(i,u,[C])}function Y_(i,u,f){return ye(i,f),C=>k(i,u,[C])}function Q_(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function X_(i,u){return le(i,u),{preventCancel:!!i?.preventCancel}}function zf(i,u){le(i,u);let f=i?.preventAbort,C=i?.preventCancel,R=i?.preventClose,M=i?.signal;return M!==void 0&&Z_(M,`${u} has member 'signal' that`),{preventAbort:!!f,preventCancel:!!C,preventClose:!!R,signal:M}}function Z_(i,u){if(!a_(i))throw new TypeError(`${u} is not an AbortSignal.`)}function eb(i,u){le(i,u);let f=i?.readable;b(f,"readable","ReadableWritablePair"),I(f,`${u} has member 'readable' that`);let C=i?.writable;return b(C,"writable","ReadableWritablePair"),Sf(C,`${u} has member 'writable' that`),{readable:f,writable:C}}class Ye{constructor(u={},f={}){u===void 0?u=null:De(u,"First parameter");let C=Fs(f,"Second parameter"),R=J_(u,"First parameter");if(xu(this),R.type==="bytes"){if(C.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let M=wo(C,0);V0(this,R,M)}else{let M=Os(C),q=wo(C,1);M_(this,R,q,M)}}get locked(){if(!Nr(this))throw on("locked");return Br(this)}cancel(u=void 0){return Nr(this)?Br(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Bt(this,u):d(on("cancel"))}getReader(u=void 0){if(!Nr(this))throw on("getReader");return Y0(u,"First parameter").mode===void 0?U(this):bf(this)}pipeThrough(u,f={}){if(!Nr(this))throw on("pipeThrough");Ne(u,1,"pipeThrough");let C=eb(u,"First parameter"),R=zf(f,"Second parameter");if(Br(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Rn(C.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let M=Uf(this,C.writable,R.preventClose,R.preventAbort,R.preventCancel,R.signal);return g(M),C.readable}pipeTo(u,f={}){if(!Nr(this))return d(on("pipeTo"));if(u===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!Dn(u))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let C;try{C=zf(f,"Second parameter")}catch(R){return d(R)}return Br(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Rn(u)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Uf(this,u,C.preventClose,C.preventAbort,C.preventCancel,C.signal)}tee(){if(!Nr(this))throw on("tee");let u=U_(this);return Se(u)}values(u=void 0){if(!Nr(this))throw on("values");let f=X_(u,"First parameter");return Sn(this,f.preventCancel)}[uu](u){return this.values(u)}static from(u){return H_(u)}}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}}),o(Ye.from,"from"),o(Ye.prototype.cancel,"cancel"),o(Ye.prototype.getReader,"getReader"),o(Ye.prototype.pipeThrough,"pipeThrough"),o(Ye.prototype.pipeTo,"pipeTo"),o(Ye.prototype.tee,"tee"),o(Ye.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ye.prototype,uu,{value:Ye.prototype.values,writable:!0,configurable:!0});function ko(i,u,f,C=1,R=()=>1){let M=Object.create(Ye.prototype);xu(M);let q=Object.create(mr.prototype);return $f(M,q,i,u,f,C,R),M}function Hf(i,u,f){let C=Object.create(Ye.prototype);xu(C);let R=Object.create(hr.prototype);return _f(C,R,i,u,f,0,void 0),C}function xu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Nr(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof Ye}function Br(i){return i._reader!==void 0}function Bt(i,u){if(i._disturbed=!0,i._state==="closed")return h(void 0);if(i._state==="errored")return d(i._storedError);vo(i);let f=i._reader;if(f!==void 0&&en(f)){let R=f._readIntoRequests;f._readIntoRequests=new D,R.forEach(M=>{M._closeSteps(void 0)})}let C=i._readableStreamController[V](u);return _(C,e)}function vo(i){i._state="closed";let u=i._reader;if(u!==void 0&&(ae(u),X(u))){let f=u._readRequests;u._readRequests=new D,f.forEach(C=>{C._closeSteps()})}}function Wf(i,u){i._state="errored",i._storedError=u;let f=i._reader;f!==void 0&&(G(f,u),X(f)?Oe(f,u):Af(f,u))}function on(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function Gf(i,u){le(i,u);let f=i?.highWaterMark;return b(f,"highWaterMark","QueuingStrategyInit"),{highWaterMark:A(f)}}let Jf=i=>i.byteLength;o(Jf,"size");class zs{constructor(u){Ne(u,1,"ByteLengthQueuingStrategy"),u=Gf(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Kf(this))throw Vf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Kf(this))throw Vf("size");return Jf}}Object.defineProperties(zs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(zs.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Vf(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function Kf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof zs}let Yf=()=>1;o(Yf,"size");class Hs{constructor(u){Ne(u,1,"CountQueuingStrategy"),u=Gf(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Xf(this))throw Qf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Xf(this))throw Qf("size");return Yf}}Object.defineProperties(Hs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Hs.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Qf(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Xf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof Hs}function tb(i,u){le(i,u);let f=i?.cancel,C=i?.flush,R=i?.readableType,M=i?.start,q=i?.transform,Q=i?.writableType;return{cancel:f===void 0?void 0:sb(f,i,`${u} has member 'cancel' that`),flush:C===void 0?void 0:rb(C,i,`${u} has member 'flush' that`),readableType:R,start:M===void 0?void 0:nb(M,i,`${u} has member 'start' that`),transform:q===void 0?void 0:ob(q,i,`${u} has member 'transform' that`),writableType:Q}}function rb(i,u,f){return ye(i,f),C=>y(i,u,[C])}function nb(i,u,f){return ye(i,f),C=>k(i,u,[C])}function ob(i,u,f){return ye(i,f),(C,R)=>y(i,u,[C,R])}function sb(i,u,f){return ye(i,f),C=>y(i,u,[C])}class Ws{constructor(u={},f={},C={}){u===void 0&&(u=null);let R=Fs(f,"Second parameter"),M=Fs(C,"Third parameter"),q=tb(u,"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 Q=wo(M,0),ce=Os(M),ne=wo(R,1),de=Os(R),ge,Te=l(jt=>{ge=jt});ib(this,Te,ne,de,Q,ce),ub(this,q),q.start!==void 0?ge(q.start(this._transformStreamController)):ge(void 0)}get readable(){if(!Zf(this))throw nh("readable");return this._readable}get writable(){if(!Zf(this))throw nh("writable");return this._writable}}Object.defineProperties(Ws.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ws.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function ib(i,u,f,C,R,M){function q(){return u}function Q(Te){return db(i,Te)}function ce(Te){return fb(i,Te)}function ne(){return hb(i)}i._writable=l_(q,Q,ne,ce,f,C);function de(){return pb(i)}function ge(Te){return mb(i,Te)}i._readable=ko(q,de,ge,R,M),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,Gs(i,!0),i._transformStreamController=void 0}function Zf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof Ws}function eh(i,u){Nt(i._readable._readableStreamController,u),Ou(i,u)}function Ou(i,u){Vs(i._transformStreamController),Eo(i._writable._writableStreamController,u),Fu(i)}function Fu(i){i._backpressure&&Gs(i,!1)}function Gs(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(f=>{i._backpressureChangePromise_resolve=f}),i._backpressure=u}class jr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Js(this))throw Ks("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return Ru(u)}enqueue(u=void 0){if(!Js(this))throw Ks("enqueue");th(this,u)}error(u=void 0){if(!Js(this))throw Ks("error");cb(this,u)}terminate(){if(!Js(this))throw Ks("terminate");lb(this)}}Object.defineProperties(jr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(jr.prototype.enqueue,"enqueue"),o(jr.prototype.error,"error"),o(jr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Js(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof jr}function ab(i,u,f,C,R){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=f,u._flushAlgorithm=C,u._cancelAlgorithm=R,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function ub(i,u){let f=Object.create(jr.prototype),C,R,M;u.transform!==void 0?C=q=>u.transform(q,f):C=q=>{try{return th(f,q),h(void 0)}catch(Q){return d(Q)}},u.flush!==void 0?R=()=>u.flush(f):R=()=>h(void 0),u.cancel!==void 0?M=q=>u.cancel(q):M=()=>h(void 0),ab(i,f,C,R,M)}function Vs(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function th(i,u){let f=i._controlledTransformStream,C=f._readable._readableStreamController;if(!Fn(C))throw new TypeError("Readable side is not in a state that permits enqueue");try{On(C,u)}catch(M){throw Ou(f,M),f._readable._storedError}L_(C)!==f._backpressure&&Gs(f,!0)}function cb(i,u){eh(i._controlledTransformStream,u)}function rh(i,u){let f=i._transformAlgorithm(u);return _(f,void 0,C=>{throw eh(i._controlledTransformStream,C),C})}function lb(i){let u=i._controlledTransformStream,f=u._readable._readableStreamController;nn(f);let C=new TypeError("TransformStream terminated");Ou(u,C)}function db(i,u){let f=i._transformStreamController;if(i._backpressure){let C=i._backpressureChangePromise;return _(C,()=>{let R=i._writable;if(R._state==="erroring")throw R._storedError;return rh(f,u)})}return rh(f,u)}function fb(i,u){let f=i._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let C=i._readable;f._finishPromise=l((M,q)=>{f._finishPromise_resolve=M,f._finishPromise_reject=q});let R=f._cancelAlgorithm(u);return Vs(f),w(R,()=>(C._state==="errored"?Pn(f,C._storedError):(Nt(C._readableStreamController,u),Pu(f)),null),M=>(Nt(C._readableStreamController,M),Pn(f,M),null)),f._finishPromise}function hb(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let f=i._readable;u._finishPromise=l((R,M)=>{u._finishPromise_resolve=R,u._finishPromise_reject=M});let C=u._flushAlgorithm();return Vs(u),w(C,()=>(f._state==="errored"?Pn(u,f._storedError):(nn(f._readableStreamController),Pu(u)),null),R=>(Nt(f._readableStreamController,R),Pn(u,R),null)),u._finishPromise}function pb(i){return Gs(i,!1),i._backpressureChangePromise}function mb(i,u){let f=i._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let C=i._writable;f._finishPromise=l((M,q)=>{f._finishPromise_resolve=M,f._finishPromise_reject=q});let R=f._cancelAlgorithm(u);return Vs(f),w(R,()=>(C._state==="errored"?Pn(f,C._storedError):(Eo(C._writableStreamController,u),Fu(i),Pu(f)),null),M=>(Eo(C._writableStreamController,M),Fu(i),Pn(f,M),null)),f._finishPromise}function Ks(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function Pu(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Pn(i,u){i._finishPromise_reject!==void 0&&(g(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function nh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=zs,t.CountQueuingStrategy=Hs,t.ReadableByteStreamController=hr,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Pr,t.ReadableStreamBYOBRequest=Qr,t.ReadableStreamDefaultController=mr,t.ReadableStreamDefaultReader=z,t.TransformStream=Ws,t.TransformStreamDefaultController=jr,t.WritableStream=Ir,t.WritableStreamDefaultController=xn,t.WritableStreamDefaultWriter=pr}))});var kp=J(()=>{if(!globalThis.ReadableStream)try{let t=require("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,Sp())}try{let{Blob:t}=require("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=c.byteLength,s.enqueue(new Uint8Array(c)),n===o.size&&s.close()}})})}catch{}});async function*dc(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,o=r.byteOffset+r.byteLength;for(;n!==o;){let s=Math.min(o-n,vp),a=r.buffer.slice(n,n+s);n+=a.byteLength,yield new Uint8Array(a)}}else yield r;else{let n=0,o=r;for(;n!==o.size;){let a=await o.slice(n,Math.min(o.size,n+vp)).arrayBuffer();n+=a.byteLength,yield new Uint8Array(a)}}}var ZD,vp,Tp,qC,Mt,Io=Be(()=>{ZD=je(kp(),1);vp=65536;Tp=class fc{#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 s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof fc?a=s:a=n.encode(`${s}`),this.#r+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let o=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of dc(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 dc(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=dc(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:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=r<0?Math.max(o+r,0):Math.min(r,o),c=Math.max(a-s,0),l=this.#e,h=[],d=0;for(let w of l){if(d>=c)break;let T=ArrayBuffer.isView(w)?w.byteLength:w.size;if(s&&T<=s)s-=T,a-=T;else{let S;ArrayBuffer.isView(w)?(S=w.subarray(s,Math.min(T,a)),d+=S.byteLength):(S=w.slice(s,Math.min(T,a)),d+=S.size),a-=T,h.push(S),s=0}}let p=new fc([],{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(Tp.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});qC=Tp,Mt=qC});var $C,zC,qr,hc=Be(()=>{Io();$C=class extends Mt{#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 o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),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 Mt&&/^(File)$/.test(e[Symbol.toStringTag])}},zC=$C,qr=zC});function xp(t,e=Mt){var r=`${Dp()}${Dp()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${r}\r
27
- Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?n.push(o+pc(a)+`"\r
22
+ `);if(C===-1){Ci("have not received end of HTTP headers yet..."),s();return}let v=m.slice(0,C).toString("ascii").split(`\r
23
+ `),A=v.shift();if(!A)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let b=A.split(" "),g=+b[1],p=b.slice(2).join(" "),k={};for(let y of v){if(!y)continue;let E=y.indexOf(":");if(E===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${y}"`));let D=y.slice(0,E).toLowerCase(),F=y.slice(E+1).trimStart(),q=k[D];typeof q=="string"?k[D]=[q,F]:Array.isArray(q)?q.push(F):k[D]=F}Ci("got proxy server response: %o %o",A,k),a(),e({connect:{statusCode:g,statusText:p,headers:k},buffered:m})}t.on("error",l),t.on("end",c),s()})}Wn.parseProxyResponse=UC});var Tp=J(Dt=>{"use strict";var $C=Dt&&Dt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),qC=Dt&&Dt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),kp=Dt&&Dt.__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)&&$C(e,t,r);return qC(e,t),e},vp=Dt&&Dt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.HttpsProxyAgent=void 0;var wi=kp(require("net")),Ep=kp(require("tls")),zC=vp(require("assert")),HC=vp(pc()),WC=Cp(),GC=require("url"),JC=wp(),Bo=(0,HC.default)("https-proxy-agent"),Ap=t=>t.servername===void 0&&t.host&&!wi.isIP(t.host)?{...t,servername:t.host}:t,Ei=class extends WC.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new GC.URL(e):e,this.proxyHeaders=r?.headers??{},Bo("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...r?Sp(r,"headers"):null,host:n,port:o}}async connect(e,r){let{proxy:n}=this;if(!r.host)throw new TypeError('No "host" provided');let o;n.protocol==="https:"?(Bo("Creating `tls.Socket`: %o",this.connectOpts),o=Ep.connect(Ap(this.connectOpts))):(Bo("Creating `net.Socket`: %o",this.connectOpts),o=wi.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=wi.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${a}:${r.port} HTTP/1.1\r
24
+ `;if(n.username||n.password){let C=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(C).toString("base64")}`}s.Host=`${a}:${r.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let C of Object.keys(s))c+=`${C}: ${s[C]}\r
25
+ `;let l=(0,JC.parseProxyResponse)(o);o.write(`${c}\r
26
+ `);let{connect:f,buffered:d}=await l;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",VC),r.secureEndpoint?(Bo("Upgrading socket connection to TLS"),Ep.connect({...Sp(Ap(r),"host","path","port"),socket:o})):o;o.destroy();let m=new wi.Socket({writable:!1});return m.readable=!0,e.once("socket",C=>{Bo("Replaying proxy buffer for failed request"),(0,zC.default)(C.listenerCount("data")>0),C.push(d),C.push(null)}),m}};Ei.protocols=["http","https"];Dt.HttpsProxyAgent=Ei;function VC(t){t.resume()}function Sp(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function KC(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="",o=!1,s=r[0]||"text/plain",a=s;for(let d=1;d<r.length;d++)r[d]==="base64"?o=!0:r[d]&&(a+=`;${r[d]}`,r[d].indexOf("charset=")===0&&(n=r[d].substring(8)));!r[0]&&!n.length&&(a+=";charset=US-ASCII",n="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),f=Buffer.from(l,c);return f.type=s,f.typeFull=a,f.charset=n,f}var Dp,Rp=Ne(()=>{Dp=KC});var Op=J((Ai,xp)=>{(function(t,e){typeof Ai=="object"&&typeof xp<"u"?e(Ai):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ai,(function(t){"use strict";function e(){}function r(i){return typeof i=="object"&&i!==null||typeof i=="function"}let n=e;function o(i,u){try{Object.defineProperty(i,"name",{value:u,configurable:!0})}catch{}}let s=Promise,a=Promise.prototype.then,c=Promise.reject.bind(s);function l(i){return new s(i)}function f(i){return l(u=>u(i))}function d(i){return c(i)}function m(i,u,h){return a.call(i,u,h)}function C(i,u,h){m(m(i,u,h),void 0,n)}function v(i,u){C(i,u)}function A(i,u){C(i,void 0,u)}function b(i,u,h){return m(i,u,h)}function g(i){m(i,void 0,n)}let p=i=>{if(typeof queueMicrotask=="function")p=queueMicrotask;else{let u=f(void 0);p=h=>m(u,h)}return p(i)};function k(i,u,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,h)}function y(i,u,h){try{return f(k(i,u,h))}catch(w){return d(w)}}let E=16384;class D{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(u){let h=this._back,w=h;h._elements.length===E-1&&(w={_elements:[],_next:void 0}),h._elements.push(u),w!==h&&(this._back=w,h._next=w),++this._size}shift(){let u=this._front,h=u,w=this._cursor,R=w+1,L=u._elements,$=L[w];return R===E&&(h=u._next,R=0),--this._size,this._cursor=R,u!==h&&(this._front=h),L[w]=void 0,$}forEach(u){let h=this._cursor,w=this._front,R=w._elements;for(;(h!==R.length||w._next!==void 0)&&!(h===R.length&&(w=w._next,R=w._elements,h=0,R.length===0));)u(R[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let F=Symbol("[[AbortSteps]]"),q=Symbol("[[ErrorSteps]]"),V=Symbol("[[CancelSteps]]"),B=Symbol("[[PullSteps]]"),Y=Symbol("[[ReleaseSteps]]");function te(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?Ee(i):u._state==="closed"?pe(i):se(i,u._storedError)}function Z(i,u){let h=i._ownerReadableStream;return jt(h,u)}function ue(i){let u=i._ownerReadableStream;u._state==="readable"?G(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[Y](),u._reader=void 0,i._ownerReadableStream=void 0}function he(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function Ee(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function se(i,u){Ee(i),G(i,u)}function pe(i){Ee(i),ae(i)}function G(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function K(i,u){se(i,u)}function ae(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let $e=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},ve=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function W(i){return typeof i=="object"||typeof i=="function"}function le(i,u){if(i!==void 0&&!W(i))throw new TypeError(`${u} is not an object.`)}function ye(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}function Bt(i){return typeof i=="object"&&i!==null||typeof i=="function"}function De(i,u){if(!Bt(i))throw new TypeError(`${u} is not an object.`)}function Be(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function _(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function S(i){return Number(i)}function T(i){return i===0?0:i}function M(i){return T(ve(i))}function O(i,u){let w=Number.MAX_SAFE_INTEGER,R=Number(i);if(R=T(R),!$e(R))throw new TypeError(`${u} is not a finite number`);if(R=M(R),R<0||R>w)throw new TypeError(`${u} is outside the accepted range of 0 to ${w}, inclusive`);return!$e(R)||R===0?0:R}function I(i,u){if(!Br(i))throw new TypeError(`${u} is not a ReadableStream.`)}function U(i){return new z(i)}function x(i,u){i._reader._readRequests.push(u)}function P(i,u,h){let R=i._reader._readRequests.shift();h?R._closeSteps():R._chunkSteps(u)}function j(i){return i._reader._readRequests.length}function N(i){let u=i._reader;return!(u===void 0||!X(u))}class z{constructor(u){if(Be(u,1,"ReadableStreamDefaultReader"),I(u,"First parameter"),Mr(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");te(this,u),this._readRequests=new D}get closed(){return X(this)?this._closedPromise:d(Ie("closed"))}cancel(u=void 0){return X(this)?this._ownerReadableStream===void 0?d(he("cancel")):Z(this,u):d(Ie("cancel"))}read(){if(!X(this))return d(Ie("read"));if(this._ownerReadableStream===void 0)return d(he("read from"));let u,h,w=l((L,$)=>{u=L,h=$});return ee(this,{_chunkSteps:L=>u({value:L,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:L=>h(L)}),w}releaseLock(){if(!X(this))throw Ie("releaseLock");this._ownerReadableStream!==void 0&&we(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(z.prototype.cancel,"cancel"),o(z.prototype.read,"read"),o(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function X(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof z}function ee(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[B](u)}function we(i){ue(i);let u=new TypeError("Reader was released");Oe(i,u)}function Oe(i,u){let h=i._readRequests;i._readRequests=new D,h.forEach(w=>{w._errorSteps(u)})}function Ie(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let Ce=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Ae{constructor(u,h){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=h}next(){let u=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?b(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let h=()=>this._returnSteps(u);return this._ongoingPromise?b(this._ongoingPromise,h,h):h()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,h,w,R=l(($,Q)=>{h=$,w=Q});return ee(u,{_chunkSteps:$=>{this._ongoingPromise=void 0,p(()=>h({value:$,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),h({value:void 0,done:!0})},_errorSteps:$=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),w($)}}),R}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let w=Z(h,u);return ue(h),b(w,()=>({value:u,done:!0}))}return ue(h),f({value:u,done:!0})}}let Le={next(){return Tn(this)?this._asyncIteratorImpl.next():d(Dn("next"))},return(i){return Tn(this)?this._asyncIteratorImpl.return(i):d(Dn("return"))}};Object.setPrototypeOf(Le,Ce);function vn(i,u){let h=U(i),w=new Ae(h,u),R=Object.create(Le);return R._asyncIteratorImpl=w,R}function Tn(i){if(!r(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Ae}catch{return!1}}function Dn(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let dt=Number.isNaN||function(i){return i!==i};var fr,Ke,Ue;function Se(i){return i.slice()}function uf(i,u,h,w,R){new Uint8Array(i).set(new Uint8Array(h,w,R),u)}let hr=i=>(typeof i.transfer=="function"?hr=u=>u.transfer():typeof structuredClone=="function"?hr=u=>structuredClone(u,{transfer:[u]}):hr=u=>u,hr(i)),Fr=i=>(typeof i.detached=="boolean"?Fr=u=>u.detached:Fr=u=>u.byteLength===0,Fr(i));function cf(i,u,h){if(i.slice)return i.slice(u,h);let w=h-u,R=new ArrayBuffer(w);return uf(R,0,i,u,w),R}function Ts(i,u){let h=i[u];if(h!=null){if(typeof h!="function")throw new TypeError(`${String(u)} is not a function`);return h}}function z0(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),w=h.next;return{iterator:h,nextMethod:w,done:!1}}let hu=(Ue=(fr=Symbol.asyncIterator)!==null&&fr!==void 0?fr:(Ke=Symbol.for)===null||Ke===void 0?void 0:Ke.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function lf(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=Ts(i,hu),h===void 0){let L=Ts(i,Symbol.iterator),$=lf(i,"sync",L);return z0($)}}else h=Ts(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let w=k(h,i,[]);if(!r(w))throw new TypeError("The iterator method must return an object");let R=w.next;return{iterator:w,nextMethod:R,done:!1}}function H0(i){let u=k(i.nextMethod,i.iterator,[]);if(!r(u))throw new TypeError("The iterator.next() method must return an object");return u}function W0(i){return!!i.done}function G0(i){return i.value}function J0(i){return!(typeof i!="number"||dt(i)||i<0)}function df(i){let u=cf(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function pu(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function mu(i,u,h){if(!J0(h)||h===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:u,size:h}),i._queueTotalSize+=h}function V0(i){return i._queue.peek().value}function Pr(i){i._queue=new D,i._queueTotalSize=0}function ff(i){return i===DataView}function K0(i){return ff(i.constructor)}function Y0(i){return ff(i)?1:i.BYTES_PER_ELEMENT}class Xr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!gu(this))throw wu("view");return this._view}respond(u){if(!gu(this))throw wu("respond");if(Be(u,1,"respond"),u=O(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Fr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Os(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!gu(this))throw wu("respondWithNewView");if(Be(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))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(Fr(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Fs(this._associatedReadableByteStreamController,u)}}Object.defineProperties(Xr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(Xr.prototype.respond,"respond"),o(Xr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class pr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Zr(this))throw Eo("byobRequest");return Cu(this)}get desiredSize(){if(!Zr(this))throw Eo("desiredSize");return Ef(this)}close(){if(!Zr(this))throw Eo("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw new TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);wo(this)}enqueue(u){if(!Zr(this))throw Eo("enqueue");if(Be(u,1,"enqueue"),!ArrayBuffer.isView(u))throw new TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(u.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 h=this._controlledReadableByteStream._state;if(h!=="readable")throw new TypeError(`The stream (in ${h} state) is not in the readable state and cannot be enqueued to`);xs(this,u)}error(u=void 0){if(!Zr(this))throw Eo("error");St(this,u)}[V](u){hf(this),Pr(this);let h=this._cancelAlgorithm(u);return Rs(this),h}[B](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){wf(this,u);return}let w=this._autoAllocateChunkSize;if(w!==void 0){let R;try{R=new ArrayBuffer(w)}catch($){u._errorSteps($);return}let L={buffer:R,bufferByteLength:w,byteOffset:0,byteLength:w,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}x(h,u),en(this)}[Y](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new D,this._pendingPullIntos.push(u)}}}Object.defineProperties(pr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(pr.prototype.close,"close"),o(pr.prototype.enqueue,"enqueue"),o(pr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Zr(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof pr}function gu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof Xr}function en(i){if(!t_(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();C(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,en(i)),null),w=>(St(i,w),null))}function hf(i){_u(i),i._pendingPullIntos=new D}function yu(i,u){let h=!1;i._state==="closed"&&(h=!0);let w=pf(u);u.readerType==="default"?P(i,w,h):a_(i,w,h)}function pf(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function Ds(i,u,h,w){i._queue.push({buffer:u,byteOffset:h,byteLength:w}),i._queueTotalSize+=w}function mf(i,u,h,w){let R;try{R=cf(u,h,h+w)}catch(L){throw St(i,L),L}Ds(i,R,0,w)}function gf(i,u){u.bytesFilled>0&&mf(i,u.buffer,u.byteOffset,u.bytesFilled),Rn(i)}function yf(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),w=u.bytesFilled+h,R=h,L=!1,$=w%u.elementSize,Q=w-$;Q>=u.minimumFill&&(R=Q-u.bytesFilled,L=!0);let ce=i._queue;for(;R>0;){let ne=ce.peek(),de=Math.min(R,ne.byteLength),ge=u.byteOffset+u.bytesFilled;uf(u.buffer,ge,ne.buffer,ne.byteOffset,de),ne.byteLength===de?ce.shift():(ne.byteOffset+=de,ne.byteLength-=de),i._queueTotalSize-=de,_f(i,de,u),R-=de}return L}function _f(i,u,h){h.bytesFilled+=u}function bf(i){i._queueTotalSize===0&&i._closeRequested?(Rs(i),Do(i._controlledReadableByteStream)):en(i)}function _u(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function bu(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();yf(i,u)&&(Rn(i),yu(i._controlledReadableByteStream,u))}}function Q0(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();wf(i,h)}}function X0(i,u,h,w){let R=i._controlledReadableByteStream,L=u.constructor,$=Y0(L),{byteOffset:Q,byteLength:ce}=u,ne=h*$,de;try{de=hr(u.buffer)}catch(Te){w._errorSteps(Te);return}let ge={buffer:de,bufferByteLength:de.byteLength,byteOffset:Q,byteLength:ce,bytesFilled:0,minimumFill:ne,elementSize:$,viewConstructor:L,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ge),kf(R,w);return}if(R._state==="closed"){let Te=new L(ge.buffer,ge.byteOffset,0);w._closeSteps(Te);return}if(i._queueTotalSize>0){if(yf(i,ge)){let Te=pf(ge);bf(i),w._chunkSteps(Te);return}if(i._closeRequested){let Te=new TypeError("Insufficient bytes to fill elements in the given buffer");St(i,Te),w._errorSteps(Te);return}}i._pendingPullIntos.push(ge),kf(R,w),en(i)}function Z0(i,u){u.readerType==="none"&&Rn(i);let h=i._controlledReadableByteStream;if(Eu(h))for(;vf(h)>0;){let w=Rn(i);yu(h,w)}}function e_(i,u,h){if(_f(i,u,h),h.readerType==="none"){gf(i,h),bu(i);return}if(h.bytesFilled<h.minimumFill)return;Rn(i);let w=h.bytesFilled%h.elementSize;if(w>0){let R=h.byteOffset+h.bytesFilled;mf(i,h.buffer,R-w,w)}h.bytesFilled-=w,yu(i._controlledReadableByteStream,h),bu(i)}function Cf(i,u){let h=i._pendingPullIntos.peek();_u(i),i._controlledReadableByteStream._state==="closed"?Z0(i,h):e_(i,u,h),en(i)}function Rn(i){return i._pendingPullIntos.shift()}function t_(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(N(u)&&j(u)>0||Eu(u)&&vf(u)>0||Ef(i)>0)}function Rs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function wo(i){let u=i._controlledReadableByteStream;if(!(i._closeRequested||u._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let h=i._pendingPullIntos.peek();if(h.bytesFilled%h.elementSize!==0){let w=new TypeError("Insufficient bytes to fill elements in the given buffer");throw St(i,w),w}}Rs(i),Do(u)}}function xs(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:w,byteOffset:R,byteLength:L}=u;if(Fr(w))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let $=hr(w);if(i._pendingPullIntos.length>0){let Q=i._pendingPullIntos.peek();if(Fr(Q.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");_u(i),Q.buffer=hr(Q.buffer),Q.readerType==="none"&&gf(i,Q)}if(N(h))if(Q0(i),j(h)===0)Ds(i,$,R,L);else{i._pendingPullIntos.length>0&&Rn(i);let Q=new Uint8Array($,R,L);P(h,Q,!1)}else Eu(h)?(Ds(i,$,R,L),bu(i)):Ds(i,$,R,L);en(i)}function St(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(hf(i),Pr(i),Rs(i),Yf(h,u))}function wf(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,bf(i);let w=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(w)}function Cu(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let u=i._pendingPullIntos.peek(),h=new Uint8Array(u.buffer,u.byteOffset+u.bytesFilled,u.byteLength-u.bytesFilled),w=Object.create(Xr.prototype);n_(w,i,h),i._byobRequest=w}return i._byobRequest}function Ef(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function Os(i,u){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(u===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(h.bytesFilled+u>h.byteLength)throw new RangeError("bytesWritten out of range")}h.buffer=hr(h.buffer),Cf(i,u)}function Fs(i,u){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(u.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(h.byteOffset+h.bytesFilled!==u.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(h.bufferByteLength!==u.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(h.bytesFilled+u.byteLength>h.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let R=u.byteLength;h.buffer=hr(u.buffer),Cf(i,R)}function Af(i,u,h,w,R,L,$){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Pr(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=L,u._pullAlgorithm=w,u._cancelAlgorithm=R,u._autoAllocateChunkSize=$,u._pendingPullIntos=new D,i._readableStreamController=u;let Q=h();C(f(Q),()=>(u._started=!0,en(u),null),ce=>(St(u,ce),null))}function r_(i,u,h){let w=Object.create(pr.prototype),R,L,$;u.start!==void 0?R=()=>u.start(w):R=()=>{},u.pull!==void 0?L=()=>u.pull(w):L=()=>f(void 0),u.cancel!==void 0?$=ce=>u.cancel(ce):$=()=>f(void 0);let Q=u.autoAllocateChunkSize;if(Q===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Af(i,w,R,L,$,h,Q)}function n_(i,u,h){i._associatedReadableByteStreamController=u,i._view=h}function wu(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function Eo(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function o_(i,u){le(i,u);let h=i?.mode;return{mode:h===void 0?void 0:s_(h,`${u} has member 'mode' that`)}}function s_(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function i_(i,u){var h;le(i,u);let w=(h=i?.min)!==null&&h!==void 0?h:1;return{min:O(w,`${u} has member 'min' that`)}}function Sf(i){return new Ir(i)}function kf(i,u){i._reader._readIntoRequests.push(u)}function a_(i,u,h){let R=i._reader._readIntoRequests.shift();h?R._closeSteps(u):R._chunkSteps(u)}function vf(i){return i._reader._readIntoRequests.length}function Eu(i){let u=i._reader;return!(u===void 0||!tn(u))}class Ir{constructor(u){if(Be(u,1,"ReadableStreamBYOBReader"),I(u,"First parameter"),Mr(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Zr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");te(this,u),this._readIntoRequests=new D}get closed(){return tn(this)?this._closedPromise:d(Ps("closed"))}cancel(u=void 0){return tn(this)?this._ownerReadableStream===void 0?d(he("cancel")):Z(this,u):d(Ps("cancel"))}read(u,h={}){if(!tn(this))return d(Ps("read"));if(!ArrayBuffer.isView(u))return d(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(Fr(u.buffer))return d(new TypeError("view's buffer has been detached"));let w;try{w=i_(h,"options")}catch(ne){return d(ne)}let R=w.min;if(R===0)return d(new TypeError("options.min must be greater than 0"));if(K0(u)){if(R>u.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(R>u.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(he("read from"));let L,$,Q=l((ne,de)=>{L=ne,$=de});return Tf(this,u,R,{_chunkSteps:ne=>L({value:ne,done:!1}),_closeSteps:ne=>L({value:ne,done:!0}),_errorSteps:ne=>$(ne)}),Q}releaseLock(){if(!tn(this))throw Ps("releaseLock");this._ownerReadableStream!==void 0&&u_(this)}}Object.defineProperties(Ir.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ir.prototype.cancel,"cancel"),o(Ir.prototype.read,"read"),o(Ir.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ir.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function tn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Ir}function Tf(i,u,h,w){let R=i._ownerReadableStream;R._disturbed=!0,R._state==="errored"?w._errorSteps(R._storedError):X0(R._readableStreamController,u,h,w)}function u_(i){ue(i);let u=new TypeError("Reader was released");Df(i,u)}function Df(i,u){let h=i._readIntoRequests;i._readIntoRequests=new D,h.forEach(w=>{w._errorSteps(u)})}function Ps(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function Ao(i,u){let{highWaterMark:h}=i;if(h===void 0)return u;if(dt(h)||h<0)throw new RangeError("Invalid highWaterMark");return h}function Is(i){let{size:u}=i;return u||(()=>1)}function Ns(i,u){le(i,u);let h=i?.highWaterMark,w=i?.size;return{highWaterMark:h===void 0?void 0:S(h),size:w===void 0?void 0:c_(w,`${u} has member 'size' that`)}}function c_(i,u){return ye(i,u),h=>S(i(h))}function l_(i,u){le(i,u);let h=i?.abort,w=i?.close,R=i?.start,L=i?.type,$=i?.write;return{abort:h===void 0?void 0:d_(h,i,`${u} has member 'abort' that`),close:w===void 0?void 0:f_(w,i,`${u} has member 'close' that`),start:R===void 0?void 0:h_(R,i,`${u} has member 'start' that`),write:$===void 0?void 0:p_($,i,`${u} has member 'write' that`),type:L}}function d_(i,u,h){return ye(i,h),w=>y(i,u,[w])}function f_(i,u,h){return ye(i,h),()=>y(i,u,[])}function h_(i,u,h){return ye(i,h),w=>k(i,u,[w])}function p_(i,u,h){return ye(i,h),(w,R)=>y(i,u,[w,R])}function Rf(i,u){if(!xn(i))throw new TypeError(`${u} is not a WritableStream.`)}function m_(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let g_=typeof AbortController=="function";function y_(){if(g_)return new AbortController}class Nr{constructor(u={},h={}){u===void 0?u=null:De(u,"First parameter");let w=Ns(h,"Second parameter"),R=l_(u,"First parameter");if(Of(this),R.type!==void 0)throw new RangeError("Invalid type is specified");let $=Is(w),Q=Ao(w,1);O_(this,R,Q,$)}get locked(){if(!xn(this))throw Us("locked");return On(this)}abort(u=void 0){return xn(this)?On(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Bs(this,u):d(Us("abort"))}close(){return xn(this)?On(this)?d(new TypeError("Cannot close a stream that already has a writer")):Qt(this)?d(new TypeError("Cannot close an already-closing stream")):Ff(this):d(Us("close"))}getWriter(){if(!xn(this))throw Us("getWriter");return xf(this)}}Object.defineProperties(Nr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Nr.prototype.abort,"abort"),o(Nr.prototype.close,"close"),o(Nr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function xf(i){return new mr(i)}function __(i,u,h,w,R=1,L=()=>1){let $=Object.create(Nr.prototype);Of($);let Q=Object.create(Fn.prototype);return jf($,Q,i,u,h,w,R,L),$}function Of(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new D,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function xn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof Nr}function On(i){return i._writer!==void 0}function Bs(i,u){var h;if(i._state==="closed"||i._state==="errored")return f(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let w=i._state;if(w==="closed"||w==="errored")return f(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let R=!1;w==="erroring"&&(R=!0,u=void 0);let L=l(($,Q)=>{i._pendingAbortRequest={_promise:void 0,_resolve:$,_reject:Q,_reason:u,_wasAlreadyErroring:R}});return i._pendingAbortRequest._promise=L,R||Su(i,u),L}function Ff(i){let u=i._state;if(u==="closed"||u==="errored")return d(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((R,L)=>{let $={_resolve:R,_reject:L};i._closeRequest=$}),w=i._writer;return w!==void 0&&i._backpressure&&u==="writable"&&Fu(w),F_(i._writableStreamController),h}function b_(i){return l((h,w)=>{let R={_resolve:h,_reject:w};i._writeRequests.push(R)})}function Au(i,u){if(i._state==="writable"){Su(i,u);return}ku(i)}function Su(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let w=i._writer;w!==void 0&&If(w,u),!S_(i)&&h._started&&ku(i)}function ku(i){i._state="errored",i._writableStreamController[q]();let u=i._storedError;if(i._writeRequests.forEach(R=>{R._reject(u)}),i._writeRequests=new D,i._pendingAbortRequest===void 0){Ms(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),Ms(i);return}let w=i._writableStreamController[F](h._reason);C(w,()=>(h._resolve(),Ms(i),null),R=>(h._reject(R),Ms(i),null))}function C_(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function w_(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,Au(i,u)}function E_(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let h=i._writer;h!==void 0&&qf(h)}function A_(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),Au(i,u)}function Qt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function S_(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function k_(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function v_(i){i._inFlightWriteRequest=i._writeRequests.shift()}function Ms(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&xu(u,i._storedError)}function vu(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?L_(h):Fu(h)),i._backpressure=u}class mr{constructor(u){if(Be(u,1,"WritableStreamDefaultWriter"),Rf(u,"First parameter"),On(u))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let h=u._state;if(h==="writable")!Qt(u)&&u._backpressure?qs(this):zf(this),$s(this);else if(h==="erroring")Ou(this,u._storedError),$s(this);else if(h==="closed")zf(this),M_(this);else{let w=u._storedError;Ou(this,w),$f(this,w)}}get closed(){return rn(this)?this._closedPromise:d(nn("closed"))}get desiredSize(){if(!rn(this))throw nn("desiredSize");if(this._ownerWritableStream===void 0)throw ko("desiredSize");return x_(this)}get ready(){return rn(this)?this._readyPromise:d(nn("ready"))}abort(u=void 0){return rn(this)?this._ownerWritableStream===void 0?d(ko("abort")):T_(this,u):d(nn("abort"))}close(){if(!rn(this))return d(nn("close"));let u=this._ownerWritableStream;return u===void 0?d(ko("close")):Qt(u)?d(new TypeError("Cannot close an already-closing stream")):Pf(this)}releaseLock(){if(!rn(this))throw nn("releaseLock");this._ownerWritableStream!==void 0&&Nf(this)}write(u=void 0){return rn(this)?this._ownerWritableStream===void 0?d(ko("write to")):Bf(this,u):d(nn("write"))}}Object.defineProperties(mr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(mr.prototype.abort,"abort"),o(mr.prototype.close,"close"),o(mr.prototype.releaseLock,"releaseLock"),o(mr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function rn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof mr}function T_(i,u){let h=i._ownerWritableStream;return Bs(h,u)}function Pf(i){let u=i._ownerWritableStream;return Ff(u)}function D_(i){let u=i._ownerWritableStream,h=u._state;return Qt(u)||h==="closed"?f(void 0):h==="errored"?d(u._storedError):Pf(i)}function R_(i,u){i._closedPromiseState==="pending"?xu(i,u):j_(i,u)}function If(i,u){i._readyPromiseState==="pending"?Hf(i,u):U_(i,u)}function x_(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:Lf(u._writableStreamController)}function Nf(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");If(i,h),R_(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function Bf(i,u){let h=i._ownerWritableStream,w=h._writableStreamController,R=P_(w,u);if(h!==i._ownerWritableStream)return d(ko("write to"));let L=h._state;if(L==="errored")return d(h._storedError);if(Qt(h)||L==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return d(h._storedError);let $=b_(h);return I_(w,u,R),$}let Mf={};class Fn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Tu(this))throw Ru("abortReason");return this._abortReason}get signal(){if(!Tu(this))throw Ru("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!Tu(this))throw Ru("error");this._controlledWritableStream._state==="writable"&&Uf(this,u)}[F](u){let h=this._abortAlgorithm(u);return js(this),h}[q](){Pr(this)}}Object.defineProperties(Fn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Tu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Fn}function jf(i,u,h,w,R,L,$,Q){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Pr(u),u._abortReason=void 0,u._abortController=y_(),u._started=!1,u._strategySizeAlgorithm=Q,u._strategyHWM=$,u._writeAlgorithm=w,u._closeAlgorithm=R,u._abortAlgorithm=L;let ce=Du(u);vu(i,ce);let ne=h(),de=f(ne);C(de,()=>(u._started=!0,Ls(u),null),ge=>(u._started=!0,Au(i,ge),null))}function O_(i,u,h,w){let R=Object.create(Fn.prototype),L,$,Q,ce;u.start!==void 0?L=()=>u.start(R):L=()=>{},u.write!==void 0?$=ne=>u.write(ne,R):$=()=>f(void 0),u.close!==void 0?Q=()=>u.close():Q=()=>f(void 0),u.abort!==void 0?ce=ne=>u.abort(ne):ce=()=>f(void 0),jf(i,R,L,$,Q,ce,h,w)}function js(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function F_(i){mu(i,Mf,0),Ls(i)}function P_(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return So(i,h),1}}function Lf(i){return i._strategyHWM-i._queueTotalSize}function I_(i,u,h){try{mu(i,u,h)}catch(R){So(i,R);return}let w=i._controlledWritableStream;if(!Qt(w)&&w._state==="writable"){let R=Du(i);vu(w,R)}Ls(i)}function Ls(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){ku(u);return}if(i._queue.length===0)return;let w=V0(i);w===Mf?N_(i):B_(i,w)}function So(i,u){i._controlledWritableStream._state==="writable"&&Uf(i,u)}function N_(i){let u=i._controlledWritableStream;k_(u),pu(i);let h=i._closeAlgorithm();js(i),C(h,()=>(E_(u),null),w=>(A_(u,w),null))}function B_(i,u){let h=i._controlledWritableStream;v_(h);let w=i._writeAlgorithm(u);C(w,()=>{C_(h);let R=h._state;if(pu(i),!Qt(h)&&R==="writable"){let L=Du(i);vu(h,L)}return Ls(i),null},R=>(h._state==="writable"&&js(i),w_(h,R),null))}function Du(i){return Lf(i)<=0}function Uf(i,u){let h=i._controlledWritableStream;js(i),Su(h,u)}function Us(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function Ru(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function nn(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function ko(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function $s(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function $f(i,u){$s(i),xu(i,u)}function M_(i){$s(i),qf(i)}function xu(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function j_(i,u){$f(i,u)}function qf(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}function qs(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function Ou(i,u){qs(i),Hf(i,u)}function zf(i){qs(i),Fu(i)}function Hf(i,u){i._readyPromise_reject!==void 0&&(g(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function L_(i){qs(i)}function U_(i,u){Ou(i,u)}function Fu(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}function $_(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Pu=$_();function q_(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function z_(){let i=Pu?.DOMException;return q_(i)?i:void 0}function H_(){let i=function(h,w){this.message=h||"",this.name=w||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}let W_=z_()||H_();function Wf(i,u,h,w,R,L){let $=U(i),Q=xf(u);i._disturbed=!0;let ce=!1,ne=f(void 0);return l((de,ge)=>{let Te;if(L!==void 0){if(Te=()=>{let oe=L.reason!==void 0?L.reason:new W_("Aborted","AbortError"),_e=[];w||_e.push(()=>u._state==="writable"?Bs(u,oe):f(void 0)),R||_e.push(()=>i._state==="readable"?jt(i,oe):f(void 0)),nt(()=>Promise.all(_e.map(Re=>Re())),!0,oe)},L.aborted){Te();return}L.addEventListener("abort",Te)}function Lt(){return l((oe,_e)=>{function Re(ft){ft?oe():m(Bn(),Re,_e)}Re(!1)})}function Bn(){return ce?f(!0):m(Q._readyPromise,()=>l((oe,_e)=>{ee($,{_chunkSteps:Re=>{ne=m(Bf(Q,Re),void 0,e),oe(!1)},_closeSteps:()=>oe(!0),_errorSteps:_e})}))}if(yr(i,$._closedPromise,oe=>(w?kt(!0,oe):nt(()=>Bs(u,oe),!0,oe),null)),yr(u,Q._closedPromise,oe=>(R?kt(!0,oe):nt(()=>jt(i,oe),!0,oe),null)),Xe(i,$._closedPromise,()=>(h?kt():nt(()=>D_(Q)),null)),Qt(u)||u._state==="closed"){let oe=new TypeError("the destination writable stream closed before all data could be piped to it");R?kt(!0,oe):nt(()=>jt(i,oe),!0,oe)}g(Lt());function Lr(){let oe=ne;return m(ne,()=>oe!==ne?Lr():void 0)}function yr(oe,_e,Re){oe._state==="errored"?Re(oe._storedError):A(_e,Re)}function Xe(oe,_e,Re){oe._state==="closed"?Re():v(_e,Re)}function nt(oe,_e,Re){if(ce)return;ce=!0,u._state==="writable"&&!Qt(u)?v(Lr(),ft):ft();function ft(){return C(oe(),()=>_r(_e,Re),Mn=>_r(!0,Mn)),null}}function kt(oe,_e){ce||(ce=!0,u._state==="writable"&&!Qt(u)?v(Lr(),()=>_r(oe,_e)):_r(oe,_e))}function _r(oe,_e){return Nf(Q),ue($),L!==void 0&&L.removeEventListener("abort",Te),oe?ge(_e):de(void 0),null}})}class gr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!zs(this))throw Ws("desiredSize");return Iu(this)}close(){if(!zs(this))throw Ws("close");if(!In(this))throw new TypeError("The stream is not in a state that permits close");on(this)}enqueue(u=void 0){if(!zs(this))throw Ws("enqueue");if(!In(this))throw new TypeError("The stream is not in a state that permits enqueue");return Pn(this,u)}error(u=void 0){if(!zs(this))throw Ws("error");Mt(this,u)}[V](u){Pr(this);let h=this._cancelAlgorithm(u);return Hs(this),h}[B](u){let h=this._controlledReadableStream;if(this._queue.length>0){let w=pu(this);this._closeRequested&&this._queue.length===0?(Hs(this),Do(h)):vo(this),u._chunkSteps(w)}else x(h,u),vo(this)}[Y](){}}Object.defineProperties(gr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(gr.prototype.close,"close"),o(gr.prototype.enqueue,"enqueue"),o(gr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function zs(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof gr}function vo(i){if(!Gf(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();C(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,vo(i)),null),w=>(Mt(i,w),null))}function Gf(i){let u=i._controlledReadableStream;return!In(i)||!i._started?!1:!!(Mr(u)&&j(u)>0||Iu(i)>0)}function Hs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function on(i){if(!In(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Hs(i),Do(u))}function Pn(i,u){if(!In(i))return;let h=i._controlledReadableStream;if(Mr(h)&&j(h)>0)P(h,u,!1);else{let w;try{w=i._strategySizeAlgorithm(u)}catch(R){throw Mt(i,R),R}try{mu(i,u,w)}catch(R){throw Mt(i,R),R}}vo(i)}function Mt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Pr(i),Hs(i),Yf(h,u))}function Iu(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function G_(i){return!Gf(i)}function In(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function Jf(i,u,h,w,R,L,$){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Pr(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=$,u._strategyHWM=L,u._pullAlgorithm=w,u._cancelAlgorithm=R,i._readableStreamController=u;let Q=h();C(f(Q),()=>(u._started=!0,vo(u),null),ce=>(Mt(u,ce),null))}function J_(i,u,h,w){let R=Object.create(gr.prototype),L,$,Q;u.start!==void 0?L=()=>u.start(R):L=()=>{},u.pull!==void 0?$=()=>u.pull(R):$=()=>f(void 0),u.cancel!==void 0?Q=ce=>u.cancel(ce):Q=()=>f(void 0),Jf(i,R,L,$,Q,h,w)}function Ws(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function V_(i,u){return Zr(i._readableStreamController)?Y_(i):K_(i)}function K_(i,u){let h=U(i),w=!1,R=!1,L=!1,$=!1,Q,ce,ne,de,ge,Te=l(Xe=>{ge=Xe});function Lt(){return w?(R=!0,f(void 0)):(w=!0,ee(h,{_chunkSteps:nt=>{p(()=>{R=!1;let kt=nt,_r=nt;L||Pn(ne._readableStreamController,kt),$||Pn(de._readableStreamController,_r),w=!1,R&&Lt()})},_closeSteps:()=>{w=!1,L||on(ne._readableStreamController),$||on(de._readableStreamController),(!L||!$)&&ge(void 0)},_errorSteps:()=>{w=!1}}),f(void 0))}function Bn(Xe){if(L=!0,Q=Xe,$){let nt=Se([Q,ce]),kt=jt(i,nt);ge(kt)}return Te}function Lr(Xe){if($=!0,ce=Xe,L){let nt=Se([Q,ce]),kt=jt(i,nt);ge(kt)}return Te}function yr(){}return ne=To(yr,Lt,Bn),de=To(yr,Lt,Lr),A(h._closedPromise,Xe=>(Mt(ne._readableStreamController,Xe),Mt(de._readableStreamController,Xe),(!L||!$)&&ge(void 0),null)),[ne,de]}function Y_(i){let u=U(i),h=!1,w=!1,R=!1,L=!1,$=!1,Q,ce,ne,de,ge,Te=l(oe=>{ge=oe});function Lt(oe){A(oe._closedPromise,_e=>(oe!==u||(St(ne._readableStreamController,_e),St(de._readableStreamController,_e),(!L||!$)&&ge(void 0)),null))}function Bn(){tn(u)&&(ue(u),u=U(i),Lt(u)),ee(u,{_chunkSteps:_e=>{p(()=>{w=!1,R=!1;let Re=_e,ft=_e;if(!L&&!$)try{ft=df(_e)}catch(Mn){St(ne._readableStreamController,Mn),St(de._readableStreamController,Mn),ge(jt(i,Mn));return}L||xs(ne._readableStreamController,Re),$||xs(de._readableStreamController,ft),h=!1,w?yr():R&&Xe()})},_closeSteps:()=>{h=!1,L||wo(ne._readableStreamController),$||wo(de._readableStreamController),ne._readableStreamController._pendingPullIntos.length>0&&Os(ne._readableStreamController,0),de._readableStreamController._pendingPullIntos.length>0&&Os(de._readableStreamController,0),(!L||!$)&&ge(void 0)},_errorSteps:()=>{h=!1}})}function Lr(oe,_e){X(u)&&(ue(u),u=Sf(i),Lt(u));let Re=_e?de:ne,ft=_e?ne:de;Tf(u,oe,1,{_chunkSteps:jn=>{p(()=>{w=!1,R=!1;let Ln=_e?$:L;if(_e?L:$)Ln||Fs(Re._readableStreamController,jn);else{let ch;try{ch=df(jn)}catch(Lu){St(Re._readableStreamController,Lu),St(ft._readableStreamController,Lu),ge(jt(i,Lu));return}Ln||Fs(Re._readableStreamController,jn),xs(ft._readableStreamController,ch)}h=!1,w?yr():R&&Xe()})},_closeSteps:jn=>{h=!1;let Ln=_e?$:L,Zs=_e?L:$;Ln||wo(Re._readableStreamController),Zs||wo(ft._readableStreamController),jn!==void 0&&(Ln||Fs(Re._readableStreamController,jn),!Zs&&ft._readableStreamController._pendingPullIntos.length>0&&Os(ft._readableStreamController,0)),(!Ln||!Zs)&&ge(void 0)},_errorSteps:()=>{h=!1}})}function yr(){if(h)return w=!0,f(void 0);h=!0;let oe=Cu(ne._readableStreamController);return oe===null?Bn():Lr(oe._view,!1),f(void 0)}function Xe(){if(h)return R=!0,f(void 0);h=!0;let oe=Cu(de._readableStreamController);return oe===null?Bn():Lr(oe._view,!0),f(void 0)}function nt(oe){if(L=!0,Q=oe,$){let _e=Se([Q,ce]),Re=jt(i,_e);ge(Re)}return Te}function kt(oe){if($=!0,ce=oe,L){let _e=Se([Q,ce]),Re=jt(i,_e);ge(Re)}return Te}function _r(){}return ne=Kf(_r,yr,nt),de=Kf(_r,Xe,kt),Lt(u),[ne,de]}function Q_(i){return r(i)&&typeof i.getReader<"u"}function X_(i){return Q_(i)?eb(i.getReader()):Z_(i)}function Z_(i){let u,h=lf(i,"async"),w=e;function R(){let $;try{$=H0(h)}catch(ce){return d(ce)}let Q=f($);return b(Q,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(W0(ce))on(u._readableStreamController);else{let de=G0(ce);Pn(u._readableStreamController,de)}})}function L($){let Q=h.iterator,ce;try{ce=Ts(Q,"return")}catch(ge){return d(ge)}if(ce===void 0)return f(void 0);let ne;try{ne=k(ce,Q,[$])}catch(ge){return d(ge)}let de=f(ne);return b(de,ge=>{if(!r(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=To(w,R,L,0),u}function eb(i){let u,h=e;function w(){let L;try{L=i.read()}catch($){return d($)}return b(L,$=>{if(!r($))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if($.done)on(u._readableStreamController);else{let Q=$.value;Pn(u._readableStreamController,Q)}})}function R(L){try{return f(i.cancel(L))}catch($){return d($)}}return u=To(h,w,R,0),u}function tb(i,u){le(i,u);let h=i,w=h?.autoAllocateChunkSize,R=h?.cancel,L=h?.pull,$=h?.start,Q=h?.type;return{autoAllocateChunkSize:w===void 0?void 0:O(w,`${u} has member 'autoAllocateChunkSize' that`),cancel:R===void 0?void 0:rb(R,h,`${u} has member 'cancel' that`),pull:L===void 0?void 0:nb(L,h,`${u} has member 'pull' that`),start:$===void 0?void 0:ob($,h,`${u} has member 'start' that`),type:Q===void 0?void 0:sb(Q,`${u} has member 'type' that`)}}function rb(i,u,h){return ye(i,h),w=>y(i,u,[w])}function nb(i,u,h){return ye(i,h),w=>y(i,u,[w])}function ob(i,u,h){return ye(i,h),w=>k(i,u,[w])}function sb(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function ib(i,u){return le(i,u),{preventCancel:!!i?.preventCancel}}function Vf(i,u){le(i,u);let h=i?.preventAbort,w=i?.preventCancel,R=i?.preventClose,L=i?.signal;return L!==void 0&&ab(L,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!w,preventClose:!!R,signal:L}}function ab(i,u){if(!m_(i))throw new TypeError(`${u} is not an AbortSignal.`)}function ub(i,u){le(i,u);let h=i?.readable;_(h,"readable","ReadableWritablePair"),I(h,`${u} has member 'readable' that`);let w=i?.writable;return _(w,"writable","ReadableWritablePair"),Rf(w,`${u} has member 'writable' that`),{readable:h,writable:w}}class Ye{constructor(u={},h={}){u===void 0?u=null:De(u,"First parameter");let w=Ns(h,"Second parameter"),R=tb(u,"First parameter");if(Nu(this),R.type==="bytes"){if(w.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=Ao(w,0);r_(this,R,L)}else{let L=Is(w),$=Ao(w,1);J_(this,R,$,L)}}get locked(){if(!Br(this))throw sn("locked");return Mr(this)}cancel(u=void 0){return Br(this)?Mr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):jt(this,u):d(sn("cancel"))}getReader(u=void 0){if(!Br(this))throw sn("getReader");return o_(u,"First parameter").mode===void 0?U(this):Sf(this)}pipeThrough(u,h={}){if(!Br(this))throw sn("pipeThrough");Be(u,1,"pipeThrough");let w=ub(u,"First parameter"),R=Vf(h,"Second parameter");if(Mr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(On(w.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=Wf(this,w.writable,R.preventClose,R.preventAbort,R.preventCancel,R.signal);return g(L),w.readable}pipeTo(u,h={}){if(!Br(this))return d(sn("pipeTo"));if(u===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!xn(u))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let w;try{w=Vf(h,"Second parameter")}catch(R){return d(R)}return Mr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):On(u)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Wf(this,u,w.preventClose,w.preventAbort,w.preventCancel,w.signal)}tee(){if(!Br(this))throw sn("tee");let u=V_(this);return Se(u)}values(u=void 0){if(!Br(this))throw sn("values");let h=ib(u,"First parameter");return vn(this,h.preventCancel)}[hu](u){return this.values(u)}static from(u){return X_(u)}}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}}),o(Ye.from,"from"),o(Ye.prototype.cancel,"cancel"),o(Ye.prototype.getReader,"getReader"),o(Ye.prototype.pipeThrough,"pipeThrough"),o(Ye.prototype.pipeTo,"pipeTo"),o(Ye.prototype.tee,"tee"),o(Ye.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ye.prototype,hu,{value:Ye.prototype.values,writable:!0,configurable:!0});function To(i,u,h,w=1,R=()=>1){let L=Object.create(Ye.prototype);Nu(L);let $=Object.create(gr.prototype);return Jf(L,$,i,u,h,w,R),L}function Kf(i,u,h){let w=Object.create(Ye.prototype);Nu(w);let R=Object.create(pr.prototype);return Af(w,R,i,u,h,0,void 0),w}function Nu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Br(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof Ye}function Mr(i){return i._reader!==void 0}function jt(i,u){if(i._disturbed=!0,i._state==="closed")return f(void 0);if(i._state==="errored")return d(i._storedError);Do(i);let h=i._reader;if(h!==void 0&&tn(h)){let R=h._readIntoRequests;h._readIntoRequests=new D,R.forEach(L=>{L._closeSteps(void 0)})}let w=i._readableStreamController[V](u);return b(w,e)}function Do(i){i._state="closed";let u=i._reader;if(u!==void 0&&(ae(u),X(u))){let h=u._readRequests;u._readRequests=new D,h.forEach(w=>{w._closeSteps()})}}function Yf(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(G(h,u),X(h)?Oe(h,u):Df(h,u))}function sn(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function Qf(i,u){le(i,u);let h=i?.highWaterMark;return _(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:S(h)}}let Xf=i=>i.byteLength;o(Xf,"size");class Gs{constructor(u){Be(u,1,"ByteLengthQueuingStrategy"),u=Qf(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!eh(this))throw Zf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!eh(this))throw Zf("size");return Xf}}Object.defineProperties(Gs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Gs.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Zf(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function eh(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof Gs}let th=()=>1;o(th,"size");class Js{constructor(u){Be(u,1,"CountQueuingStrategy"),u=Qf(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!nh(this))throw rh("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!nh(this))throw rh("size");return th}}Object.defineProperties(Js.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Js.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function rh(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function nh(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof Js}function cb(i,u){le(i,u);let h=i?.cancel,w=i?.flush,R=i?.readableType,L=i?.start,$=i?.transform,Q=i?.writableType;return{cancel:h===void 0?void 0:hb(h,i,`${u} has member 'cancel' that`),flush:w===void 0?void 0:lb(w,i,`${u} has member 'flush' that`),readableType:R,start:L===void 0?void 0:db(L,i,`${u} has member 'start' that`),transform:$===void 0?void 0:fb($,i,`${u} has member 'transform' that`),writableType:Q}}function lb(i,u,h){return ye(i,h),w=>y(i,u,[w])}function db(i,u,h){return ye(i,h),w=>k(i,u,[w])}function fb(i,u,h){return ye(i,h),(w,R)=>y(i,u,[w,R])}function hb(i,u,h){return ye(i,h),w=>y(i,u,[w])}class Vs{constructor(u={},h={},w={}){u===void 0&&(u=null);let R=Ns(h,"Second parameter"),L=Ns(w,"Third parameter"),$=cb(u,"First parameter");if($.readableType!==void 0)throw new RangeError("Invalid readableType specified");if($.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Q=Ao(L,0),ce=Is(L),ne=Ao(R,1),de=Is(R),ge,Te=l(Lt=>{ge=Lt});pb(this,Te,ne,de,Q,ce),gb(this,$),$.start!==void 0?ge($.start(this._transformStreamController)):ge(void 0)}get readable(){if(!oh(this))throw uh("readable");return this._readable}get writable(){if(!oh(this))throw uh("writable");return this._writable}}Object.defineProperties(Vs.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Vs.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function pb(i,u,h,w,R,L){function $(){return u}function Q(Te){return bb(i,Te)}function ce(Te){return Cb(i,Te)}function ne(){return wb(i)}i._writable=__($,Q,ne,ce,h,w);function de(){return Eb(i)}function ge(Te){return Ab(i,Te)}i._readable=To($,de,ge,R,L),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,Ks(i,!0),i._transformStreamController=void 0}function oh(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof Vs}function sh(i,u){Mt(i._readable._readableStreamController,u),Bu(i,u)}function Bu(i,u){Qs(i._transformStreamController),So(i._writable._writableStreamController,u),Mu(i)}function Mu(i){i._backpressure&&Ks(i,!1)}function Ks(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class jr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ys(this))throw Xs("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return Iu(u)}enqueue(u=void 0){if(!Ys(this))throw Xs("enqueue");ih(this,u)}error(u=void 0){if(!Ys(this))throw Xs("error");yb(this,u)}terminate(){if(!Ys(this))throw Xs("terminate");_b(this)}}Object.defineProperties(jr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(jr.prototype.enqueue,"enqueue"),o(jr.prototype.error,"error"),o(jr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Ys(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof jr}function mb(i,u,h,w,R){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=w,u._cancelAlgorithm=R,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function gb(i,u){let h=Object.create(jr.prototype),w,R,L;u.transform!==void 0?w=$=>u.transform($,h):w=$=>{try{return ih(h,$),f(void 0)}catch(Q){return d(Q)}},u.flush!==void 0?R=()=>u.flush(h):R=()=>f(void 0),u.cancel!==void 0?L=$=>u.cancel($):L=()=>f(void 0),mb(i,h,w,R,L)}function Qs(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function ih(i,u){let h=i._controlledTransformStream,w=h._readable._readableStreamController;if(!In(w))throw new TypeError("Readable side is not in a state that permits enqueue");try{Pn(w,u)}catch(L){throw Bu(h,L),h._readable._storedError}G_(w)!==h._backpressure&&Ks(h,!0)}function yb(i,u){sh(i._controlledTransformStream,u)}function ah(i,u){let h=i._transformAlgorithm(u);return b(h,void 0,w=>{throw sh(i._controlledTransformStream,w),w})}function _b(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;on(h);let w=new TypeError("TransformStream terminated");Bu(u,w)}function bb(i,u){let h=i._transformStreamController;if(i._backpressure){let w=i._backpressureChangePromise;return b(w,()=>{let R=i._writable;if(R._state==="erroring")throw R._storedError;return ah(h,u)})}return ah(h,u)}function Cb(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let w=i._readable;h._finishPromise=l((L,$)=>{h._finishPromise_resolve=L,h._finishPromise_reject=$});let R=h._cancelAlgorithm(u);return Qs(h),C(R,()=>(w._state==="errored"?Nn(h,w._storedError):(Mt(w._readableStreamController,u),ju(h)),null),L=>(Mt(w._readableStreamController,L),Nn(h,L),null)),h._finishPromise}function wb(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let h=i._readable;u._finishPromise=l((R,L)=>{u._finishPromise_resolve=R,u._finishPromise_reject=L});let w=u._flushAlgorithm();return Qs(u),C(w,()=>(h._state==="errored"?Nn(u,h._storedError):(on(h._readableStreamController),ju(u)),null),R=>(Mt(h._readableStreamController,R),Nn(u,R),null)),u._finishPromise}function Eb(i){return Ks(i,!1),i._backpressureChangePromise}function Ab(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let w=i._writable;h._finishPromise=l((L,$)=>{h._finishPromise_resolve=L,h._finishPromise_reject=$});let R=h._cancelAlgorithm(u);return Qs(h),C(R,()=>(w._state==="errored"?Nn(h,w._storedError):(So(w._writableStreamController,u),Mu(i),ju(h)),null),L=>(So(w._writableStreamController,L),Mu(i),Nn(h,L),null)),h._finishPromise}function Xs(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function ju(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Nn(i,u){i._finishPromise_reject!==void 0&&(g(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function uh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=Gs,t.CountQueuingStrategy=Js,t.ReadableByteStreamController=pr,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Ir,t.ReadableStreamBYOBRequest=Xr,t.ReadableStreamDefaultController=gr,t.ReadableStreamDefaultReader=z,t.TransformStream=Vs,t.TransformStreamDefaultController=jr,t.WritableStream=Nr,t.WritableStreamDefaultController=Fn,t.WritableStreamDefaultWriter=mr}))});var Fp=J(()=>{if(!globalThis.ReadableStream)try{let t=require("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,Op())}try{let{Blob:t}=require("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=c.byteLength,s.enqueue(new Uint8Array(c)),n===o.size&&s.close()}})})}catch{}});async function*gc(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,o=r.byteOffset+r.byteLength;for(;n!==o;){let s=Math.min(o-n,Pp),a=r.buffer.slice(n,n+s);n+=a.byteLength,yield new Uint8Array(a)}}else yield r;else{let n=0,o=r;for(;n!==o.size;){let a=await o.slice(n,Math.min(o.size,n+Pp)).arrayBuffer();n+=a.byteLength,yield new Uint8Array(a)}}}var cR,Pp,Ip,YC,$t,Mo=Ne(()=>{cR=Me(Fp(),1);Pp=65536;Ip=class yc{#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 s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof yc?a=s:a=n.encode(`${s}`),this.#r+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let o=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of gc(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 gc(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=gc(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:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=r<0?Math.max(o+r,0):Math.min(r,o),c=Math.max(a-s,0),l=this.#e,f=[],d=0;for(let C of l){if(d>=c)break;let v=ArrayBuffer.isView(C)?C.byteLength:C.size;if(s&&v<=s)s-=v,a-=v;else{let A;ArrayBuffer.isView(C)?(A=C.subarray(s,Math.min(v,a)),d+=A.byteLength):(A=C.slice(s,Math.min(v,a)),d+=A.size),a-=v,f.push(A),s=0}}let m=new yc([],{type:String(n).toLowerCase()});return m.#r=c,m.#e=f,m}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(Ip.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});YC=Ip,$t=YC});var QC,XC,qr,_c=Ne(()=>{Mo();QC=class extends $t{#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 o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),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 $t&&/^(File)$/.test(e[Symbol.toStringTag])}},XC=QC,qr=XC});function Mp(t,e=$t){var r=`${Np()}${Np()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${r}\r
27
+ Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?n.push(o+bc(a)+`"\r
28
28
  \r
29
29
  ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
30
30
  `)}\r
31
- `):n.push(o+pc(a)+`"; filename="${pc(s.name,1)}"\r
31
+ `):n.push(o+bc(a)+`"; filename="${bc(s.name,1)}"\r
32
32
  Content-Type: ${s.type||"application/octet-stream"}\r
33
33
  \r
34
34
  `,s,`\r
35
- `)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var No,HC,WC,Dp,GC,Rp,pc,dn,$r,bi=Be(()=>{Io();hc();({toStringTag:No,iterator:HC,hasInstance:WC}=Symbol),Dp=Math.random,GC="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Rp=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[No])?[(r=r!==void 0?r+"":e[No]=="File"?e.name:"blob",t),e.name!==r||e[No]=="blob"?new qr([e],r,e):e]:[t,e+""]),pc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),dn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},$r=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[No](){return"FormData"}[HC](){return this.entries()}static[WC](e){return e&&typeof e=="object"&&e[No]==="FormData"&&!GC.some(r=>typeof e[r]!="function")}append(...e){dn("append",arguments,2),this.#e.push(Rp(...e))}delete(e){dn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){dn("get",arguments,1),e+="";for(var r=this.#e,n=r.length,o=0;o<n;o++)if(r[o][0]===e)return r[o][1];return null}getAll(e,r){return dn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return dn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){dn("forEach",arguments,1);for(var[n,o]of this)e.call(r,o,n,this)}set(...e){dn("set",arguments,2);var r=[],n=!0;e=Rp(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!r.push(e)):r.push(o)}),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 wr,Ci=Be(()=>{wr=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,mc=Be(()=>{Ci();et=class extends wr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var wi,gc,Bo,Op,Fp,Pp,Ei=Be(()=>{wi=Symbol.toStringTag,gc=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[wi]==="URLSearchParams",Bo=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[wi]),Op=t=>typeof t=="object"&&(t[wi]==="AbortSignal"||t[wi]==="EventTarget"),Fp=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Pp=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Np=J((fR,Ip)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Ip.exports=globalThis.DOMException});var fn,Bp,jp,yc,Lp,Mp,Up,qp,$p,zp,Ai,_c=Be(()=>{fn=require("node:fs"),Bp=require("node:path"),jp=je(Np(),1);hc();Io();({stat:yc}=fn.promises),Lp=(t,e)=>$p((0,fn.statSync)(t),t,e),Mp=(t,e)=>yc(t).then(r=>$p(r,t,e)),Up=(t,e)=>yc(t).then(r=>zp(r,t,e)),qp=(t,e)=>zp((0,fn.statSync)(t),t,e),$p=(t,e,r="")=>new Mt([new Ai({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),zp=(t,e,r="")=>new qr([new Ai({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,Bp.basename)(e),{type:r,lastModified:t.mtimeMs}),Ai=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 yc(this.#e);if(e>this.lastModified)throw new jp.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*(0,fn.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Wp={};Nu(Wp,{toFormData:()=>ZC});function XC(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,(o,s)=>String.fromCharCode(s)),n}async function ZC(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 bc(r[1]||r[2]),o,s,a,c,l,h,d=[],p=new $r,w=m=>{a+=g.decode(m,{stream:!0})},T=m=>{d.push(m)},S=()=>{let m=new qr(d,h,{type:l});p.append(c,m)},_=()=>{p.append(c,a)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=w,n.onPartEnd=_,o="",s="",a="",c="",l="",h=null,d.length=0},n.onHeaderField=function(m){o+=g.decode(m,{stream:!0})},n.onHeaderValue=function(m){s+=g.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(s+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let m=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),h=XC(s),h&&(n.onPartData=T,n.onPartEnd=S)}else o==="content-type"&&(l=s);s="",o=""};for await(let m of t)n.write(m);return n.end(),p}var Zt,xe,Hp,zr,Si,ki,JC,jo,VC,KC,YC,QC,hn,bc,Gp=Be(()=>{_c();bi();Zt=0,xe={START_BOUNDARY:Zt++,HEADER_FIELD_START:Zt++,HEADER_FIELD:Zt++,HEADER_VALUE_START:Zt++,HEADER_VALUE:Zt++,HEADER_VALUE_ALMOST_DONE:Zt++,HEADERS_ALMOST_DONE:Zt++,PART_DATA_START:Zt++,PART_DATA:Zt++,END:Zt++},Hp=1,zr={PART_BOUNDARY:Hp,LAST_BOUNDARY:Hp*=2},Si=10,ki=13,JC=32,jo=45,VC=58,KC=97,YC=122,QC=t=>t|32,hn=()=>{},bc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=hn,this.onHeaderField=hn,this.onHeadersEnd=hn,this.onHeaderValue=hn,this.onPartBegin=hn,this.onPartData=hn,this.onPartEnd=hn,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=xe.START_BOUNDARY}write(e){let r=0,n=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:h,flags:d}=this,p=this.boundary.length,w=p-1,T=e.length,S,_,g=E=>{this[E+"Mark"]=r},m=E=>{delete this[E+"Mark"]},k=(E,D,F,$)=>{(D===void 0||D!==F)&&this[E]($&&$.subarray(D,F))},y=(E,D)=>{let F=E+"Mark";F in this&&(D?(k(E,this[F],r,e),delete this[F]):(k(E,this[F],e.length,e),this[F]=0))};for(r=0;r<n;r++)switch(S=e[r],h){case xe.START_BOUNDARY:if(l===a.length-2){if(S===jo)d|=zr.LAST_BOUNDARY;else if(S!==ki)return;l++;break}else if(l-1===a.length-2){if(d&zr.LAST_BOUNDARY&&S===jo)h=xe.END,d=0;else if(!(d&zr.LAST_BOUNDARY)&&S===Si)l=0,k("onPartBegin"),h=xe.HEADER_FIELD_START;else return;break}S!==a[l+2]&&(l=-2),S===a[l+2]&&l++;break;case xe.HEADER_FIELD_START:h=xe.HEADER_FIELD,g("onHeaderField"),l=0;case xe.HEADER_FIELD:if(S===ki){m("onHeaderField"),h=xe.HEADERS_ALMOST_DONE;break}if(l++,S===jo)break;if(S===VC){if(l===1)return;y("onHeaderField",!0),h=xe.HEADER_VALUE_START;break}if(_=QC(S),_<KC||_>YC)return;break;case xe.HEADER_VALUE_START:if(S===JC)break;g("onHeaderValue"),h=xe.HEADER_VALUE;case xe.HEADER_VALUE:S===ki&&(y("onHeaderValue",!0),k("onHeaderEnd"),h=xe.HEADER_VALUE_ALMOST_DONE);break;case xe.HEADER_VALUE_ALMOST_DONE:if(S!==Si)return;h=xe.HEADER_FIELD_START;break;case xe.HEADERS_ALMOST_DONE:if(S!==Si)return;k("onHeadersEnd"),h=xe.PART_DATA_START;break;case xe.PART_DATA_START:h=xe.PART_DATA,g("onPartData");case xe.PART_DATA:if(o=l,l===0){for(r+=w;r<T&&!(e[r]in c);)r+=p;r-=w,S=e[r]}if(l<a.length)a[l]===S?(l===0&&y("onPartData",!0),l++):l=0;else if(l===a.length)l++,S===ki?d|=zr.PART_BOUNDARY:S===jo?d|=zr.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&zr.PART_BOUNDARY){if(l=0,S===Si){d&=~zr.PART_BOUNDARY,k("onPartEnd"),k("onPartBegin"),h=xe.HEADER_FIELD_START;break}}else d&zr.LAST_BOUNDARY&&S===jo?(k("onPartEnd"),h=xe.END,d=0):l=0;if(l>0)s[l-1]=S;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);k("onPartData",0,o,E),o=0,g("onPartData"),r--}break;case xe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}y("onHeaderField"),y("onHeaderValue"),y("onPartData"),this.index=l,this.state=h,this.flags=d}end(){if(this.state===xe.HEADER_FIELD_START&&this.index===0||this.state===xe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==xe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});async function Cc(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 dt.Buffer.alloc(0);if(!(e instanceof Tt.default))return dt.Buffer.alloc(0);let r=[],n=0;try{for await(let o of e){if(t.size>0&&n+o.length>t.size){let s=new et(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}n+=o.length,r.push(o)}}catch(o){throw o instanceof wr?o:new et(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(o=>typeof o=="string")?dt.Buffer.from(r.join("")):dt.Buffer.concat(r,n)}catch(o){throw new et(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new et(`Premature close of server response while trying to fetch ${t.url}`)}var Tt,Er,dt,ew,it,er,zn,tw,vi,Jp,Vp,Ti=Be(()=>{Tt=je(require("node:stream"),1),Er=require("node:util"),dt=require("node:buffer");Io();bi();mc();Ci();Ei();ew=(0,Er.promisify)(Tt.default.pipeline),it=Symbol("Body internals"),er=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:gc(e)?e=dt.Buffer.from(e.toString()):Bo(e)||dt.Buffer.isBuffer(e)||(Er.types.isAnyArrayBuffer(e)?e=dt.Buffer.from(e):ArrayBuffer.isView(e)?e=dt.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Tt.default||(e instanceof $r?(e=xp(e),n=e.type.split("=")[1]):e=dt.Buffer.from(String(e))));let o=e;dt.Buffer.isBuffer(e)?o=Tt.default.Readable.from(e):Bo(e)&&(o=Tt.default.Readable.from(e.stream())),this[it]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Tt.default&&e.on("error",s=>{let a=s instanceof wr?s:new et(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[it].error=a})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:n}=await Cc(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 $r,o=new URLSearchParams(await this.text());for(let[s,a]of o)n.append(s,a);return n}let{toFormData:r}=await Promise.resolve().then(()=>(Gp(),Wp));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 Mt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Cc(this);return new TextDecoder().decode(e)}buffer(){return Cc(this)}};er.prototype.buffer=(0,Er.deprecate)(er.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(er.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Er.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});zn=(t,e)=>{let r,n,{body:o}=t[it];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Tt.default&&typeof o.getBoundary!="function"&&(r=new Tt.PassThrough({highWaterMark:e}),n=new Tt.PassThrough({highWaterMark:e}),o.pipe(r),o.pipe(n),t[it].stream=r,o=n),o},tw=(0,Er.deprecate)(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"),vi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":gc(t)?"application/x-www-form-urlencoded;charset=UTF-8":Bo(t)?t.type||null:dt.Buffer.isBuffer(t)||Er.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof $r?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${tw(t)}`:t instanceof Tt.default?null:"text/plain;charset=UTF-8",Jp=t=>{let{body:e}=t[it];return e===null?0:Bo(e)?e.size:dt.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Vp=async(t,{body:e})=>{e===null?t.end():await ew(e,t)}});function Kp(t=[]){return new at(t.reduce((e,r,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return Di(e),Ec(e,String(r)),!0}catch{return!1}}))}var wc,Lo,Di,Ec,at,Ri=Be(()=>{wc=require("node:util"),Lo=je(require("node:http"),1),Di=typeof Lo.default.validateHeaderName=="function"?Lo.default.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}},Ec=typeof Lo.default.validateHeaderValue=="function"?Lo.default.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[o,s]of Object.entries(n))r.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!wc.types.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(o=>{if(typeof o!="object"||wc.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}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,o])=>(Di(n),Ec(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(r),new Proxy(this,{get(n,o,s){switch(o){case"append":case"set":return(a,c)=>(Di(a),Ec(a,String(c)),URLSearchParams.prototype[o].call(n,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(Di(a),URLSearchParams.prototype[o].call(n,String(a).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,s)}}})}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 rw,Mo,Ac=Be(()=>{rw=new Set([301,302,303,307,308]),Mo=t=>rw.has(t)});var Ut,ft,Yp=Be(()=>{Ri();Ti();Ac();Ut=Symbol("Response internals"),ft=class t extends er{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,o=new at(r.headers);if(e!==null&&!o.has("Content-Type")){let s=vi(e,this);s&&o.append("Content-Type",s)}this[Ut]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:o,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[Ut].type}get url(){return this[Ut].url||""}get status(){return this[Ut].status}get ok(){return this[Ut].status>=200&&this[Ut].status<300}get redirected(){return this[Ut].counter>0}get statusText(){return this[Ut].statusText}get headers(){return this[Ut].headers}get highWaterMark(){return this[Ut].highWaterMark}clone(){return new t(zn(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(!Mo(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[Ut].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 o=new at(r&&r.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(n,{...r,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(ft.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 Qp,Xp=Be(()=>{Qp=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]==="?"?"?":""}});function Zp(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 nm(t){if(!tm.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function nw(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=(0,em.isIP)(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 Hn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:nw(t)}function om(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 o=t.referrer,s=Zp(o),a=Zp(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),r&&(a=r(a));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return Hn(s)&&!Hn(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:Hn(s)&&!Hn(c)?"no-referrer":a;case"same-origin":return s.origin===c.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===c.origin?s:a;case"no-referrer-when-downgrade":return Hn(s)&&!Hn(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function sm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&tm.has(n)&&(r=n);return r}var em,tm,rm,Sc=Be(()=>{em=require("node:net");tm=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),rm="strict-origin-when-cross-origin"});var im,am,Ge,Uo,ow,Hr,um,cm=Be(()=>{im=require("node:url"),am=require("node:util");Ri();Ti();Ei();Xp();Sc();Ge=Symbol("Request internals"),Uo=t=>typeof t=="object"&&typeof t[Ge]=="object",ow=(0,am.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Hr=class t extends er{constructor(e,r={}){let n;if(Uo(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 o=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!Uo(r)&&"data"in r&&ow(),(r.body!=null||Uo(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=r.body?r.body:Uo(e)&&e.body!==null?zn(e):null;super(s,{size:r.size||e.size||0});let a=new at(r.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let h=vi(s,this);h&&a.set("Content-Type",h)}let c=Uo(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Op(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:o,redirect:r.redirect||e.redirect||"follow",headers:a,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(0,im.format)(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=nm(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Hr.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}});um=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=Jp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=rm),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=om(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:o}=t;typeof o=="function"&&(o=o(e));let s=Qp(e),a={path:e.pathname+s,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var qo,lm=Be(()=>{Ci();qo=class extends wr{constructor(e,r="aborted"){super(e,r)}}});var hm={};Nu(hm,{AbortError:()=>qo,Blob:()=>Mt,FetchError:()=>et,File:()=>qr,FormData:()=>$r,Headers:()=>at,Request:()=>Hr,Response:()=>ft,blobFrom:()=>Mp,blobFromSync:()=>Lp,default:()=>kc,fileFrom:()=>Up,fileFromSync:()=>qp,isRedirect:()=>Mo});async function kc(t,e){return new Promise((r,n)=>{let o=new Hr(t,e),{parsedURL:s,options:a}=um(o);if(!sw.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let S=wp(o.url),_=new ft(S,{headers:{"Content-Type":S.typeFull}});r(_);return}let c=(s.protocol==="https:"?fm.default:dm.default).request,{signal:l}=o,h=null,d=()=>{let S=new qo("The operation was aborted.");n(S),o.body&&o.body instanceof ht.default.Readable&&o.body.destroy(S),!(!h||!h.body)&&h.body.emit("error",S)};if(l&&l.aborted){d();return}let p=()=>{d(),T()},w=c(s.toString(),a);l&&l.addEventListener("abort",p);let T=()=>{w.abort(),l&&l.removeEventListener("abort",p)};w.on("error",S=>{n(new et(`request to ${o.url} failed, reason: ${S.message}`,"system",S)),T()}),iw(w,S=>{h&&h.body&&h.body.destroy(S)}),process.version<"v14"&&w.on("socket",S=>{let _;S.prependListener("end",()=>{_=S._eventsCount}),S.prependListener("close",g=>{if(h&&_<S._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",h.body.emit("error",m)}})}),w.on("response",S=>{w.setTimeout(0);let _=Kp(S.rawHeaders);if(Mo(S.statusCode)){let E=_.get("Location"),D=null;try{D=E===null?null:new URL(E,o.url)}catch{if(o.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),T();return}}switch(o.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),T();return;case"manual":break;case"follow":{if(D===null)break;if(o.counter>=o.follow){n(new et(`maximum redirect reached at: ${o.url}`,"max-redirect")),T();return}let F={headers:new at(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:zn(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Fp(o.url,D)||!Pp(o.url,D))for(let V of["authorization","www-authenticate","cookie","cookie2"])F.headers.delete(V);if(S.statusCode!==303&&o.body&&e.body instanceof ht.default.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),T();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&o.method==="POST")&&(F.method="GET",F.body=void 0,F.headers.delete("content-length"));let $=sm(_);$&&(F.referrerPolicy=$),r(kc(new Hr(D,F))),T();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&S.once("end",()=>{l.removeEventListener("abort",p)});let g=(0,ht.pipeline)(S,new ht.PassThrough,E=>{E&&n(E)});process.version<"v12.10"&&S.on("aborted",p);let m={url:o.url,status:S.statusCode,statusText:S.statusMessage,headers:_,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},k=_.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||k===null||S.statusCode===204||S.statusCode===304){h=new ft(g,m),r(h);return}let y={flush:pn.default.Z_SYNC_FLUSH,finishFlush:pn.default.Z_SYNC_FLUSH};if(k==="gzip"||k==="x-gzip"){g=(0,ht.pipeline)(g,pn.default.createGunzip(y),E=>{E&&n(E)}),h=new ft(g,m),r(h);return}if(k==="deflate"||k==="x-deflate"){let E=(0,ht.pipeline)(S,new ht.PassThrough,D=>{D&&n(D)});E.once("data",D=>{(D[0]&15)===8?g=(0,ht.pipeline)(g,pn.default.createInflate(),F=>{F&&n(F)}):g=(0,ht.pipeline)(g,pn.default.createInflateRaw(),F=>{F&&n(F)}),h=new ft(g,m),r(h)}),E.once("end",()=>{h||(h=new ft(g,m),r(h))});return}if(k==="br"){g=(0,ht.pipeline)(g,pn.default.createBrotliDecompress(),E=>{E&&n(E)}),h=new ft(g,m),r(h);return}h=new ft(g,m),r(h)}),Vp(w,o).catch(n)})}function iw(t,e){let r=$o.Buffer.from(`0\r
35
+ `)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var jo,ZC,ew,Np,tw,Bp,bc,hn,zr,Si=Ne(()=>{Mo();_c();({toStringTag:jo,iterator:ZC,hasInstance:ew}=Symbol),Np=Math.random,tw="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Bp=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[jo])?[(r=r!==void 0?r+"":e[jo]=="File"?e.name:"blob",t),e.name!==r||e[jo]=="blob"?new qr([e],r,e):e]:[t,e+""]),bc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),hn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},zr=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[jo](){return"FormData"}[ZC](){return this.entries()}static[ew](e){return e&&typeof e=="object"&&e[jo]==="FormData"&&!tw.some(r=>typeof e[r]!="function")}append(...e){hn("append",arguments,2),this.#e.push(Bp(...e))}delete(e){hn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){hn("get",arguments,1),e+="";for(var r=this.#e,n=r.length,o=0;o<n;o++)if(r[o][0]===e)return r[o][1];return null}getAll(e,r){return hn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return hn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){hn("forEach",arguments,1);for(var[n,o]of this)e.call(r,o,n,this)}set(...e){hn("set",arguments,2);var r=[],n=!0;e=Bp(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!r.push(e)):r.push(o)}),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 Er,ki=Ne(()=>{Er=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,Cc=Ne(()=>{ki();et=class extends Er{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var vi,wc,Lo,jp,Lp,Up,Ti=Ne(()=>{vi=Symbol.toStringTag,wc=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[vi]==="URLSearchParams",Lo=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[vi]),jp=t=>typeof t=="object"&&(t[vi]==="AbortSignal"||t[vi]==="EventTarget"),Lp=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Up=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var qp=J((ER,$p)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}$p.exports=globalThis.DOMException});var pn,zp,Hp,Ec,Wp,Gp,Jp,Vp,Kp,Yp,Di,Ac=Ne(()=>{pn=require("node:fs"),zp=require("node:path"),Hp=Me(qp(),1);_c();Mo();({stat:Ec}=pn.promises),Wp=(t,e)=>Kp((0,pn.statSync)(t),t,e),Gp=(t,e)=>Ec(t).then(r=>Kp(r,t,e)),Jp=(t,e)=>Ec(t).then(r=>Yp(r,t,e)),Vp=(t,e)=>Yp((0,pn.statSync)(t),t,e),Kp=(t,e,r="")=>new $t([new Di({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),Yp=(t,e,r="")=>new qr([new Di({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,zp.basename)(e),{type:r,lastModified:t.mtimeMs}),Di=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 Ec(this.#e);if(e>this.lastModified)throw new Hp.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*(0,pn.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Xp={};ti(Xp,{toFormData:()=>uw});function aw(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,(o,s)=>String.fromCharCode(s)),n}async function uw(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 Sc(r[1]||r[2]),o,s,a,c,l,f,d=[],m=new zr,C=p=>{a+=g.decode(p,{stream:!0})},v=p=>{d.push(p)},A=()=>{let p=new qr(d,f,{type:l});m.append(c,p)},b=()=>{m.append(c,a)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=C,n.onPartEnd=b,o="",s="",a="",c="",l="",f=null,d.length=0},n.onHeaderField=function(p){o+=g.decode(p,{stream:!0})},n.onHeaderValue=function(p){s+=g.decode(p,{stream:!0})},n.onHeaderEnd=function(){if(s+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let p=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);p&&(c=p[2]||p[3]||""),f=aw(s),f&&(n.onPartData=v,n.onPartEnd=A)}else o==="content-type"&&(l=s);s="",o=""};for await(let p of t)n.write(p);return n.end(),m}var er,xe,Qp,Hr,Ri,xi,rw,Uo,nw,ow,sw,iw,mn,Sc,Zp=Ne(()=>{Ac();Si();er=0,xe={START_BOUNDARY:er++,HEADER_FIELD_START:er++,HEADER_FIELD:er++,HEADER_VALUE_START:er++,HEADER_VALUE:er++,HEADER_VALUE_ALMOST_DONE:er++,HEADERS_ALMOST_DONE:er++,PART_DATA_START:er++,PART_DATA:er++,END:er++},Qp=1,Hr={PART_BOUNDARY:Qp,LAST_BOUNDARY:Qp*=2},Ri=10,xi=13,rw=32,Uo=45,nw=58,ow=97,sw=122,iw=t=>t|32,mn=()=>{},Sc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=mn,this.onHeaderField=mn,this.onHeadersEnd=mn,this.onHeaderValue=mn,this.onPartBegin=mn,this.onPartData=mn,this.onPartEnd=mn,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=xe.START_BOUNDARY}write(e){let r=0,n=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:f,flags:d}=this,m=this.boundary.length,C=m-1,v=e.length,A,b,g=E=>{this[E+"Mark"]=r},p=E=>{delete this[E+"Mark"]},k=(E,D,F,q)=>{(D===void 0||D!==F)&&this[E](q&&q.subarray(D,F))},y=(E,D)=>{let F=E+"Mark";F in this&&(D?(k(E,this[F],r,e),delete this[F]):(k(E,this[F],e.length,e),this[F]=0))};for(r=0;r<n;r++)switch(A=e[r],f){case xe.START_BOUNDARY:if(l===a.length-2){if(A===Uo)d|=Hr.LAST_BOUNDARY;else if(A!==xi)return;l++;break}else if(l-1===a.length-2){if(d&Hr.LAST_BOUNDARY&&A===Uo)f=xe.END,d=0;else if(!(d&Hr.LAST_BOUNDARY)&&A===Ri)l=0,k("onPartBegin"),f=xe.HEADER_FIELD_START;else return;break}A!==a[l+2]&&(l=-2),A===a[l+2]&&l++;break;case xe.HEADER_FIELD_START:f=xe.HEADER_FIELD,g("onHeaderField"),l=0;case xe.HEADER_FIELD:if(A===xi){p("onHeaderField"),f=xe.HEADERS_ALMOST_DONE;break}if(l++,A===Uo)break;if(A===nw){if(l===1)return;y("onHeaderField",!0),f=xe.HEADER_VALUE_START;break}if(b=iw(A),b<ow||b>sw)return;break;case xe.HEADER_VALUE_START:if(A===rw)break;g("onHeaderValue"),f=xe.HEADER_VALUE;case xe.HEADER_VALUE:A===xi&&(y("onHeaderValue",!0),k("onHeaderEnd"),f=xe.HEADER_VALUE_ALMOST_DONE);break;case xe.HEADER_VALUE_ALMOST_DONE:if(A!==Ri)return;f=xe.HEADER_FIELD_START;break;case xe.HEADERS_ALMOST_DONE:if(A!==Ri)return;k("onHeadersEnd"),f=xe.PART_DATA_START;break;case xe.PART_DATA_START:f=xe.PART_DATA,g("onPartData");case xe.PART_DATA:if(o=l,l===0){for(r+=C;r<v&&!(e[r]in c);)r+=m;r-=C,A=e[r]}if(l<a.length)a[l]===A?(l===0&&y("onPartData",!0),l++):l=0;else if(l===a.length)l++,A===xi?d|=Hr.PART_BOUNDARY:A===Uo?d|=Hr.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&Hr.PART_BOUNDARY){if(l=0,A===Ri){d&=~Hr.PART_BOUNDARY,k("onPartEnd"),k("onPartBegin"),f=xe.HEADER_FIELD_START;break}}else d&Hr.LAST_BOUNDARY&&A===Uo?(k("onPartEnd"),f=xe.END,d=0):l=0;if(l>0)s[l-1]=A;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);k("onPartData",0,o,E),o=0,g("onPartData"),r--}break;case xe.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}y("onHeaderField"),y("onHeaderValue"),y("onPartData"),this.index=l,this.state=f,this.flags=d}end(){if(this.state===xe.HEADER_FIELD_START&&this.index===0||this.state===xe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==xe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});async function kc(t){if(t[ut].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[ut].disturbed=!0,t[ut].error)throw t[ut].error;let{body:e}=t;if(e===null)return pt.Buffer.alloc(0);if(!(e instanceof Rt.default))return pt.Buffer.alloc(0);let r=[],n=0;try{for await(let o of e){if(t.size>0&&n+o.length>t.size){let s=new et(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}n+=o.length,r.push(o)}}catch(o){throw o instanceof Er?o:new et(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(o=>typeof o=="string")?pt.Buffer.from(r.join("")):pt.Buffer.concat(r,n)}catch(o){throw new et(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new et(`Premature close of server response while trying to fetch ${t.url}`)}var Rt,Ar,pt,cw,ut,tr,Gn,lw,Oi,em,tm,Fi=Ne(()=>{Rt=Me(require("node:stream"),1),Ar=require("node:util"),pt=require("node:buffer");Mo();Si();Cc();ki();Ti();cw=(0,Ar.promisify)(Rt.default.pipeline),ut=Symbol("Body internals"),tr=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:wc(e)?e=pt.Buffer.from(e.toString()):Lo(e)||pt.Buffer.isBuffer(e)||(Ar.types.isAnyArrayBuffer(e)?e=pt.Buffer.from(e):ArrayBuffer.isView(e)?e=pt.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Rt.default||(e instanceof zr?(e=Mp(e),n=e.type.split("=")[1]):e=pt.Buffer.from(String(e))));let o=e;pt.Buffer.isBuffer(e)?o=Rt.default.Readable.from(e):Lo(e)&&(o=Rt.default.Readable.from(e.stream())),this[ut]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Rt.default&&e.on("error",s=>{let a=s instanceof Er?s:new et(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[ut].error=a})}get body(){return this[ut].stream}get bodyUsed(){return this[ut].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:n}=await kc(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 zr,o=new URLSearchParams(await this.text());for(let[s,a]of o)n.append(s,a);return n}let{toFormData:r}=await Promise.resolve().then(()=>(Zp(),Xp));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[ut].body&&this[ut].body.type||"",r=await this.arrayBuffer();return new $t([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await kc(this);return new TextDecoder().decode(e)}buffer(){return kc(this)}};tr.prototype.buffer=(0,Ar.deprecate)(tr.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(tr.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Ar.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Gn=(t,e)=>{let r,n,{body:o}=t[ut];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Rt.default&&typeof o.getBoundary!="function"&&(r=new Rt.PassThrough({highWaterMark:e}),n=new Rt.PassThrough({highWaterMark:e}),o.pipe(r),o.pipe(n),t[ut].stream=r,o=n),o},lw=(0,Ar.deprecate)(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"),Oi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":wc(t)?"application/x-www-form-urlencoded;charset=UTF-8":Lo(t)?t.type||null:pt.Buffer.isBuffer(t)||Ar.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof zr?`multipart/form-data; boundary=${e[ut].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${lw(t)}`:t instanceof Rt.default?null:"text/plain;charset=UTF-8",em=t=>{let{body:e}=t[ut];return e===null?0:Lo(e)?e.size:pt.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},tm=async(t,{body:e})=>{e===null?t.end():await cw(e,t)}});function rm(t=[]){return new ct(t.reduce((e,r,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return Pi(e),Tc(e,String(r)),!0}catch{return!1}}))}var vc,$o,Pi,Tc,ct,Ii=Ne(()=>{vc=require("node:util"),$o=Me(require("node:http"),1),Pi=typeof $o.default.validateHeaderName=="function"?$o.default.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}},Tc=typeof $o.default.validateHeaderValue=="function"?$o.default.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}},ct=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[o,s]of Object.entries(n))r.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!vc.types.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(o=>{if(typeof o!="object"||vc.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}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,o])=>(Pi(n),Tc(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(r),new Proxy(this,{get(n,o,s){switch(o){case"append":case"set":return(a,c)=>(Pi(a),Tc(a,String(c)),URLSearchParams.prototype[o].call(n,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(Pi(a),URLSearchParams.prototype[o].call(n,String(a).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,s)}}})}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(ct.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var dw,qo,Dc=Ne(()=>{dw=new Set([301,302,303,307,308]),qo=t=>dw.has(t)});var qt,mt,nm=Ne(()=>{Ii();Fi();Dc();qt=Symbol("Response internals"),mt=class t extends tr{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,o=new ct(r.headers);if(e!==null&&!o.has("Content-Type")){let s=Oi(e,this);s&&o.append("Content-Type",s)}this[qt]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:o,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[qt].type}get url(){return this[qt].url||""}get status(){return this[qt].status}get ok(){return this[qt].status>=200&&this[qt].status<300}get redirected(){return this[qt].counter>0}get statusText(){return this[qt].statusText}get headers(){return this[qt].headers}get highWaterMark(){return this[qt].highWaterMark}clone(){return new t(Gn(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(!qo(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[qt].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 o=new ct(r&&r.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(n,{...r,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(mt.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 om,sm=Ne(()=>{om=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]==="?"?"?":""}});function im(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 lm(t){if(!um.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function fw(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=(0,am.isIP)(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 Jn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:fw(t)}function dm(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 o=t.referrer,s=im(o),a=im(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),r&&(a=r(a));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return Jn(s)&&!Jn(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:Jn(s)&&!Jn(c)?"no-referrer":a;case"same-origin":return s.origin===c.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===c.origin?s:a;case"no-referrer-when-downgrade":return Jn(s)&&!Jn(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function fm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&um.has(n)&&(r=n);return r}var am,um,cm,Rc=Ne(()=>{am=require("node:net");um=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),cm="strict-origin-when-cross-origin"});var hm,pm,Ge,zo,hw,Wr,mm,gm=Ne(()=>{hm=require("node:url"),pm=require("node:util");Ii();Fi();Ti();sm();Rc();Ge=Symbol("Request internals"),zo=t=>typeof t=="object"&&typeof t[Ge]=="object",hw=(0,pm.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Wr=class t extends tr{constructor(e,r={}){let n;if(zo(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 o=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!zo(r)&&"data"in r&&hw(),(r.body!=null||zo(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=r.body?r.body:zo(e)&&e.body!==null?Gn(e):null;super(s,{size:r.size||e.size||0});let a=new ct(r.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let f=Oi(s,this);f&&a.set("Content-Type",f)}let c=zo(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!jp(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 f=new URL(l);l=/^about:(\/\/)?client$/.test(f)?"client":f}else l=void 0;this[Ge]={method:o,redirect:r.redirect||e.redirect||"follow",headers:a,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(0,hm.format)(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=lm(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Wr.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}});mm=t=>{let{parsedURL:e}=t[Ge],r=new ct(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=em(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=cm),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=dm(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:o}=t;typeof o=="function"&&(o=o(e));let s=om(e),a={path:e.pathname+s,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var Ho,ym=Ne(()=>{ki();Ho=class extends Er{constructor(e,r="aborted"){super(e,r)}}});var Cm={};ti(Cm,{AbortError:()=>Ho,Blob:()=>$t,FetchError:()=>et,File:()=>qr,FormData:()=>zr,Headers:()=>ct,Request:()=>Wr,Response:()=>mt,blobFrom:()=>Gp,blobFromSync:()=>Wp,default:()=>xc,fileFrom:()=>Jp,fileFromSync:()=>Vp,isRedirect:()=>qo});async function xc(t,e){return new Promise((r,n)=>{let o=new Wr(t,e),{parsedURL:s,options:a}=mm(o);if(!pw.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let A=Dp(o.url),b=new mt(A,{headers:{"Content-Type":A.typeFull}});r(b);return}let c=(s.protocol==="https:"?bm.default:_m.default).request,{signal:l}=o,f=null,d=()=>{let A=new Ho("The operation was aborted.");n(A),o.body&&o.body instanceof gt.default.Readable&&o.body.destroy(A),!(!f||!f.body)&&f.body.emit("error",A)};if(l&&l.aborted){d();return}let m=()=>{d(),v()},C=c(s.toString(),a);l&&l.addEventListener("abort",m);let v=()=>{C.abort(),l&&l.removeEventListener("abort",m)};C.on("error",A=>{n(new et(`request to ${o.url} failed, reason: ${A.message}`,"system",A)),v()}),mw(C,A=>{f&&f.body&&f.body.destroy(A)}),process.version<"v14"&&C.on("socket",A=>{let b;A.prependListener("end",()=>{b=A._eventsCount}),A.prependListener("close",g=>{if(f&&b<A._eventsCount&&!g){let p=new Error("Premature close");p.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",p)}})}),C.on("response",A=>{C.setTimeout(0);let b=rm(A.rawHeaders);if(qo(A.statusCode)){let E=b.get("Location"),D=null;try{D=E===null?null:new URL(E,o.url)}catch{if(o.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),v();return}}switch(o.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),v();return;case"manual":break;case"follow":{if(D===null)break;if(o.counter>=o.follow){n(new et(`maximum redirect reached at: ${o.url}`,"max-redirect")),v();return}let F={headers:new ct(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Gn(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Lp(o.url,D)||!Up(o.url,D))for(let V of["authorization","www-authenticate","cookie","cookie2"])F.headers.delete(V);if(A.statusCode!==303&&o.body&&e.body instanceof gt.default.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),v();return}(A.statusCode===303||(A.statusCode===301||A.statusCode===302)&&o.method==="POST")&&(F.method="GET",F.body=void 0,F.headers.delete("content-length"));let q=fm(b);q&&(F.referrerPolicy=q),r(xc(new Wr(D,F))),v();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&A.once("end",()=>{l.removeEventListener("abort",m)});let g=(0,gt.pipeline)(A,new gt.PassThrough,E=>{E&&n(E)});process.version<"v12.10"&&A.on("aborted",m);let p={url:o.url,status:A.statusCode,statusText:A.statusMessage,headers:b,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},k=b.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||k===null||A.statusCode===204||A.statusCode===304){f=new mt(g,p),r(f);return}let y={flush:gn.default.Z_SYNC_FLUSH,finishFlush:gn.default.Z_SYNC_FLUSH};if(k==="gzip"||k==="x-gzip"){g=(0,gt.pipeline)(g,gn.default.createGunzip(y),E=>{E&&n(E)}),f=new mt(g,p),r(f);return}if(k==="deflate"||k==="x-deflate"){let E=(0,gt.pipeline)(A,new gt.PassThrough,D=>{D&&n(D)});E.once("data",D=>{(D[0]&15)===8?g=(0,gt.pipeline)(g,gn.default.createInflate(),F=>{F&&n(F)}):g=(0,gt.pipeline)(g,gn.default.createInflateRaw(),F=>{F&&n(F)}),f=new mt(g,p),r(f)}),E.once("end",()=>{f||(f=new mt(g,p),r(f))});return}if(k==="br"){g=(0,gt.pipeline)(g,gn.default.createBrotliDecompress(),E=>{E&&n(E)}),f=new mt(g,p),r(f);return}f=new mt(g,p),r(f)}),tm(C,o).catch(n)})}function mw(t,e){let r=Wo.Buffer.from(`0\r
38
38
  \r
39
- `),n=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=()=>{if(n&&!o){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},l=h=>{o=$o.Buffer.compare(h.slice(-5),r)===0,!o&&s&&(o=$o.Buffer.compare(s.slice(-3),r.slice(0,3))===0&&$o.Buffer.compare(h.slice(-2),r.slice(3))===0),s=h};a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}var dm,fm,pn,ht,$o,sw,pm=Be(()=>{dm=je(require("node:http"),1),fm=je(require("node:https"),1),pn=je(require("node:zlib"),1),ht=je(require("node:stream"),1),$o=require("node:buffer");Ep();Ti();Yp();Ri();cm();mc();lm();Ac();bi();Ei();Sc();_c();sw=new Set(["data:","http:","https:"])});var ym=J(Gn=>{"use strict";var aw=Gn&&Gn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Wn;Object.defineProperty(Gn,"__esModule",{value:!0});Gn.Gaxios=void 0;var uw=aw(Xu()),cw=require("https"),mn=tc(),lw=Kh(),mm=require("stream"),gm=oc(),dw=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),xi=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new gm.GaxiosInterceptorManager,response:new gm.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Wn.mergeHeaders(s,r.headers),n&&Wn.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,headers:s,url:o})}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 Wn.#u(),n={...e};delete n.data;let o=await r(e.url,n),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}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 o=[];for await(let s of r.data)o.push(s);r.data=o.toString()}let n=mn.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new mn.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof mn.GaxiosError?n=r:r instanceof Error?n=new mn.GaxiosError(r.message,e,void 0,r):n=new mn.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:o,config:s}=await(0,lw.getRetryConfig)(n);if(o&&s)return n.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#o(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 mn.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),o=[...r],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(n.toString()))return!1}else if(a instanceof URL){if(a.origin===n.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(a===n.origin||a===n.hostname||a===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);Wn.mergeHeaders(r,e.headers);let n=(0,uw.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 a=n.paramsSerializer(n.params);a.startsWith("?")&&(a=a.slice(1));let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+a}else{let a=n.url instanceof URL?n.url:new URL(n.url);for(let[c,l]of new URLSearchParams(n.params))a.searchParams.append(c,l);n.url=a}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let o=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 mm.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 a=await dw();r.set("content-type",`multipart/related; boundary=${a}`),n.body=mm.Readable.from(this.getMultipartRequest(n.multipart,a))}else o?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 s=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(s&&this.#e(n.url,n.noProxy)){let a=await Wn.#a();this.agentCache.has(s)?n.agent=this.agentCache.get(s):(n.agent=new a(s,{cert:n.cert,key:n.key}),this.agentCache.set(s,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new cw.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=mn.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#o(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#o(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 o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
39
+ `),n=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=()=>{if(n&&!o){let f=new Error("Premature close");f.code="ERR_STREAM_PREMATURE_CLOSE",e(f)}},l=f=>{o=Wo.Buffer.compare(f.slice(-5),r)===0,!o&&s&&(o=Wo.Buffer.compare(s.slice(-3),r.slice(0,3))===0&&Wo.Buffer.compare(f.slice(-2),r.slice(3))===0),s=f};a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}var _m,bm,gn,gt,Wo,pw,wm=Ne(()=>{_m=Me(require("node:http"),1),bm=Me(require("node:https"),1),gn=Me(require("node:zlib"),1),gt=Me(require("node:stream"),1),Wo=require("node:buffer");Rp();Fi();nm();Ii();gm();Cc();ym();Dc();Si();Ti();Rc();Ac();pw=new Set(["data:","http:","https:"])});var Sm=J(Kn=>{"use strict";var gw=Kn&&Kn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Vn;Object.defineProperty(Kn,"__esModule",{value:!0});Kn.Gaxios=void 0;var yw=gw(nc()),_w=require("https"),yn=ic(),bw=rp(),Em=require("stream"),Am=cc(),Cw=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Ni=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Am.GaxiosInterceptorManager,response:new Am.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Vn.mergeHeaders(s,r.headers),n&&Vn.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,headers:s,url:o})}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 Vn.#u(),n={...e};delete n.data;let o=await r(e.url,n),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}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 o=[];for await(let s of r.data)o.push(s);r.data=o.toString()}let n=yn.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new yn.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof yn.GaxiosError?n=r:r instanceof Error?n=new yn.GaxiosError(r.message,e,void 0,r):n=new yn.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:o,config:s}=await(0,bw.getRetryConfig)(n);if(o&&s)return n.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#o(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 yn.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),o=[...r],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(n.toString()))return!1}else if(a instanceof URL){if(a.origin===n.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(a===n.origin||a===n.hostname||a===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);Vn.mergeHeaders(r,e.headers);let n=(0,yw.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 a=n.paramsSerializer(n.params);a.startsWith("?")&&(a=a.slice(1));let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+a}else{let a=n.url instanceof URL?n.url:new URL(n.url);for(let[c,l]of new URLSearchParams(n.params))a.searchParams.append(c,l);n.url=a}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let o=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 Em.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 a=await Cw();r.set("content-type",`multipart/related; boundary=${a}`),n.body=Em.Readable.from(this.getMultipartRequest(n.multipart,a))}else o?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 s=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(s&&this.#e(n.url,n.noProxy)){let a=await Vn.#a();this.agentCache.has(s)?n.agent=this.agentCache.get(s):(n.agent=new a(s,{cert:n.cert,key:n.key}),this.agentCache.set(s,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new _w.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=yn.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#o(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#o(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 o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
40
40
  Content-Type: ${s}\r
41
41
  \r
42
42
  `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
43
- `}yield n}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>je(Cp()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(pm(),hm))).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((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};Gn.Gaxios=xi;Wn=xi});var Ve=J(tt=>{"use strict";var fw=tt&&tt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),hw=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fw(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=mw;var _m=ym();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return _m.Gaxios}});var pw=tc();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return pw.GaxiosError}});hw(oc(),tt);tt.instance=new _m.Gaxios;async function mw(t){return tt.instance.request(t)}});var vc=J((bm,Oi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,h=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,w=1e9;function T(D){var F,$,V,B=W.prototype={constructor:W,toString:null,valueOf:null},Y=new W(1),te=20,Z=4,ue=-7,he=21,Ee=-1e7,se=1e7,pe=!1,G=1,K=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",ve=!0;function W(b,A){var v,j,O,I,U,x,P,L,N=this;if(!(N instanceof W))return new W(b,A);if(A==null){if(b&&b._isBigNumber===!0){N.s=b.s,!b.c||b.e>se?N.c=N.e=null:b.e<Ee?N.c=[N.e=0]:(N.e=b.e,N.c=b.c.slice());return}if((x=typeof b=="number")&&b*0==0){if(N.s=1/b<0?(b=-b,-1):1,b===~~b){for(I=0,U=b;U>=10;U/=10,I++);I>se?N.c=N.e=null:(N.e=I,N.c=[b]);return}L=String(b)}else{if(!r.test(L=String(b)))return V(N,L,x);N.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(I=L.indexOf("."))>-1&&(L=L.replace(".","")),(U=L.search(/e/i))>0?(I<0&&(I=U),I+=+L.slice(U+1),L=L.substring(0,U)):I<0&&(I=L.length)}else{if(m(A,2,qe.length,"Base"),A==10&&ve)return N=new W(b),De(N,te+N.e+1,Z);if(L=String(b),x=typeof b=="number"){if(b*0!=0)return V(N,L,x,A);if(N.s=1/b<0?(L=L.slice(1),-1):1,W.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+b)}else N.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(v=qe.slice(0,A),I=U=0,P=L.length;U<P;U++)if(v.indexOf(j=L.charAt(U))<0){if(j=="."){if(U>I){I=P;continue}}else if(!O&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){O=!0,U=-1,I=0;continue}return V(N,String(b),x,A)}x=!1,L=$(L,A,10,N.s),(I=L.indexOf("."))>-1?L=L.replace(".",""):I=L.length}for(U=0;L.charCodeAt(U)===48;U++);for(P=L.length;L.charCodeAt(--P)===48;);if(L=L.slice(U,++P)){if(P-=U,x&&W.DEBUG&&P>15&&(b>h||b!==o(b)))throw Error(a+N.s*b);if((I=I-U-1)>se)N.c=N.e=null;else if(I<Ee)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(+L.slice(0,U)),P-=l;U<P;)N.c.push(+L.slice(U,U+=l));U=l-(L=L.slice(U)).length}else U-=P;for(;U--;L+="0");N.c.push(+L)}}else N.c=[N.e=0]}W.clone=T,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(b){var A,v;if(b!=null)if(typeof b=="object"){if(b.hasOwnProperty(A="DECIMAL_PLACES")&&(v=b[A],m(v,0,w,A),te=v),b.hasOwnProperty(A="ROUNDING_MODE")&&(v=b[A],m(v,0,8,A),Z=v),b.hasOwnProperty(A="EXPONENTIAL_AT")&&(v=b[A],v&&v.pop?(m(v[0],-w,0,A),m(v[1],0,w,A),ue=v[0],he=v[1]):(m(v,-w,w,A),ue=-(he=v<0?-v:v))),b.hasOwnProperty(A="RANGE"))if(v=b[A],v&&v.pop)m(v[0],-w,-1,A),m(v[1],1,w,A),Ee=v[0],se=v[1];else if(m(v,-w,w,A),v)Ee=-(se=v<0?-v:v);else throw Error(s+A+" cannot be zero: "+v);if(b.hasOwnProperty(A="CRYPTO"))if(v=b[A],v===!!v)if(v)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=v;else throw pe=!v,Error(s+"crypto unavailable");else pe=v;else throw Error(s+A+" not true or false: "+v);if(b.hasOwnProperty(A="MODULO_MODE")&&(v=b[A],m(v,0,9,A),G=v),b.hasOwnProperty(A="POW_PRECISION")&&(v=b[A],m(v,0,w,A),K=v),b.hasOwnProperty(A="FORMAT"))if(v=b[A],typeof v=="object")ae=v;else throw Error(s+A+" not an object: "+v);if(b.hasOwnProperty(A="ALPHABET"))if(v=b[A],typeof v=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(v))ve=v.slice(0,10)=="0123456789",qe=v;else throw Error(s+A+" invalid: "+v)}else throw Error(s+"Object expected: "+b);return{DECIMAL_PLACES:te,ROUNDING_MODE:Z,EXPONENTIAL_AT:[ue,he],RANGE:[Ee,se],CRYPTO:pe,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ae,ALPHABET:qe}},W.isBigNumber=function(b){if(!b||b._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var A,v,j=b.c,O=b.e,I=b.s;e:if({}.toString.call(j)=="[object Array]"){if((I===1||I===-1)&&O>=-w&&O<=w&&O===o(O)){if(j[0]===0){if(O===0&&j.length===1)return!0;break e}if(A=(O+1)%l,A<1&&(A+=l),String(j[0]).length==A){for(A=0;A<j.length;A++)if(v=j[A],v<0||v>=c||v!==o(v))break e;if(v!==0)return!0}}}else if(j===null&&O===null&&(I===null||I===1||I===-1))return!0;throw Error(s+"Invalid BigNumber: "+b)},W.maximum=W.max=function(){return ye(arguments,-1)},W.minimum=W.min=function(){return ye(arguments,1)},W.random=(function(){var b=9007199254740992,A=Math.random()*b&2097151?function(){return o(Math.random()*b)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(v){var j,O,I,U,x,P=0,L=[],N=new W(Y);if(v==null?v=te:m(v,0,w),U=n(v/l),pe)if(crypto.getRandomValues){for(j=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)x=j[P]*131072+(j[P+1]>>>11),x>=9e15?(O=crypto.getRandomValues(new Uint32Array(2)),j[P]=O[0],j[P+1]=O[1]):(L.push(x%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(j=crypto.randomBytes(U*=7);P<U;)x=(j[P]&31)*281474976710656+j[P+1]*1099511627776+j[P+2]*4294967296+j[P+3]*16777216+(j[P+4]<<16)+(j[P+5]<<8)+j[P+6],x>=9e15?crypto.randomBytes(7).copy(j,P):(L.push(x%1e14),P+=7);P=U/7}else throw pe=!1,Error(s+"crypto unavailable");if(!pe)for(;P<U;)x=A(),x<9e15&&(L[P++]=x%1e14);for(U=L[--P],v%=l,U&&v&&(x=d[l-v],L[P]=o(U/x)*x);L[P]===0;L.pop(),P--);if(P<0)L=[I=0];else{for(I=-1;L[0]===0;L.splice(0,1),I-=l);for(P=1,x=L[0];x>=10;x/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=L,N}})(),W.sum=function(){for(var b=1,A=arguments,v=new W(A[0]);b<A.length;)v=v.plus(A[b++]);return v},$=(function(){var b="0123456789";function A(v,j,O,I){for(var U,x=[0],P,L=0,N=v.length;L<N;){for(P=x.length;P--;x[P]*=j);for(x[0]+=I.indexOf(v.charAt(L++)),U=0;U<x.length;U++)x[U]>O-1&&(x[U+1]==null&&(x[U+1]=0),x[U+1]+=x[U]/O|0,x[U]%=O)}return x.reverse()}return function(v,j,O,I,U){var x,P,L,N,z,X,ee,we,Oe=v.indexOf("."),Ie=te,Ce=Z;for(Oe>=0&&(N=K,K=0,v=v.replace(".",""),we=new W(j),X=we.pow(v.length-Oe),K=N,we.c=A(E(_(X.c),X.e,"0"),10,O,b),we.e=we.c.length),ee=A(v,j,O,U?(x=qe,b):(x=b,qe)),L=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return x.charAt(0);if(Oe<0?--L:(X.c=ee,X.e=L,X.s=I,X=F(X,we,Ie,Ce,O),ee=X.c,z=X.r,L=X.e),P=L+Ie+1,Oe=ee[P],N=O/2,z=z||P<0||ee[P+1]!=null,z=Ce<4?(Oe!=null||z)&&(Ce==0||Ce==(X.s<0?3:2)):Oe>N||Oe==N&&(Ce==4||z||Ce==6&&ee[P-1]&1||Ce==(X.s<0?8:7)),P<1||!ee[0])v=z?E(x.charAt(1),-Ie,x.charAt(0)):x.charAt(0);else{if(ee.length=P,z)for(--O;++ee[--P]>O;)ee[P]=0,P||(++L,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(Oe=0,v="";Oe<=N;v+=x.charAt(ee[Oe++]));v=E(v,L,x.charAt(0))}return v}})(),F=(function(){function b(j,O,I){var U,x,P,L,N=0,z=j.length,X=O%p,ee=O/p|0;for(j=j.slice();z--;)P=j[z]%p,L=j[z]/p|0,U=ee*P+L*X,x=X*P+U%p*p+N,N=(x/I|0)+(U/p|0)+ee*L,j[z]=x%I;return N&&(j=[N].concat(j)),j}function A(j,O,I,U){var x,P;if(I!=U)P=I>U?1:-1;else for(x=P=0;x<I;x++)if(j[x]!=O[x]){P=j[x]>O[x]?1:-1;break}return P}function v(j,O,I,U){for(var x=0;I--;)j[I]-=x,x=j[I]<O[I]?1:0,j[I]=x*U+j[I]-O[I];for(;!j[0]&&j.length>1;j.splice(0,1));}return function(j,O,I,U,x){var P,L,N,z,X,ee,we,Oe,Ie,Ce,Ae,Me,Sn,kn,vn,ut,dr,Ke=j.s==O.s?1:-1,Ue=j.c,Se=O.c;if(!Ue||!Ue[0]||!Se||!Se[0])return new W(!j.s||!O.s||(Ue?Se&&Ue[0]==Se[0]:!Se)?NaN:Ue&&Ue[0]==0||!Se?Ke*0:Ke/0);for(Oe=new W(Ke),Ie=Oe.c=[],L=j.e-O.e,Ke=I+L+1,x||(x=c,L=S(j.e/l)-S(O.e/l),Ke=Ke/l|0),N=0;Se[N]==(Ue[N]||0);N++);if(Se[N]>(Ue[N]||0)&&L--,Ke<0)Ie.push(1),z=!0;else{for(kn=Ue.length,ut=Se.length,N=0,Ke+=2,X=o(x/(Se[0]+1)),X>1&&(Se=b(Se,X,x),Ue=b(Ue,X,x),ut=Se.length,kn=Ue.length),Sn=ut,Ce=Ue.slice(0,ut),Ae=Ce.length;Ae<ut;Ce[Ae++]=0);dr=Se.slice(),dr=[0].concat(dr),vn=Se[0],Se[1]>=x/2&&vn++;do{if(X=0,P=A(Se,Ce,ut,Ae),P<0){if(Me=Ce[0],ut!=Ae&&(Me=Me*x+(Ce[1]||0)),X=o(Me/vn),X>1)for(X>=x&&(X=x-1),ee=b(Se,X,x),we=ee.length,Ae=Ce.length;A(ee,Ce,we,Ae)==1;)X--,v(ee,ut<we?dr:Se,we,x),we=ee.length,P=1;else X==0&&(P=X=1),ee=Se.slice(),we=ee.length;if(we<Ae&&(ee=[0].concat(ee)),v(Ce,ee,Ae,x),Ae=Ce.length,P==-1)for(;A(Se,Ce,ut,Ae)<1;)X++,v(Ce,ut<Ae?dr:Se,Ae,x),Ae=Ce.length}else P===0&&(X++,Ce=[0]);Ie[N++]=X,Ce[0]?Ce[Ae++]=Ue[Sn]||0:(Ce=[Ue[Sn]],Ae=1)}while((Sn++<kn||Ce[0]!=null)&&Ke--);z=Ce[0]!=null,Ie[0]||Ie.splice(0,1)}if(x==c){for(N=1,Ke=Ie[0];Ke>=10;Ke/=10,N++);De(Oe,I+(Oe.e=N+L*l-1)+1,U,z)}else Oe.e=L,Oe.r=+z;return Oe}})();function le(b,A,v,j){var O,I,U,x,P;if(v==null?v=Z:m(v,0,8),!b.c)return b.toString();if(O=b.c[0],U=b.e,A==null)P=_(b.c),P=j==1||j==2&&(U<=ue||U>=he)?y(P,U):E(P,U,"0");else if(b=De(new W(b),A,v),I=b.e,P=_(b.c),x=P.length,j==1||j==2&&(A<=I||I<=ue)){for(;x<A;P+="0",x++);P=y(P,I)}else if(A-=U+(j===2&&I>U),P=E(P,I,"0"),I+1>x){if(--A>0)for(P+=".";A--;P+="0");}else if(A+=I-x,A>0)for(I+1==x&&(P+=".");A--;P+="0");return b.s<0&&O?"-"+P:P}function ye(b,A){for(var v,j,O=1,I=new W(b[0]);O<b.length;O++)j=new W(b[O]),(!j.s||(v=g(I,j))===A||v===0&&I.s===A)&&(I=j);return I}function It(b,A,v){for(var j=1,O=A.length;!A[--O];A.pop());for(O=A[0];O>=10;O/=10,j++);return(v=j+v*l-1)>se?b.c=b.e=null:v<Ee?b.c=[b.e=0]:(b.e=v,b.c=A),b}V=(function(){var b=/^(-?)0([xbo])(?=\w[\w.]*$)/i,A=/^([^.]+)\.$/,v=/^\.([^.]+)$/,j=/^-?(Infinity|NaN)$/,O=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,x,P){var L,N=x?U:U.replace(O,"");if(j.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!x&&(N=N.replace(b,function(z,X,ee){return L=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!P||P==L?X:z}),P&&(L=P,N=N.replace(A,"$1").replace(v,"0.$1")),U!=N))return new W(N,L);if(W.DEBUG)throw Error(s+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function De(b,A,v,j){var O,I,U,x,P,L,N,z=b.c,X=d;if(z){e:{for(O=1,x=z[0];x>=10;x/=10,O++);if(I=A-O,I<0)I+=l,U=A,P=z[L=0],N=o(P/X[O-U-1]%10);else if(L=n((I+1)/l),L>=z.length)if(j){for(;z.length<=L;z.push(0));P=N=0,O=1,I%=l,U=I-l+1}else break e;else{for(P=x=z[L],O=1;x>=10;x/=10,O++);I%=l,U=I-l+O,N=U<0?0:o(P/X[O-U-1]%10)}if(j=j||A<0||z[L+1]!=null||(U<0?P:P%X[O-U-1]),j=v<4?(N||j)&&(v==0||v==(b.s<0?3:2)):N>5||N==5&&(v==4||j||v==6&&(I>0?U>0?P/X[O-U]:0:z[L-1])%10&1||v==(b.s<0?8:7)),A<1||!z[0])return z.length=0,j?(A-=b.e+1,z[0]=X[(l-A%l)%l],b.e=-A||0):z[0]=b.e=0,b;if(I==0?(z.length=L,x=1,L--):(z.length=L+1,x=X[l-I],z[L]=U>0?o(P/X[O-U]%X[U])*x:0),j)for(;;)if(L==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=x,x=1;U>=10;U/=10,x++);I!=x&&(b.e++,z[0]==c&&(z[0]=1));break}else{if(z[L]+=x,z[L]!=c)break;z[L--]=0,x=1}for(I=z.length;z[--I]===0;z.pop());}b.e>se?b.c=b.e=null:b.e<Ee&&(b.c=[b.e=0])}return b}function Ne(b){var A,v=b.e;return v===null?b.toString():(A=_(b.c),A=v<=ue||v>=he?y(A,v):E(A,v,"0"),b.s<0?"-"+A:A)}return B.absoluteValue=B.abs=function(){var b=new W(this);return b.s<0&&(b.s=1),b},B.comparedTo=function(b,A){return g(this,new W(b,A))},B.decimalPlaces=B.dp=function(b,A){var v,j,O,I=this;if(b!=null)return m(b,0,w),A==null?A=Z:m(A,0,8),De(new W(I),b+I.e+1,A);if(!(v=I.c))return null;if(j=((O=v.length-1)-S(this.e/l))*l,O=v[O])for(;O%10==0;O/=10,j--);return j<0&&(j=0),j},B.dividedBy=B.div=function(b,A){return F(this,new W(b,A),te,Z)},B.dividedToIntegerBy=B.idiv=function(b,A){return F(this,new W(b,A),0,1)},B.exponentiatedBy=B.pow=function(b,A){var v,j,O,I,U,x,P,L,N,z=this;if(b=new W(b),b.c&&!b.isInteger())throw Error(s+"Exponent not an integer: "+Ne(b));if(A!=null&&(A=new W(A)),x=b.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!b.c||!b.c[0])return N=new W(Math.pow(+Ne(z),x?b.s*(2-k(b)):+Ne(b))),A?N.mod(A):N;if(P=b.s<0,A){if(A.c?!A.c[0]:!A.s)return new W(NaN);j=!P&&z.isInteger()&&A.isInteger(),j&&(z=z.mod(A))}else{if(b.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||x&&z.c[1]>=24e7:z.c[0]<8e13||x&&z.c[0]<=9999975e7)))return I=z.s<0&&k(b)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(x?(v=new W(.5),P&&(b.s=1),L=k(b)):(O=Math.abs(+Ne(b)),L=O%2),N=new W(Y);;){if(L){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):j&&(N=N.mod(A))}if(O){if(O=o(O/2),O===0)break;L=O%2}else if(b=b.times(v),De(b,b.e+1,1),b.e>14)L=k(b);else{if(O=+Ne(b),O===0)break;L=O%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):j&&(z=z.mod(A))}return j?N:(P&&(N=Y.div(N)),A?N.mod(A):I?De(N,K,Z,U):N)},B.integerValue=function(b){var A=new W(this);return b==null?b=Z:m(b,0,8),De(A,A.e+1,b)},B.isEqualTo=B.eq=function(b,A){return g(this,new W(b,A))===0},B.isFinite=function(){return!!this.c},B.isGreaterThan=B.gt=function(b,A){return g(this,new W(b,A))>0},B.isGreaterThanOrEqualTo=B.gte=function(b,A){return(A=g(this,new W(b,A)))===1||A===0},B.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},B.isLessThan=B.lt=function(b,A){return g(this,new W(b,A))<0},B.isLessThanOrEqualTo=B.lte=function(b,A){return(A=g(this,new W(b,A)))===-1||A===0},B.isNaN=function(){return!this.s},B.isNegative=function(){return this.s<0},B.isPositive=function(){return this.s>0},B.isZero=function(){return!!this.c&&this.c[0]==0},B.minus=function(b,A){var v,j,O,I,U=this,x=U.s;if(b=new W(b,A),A=b.s,!x||!A)return new W(NaN);if(x!=A)return b.s=-A,U.plus(b);var P=U.e/l,L=b.e/l,N=U.c,z=b.c;if(!P||!L){if(!N||!z)return N?(b.s=-A,b):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(b.s=-A,b):new W(N[0]?U:Z==3?-0:0)}if(P=S(P),L=S(L),N=N.slice(),x=P-L){for((I=x<0)?(x=-x,O=N):(L=P,O=z),O.reverse(),A=x;A--;O.push(0));O.reverse()}else for(j=(I=(x=N.length)<(A=z.length))?x:A,x=A=0;A<j;A++)if(N[A]!=z[A]){I=N[A]<z[A];break}if(I&&(O=N,N=z,z=O,b.s=-b.s),A=(j=z.length)-(v=N.length),A>0)for(;A--;N[v++]=0);for(A=c-1;j>x;){if(N[--j]<z[j]){for(v=j;v&&!N[--v];N[v]=A);--N[v],N[j]+=c}N[j]-=z[j]}for(;N[0]==0;N.splice(0,1),--L);return N[0]?It(b,N,L):(b.s=Z==3?-1:1,b.c=[b.e=0],b)},B.modulo=B.mod=function(b,A){var v,j,O=this;return b=new W(b,A),!O.c||!b.s||b.c&&!b.c[0]?new W(NaN):!b.c||O.c&&!O.c[0]?new W(O):(G==9?(j=b.s,b.s=1,v=F(O,b,0,3),b.s=j,v.s*=j):v=F(O,b,0,G),b=O.minus(v.times(b)),!b.c[0]&&G==1&&(b.s=O.s),b)},B.multipliedBy=B.times=function(b,A){var v,j,O,I,U,x,P,L,N,z,X,ee,we,Oe,Ie,Ce=this,Ae=Ce.c,Me=(b=new W(b,A)).c;if(!Ae||!Me||!Ae[0]||!Me[0])return!Ce.s||!b.s||Ae&&!Ae[0]&&!Me||Me&&!Me[0]&&!Ae?b.c=b.e=b.s=null:(b.s*=Ce.s,!Ae||!Me?b.c=b.e=null:(b.c=[0],b.e=0)),b;for(j=S(Ce.e/l)+S(b.e/l),b.s*=Ce.s,P=Ae.length,z=Me.length,P<z&&(we=Ae,Ae=Me,Me=we,O=P,P=z,z=O),O=P+z,we=[];O--;we.push(0));for(Oe=c,Ie=p,O=z;--O>=0;){for(v=0,X=Me[O]%Ie,ee=Me[O]/Ie|0,U=P,I=O+U;I>O;)L=Ae[--U]%Ie,N=Ae[U]/Ie|0,x=ee*L+N*X,L=X*L+x%Ie*Ie+we[I]+v,v=(L/Oe|0)+(x/Ie|0)+ee*N,we[I--]=L%Oe;we[I]=v}return v?++j:we.splice(0,1),It(b,we,j)},B.negated=function(){var b=new W(this);return b.s=-b.s||null,b},B.plus=function(b,A){var v,j=this,O=j.s;if(b=new W(b,A),A=b.s,!O||!A)return new W(NaN);if(O!=A)return b.s=-A,j.minus(b);var I=j.e/l,U=b.e/l,x=j.c,P=b.c;if(!I||!U){if(!x||!P)return new W(O/0);if(!x[0]||!P[0])return P[0]?b:new W(x[0]?j:O*0)}if(I=S(I),U=S(U),x=x.slice(),O=I-U){for(O>0?(U=I,v=P):(O=-O,v=x),v.reverse();O--;v.push(0));v.reverse()}for(O=x.length,A=P.length,O-A<0&&(v=P,P=x,x=v,A=O),O=0;A;)O=(x[--A]=x[A]+P[A]+O)/c|0,x[A]=c===x[A]?0:x[A]%c;return O&&(x=[O].concat(x),++U),It(b,x,U)},B.precision=B.sd=function(b,A){var v,j,O,I=this;if(b!=null&&b!==!!b)return m(b,1,w),A==null?A=Z:m(A,0,8),De(new W(I),b,A);if(!(v=I.c))return null;if(O=v.length-1,j=O*l+1,O=v[O]){for(;O%10==0;O/=10,j--);for(O=v[0];O>=10;O/=10,j++);}return b&&I.e+1>j&&(j=I.e+1),j},B.shiftedBy=function(b){return m(b,-h,h),this.times("1e"+b)},B.squareRoot=B.sqrt=function(){var b,A,v,j,O,I=this,U=I.c,x=I.s,P=I.e,L=te+4,N=new W("0.5");if(x!==1||!U||!U[0])return new W(!x||x<0&&(!U||U[0])?NaN:U?I:1/0);if(x=Math.sqrt(+Ne(I)),x==0||x==1/0?(A=_(U),(A.length+P)%2==0&&(A+="0"),x=Math.sqrt(+A),P=S((P+1)/2)-(P<0||P%2),x==1/0?A="5e"+P:(A=x.toExponential(),A=A.slice(0,A.indexOf("e")+1)+P),v=new W(A)):v=new W(x+""),v.c[0]){for(P=v.e,x=P+L,x<3&&(x=0);;)if(O=v,v=N.times(O.plus(F(I,O,L,1))),_(O.c).slice(0,x)===(A=_(v.c)).slice(0,x))if(v.e<P&&--x,A=A.slice(x-3,x+1),A=="9999"||!j&&A=="4999"){if(!j&&(De(O,O.e+te+2,0),O.times(O).eq(I))){v=O;break}L+=4,x+=4,j=1}else{(!+A||!+A.slice(1)&&A.charAt(0)=="5")&&(De(v,v.e+te+2,1),b=!v.times(v).eq(I));break}}return De(v,v.e+te+1,Z,b)},B.toExponential=function(b,A){return b!=null&&(m(b,0,w),b++),le(this,b,A,1)},B.toFixed=function(b,A){return b!=null&&(m(b,0,w),b=b+this.e+1),le(this,b,A)},B.toFormat=function(b,A,v){var j,O=this;if(v==null)b!=null&&A&&typeof A=="object"?(v=A,A=null):b&&typeof b=="object"?(v=b,b=A=null):v=ae;else if(typeof v!="object")throw Error(s+"Argument not an object: "+v);if(j=O.toFixed(b,A),O.c){var I,U=j.split("."),x=+v.groupSize,P=+v.secondaryGroupSize,L=v.groupSeparator||"",N=U[0],z=U[1],X=O.s<0,ee=X?N.slice(1):N,we=ee.length;if(P&&(I=x,x=P,P=I,we-=I),x>0&&we>0){for(I=we%x||x,N=ee.substr(0,I);I<we;I+=x)N+=L+ee.substr(I,x);P>0&&(N+=L+ee.slice(I)),X&&(N="-"+N)}j=z?N+(v.decimalSeparator||"")+((P=+v.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(v.fractionGroupSeparator||"")):z):N}return(v.prefix||"")+j+(v.suffix||"")},B.toFraction=function(b){var A,v,j,O,I,U,x,P,L,N,z,X,ee=this,we=ee.c;if(b!=null&&(x=new W(b),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Y)))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+Ne(x));if(!we)return new W(ee);for(A=new W(Y),L=v=new W(Y),j=P=new W(Y),X=_(we),I=A.e=X.length-ee.e-1,A.c[0]=d[(U=I%l)<0?l+U:U],b=!b||x.comparedTo(A)>0?I>0?A:L:x,U=se,se=1/0,x=new W(X),P.c[0]=0;N=F(x,A,0,1),O=v.plus(N.times(j)),O.comparedTo(b)!=1;)v=j,j=O,L=P.plus(N.times(O=L)),P=O,A=x.minus(N.times(O=A)),x=O;return O=F(b.minus(v),j,0,1),P=P.plus(O.times(L)),v=v.plus(O.times(j)),P.s=L.s=ee.s,I=I*2,z=F(L,j,I,Z).minus(ee).abs().comparedTo(F(P,v,I,Z).minus(ee).abs())<1?[L,j]:[P,v],se=U,z},B.toNumber=function(){return+Ne(this)},B.toPrecision=function(b,A){return b!=null&&m(b,1,w),le(this,b,A,2)},B.toString=function(b){var A,v=this,j=v.s,O=v.e;return O===null?j?(A="Infinity",j<0&&(A="-"+A)):A="NaN":(b==null?A=O<=ue||O>=he?y(_(v.c),O):E(_(v.c),O,"0"):b===10&&ve?(v=De(new W(v),te+O+1,Z),A=E(_(v.c),v.e,"0")):(m(b,2,qe.length,"Base"),A=$(E(_(v.c),O,"0"),10,b,j,!0)),j<0&&v.c[0]&&(A="-"+A)),A},B.valueOf=B.toJSON=function(){return Ne(this)},B._isBigNumber=!0,D!=null&&W.set(D),W}function S(D){var F=D|0;return D>0||D===F?F:F-1}function _(D){for(var F,$,V=1,B=D.length,Y=D[0]+"";V<B;){for(F=D[V++]+"",$=l-F.length;$--;F="0"+F);Y+=F}for(B=Y.length;Y.charCodeAt(--B)===48;);return Y.slice(0,B+1||1)}function g(D,F){var $,V,B=D.c,Y=F.c,te=D.s,Z=F.s,ue=D.e,he=F.e;if(!te||!Z)return null;if($=B&&!B[0],V=Y&&!Y[0],$||V)return $?V?0:-Z:te;if(te!=Z)return te;if($=te<0,V=ue==he,!B||!Y)return V?0:!B^$?1:-1;if(!V)return ue>he^$?1:-1;for(Z=(ue=B.length)<(he=Y.length)?ue:he,te=0;te<Z;te++)if(B[te]!=Y[te])return B[te]>Y[te]^$?1:-1;return ue==he?0:ue>he^$?1:-1}function m(D,F,$,V){if(D<F||D>$||D!==o(D))throw Error(s+(V||"Argument")+(typeof D=="number"?D<F||D>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function k(D){var F=D.c.length-1;return S(D.e/l)==F&&D.c[F]%2!=0}function y(D,F){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(F<0?"e":"e+")+F}function E(D,F,$){var V,B;if(F<0){for(B=$+".";++F;B+=$);D=B+D}else if(V=D.length,++F>V){for(B=$,F-=V;--F;B+=$);D+=B}else F<V&&(D=D.slice(0,F)+"."+D.slice(F));return D}e=T(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Oi<"u"&&Oi.exports?Oi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(bm)});var Am=J((e1,Em)=>{var Cm=vc(),wm=Em.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,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(h){return r.lastIndex=0,r.test(h)?'"'+h.replace(r,function(d){var p=s[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function l(h,d){var p,w,T,S,_=n,g,m=d[h],k=m!=null&&(m instanceof Cm||Cm.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(h)),typeof a=="function"&&(m=a.call(d,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+=o,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 T=g.length===0?"[]":n?`[
43
+ `}yield n}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>Me(Tp()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(wm(),Cm))).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((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};Kn.Gaxios=Ni;Vn=Ni});var Ve=J(tt=>{"use strict";var ww=tt&&tt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Ew=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ww(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=Sw;var km=Sm();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return km.Gaxios}});var Aw=ic();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return Aw.GaxiosError}});Ew(cc(),tt);tt.instance=new km.Gaxios;async function Sw(t){return tt.instance.request(t)}});var Oc=J((vm,Bi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],m=1e7,C=1e9;function v(D){var F,q,V,B=W.prototype={constructor:W,toString:null,valueOf:null},Y=new W(1),te=20,Z=4,ue=-7,he=21,Ee=-1e7,se=1e7,pe=!1,G=1,K=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},$e="0123456789abcdefghijklmnopqrstuvwxyz",ve=!0;function W(_,S){var T,M,O,I,U,x,P,j,N=this;if(!(N instanceof W))return new W(_,S);if(S==null){if(_&&_._isBigNumber===!0){N.s=_.s,!_.c||_.e>se?N.c=N.e=null:_.e<Ee?N.c=[N.e=0]:(N.e=_.e,N.c=_.c.slice());return}if((x=typeof _=="number")&&_*0==0){if(N.s=1/_<0?(_=-_,-1):1,_===~~_){for(I=0,U=_;U>=10;U/=10,I++);I>se?N.c=N.e=null:(N.e=I,N.c=[_]);return}j=String(_)}else{if(!r.test(j=String(_)))return V(N,j,x);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(p(S,2,$e.length,"Base"),S==10&&ve)return N=new W(_),De(N,te+N.e+1,Z);if(j=String(_),x=typeof _=="number"){if(_*0!=0)return V(N,j,x,S);if(N.s=1/_<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(a+_)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(T=$e.slice(0,S),I=U=0,P=j.length;U<P;U++)if(T.indexOf(M=j.charAt(U))<0){if(M=="."){if(U>I){I=P;continue}}else if(!O&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){O=!0,U=-1,I=0;continue}return V(N,String(_),x,S)}x=!1,j=q(j,S,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,x&&W.DEBUG&&P>15&&(_>f||_!==o(_)))throw Error(a+N.s*_);if((I=I-U-1)>se)N.c=N.e=null;else if(I<Ee)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 S,T;if(_!=null)if(typeof _=="object"){if(_.hasOwnProperty(S="DECIMAL_PLACES")&&(T=_[S],p(T,0,C,S),te=T),_.hasOwnProperty(S="ROUNDING_MODE")&&(T=_[S],p(T,0,8,S),Z=T),_.hasOwnProperty(S="EXPONENTIAL_AT")&&(T=_[S],T&&T.pop?(p(T[0],-C,0,S),p(T[1],0,C,S),ue=T[0],he=T[1]):(p(T,-C,C,S),ue=-(he=T<0?-T:T))),_.hasOwnProperty(S="RANGE"))if(T=_[S],T&&T.pop)p(T[0],-C,-1,S),p(T[1],1,C,S),Ee=T[0],se=T[1];else if(p(T,-C,C,S),T)Ee=-(se=T<0?-T:T);else throw Error(s+S+" cannot be zero: "+T);if(_.hasOwnProperty(S="CRYPTO"))if(T=_[S],T===!!T)if(T)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=T;else throw pe=!T,Error(s+"crypto unavailable");else pe=T;else throw Error(s+S+" not true or false: "+T);if(_.hasOwnProperty(S="MODULO_MODE")&&(T=_[S],p(T,0,9,S),G=T),_.hasOwnProperty(S="POW_PRECISION")&&(T=_[S],p(T,0,C,S),K=T),_.hasOwnProperty(S="FORMAT"))if(T=_[S],typeof T=="object")ae=T;else throw Error(s+S+" not an object: "+T);if(_.hasOwnProperty(S="ALPHABET"))if(T=_[S],typeof T=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(T))ve=T.slice(0,10)=="0123456789",$e=T;else throw Error(s+S+" invalid: "+T)}else throw Error(s+"Object expected: "+_);return{DECIMAL_PLACES:te,ROUNDING_MODE:Z,EXPONENTIAL_AT:[ue,he],RANGE:[Ee,se],CRYPTO:pe,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ae,ALPHABET:$e}},W.isBigNumber=function(_){if(!_||_._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var S,T,M=_.c,O=_.e,I=_.s;e:if({}.toString.call(M)=="[object Array]"){if((I===1||I===-1)&&O>=-C&&O<=C&&O===o(O)){if(M[0]===0){if(O===0&&M.length===1)return!0;break e}if(S=(O+1)%l,S<1&&(S+=l),String(M[0]).length==S){for(S=0;S<M.length;S++)if(T=M[S],T<0||T>=c||T!==o(T))break e;if(T!==0)return!0}}}else if(M===null&&O===null&&(I===null||I===1||I===-1))return!0;throw Error(s+"Invalid BigNumber: "+_)},W.maximum=W.max=function(){return ye(arguments,-1)},W.minimum=W.min=function(){return ye(arguments,1)},W.random=(function(){var _=9007199254740992,S=Math.random()*_&2097151?function(){return o(Math.random()*_)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(T){var M,O,I,U,x,P=0,j=[],N=new W(Y);if(T==null?T=te:p(T,0,C),U=n(T/l),pe)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)x=M[P]*131072+(M[P+1]>>>11),x>=9e15?(O=crypto.getRandomValues(new Uint32Array(2)),M[P]=O[0],M[P+1]=O[1]):(j.push(x%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);P<U;)x=(M[P]&31)*281474976710656+M[P+1]*1099511627776+M[P+2]*4294967296+M[P+3]*16777216+(M[P+4]<<16)+(M[P+5]<<8)+M[P+6],x>=9e15?crypto.randomBytes(7).copy(M,P):(j.push(x%1e14),P+=7);P=U/7}else throw pe=!1,Error(s+"crypto unavailable");if(!pe)for(;P<U;)x=S(),x<9e15&&(j[P++]=x%1e14);for(U=j[--P],T%=l,U&&T&&(x=d[l-T],j[P]=o(U/x)*x);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,x=j[0];x>=10;x/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var _=1,S=arguments,T=new W(S[0]);_<S.length;)T=T.plus(S[_++]);return T},q=(function(){var _="0123456789";function S(T,M,O,I){for(var U,x=[0],P,j=0,N=T.length;j<N;){for(P=x.length;P--;x[P]*=M);for(x[0]+=I.indexOf(T.charAt(j++)),U=0;U<x.length;U++)x[U]>O-1&&(x[U+1]==null&&(x[U+1]=0),x[U+1]+=x[U]/O|0,x[U]%=O)}return x.reverse()}return function(T,M,O,I,U){var x,P,j,N,z,X,ee,we,Oe=T.indexOf("."),Ie=te,Ce=Z;for(Oe>=0&&(N=K,K=0,T=T.replace(".",""),we=new W(M),X=we.pow(T.length-Oe),K=N,we.c=S(E(b(X.c),X.e,"0"),10,O,_),we.e=we.c.length),ee=S(T,M,O,U?(x=$e,_):(x=_,$e)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return x.charAt(0);if(Oe<0?--j:(X.c=ee,X.e=j,X.s=I,X=F(X,we,Ie,Ce,O),ee=X.c,z=X.r,j=X.e),P=j+Ie+1,Oe=ee[P],N=O/2,z=z||P<0||ee[P+1]!=null,z=Ce<4?(Oe!=null||z)&&(Ce==0||Ce==(X.s<0?3:2)):Oe>N||Oe==N&&(Ce==4||z||Ce==6&&ee[P-1]&1||Ce==(X.s<0?8:7)),P<1||!ee[0])T=z?E(x.charAt(1),-Ie,x.charAt(0)):x.charAt(0);else{if(ee.length=P,z)for(--O;++ee[--P]>O;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(Oe=0,T="";Oe<=N;T+=x.charAt(ee[Oe++]));T=E(T,j,x.charAt(0))}return T}})(),F=(function(){function _(M,O,I){var U,x,P,j,N=0,z=M.length,X=O%m,ee=O/m|0;for(M=M.slice();z--;)P=M[z]%m,j=M[z]/m|0,U=ee*P+j*X,x=X*P+U%m*m+N,N=(x/I|0)+(U/m|0)+ee*j,M[z]=x%I;return N&&(M=[N].concat(M)),M}function S(M,O,I,U){var x,P;if(I!=U)P=I>U?1:-1;else for(x=P=0;x<I;x++)if(M[x]!=O[x]){P=M[x]>O[x]?1:-1;break}return P}function T(M,O,I,U){for(var x=0;I--;)M[I]-=x,x=M[I]<O[I]?1:0,M[I]=x*U+M[I]-O[I];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,O,I,U,x){var P,j,N,z,X,ee,we,Oe,Ie,Ce,Ae,Le,vn,Tn,Dn,dt,fr,Ke=M.s==O.s?1:-1,Ue=M.c,Se=O.c;if(!Ue||!Ue[0]||!Se||!Se[0])return new W(!M.s||!O.s||(Ue?Se&&Ue[0]==Se[0]:!Se)?NaN:Ue&&Ue[0]==0||!Se?Ke*0:Ke/0);for(Oe=new W(Ke),Ie=Oe.c=[],j=M.e-O.e,Ke=I+j+1,x||(x=c,j=A(M.e/l)-A(O.e/l),Ke=Ke/l|0),N=0;Se[N]==(Ue[N]||0);N++);if(Se[N]>(Ue[N]||0)&&j--,Ke<0)Ie.push(1),z=!0;else{for(Tn=Ue.length,dt=Se.length,N=0,Ke+=2,X=o(x/(Se[0]+1)),X>1&&(Se=_(Se,X,x),Ue=_(Ue,X,x),dt=Se.length,Tn=Ue.length),vn=dt,Ce=Ue.slice(0,dt),Ae=Ce.length;Ae<dt;Ce[Ae++]=0);fr=Se.slice(),fr=[0].concat(fr),Dn=Se[0],Se[1]>=x/2&&Dn++;do{if(X=0,P=S(Se,Ce,dt,Ae),P<0){if(Le=Ce[0],dt!=Ae&&(Le=Le*x+(Ce[1]||0)),X=o(Le/Dn),X>1)for(X>=x&&(X=x-1),ee=_(Se,X,x),we=ee.length,Ae=Ce.length;S(ee,Ce,we,Ae)==1;)X--,T(ee,dt<we?fr:Se,we,x),we=ee.length,P=1;else X==0&&(P=X=1),ee=Se.slice(),we=ee.length;if(we<Ae&&(ee=[0].concat(ee)),T(Ce,ee,Ae,x),Ae=Ce.length,P==-1)for(;S(Se,Ce,dt,Ae)<1;)X++,T(Ce,dt<Ae?fr:Se,Ae,x),Ae=Ce.length}else P===0&&(X++,Ce=[0]);Ie[N++]=X,Ce[0]?Ce[Ae++]=Ue[vn]||0:(Ce=[Ue[vn]],Ae=1)}while((vn++<Tn||Ce[0]!=null)&&Ke--);z=Ce[0]!=null,Ie[0]||Ie.splice(0,1)}if(x==c){for(N=1,Ke=Ie[0];Ke>=10;Ke/=10,N++);De(Oe,I+(Oe.e=N+j*l-1)+1,U,z)}else Oe.e=j,Oe.r=+z;return Oe}})();function le(_,S,T,M){var O,I,U,x,P;if(T==null?T=Z:p(T,0,8),!_.c)return _.toString();if(O=_.c[0],U=_.e,S==null)P=b(_.c),P=M==1||M==2&&(U<=ue||U>=he)?y(P,U):E(P,U,"0");else if(_=De(new W(_),S,T),I=_.e,P=b(_.c),x=P.length,M==1||M==2&&(S<=I||I<=ue)){for(;x<S;P+="0",x++);P=y(P,I)}else if(S-=U+(M===2&&I>U),P=E(P,I,"0"),I+1>x){if(--S>0)for(P+=".";S--;P+="0");}else if(S+=I-x,S>0)for(I+1==x&&(P+=".");S--;P+="0");return _.s<0&&O?"-"+P:P}function ye(_,S){for(var T,M,O=1,I=new W(_[0]);O<_.length;O++)M=new W(_[O]),(!M.s||(T=g(I,M))===S||T===0&&I.s===S)&&(I=M);return I}function Bt(_,S,T){for(var M=1,O=S.length;!S[--O];S.pop());for(O=S[0];O>=10;O/=10,M++);return(T=M+T*l-1)>se?_.c=_.e=null:T<Ee?_.c=[_.e=0]:(_.e=T,_.c=S),_}V=(function(){var _=/^(-?)0([xbo])(?=\w[\w.]*$)/i,S=/^([^.]+)\.$/,T=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,O=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,x,P){var j,N=x?U:U.replace(O,"");if(M.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!x&&(N=N.replace(_,function(z,X,ee){return j=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!P||P==j?X:z}),P&&(j=P,N=N.replace(S,"$1").replace(T,"0.$1")),U!=N))return new W(N,j);if(W.DEBUG)throw Error(s+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function De(_,S,T,M){var O,I,U,x,P,j,N,z=_.c,X=d;if(z){e:{for(O=1,x=z[0];x>=10;x/=10,O++);if(I=S-O,I<0)I+=l,U=S,P=z[j=0],N=o(P/X[O-U-1]%10);else if(j=n((I+1)/l),j>=z.length)if(M){for(;z.length<=j;z.push(0));P=N=0,O=1,I%=l,U=I-l+1}else break e;else{for(P=x=z[j],O=1;x>=10;x/=10,O++);I%=l,U=I-l+O,N=U<0?0:o(P/X[O-U-1]%10)}if(M=M||S<0||z[j+1]!=null||(U<0?P:P%X[O-U-1]),M=T<4?(N||M)&&(T==0||T==(_.s<0?3:2)):N>5||N==5&&(T==4||M||T==6&&(I>0?U>0?P/X[O-U]:0:z[j-1])%10&1||T==(_.s<0?8:7)),S<1||!z[0])return z.length=0,M?(S-=_.e+1,z[0]=X[(l-S%l)%l],_.e=-S||0):z[0]=_.e=0,_;if(I==0?(z.length=j,x=1,j--):(z.length=j+1,x=X[l-I],z[j]=U>0?o(P/X[O-U]%X[U])*x:0),M)for(;;)if(j==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=x,x=1;U>=10;U/=10,x++);I!=x&&(_.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=x,z[j]!=c)break;z[j--]=0,x=1}for(I=z.length;z[--I]===0;z.pop());}_.e>se?_.c=_.e=null:_.e<Ee&&(_.c=[_.e=0])}return _}function Be(_){var S,T=_.e;return T===null?_.toString():(S=b(_.c),S=T<=ue||T>=he?y(S,T):E(S,T,"0"),_.s<0?"-"+S:S)}return B.absoluteValue=B.abs=function(){var _=new W(this);return _.s<0&&(_.s=1),_},B.comparedTo=function(_,S){return g(this,new W(_,S))},B.decimalPlaces=B.dp=function(_,S){var T,M,O,I=this;if(_!=null)return p(_,0,C),S==null?S=Z:p(S,0,8),De(new W(I),_+I.e+1,S);if(!(T=I.c))return null;if(M=((O=T.length-1)-A(this.e/l))*l,O=T[O])for(;O%10==0;O/=10,M--);return M<0&&(M=0),M},B.dividedBy=B.div=function(_,S){return F(this,new W(_,S),te,Z)},B.dividedToIntegerBy=B.idiv=function(_,S){return F(this,new W(_,S),0,1)},B.exponentiatedBy=B.pow=function(_,S){var T,M,O,I,U,x,P,j,N,z=this;if(_=new W(_),_.c&&!_.isInteger())throw Error(s+"Exponent not an integer: "+Be(_));if(S!=null&&(S=new W(S)),x=_.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),x?_.s*(2-k(_)):+Be(_))),S?N.mod(S):N;if(P=_.s<0,S){if(S.c?!S.c[0]:!S.s)return new W(NaN);M=!P&&z.isInteger()&&S.isInteger(),M&&(z=z.mod(S))}else{if(_.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||x&&z.c[1]>=24e7:z.c[0]<8e13||x&&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(x?(T=new W(.5),P&&(_.s=1),j=k(_)):(O=Math.abs(+Be(_)),j=O%2),N=new W(Y);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):M&&(N=N.mod(S))}if(O){if(O=o(O/2),O===0)break;j=O%2}else if(_=_.times(T),De(_,_.e+1,1),_.e>14)j=k(_);else{if(O=+Be(_),O===0)break;j=O%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):M&&(z=z.mod(S))}return M?N:(P&&(N=Y.div(N)),S?N.mod(S):I?De(N,K,Z,U):N)},B.integerValue=function(_){var S=new W(this);return _==null?_=Z:p(_,0,8),De(S,S.e+1,_)},B.isEqualTo=B.eq=function(_,S){return g(this,new W(_,S))===0},B.isFinite=function(){return!!this.c},B.isGreaterThan=B.gt=function(_,S){return g(this,new W(_,S))>0},B.isGreaterThanOrEqualTo=B.gte=function(_,S){return(S=g(this,new W(_,S)))===1||S===0},B.isInteger=function(){return!!this.c&&A(this.e/l)>this.c.length-2},B.isLessThan=B.lt=function(_,S){return g(this,new W(_,S))<0},B.isLessThanOrEqualTo=B.lte=function(_,S){return(S=g(this,new W(_,S)))===-1||S===0},B.isNaN=function(){return!this.s},B.isNegative=function(){return this.s<0},B.isPositive=function(){return this.s>0},B.isZero=function(){return!!this.c&&this.c[0]==0},B.minus=function(_,S){var T,M,O,I,U=this,x=U.s;if(_=new W(_,S),S=_.s,!x||!S)return new W(NaN);if(x!=S)return _.s=-S,U.plus(_);var P=U.e/l,j=_.e/l,N=U.c,z=_.c;if(!P||!j){if(!N||!z)return N?(_.s=-S,_):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(_.s=-S,_):new W(N[0]?U:Z==3?-0:0)}if(P=A(P),j=A(j),N=N.slice(),x=P-j){for((I=x<0)?(x=-x,O=N):(j=P,O=z),O.reverse(),S=x;S--;O.push(0));O.reverse()}else for(M=(I=(x=N.length)<(S=z.length))?x:S,x=S=0;S<M;S++)if(N[S]!=z[S]){I=N[S]<z[S];break}if(I&&(O=N,N=z,z=O,_.s=-_.s),S=(M=z.length)-(T=N.length),S>0)for(;S--;N[T++]=0);for(S=c-1;M>x;){if(N[--M]<z[M]){for(T=M;T&&!N[--T];N[T]=S);--N[T],N[M]+=c}N[M]-=z[M]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?Bt(_,N,j):(_.s=Z==3?-1:1,_.c=[_.e=0],_)},B.modulo=B.mod=function(_,S){var T,M,O=this;return _=new W(_,S),!O.c||!_.s||_.c&&!_.c[0]?new W(NaN):!_.c||O.c&&!O.c[0]?new W(O):(G==9?(M=_.s,_.s=1,T=F(O,_,0,3),_.s=M,T.s*=M):T=F(O,_,0,G),_=O.minus(T.times(_)),!_.c[0]&&G==1&&(_.s=O.s),_)},B.multipliedBy=B.times=function(_,S){var T,M,O,I,U,x,P,j,N,z,X,ee,we,Oe,Ie,Ce=this,Ae=Ce.c,Le=(_=new W(_,S)).c;if(!Ae||!Le||!Ae[0]||!Le[0])return!Ce.s||!_.s||Ae&&!Ae[0]&&!Le||Le&&!Le[0]&&!Ae?_.c=_.e=_.s=null:(_.s*=Ce.s,!Ae||!Le?_.c=_.e=null:(_.c=[0],_.e=0)),_;for(M=A(Ce.e/l)+A(_.e/l),_.s*=Ce.s,P=Ae.length,z=Le.length,P<z&&(we=Ae,Ae=Le,Le=we,O=P,P=z,z=O),O=P+z,we=[];O--;we.push(0));for(Oe=c,Ie=m,O=z;--O>=0;){for(T=0,X=Le[O]%Ie,ee=Le[O]/Ie|0,U=P,I=O+U;I>O;)j=Ae[--U]%Ie,N=Ae[U]/Ie|0,x=ee*j+N*X,j=X*j+x%Ie*Ie+we[I]+T,T=(j/Oe|0)+(x/Ie|0)+ee*N,we[I--]=j%Oe;we[I]=T}return T?++M:we.splice(0,1),Bt(_,we,M)},B.negated=function(){var _=new W(this);return _.s=-_.s||null,_},B.plus=function(_,S){var T,M=this,O=M.s;if(_=new W(_,S),S=_.s,!O||!S)return new W(NaN);if(O!=S)return _.s=-S,M.minus(_);var I=M.e/l,U=_.e/l,x=M.c,P=_.c;if(!I||!U){if(!x||!P)return new W(O/0);if(!x[0]||!P[0])return P[0]?_:new W(x[0]?M:O*0)}if(I=A(I),U=A(U),x=x.slice(),O=I-U){for(O>0?(U=I,T=P):(O=-O,T=x),T.reverse();O--;T.push(0));T.reverse()}for(O=x.length,S=P.length,O-S<0&&(T=P,P=x,x=T,S=O),O=0;S;)O=(x[--S]=x[S]+P[S]+O)/c|0,x[S]=c===x[S]?0:x[S]%c;return O&&(x=[O].concat(x),++U),Bt(_,x,U)},B.precision=B.sd=function(_,S){var T,M,O,I=this;if(_!=null&&_!==!!_)return p(_,1,C),S==null?S=Z:p(S,0,8),De(new W(I),_,S);if(!(T=I.c))return null;if(O=T.length-1,M=O*l+1,O=T[O]){for(;O%10==0;O/=10,M--);for(O=T[0];O>=10;O/=10,M++);}return _&&I.e+1>M&&(M=I.e+1),M},B.shiftedBy=function(_){return p(_,-f,f),this.times("1e"+_)},B.squareRoot=B.sqrt=function(){var _,S,T,M,O,I=this,U=I.c,x=I.s,P=I.e,j=te+4,N=new W("0.5");if(x!==1||!U||!U[0])return new W(!x||x<0&&(!U||U[0])?NaN:U?I:1/0);if(x=Math.sqrt(+Be(I)),x==0||x==1/0?(S=b(U),(S.length+P)%2==0&&(S+="0"),x=Math.sqrt(+S),P=A((P+1)/2)-(P<0||P%2),x==1/0?S="5e"+P:(S=x.toExponential(),S=S.slice(0,S.indexOf("e")+1)+P),T=new W(S)):T=new W(x+""),T.c[0]){for(P=T.e,x=P+j,x<3&&(x=0);;)if(O=T,T=N.times(O.plus(F(I,O,j,1))),b(O.c).slice(0,x)===(S=b(T.c)).slice(0,x))if(T.e<P&&--x,S=S.slice(x-3,x+1),S=="9999"||!M&&S=="4999"){if(!M&&(De(O,O.e+te+2,0),O.times(O).eq(I))){T=O;break}j+=4,x+=4,M=1}else{(!+S||!+S.slice(1)&&S.charAt(0)=="5")&&(De(T,T.e+te+2,1),_=!T.times(T).eq(I));break}}return De(T,T.e+te+1,Z,_)},B.toExponential=function(_,S){return _!=null&&(p(_,0,C),_++),le(this,_,S,1)},B.toFixed=function(_,S){return _!=null&&(p(_,0,C),_=_+this.e+1),le(this,_,S)},B.toFormat=function(_,S,T){var M,O=this;if(T==null)_!=null&&S&&typeof S=="object"?(T=S,S=null):_&&typeof _=="object"?(T=_,_=S=null):T=ae;else if(typeof T!="object")throw Error(s+"Argument not an object: "+T);if(M=O.toFixed(_,S),O.c){var I,U=M.split("."),x=+T.groupSize,P=+T.secondaryGroupSize,j=T.groupSeparator||"",N=U[0],z=U[1],X=O.s<0,ee=X?N.slice(1):N,we=ee.length;if(P&&(I=x,x=P,P=I,we-=I),x>0&&we>0){for(I=we%x||x,N=ee.substr(0,I);I<we;I+=x)N+=j+ee.substr(I,x);P>0&&(N+=j+ee.slice(I)),X&&(N="-"+N)}M=z?N+(T.decimalSeparator||"")+((P=+T.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(T.fractionGroupSeparator||"")):z):N}return(T.prefix||"")+M+(T.suffix||"")},B.toFraction=function(_){var S,T,M,O,I,U,x,P,j,N,z,X,ee=this,we=ee.c;if(_!=null&&(x=new W(_),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Y)))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+Be(x));if(!we)return new W(ee);for(S=new W(Y),j=T=new W(Y),M=P=new W(Y),X=b(we),I=S.e=X.length-ee.e-1,S.c[0]=d[(U=I%l)<0?l+U:U],_=!_||x.comparedTo(S)>0?I>0?S:j:x,U=se,se=1/0,x=new W(X),P.c[0]=0;N=F(x,S,0,1),O=T.plus(N.times(M)),O.comparedTo(_)!=1;)T=M,M=O,j=P.plus(N.times(O=j)),P=O,S=x.minus(N.times(O=S)),x=O;return O=F(_.minus(T),M,0,1),P=P.plus(O.times(j)),T=T.plus(O.times(M)),P.s=j.s=ee.s,I=I*2,z=F(j,M,I,Z).minus(ee).abs().comparedTo(F(P,T,I,Z).minus(ee).abs())<1?[j,M]:[P,T],se=U,z},B.toNumber=function(){return+Be(this)},B.toPrecision=function(_,S){return _!=null&&p(_,1,C),le(this,_,S,2)},B.toString=function(_){var S,T=this,M=T.s,O=T.e;return O===null?M?(S="Infinity",M<0&&(S="-"+S)):S="NaN":(_==null?S=O<=ue||O>=he?y(b(T.c),O):E(b(T.c),O,"0"):_===10&&ve?(T=De(new W(T),te+O+1,Z),S=E(b(T.c),T.e,"0")):(p(_,2,$e.length,"Base"),S=q(E(b(T.c),O,"0"),10,_,M,!0)),M<0&&T.c[0]&&(S="-"+S)),S},B.valueOf=B.toJSON=function(){return Be(this)},B._isBigNumber=!0,D!=null&&W.set(D),W}function A(D){var F=D|0;return D>0||D===F?F:F-1}function b(D){for(var F,q,V=1,B=D.length,Y=D[0]+"";V<B;){for(F=D[V++]+"",q=l-F.length;q--;F="0"+F);Y+=F}for(B=Y.length;Y.charCodeAt(--B)===48;);return Y.slice(0,B+1||1)}function g(D,F){var q,V,B=D.c,Y=F.c,te=D.s,Z=F.s,ue=D.e,he=F.e;if(!te||!Z)return null;if(q=B&&!B[0],V=Y&&!Y[0],q||V)return q?V?0:-Z:te;if(te!=Z)return te;if(q=te<0,V=ue==he,!B||!Y)return V?0:!B^q?1:-1;if(!V)return ue>he^q?1:-1;for(Z=(ue=B.length)<(he=Y.length)?ue:he,te=0;te<Z;te++)if(B[te]!=Y[te])return B[te]>Y[te]^q?1:-1;return ue==he?0:ue>he^q?1:-1}function p(D,F,q,V){if(D<F||D>q||D!==o(D))throw Error(s+(V||"Argument")+(typeof D=="number"?D<F||D>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function k(D){var F=D.c.length-1;return A(D.e/l)==F&&D.c[F]%2!=0}function y(D,F){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(F<0?"e":"e+")+F}function E(D,F,q){var V,B;if(F<0){for(B=q+".";++F;B+=q);D=B+D}else if(V=D.length,++F>V){for(B=q,F-=V;--F;B+=q);D+=B}else F<V&&(D=D.slice(0,F)+"."+D.slice(F));return D}e=v(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Bi<"u"&&Bi.exports?Bi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(vm)});var xm=J((l1,Rm)=>{var Tm=Oc(),Dm=Rm.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}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,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(f){return r.lastIndex=0,r.test(f)?'"'+f.replace(r,function(d){var m=s[d];return typeof m=="string"?m:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function l(f,d){var m,C,v,A,b=n,g,p=d[f],k=p!=null&&(p instanceof Tm||Tm.isBigNumber(p));switch(p&&typeof p=="object"&&typeof p.toJSON=="function"&&(p=p.toJSON(f)),typeof a=="function"&&(p=a.call(d,f,p)),typeof p){case"string":return k?p:c(p);case"number":return isFinite(p)?String(p):"null";case"boolean":case"null":case"bigint":return String(p);case"object":if(!p)return"null";if(n+=o,g=[],Object.prototype.toString.apply(p)==="[object Array]"){for(A=p.length,m=0;m<A;m+=1)g[m]=l(m,p)||"null";return v=g.length===0?"[]":n?`[
44
44
  `+n+g.join(`,
45
45
  `+n)+`
46
- `+_+"]":"["+g.join(",")+"]",n=_,T}if(a&&typeof a=="object")for(S=a.length,p=0;p<S;p+=1)typeof a[p]=="string"&&(w=a[p],T=l(w,m),T&&g.push(c(w)+(n?": ":":")+T));else Object.keys(m).forEach(function(y){var E=l(y,m);E&&g.push(c(y)+(n?": ":":")+E)});return T=g.length===0?"{}":n?`{
46
+ `+b+"]":"["+g.join(",")+"]",n=b,v}if(a&&typeof a=="object")for(A=a.length,m=0;m<A;m+=1)typeof a[m]=="string"&&(C=a[m],v=l(C,p),v&&g.push(c(C)+(n?": ":":")+v));else Object.keys(p).forEach(function(y){var E=l(y,p);E&&g.push(c(y)+(n?": ":":")+E)});return v=g.length===0?"{}":n?`{
47
47
  `+n+g.join(`,
48
48
  `+n)+`
49
- `+_+"}":"{"+g.join(",")+"}",n=_,T}}typeof wm.stringify!="function"&&(wm.stringify=function(h,d,p){var w;if(n="",o="",typeof p=="number")for(w=0;w<p;w+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":h})})})()});var km=J((t1,Sm)=>{var Fi=null,gw=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,yw=/(?: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)/,_w=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,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
- `,r:"\r",t:" "},s,a=function(_){throw{name:"SyntaxError",message:_,at:r,text:s}},c=function(_){return _&&_!==n&&a("Expected '"+_+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},l=function(){var _,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(_=+g,!isFinite(_))a("Bad number");else return Fi==null&&(Fi=vc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Fi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new Fi(_):_},h=function(){var _,g,m="",k;if(n==='"')for(var y=r;c();){if(n==='"')return r-1>y&&(m+=s.substring(y,r-1)),c(),m;if(n==="\\"){if(r-1>y&&(m+=s.substring(y,r-1)),c(),n==="u"){for(k=0,g=0;g<4&&(_=parseInt(c(),16),!!isFinite(_));g+=1)k=k*16+_;m+=String.fromCharCode(k)}else if(typeof o[n]=="string")m+=o[n];else break;y=r}}a("Bad string")},d=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}a("Unexpected '"+n+"'")},w,T=function(){var _=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),_;for(;n;){if(_.push(w()),d(),n==="]")return c("]"),_;c(","),d()}}a("Bad array")},S=function(){var _,g=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),g;for(;n;){if(_=h(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,_)&&a('Duplicate key "'+_+'"'),gw.test(_)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():g[_]=w():yw.test(_)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():g[_]=w():g[_]=w(),d(),n==="}")return c("}"),g;c(","),d()}}a("Bad object")};return w=function(){switch(d(),n){case"{":return S();case"[":return T();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(_,g){var m;return s=_+"",r=0,n=" ",m=w(),d(),n&&a("Syntax error"),typeof g=="function"?(function k(y,E){var D,F,$=y[E];return $&&typeof $=="object"&&Object.keys($).forEach(function(V){F=k($,V),F!==void 0?$[V]=F:delete $[V]}),g.call(y,E,$)})({"":m},""):m}};Sm.exports=_w});var Dm=J((r1,Pi)=>{var vm=Am().stringify,Tm=km();Pi.exports=function(t){return{parse:Tm(t),stringify:vm}};Pi.exports.parse=Tm();Pi.exports.stringify=vm});var Tc=J(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.GCE_LINUX_BIOS_PATHS=void 0;qt.isGoogleCloudServerless=Om;qt.isGoogleComputeEngineLinux=Fm;qt.isGoogleComputeEngineMACAddress=Pm;qt.isGoogleComputeEngine=Im;qt.detectGCPResidency=Cw;var Rm=require("fs"),xm=require("os");qt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var bw=/^42:01/;function Om(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Fm(){if((0,xm.platform)()!=="linux")return!1;try{(0,Rm.statSync)(qt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Rm.readFileSync)(qt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Pm(){let t=(0,xm.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(bw.test(r))return!0}return!1}function Im(){return Fm()||Pm()}function Cw(){return Om()||Im()}});var Nm=J(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.Colours=void 0;var Qe=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="")}};Ii.Colours=Qe;Qe.enabled=!1;Qe.reset="";Qe.bright="";Qe.dim="";Qe.red="";Qe.green="";Qe.yellow="";Qe.blue="";Qe.magenta="";Qe.cyan="";Qe.white="";Qe.grey="";Qe.refresh()});var Mm=J(ke=>{"use strict";var ww=ke&&ke.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Ew=ke&&ke.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bm=ke&&ke.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&ww(r,e,n[o]);return Ew(r,e),r}})();Object.defineProperty(ke,"__esModule",{value:!0});ke.env=ke.DebugLogBackendBase=ke.placeholder=ke.AdhocDebugLogger=ke.LogSeverity=void 0;ke.getNodeBackend=Rc;ke.getDebugBackend=Sw;ke.getStructuredBackend=kw;ke.setBackend=vw;ke.log=Lm;var Aw=require("events"),zo=Bm(require("process")),jm=Bm(require("util")),pt=Nm(),$t;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})($t||(ke.LogSeverity=$t={}));var Ho=class extends Aw.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity($t.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity($t.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity($t.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity($t.ERROR,...n),this.func.sublog=n=>Lm(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)}};ke.AdhocDebugLogger=Ho;ke.placeholder=new Ho("",()=>{}).func;var Jn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=zo.env[ke.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 o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(r,...n)}catch(o){console.error(o)}}};ke.DebugLogBackendBase=Jn;var Dc=class extends Jn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var o;let s=`${pt.Colours.green}${e}${pt.Colours.reset}`,a=`${pt.Colours.yellow}${zo.pid}${pt.Colours.reset}`,c;switch(r.severity){case $t.ERROR:c=`${pt.Colours.red}${r.severity}${pt.Colours.reset}`;break;case $t.INFO:c=`${pt.Colours.magenta}${r.severity}${pt.Colours.reset}`;break;case $t.WARNING:c=`${pt.Colours.yellow}${r.severity}${pt.Colours.reset}`;break;default:c=(o=r.severity)!==null&&o!==void 0?o:$t.DEFAULT;break}let l=jm.formatWithOptions({colors:pt.Colours.enabled},...n),h=Object.assign({},r);delete h.severity;let d=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=d?`${pt.Colours.grey}${d}${pt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,d?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function Rc(){return new Dc}var xc=class extends Jn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...o)=>{r(o[0],...o.slice(1))}}setFilters(){var e;let r=(e=zo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";zo.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function Sw(t){return new xc(t)}var Oc=class extends Jn{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(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:$t.INFO,l=Object.assign({severity:c,message:jm.format(...s)},o),h=JSON.stringify(l);n?n(o,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function kw(t){return new Oc(t)}ke.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Fc=new Map,mt;function vw(t){mt=t,Fc.clear()}function Lm(t,e){if(!mt&&!zo.env[ke.env.nodeEnables]||!t)return ke.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=Fc.get(t);if(r)return r.func;if(mt===null)return ke.placeholder;mt===void 0&&(mt=Rc());let n=(()=>{let o;return new Ho(t,(a,...c)=>{if(o!==mt){if(mt===null)return;mt===void 0&&(mt=Rc()),o=mt}mt?.log(t,a,...c)})})();return Fc.set(t,n),n.func}});var Pc=J(gn=>{"use strict";var Tw=gn&&gn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Dw=gn&&gn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Tw(e,t,r)};Object.defineProperty(gn,"__esModule",{value:!0});Dw(Mm(),gn)});var Go=J(ie=>{"use strict";var qm=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Rw=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xw=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&qm(r,e,n[o]);return Rw(r,e),r}})(),Ow=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&qm(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=jw;ie.project=Lw;ie.universe=Mw;ie.bulk=Uw;ie.isAvailable=$w;ie.resetIsAvailableCache=zw;ie.getGCPResidency=Bc;ie.setGCPResidency=$m;ie.requestTimeout=zm;var Ic=Ve(),Fw=Dm(),Pw=Tc(),Iw=xw(Pc());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 Um=Iw.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 Nc(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 Wo(t,e={},r=3,n=!1){let o=new Headers(ie.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((w,T)=>o.set(T,w)),s=p.metadataKey,a=p.params||a,r=p.noResponseRetries||r,n=p.fastFail||n}else s=t;typeof e=="string"?s+=`/${e}`:(Nw(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,w)=>o.set(w,p)),a=e.params||a);let c=n?Bw:Ic.request,l={url:`${Nc()}/${s}`,headers:o,retryConfig:{noResponseRetries:r},params:a,responseType:"text",timeout:zm()};Um.info("instance request %j",l);let h=await c(l);Um.info("instance metadata is %s",h.data);let d=h.headers.get(ie.HEADER_NAME);if(d!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof h.data=="string")try{return Fw.parse(h.data)}catch{}return h.data}async function Bw(t){let e={...t,url:t.url?.toString().replace(Nc(),Nc(ie.SECONDARY_HOST_ADDRESS))},r=(0,Ic.request)(t),n=(0,Ic.request)(e);return Promise.any([r,n])}function jw(t){return Wo("instance",t)}function Lw(t){return Wo("project",t)}function Mw(t){return Wo("universe",t)}async function Uw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Wo(r),o=r.metadataKey;e[o]=n})())),e}function qw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Ni;async function $w(){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 Bc();case"ping-only":}}try{return Ni===void 0&&(Ni=Wo("instance",void 0,qw(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Ni,!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 zw(){Ni=void 0}ie.gcpResidencyCache=null;function Bc(){return ie.gcpResidencyCache===null&&$m(),ie.gcpResidencyCache}function $m(t=null){ie.gcpResidencyCache=t!==null?t:(0,Pw.detectGCPResidency)()}function zm(){return Bc()?0:3e3}Ow(Tc(),ie)});var Gm=J(Bi=>{"use strict";Bi.byteLength=Ww;Bi.toByteArray=Jw;Bi.fromByteArray=Yw;var tr=[],Dt=[],Hw=typeof Uint8Array<"u"?Uint8Array:Array,jc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(yn=0,Hm=jc.length;yn<Hm;++yn)tr[yn]=jc[yn],Dt[jc.charCodeAt(yn)]=yn;var yn,Hm;Dt[45]=62;Dt[95]=63;function Wm(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 Ww(t){var e=Wm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Gw(t,e,r){return(e+r)*3/4-r}function Jw(t){var e,r=Wm(t),n=r[0],o=r[1],s=new Hw(Gw(t,n,o)),a=0,c=o>0?n-4:n,l;for(l=0;l<c;l+=4)e=Dt[t.charCodeAt(l)]<<18|Dt[t.charCodeAt(l+1)]<<12|Dt[t.charCodeAt(l+2)]<<6|Dt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Dt[t.charCodeAt(l)]<<2|Dt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Dt[t.charCodeAt(l)]<<10|Dt[t.charCodeAt(l+1)]<<4|Dt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function Vw(t){return tr[t>>18&63]+tr[t>>12&63]+tr[t>>6&63]+tr[t&63]}function Kw(t,e,r){for(var n,o=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(Vw(n));return o.join("")}function Yw(t){for(var e,r=t.length,n=r%3,o=[],s=16383,a=0,c=r-n;a<c;a+=s)o.push(Kw(t,a,a+s>c?c:a+s));return n===1?(e=t[r-1],o.push(tr[e>>2]+tr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],o.push(tr[e>>10]+tr[e>>4&63]+tr[e<<2&63]+"=")),o.join("")}});var Mc=J(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.fromArrayBufferToHex=Qw;function Qw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var Jm=J(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.BrowserCrypto=void 0;var Vn=Gm(),Xw=Mc(),Uc=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 Vn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Vn.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),a=Vn.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),s=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),a=await window.crypto.subtle.sign(n,s,o);return Vn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let r=Vn.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Vn.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,Xw.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(r))}};ji.BrowserCrypto=Uc});var Vm=J(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.NodeCrypto=void 0;var Kn=require("crypto"),qc=class{async sha256DigestBase64(e){return Kn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Kn.randomBytes(e).toString("base64")}async verify(e,r,n){let o=Kn.createVerify("RSA-SHA256");return o.update(r),o.end(),o.verify(e,n,"base64")}async sign(e,r){let n=Kn.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 Kn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:eE(e);return Zw(Kn.createHmac("sha256",n).update(r).digest())}};Li.NodeCrypto=qc;function Zw(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function eE(t){return Buffer.from(t)}});var Jo=J(Ar=>{"use strict";var tE=Ar&&Ar.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),rE=Ar&&Ar.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&tE(e,t,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.createCrypto=sE;Ar.hasBrowserCrypto=Km;var nE=Jm(),oE=Vm();rE(Mc(),Ar);function sE(){return Km()?new nE.BrowserCrypto:new oE.NodeCrypto}function Km(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Yn=J(($c,Qm)=>{var Mi=require("buffer"),rr=Mi.Buffer;function Ym(t,e){for(var r in t)e[r]=t[r]}rr.from&&rr.alloc&&rr.allocUnsafe&&rr.allocUnsafeSlow?Qm.exports=Mi:(Ym(Mi,$c),$c.Buffer=_n);function _n(t,e,r){return rr(t,e,r)}_n.prototype=Object.create(rr.prototype);Ym(rr,_n);_n.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return rr(t,e,r)};_n.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=rr(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};_n.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rr(t)};_n.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Mi.SlowBuffer(t)}});var Zm=J((h1,Xm)=>{"use strict";function zc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var iE={ES256:zc(256),ES384:zc(384),ES512:zc(521)};function aE(t){var e=iE[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Xm.exports=aE});var Hc=J((p1,sg)=>{"use strict";var Ui=Yn().Buffer,tg=Zm(),qi=128,rg=0,uE=32,cE=16,lE=2,ng=cE|uE|rg<<6,$i=lE|rg<<6;function dE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function og(t){if(Ui.isBuffer(t))return t;if(typeof t=="string")return Ui.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function fE(t,e){t=og(t);var r=tg(e),n=r+1,o=t.length,s=0;if(t[s++]!==ng)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(qi|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==$i)throw new Error('Could not find expected "int" for "r"');var c=t[s++];if(o-s-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(o-s-2)+'" available');if(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=s;if(s+=c,t[s++]!==$i)throw new Error('Could not find expected "int" for "s"');var h=t[s++];if(o-s!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(o-s)+'"');if(n<h)throw new Error('"s" specified length of "'+h+'", max of "'+n+'" is acceptable');var d=s;if(s+=h,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=r-c,w=r-h,T=Ui.allocUnsafe(p+c+w+h);for(s=0;s<p;++s)T[s]=0;t.copy(T,s,l+Math.max(-p,0),l+c),s=r;for(var S=s;s<S+w;++s)T[s]=0;return t.copy(T,s,d+Math.max(-w,0),d+h),T=T.toString("base64"),T=dE(T),T}function eg(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var o=t[e+n]>=qi;return o&&--n,n}function hE(t,e){t=og(t);var r=tg(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var o=eg(t,0,r),s=eg(t,r,t.length),a=r-o,c=r-s,l=2+a+1+1+c,h=l<qi,d=Ui.allocUnsafe((h?2:3)+l),p=0;return d[p++]=ng,h?d[p++]=l:(d[p++]=qi|1,d[p++]=l&255),d[p++]=$i,d[p++]=a,o<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,o,r),d[p++]=$i,d[p++]=c,s<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+s),d}sg.exports={derToJose:fE,joseToDer:hE}});var zt=J(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.LRUCache=void 0;Sr.snakeToCamel=ag;Sr.originalOrCamelOptions=yE;Sr.removeUndefinedValuesInObject=_E;Sr.isValidFile=bE;Sr.getWellKnownCertificateConfigFileLocation=CE;var pE=require("fs"),mE=require("os"),Wc=require("path"),gE="certificate_config.json",ig="gcloud";function ag(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function yE(t){function e(r){let n=t||{};return n[r]??n[ag(r)]}return{get:e}}var Gc=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()}};Sr.LRUCache=Gc;function _E(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function bE(t){try{return(await pE.promises.lstat(t)).isFile()}catch{return!1}}function CE(){let t=process.env.CLOUDSDK_CONFIG||(wE()?Wc.join(process.env.APPDATA||"",ig):Wc.join(process.env.HOME||"",".config",ig));return Wc.join(t,gE)}function wE(){return mE.platform().startsWith("win")}});var ug=J((g1,EE)=>{EE.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 Jc=J(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.USER_AGENT=Wr.PRODUCT_NAME=Wr.pkg=void 0;var cg=ug();Wr.pkg=cg;var lg="google-api-nodejs-client";Wr.PRODUCT_NAME=lg;var AE=`${lg}/${cg.version}`;Wr.USER_AGENT=AE});var gt=J(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.AuthClient=Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Ht.DEFAULT_UNIVERSE=void 0;var SE=require("events"),Vc=Ve(),kE=zt(),vE=Pc(),Kc=Jc();Ht.DEFAULT_UNIVERSE="googleapis.com";Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Yc=class t extends SE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Ht.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,kE.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")??Ht.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Vc.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],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Vc.Gaxios.mergeHeaders(s,r.headers),n&&Vc.Gaxios.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,headers:s,url:o})}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"),o=r.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,vE.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,o=n[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,o,e.response?.data):t.log.error("[%s] error %j",o,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"]}}}};Ht.AuthClient=Yc});var Xc=J(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.LoginTicket=void 0;var Qc=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()}}};zi.LoginTicket=Qc});var bn=J(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.OAuth2Client=nr.ClientAuthentication=nr.CertificateFormat=nr.CodeChallengeMethod=void 0;var dg=Ve(),TE=require("querystring"),DE=require("stream"),RE=Hc(),fg=zt(),Zc=Jo(),Qn=gt(),xE=Xc(),hg;(function(t){t.Plain="plain",t.S256="S256"})(hg||(nr.CodeChallengeMethod=hg={}));var kr;(function(t){t.PEM="PEM",t.JWK="JWK"})(kr||(nr.CertificateFormat=kr={}));var Vo;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Vo||(nr.ClientAuthentication=Vo={}));var el=class t extends Qn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=kr.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||Vo.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()+"?"+TE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Zc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:s}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(o=>r(null,o.tokens,o.res),o=>r(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={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===Vo.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Vo.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,fg.removeUndefinedValuesInObject)(o)),headers:n};Qn.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}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"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,fg.removeUndefinedValuesInObject)(n))};Qn.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof dg.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}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,o=null;try{n=await this.refreshToken(r.refresh_token),o=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 s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),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(Qn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(o=>r(null,o),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=dg.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 o=n.response;if(o){let s=o.status,a=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=o.config.data instanceof DE.Readable,h=s===401||s===403;if(!r&&h&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&h&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),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,Zc.hasBrowserCrypto)()?kr.JWK:kr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,o;switch(r){case kr.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case kr.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let h={...t.RETRY_CONFIG,url:o};Qn.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 s=n?.headers.get("cache-control"),a=-1;if(s){let h=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;h&&(a=Number(h)*1e3)}let c={};switch(r){case kr.PEM:c=n.data;break;case kr.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=a===-1?null:new Date(l.getTime()+a),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};Qn.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,o,s){let a=(0,Zc.createCrypto)();s||(s=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],d,p;try{d=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(y){throw y instanceof Error&&(y.message=`Can't parse token envelope: ${c[0]}': ${y.message}`),y}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(y){throw y instanceof Error&&(y.message=`Can't parse token payload '${c[0]}`),y}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let w=r[d.kid];if(d.alg==="ES256"&&(h=RE.joseToDer(h,"ES256").toString("base64")),!await a.verify(w,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 _=Number(p.exp);if(isNaN(_))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(_>=g+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=S-t.CLOCK_SKEW_SECS_,k=_+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(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof n<"u"&&n!==null){let y=p.aud,E=!1;if(n.constructor===Array?E=n.indexOf(y)>-1:E=y===n,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new xE.LoginTicket(d,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}};nr.OAuth2Client=el});var rl=J(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.Compute=void 0;var OE=Ve(),pg=Go(),FE=bn(),tl=class extends FE.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 o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),r=await pg.instance(o)}catch(o){throw o instanceof OE.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}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 o={property:r};n=await pg.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}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))}};Hi.Compute=tl});var ol=J(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.IdTokenClient=void 0;var PE=bn(),nl=class extends PE.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}};Wi.IdTokenClient=nl});var sl=J(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.GCPEnv=void 0;Xn.clear=IE;Xn.getEnv=NE;var mg=Go(),or;(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"})(or||(Xn.GCPEnv=or={}));var Ko;function IE(){Ko=void 0}async function NE(){return Ko||(Ko=BE(),Ko)}async function BE(){let t=or.NONE;return jE()?t=or.APP_ENGINE:LE()?t=or.CLOUD_FUNCTIONS:await $E()?await qE()?t=or.KUBERNETES_ENGINE:ME()?t=or.CLOUD_RUN:UE()?t=or.CLOUD_RUN_JOBS:t=or.COMPUTE_ENGINE:t=or.NONE,t}function jE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function LE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function ME(){return!!process.env.K_CONFIGURATION}function UE(){return!!process.env.CLOUD_RUN_JOB}async function qE(){try{return await mg.instance("attributes/cluster-name"),!0}catch{return!1}}async function $E(){return mg.isAvailable()}});var il=J((S1,gg)=>{var Gi=Yn().Buffer,zE=require("stream"),HE=require("util");function Ji(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Gi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Gi.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(Ji,zE);Ji.prototype.write=function(e){this.buffer=Gi.concat([this.buffer,Gi.from(e)]),this.emit("data",e)};Ji.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};gg.exports=Ji});var _g=J((k1,yg)=>{"use strict";var Yo=require("buffer").Buffer,al=require("buffer").SlowBuffer;yg.exports=Vi;function Vi(t,e){if(!Yo.isBuffer(t)||!Yo.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}Vi.install=function(){Yo.prototype.equal=al.prototype.equal=function(e){return Vi(this,e)}};var WE=Yo.prototype.equal,GE=al.prototype.equal;Vi.restore=function(){Yo.prototype.equal=WE,al.prototype.equal=GE}});var dl=J((v1,Tg)=>{var eo=Yn().Buffer,Rt=require("crypto"),Cg=Hc(),bg=require("util"),JE=`"%s" is not a valid algorithm.
49
+ `+b+"}":"{"+g.join(",")+"}",n=b,v}}typeof Dm.stringify!="function"&&(Dm.stringify=function(f,d,m){var C;if(n="",o="",typeof m=="number")for(C=0;C<m;C+=1)o+=" ";else typeof m=="string"&&(o=m);if(a=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":f})})})()});var Fm=J((d1,Om)=>{var Mi=null,kw=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,vw=/(?: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)/,Tw=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,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
+ `,r:"\r",t:" "},s,a=function(b){throw{name:"SyntaxError",message:b,at:r,text:s}},c=function(b){return b&&b!==n&&a("Expected '"+b+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},l=function(){var b,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(b=+g,!isFinite(b))a("Bad number");else return Mi==null&&(Mi=Oc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Mi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(b):new Mi(b):b},f=function(){var b,g,p="",k;if(n==='"')for(var y=r;c();){if(n==='"')return r-1>y&&(p+=s.substring(y,r-1)),c(),p;if(n==="\\"){if(r-1>y&&(p+=s.substring(y,r-1)),c(),n==="u"){for(k=0,g=0;g<4&&(b=parseInt(c(),16),!!isFinite(b));g+=1)k=k*16+b;p+=String.fromCharCode(k)}else if(typeof o[n]=="string")p+=o[n];else break;y=r}}a("Bad string")},d=function(){for(;n&&n<=" ";)c()},m=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}a("Unexpected '"+n+"'")},C,v=function(){var b=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),b;for(;n;){if(b.push(C()),d(),n==="]")return c("]"),b;c(","),d()}}a("Bad array")},A=function(){var b,g=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),g;for(;n;){if(b=f(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,b)&&a('Duplicate key "'+b+'"'),kw.test(b)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?C():g[b]=C():vw.test(b)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?C():g[b]=C():g[b]=C(),d(),n==="}")return c("}"),g;c(","),d()}}a("Bad object")};return C=function(){switch(d(),n){case"{":return A();case"[":return v();case'"':return f();case"-":return l();default:return n>="0"&&n<="9"?l():m()}},function(b,g){var p;return s=b+"",r=0,n=" ",p=C(),d(),n&&a("Syntax error"),typeof g=="function"?(function k(y,E){var D,F,q=y[E];return q&&typeof q=="object"&&Object.keys(q).forEach(function(V){F=k(q,V),F!==void 0?q[V]=F:delete q[V]}),g.call(y,E,q)})({"":p},""):p}};Om.exports=Tw});var Nm=J((f1,ji)=>{var Pm=xm().stringify,Im=Fm();ji.exports=function(t){return{parse:Im(t),stringify:Pm}};ji.exports.parse=Im();ji.exports.stringify=Pm});var Fc=J(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.GCE_LINUX_BIOS_PATHS=void 0;zt.isGoogleCloudServerless=jm;zt.isGoogleComputeEngineLinux=Lm;zt.isGoogleComputeEngineMACAddress=Um;zt.isGoogleComputeEngine=$m;zt.detectGCPResidency=Rw;var Bm=require("fs"),Mm=require("os");zt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Dw=/^42:01/;function jm(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Lm(){if((0,Mm.platform)()!=="linux")return!1;try{(0,Bm.statSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Bm.readFileSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Um(){let t=(0,Mm.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(Dw.test(r))return!0}return!1}function $m(){return Lm()||Um()}function Rw(){return jm()||$m()}});var qm=J(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.Colours=void 0;var Qe=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="")}};Li.Colours=Qe;Qe.enabled=!1;Qe.reset="";Qe.bright="";Qe.dim="";Qe.red="";Qe.green="";Qe.yellow="";Qe.blue="";Qe.magenta="";Qe.cyan="";Qe.white="";Qe.grey="";Qe.refresh()});var Gm=J(ke=>{"use strict";var xw=ke&&ke.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Ow=ke&&ke.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zm=ke&&ke.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&xw(r,e,n[o]);return Ow(r,e),r}})();Object.defineProperty(ke,"__esModule",{value:!0});ke.env=ke.DebugLogBackendBase=ke.placeholder=ke.AdhocDebugLogger=ke.LogSeverity=void 0;ke.getNodeBackend=Ic;ke.getDebugBackend=Pw;ke.getStructuredBackend=Iw;ke.setBackend=Nw;ke.log=Wm;var Fw=require("events"),Go=zm(require("process")),Hm=zm(require("util")),yt=qm(),Ht;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Ht||(ke.LogSeverity=Ht={}));var Jo=class extends Fw.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(Ht.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Ht.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Ht.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Ht.ERROR,...n),this.func.sublog=n=>Wm(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)}};ke.AdhocDebugLogger=Jo;ke.placeholder=new Jo("",()=>{}).func;var Yn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Go.env[ke.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 o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(r,...n)}catch(o){console.error(o)}}};ke.DebugLogBackendBase=Yn;var Pc=class extends Yn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var o;let s=`${yt.Colours.green}${e}${yt.Colours.reset}`,a=`${yt.Colours.yellow}${Go.pid}${yt.Colours.reset}`,c;switch(r.severity){case Ht.ERROR:c=`${yt.Colours.red}${r.severity}${yt.Colours.reset}`;break;case Ht.INFO:c=`${yt.Colours.magenta}${r.severity}${yt.Colours.reset}`;break;case Ht.WARNING:c=`${yt.Colours.yellow}${r.severity}${yt.Colours.reset}`;break;default:c=(o=r.severity)!==null&&o!==void 0?o:Ht.DEFAULT;break}let l=Hm.formatWithOptions({colors:yt.Colours.enabled},...n),f=Object.assign({},r);delete f.severity;let d=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",m=d?`${yt.Colours.grey}${d}${yt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,d?` ${m}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function Ic(){return new Pc}var Nc=class extends Yn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...o)=>{r(o[0],...o.slice(1))}}setFilters(){var e;let r=(e=Go.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Go.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function Pw(t){return new Nc(t)}var Bc=class extends Yn{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(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:Ht.INFO,l=Object.assign({severity:c,message:Hm.format(...s)},o),f=JSON.stringify(l);n?n(o,f):console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Iw(t){return new Bc(t)}ke.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Mc=new Map,_t;function Nw(t){_t=t,Mc.clear()}function Wm(t,e){if(!_t&&!Go.env[ke.env.nodeEnables]||!t)return ke.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=Mc.get(t);if(r)return r.func;if(_t===null)return ke.placeholder;_t===void 0&&(_t=Ic());let n=(()=>{let o;return new Jo(t,(a,...c)=>{if(o!==_t){if(_t===null)return;_t===void 0&&(_t=Ic()),o=_t}_t?.log(t,a,...c)})})();return Mc.set(t,n),n.func}});var jc=J(_n=>{"use strict";var Bw=_n&&_n.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Mw=_n&&_n.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Bw(e,t,r)};Object.defineProperty(_n,"__esModule",{value:!0});Mw(Gm(),_n)});var Ko=J(ie=>{"use strict";var Vm=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),jw=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Lw=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Vm(r,e,n[o]);return jw(r,e),r}})(),Uw=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Vm(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=Gw;ie.project=Jw;ie.universe=Vw;ie.bulk=Kw;ie.isAvailable=Qw;ie.resetIsAvailableCache=Xw;ie.getGCPResidency=$c;ie.setGCPResidency=Km;ie.requestTimeout=Ym;var Lc=Ve(),$w=Nm(),qw=Fc(),zw=Lw(jc());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 Jm=zw.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 Uc(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 Hw(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 Vo(t,e={},r=3,n=!1){let o=new Headers(ie.HEADERS),s="",a={};if(typeof t=="object"){let m=t;new Headers(m.headers).forEach((C,v)=>o.set(v,C)),s=m.metadataKey,a=m.params||a,r=m.noResponseRetries||r,n=m.fastFail||n}else s=t;typeof e=="string"?s+=`/${e}`:(Hw(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((m,C)=>o.set(C,m)),a=e.params||a);let c=n?Ww:Lc.request,l={url:`${Uc()}/${s}`,headers:o,retryConfig:{noResponseRetries:r},params:a,responseType:"text",timeout:Ym()};Jm.info("instance request %j",l);let f=await c(l);Jm.info("instance metadata is %s",f.data);let d=f.headers.get(ie.HEADER_NAME);if(d!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return $w.parse(f.data)}catch{}return f.data}async function Ww(t){let e={...t,url:t.url?.toString().replace(Uc(),Uc(ie.SECONDARY_HOST_ADDRESS))},r=(0,Lc.request)(t),n=(0,Lc.request)(e);return Promise.any([r,n])}function Gw(t){return Vo("instance",t)}function Jw(t){return Vo("project",t)}function Vw(t){return Vo("universe",t)}async function Kw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Vo(r),o=r.metadataKey;e[o]=n})())),e}function Yw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Ui;async function Qw(){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 $c();case"ping-only":}}try{return Ui===void 0&&(Ui=Vo("instance",void 0,Yw(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Ui,!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 Xw(){Ui=void 0}ie.gcpResidencyCache=null;function $c(){return ie.gcpResidencyCache===null&&Km(),ie.gcpResidencyCache}function Km(t=null){ie.gcpResidencyCache=t!==null?t:(0,qw.detectGCPResidency)()}function Ym(){return $c()?0:3e3}Uw(Fc(),ie)});var Zm=J($i=>{"use strict";$i.byteLength=eE;$i.toByteArray=rE;$i.fromByteArray=sE;var rr=[],xt=[],Zw=typeof Uint8Array<"u"?Uint8Array:Array,qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(bn=0,Qm=qc.length;bn<Qm;++bn)rr[bn]=qc[bn],xt[qc.charCodeAt(bn)]=bn;var bn,Qm;xt[45]=62;xt[95]=63;function Xm(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 eE(t){var e=Xm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function tE(t,e,r){return(e+r)*3/4-r}function rE(t){var e,r=Xm(t),n=r[0],o=r[1],s=new Zw(tE(t,n,o)),a=0,c=o>0?n-4:n,l;for(l=0;l<c;l+=4)e=xt[t.charCodeAt(l)]<<18|xt[t.charCodeAt(l+1)]<<12|xt[t.charCodeAt(l+2)]<<6|xt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=xt[t.charCodeAt(l)]<<2|xt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=xt[t.charCodeAt(l)]<<10|xt[t.charCodeAt(l+1)]<<4|xt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function nE(t){return rr[t>>18&63]+rr[t>>12&63]+rr[t>>6&63]+rr[t&63]}function oE(t,e,r){for(var n,o=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(nE(n));return o.join("")}function sE(t){for(var e,r=t.length,n=r%3,o=[],s=16383,a=0,c=r-n;a<c;a+=s)o.push(oE(t,a,a+s>c?c:a+s));return n===1?(e=t[r-1],o.push(rr[e>>2]+rr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],o.push(rr[e>>10]+rr[e>>4&63]+rr[e<<2&63]+"=")),o.join("")}});var Hc=J(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.fromArrayBufferToHex=iE;function iE(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var eg=J(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.BrowserCrypto=void 0;var Qn=Zm(),aE=Hc(),Wc=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 Qn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Qn.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),a=Qn.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),s=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),a=await window.crypto.subtle.sign(n,s,o);return Qn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let r=Qn.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Qn.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,aE.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(r))}};qi.BrowserCrypto=Wc});var tg=J(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.NodeCrypto=void 0;var Xn=require("crypto"),Gc=class{async sha256DigestBase64(e){return Xn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Xn.randomBytes(e).toString("base64")}async verify(e,r,n){let o=Xn.createVerify("RSA-SHA256");return o.update(r),o.end(),o.verify(e,n,"base64")}async sign(e,r){let n=Xn.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 Xn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:cE(e);return uE(Xn.createHmac("sha256",n).update(r).digest())}};zi.NodeCrypto=Gc;function uE(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function cE(t){return Buffer.from(t)}});var Yo=J(Sr=>{"use strict";var lE=Sr&&Sr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),dE=Sr&&Sr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&lE(e,t,r)};Object.defineProperty(Sr,"__esModule",{value:!0});Sr.createCrypto=pE;Sr.hasBrowserCrypto=rg;var fE=eg(),hE=tg();dE(Hc(),Sr);function pE(){return rg()?new fE.BrowserCrypto:new hE.NodeCrypto}function rg(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Zn=J((Jc,og)=>{var Hi=require("buffer"),nr=Hi.Buffer;function ng(t,e){for(var r in t)e[r]=t[r]}nr.from&&nr.alloc&&nr.allocUnsafe&&nr.allocUnsafeSlow?og.exports=Hi:(ng(Hi,Jc),Jc.Buffer=Cn);function Cn(t,e,r){return nr(t,e,r)}Cn.prototype=Object.create(nr.prototype);ng(nr,Cn);Cn.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return nr(t,e,r)};Cn.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=nr(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Cn.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return nr(t)};Cn.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Hi.SlowBuffer(t)}});var ig=J((A1,sg)=>{"use strict";function Vc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var mE={ES256:Vc(256),ES384:Vc(384),ES512:Vc(521)};function gE(t){var e=mE[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}sg.exports=gE});var Kc=J((S1,fg)=>{"use strict";var Wi=Zn().Buffer,ug=ig(),Gi=128,cg=0,yE=32,_E=16,bE=2,lg=_E|yE|cg<<6,Ji=bE|cg<<6;function CE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function dg(t){if(Wi.isBuffer(t))return t;if(typeof t=="string")return Wi.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function wE(t,e){t=dg(t);var r=ug(e),n=r+1,o=t.length,s=0;if(t[s++]!==lg)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(Gi|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==Ji)throw new Error('Could not find expected "int" for "r"');var c=t[s++];if(o-s-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(o-s-2)+'" available');if(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=s;if(s+=c,t[s++]!==Ji)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(n<f)throw new Error('"s" specified length of "'+f+'", max of "'+n+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var m=r-c,C=r-f,v=Wi.allocUnsafe(m+c+C+f);for(s=0;s<m;++s)v[s]=0;t.copy(v,s,l+Math.max(-m,0),l+c),s=r;for(var A=s;s<A+C;++s)v[s]=0;return t.copy(v,s,d+Math.max(-C,0),d+f),v=v.toString("base64"),v=CE(v),v}function ag(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var o=t[e+n]>=Gi;return o&&--n,n}function EE(t,e){t=dg(t);var r=ug(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var o=ag(t,0,r),s=ag(t,r,t.length),a=r-o,c=r-s,l=2+a+1+1+c,f=l<Gi,d=Wi.allocUnsafe((f?2:3)+l),m=0;return d[m++]=lg,f?d[m++]=l:(d[m++]=Gi|1,d[m++]=l&255),d[m++]=Ji,d[m++]=a,o<0?(d[m++]=0,m+=t.copy(d,m,0,r)):m+=t.copy(d,m,o,r),d[m++]=Ji,d[m++]=c,s<0?(d[m++]=0,t.copy(d,m,r)):t.copy(d,m,r+s),d}fg.exports={derToJose:wE,joseToDer:EE}});var Wt=J(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.LRUCache=void 0;kr.snakeToCamel=pg;kr.originalOrCamelOptions=vE;kr.removeUndefinedValuesInObject=TE;kr.isValidFile=DE;kr.getWellKnownCertificateConfigFileLocation=RE;var AE=require("fs"),SE=require("os"),Yc=require("path"),kE="certificate_config.json",hg="gcloud";function pg(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function vE(t){function e(r){let n=t||{};return n[r]??n[pg(r)]}return{get:e}}var Qc=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()}};kr.LRUCache=Qc;function TE(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function DE(t){try{return(await AE.promises.lstat(t)).isFile()}catch{return!1}}function RE(){let t=process.env.CLOUDSDK_CONFIG||(xE()?Yc.join(process.env.APPDATA||"",hg):Yc.join(process.env.HOME||"",".config",hg));return Yc.join(t,kE)}function xE(){return SE.platform().startsWith("win")}});var mg=J((v1,OE)=>{OE.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 Xc=J(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.USER_AGENT=Gr.PRODUCT_NAME=Gr.pkg=void 0;var gg=mg();Gr.pkg=gg;var yg="google-api-nodejs-client";Gr.PRODUCT_NAME=yg;var FE=`${yg}/${gg.version}`;Gr.USER_AGENT=FE});var bt=J(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AuthClient=Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Gt.DEFAULT_UNIVERSE=void 0;var PE=require("events"),Zc=Ve(),IE=Wt(),NE=jc(),el=Xc();Gt.DEFAULT_UNIVERSE="googleapis.com";Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var tl=class t extends PE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Gt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,IE.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")??Gt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Zc.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],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Zc.Gaxios.mergeHeaders(s,r.headers),n&&Zc.Gaxios.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,headers:s,url:o})}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"),o=r.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,NE.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(`${el.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${el.USER_AGENT}`):e.headers.set("User-Agent",el.USER_AGENT);try{let n=e,o=n[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,o,e.response?.data):t.log.error("[%s] error %j",o,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"]}}}};Gt.AuthClient=tl});var nl=J(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.LoginTicket=void 0;var rl=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=rl});var wn=J(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.OAuth2Client=or.ClientAuthentication=or.CertificateFormat=or.CodeChallengeMethod=void 0;var _g=Ve(),BE=require("querystring"),ME=require("stream"),jE=Kc(),bg=Wt(),ol=Yo(),eo=bt(),LE=nl(),Cg;(function(t){t.Plain="plain",t.S256="S256"})(Cg||(or.CodeChallengeMethod=Cg={}));var vr;(function(t){t.PEM="PEM",t.JWK="JWK"})(vr||(or.CertificateFormat=vr={}));var Qo;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Qo||(or.ClientAuthentication=Qo={}));var sl=class t extends eo.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=vr.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||Qo.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()+"?"+BE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,ol.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:s}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(o=>r(null,o.tokens,o.res),o=>r(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={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===Qo.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Qo.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,bg.removeUndefinedValuesInObject)(o)),headers:n};eo.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}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"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,bg.removeUndefinedValuesInObject)(n))};eo.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof _g.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}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,o=null;try{n=await this.refreshToken(r.refresh_token),o=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 s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),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(eo.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(o=>r(null,o),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=_g.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 o=n.response;if(o){let s=o.status,a=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=o.config.data instanceof ME.Readable,f=s===401||s===403;if(!r&&f&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&f&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),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,ol.hasBrowserCrypto)()?vr.JWK:vr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,o;switch(r){case vr.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case vr.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let f={...t.RETRY_CONFIG,url:o};eo.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),n=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=n?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(a=Number(f)*1e3)}let c={};switch(r){case vr.PEM:c=n.data;break;case vr.JWK:for(let f of n.data.keys)c[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),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};eo.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,o,s){let a=(0,ol.createCrypto)();s||(s=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],f=c[2],d,m;try{d=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(y){throw y instanceof Error&&(y.message=`Can't parse token envelope: ${c[0]}': ${y.message}`),y}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{m=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(y){throw y instanceof Error&&(y.message=`Can't parse token payload '${c[0]}`),y}if(!m)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let C=r[d.kid];if(d.alg==="ES256"&&(f=jE.joseToDer(f,"ES256").toString("base64")),!await a.verify(C,l,f))throw new Error("Invalid token signature: "+e);if(!m.iat)throw new Error("No issue time in token: "+JSON.stringify(m));if(!m.exp)throw new Error("No expiration time in token: "+JSON.stringify(m));let A=Number(m.iat);if(isNaN(A))throw new Error("iat field using invalid format");let b=Number(m.exp);if(isNaN(b))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(b>=g+s)throw new Error("Expiration time too far in future: "+JSON.stringify(m));let p=A-t.CLOCK_SKEW_SECS_,k=b+t.CLOCK_SKEW_SECS_;if(g<p)throw new Error("Token used too early, "+g+" < "+p+": "+JSON.stringify(m));if(g>k)throw new Error("Token used too late, "+g+" > "+k+": "+JSON.stringify(m));if(o&&o.indexOf(m.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+m.iss);if(typeof n<"u"&&n!==null){let y=m.aud,E=!1;if(n.constructor===Array?E=n.indexOf(y)>-1:E=y===n,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new LE.LoginTicket(d,m)}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}};or.OAuth2Client=sl});var al=J(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Compute=void 0;var UE=Ve(),wg=Ko(),$E=wn(),il=class extends $E.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 o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),r=await wg.instance(o)}catch(o){throw o instanceof UE.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}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 o={property:r};n=await wg.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}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))}};Ki.Compute=il});var cl=J(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.IdTokenClient=void 0;var qE=wn(),ul=class extends qE.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}};Yi.IdTokenClient=ul});var ll=J(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.GCPEnv=void 0;to.clear=zE;to.getEnv=HE;var Eg=Ko(),sr;(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"})(sr||(to.GCPEnv=sr={}));var Xo;function zE(){Xo=void 0}async function HE(){return Xo||(Xo=WE(),Xo)}async function WE(){let t=sr.NONE;return GE()?t=sr.APP_ENGINE:JE()?t=sr.CLOUD_FUNCTIONS:await QE()?await YE()?t=sr.KUBERNETES_ENGINE:VE()?t=sr.CLOUD_RUN:KE()?t=sr.CLOUD_RUN_JOBS:t=sr.COMPUTE_ENGINE:t=sr.NONE,t}function GE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function JE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function VE(){return!!process.env.K_CONFIGURATION}function KE(){return!!process.env.CLOUD_RUN_JOB}async function YE(){try{return await Eg.instance("attributes/cluster-name"),!0}catch{return!1}}async function QE(){return Eg.isAvailable()}});var dl=J((I1,Ag)=>{var Qi=Zn().Buffer,XE=require("stream"),ZE=require("util");function Xi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Qi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Qi.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+")")}ZE.inherits(Xi,XE);Xi.prototype.write=function(e){this.buffer=Qi.concat([this.buffer,Qi.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};Ag.exports=Xi});var kg=J((N1,Sg)=>{"use strict";var Zo=require("buffer").Buffer,fl=require("buffer").SlowBuffer;Sg.exports=Zi;function Zi(t,e){if(!Zo.isBuffer(t)||!Zo.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}Zi.install=function(){Zo.prototype.equal=fl.prototype.equal=function(e){return Zi(this,e)}};var eA=Zo.prototype.equal,tA=fl.prototype.equal;Zi.restore=function(){Zo.prototype.equal=eA,fl.prototype.equal=tA}});var gl=J((B1,Ig)=>{var no=Zn().Buffer,Ot=require("crypto"),Tg=Kc(),vg=require("util"),rA=`"%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".`,Qo="secret must be a string or buffer",Zn="key must be a string or a buffer",VE="key must be a string, a buffer or an object",cl=typeof Rt.createPublicKey=="function";cl&&(Zn+=" or a KeyObject",Qo+="or a KeyObject");function wg(t){if(!eo.isBuffer(t)&&typeof t!="string"&&(!cl||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Wt(Zn)}function Eg(t){if(!eo.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Wt(VE)}function KE(t){if(!eo.isBuffer(t)){if(typeof t=="string")return t;if(!cl||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Wt(Qo)}}function ll(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ag(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 Wt(t){var e=[].slice.call(arguments,1),r=bg.format.bind(bg,t).apply(null,e);return new TypeError(r)}function YE(t){return eo.isBuffer(t)||typeof t=="string"}function Xo(t){return YE(t)||(t=JSON.stringify(t)),t}function Sg(t){return function(r,n){KE(n),r=Xo(r);var o=Rt.createHmac("sha"+t,n),s=(o.update(r),o.digest("base64"));return ll(s)}}var ul,QE="timingSafeEqual"in Rt?function(e,r){return e.byteLength!==r.byteLength?!1:Rt.timingSafeEqual(e,r)}:function(e,r){return ul||(ul=_g()),ul(e,r)};function XE(t){return function(r,n,o){var s=Sg(t)(r,o);return QE(eo.from(n),eo.from(s))}}function kg(t){return function(r,n){Eg(n),r=Xo(r);var o=Rt.createSign("RSA-SHA"+t),s=(o.update(r),o.sign(n,"base64"));return ll(s)}}function vg(t){return function(r,n,o){wg(o),r=Xo(r),n=Ag(n);var s=Rt.createVerify("RSA-SHA"+t);return s.update(r),s.verify(o,n,"base64")}}function ZE(t){return function(r,n){Eg(n),r=Xo(r);var o=Rt.createSign("RSA-SHA"+t),s=(o.update(r),o.sign({key:n,padding:Rt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Rt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return ll(s)}}function eA(t){return function(r,n,o){wg(o),r=Xo(r),n=Ag(n);var s=Rt.createVerify("RSA-SHA"+t);return s.update(r),s.verify({key:o,padding:Rt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Rt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function tA(t){var e=kg(t);return function(){var n=e.apply(null,arguments);return n=Cg.derToJose(n,"ES"+t),n}}function rA(t){var e=vg(t);return function(n,o,s){o=Cg.joseToDer(o,"ES"+t).toString("base64");var a=e(n,o,s);return a}}function nA(){return function(){return""}}function oA(){return function(e,r){return r===""}}Tg.exports=function(e){var r={hs:Sg,rs:kg,ps:ZE,es:tA,none:nA},n={hs:XE,rs:vg,ps:eA,es:rA,none:oA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Wt(JE,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:r[s](a),verify:n[s](a)}}});var fl=J((T1,Dg)=>{var sA=require("buffer").Buffer;Dg.exports=function(e){return typeof e=="string"?e:typeof e=="number"||sA.isBuffer(e)?e.toString():JSON.stringify(e)}});var Ig=J((D1,Pg)=>{var iA=Yn().Buffer,Rg=il(),aA=dl(),uA=require("stream"),xg=fl(),hl=require("util");function Og(t,e){return iA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cA(t,e,r){r=r||"utf8";var n=Og(xg(t),"binary"),o=Og(xg(e),r);return hl.format("%s.%s",n,o)}function Fg(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,o=t.encoding,s=aA(e.alg),a=cA(e,r,o),c=s.sign(a,n);return hl.format("%s.%s",a,c)}function Ki(t){var e=t.secret||t.privateKey||t.key,r=new Rg(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Rg(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))}hl.inherits(Ki,uA);Ki.prototype.sign=function(){try{var e=Fg({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")}};Ki.sign=Fg;Pg.exports=Ki});var Hg=J((R1,zg)=>{var Bg=Yn().Buffer,Ng=il(),lA=dl(),dA=require("stream"),jg=fl(),fA=require("util"),hA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function pA(t){return Object.prototype.toString.call(t)==="[object Object]"}function mA(t){if(pA(t))return t;try{return JSON.parse(t)}catch{return}}function Lg(t){var e=t.split(".",1)[0];return mA(Bg.from(e,"base64").toString("binary"))}function gA(t){return t.split(".",2).join(".")}function Mg(t){return t.split(".")[2]}function yA(t,e){e=e||"utf8";var r=t.split(".")[1];return Bg.from(r,"base64").toString(e)}function Ug(t){return hA.test(t)&&!!Lg(t)}function qg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=jg(t);var o=Mg(t),s=gA(t),a=lA(e);return a.verify(s,o,r)}function $g(t,e){if(e=e||{},t=jg(t),!Ug(t))return null;var r=Lg(t);if(!r)return null;var n=yA(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:Mg(t)}}function to(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Ng(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Ng(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))}fA.inherits(to,dA);to.prototype.verify=function(){try{var e=qg(this.signature.buffer,this.algorithm,this.key.buffer),r=$g(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")}};to.decode=$g;to.isValid=Ug;to.verify=qg;zg.exports=to});var pl=J(Gr=>{var Wg=Ig(),Yi=Hg(),_A=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Gr.ALGORITHMS=_A;Gr.sign=Wg.sign;Gr.verify=Yi.verify;Gr.decode=Yi.decode;Gr.isValid=Yi.isValid;Gr.createSign=function(e){return new Wg(e)};Gr.createVerify=function(e){return new Yi(e)}});var iy=J(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.GoogleToken=void 0;var Gg=Qi(require("fs")),bA=Ve(),CA=Qi(pl()),wA=Qi(require("path")),EA=require("util");function Qi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Qi=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,h={__proto__:null,default:s};if(s===null||vr(s)!="object"&&typeof s!="function")return h;if(c=a?n:r){if(c.has(s))return c.get(s);c.set(s,h)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?c(h,d,l):h[d]=s[d]);return h})(t,e)}function vr(t){"@babel/helpers - typeof";return vr=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},vr(t)}function AA(t,e){ty(t,e),e.add(t)}function SA(t,e,r){ty(t,e),e.set(t,r)}function ty(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Jg(t,e,r){return t.set(Gt(t,e),r),r}function Vg(t,e){return t.get(Gt(t,e))}function Gt(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 Kg(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,oy(n.key),n)}}function ry(t,e,r){return e&&Kg(t.prototype,e),r&&Kg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function ny(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function kA(t,e,r){return e=rs(e),vA(t,Cl()?Reflect.construct(e,r||[],rs(t).constructor):e.apply(t,r))}function vA(t,e){if(e&&(vr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return TA(t)}function TA(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function DA(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&&ts(t,e)}function ml(t){var e=typeof Map=="function"?new Map:void 0;return ml=function(n){if(n===null||!xA(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,o)}function o(){return RA(n,arguments,rs(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),ts(o,n)},ml(t)}function RA(t,e,r){if(Cl())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var o=new(t.bind.apply(t,n));return r&&ts(o,r.prototype),o}function Cl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Cl=function(){return!!t})()}function xA(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function ts(t,e){return ts=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},ts(t,e)}function rs(t){return rs=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},rs(t)}function yt(t,e,r){return(e=oy(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function oy(t){var e=OA(t,"string");return vr(e)=="symbol"?e:e+""}function OA(t,e){if(vr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(vr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function bt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function s(T,S,_,g){var m=S&&S.prototype instanceof c?S:c,k=Object.create(m.prototype);return _t(k,"_invoke",(function(y,E,D){var F,$,V,B=0,Y=D||[],te=!1,Z={p:0,n:0,v:t,a:ue,f:ue.bind(t,4),d:function(Ee,se){return F=Ee,$=0,V=t,Z.n=se,a}};function ue(he,Ee){for($=he,V=Ee,e=0;!te&&B&&!se&&e<Y.length;e++){var se,pe=Y[e],G=Z.p,K=pe[2];he>3?(se=K===Ee)&&(V=pe[($=pe[4])?5:($=3,3)],pe[4]=pe[5]=t):pe[0]<=G&&((se=he<2&&G<pe[1])?($=0,Z.v=Ee,Z.n=pe[1]):G<K&&(se=he<3||pe[0]>Ee||Ee>K)&&(pe[4]=he,pe[5]=Ee,Z.n=K,$=0))}if(se||he>1)return a;throw te=!0,Ee}return function(he,Ee,se){if(B>1)throw TypeError("Generator is already running");for(te&&Ee===1&&ue(Ee,se),$=Ee,V=se;(e=$<2?t:V)||!te;){F||($?$<3?($>1&&(Z.n=-1),ue($,V)):Z.n=V:Z.v=V);try{if(B=2,F){if($||(he="next"),e=F[he]){if(!(e=e.call(F,V)))throw TypeError("iterator result is not an object");if(!e.done)return e;V=e.value,$<2&&($=0)}else $===1&&(e=F.return)&&e.call(F),$<2&&(V=TypeError("The iterator does not provide a '"+he+"' method"),$=1);F=t}else if((e=(te=Z.n<0)?V:y.call(E,Z))!==a)break}catch(pe){F=t,$=1,V=pe}finally{B=1}}return{value:e,done:te}}})(T,_,g),!0),k}var a={};function c(){}function l(){}function h(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(_t(e={},n,function(){return this}),e),p=h.prototype=c.prototype=Object.create(d);function w(T){return Object.setPrototypeOf?Object.setPrototypeOf(T,h):(T.__proto__=h,_t(T,o,"GeneratorFunction")),T.prototype=Object.create(p),T}return l.prototype=h,_t(p,"constructor",h),_t(h,"constructor",l),l.displayName="GeneratorFunction",_t(h,o,"GeneratorFunction"),_t(p),_t(p,o,"Generator"),_t(p,n,function(){return this}),_t(p,"toString",function(){return"[object Generator]"}),(bt=function(){return{w:s,m:w}})()}function _t(t,e,r,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}_t=function(a,c,l,h){if(c)o?o(a,c,{value:l,enumerable:!h,configurable:!h,writable:!h}):a[c]=l;else{var d=function(w,T){_t(a,w,function(S){return this._invoke(w,T,S)})};d("next",0),d("throw",1),d("return",2)}},_t(t,e,r,n)}function Yg(t,e,r,n,o,s,a){try{var c=t[s](a),l=c.value}catch(h){return void r(h)}c.done?e(l):Promise.resolve(l).then(n,o)}function ro(t){return function(){var e=this,r=arguments;return new Promise(function(n,o){var s=t.apply(e,r);function a(l){Yg(s,n,o,a,c,"next",l)}function c(l){Yg(s,n,o,a,c,"throw",l)}a(void 0)})}}var Qg=Gg.readFile?(0,EA.promisify)(Gg.readFile):ro(bt().m(function t(){return bt().w(function(e){for(;;)switch(e.n){case 0:throw new es("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Xg="https://oauth2.googleapis.com/token",FA="https://oauth2.googleapis.com/revoke?token=",es=(function(t){function e(r,n){var o;return ny(this,e),o=kA(this,e,[r]),yt(o,"code",void 0),o.code=n,o}return DA(e,t),ry(e)})(ml(Error)),Zo=new WeakMap,sr=new WeakSet,O1=Xi.GoogleToken=(function(){function t(e){ny(this,t),AA(this,sr),yt(this,"expiresAt",void 0),yt(this,"key",void 0),yt(this,"keyFile",void 0),yt(this,"iss",void 0),yt(this,"sub",void 0),yt(this,"scope",void 0),yt(this,"rawToken",void 0),yt(this,"tokenExpires",void 0),yt(this,"email",void 0),yt(this,"additionalClaims",void 0),yt(this,"eagerRefreshThresholdMillis",void 0),yt(this,"transporter",{request:function(n){return(0,bA.request)(n)}}),SA(this,Zo,void 0),Gt(sr,this,sy).call(this,e)}return ry(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(),o=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(vr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var o=r;Gt(sr,this,Zg).call(this,n).then(function(s){return o(null,s)},r);return}return Gt(sr,this,Zg).call(this,n)}},{key:"getCredentials",value:(function(){var e=ro(bt().m(function n(o){var s,a,c,l,h,d,p;return bt().w(function(w){for(;;)switch(w.n){case 0:s=wA.extname(o),p=s,w.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return w.n=2,Qg(o,"utf8");case 2:if(a=w.v,c=JSON.parse(a),l=c.private_key,h=c.client_email,!(!l||!h)){w.n=3;break}throw new es("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return w.a(2,{privateKey:l,clientEmail:h});case 4:return w.n=5,Qg(o,"utf8");case 5:return d=w.v,w.a(2,{privateKey:d});case 6:throw new es("*.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 es("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return w.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){Gt(sr,this,ey).call(this).then(function(){return r()},r);return}return Gt(sr,this,ey).call(this)}}])})();function Zg(t){return gl.apply(this,arguments)}function gl(){return gl=ro(bt().m(function t(e){return bt().w(function(r){for(;;)switch(r.n){case 0:if(!(Vg(Zo,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,Vg(Zo,this));case 1:return r.p=1,r.n=2,Jg(Zo,this,Gt(sr,this,PA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,Jg(Zo,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),gl.apply(this,arguments)}function PA(t){return yl.apply(this,arguments)}function yl(){return yl=ro(bt().m(function t(e){var r;return bt().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||Gt(sr,this,IA).call(this);case 4:return n.a(2,Gt(sr,this,NA).call(this))}},t,this)})),yl.apply(this,arguments)}function IA(){if(!this.iss)throw new es("email is required.","MISSING_CREDENTIALS")}function ey(){return _l.apply(this,arguments)}function _l(){return _l=ro(bt().m(function t(){var e;return bt().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=FA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:Gt(sr,this,sy).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)})),_l.apply(this,arguments)}function sy(){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,vr(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 bl.apply(this,arguments)}function bl(){return bl=ro(bt().m(function t(){var e,r,n,o,s,a,c,l,h,d;return bt().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:Xg,exp:e+3600,iat:e,sub:this.sub},r),o=CA.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Xg,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=p.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,d=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(a=d.response)!==null&&a!==void 0&&a.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(h=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(h)),d;case 4:return p.a(2)}},t,this,[[1,3]])})),bl.apply(this,arguments)}});var El=J(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.JWTAccess=void 0;var BA=pl(),jA=zt(),ay={alg:"RS256",typ:"JWT"},wl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new jA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,o){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=o??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 o=this.getCachedKey(e,n),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.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 d=this.keyId?{...ay,kid:this.keyId}:ay,p=Object.assign(h,r),w=BA.sign({header:d,payload:p,secret:this.key}),T=new Headers({authorization:`Bearer ${w}`});return this.cache.set(o,{expiration:l*1e3,headers:T}),T}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 o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",n).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(s)}})})}};Zi.JWTAccess=wl});var Sl=J(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.JWT=void 0;var uy=iy(),LA=El(),MA=bn(),ea=gt(),Al=class t extends MA.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!==ea.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ea.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ea.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 LA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==ea.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new uy.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 uy.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 o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(s)}})})}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.")}};ta.JWT=Al});var vl=J(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.UserRefreshClient=no.USER_REFRESH_ACCOUNT_TYPE=void 0;var UA=bn(),qA=gt();no.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var kl=class t extends UA.OAuth2Client{_refreshToken;constructor(e,r,n,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.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 qA.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 o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),r()}catch(s){return n(s)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};no.UserRefreshClient=kl});var Dl=J(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.Impersonated=oo.IMPERSONATED_ACCOUNT_TYPE=void 0;var cy=bn(),$A=Ve(),zA=zt();oo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Tl=class t extends cy.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 cy.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,zA.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`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,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"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof $A.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}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};oo.Impersonated=Tl});var xl=J(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.OAuthClientAuthHandler=void 0;ns.getErrorFromOAuthErrorResponse=GA;var so=Ve(),HA=Jo(),WA=["PUT","POST","PATCH"],Rl=class{#e=(0,HA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new so.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new so.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=so.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=so.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=so.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${n}:${o}`);so.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!WA.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.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(`${o} 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"]}}}};ns.OAuthClientAuthHandler=Rl;function GA(t,e){let r=t.error,n=t.error_description,o=t.error_uri,s=`Error code ${r}`;typeof n<"u"&&(s+=`: ${n}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var na=J(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.StsCredentials=void 0;var JA=Ve(),VA=gt(),ly=xl(),KA=zt(),Ol=class t extends ly.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 o={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)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,KA.removeUndefinedValuesInObject)(o))};VA.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),c=a.data;return c.res=a,c}catch(a){throw a instanceof JA.GaxiosError&&a.response?(0,ly.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};ra.StsCredentials=Ol});var Jr=J(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.BaseExternalAccountClient=xt.CLOUD_RESOURCE_MANAGER=xt.EXTERNAL_ACCOUNT_TYPE=xt.EXPIRATION_TIME_OFFSET=void 0;var YA=Ve(),QA=require("stream"),Fl=gt(),XA=na(),dy=zt(),ZA=Jc(),eS="urn:ietf:params:oauth:grant-type:token-exchange",tS="urn:ietf:params:oauth:token-type:access_token",Pl="https://www.googleapis.com/auth/cloud-platform",rS=3600;xt.EXPIRATION_TIME_OFFSET=300*1e3;xt.EXTERNAL_ACCOUNT_TYPE="external_account";xt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var nS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",oS="https://sts.{universeDomain}/v1/token",Il=class t extends Fl.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,dy.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==xt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${xt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=r.get("client_id"),s=r.get("client_secret");this.tokenUrl=r.get("token_url")??oS.replace("{universeDomain}",this.universeDomain);let a=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"),d=(0,dy.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new XA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[Pl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(nS);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=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=rS),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}`};Fl.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=YA.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof QA.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}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:eS,audience:this.audience,requestedTokenType:tS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Pl]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(r,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.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"}};Fl.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.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||[Pl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${ZA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};xt.BaseExternalAccountClient=Il});var fy=J(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.FileSubjectTokenSupplier=void 0;var Bl=require("util"),jl=require("fs"),sS=(0,Bl.promisify)(jl.readFile??(()=>{})),iS=(0,Bl.promisify)(jl.realpath??(()=>{})),aS=(0,Bl.promisify)(jl.lstat??(()=>{})),Nl=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 iS(e),!(await aS(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r,n=await sS(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}};oa.FileSubjectTokenSupplier=Nl});var hy=J(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.UrlSubjectTokenSupplier=void 0;var uS=gt(),Ll=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};uS.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}};sa.UrlSubjectTokenSupplier=Ll});var py=J(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.CertificateSubjectTokenSupplier=Ct.InvalidConfigurationError=Ct.CertificateSourceUnavailableError=Ct.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var ia=zt(),aa=require("fs"),ua=require("crypto"),cS=require("https");Ct.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var ir=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Ct.CertificateSourceUnavailableError=ir;var Ot=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Ct.InvalidConfigurationError=Ot;var Ml=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ot("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ot("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ot("Cannot create mTLS Agent with missing certificate or key");return new cS.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,ia.isValidFile)(e))return e;throw new ir(`Provided certificate config path is invalid: ${e}`)}let r=process.env[Ct.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,ia.isValidFile)(r))return r;throw new ir(`Path from environment variable "${Ct.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,ia.getWellKnownCertificateConfigFileLocation)();if(await(0,ia.isValidFile)(n))return n;throw new ir(`Could not find certificate configuration file. Searched override path, the "${Ct.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await aa.promises.readFile(e,"utf8")}catch{throw new ir(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),o=n?.cert_configs?.workload?.cert_path,s=n?.cert_configs?.workload?.key_path;if(!o||!s)throw new Ot(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(n){throw n instanceof Ot?n:new Ot(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,o;try{n=await aa.promises.readFile(e),new ua.X509Certificate(n)}catch(s){let a=s instanceof Error?s.message:String(s);throw new ir(`Failed to read certificate file at ${e}: ${a}`)}try{o=await aa.promises.readFile(r),(0,ua.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new ir(`Failed to read private key file at ${r}: ${a}`)}return{cert:n,key:o}}async#n(e){let r=new ua.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let s=((await aa.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new ua.X509Certificate(l)}catch(d){let p=d instanceof Error?d.message:String(d);throw new Ot(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>r.raw.equals(l.raw)),c;if(a===-1)c=[r,...s];else if(a===0)c=s;else throw new Ot(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof Ot)throw n;let o=n instanceof Error?n.message:String(n);throw new ir(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Ct.CertificateSubjectTokenSupplier=Ml});var $l=J(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.IdentityPoolClient=void 0;var lS=Jr(),Ul=zt(),dS=fy(),fS=hy(),my=py(),hS=na(),gy=Ve(),ql=class t extends lS.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,Ul.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,Ul.originalOrCamelOptions)(n),a=(0,Ul.originalOrCamelOptions)(s.get("format")),c=a.get("type")||"text",l=a.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=s.get("file"),d=s.get("url"),p=s.get("certificate"),w=s.get("headers");if(h&&d||d&&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 dS.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new fS.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:w,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let T=new my.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=T}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 my.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new hS.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new gy.Gaxios({agent:r})}),this.transporter=new gy.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};ca.IdentityPoolClient=ql});var Hl=J(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.AwsRequestSigner=void 0;var la=Ve(),_y=Jo(),yy="AWS4-HMAC-SHA256",pS="aws4_request",zl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,_y.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,o=e.method||"GET",s=e.body||r,a=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let h=await gS({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:a}),d=la.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},a||{});c.token&&la.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let p={url:n,method:o,headers:d};return s!==void 0&&(p.body=s),p}};da.AwsRequestSigner=zl;async function os(t,e,r){return await t.signWithHmacSha256(e,r)}async function mS(t,e,r,n,o){let s=await os(t,`AWS4${e}`,r),a=await os(t,s,n),c=await os(t,a,o);return await os(t,c,"aws4_request")}async function gS(t){let e=la.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=la.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",h=[...c.keys()].sort();h.forEach(k=>{l+=`${k}:${c.get(k)}
53
- `});let d=h.join(";"),p=await t.crypto.sha256DigestHex(r),w=`${t.method.toUpperCase()}
52
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,es="secret must be a string or buffer",ro="key must be a string or a buffer",nA="key must be a string, a buffer or an object",pl=typeof Ot.createPublicKey=="function";pl&&(ro+=" or a KeyObject",es+="or a KeyObject");function Dg(t){if(!no.isBuffer(t)&&typeof t!="string"&&(!pl||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Jt(ro)}function Rg(t){if(!no.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Jt(nA)}function oA(t){if(!no.isBuffer(t)){if(typeof t=="string")return t;if(!pl||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Jt(es)}}function ml(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function xg(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 Jt(t){var e=[].slice.call(arguments,1),r=vg.format.bind(vg,t).apply(null,e);return new TypeError(r)}function sA(t){return no.isBuffer(t)||typeof t=="string"}function ts(t){return sA(t)||(t=JSON.stringify(t)),t}function Og(t){return function(r,n){oA(n),r=ts(r);var o=Ot.createHmac("sha"+t,n),s=(o.update(r),o.digest("base64"));return ml(s)}}var hl,iA="timingSafeEqual"in Ot?function(e,r){return e.byteLength!==r.byteLength?!1:Ot.timingSafeEqual(e,r)}:function(e,r){return hl||(hl=kg()),hl(e,r)};function aA(t){return function(r,n,o){var s=Og(t)(r,o);return iA(no.from(n),no.from(s))}}function Fg(t){return function(r,n){Rg(n),r=ts(r);var o=Ot.createSign("RSA-SHA"+t),s=(o.update(r),o.sign(n,"base64"));return ml(s)}}function Pg(t){return function(r,n,o){Dg(o),r=ts(r),n=xg(n);var s=Ot.createVerify("RSA-SHA"+t);return s.update(r),s.verify(o,n,"base64")}}function uA(t){return function(r,n){Rg(n),r=ts(r);var o=Ot.createSign("RSA-SHA"+t),s=(o.update(r),o.sign({key:n,padding:Ot.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ot.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return ml(s)}}function cA(t){return function(r,n,o){Dg(o),r=ts(r),n=xg(n);var s=Ot.createVerify("RSA-SHA"+t);return s.update(r),s.verify({key:o,padding:Ot.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ot.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function lA(t){var e=Fg(t);return function(){var n=e.apply(null,arguments);return n=Tg.derToJose(n,"ES"+t),n}}function dA(t){var e=Pg(t);return function(n,o,s){o=Tg.joseToDer(o,"ES"+t).toString("base64");var a=e(n,o,s);return a}}function fA(){return function(){return""}}function hA(){return function(e,r){return r===""}}Ig.exports=function(e){var r={hs:Og,rs:Fg,ps:uA,es:lA,none:fA},n={hs:aA,rs:Pg,ps:cA,es:dA,none:hA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Jt(rA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:r[s](a),verify:n[s](a)}}});var yl=J((M1,Ng)=>{var pA=require("buffer").Buffer;Ng.exports=function(e){return typeof e=="string"?e:typeof e=="number"||pA.isBuffer(e)?e.toString():JSON.stringify(e)}});var $g=J((j1,Ug)=>{var mA=Zn().Buffer,Bg=dl(),gA=gl(),yA=require("stream"),Mg=yl(),_l=require("util");function jg(t,e){return mA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function _A(t,e,r){r=r||"utf8";var n=jg(Mg(t),"binary"),o=jg(Mg(e),r);return _l.format("%s.%s",n,o)}function Lg(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,o=t.encoding,s=gA(e.alg),a=_A(e,r,o),c=s.sign(a,n);return _l.format("%s.%s",a,c)}function ea(t){var e=t.secret||t.privateKey||t.key,r=new Bg(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Bg(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))}_l.inherits(ea,yA);ea.prototype.sign=function(){try{var e=Lg({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")}};ea.sign=Lg;Ug.exports=ea});var Qg=J((L1,Yg)=>{var zg=Zn().Buffer,qg=dl(),bA=gl(),CA=require("stream"),Hg=yl(),wA=require("util"),EA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function AA(t){return Object.prototype.toString.call(t)==="[object Object]"}function SA(t){if(AA(t))return t;try{return JSON.parse(t)}catch{return}}function Wg(t){var e=t.split(".",1)[0];return SA(zg.from(e,"base64").toString("binary"))}function kA(t){return t.split(".",2).join(".")}function Gg(t){return t.split(".")[2]}function vA(t,e){e=e||"utf8";var r=t.split(".")[1];return zg.from(r,"base64").toString(e)}function Jg(t){return EA.test(t)&&!!Wg(t)}function Vg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=Hg(t);var o=Gg(t),s=kA(t),a=bA(e);return a.verify(s,o,r)}function Kg(t,e){if(e=e||{},t=Hg(t),!Jg(t))return null;var r=Wg(t);if(!r)return null;var n=vA(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:Gg(t)}}function oo(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new qg(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new qg(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))}wA.inherits(oo,CA);oo.prototype.verify=function(){try{var e=Vg(this.signature.buffer,this.algorithm,this.key.buffer),r=Kg(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")}};oo.decode=Kg;oo.isValid=Jg;oo.verify=Vg;Yg.exports=oo});var bl=J(Jr=>{var Xg=$g(),ta=Qg(),TA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Jr.ALGORITHMS=TA;Jr.sign=Xg.sign;Jr.verify=ta.verify;Jr.decode=ta.decode;Jr.isValid=ta.isValid;Jr.createSign=function(e){return new Xg(e)};Jr.createVerify=function(e){return new ta(e)}});var hy=J(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.GoogleToken=void 0;var Zg=ra(require("fs")),DA=Ve(),RA=ra(bl()),xA=ra(require("path")),OA=require("util");function ra(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(ra=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,f={__proto__:null,default:s};if(s===null||Tr(s)!="object"&&typeof s!="function")return f;if(c=a?n:r){if(c.has(s))return c.get(s);c.set(s,f)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?c(f,d,l):f[d]=s[d]);return f})(t,e)}function Tr(t){"@babel/helpers - typeof";return Tr=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},Tr(t)}function FA(t,e){uy(t,e),e.add(t)}function PA(t,e,r){uy(t,e),e.set(t,r)}function uy(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function ey(t,e,r){return t.set(Vt(t,e),r),r}function ty(t,e){return t.get(Vt(t,e))}function Vt(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 ry(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,dy(n.key),n)}}function cy(t,e,r){return e&&ry(t.prototype,e),r&&ry(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function ly(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function IA(t,e,r){return e=ss(e),NA(t,kl()?Reflect.construct(e,r||[],ss(t).constructor):e.apply(t,r))}function NA(t,e){if(e&&(Tr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return BA(t)}function BA(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function MA(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&&os(t,e)}function Cl(t){var e=typeof Map=="function"?new Map:void 0;return Cl=function(n){if(n===null||!LA(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,o)}function o(){return jA(n,arguments,ss(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),os(o,n)},Cl(t)}function jA(t,e,r){if(kl())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var o=new(t.bind.apply(t,n));return r&&os(o,r.prototype),o}function kl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(kl=function(){return!!t})()}function LA(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function os(t,e){return os=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},os(t,e)}function ss(t){return ss=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ss(t)}function Ct(t,e,r){return(e=dy(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function dy(t){var e=UA(t,"string");return Tr(e)=="symbol"?e:e+""}function UA(t,e){if(Tr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Tr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Et(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function s(v,A,b,g){var p=A&&A.prototype instanceof c?A:c,k=Object.create(p.prototype);return wt(k,"_invoke",(function(y,E,D){var F,q,V,B=0,Y=D||[],te=!1,Z={p:0,n:0,v:t,a:ue,f:ue.bind(t,4),d:function(Ee,se){return F=Ee,q=0,V=t,Z.n=se,a}};function ue(he,Ee){for(q=he,V=Ee,e=0;!te&&B&&!se&&e<Y.length;e++){var se,pe=Y[e],G=Z.p,K=pe[2];he>3?(se=K===Ee)&&(V=pe[(q=pe[4])?5:(q=3,3)],pe[4]=pe[5]=t):pe[0]<=G&&((se=he<2&&G<pe[1])?(q=0,Z.v=Ee,Z.n=pe[1]):G<K&&(se=he<3||pe[0]>Ee||Ee>K)&&(pe[4]=he,pe[5]=Ee,Z.n=K,q=0))}if(se||he>1)return a;throw te=!0,Ee}return function(he,Ee,se){if(B>1)throw TypeError("Generator is already running");for(te&&Ee===1&&ue(Ee,se),q=Ee,V=se;(e=q<2?t:V)||!te;){F||(q?q<3?(q>1&&(Z.n=-1),ue(q,V)):Z.n=V:Z.v=V);try{if(B=2,F){if(q||(he="next"),e=F[he]){if(!(e=e.call(F,V)))throw TypeError("iterator result is not an object");if(!e.done)return e;V=e.value,q<2&&(q=0)}else q===1&&(e=F.return)&&e.call(F),q<2&&(V=TypeError("The iterator does not provide a '"+he+"' method"),q=1);F=t}else if((e=(te=Z.n<0)?V:y.call(E,Z))!==a)break}catch(pe){F=t,q=1,V=pe}finally{B=1}}return{value:e,done:te}}})(v,b,g),!0),k}var a={};function c(){}function l(){}function f(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(wt(e={},n,function(){return this}),e),m=f.prototype=c.prototype=Object.create(d);function C(v){return Object.setPrototypeOf?Object.setPrototypeOf(v,f):(v.__proto__=f,wt(v,o,"GeneratorFunction")),v.prototype=Object.create(m),v}return l.prototype=f,wt(m,"constructor",f),wt(f,"constructor",l),l.displayName="GeneratorFunction",wt(f,o,"GeneratorFunction"),wt(m),wt(m,o,"Generator"),wt(m,n,function(){return this}),wt(m,"toString",function(){return"[object Generator]"}),(Et=function(){return{w:s,m:C}})()}function wt(t,e,r,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}wt=function(a,c,l,f){if(c)o?o(a,c,{value:l,enumerable:!f,configurable:!f,writable:!f}):a[c]=l;else{var d=function(C,v){wt(a,C,function(A){return this._invoke(C,v,A)})};d("next",0),d("throw",1),d("return",2)}},wt(t,e,r,n)}function ny(t,e,r,n,o,s,a){try{var c=t[s](a),l=c.value}catch(f){return void r(f)}c.done?e(l):Promise.resolve(l).then(n,o)}function so(t){return function(){var e=this,r=arguments;return new Promise(function(n,o){var s=t.apply(e,r);function a(l){ny(s,n,o,a,c,"next",l)}function c(l){ny(s,n,o,a,c,"throw",l)}a(void 0)})}}var oy=Zg.readFile?(0,OA.promisify)(Zg.readFile):so(Et().m(function t(){return Et().w(function(e){for(;;)switch(e.n){case 0:throw new ns("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),sy="https://oauth2.googleapis.com/token",$A="https://oauth2.googleapis.com/revoke?token=",ns=(function(t){function e(r,n){var o;return ly(this,e),o=IA(this,e,[r]),Ct(o,"code",void 0),o.code=n,o}return MA(e,t),cy(e)})(Cl(Error)),rs=new WeakMap,ir=new WeakSet,$1=na.GoogleToken=(function(){function t(e){ly(this,t),FA(this,ir),Ct(this,"expiresAt",void 0),Ct(this,"key",void 0),Ct(this,"keyFile",void 0),Ct(this,"iss",void 0),Ct(this,"sub",void 0),Ct(this,"scope",void 0),Ct(this,"rawToken",void 0),Ct(this,"tokenExpires",void 0),Ct(this,"email",void 0),Ct(this,"additionalClaims",void 0),Ct(this,"eagerRefreshThresholdMillis",void 0),Ct(this,"transporter",{request:function(n){return(0,DA.request)(n)}}),PA(this,rs,void 0),Vt(ir,this,fy).call(this,e)}return cy(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(),o=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Tr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var o=r;Vt(ir,this,iy).call(this,n).then(function(s){return o(null,s)},r);return}return Vt(ir,this,iy).call(this,n)}},{key:"getCredentials",value:(function(){var e=so(Et().m(function n(o){var s,a,c,l,f,d,m;return Et().w(function(C){for(;;)switch(C.n){case 0:s=xA.extname(o),m=s,C.n=m===".json"?1:m===".der"||m===".crt"||m===".pem"?4:m===".p12"||m===".pfx"?6:7;break;case 1:return C.n=2,oy(o,"utf8");case 2:if(a=C.v,c=JSON.parse(a),l=c.private_key,f=c.client_email,!(!l||!f)){C.n=3;break}throw new ns("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return C.a(2,{privateKey:l,clientEmail:f});case 4:return C.n=5,oy(o,"utf8");case 5:return d=C.v,C.a(2,{privateKey:d});case 6:throw new ns("*.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 ns("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return C.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){Vt(ir,this,ay).call(this).then(function(){return r()},r);return}return Vt(ir,this,ay).call(this)}}])})();function iy(t){return wl.apply(this,arguments)}function wl(){return wl=so(Et().m(function t(e){return Et().w(function(r){for(;;)switch(r.n){case 0:if(!(ty(rs,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,ty(rs,this));case 1:return r.p=1,r.n=2,ey(rs,this,Vt(ir,this,qA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,ey(rs,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),wl.apply(this,arguments)}function qA(t){return El.apply(this,arguments)}function El(){return El=so(Et().m(function t(e){var r;return Et().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||Vt(ir,this,zA).call(this);case 4:return n.a(2,Vt(ir,this,HA).call(this))}},t,this)})),El.apply(this,arguments)}function zA(){if(!this.iss)throw new ns("email is required.","MISSING_CREDENTIALS")}function ay(){return Al.apply(this,arguments)}function Al(){return Al=so(Et().m(function t(){var e;return Et().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=$A+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:Vt(ir,this,fy).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)})),Al.apply(this,arguments)}function fy(){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,Tr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function HA(){return Sl.apply(this,arguments)}function Sl(){return Sl=so(Et().m(function t(){var e,r,n,o,s,a,c,l,f,d;return Et().w(function(m){for(;;)switch(m.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:sy,exp:e+3600,iat:e,sub:this.sub},r),o=RA.sign({header:{alg:"RS256"},payload:n,secret:this.key}),m.p=1,m.n=2,this.transporter.request({method:"POST",url:sy,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=m.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.data.expires_in)*1e3,m.a(2,this.rawToken);case 3:throw m.p=3,d=m.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(a=d.response)!==null&&a!==void 0&&a.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(f=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(f)),d;case 4:return m.a(2)}},t,this,[[1,3]])})),Sl.apply(this,arguments)}});var Tl=J(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.JWTAccess=void 0;var WA=bl(),GA=Wt(),py={alg:"RS256",typ:"JWT"},vl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new GA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,o){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=o??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 o=this.getCachedKey(e,n),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),f;if(Array.isArray(n)&&(n=n.join(" ")),n?f={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:f={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let A in f)if(r[A])throw new Error(`The '${A}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...py,kid:this.keyId}:py,m=Object.assign(f,r),C=WA.sign({header:d,payload:m,secret:this.key}),v=new Headers({authorization:`Bearer ${C}`});return this.cache.set(o,{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 o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",n).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(s)}})})}};oa.JWTAccess=vl});var Rl=J(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.JWT=void 0;var my=hy(),JA=Tl(),VA=wn(),sa=bt(),Dl=class t extends VA.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!==sa.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==sa.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${sa.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 JA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==sa.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new my.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 my.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 o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(s)}})})}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.")}};ia.JWT=Dl});var Ol=J(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.UserRefreshClient=io.USER_REFRESH_ACCOUNT_TYPE=void 0;var KA=wn(),YA=bt();io.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var xl=class t extends KA.OAuth2Client{_refreshToken;constructor(e,r,n,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.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 YA.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 o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),r()}catch(s){return n(s)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};io.UserRefreshClient=xl});var Pl=J(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.Impersonated=ao.IMPERSONATED_ACCOUNT_TYPE=void 0;var gy=wn(),QA=Ve(),XA=Wt();ao.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Fl=class t extends gy.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 gy.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,XA.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`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,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"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof QA.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}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};ao.Impersonated=Fl});var Nl=J(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.OAuthClientAuthHandler=void 0;is.getErrorFromOAuthErrorResponse=tS;var uo=Ve(),ZA=Yo(),eS=["PUT","POST","PATCH"],Il=class{#e=(0,ZA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new uo.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new uo.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=uo.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=uo.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=uo.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${n}:${o}`);uo.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!eS.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.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(`${o} 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"]}}}};is.OAuthClientAuthHandler=Il;function tS(t,e){let r=t.error,n=t.error_description,o=t.error_uri,s=`Error code ${r}`;typeof n<"u"&&(s+=`: ${n}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var ua=J(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.StsCredentials=void 0;var rS=Ve(),nS=bt(),yy=Nl(),oS=Wt(),Bl=class t extends yy.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 o={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)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,oS.removeUndefinedValuesInObject)(o))};nS.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),c=a.data;return c.res=a,c}catch(a){throw a instanceof rS.GaxiosError&&a.response?(0,yy.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};aa.StsCredentials=Bl});var Vr=J(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.BaseExternalAccountClient=Ft.CLOUD_RESOURCE_MANAGER=Ft.EXTERNAL_ACCOUNT_TYPE=Ft.EXPIRATION_TIME_OFFSET=void 0;var sS=Ve(),iS=require("stream"),Ml=bt(),aS=ua(),_y=Wt(),uS=Xc(),cS="urn:ietf:params:oauth:grant-type:token-exchange",lS="urn:ietf:params:oauth:token-type:access_token",jl="https://www.googleapis.com/auth/cloud-platform",dS=3600;Ft.EXPIRATION_TIME_OFFSET=300*1e3;Ft.EXTERNAL_ACCOUNT_TYPE="external_account";Ft.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var fS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",hS="https://sts.{universeDomain}/v1/token",Ll=class t extends Ml.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,_y.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Ft.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Ft.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=r.get("client_id"),s=r.get("client_secret");this.tokenUrl=r.get("token_url")??hS.replace("{universeDomain}",this.universeDomain);let a=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),f=r.get("service_account_impersonation"),d=(0,_y.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new aS.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[jl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let m=new RegExp(fS);if(this.workforcePoolUserProject&&!this.audience.match(m))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=dS),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}`};Ml.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=sS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof iS.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}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:cS,audience:this.audience,requestedTokenType:lS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[jl]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(r,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.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"}};Ml.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.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||[jl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${uS.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Ft.BaseExternalAccountClient=Ll});var by=J(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.FileSubjectTokenSupplier=void 0;var $l=require("util"),ql=require("fs"),pS=(0,$l.promisify)(ql.readFile??(()=>{})),mS=(0,$l.promisify)(ql.realpath??(()=>{})),gS=(0,$l.promisify)(ql.lstat??(()=>{})),Ul=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 mS(e),!(await gS(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r,n=await pS(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}};ca.FileSubjectTokenSupplier=Ul});var Cy=J(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.UrlSubjectTokenSupplier=void 0;var yS=bt(),zl=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};yS.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}};la.UrlSubjectTokenSupplier=zl});var wy=J(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.CertificateSubjectTokenSupplier=At.InvalidConfigurationError=At.CertificateSourceUnavailableError=At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var da=Wt(),fa=require("fs"),ha=require("crypto"),_S=require("https");At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var ar=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};At.CertificateSourceUnavailableError=ar;var Pt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};At.InvalidConfigurationError=Pt;var Hl=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Pt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Pt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Pt("Cannot create mTLS Agent with missing certificate or key");return new _S.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,da.isValidFile)(e))return e;throw new ar(`Provided certificate config path is invalid: ${e}`)}let r=process.env[At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,da.isValidFile)(r))return r;throw new ar(`Path from environment variable "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,da.getWellKnownCertificateConfigFileLocation)();if(await(0,da.isValidFile)(n))return n;throw new ar(`Could not find certificate configuration file. Searched override path, the "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await fa.promises.readFile(e,"utf8")}catch{throw new ar(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),o=n?.cert_configs?.workload?.cert_path,s=n?.cert_configs?.workload?.key_path;if(!o||!s)throw new Pt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(n){throw n instanceof Pt?n:new Pt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,o;try{n=await fa.promises.readFile(e),new ha.X509Certificate(n)}catch(s){let a=s instanceof Error?s.message:String(s);throw new ar(`Failed to read certificate file at ${e}: ${a}`)}try{o=await fa.promises.readFile(r),(0,ha.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new ar(`Failed to read private key file at ${r}: ${a}`)}return{cert:n,key:o}}async#n(e){let r=new ha.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let s=((await fa.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,f)=>{try{return new ha.X509Certificate(l)}catch(d){let m=d instanceof Error?d.message:String(d);throw new Pt(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${m}`)}}),a=s.findIndex(l=>r.raw.equals(l.raw)),c;if(a===-1)c=[r,...s];else if(a===0)c=s;else throw new Pt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof Pt)throw n;let o=n instanceof Error?n.message:String(n);throw new ar(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};At.CertificateSubjectTokenSupplier=Hl});var Jl=J(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.IdentityPoolClient=void 0;var bS=Vr(),Wl=Wt(),CS=by(),wS=Cy(),Ey=wy(),ES=ua(),Ay=Ve(),Gl=class t extends bS.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,Wl.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,Wl.originalOrCamelOptions)(n),a=(0,Wl.originalOrCamelOptions)(s.get("format")),c=a.get("type")||"text",l=a.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 f=s.get("file"),d=s.get("url"),m=s.get("certificate"),C=s.get("headers");if(f&&d||d&&m||f&&m)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new CS.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new wS.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:C,additionalGaxiosOptions:t.RETRY_CONFIG});else if(m){this.credentialSourceType="certificate";let v=new Ey.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:m.use_default_certificate_config,certificateConfigLocation:m.certificate_config_location,trustChainPath:m.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 Ey.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new ES.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Ay.Gaxios({agent:r})}),this.transporter=new Ay.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};pa.IdentityPoolClient=Gl});var Kl=J(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.AwsRequestSigner=void 0;var ma=Ve(),ky=Yo(),Sy="AWS4-HMAC-SHA256",AS="aws4_request",Vl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,ky.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,o=e.method||"GET",s=e.body||r,a=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await kS({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:a}),d=ma.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:l.host},a||{});c.token&&ma.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let m={url:n,method:o,headers:d};return s!==void 0&&(m.body=s),m}};ga.AwsRequestSigner=Vl;async function as(t,e,r){return await t.signWithHmacSha256(e,r)}async function SS(t,e,r,n,o){let s=await as(t,`AWS4${e}`,r),a=await as(t,s,n),c=await as(t,a,o);return await as(t,c,"aws4_request")}async function kS(t){let e=ma.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=ma.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",f=[...c.keys()].sort();f.forEach(k=>{l+=`${k}:${c.get(k)}
53
+ `});let d=f.join(";"),m=await t.crypto.sha256DigestHex(r),C=`${t.method.toUpperCase()}
54
54
  ${t.canonicalUri}
55
55
  ${t.canonicalQuerystring}
56
56
  ${l}
57
57
  ${d}
58
- ${p}`,T=`${a}/${t.region}/${n}/${pS}`,S=`${yy}
58
+ ${m}`,v=`${a}/${t.region}/${n}/${AS}`,A=`${Sy}
59
59
  ${s}
60
- ${T}
61
- `+await t.crypto.sha256DigestHex(w),_=await mS(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,n),g=await os(t.crypto,_,S),m=`${yy} Credential=${t.securityCredentials.accessKeyId}/${T}, SignedHeaders=${d}, Signature=${(0,_y.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var by=J(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.DefaultAwsSecurityCredentialsSupplier=void 0;var fa=gt(),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};fa.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;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),o=await this.#r(n,r,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return fa.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 fa.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return fa.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){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}};ha.DefaultAwsSecurityCredentialsSupplier=Wl});var Jl=J(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.AwsClient=void 0;var yS=Hl(),_S=Jr(),bS=by(),Cy=zt(),CS=Ve(),Gl=class t extends _S.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,Cy.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,Cy.originalOrCamelOptions)(n);this.environmentId=s.get("environment_id");let a=s.get("region_url"),c=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new bS.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.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 yS.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 CS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>r.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};pa.AwsClient=Gl});var Xl=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 ma="urn:ietf:params:oauth:token-type:saml2",Vl="urn:ietf:params:oauth:token-type:id_token",Kl="urn:ietf:params:oauth:token-type:jwt",Yl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new ga("Executable response must contain a 'version' field.");if(e.success===void 0)throw new ya("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!==ma&&this.tokenType!==Vl&&this.tokenType!==Kl)throw new _a(`Executable response must contain a 'token_type' field when successful and it must be one of ${Vl}, ${Kl}, or ${ma}.`);if(this.tokenType===ma){if(!e.saml_response)throw new ss(`Executable response must contain a 'saml_response' field when token_type=${ma}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new ss(`Executable response must contain a 'id_token' field when token_type=${Vl} or ${Kl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ba("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Ca("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=Yl;var ar=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=ar;var ga=class extends ar{};Le.InvalidVersionFieldError=ga;var ya=class extends ar{};Le.InvalidSuccessFieldError=ya;var Ql=class extends ar{};Le.InvalidExpirationTimeFieldError=Ql;var _a=class extends ar{};Le.InvalidTokenTypeFieldError=_a;var ba=class extends ar{};Le.InvalidCodeFieldError=ba;var Ca=class extends ar{};Le.InvalidMessageFieldError=Ca;var ss=class extends ar{};Le.InvalidSubjectTokenError=ss});var td=J(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.PluggableAuthHandler=io.ExecutableError=void 0;var Cn=Xl(),wS=require("child_process"),Zl=require("fs"),wa=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)}};io.ExecutableError=wa;var ed=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 o=wS.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",c=>{s+=c}),o.stderr.on("data",c=>{s+=c});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",c=>{if(clearTimeout(a),c===0)try{let l=JSON.parse(s),h=new Cn.ExecutableResponse(l);return r(h)}catch(l){return l instanceof Cn.ExecutableResponseError?n(l):n(new Cn.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return n(new wa(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Zl.promises.realpath(this.outputFile)}catch{return}if(!(await Zl.promises.lstat(e)).isFile())return;let r=await Zl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new Cn.ExecutableResponse(n).isValid()?new Cn.ExecutableResponse(n):void 0}catch(n){throw n instanceof Cn.ExecutableResponseError?n:new Cn.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}};io.PluggableAuthHandler=ed});var nd=J(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.PluggableAuthClient=ao.ExecutableError=void 0;var ES=Jr(),AS=Xl(),wy=td(),SS=td();Object.defineProperty(ao,"ExecutableError",{enumerable:!0,get:function(){return SS.ExecutableError}});var kS=30*1e3,Ey=5*1e3,Ay=120*1e3,vS="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Sy=1,rd=class extends ES.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=kS;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Ey||this.timeoutMillis>Ay)throw new Error(`Timeout must be between ${Ey} and ${Ay} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new wy.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[vS]!=="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>Sy)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Sy}.`);if(!e.success)throw new wy.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new AS.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}};ao.PluggableAuthClient=rd});var sd=J(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.ExternalAccountClient=void 0;var TS=Jr(),DS=$l(),RS=Jl(),xS=nd(),od=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===TS.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new RS.AwsClient(e):e.credential_source?.executable?new xS.PluggableAuthClient(e):new DS.IdentityPoolClient(e):null}};Ea.ExternalAccountClient=od});var Dy=J(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.ExternalAccountAuthorizedUserClient=uo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var vy=gt(),ky=xl(),Ty=Ve(),OS=require("stream"),FS=Jr();uo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var PS="https://sts.{universeDomain}/v1/oauthtoken",id=class t extends ky.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})};vy.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),s=o.data;return s.res=o,s}catch(o){throw o instanceof Ty.GaxiosError&&o.response?(0,ky.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},ad=class extends vy.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 id({tokenRefreshEndpoint:e.token_url??PS.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=FS.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 o=await this.getRequestHeaders();e.headers=Ty.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof OS.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}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}};uo.ExternalAccountAuthorizedUserClient=ad});var Fy=J(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.GoogleAuth=Jt.GoogleAuthExceptionMessages=void 0;var IS=require("child_process"),is=require("fs"),NS=Ve(),as=Go(),BS=require("os"),ud=require("path"),jS=Jo(),LS=rl(),MS=ol(),US=sl(),co=Sl(),Ry=vl(),lo=Dl(),qS=sd(),us=Jr(),cd=gt(),xy=Dy(),Oy=zt();Jt.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(C),b=await SS(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,n),g=await as(t.crypto,b,A),p=`${Sy} Credential=${t.securityCredentials.accessKeyId}/${v}, SignedHeaders=${d}, Signature=${(0,ky.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:p,canonicalQuerystring:t.canonicalQuerystring}}});var vy=J(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.DefaultAwsSecurityCredentialsSupplier=void 0;var ya=bt(),Yl=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};ya.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;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),o=await this.#r(n,r,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ya.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 ya.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return ya.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){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}};_a.DefaultAwsSecurityCredentialsSupplier=Yl});var Xl=J(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.AwsClient=void 0;var vS=Kl(),TS=Vr(),DS=vy(),Ty=Wt(),RS=Ve(),Ql=class t extends TS.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,Ty.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,Ty.originalOrCamelOptions)(n);this.environmentId=s.get("environment_id");let a=s.get("region_url"),c=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new DS.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.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 vS.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 RS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>r.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};ba.AwsClient=Ql});var nd=J(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.InvalidSubjectTokenError=je.InvalidMessageFieldError=je.InvalidCodeFieldError=je.InvalidTokenTypeFieldError=je.InvalidExpirationTimeFieldError=je.InvalidSuccessFieldError=je.InvalidVersionFieldError=je.ExecutableResponseError=je.ExecutableResponse=void 0;var Ca="urn:ietf:params:oauth:token-type:saml2",Zl="urn:ietf:params:oauth:token-type:id_token",ed="urn:ietf:params:oauth:token-type:jwt",td=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new wa("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Ea("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!==Ca&&this.tokenType!==Zl&&this.tokenType!==ed)throw new Aa(`Executable response must contain a 'token_type' field when successful and it must be one of ${Zl}, ${ed}, or ${Ca}.`);if(this.tokenType===Ca){if(!e.saml_response)throw new us(`Executable response must contain a 'saml_response' field when token_type=${Ca}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new us(`Executable response must contain a 'id_token' field when token_type=${Zl} or ${ed}.`);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 ka("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)}};je.ExecutableResponse=td;var ur=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};je.ExecutableResponseError=ur;var wa=class extends ur{};je.InvalidVersionFieldError=wa;var Ea=class extends ur{};je.InvalidSuccessFieldError=Ea;var rd=class extends ur{};je.InvalidExpirationTimeFieldError=rd;var Aa=class extends ur{};je.InvalidTokenTypeFieldError=Aa;var Sa=class extends ur{};je.InvalidCodeFieldError=Sa;var ka=class extends ur{};je.InvalidMessageFieldError=ka;var us=class extends ur{};je.InvalidSubjectTokenError=us});var id=J(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.PluggableAuthHandler=co.ExecutableError=void 0;var En=nd(),xS=require("child_process"),od=require("fs"),va=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)}};co.ExecutableError=va;var sd=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 o=xS.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",c=>{s+=c}),o.stderr.on("data",c=>{s+=c});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",c=>{if(clearTimeout(a),c===0)try{let l=JSON.parse(s),f=new En.ExecutableResponse(l);return r(f)}catch(l){return l instanceof En.ExecutableResponseError?n(l):n(new En.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return n(new va(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await od.promises.realpath(this.outputFile)}catch{return}if(!(await od.promises.lstat(e)).isFile())return;let r=await od.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new En.ExecutableResponse(n).isValid()?new En.ExecutableResponse(n):void 0}catch(n){throw n instanceof En.ExecutableResponseError?n:new En.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}};co.PluggableAuthHandler=sd});var ud=J(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.PluggableAuthClient=lo.ExecutableError=void 0;var OS=Vr(),FS=nd(),Dy=id(),PS=id();Object.defineProperty(lo,"ExecutableError",{enumerable:!0,get:function(){return PS.ExecutableError}});var IS=30*1e3,Ry=5*1e3,xy=120*1e3,NS="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Oy=1,ad=class extends OS.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=IS;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Ry||this.timeoutMillis>xy)throw new Error(`Timeout must be between ${Ry} and ${xy} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Dy.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[NS]!=="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>Oy)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Oy}.`);if(!e.success)throw new Dy.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new FS.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}};lo.PluggableAuthClient=ad});var ld=J(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ExternalAccountClient=void 0;var BS=Vr(),MS=Jl(),jS=Xl(),LS=ud(),cd=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===BS.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new jS.AwsClient(e):e.credential_source?.executable?new LS.PluggableAuthClient(e):new MS.IdentityPoolClient(e):null}};Ta.ExternalAccountClient=cd});var Ny=J(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.ExternalAccountAuthorizedUserClient=fo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Py=bt(),Fy=Nl(),Iy=Ve(),US=require("stream"),$S=Vr();fo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var qS="https://sts.{universeDomain}/v1/oauthtoken",dd=class t extends Fy.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})};Py.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),s=o.data;return s.res=o,s}catch(o){throw o instanceof Iy.GaxiosError&&o.response?(0,Fy.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},fd=class extends Py.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 dd({tokenRefreshEndpoint:e.token_url??qS.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=$S.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 o=await this.getRequestHeaders();e.headers=Iy.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof US.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}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}};fo.ExternalAccountAuthorizedUserClient=fd});var Ly=J(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GoogleAuth=Kt.GoogleAuthExceptionMessages=void 0;var zS=require("child_process"),cs=require("fs"),HS=Ve(),ls=Ko(),WS=require("os"),hd=require("path"),GS=Yo(),JS=al(),VS=cl(),KS=ll(),ho=Rl(),By=Ol(),po=Pl(),YS=ld(),ds=Vr(),pd=bt(),My=Ny(),jy=Wt();Kt.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 ld=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(Jt.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===Jt.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(Jt.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 as.universe("universe-domain"),e||=cd.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=cd.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,Oy.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=cd.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(o=>r(null,o.credential,o.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 co.JWT?r.scopes=this.scopes:r instanceof us.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof co.JWT?r.scopes=this.scopes:r instanceof us.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new LS.Compute(e));throw new Error(Jt.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=as.getGCPResidency()||await as.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 o=process.env.HOME;o&&(r=ud.join(o,".config"))}return r&&(r=ud.join(r,"gcloud","application_default_credentials.json"),is.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=is.realpathSync(e),!is.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=is.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!==lo.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${lo.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 o=this.getAnyScopes()??[];return new lo.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}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,o=(0,Oy.originalOrCamelOptions)(r).get("universe_domain");return e.type===Ry.USER_REFRESH_ACCOUNT_TYPE?(n=new Ry.UserRefreshClient(r),n.fromJSON(e)):e.type===lo.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===us.EXTERNAL_ACCOUNT_TYPE?(n=qS.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===xy.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new xy.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new co.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),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 o={};if(typeof r=="function"?n=r:o=r,n)this.fromStreamAsync(e,o).then(s=>n(null,s),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,r){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",a=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),c=this._cacheClientFromJSON(a,r);return n(c)}catch(a){if(!this.keyFilename)throw a;let c=new co.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(a){return o(a)}})})}fromAPIKey(e,r={}){return new co.JWT({...r,apiKey:e})}_isWindows(){let e=BS.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,IS.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);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!==us.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await as.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 lo.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof us.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([as.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(Jt.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=ud.resolve(this.keyFilename),r=is.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 MS.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,o=await(await this.getClient()).getRequestHeaders(r);return e.headers=NS.Gaxios.mergeHeaders(e.headers,o),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(),o=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof lo.Impersonated)return(await n.sign(e)).signedBlob;let s=(0,jS.createCrypto)();if(n instanceof co.JWT&&n.key)return await s.sign(n.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,e,r)}async signBlob(e,r,n,o){let s=new URL(o+`${r}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Jt.GoogleAuth=ld});var Py=J(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.IAMAuth=void 0;var dd=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}}};Aa.IAMAuth=dd});var Iy=J(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DownscopedClient=ur.EXPIRATION_TIME_OFFSET=ur.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var $S=Ve(),zS=require("stream"),fd=gt(),HS=na(),WS="urn:ietf:params:oauth:grant-type:token-exchange",GS="urn:ietf:params:oauth:token-type:access_token",JS="urn:ietf:params:oauth:token-type:access_token";ur.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;ur.EXPIRATION_TIME_OFFSET=300*1e3;var hd=class extends fd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof fd.AuthClient?{}:e),e instanceof fd.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>ur.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${ur.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 o=await this.getRequestHeaders();e.headers=$S.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof zS.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:WS,requestedTokenType:GS,subjectToken:e,subjectTokenType:JS},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:s,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}};ur.DownscopedClient=hd});var Ny=J(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.PassThroughClient=void 0;var VS=gt(),pd=class extends VS.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Sa.PassThroughClient=pd});var gd=J(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.GoogleAuth=re.auth=re.PassThroughClient=re.ExecutableError=re.PluggableAuthClient=re.DownscopedClient=re.BaseExternalAccountClient=re.ExternalAccountClient=re.IdentityPoolClient=re.AwsRequestSigner=re.AwsClient=re.UserRefreshClient=re.LoginTicket=re.ClientAuthentication=re.OAuth2Client=re.CodeChallengeMethod=re.Impersonated=re.JWT=re.JWTAccess=re.IdTokenClient=re.IAMAuth=re.GCPEnv=re.Compute=re.DEFAULT_UNIVERSE=re.AuthClient=re.gaxios=re.gcpMetadata=void 0;var By=Fy();Object.defineProperty(re,"GoogleAuth",{enumerable:!0,get:function(){return By.GoogleAuth}});re.gcpMetadata=Go();re.gaxios=Ve();var jy=gt();Object.defineProperty(re,"AuthClient",{enumerable:!0,get:function(){return jy.AuthClient}});Object.defineProperty(re,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return jy.DEFAULT_UNIVERSE}});var KS=rl();Object.defineProperty(re,"Compute",{enumerable:!0,get:function(){return KS.Compute}});var YS=sl();Object.defineProperty(re,"GCPEnv",{enumerable:!0,get:function(){return YS.GCPEnv}});var QS=Py();Object.defineProperty(re,"IAMAuth",{enumerable:!0,get:function(){return QS.IAMAuth}});var XS=ol();Object.defineProperty(re,"IdTokenClient",{enumerable:!0,get:function(){return XS.IdTokenClient}});var ZS=El();Object.defineProperty(re,"JWTAccess",{enumerable:!0,get:function(){return ZS.JWTAccess}});var ek=Sl();Object.defineProperty(re,"JWT",{enumerable:!0,get:function(){return ek.JWT}});var tk=Dl();Object.defineProperty(re,"Impersonated",{enumerable:!0,get:function(){return tk.Impersonated}});var md=bn();Object.defineProperty(re,"CodeChallengeMethod",{enumerable:!0,get:function(){return md.CodeChallengeMethod}});Object.defineProperty(re,"OAuth2Client",{enumerable:!0,get:function(){return md.OAuth2Client}});Object.defineProperty(re,"ClientAuthentication",{enumerable:!0,get:function(){return md.ClientAuthentication}});var rk=Xc();Object.defineProperty(re,"LoginTicket",{enumerable:!0,get:function(){return rk.LoginTicket}});var nk=vl();Object.defineProperty(re,"UserRefreshClient",{enumerable:!0,get:function(){return nk.UserRefreshClient}});var ok=Jl();Object.defineProperty(re,"AwsClient",{enumerable:!0,get:function(){return ok.AwsClient}});var sk=Hl();Object.defineProperty(re,"AwsRequestSigner",{enumerable:!0,get:function(){return sk.AwsRequestSigner}});var ik=$l();Object.defineProperty(re,"IdentityPoolClient",{enumerable:!0,get:function(){return ik.IdentityPoolClient}});var ak=sd();Object.defineProperty(re,"ExternalAccountClient",{enumerable:!0,get:function(){return ak.ExternalAccountClient}});var uk=Jr();Object.defineProperty(re,"BaseExternalAccountClient",{enumerable:!0,get:function(){return uk.BaseExternalAccountClient}});var ck=Iy();Object.defineProperty(re,"DownscopedClient",{enumerable:!0,get:function(){return ck.DownscopedClient}});var Ly=nd();Object.defineProperty(re,"PluggableAuthClient",{enumerable:!0,get:function(){return Ly.PluggableAuthClient}});Object.defineProperty(re,"ExecutableError",{enumerable:!0,get:function(){return Ly.ExecutableError}});var lk=Ny();Object.defineProperty(re,"PassThroughClient",{enumerable:!0,get:function(){return lk.PassThroughClient}});var dk=new By.GoogleAuth;re.auth=dk});var S0=J((jF,Wd)=>{"use strict";var $T=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,zT=/(\w*(\.\w*)*)\..*/;Wd.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,A0(n.stack)}};function A0(t){let e=t.match($T);return e?e[1].split(/[/\\]/).slice(-1)[0].match(zT)[1]:"anonymous"}Wd.exports.extractPluginName=A0});var v0=J((LF,k0)=>{"use strict";k0.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var T0=J((MF,au)=>{"use strict";var HT=S0(),WT=v0(),GT=0;function Gd(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=HT(t)+"-auto-"+GT++),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=WT(e.name);return!r&&!t[n]&&(t[n]=t),t}au.exports=Gd;au.exports.default=Gd;au.exports.fastifyPlugin=Gd});var bs,Vd=Be(()=>{"use strict";bs=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:o=!0,prefix:s,metadata:a}=r||{},c="";if(o){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(c+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),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 a&&Object.keys(a).length>0&&(c+=`
67
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var md=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(Kt.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===Kt.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(Kt.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 ls.universe("universe-domain"),e||=pd.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=pd.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,jy.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=pd.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(o=>r(null,o.credential,o.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 ho.JWT?r.scopes=this.scopes:r instanceof ds.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof ho.JWT?r.scopes=this.scopes:r instanceof ds.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new JS.Compute(e));throw new Error(Kt.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=ls.getGCPResidency()||await ls.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 o=process.env.HOME;o&&(r=hd.join(o,".config"))}return r&&(r=hd.join(r,"gcloud","application_default_credentials.json"),cs.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=cs.realpathSync(e),!cs.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=cs.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!==po.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${po.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 o=this.getAnyScopes()??[];return new po.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}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,o=(0,jy.originalOrCamelOptions)(r).get("universe_domain");return e.type===By.USER_REFRESH_ACCOUNT_TYPE?(n=new By.UserRefreshClient(r),n.fromJSON(e)):e.type===po.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===ds.EXTERNAL_ACCOUNT_TYPE?(n=YS.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===My.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new My.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new ho.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),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 o={};if(typeof r=="function"?n=r:o=r,n)this.fromStreamAsync(e,o).then(s=>n(null,s),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,r){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",a=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),c=this._cacheClientFromJSON(a,r);return n(c)}catch(a){if(!this.keyFilename)throw a;let c=new ho.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(a){return o(a)}})})}fromAPIKey(e,r={}){return new ho.JWT({...r,apiKey:e})}_isWindows(){let e=WS.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,zS.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);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!==ds.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await ls.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 po.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof ds.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([ls.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(Kt.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=hd.resolve(this.keyFilename),r=cs.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 VS.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,o=await(await this.getClient()).getRequestHeaders(r);return e.headers=HS.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,KS.getEnv)()}async sign(e,r){let n=await this.getClient(),o=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof po.Impersonated)return(await n.sign(e)).signedBlob;let s=(0,GS.createCrypto)();if(n instanceof ho.JWT&&n.key)return await s.sign(n.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,e,r)}async signBlob(e,r,n,o){let s=new URL(o+`${r}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Kt.GoogleAuth=md});var Uy=J(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.IAMAuth=void 0;var gd=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}}};Da.IAMAuth=gd});var $y=J(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.DownscopedClient=cr.EXPIRATION_TIME_OFFSET=cr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var QS=Ve(),XS=require("stream"),yd=bt(),ZS=ua(),ek="urn:ietf:params:oauth:grant-type:token-exchange",tk="urn:ietf:params:oauth:token-type:access_token",rk="urn:ietf:params:oauth:token-type:access_token";cr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;cr.EXPIRATION_TIME_OFFSET=300*1e3;var _d=class extends yd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof yd.AuthClient?{}:e),e instanceof yd.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>cr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${cr.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 ZS.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 o=await this.getRequestHeaders();e.headers=QS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof XS.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:ek,requestedTokenType:tk,subjectToken:e,subjectTokenType:rk},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:s,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}};cr.DownscopedClient=_d});var qy=J(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.PassThroughClient=void 0;var nk=bt(),bd=class extends nk.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Ra.PassThroughClient=bd});var wd=J(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.GoogleAuth=re.auth=re.PassThroughClient=re.ExecutableError=re.PluggableAuthClient=re.DownscopedClient=re.BaseExternalAccountClient=re.ExternalAccountClient=re.IdentityPoolClient=re.AwsRequestSigner=re.AwsClient=re.UserRefreshClient=re.LoginTicket=re.ClientAuthentication=re.OAuth2Client=re.CodeChallengeMethod=re.Impersonated=re.JWT=re.JWTAccess=re.IdTokenClient=re.IAMAuth=re.GCPEnv=re.Compute=re.DEFAULT_UNIVERSE=re.AuthClient=re.gaxios=re.gcpMetadata=void 0;var zy=Ly();Object.defineProperty(re,"GoogleAuth",{enumerable:!0,get:function(){return zy.GoogleAuth}});re.gcpMetadata=Ko();re.gaxios=Ve();var Hy=bt();Object.defineProperty(re,"AuthClient",{enumerable:!0,get:function(){return Hy.AuthClient}});Object.defineProperty(re,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Hy.DEFAULT_UNIVERSE}});var ok=al();Object.defineProperty(re,"Compute",{enumerable:!0,get:function(){return ok.Compute}});var sk=ll();Object.defineProperty(re,"GCPEnv",{enumerable:!0,get:function(){return sk.GCPEnv}});var ik=Uy();Object.defineProperty(re,"IAMAuth",{enumerable:!0,get:function(){return ik.IAMAuth}});var ak=cl();Object.defineProperty(re,"IdTokenClient",{enumerable:!0,get:function(){return ak.IdTokenClient}});var uk=Tl();Object.defineProperty(re,"JWTAccess",{enumerable:!0,get:function(){return uk.JWTAccess}});var ck=Rl();Object.defineProperty(re,"JWT",{enumerable:!0,get:function(){return ck.JWT}});var lk=Pl();Object.defineProperty(re,"Impersonated",{enumerable:!0,get:function(){return lk.Impersonated}});var Cd=wn();Object.defineProperty(re,"CodeChallengeMethod",{enumerable:!0,get:function(){return Cd.CodeChallengeMethod}});Object.defineProperty(re,"OAuth2Client",{enumerable:!0,get:function(){return Cd.OAuth2Client}});Object.defineProperty(re,"ClientAuthentication",{enumerable:!0,get:function(){return Cd.ClientAuthentication}});var dk=nl();Object.defineProperty(re,"LoginTicket",{enumerable:!0,get:function(){return dk.LoginTicket}});var fk=Ol();Object.defineProperty(re,"UserRefreshClient",{enumerable:!0,get:function(){return fk.UserRefreshClient}});var hk=Xl();Object.defineProperty(re,"AwsClient",{enumerable:!0,get:function(){return hk.AwsClient}});var pk=Kl();Object.defineProperty(re,"AwsRequestSigner",{enumerable:!0,get:function(){return pk.AwsRequestSigner}});var mk=Jl();Object.defineProperty(re,"IdentityPoolClient",{enumerable:!0,get:function(){return mk.IdentityPoolClient}});var gk=ld();Object.defineProperty(re,"ExternalAccountClient",{enumerable:!0,get:function(){return gk.ExternalAccountClient}});var yk=Vr();Object.defineProperty(re,"BaseExternalAccountClient",{enumerable:!0,get:function(){return yk.BaseExternalAccountClient}});var _k=$y();Object.defineProperty(re,"DownscopedClient",{enumerable:!0,get:function(){return _k.DownscopedClient}});var Wy=ud();Object.defineProperty(re,"PluggableAuthClient",{enumerable:!0,get:function(){return Wy.PluggableAuthClient}});Object.defineProperty(re,"ExecutableError",{enumerable:!0,get:function(){return Wy.ExecutableError}});var bk=qy();Object.defineProperty(re,"PassThroughClient",{enumerable:!0,get:function(){return bk.PassThroughClient}});var Ck=new zy.GoogleAuth;re.auth=Ck});var F0=J((VF,Yd)=>{"use strict";var YT=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,QT=/(\w*(\.\w*)*)\..*/;Yd.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,O0(n.stack)}};function O0(t){let e=t.match(YT);return e?e[1].split(/[/\\]/).slice(-1)[0].match(QT)[1]:"anonymous"}Yd.exports.extractPluginName=O0});var I0=J((KF,P0)=>{"use strict";P0.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var N0=J((YF,fu)=>{"use strict";var XT=F0(),ZT=I0(),eD=0;function Qd(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=XT(t)+"-auto-"+eD++),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=ZT(e.name);return!r&&!t[n]&&(t[n]=t),t}fu.exports=Qd;fu.exports.default=Qd;fu.exports.fastifyPlugin=Qd});var Es,Zd=Ne(()=>{"use strict";Es=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:o=!0,prefix:s,metadata:a}=r||{},c="";if(o){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(c+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),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 a&&Object.keys(a).length>0&&(c+=`
68
68
  `+(this.config.colors?`${this.colors.dim}`:""),c+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(c+=this.colors.reset)),c}toMarkdown(e,r=0){let n=" ".repeat(r);return Array.isArray(e)?e.map(o=>typeof o=="object"?`${n}-
69
69
  ${this.toMarkdown(o,r+1)}`:`${n}- ${o}`).join(`
70
70
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([o,s])=>typeof s=="object"&&s!==null?`${n}${o}:
71
71
  ${this.toMarkdown(s,r+1)}`:`${n}${o}: ${s}`).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 Cs,Kd=Be(()=>{"use strict";Cs=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:o=!0,prefix:s,metadata:a}=r||{},c={data:e};return o&&(c.timestamp=new Date().toISOString()),s&&(c.prefix=s),a&&Object.keys(a).length>0&&(c.metadata=a),c}async sendRequest(e,r,n,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(o),signal:a.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,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,r,n,o,s)}catch(h){if(c=h,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,h.message),await this.delay(d)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,r),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,n,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var yo,Yd,D0,ws,Qd=Be(()=>{"use strict";yo=require("fs"),Yd=require("path"),D0=require("os"),ws=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=(0,D0.tmpdir)();this.baseDir=(0,Yd.join)(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,yo.existsSync)(this.baseDir)||(0,yo.mkdirSync)(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}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${r}-${e}-${s}${n}`}else o=`${r}-${e}${n}`;return(0,Yd.join)(this.baseDir,o)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let o={...e,timestamp:Date.now(),sessionId:n},s=this.getFilePath(n);return(0,yo.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Xd,_o,R0=Be(()=>{"use strict";Vd();Kd();Qd();Xd=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),o=r.type+"_"+Date.now();this.registerHandler(o,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new bs(e.config);case"webhook":return new Cs(e.config);case"temp-file":return new ws(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},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,n)?o.success.push(a):o.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,r,n){let o={...this.defaultOptions,...n},s={success:[],failed:[]},a=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),s.failed.push(c);return}try{await l.output(r,o)?s.success.push(c):s.failed.push(c)}catch(h){console.error(`[OutputManager] Handler ${c} failed:`,h),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,r,n){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,r,n)}},_o=new Xd});var YT={};Nu(YT,{ActiveProbeService:()=>ys,ConfigService:()=>un,ProviderHealthStore:()=>xo,ProviderService:()=>cn,SSEParserTransform:()=>An,SSESerializerTransform:()=>_s,TokenizerService:()=>En,TransformerService:()=>wn,calculateTokenCount:()=>Id,default:()=>KT,getActiveProbeService:()=>$d,getAllQuotaResults:()=>w0,getAllRateLimitInfo:()=>Sh,getHealthStore:()=>At,getQuotaAdapter:()=>nu,getQuotaResult:()=>C0,getRateLimitInfo:()=>Ah,pluginManager:()=>Hd,resetActiveProbeService:()=>E0,rewriteStream:()=>Jd,router:()=>ru,searchProjectBySession:()=>Nd,sessionUsageCache:()=>Qa,startActiveProbe:()=>su,stopActiveProbe:()=>iu,storeQuotaResult:()=>ou,tokenSpeedPlugin:()=>ef});module.exports=wb(YT);var P0=je(require("fastify"),1),I0=je(require("@fastify/cors"),1);var Ro=require("fs"),Wu=require("path"),gh=require("dotenv"),yh=je(Hu(),1),un=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:(0,Wu.join)(process.cwd(),this.options.jsonPath);if((0,Ro.existsSync)(e))try{let r=(0,Ro.readFileSync)(e,"utf-8"),n=yh.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:(0,Wu.join)(process.cwd(),this.options.envPath);if((0,Ro.existsSync)(e))try{let r=(0,gh.config)({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 o=new Error(t);return o.statusCode=e,o.code=r,o.type=n,o}async function _h(t,e,r){e.log.error(t);let n=t.statusCode||500,o={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(o)}var bh=require("undici");function Ch(t,e,r,n,o){let s=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([h,d])=>{d&&s.set(h,d)});let a,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let h=new AbortController,d=()=>h.abort();r.signal.addEventListener("abort",d),c.addEventListener("abort",d),a=h.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return r.httpsProxy&&(l.dispatcher=new bh.ProxyAgent(new URL(r.httpsProxy).toString())),o?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var wh="2.0.70";var Ob={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},xo=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ob,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),o=this.states.get(n);o&&(o.successCount++,o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(n):o.status==="open"&&(o.status="half-open",o.successCount=1,o.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 o=this.getKey(e,r),s=this.states.get(o);s||(s={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=n;let c=this.isRateLimitError(n)?this.config.rateLimitThreshold:this.config.failureThreshold;s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=c&&(s.status="open",s.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),o=this.states.get(n);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Gu=null;function At(t){return Gu||(Gu=new xo(t)),Gu}var Vu=new Map,Fb=["x-ratelimit-remaining","x-ratelimit-remaining-requests","x-ratelimit-remaining-tokens"],Pb=["x-ratelimit-limit","x-ratelimit-limit-requests","x-ratelimit-limit-tokens"],Ib=["x-ratelimit-reset","x-ratelimit-reset-requests","x-ratelimit-reset-tokens"];function Oo(t,e,r){let n=c=>{if(r instanceof Headers)return r.get(c);let l=Object.keys(r).find(h=>h.toLowerCase()===c);return l?r[l]:null},o=Ju(n,Fb),s=Ju(n,Pb),a=Ju(n,Ib);(o||s||a)&&Vu.set(t,{provider:t,remaining:Eh(o),limit:Eh(s),reset:Nb(a),capturedAt:Date.now()})}function Ah(t){return Vu.get(t)}function Sh(){return Array.from(Vu.values())}function Ju(t,e){for(let r of e){let n=t(r);if(n)return n}return null}function Eh(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Nb(t){if(!t)return null;let e=t.trim();if(!e)return null;let r=Number(e);if(Number.isFinite(r))return r>1e12?Math.floor(r/1e3):r>1e9?Math.floor(r):Math.floor(Date.now()/1e3+r);let n=Date.parse(e);if(Number.isFinite(n))return Math.floor(n/1e3);let o=Bb(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function Bb(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,r=0,n=!1;for(let o of t.matchAll(e)){n=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":r+=s;break;case"s":r+=s*1e3;break;case"m":r+=s*60*1e3;break;case"h":r+=s*60*60*1e3;break;case"d":r+=s*24*60*60*1e3;break}}return n?r:null}async function jb(t,e,r,n){let o=t.body,s=t.provider,a=r.providerService.getProvider(s);if(!a)throw nt(`Provider '${s}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:h}=await kh(o,a,n,t.headers,{req:t}),d=await vh(c,l,a,r,h,n,{req:t});try{a?.baseUrl&&d?.headers&&Oo(s,a.baseUrl,d.headers)}catch{}let p=await Th(c,d,a,n,h,{req:t});return Dh(p,e,o)}catch(c){let l=await Lb(t,e,r,n,c);if(l)return l;throw c}}async function Lb(t,e,r,n,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=r.configService.get("fallback"),h=At(),d=g=>{let[m,...k]=g.split(","),y=m?.trim(),E=k.join(",").trim();return!y||!E?null:{provider:y,model:E,key:`${y},${E}`}},p=[];if(c){let g=a?.[s];Array.isArray(g)&&g.length>0?p.push({name:`${c}/${s}`,models:g}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&p.push({name:`global/${s}`,models:l[s]}),p.length===0)return null;let w=t.provider||"",T=t.body.model||"",S=new Set;w&&T&&(h.recordFailure(w,T,o?.message),S.add(`${w},${T}`));let _=p.reduce((g,m)=>g+m.models.length,0);t.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${p.length} fallback stage(s)`);for(let g of p){t.log.info(`Trying ${g.name} fallback stage with ${g.models.length} models`);for(let m of g.models){let k=d(m);if(!k){t.log.warn(`Fallback model '${m}' is invalid, skipping`);continue}if(S.has(k.key))continue;S.add(k.key);let y=k.provider,E=k.model;try{if(!h.isAvailable(y,E)){t.log.warn(`Fallback model ${m} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${m}`);let D={...t.body};D.model=E;let F={...t,provider:y,body:D},$=r.providerService.getProvider(y);if(!$){t.log.warn(`Fallback provider '${y}' not found, skipping`);continue}let{requestBody:V,config:B,bypass:Y}=await kh(D,$,n,t.headers,{req:F}),te=await vh(V,B,$,r,Y,n,{req:F});try{$?.baseUrl&&te?.headers&&Oo(y,$.baseUrl,te.headers)}catch{}let Z=await Th(V,te,$,n,Y,{req:F});return t.log.info(`Fallback model ${m} succeeded`),h.recordSuccess(y,E),t.provider=y,t.body=D,Dh(Z,e,D)}catch(D){h.recordFailure(y,E,D.message),t.log.warn(`Fallback model ${k.key} failed: ${D.message}`);continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function kh(t,e,r,n,o){let s=JSON.parse(JSON.stringify(t)),a={},c=!1;if(c=Mb(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(s);l.body?(s=l.body,a=l.config||{}):s=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(s,e,o);h.body?(s=h.body,a={...a,...h.config}):s=h}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(s=await l.transformRequestIn(s,e,o));return{requestBody:s,config:a,bypass:c}}function Mb(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 vh(t,e,r,n,o,s,a){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let d=n.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(o&&typeof s.auth=="function"){let d=await s.auth(t,r);if(d.body){t=d.body;let p=e.headers||{};d.config?.headers&&(p={...p,...d.config.headers},delete p.host,delete d.config.headers),e={...e,...d.config,headers:p}}else t=d}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];let h=await Ch(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,n.log);if(!h.ok){let d=await h.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${h.status}): ${d}`),nt(`Error from provider(${r.name},${t.model}: ${h.status}): ${d}`,h.status,"provider_response_error")}return h}async function Th(t,e,r,n,o,s){let a=e;if(!o&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a,s)),a}function Dh(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:wh})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:At().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,o)=>jb(n,o,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:o,baseUrl:s,apiKey:a,models:c}=r.body;if(!o?.trim())throw nt("Provider name is required",400,"invalid_request");if(!s||!Ub(s))throw nt("Valid base URL is required",400,"invalid_request");if(!a?.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 o=t.providerService.updateProvider(r.params.id,r.body);if(!o)throw nt("Provider not found",404,"provider_not_found");return o}),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 Ub(t){try{return new URL(t),!0}catch{return!1}}var cn=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(o=>{o==="use"?Array.isArray(r.transformer.use)&&(n.use=r.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(r.transformer[o]?.use)&&(n[o]={use:r.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],quotaToken:r.quota_token,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 o=`${r.name},${n}`,s={provider:r.name,model:n,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(n)||this.modelRoutes.set(n,s)}),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 o={...n,...r,updatedAt:new Date};return this.providers.set(e,o),r.models&&(n.models.forEach(s=>{let a=`${n.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),r.models.forEach(s=>{let a=`${n.name},${s}`,c={provider:n.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let o=`${r.name},${n}`;this.modelRoutes.delete(o),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[o,s={}]=n;r[o]=s}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 Rh(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()}var xh=require("crypto"),ni=new Uint8Array(256),ri=ni.length;function Yu(){return ri>ni.length-16&&((0,xh.randomFillSync)(ni),ri=0),ni.slice(ri,ri+=16)}var Oh=require("crypto"),Qu={randomUUID:Oh.randomUUID};function qb(t,e,r){if(Qu.randomUUID&&!e&&!t)return Qu.randomUUID();t=t||{};let n=t.random??t.rng?.()??Yu();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 o=0;o<16;++o)e[r+o]=n[o];return e}return Rh(n)}var Qt=qb;var Fh=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Ph=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var oi=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 s=e.system.filter(a=>a.type==="text"&&a.text).map(a=>({type:"text",text:a.text,cache_control:a.cache_control}));r.push({role:"system",content:s})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(s=>{if(s.role==="user"||s.role==="assistant"){if(typeof s.content=="string"){r.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let a=s.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);a.length&&a.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=s.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"?Ph(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(s.role==="assistant"){let a={role:"assistant",content:""},c=s.content.filter(d=>d.type==="text"&&d.text);c.length&&(a.content=c.map(d=>d.text).join(`
73
- `));let l=s.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(a.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let h=s.content.find(d=>d.type==="thinking"&&d.signature);h&&(a.thinking={content:h.thinking,signature:h.signature}),r.push(a)}return}}});let o={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&&(o.reasoning={effort:Fh(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}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 o=await this.convertOpenAIStreamToAnthropic(e.body,r);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,r);return new Response(JSON.stringify(s),{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 o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",h=!1,d=!1,p=!1,w=new Map,T=new Map,S=0,_=0,g=0,m=!1,k=!1,y=0,E=-1,D=()=>{let B=y;return y++,B},F=B=>{if(!m)try{o.enqueue(B);let Y=new TextDecoder().decode(B);this.logger.debug({reqId:r.req.id,data:Y,type:"send data"})}catch(Y){if(Y instanceof TypeError&&Y.message.includes("Controller is already closed"))m=!0;else throw this.logger.debug({reqId:r.req.id,error:Y instanceof Error?Y.message:String(Y),type:"send data error"}),Y}},$=()=>{if(!m)try{if(E>=0){let Y={type:"content_block_stop",index:E};F(s.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 As,ef=Ne(()=>{"use strict";As=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:o=!0,prefix:s,metadata:a}=r||{},c={data:e};return o&&(c.timestamp=new Date().toISOString()),s&&(c.prefix=s),a&&Object.keys(a).length>0&&(c.metadata=a),c}async sendRequest(e,r,n,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(o),signal:a.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,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,r,n,o,s)}catch(f){if(c=f,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,r),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,n,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var bo,tf,B0,Ss,rf=Ne(()=>{"use strict";bo=require("fs"),tf=require("path"),B0=require("os"),Ss=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=(0,B0.tmpdir)();this.baseDir=(0,tf.join)(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,bo.existsSync)(this.baseDir)||(0,bo.mkdirSync)(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}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${r}-${e}-${s}${n}`}else o=`${r}-${e}${n}`;return(0,tf.join)(this.baseDir,o)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let o={...e,timestamp:Date.now(),sessionId:n},s=this.getFilePath(n);return(0,bo.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var nf,Co,M0=Ne(()=>{"use strict";Zd();ef();rf();nf=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),o=r.type+"_"+Date.now();this.registerHandler(o,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new Es(e.config);case"webhook":return new As(e.config);case"temp-file":return new Ss(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},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,n)?o.success.push(a):o.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,r,n){let o={...this.defaultOptions,...n},s={success:[],failed:[]},a=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),s.failed.push(c);return}try{await l.output(r,o)?s.success.push(c):s.failed.push(c)}catch(f){console.error(`[OutputManager] Handler ${c} failed:`,f),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,r,n){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,r,n)}},Co=new nf});var oD={};ti(oD,{ActiveProbeService:()=>Cs,ConfigService:()=>cn,ProviderHealthStore:()=>Po,ProviderService:()=>dn,SSEParserTransform:()=>kn,SSESerializerTransform:()=>ws,TokenizerService:()=>Sn,TransformerService:()=>An,calculateTokenCount:()=>Ld,default:()=>nD,getActiveProbeService:()=>Jd,getAllQuotaResults:()=>R0,getAllRateLimitInfo:()=>Oh,getHealthStore:()=>st,getQuotaAdapter:()=>uu,getQuotaResult:()=>D0,getRateLimitInfo:()=>xh,pluginManager:()=>Kd,resetActiveProbeService:()=>x0,rewriteStream:()=>Xd,router:()=>au,searchProjectBySession:()=>Ud,sessionUsageCache:()=>ru,startActiveProbe:()=>lu,stopActiveProbe:()=>du,storeQuotaResult:()=>cu,tokenSpeedPlugin:()=>sf});module.exports=dh(oD);var $0=Me(require("fastify"),1),q0=Me(require("@fastify/cors"),1);var Oo=require("fs"),Ku=require("path"),Eh=require("dotenv"),Ah=Me(Vu(),1),cn=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:(0,Ku.join)(process.cwd(),this.options.jsonPath);if((0,Oo.existsSync)(e))try{let r=(0,Oo.readFileSync)(e,"utf-8"),n=Ah.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:(0,Ku.join)(process.cwd(),this.options.envPath);if((0,Oo.existsSync)(e))try{let r=(0,Eh.config)({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 ot(t,e=500,r="internal_error",n="api_error"){let o=new Error(t);return o.statusCode=e,o.code=r,o.type=n,o}async function Sh(t,e,r){e.log.error(t);let n=t.statusCode||500,o={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(o)}var kh=require("undici");function vh(t,e,r,n,o){let s=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([f,d])=>{d&&s.set(f,d)});let a,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let f=new AbortController,d=()=>f.abort();r.signal.addEventListener("abort",d),c.addEventListener("abort",d),a=f.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return r.httpsProxy&&(l.dispatcher=new kh.ProxyAgent(new URL(r.httpsProxy).toString())),o?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var Th="2.0.71";Un();var Zu=new Map,$b=["x-ratelimit-remaining","x-ratelimit-remaining-requests","x-ratelimit-remaining-tokens"],qb=["x-ratelimit-limit","x-ratelimit-limit-requests","x-ratelimit-limit-tokens"],zb=["x-ratelimit-reset","x-ratelimit-reset-requests","x-ratelimit-reset-tokens"];function Io(t,e,r){let n=c=>{if(r instanceof Headers)return r.get(c);let l=Object.keys(r).find(f=>f.toLowerCase()===c);return l?r[l]:null},o=Xu(n,$b),s=Xu(n,qb),a=Xu(n,zb);(o||s||a)&&Zu.set(t,{provider:t,remaining:Rh(o),limit:Rh(s),reset:Hb(a),capturedAt:Date.now()})}function xh(t){return Zu.get(t)}function Oh(){return Array.from(Zu.values())}function Xu(t,e){for(let r of e){let n=t(r);if(n)return n}return null}function Rh(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Hb(t){if(!t)return null;let e=t.trim();if(!e)return null;let r=Number(e);if(Number.isFinite(r))return r>1e12?Math.floor(r/1e3):r>1e9?Math.floor(r):Math.floor(Date.now()/1e3+r);let n=Date.parse(e);if(Number.isFinite(n))return Math.floor(n/1e3);let o=Wb(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function Wb(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,r=0,n=!1;for(let o of t.matchAll(e)){n=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":r+=s;break;case"s":r+=s*1e3;break;case"m":r+=s*60*1e3;break;case"h":r+=s*60*60*1e3;break;case"d":r+=s*24*60*60*1e3;break}}return n?r:null}ii();async function Gb(t,e,r,n){let o=t.body,s=t.provider,a=r.providerService.getProvider(s);if(!a)throw ot(`Provider '${s}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:f}=await Fh(o,a,n,t.headers,{req:t}),d=await Ph(c,l,a,r,f,n,{req:t});try{a?.baseUrl&&d?.headers&&Io(s,a.baseUrl,d.headers)}catch{}let m=await Ih(c,d,a,n,f,{req:t});return Nh(m,e,o)}catch(c){let l=await Jb(t,e,r,n,c);if(l)return l;throw c}}async function Jb(t,e,r,n,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=r.configService.get("fallback"),f=st(),d=g=>{let[p,...k]=g.split(","),y=p?.trim(),E=k.join(",").trim();return!y||!E?null:{provider:y,model:E,key:`${y},${E}`}},m=[];if(c){let g=a?.[s];Array.isArray(g)&&g.length>0?m.push({name:`${c}/${s}`,models:g}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.length===0)return null;let C=t.provider||"",v=t.body.model||"",A=new Set;C&&v&&(f.recordFailure(C,v,o?.message),A.add(`${C},${v}`));let b=m.reduce((g,p)=>g+p.models.length,0);t.log.warn(`Request failed for ${s}, trying ${b} fallback models across ${m.length} fallback stage(s)`);for(let g of m){t.log.info(`Trying ${g.name} fallback stage with ${g.models.length} models`);for(let p of g.models){let k=d(p);if(!k){t.log.warn(`Fallback model '${p}' is invalid, skipping`);continue}if(A.has(k.key))continue;A.add(k.key);let y=k.provider,E=k.model;try{if(!f.isAvailable(y,E)){t.log.warn(`Fallback model ${p} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${p}`);let D={...t.body};D.model=E;let F={...t,provider:y,body:D},q=r.providerService.getProvider(y);if(!q){t.log.warn(`Fallback provider '${y}' not found, skipping`);continue}let{requestBody:V,config:B,bypass:Y}=await Fh(D,q,n,t.headers,{req:F}),te=await Ph(V,B,q,r,Y,n,{req:F});try{q?.baseUrl&&te?.headers&&Io(y,q.baseUrl,te.headers)}catch{}let Z=await Ih(V,te,q,n,Y,{req:F});return t.log.info(`Fallback model ${p} succeeded`),f.recordSuccess(y,E),C&&v&&(Fo().promote(C,v,s,y,E),t.log.info(`Promoted fallback model ${y},${E} for ${C},${v}:${s}`),f.forceOpen(C,v,o?.message),t.log.info(`Marked original model ${C},${v} as unavailable`)),t.provider=y,t.body=D,Nh(Z,e,D)}catch(D){f.recordFailure(y,E,D.message),t.log.warn(`Fallback model ${k.key} failed: ${D.message}`),r.recordUsage?.({provider:y,model:E,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:D.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function Fh(t,e,r,n,o){let s=JSON.parse(JSON.stringify(t)),a={},c=!1;if(c=Vb(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(s);l.body?(s=l.body,a=l.config||{}):s=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let f=await l.transformRequestIn(s,e,o);f.body?(s=f.body,a={...a,...f.config}):s=f}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(s=await l.transformRequestIn(s,e,o));return{requestBody:s,config:a,bypass:c}}function Vb(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 Ph(t,e,r,n,o,s,a){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let d=n.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(o&&typeof s.auth=="function"){let d=await s.auth(t,r);if(d.body){t=d.body;let m=e.headers||{};d.config?.headers&&(m={...m,...d.config.headers},delete m.host,delete d.config.headers),e={...e,...d.config,headers:m}}else t=d}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];let f=await vh(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,n.log);if(!f.ok){let d=await f.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${f.status}): ${d}`),ot(`Error from provider(${r.name},${t.model}: ${f.status}): ${d}`,f.status,"provider_response_error")}return f}async function Ih(t,e,r,n,o,s){let a=e;if(!o&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a,s)),a}function Nh(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 ec=async t=>{t.get("/",async()=>({message:"LLMs API",version:Th})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:st().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,o)=>Gb(n,o,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:o,baseUrl:s,apiKey:a,models:c}=r.body;if(!o?.trim())throw ot("Provider name is required",400,"invalid_request");if(!s||!Kb(s))throw ot("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw ot("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw ot("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw ot(`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 ot("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 o=t.providerService.updateProvider(r.params.id,r.body);if(!o)throw ot("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw ot("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 ot("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function Kb(t){try{return new URL(t),!0}catch{return!1}}var dn=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(o=>{o==="use"?Array.isArray(r.transformer.use)&&(n.use=r.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(r.transformer[o]?.use)&&(n[o]={use:r.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],quotaToken:r.quota_token,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 o=`${r.name},${n}`,s={provider:r.name,model:n,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(n)||this.modelRoutes.set(n,s)}),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 o={...n,...r,updatedAt:new Date};return this.providers.set(e,o),r.models&&(n.models.forEach(s=>{let a=`${n.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),r.models.forEach(s=>{let a=`${n.name},${s}`,c={provider:n.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let o=`${r.name},${n}`;this.modelRoutes.delete(o),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[o,s={}]=n;r[o]=s}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 Bh(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()}var Mh=require("crypto"),ui=new Uint8Array(256),ai=ui.length;function tc(){return ai>ui.length-16&&((0,Mh.randomFillSync)(ui),ai=0),ui.slice(ai,ai+=16)}var jh=require("crypto"),rc={randomUUID:jh.randomUUID};function Yb(t,e,r){if(rc.randomUUID&&!e&&!t)return rc.randomUUID();t=t||{};let n=t.random??t.rng?.()??tc();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 o=0;o<16;++o)e[r+o]=n[o];return e}return Bh(n)}var Xt=Yb;var Lh=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Uh=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var ci=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 s=e.system.filter(a=>a.type==="text"&&a.text).map(a=>({type:"text",text:a.text,cache_control:a.cache_control}));r.push({role:"system",content:s})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(s=>{if(s.role==="user"||s.role==="assistant"){if(typeof s.content=="string"){r.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let a=s.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);a.length&&a.forEach(l=>{let f={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(f)});let c=s.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"?Uh(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(s.role==="assistant"){let a={role:"assistant",content:""},c=s.content.filter(d=>d.type==="text"&&d.text);c.length&&(a.content=c.map(d=>d.text).join(`
73
+ `));let l=s.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(a.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let f=s.content.find(d=>d.type==="thinking"&&d.signature);f&&(a.thinking={content:f.thinking,signature:f.signature}),r.push(a)}return}}});let o={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&&(o.reasoning={effort:Lh(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}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 o=await this.convertOpenAIStreamToAnthropic(e.body,r);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,r);return new Response(JSON.stringify(s),{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 o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",f=!1,d=!1,m=!1,C=new Map,v=new Map,A=0,b=0,g=0,p=!1,k=!1,y=0,E=-1,D=()=>{let B=y;return y++,B},F=B=>{if(!p)try{o.enqueue(B);let Y=new TextDecoder().decode(B);this.logger.debug({reqId:r.req.id,data:Y,type:"send data"})}catch(Y){if(Y instanceof TypeError&&Y.message.includes("Controller is already closed"))p=!0;else throw this.logger.debug({reqId:r.req.id,error:Y instanceof Error?Y.message:String(Y),type:"send data error"}),Y}},q=()=>{if(!p)try{if(E>=0){let Y={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
74
74
  data: ${JSON.stringify(Y)}
75
75
 
76
76
  `)),E=-1}c?(F(s.encode(`event: message_delta
@@ -82,14 +82,14 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
82
82
  `));let B={type:"message_stop"};F(s.encode(`event: message_stop
83
83
  data: ${JSON.stringify(B)}
84
84
 
85
- `)),o.close(),m=!0}catch(B){if(B instanceof TypeError&&B.message.includes("Controller is already closed"))m=!0;else throw B}},V=null;try{V=e.getReader();let B=new TextDecoder,Y="";for(;!m;){let{done:te,value:Z}=await V.read();if(te)break;Y+=B.decode(Z,{stream:!0});let ue=Y.split(`
86
- `);Y=ue.pop()||"";for(let he of ue){if(m||p)break;if(!he.startsWith("data:"))continue;let Ee=he.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:Ee}),Ee!=="[DONE]")try{let se=JSON.parse(Ee);if(S++,this.logger.debug({reqId:r.req.id,response:se,tppe:"Original Response"}),se.error){let G={type:"error",message:{type:"api_error",message:JSON.stringify(se.error)}};F(s.encode(`event: error
85
+ `)),o.close(),p=!0}catch(B){if(B instanceof TypeError&&B.message.includes("Controller is already closed"))p=!0;else throw B}},V=null;try{V=e.getReader();let B=new TextDecoder,Y="";for(;!p;){let{done:te,value:Z}=await V.read();if(te)break;Y+=B.decode(Z,{stream:!0});let ue=Y.split(`
86
+ `);Y=ue.pop()||"";for(let he of ue){if(p||m)break;if(!he.startsWith("data:"))continue;let Ee=he.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:Ee}),Ee!=="[DONE]")try{let se=JSON.parse(Ee);if(A++,this.logger.debug({reqId:r.req.id,response:se,tppe:"Original Response"}),se.error){let G={type:"error",message:{type:"api_error",message:JSON.stringify(se.error)}};F(s.encode(`event: error
87
87
  data: ${JSON.stringify(G)}
88
88
 
89
- `));continue}if(l=se.model||l,!h&&!m&&!p){h=!0;let G={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};F(s.encode(`event: message_start
89
+ `));continue}if(l=se.model||l,!f&&!p&&!m){f=!0;let G={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};F(s.encode(`event: message_start
90
90
  data: ${JSON.stringify(G)}
91
91
 
92
- `))}let pe=se.choices?.[0];if(se.usage&&(c?c.usage={input_tokens:(se.usage?.prompt_tokens||0)-(se.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:se.usage?.prompt_tokens_details?.cached_tokens||0}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:(se.usage?.prompt_tokens||0)-(se.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:se.usage?.prompt_tokens_details?.cached_tokens||0}}),!pe)continue;if(pe?.delta?.thinking&&!m&&!p){if(!k){let G=D(),K={type:"content_block_start",index:G,content_block:{type:"thinking",thinking:""}};F(s.encode(`event: content_block_start
92
+ `))}let pe=se.choices?.[0];if(se.usage&&(c?c.usage={input_tokens:(se.usage?.prompt_tokens||0)-(se.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:se.usage?.prompt_tokens_details?.cached_tokens||0}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:(se.usage?.prompt_tokens||0)-(se.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:se.usage?.prompt_tokens_details?.cached_tokens||0}}),!pe)continue;if(pe?.delta?.thinking&&!p&&!m){if(!k){let G=D(),K={type:"content_block_start",index:G,content_block:{type:"thinking",thinking:""}};F(s.encode(`event: content_block_start
93
93
  data: ${JSON.stringify(K)}
94
94
 
95
95
  `)),E=G,k=!0}if(pe.delta.thinking.signature){let G={type:"content_block_delta",index:E,delta:{type:"signature_delta",signature:pe.delta.thinking.signature}};F(s.encode(`event: content_block_delta
@@ -101,254 +101,254 @@ data: ${JSON.stringify(K)}
101
101
  `)),E=-1}else if(pe.delta.thinking.content){let G={type:"content_block_delta",index:E,delta:{type:"thinking_delta",thinking:pe.delta.thinking.content||""}};F(s.encode(`event: content_block_delta
102
102
  data: ${JSON.stringify(G)}
103
103
 
104
- `))}}if(pe?.delta?.content&&!m&&!p){if(_++,E>=0&&!d){let K={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
104
+ `))}}if(pe?.delta?.content&&!p&&!m){if(b++,E>=0&&!d){let K={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
105
105
  data: ${JSON.stringify(K)}
106
106
 
107
- `)),E=-1}if(!d&&!p){d=!0;let G=D(),K={type:"content_block_start",index:G,content_block:{type:"text",text:""}};F(s.encode(`event: content_block_start
107
+ `)),E=-1}if(!d&&!m){d=!0;let G=D(),K={type:"content_block_start",index:G,content_block:{type:"text",text:""}};F(s.encode(`event: content_block_start
108
108
  data: ${JSON.stringify(K)}
109
109
 
110
- `)),E=G}if(!m&&!p){let G={type:"content_block_delta",index:E,delta:{type:"text_delta",text:pe.delta.content}};F(s.encode(`event: content_block_delta
110
+ `)),E=G}if(!p&&!m){let G={type:"content_block_delta",index:E,delta:{type:"text_delta",text:pe.delta.content}};F(s.encode(`event: content_block_delta
111
111
  data: ${JSON.stringify(G)}
112
112
 
113
- `))}}if(pe?.delta?.annotations?.length&&!m&&!p){if(E>=0&&d){let G={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
113
+ `))}}if(pe?.delta?.annotations?.length&&!p&&!m){if(E>=0&&d){let G={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
114
114
  data: ${JSON.stringify(G)}
115
115
 
116
- `)),E=-1,d=!1}pe?.delta?.annotations.forEach(G=>{let K=D(),ae={type:"content_block_start",index:K,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Qt()}`,content:[{type:"web_search_result",title:G.url_citation.title,url:G.url_citation.url}]}};F(s.encode(`event: content_block_start
116
+ `)),E=-1,d=!1}pe?.delta?.annotations.forEach(G=>{let K=D(),ae={type:"content_block_start",index:K,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Xt()}`,content:[{type:"web_search_result",title:G.url_citation.title,url:G.url_citation.url}]}};F(s.encode(`event: content_block_start
117
117
  data: ${JSON.stringify(ae)}
118
118
 
119
- `));let qe={type:"content_block_stop",index:K};F(s.encode(`event: content_block_stop
120
- data: ${JSON.stringify(qe)}
119
+ `));let $e={type:"content_block_stop",index:K};F(s.encode(`event: content_block_stop
120
+ data: ${JSON.stringify($e)}
121
121
 
122
- `)),E=-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 ae=K.index??0;if(G.has(ae))continue;if(G.add(ae),!T.has(ae)){if(E>=0){let De={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
122
+ `)),E=-1})}if(pe?.delta?.tool_calls&&!p&&!m){g++;let G=new Set;for(let K of pe.delta.tool_calls){if(p)break;let ae=K.index??0;if(G.has(ae))continue;if(G.add(ae),!v.has(ae)){if(E>=0){let De={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
123
123
  data: ${JSON.stringify(De)}
124
124
 
125
- `)),E=-1}let ve=D();T.set(ae,ve);let W=K.id||`call_${Date.now()}_${ae}`,le=K.function?.name||`tool_${ae}`,ye={type:"content_block_start",index:ve,content_block:{type:"tool_use",id:W,name:le,input:{}}};F(s.encode(`event: content_block_start
125
+ `)),E=-1}let ve=D();v.set(ae,ve);let W=K.id||`call_${Date.now()}_${ae}`,le=K.function?.name||`tool_${ae}`,ye={type:"content_block_start",index:ve,content_block:{type:"tool_use",id:W,name:le,input:{}}};F(s.encode(`event: content_block_start
126
126
  data: ${JSON.stringify(ye)}
127
127
 
128
- `)),E=ve;let It={id:W,name:le,arguments:"",contentBlockIndex:ve};w.set(ae,It)}else if(K.id&&K.function?.name){let ve=w.get(ae);ve.id.startsWith("call_")&&ve.name.startsWith("tool_")&&(ve.id=K.id,ve.name=K.function.name)}if(K.function?.arguments&&!m&&!p){let ve=T.get(ae);if(ve===void 0)continue;let W=w.get(ae);W&&(W.arguments+=K.function.arguments);try{let le={type:"content_block_delta",index:ve,delta:{type:"input_json_delta",partial_json:K.function.arguments}};F(s.encode(`event: content_block_delta
128
+ `)),E=ve;let Bt={id:W,name:le,arguments:"",contentBlockIndex:ve};C.set(ae,Bt)}else if(K.id&&K.function?.name){let ve=C.get(ae);ve.id.startsWith("call_")&&ve.name.startsWith("tool_")&&(ve.id=K.id,ve.name=K.function.name)}if(K.function?.arguments&&!p&&!m){let ve=v.get(ae);if(ve===void 0)continue;let W=C.get(ae);W&&(W.arguments+=K.function.arguments);try{let le={type:"content_block_delta",index:ve,delta:{type:"input_json_delta",partial_json:K.function.arguments}};F(s.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,'\\"'),ye={type:"content_block_delta",index:ve,delta:{type:"input_json_delta",partial_json:le}};F(s.encode(`event: content_block_delta
132
132
  data: ${JSON.stringify(ye)}
133
133
 
134
- `))}catch(le){console.error(le)}}}}}if(pe?.finish_reason&&!m&&!p){if(_===0&&g===0&&console.error("Warning: No content in the stream response!"),E>=0){let G={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
134
+ `))}catch(le){console.error(le)}}}}}if(pe?.finish_reason&&!p&&!m){if(b===0&&g===0&&console.error("Warning: No content in the stream response!"),E>=0){let G={type:"content_block_stop",index:E};F(s.encode(`event: content_block_stop
135
135
  data: ${JSON.stringify(G)}
136
136
 
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"}[pe.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:(se.usage?.prompt_tokens||0)-(se.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:se.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(se){this.logger?.error(`parseError: ${se.name} message: ${se.message} stack: ${se.stack} data: ${Ee}`)}}}$()}catch(B){if(!m)try{o.error(B)}catch(Y){console.error(Y)}}finally{if(V)try{V.releaseLock()}catch(B){console.error(B)}}},cancel:o=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${o}`)}})}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 o=[];if(n.message.annotations){let a=`srvtoolu_${Qt()}`;o.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:a,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&o.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(a=>{let c={};try{let l=a.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:a.function.arguments||""}}o.push({type:"tool_use",id:a.id,name:a.function.name,input:c})}),n.message?.thinking?.content&&o.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let s={id:e.id,type:"message",role:"assistant",model:e.model,content:o,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:s},"Conversion complete, final Anthropic response"),s}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Ln={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function $b(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(Ln).includes(n)?n:Ln.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let o=n.toUpperCase();e.anyOf.push({type:Object.values(Ln).includes(o)?o:Ln.TYPE_UNSPECIFIED})}}}function Fo(t){let e={},r=["items"],n=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&$b(t.type,e);for(let[a,c]of Object.entries(t))if(c!=null)if(a=="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(Ln).includes(l)?l:Ln.TYPE_UNSPECIFIED}else if(r.includes(a))e[a]=Fo(c);else if(n.includes(a)){let l=[];for(let h of c){if(h.type=="null"){e.nullable=!0;continue}l.push(Fo(h))}e[a]=l}else if(o.includes(a)){let l={};for(let[h,d]of Object.entries(c))l[h]=Fo(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function zb(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=Fo(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Fo(e.response));return t}function si(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(zb({functionDeclarations:r})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let o=[],s=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 d=[];if(typeof l.content=="string"){let p={text:l.content};l?.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),d.push(p)}else Array.isArray(l.content)?d.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?d.push({text:l.content.text}):d.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&d.push(...l.tool_calls.map((p,w)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:w===0&&l.thinking?.signature?l.thinking?.signature:void 0}))),d.length===0&&d.push({text:""}),o.push({role:h,parts:d}),h==="model"&&l.tool_calls){let p=l.tool_calls.map(w=>{let T=s.find(S=>S.tool_call_id===w.id);return{functionResponse:{name:w?.function?.name,response:{result:T?.content}}}});o.push({role:"user",parts:p})}});let a={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],h,d=t.reasoning.max_tokens;typeof d<"u"&&(d>=l[0]&&d<=l[1]?h=d:d<l[0]?h=l[0]:d>l[1]&&(h=l[1]),a.thinkingConfig.thinkingBudget=h)}let c={contents:o,tools:e.length?e:void 0,generationConfig:a};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 ii(t){let e=t.contents,r=t.tools,n=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:o,temperature:s,stream:a,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(d=>({type:"text",text:d.text||""}))||[]}):h.role==="model"&&l.messages.push({role:"assistant",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(d=>{l.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),l}async function ai(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let o="",s="",a=n.candidates[0]?.content?.parts||[],c=[];for(let p of a)p.text&&p.thought===!0?o+=p.text:c.push(p);s=a.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
- `)||"",d={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,...s&&{thinking:{content:o||"(no content)",signature:s}}}}],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(d),{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,o=new TextEncoder,s=!1,a=!1,c=!1,l="",h=0,d=-1,p=new ReadableStream({async start(w){let T=async(g,m)=>{if(g.startsWith("data: ")){let k=g.slice(6).trim();if(k){r?.debug({chunkStr:k},`${e} chunk:`);try{let y=JSON.parse(k);if(!y.candidates||!y.candidates[0]){r?.debug({chunkStr:k},"Invalid chunk structure");return}let E=y.candidates[0],D=E.content?.parts||[];D.filter(B=>B.text&&B.thought===!0).forEach(B=>{c||(c=!0);let Y={choices:[{delta:{role:"assistant",content:null,thinking:{content:B.text}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
137
+ `)),E=-1}p||(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:(se.usage?.prompt_tokens||0)-(se.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:se.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(se){this.logger?.error(`parseError: ${se.name} message: ${se.message} stack: ${se.stack} data: ${Ee}`)}}}q()}catch(B){if(!p)try{o.error(B)}catch(Y){console.error(Y)}}finally{if(V)try{V.releaseLock()}catch(B){console.error(B)}}},cancel:o=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${o}`)}})}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 o=[];if(n.message.annotations){let a=`srvtoolu_${Xt()}`;o.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:a,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&o.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(a=>{let c={};try{let l=a.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:a.function.arguments||""}}o.push({type:"tool_use",id:a.id,name:a.function.name,input:c})}),n.message?.thinking?.content&&o.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let s={id:e.id,type:"message",role:"assistant",model:e.model,content:o,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:s},"Conversion complete, final Anthropic response"),s}catch{throw ot(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var $n={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function Qb(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($n).includes(n)?n:$n.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let o=n.toUpperCase();e.anyOf.push({type:Object.values($n).includes(o)?o:$n.TYPE_UNSPECIFIED})}}}function No(t){let e={},r=["items"],n=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&Qb(t.type,e);for(let[a,c]of Object.entries(t))if(c!=null)if(a=="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($n).includes(l)?l:$n.TYPE_UNSPECIFIED}else if(r.includes(a))e[a]=No(c);else if(n.includes(a)){let l=[];for(let f of c){if(f.type=="null"){e.nullable=!0;continue}l.push(No(f))}e[a]=l}else if(o.includes(a)){let l={};for(let[f,d]of Object.entries(c))l[f]=No(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function Xb(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=No(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=No(e.response));return t}function li(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(Xb({functionDeclarations:r})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let o=[],s=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let f;l.role==="assistant"?f="model":(["user","system"].includes(l.role),f="user");let d=[];if(typeof l.content=="string"){let m={text:l.content};l?.thinking?.signature&&(m.thoughtSignature=l.thinking.signature),d.push(m)}else Array.isArray(l.content)?d.push(...l.content.map(m=>{if(m.type==="text")return{text:m.text||""};if(m.type==="image_url")return m.image_url.url.startsWith("http")?{file_data:{mime_type:m.media_type,file_uri:m.image_url.url}}:{inlineData:{mime_type:m.media_type,data:m.image_url.url?.split(",")?.pop()||m.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?d.push({text:l.content.text}):d.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&d.push(...l.tool_calls.map((m,C)=>({functionCall:{id:m.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:m.function.name,args:JSON.parse(m.function.arguments||"{}")},thoughtSignature:C===0&&l.thinking?.signature?l.thinking?.signature:void 0}))),d.length===0&&d.push({text:""}),o.push({role:f,parts:d}),f==="model"&&l.tool_calls){let m=l.tool_calls.map(C=>{let v=s.find(A=>A.tool_call_id===C.id);return{functionResponse:{name:C?.function?.name,response:{result:v?.content}}}});o.push({role:"user",parts:m})}});let a={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],f,d=t.reasoning.max_tokens;typeof d<"u"&&(d>=l[0]&&d<=l[1]?f=d:d<l[0]?f=l[0]:d>l[1]&&(f=l[1]),a.thinkingConfig.thinkingBudget=f)}let c={contents:o,tools:e.length?e:void 0,generationConfig:a};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 di(t){let e=t.contents,r=t.tools,n=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:o,temperature:s,stream:a,tool_choice:c};return Array.isArray(e)&&e.forEach(f=>{typeof f=="string"?l.messages.push({role:"user",content:f}):typeof f.text=="string"?l.messages.push({role:"user",content:f.text||null}):f.role==="user"?l.messages.push({role:"user",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):f.role==="model"&&l.messages.push({role:"assistant",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(f=>{Array.isArray(f.functionDeclarations)&&f.functionDeclarations.forEach(d=>{l.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),l}async function fi(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let o="",s="",a=n.candidates[0]?.content?.parts||[],c=[];for(let m of a)m.text&&m.thought===!0?o+=m.text:c.push(m);s=a.find(m=>m.thoughtSignature)?.thoughtSignature;let l=c?.filter(m=>m.functionCall)?.map(m=>({id:m.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:m.functionCall?.name,arguments:JSON.stringify(m.functionCall?.args||{})}}))||[],f=c?.filter(m=>m.text)?.map(m=>m.text)?.join(`
138
+ `)||"",d={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:f,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:o||"(no content)",signature:s}}}}],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(d),{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,o=new TextEncoder,s=!1,a=!1,c=!1,l="",f=0,d=-1,m=new ReadableStream({async start(C){let v=async(g,p)=>{if(g.startsWith("data: ")){let k=g.slice(6).trim();if(k){r?.debug({chunkStr:k},`${e} chunk:`);try{let y=JSON.parse(k);if(!y.candidates||!y.candidates[0]){r?.debug({chunkStr:k},"Invalid chunk structure");return}let E=y.candidates[0],D=E.content?.parts||[];D.filter(B=>B.text&&B.thought===!0).forEach(B=>{c||(c=!0);let Y={choices:[{delta:{role:"assistant",content:null,thinking:{content:B.text}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};p.enqueue(o.encode(`data: ${JSON.stringify(Y)}
139
139
 
140
- `))});let F=D.find(B=>B.thoughtSignature)?.thoughtSignature;if(F&&!s){if(!c){let Y={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:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
140
+ `))});let F=D.find(B=>B.thoughtSignature)?.thoughtSignature;if(F&&!s){if(!c){let Y={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};p.enqueue(o.encode(`data: ${JSON.stringify(Y)}
141
141
 
142
- `))}let B={choices:[{delta:{role:"assistant",content:null,thinking:{signature:F}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(o.encode(`data: ${JSON.stringify(B)}
142
+ `))}let B={choices:[{delta:{role:"assistant",content:null,thinking:{signature:F}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(p.enqueue(o.encode(`data: ${JSON.stringify(B)}
143
143
 
144
- `)),s=!0,h++,l){let Y={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
144
+ `)),s=!0,f++,l){let Y={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};p.enqueue(o.encode(`data: ${JSON.stringify(Y)}
145
145
 
146
- `)),l="",a||(a=!0)}}let $=D.filter(B=>B.functionCall).map(B=>({id:B.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:B.functionCall?.name,arguments:JSON.stringify(B.functionCall?.args||{})}})),V=D.filter(B=>B.text&&B.thought!==!0).map(B=>B.text).join(`
147
- `);if(!V&&s&&!a){let B={choices:[{delta:{role:"assistant",content:"(no content)"},index:h,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(B)}
146
+ `)),l="",a||(a=!0)}}let q=D.filter(B=>B.functionCall).map(B=>({id:B.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:B.functionCall?.name,arguments:JSON.stringify(B.functionCall?.args||{})}})),V=D.filter(B=>B.text&&B.thought!==!0).map(B=>B.text).join(`
147
+ `);if(!V&&s&&!a){let B={choices:[{delta:{role:"assistant",content:"(no content)"},index:f,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};p.enqueue(o.encode(`data: ${JSON.stringify(B)}
148
148
 
149
- `)),a||(a=!0)}if(c&&V&&!s)if(y.modelVersion.includes("3")){l+=V;return}else{let B={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:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(B)}
149
+ `)),a||(a=!0)}if(c&&V&&!s)if(y.modelVersion.includes("3")){l+=V;return}else{let B={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};p.enqueue(o.encode(`data: ${JSON.stringify(B)}
150
150
 
151
- `)),s=!0}if(V){l||h++;let B={choices:[{delta:{role:"assistant",content:V},finish_reason:E.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:y.usageMetadata?.candidatesTokenCount||0,prompt_tokens:y.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:y.usageMetadata?.cachedContentTokenCount||0},total_tokens:y.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:y.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(B.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((Y,te)=>{let Z=E?.groundingMetadata?.groundingSupports?.filter(ue=>ue.groundingChunkIndices?.includes(te));return{type:"url_citation",url_citation:{url:Y?.web?.uri||"",title:Y?.web?.title||"",content:Z?.[0]?.segment?.text||"",start_index:Z?.[0]?.segment?.startIndex||0,end_index:Z?.[0]?.segment?.endIndex||0}}})),m.enqueue(o.encode(`data: ${JSON.stringify(B)}
151
+ `)),s=!0}if(V){l||f++;let B={choices:[{delta:{role:"assistant",content:V},finish_reason:E.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:y.usageMetadata?.candidatesTokenCount||0,prompt_tokens:y.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:y.usageMetadata?.cachedContentTokenCount||0},total_tokens:y.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:y.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(B.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((Y,te)=>{let Z=E?.groundingMetadata?.groundingSupports?.filter(ue=>ue.groundingChunkIndices?.includes(te));return{type:"url_citation",url_citation:{url:Y?.web?.uri||"",title:Y?.web?.title||"",content:Z?.[0]?.segment?.text||"",start_index:Z?.[0]?.segment?.startIndex||0,end_index:Z?.[0]?.segment?.endIndex||0}}})),p.enqueue(o.encode(`data: ${JSON.stringify(B)}
152
152
 
153
- `)),!a&&V&&(a=!0)}$.length>0&&($.forEach(B=>{h++,d++;let Y={choices:[{delta:{role:"assistant",tool_calls:[{...B,index:d}]},finish_reason:E.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:y.usageMetadata?.candidatesTokenCount||0,prompt_tokens:y.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:y.usageMetadata?.cachedContentTokenCount||0},total_tokens:y.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:y.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(Y.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((te,Z)=>{let ue=E?.groundingMetadata?.groundingSupports?.filter(he=>he.groundingChunkIndices?.includes(Z));return{type:"url_citation",url_citation:{url:te?.web?.uri||"",title:te?.web?.title||"",content:ue?.[0]?.segment?.text||"",start_index:ue?.[0]?.segment?.startIndex||0,end_index:ue?.[0]?.segment?.endIndex||0}}})),m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
153
+ `)),!a&&V&&(a=!0)}q.length>0&&(q.forEach(B=>{f++,d++;let Y={choices:[{delta:{role:"assistant",tool_calls:[{...B,index:d}]},finish_reason:E.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:y.usageMetadata?.candidatesTokenCount||0,prompt_tokens:y.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:y.usageMetadata?.cachedContentTokenCount||0},total_tokens:y.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:y.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(Y.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((te,Z)=>{let ue=E?.groundingMetadata?.groundingSupports?.filter(he=>he.groundingChunkIndices?.includes(Z));return{type:"url_citation",url_citation:{url:te?.web?.uri||"",title:te?.web?.title||"",content:ue?.[0]?.segment?.text||"",start_index:ue?.[0]?.segment?.startIndex||0,end_index:ue?.[0]?.segment?.endIndex||0}}})),p.enqueue(o.encode(`data: ${JSON.stringify(Y)}
154
154
 
155
- `))}),!a&&V&&(a=!0))}catch(y){r?.error(`Error parsing ${e} stream chunk`,k,y.message)}}}},S=t.body.getReader(),_="";try{for(;;){let{done:g,value:m}=await S.read();if(g){_&&await T(_,w);break}_+=n.decode(m,{stream:!0});let k=_.split(`
156
- `);_=k.pop()||"";for(let y of k)await T(y,w)}}catch(g){w.error(g)}finally{w.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var ui=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:si(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=ii;async transformResponseOut(e){return ai(e,this.name,this.logger)}};async function fk(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>je(gd(),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
+ `))}),!a&&V&&(a=!0))}catch(y){r?.error(`Error parsing ${e} stream chunk`,k,y.message)}}}},A=t.body.getReader(),b="";try{for(;;){let{done:g,value:p}=await A.read();if(g){b&&await v(b,C);break}b+=n.decode(p,{stream:!0});let k=b.split(`
156
+ `);b=k.pop()||"";for(let y of k)await v(y,C)}}catch(g){C.error(g)}finally{C.close()}}});return new Response(m,{status:t.status,statusText:t.statusText,headers:t.headers})}}var hi=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:li(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=di;async transformResponseOut(e){return fi(e,this.name,this.logger)}};async function wk(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Me(wd(),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 ka=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=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(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}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 s=await fk();return{body:si(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return ii(e)}async transformResponseOut(e){return ai(e,this.name)}};var va=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,o=r.thinking?.signature;n&&typeof n=="string"&&n.trim()&&(r.reasoning_content=n,o&&(r.reasoning_content_signature=o)),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,o="",s=!1,a="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(w,T,S)=>{let _=w.split(`
160
- `);for(let g of _)g.trim()&&T.enqueue(S.encode(g+`
161
- `))},p=(w,T)=>{let{controller:S,encoder:_}=T;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let g=JSON.parse(w.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){T.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)}
159
+ 3. Use Google Cloud environment with default service account`)}}var xa=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=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(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}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 s=await wk();return{body:li(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return di(e)}async transformResponseOut(e){return fi(e,this.name)}};var Oa=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,o=r.thinking?.signature;n&&typeof n=="string"&&n.trim()&&(r.reasoning_content=n,o&&(r.reasoning_content_signature=o)),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,o="",s=!1,a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(C,v,A)=>{let b=C.split(`
160
+ `);for(let g of b)g.trim()&&v.enqueue(A.encode(g+`
161
+ `))},m=(C,v)=>{let{controller:A,encoder:b}=v;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let g=JSON.parse(C.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){v.appendReasoningContent(g.choices[0].delta.reasoning_content);let p={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete p.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(p)}
162
162
 
163
- `;S.enqueue(_.encode(k));return}if(g.choices?.[0]?.delta?.content&&T.reasoningContent()&&!T.isReasoningComplete()){T.setReasoningComplete(!0);let m=Date.now().toString(),k=g.choices[0].delta.content,y={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:T.reasoningContent(),signature:m}}}]};delete y.choices[0].delta.reasoning_content;let E=`data: ${JSON.stringify(y)}
163
+ `;A.enqueue(b.encode(k));return}if(g.choices?.[0]?.delta?.content&&v.reasoningContent()&&!v.isReasoningComplete()){v.setReasoningComplete(!0);let p=Date.now().toString(),k=g.choices[0].delta.content,y={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:v.reasoningContent(),signature:p}}}]};delete y.choices[0].delta.reasoning_content;let E=`data: ${JSON.stringify(y)}
164
164
 
165
- `;S.enqueue(_.encode(E));let D={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:k}}]};delete D.choices[0].delta.reasoning_content;let F=`data: ${JSON.stringify(D)}
165
+ `;A.enqueue(b.encode(E));let D={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:k}}]};delete D.choices[0].delta.reasoning_content;let F=`data: ${JSON.stringify(D)}
166
166
 
167
- `;S.enqueue(_.encode(F));return}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){let m=`data: ${JSON.stringify(g)}
167
+ `;A.enqueue(b.encode(F));return}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){let p=`data: ${JSON.stringify(g)}
168
168
 
169
- `;S.enqueue(_.encode(m))}}catch{S.enqueue(_.encode(w+`
170
- `))}else S.enqueue(_.encode(w+`
171
- `))};try{for(;;){let{done:w,value:T}=await h.read();if(w){a.trim()&&d(a,l,n);break}let S=r.decode(T,{stream:!0});a+=S;let _=a.split(`
172
- `);a=_.pop()||"";for(let g of _)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>o,appendReasoningContent:m=>o+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
173
- `))}}}catch(w){console.error("Stream error:",w),l.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}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 Ta=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.
169
+ `;A.enqueue(b.encode(p))}}catch{A.enqueue(b.encode(C+`
170
+ `))}else A.enqueue(b.encode(C+`
171
+ `))};try{for(;;){let{done:C,value:v}=await f.read();if(C){a.trim()&&d(a,l,n);break}let A=r.decode(v,{stream:!0});a+=A;let b=a.split(`
172
+ `);a=b.pop()||"";for(let g of b)if(g.trim())try{m(g,{controller:l,encoder:n,reasoningContent:()=>o,appendReasoningContent:p=>o+=p,isReasoningComplete:()=>s,setReasoningComplete:p=>s=p})}catch(p){console.error("Error processing line:",g,p),l.enqueue(n.encode(g+`
173
+ `))}}}catch(C){console.error("Stream error:",C),l.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}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.
174
174
  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.
175
175
  Examples:
176
176
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
177
- 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],o=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=o.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,o=-1,s="",a="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(w,T,S)=>{let _=w.split(`
178
- `);for(let g of _)g.trim()&&T.enqueue(S.encode(g+`
179
- `))},p=(w,T)=>{let{controller:S,encoder:_,exitToolIndex:g,setExitToolIndex:m,appendExitToolResponse:k}=T;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let y=JSON.parse(w.slice(6));if(y.choices[0]?.delta?.tool_calls?.length){let E=y.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 D=JSON.parse(T.exitToolResponse());y.choices=[{delta:{role:"assistant",content:D.response||""}}];let F=`data: ${JSON.stringify(y)}
180
-
181
- `;S.enqueue(_.encode(F))}catch{}return}}if(y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let E=`data: ${JSON.stringify(y)}
182
-
183
- `;S.enqueue(_.encode(E))}}catch{S.enqueue(_.encode(w+`
184
- `))}else S.enqueue(_.encode(w+`
185
- `))};try{for(;;){let{done:w,value:T}=await h.read();if(w){a.trim()&&d(a,l,n);break}let S=r.decode(T,{stream:!0});a+=S;let _=a.split(`
186
- `);a=_.pop()||"";for(let g of _)if(g.trim())try{p(g,{controller:l,encoder:n,exitToolIndex:()=>o,setExitToolIndex:m=>o=m,exitToolResponse:()=>s,appendExitToolResponse:m=>s+=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
187
- `))}}}catch(w){console.error("Stream error:",w),l.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}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 Da=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,o=!1,s="",a=!1,c=!1,l="",h=new ReadableStream({async start(d){let p=e.body.getReader(),w=(S,_,g)=>{let m=S.split(`
188
- `);for(let k of m)k.trim()&&_.enqueue(g.encode(k+`
189
- `))},T=(S,_)=>{let{controller:g,encoder:m}=_;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let k=S.slice(6);try{let y=JSON.parse(k);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:c},"usage"),y.choices[0].finish_reason=c?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"){g.enqueue(m.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
190
-
191
- `));return}y.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0);let E=y.choices?.[0]?.delta?.reasoning||y.choices?.[0]?.delta?.reasoning_content;if(E){_.appendReasoningContent(E);let B={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:E}}}]};B.choices?.[0]?.delta&&(delete B.choices[0].delta.reasoning,delete B.choices[0].delta.reasoning_content);let Y=`data: ${JSON.stringify(B)}
192
-
193
- `;g.enqueue(m.encode(Y));return}if(y.choices?.[0]?.delta?.content&&_.reasoningContent()&&!_.isReasoningComplete()){_.setReasoningComplete(!0);let B=Date.now().toString(),Y=y.choices[0].delta.content,te={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:_.reasoningContent(),signature:B}}}]};te.choices?.[0]?.delta&&delete te.choices[0].delta.reasoning;let Z=`data: ${JSON.stringify(te)}
194
-
195
- `;g.enqueue(m.encode(Z));let ue={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:Y}}]};ue.choices?.[0]?.delta&&(delete ue.choices[0].delta.reasoning,delete ue.choices[0].delta.reasoning_content);let he=`data: ${JSON.stringify(ue)}
196
-
197
- `;g.enqueue(m.encode(he));return}y.choices?.[0]?.delta?.reasoning&&delete y.choices[0].delta.reasoning,y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(y.choices?.[0]?.delta?.tool_calls[0].id,10))&&y.choices?.[0]?.delta?.tool_calls.forEach(B=>{B.id=`call_${Qt()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0);let D=y.choices?.[0]?.delta,F=D&&Object.keys(D).length>0,$=y.choices?.[0]?.finish_reason,V=y.usage;if(F||$||V){let B=`data: ${JSON.stringify(y)}
198
-
199
- `;g.enqueue(m.encode(B))}}catch{g.enqueue(m.encode(S+`
200
- `))}}else g.enqueue(m.encode(S+`
201
- `))};try{for(;;){let{done:S,value:_}=await p.read();if(S){l.trim()&&w(l,d,n);break}if(!_||_.length===0)continue;let g;try{g=r.decode(_,{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(`
202
- `);l=k.pop()||"";for(let y of k)if(y.trim())try{T(y,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",y,E),d.enqueue(n.encode(y+`
203
- `))}continue}let m=l.split(`
204
- `);l=m.pop()||"";for(let k of m)if(k.trim())try{T(k,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:y=>o=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",k,y),d.enqueue(n.encode(k+`
205
- `))}}}catch(S){console.error("Stream error:",S),d.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}d.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 Ra=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 xa=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,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(h){let d=e.body.getReader(),p=(T,S,_)=>{let g=T.split(`
206
- `);for(let m of g)m.trim()&&S.enqueue(_.encode(m+`
207
- `))},w=(T,S)=>{let{controller:_,encoder:g}=S;if(T.startsWith("data: ")&&T.trim()!=="data: [DONE]"){let m=T.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_${Qt()}`}),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 y=`data: ${JSON.stringify(k)}
208
-
209
- `;_.enqueue(g.encode(y))}catch{_.enqueue(g.encode(T+`
210
- `))}}else _.enqueue(g.encode(T+`
211
- `))};try{for(;;){let{done:T,value:S}=await d.read();if(T){c.trim()&&p(c,h,n);break}if(!S||S.length===0)continue;let _;try{_=r.decode(S,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(_.length===0)continue;if(c+=_,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=c.split(`
212
- `);c=m.pop()||"";for(let k of m)if(k.trim())try{w(k,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:y=>o=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",k,y),h.enqueue(n.encode(k+`
177
+ 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],o=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=o.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,o=-1,s="",a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(C,v,A)=>{let b=C.split(`
178
+ `);for(let g of b)g.trim()&&v.enqueue(A.encode(g+`
179
+ `))},m=(C,v)=>{let{controller:A,encoder:b,exitToolIndex:g,setExitToolIndex:p,appendExitToolResponse:k}=v;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let y=JSON.parse(C.slice(6));if(y.choices[0]?.delta?.tool_calls?.length){let E=y.choices[0].delta.tool_calls[0];if(E.function?.name==="ExitTool"){p(E.index);return}else if(g()>-1&&E.index===g()&&E.function.arguments){k(E.function.arguments);try{let D=JSON.parse(v.exitToolResponse());y.choices=[{delta:{role:"assistant",content:D.response||""}}];let F=`data: ${JSON.stringify(y)}
180
+
181
+ `;A.enqueue(b.encode(F))}catch{}return}}if(y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let E=`data: ${JSON.stringify(y)}
182
+
183
+ `;A.enqueue(b.encode(E))}}catch{A.enqueue(b.encode(C+`
184
+ `))}else A.enqueue(b.encode(C+`
185
+ `))};try{for(;;){let{done:C,value:v}=await f.read();if(C){a.trim()&&d(a,l,n);break}let A=r.decode(v,{stream:!0});a+=A;let b=a.split(`
186
+ `);a=b.pop()||"";for(let g of b)if(g.trim())try{m(g,{controller:l,encoder:n,exitToolIndex:()=>o,setExitToolIndex:p=>o=p,exitToolResponse:()=>s,appendExitToolResponse:p=>s+=p})}catch(p){console.error("Error processing line:",g,p),l.enqueue(n.encode(g+`
187
+ `))}}}catch(C){console.error("Stream error:",C),l.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}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 Pa=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,o=!1,s="",a=!1,c=!1,l="",f=new ReadableStream({async start(d){let m=e.body.getReader(),C=(A,b,g)=>{let p=A.split(`
188
+ `);for(let k of p)k.trim()&&b.enqueue(g.encode(k+`
189
+ `))},v=(A,b)=>{let{controller:g,encoder:p}=b;if(A.startsWith("data: ")&&A.trim()!=="data: [DONE]"){let k=A.slice(6);try{let y=JSON.parse(k);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:c},"usage"),y.choices[0].finish_reason=c?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"){g.enqueue(p.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
190
+
191
+ `));return}y.choices?.[0]?.delta?.content&&!b.hasTextContent()&&b.setHasTextContent(!0);let E=y.choices?.[0]?.delta?.reasoning||y.choices?.[0]?.delta?.reasoning_content;if(E){b.appendReasoningContent(E);let B={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:E}}}]};B.choices?.[0]?.delta&&(delete B.choices[0].delta.reasoning,delete B.choices[0].delta.reasoning_content);let Y=`data: ${JSON.stringify(B)}
192
+
193
+ `;g.enqueue(p.encode(Y));return}if(y.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let B=Date.now().toString(),Y=y.choices[0].delta.content,te={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:B}}}]};te.choices?.[0]?.delta&&delete te.choices[0].delta.reasoning;let Z=`data: ${JSON.stringify(te)}
194
+
195
+ `;g.enqueue(p.encode(Z));let ue={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:Y}}]};ue.choices?.[0]?.delta&&(delete ue.choices[0].delta.reasoning,delete ue.choices[0].delta.reasoning_content);let he=`data: ${JSON.stringify(ue)}
196
+
197
+ `;g.enqueue(p.encode(he));return}y.choices?.[0]?.delta?.reasoning&&delete y.choices[0].delta.reasoning,y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(y.choices?.[0]?.delta?.tool_calls[0].id,10))&&y.choices?.[0]?.delta?.tool_calls.forEach(B=>{B.id=`call_${Xt()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0);let D=y.choices?.[0]?.delta,F=D&&Object.keys(D).length>0,q=y.choices?.[0]?.finish_reason,V=y.usage;if(F||q||V){let B=`data: ${JSON.stringify(y)}
198
+
199
+ `;g.enqueue(p.encode(B))}}catch{g.enqueue(p.encode(A+`
200
+ `))}}else g.enqueue(p.encode(A+`
201
+ `))};try{for(;;){let{done:A,value:b}=await m.read();if(A){l.trim()&&C(l,d,n);break}if(!b||b.length===0)continue;let g;try{g=r.decode(b,{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(`
202
+ `);l=k.pop()||"";for(let y of k)if(y.trim())try{v(y,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",y,E),d.enqueue(n.encode(y+`
203
+ `))}continue}let p=l.split(`
204
+ `);l=p.pop()||"";for(let k of p)if(k.trim())try{v(k,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:y=>o=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",k,y),d.enqueue(n.encode(k+`
205
+ `))}}}catch(A){console.error("Stream error:",A),d.error(A)}finally{try{m.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}d.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 Ia=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 Na=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,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(f){let d=e.body.getReader(),m=(v,A,b)=>{let g=v.split(`
206
+ `);for(let p of g)p.trim()&&A.enqueue(b.encode(p+`
207
+ `))},C=(v,A)=>{let{controller:b,encoder:g}=A;if(v.startsWith("data: ")&&v.trim()!=="data: [DONE]"){let p=v.slice(6);try{let k=JSON.parse(p);if(k.error)throw new Error(JSON.stringify(k));k.choices?.[0]?.delta?.content&&!A.hasTextContent()&&A.setHasTextContent(!0),k.choices?.[0]?.delta?.tool_calls?.length&&k.choices?.[0]?.delta?.tool_calls.forEach(E=>{E.id=`call_${Xt()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&A.hasTextContent()&&(typeof k.choices[0].index=="number"?k.choices[0].index+=1:k.choices[0].index=1);let y=`data: ${JSON.stringify(k)}
208
+
209
+ `;b.enqueue(g.encode(y))}catch{b.enqueue(g.encode(v+`
210
+ `))}}else b.enqueue(g.encode(v+`
211
+ `))};try{for(;;){let{done:v,value:A}=await d.read();if(v){c.trim()&&m(c,f,n);break}if(!A||A.length===0)continue;let b;try{b=r.decode(A,{stream:!0})}catch(p){console.warn("Failed to decode chunk",p);continue}if(b.length===0)continue;if(c+=b,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let p=c.split(`
212
+ `);c=p.pop()||"";for(let k of p)if(k.trim())try{C(k,{controller:f,encoder:n,hasTextContent:()=>o,setHasTextContent:y=>o=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",k,y),f.enqueue(n.encode(k+`
213
213
  `))}continue}let g=c.split(`
214
- `);c=g.pop()||"";for(let m of g)if(m.trim())try{w(m,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:k=>o=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",m,k),h.enqueue(n.encode(m+`
215
- `))}}}catch(T){console.error("Stream error:",T),h.error(T)}finally{try{d.releaseLock()}catch(T){console.error("Error releasing reader lock:",T)}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 Oa=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 Gy=je(Hu());var Tr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function My(t){return/^[0-9A-Fa-f]$/.test(t)}function Kr(t){return t>="0"&&t<="9"}function Uy(t){return t>=" "}function cs(t){return`,:[]/{}()
216
- +`.includes(t)}function yd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function _d(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var bd=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Cd=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function wd(t){return`,[]/{}
217
- +`.includes(t)}function Ed(t){return ls(t)||hk.test(t)}var hk=/^[[{\w-]$/;function qy(t){return t===`
218
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Vr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function $y(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function zy(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function ls(t){return Ad(t)||Fa(t)}function Ad(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Sd(t){return t==='"'}function Fa(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function kd(t){return t==="'"}function fo(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 Ft(t,e){let r=t.length;if(!Vr(t,r-1))return t+e;for(;Vr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function Hy(t,e,r){return t.substring(0,e)+t.substring(e+r)}function Wy(t){return/[,\n][ \t\r]*$/.test(t)}var pk={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},mk={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
219
- `,r:"\r",t:" "};function vd(t){let e=0,r="";h(["```","[```","{```"]),s()||he(),h(["```","```]","```}"]);let o=p(",");for(o&&a(),Ed(t[e])&&Wy(r)?(o||(r=Ft(r,",")),m()):o&&(r=fo(r,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return r;ue();function s(){a();let G=_()||g()||k()||E()||D()||$(!1)||V();return a(),G}function a(){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?Vr:$y,ae="";for(;;)if(K(t,e))ae+=t[e],e++;else if(zy(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&&!gk(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
220
- `;)e++;return!0}return!1}function h(G){if(d(G)){if(yd(t[e]))for(;e<t.length&&_d(t[e]);)e++;return a(),!0}return!1}function d(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 w(G){return t[e]===G?(e++,!0):!1}function T(){return w("\\")}function S(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),w(","),!0):!1}function _(){if(t[e]==="{"){r+="{",e++,a(),w(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="}";){let K;if(G?(K=!0,G=!1):(K=p(","),K||(r=Ft(r,",")),a()),S(),!(k()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=fo(r,","):Ee();break}a();let qe=p(":"),ve=e>=t.length;qe||(Ed(t[e])||ve?r=Ft(r,":"):se()),s()||(qe||ve?r+="null":se())}return t[e]==="}"?(r+="}",e++):r=Ft(r,"}"),!0}return!1}function g(){if(t[e]==="["){r+="[",e++,a(),w(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Ft(r,",")),S(),!s()){r=fo(r,",");break}return t[e]==="]"?(r+="]",e++):r=Ft(r,"]"),!0}return!1}function m(){let G=!0,K=!0;for(;K;)G?G=!1:p(",")||(r=Ft(r,",")),K=s();K||(r=fo(r,",")),r=`[
214
+ `);c=g.pop()||"";for(let p of g)if(p.trim())try{C(p,{controller:f,encoder:n,hasTextContent:()=>o,setHasTextContent:k=>o=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",p,k),f.enqueue(n.encode(p+`
215
+ `))}}}catch(v){console.error("Stream error:",v),f.error(v)}finally{try{d.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}f.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 Ba=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 Zy=Me(Vu());var Dr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function Gy(t){return/^[0-9A-Fa-f]$/.test(t)}function Yr(t){return t>="0"&&t<="9"}function Jy(t){return t>=" "}function fs(t){return`,:[]/{}()
216
+ +`.includes(t)}function Ed(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Ad(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Sd=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,kd=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function vd(t){return`,[]/{}
217
+ +`.includes(t)}function Td(t){return hs(t)||Ek.test(t)}var Ek=/^[[{\w-]$/;function Vy(t){return t===`
218
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Kr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function Ky(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function Yy(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function hs(t){return Dd(t)||Ma(t)}function Dd(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Rd(t){return t==='"'}function Ma(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function xd(t){return t==="'"}function mo(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 It(t,e){let r=t.length;if(!Kr(t,r-1))return t+e;for(;Kr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function Qy(t,e,r){return t.substring(0,e)+t.substring(e+r)}function Xy(t){return/[,\n][ \t\r]*$/.test(t)}var Ak={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Sk={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
219
+ `,r:"\r",t:" "};function Od(t){let e=0,r="";f(["```","[```","{```"]),s()||he(),f(["```","```]","```}"]);let o=m(",");for(o&&a(),Td(t[e])&&Xy(r)?(o||(r=It(r,",")),p()):o&&(r=mo(r,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return r;ue();function s(){a();let G=b()||g()||k()||E()||D()||q(!1)||V();return a(),G}function a(){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?Kr:Ky,ae="";for(;;)if(K(t,e))ae+=t[e],e++;else if(Yy(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&&!kk(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
220
+ `;)e++;return!0}return!1}function f(G){if(d(G)){if(Ed(t[e]))for(;e<t.length&&Ad(t[e]);)e++;return a(),!0}return!1}function d(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 m(G){return t[e]===G?(r+=t[e],e++,!0):!1}function C(G){return t[e]===G?(e++,!0):!1}function v(){return C("\\")}function A(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),C(","),!0):!1}function b(){if(t[e]==="{"){r+="{",e++,a(),C(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="}";){let K;if(G?(K=!0,G=!1):(K=m(","),K||(r=It(r,",")),a()),A(),!(k()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=mo(r,","):Ee();break}a();let $e=m(":"),ve=e>=t.length;$e||(Td(t[e])||ve?r=It(r,":"):se()),s()||($e||ve?r+="null":se())}return t[e]==="}"?(r+="}",e++):r=It(r,"}"),!0}return!1}function g(){if(t[e]==="["){r+="[",e++,a(),C(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:m(",")||(r=It(r,",")),A(),!s()){r=mo(r,",");break}return t[e]==="]"?(r+="]",e++):r=It(r,"]"),!0}return!1}function p(){let G=!0,K=!0;for(;K;)G?G=!1:m(",")||(r=It(r,",")),K=s();K||(r=mo(r,",")),r=`[
221
221
  ${r}
222
- ]`}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),ls(t[e])){let qe=Sd(t[e])?Sd:kd(t[e])?kd:Fa(t[e])?Fa:Ad,ve=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let ye=B(e-1);return!G&&cs(t.charAt(ye))?(e=ve,r=r.substring(0,W),k(!0)):(le=Ft(le,'"'),r+=le,!0)}if(e===K)return le=Ft(le,'"'),r+=le,!0;if(qe(t[e])){let ye=e,It=le.length;if(le+='"',e++,r+=le,a(!1),G||e>=t.length||cs(t[e])||ls(t[e])||Kr(t[e]))return y(),!0;let De=B(ye-1),Ne=t.charAt(De);if(Ne===",")return e=ve,r=r.substring(0,W),k(!1,De);if(cs(Ne))return e=ve,r=r.substring(0,W),k(!0);r=r.substring(0,W),e=ye+1,le=`${le.substring(0,It)}\\${le.substring(It)}`}else if(G&&wd(t[e])){if(t[e-1]===":"&&bd.test(t.substring(ve+1,e+2)))for(;e<t.length&&Cd.test(t[e]);)le+=t[e],e++;return le=Ft(le,'"'),r+=le,y(),!0}else if(t[e]==="\\"){let ye=t.charAt(e+1);if(mk[ye]!==void 0)le+=t.slice(e,e+2),e+=2;else if(ye==="u"){let De=2;for(;De<6&&My(t[e+De]);)De++;De===6?(le+=t.slice(e,e+6),e+=6):e+De>=t.length?e=t.length:pe()}else le+=ye,e+=2}else{let ye=t.charAt(e);ye==='"'&&t[e-1]!=="\\"?(le+=`\\${ye}`,e++):qy(ye)?(le+=pk[ye],e++):(Uy(ye)||Z(ye),le+=ye,e++)}ae&&T()}}return!1}function y(){let G=!1;for(a();t[e]==="+";){G=!0,e++,a(),r=fo(r,'"',!0);let K=r.length;k()?r=Hy(r,K,1):r=Ft(r,'"')}return G}function E(){let G=e;if(t[e]==="-"){if(e++,Y())return te(G),!0;if(!Kr(t[e]))return e=G,!1}for(;Kr(t[e]);)e++;if(t[e]==="."){if(e++,Y())return te(G),!0;if(!Kr(t[e]))return e=G,!1;for(;Kr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Y())return te(G),!0;if(!Kr(t[e]))return e=G,!1;for(;Kr(t[e]);)e++}if(!Y())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 D(){return F("true","true")||F("false","false")||F("null","null")||F("True","true")||F("False","false")||F("None","null")}function F(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function $(G){let K=e;if(yd(t[e])){for(;e<t.length&&_d(t[e]);)e++;let ae=e;for(;Vr(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!wd(t[e])&&!ls(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&bd.test(t.substring(K,e+2)))for(;e<t.length&&Cd.test(t[e]);)e++;if(e>K){for(;Vr(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 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 B(G){let K=G;for(;K>0&&Vr(t,K);)K--;return K}function Y(){return e>=t.length||cs(t[e])||Vr(t,e)}function te(G){r+=`${t.slice(G,e)}0`}function Z(G){throw new Tr(`Invalid character ${JSON.stringify(G)}`,e)}function ue(){throw new Tr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function he(){throw new Tr("Unexpected end of json string",t.length)}function Ee(){throw new Tr("Object key expected",e)}function se(){throw new Tr("Colon expected",e)}function pe(){let G=t.slice(e,e+6);throw new Tr(`Invalid unicode character "${G}"`,e)}}function gk(t,e){return t[e]==="*"&&t[e+1]==="/"}function Td(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=Gy.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let o=vd(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${r.message}. JSON5 parsing failed: ${n.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Pa=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=Td(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,o={},s=!1,a="",c=!1,l=!1,h="",d=new ReadableStream({async start(p){let w=e.body.getReader(),T=(g,m,k)=>{let y=g.split(`
223
- `);for(let E of y)E.trim()&&m.enqueue(k.encode(E+`
224
- `))},S=(g,m,k)=>{let y="";try{y=Td(o.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),y=o.arguments||""}let E={role:"assistant",tool_calls:[{function:{name:o.name,arguments:y},id:o.id,index:o.index,type:"function"}]},D={...g,choices:[{...g.choices[0],delta:E}]};D.choices[0].delta.content!==void 0&&delete D.choices[0].delta.content;let F=`data: ${JSON.stringify(D)}
222
+ ]`}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),hs(t[e])){let $e=Rd(t[e])?Rd:xd(t[e])?xd:Ma(t[e])?Ma:Dd,ve=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let ye=B(e-1);return!G&&fs(t.charAt(ye))?(e=ve,r=r.substring(0,W),k(!0)):(le=It(le,'"'),r+=le,!0)}if(e===K)return le=It(le,'"'),r+=le,!0;if($e(t[e])){let ye=e,Bt=le.length;if(le+='"',e++,r+=le,a(!1),G||e>=t.length||fs(t[e])||hs(t[e])||Yr(t[e]))return y(),!0;let De=B(ye-1),Be=t.charAt(De);if(Be===",")return e=ve,r=r.substring(0,W),k(!1,De);if(fs(Be))return e=ve,r=r.substring(0,W),k(!0);r=r.substring(0,W),e=ye+1,le=`${le.substring(0,Bt)}\\${le.substring(Bt)}`}else if(G&&vd(t[e])){if(t[e-1]===":"&&Sd.test(t.substring(ve+1,e+2)))for(;e<t.length&&kd.test(t[e]);)le+=t[e],e++;return le=It(le,'"'),r+=le,y(),!0}else if(t[e]==="\\"){let ye=t.charAt(e+1);if(Sk[ye]!==void 0)le+=t.slice(e,e+2),e+=2;else if(ye==="u"){let De=2;for(;De<6&&Gy(t[e+De]);)De++;De===6?(le+=t.slice(e,e+6),e+=6):e+De>=t.length?e=t.length:pe()}else le+=ye,e+=2}else{let ye=t.charAt(e);ye==='"'&&t[e-1]!=="\\"?(le+=`\\${ye}`,e++):Vy(ye)?(le+=Ak[ye],e++):(Jy(ye)||Z(ye),le+=ye,e++)}ae&&v()}}return!1}function y(){let G=!1;for(a();t[e]==="+";){G=!0,e++,a(),r=mo(r,'"',!0);let K=r.length;k()?r=Qy(r,K,1):r=It(r,'"')}return G}function E(){let G=e;if(t[e]==="-"){if(e++,Y())return te(G),!0;if(!Yr(t[e]))return e=G,!1}for(;Yr(t[e]);)e++;if(t[e]==="."){if(e++,Y())return te(G),!0;if(!Yr(t[e]))return e=G,!1;for(;Yr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Y())return te(G),!0;if(!Yr(t[e]))return e=G,!1;for(;Yr(t[e]);)e++}if(!Y())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 D(){return F("true","true")||F("false","false")||F("null","null")||F("True","true")||F("False","false")||F("None","null")}function F(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function q(G){let K=e;if(Ed(t[e])){for(;e<t.length&&Ad(t[e]);)e++;let ae=e;for(;Kr(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!vd(t[e])&&!hs(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&Sd.test(t.substring(K,e+2)))for(;e<t.length&&kd.test(t[e]);)e++;if(e>K){for(;Kr(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 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 B(G){let K=G;for(;K>0&&Kr(t,K);)K--;return K}function Y(){return e>=t.length||fs(t[e])||Kr(t,e)}function te(G){r+=`${t.slice(G,e)}0`}function Z(G){throw new Dr(`Invalid character ${JSON.stringify(G)}`,e)}function ue(){throw new Dr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function he(){throw new Dr("Unexpected end of json string",t.length)}function Ee(){throw new Dr("Object key expected",e)}function se(){throw new Dr("Colon expected",e)}function pe(){let G=t.slice(e,e+6);throw new Dr(`Invalid unicode character "${G}"`,e)}}function kk(t,e){return t[e]==="*"&&t[e+1]==="/"}function Fd(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=Zy.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let o=Od(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${r.message}. JSON5 parsing failed: ${n.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var ja=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=Fd(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,o={},s=!1,a="",c=!1,l=!1,f="",d=new ReadableStream({async start(m){let C=e.body.getReader(),v=(g,p,k)=>{let y=g.split(`
223
+ `);for(let E of y)E.trim()&&p.enqueue(k.encode(E+`
224
+ `))},A=(g,p,k)=>{let y="";try{y=Fd(o.arguments||"",this.logger)}catch(q){console.error(`${q.message} ${q.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),y=o.arguments||""}let E={role:"assistant",tool_calls:[{function:{name:o.name,arguments:y},id:o.id,index:o.index,type:"function"}]},D={...g,choices:[{...g.choices[0],delta:E}]};D.choices[0].delta.content!==void 0&&delete D.choices[0].delta.content;let F=`data: ${JSON.stringify(D)}
225
225
 
226
- `;m.enqueue(k.encode(F))},_=(g,m)=>{let{controller:k,encoder:y}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let E=g.slice(6);try{let D=JSON.parse(E);if(D.choices?.[0]?.delta?.tool_calls?.length){let $=D.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""},$.function?.arguments&&($.function.arguments="");let V=`data: ${JSON.stringify(D)}
226
+ `;p.enqueue(k.encode(F))},b=(g,p)=>{let{controller:k,encoder:y}=p;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let E=g.slice(6);try{let D=JSON.parse(E);if(D.choices?.[0]?.delta?.tool_calls?.length){let q=D.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:q.index,name:q.function?.name||"",id:q.id||"",arguments:q.function?.arguments||""},q.function?.arguments&&(q.function.arguments="");let V=`data: ${JSON.stringify(D)}
227
227
 
228
- `;k.enqueue(y.encode(V));return}else if(o.index===$.index){$.function?.arguments&&(o.arguments+=$.function.arguments);return}else{S(D,k,y),o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(D.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){S(D,k,y),o={};return}D.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof D.choices[0].index=="number"?D.choices[0].index+=1:D.choices[0].index=1);let F=`data: ${JSON.stringify(D)}
228
+ `;k.enqueue(y.encode(V));return}else if(o.index===q.index){q.function?.arguments&&(o.arguments+=q.function.arguments);return}else{A(D,k,y),o={index:q.index,name:q.function?.name||"",id:q.id||"",arguments:q.function?.arguments||""};return}}if(D.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){A(D,k,y),o={};return}D.choices?.[0]?.delta?.tool_calls?.length&&p.hasTextContent()&&(typeof D.choices[0].index=="number"?D.choices[0].index+=1:D.choices[0].index=1);let F=`data: ${JSON.stringify(D)}
229
229
 
230
230
  `;k.enqueue(y.encode(F))}catch{k.enqueue(y.encode(g+`
231
231
  `))}}else k.enqueue(y.encode(g+`
232
- `))};try{for(;;){let{done:g,value:m}=await w.read();if(g){h.trim()&&T(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(`
233
- `);h=E.pop()||"";for(let D of E)if(D.trim())try{_(D,{controller:p,encoder:n,hasTextContent:()=>s,setHasTextContent:F=>s=F,reasoningContent:()=>a,appendReasoningContent:F=>a+=F,isReasoningComplete:()=>c,setReasoningComplete:F=>c=F})}catch(F){console.error("Error processing line:",D,F),p.enqueue(n.encode(D+`
234
- `))}continue}let y=h.split(`
235
- `);h=y.pop()||"";for(let E of y)if(E.trim())try{_(E,{controller:p,encoder:n,hasTextContent:()=>s,setHasTextContent:D=>s=D,reasoningContent:()=>a,appendReasoningContent:D=>a+=D,isReasoningComplete:()=>c,setReasoningComplete:D=>c=D})}catch(D){console.error("Error processing line:",E,D),p.enqueue(n.encode(E+`
236
- `))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{w.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ia=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,o="",s=!1,a="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(w,T,S)=>{let _=w.split(`
237
- `);for(let g of _)g.trim()&&T.enqueue(S.encode(g+`
238
- `))},p=(w,T)=>{let{controller:S,encoder:_}=T;if(this.logger?.debug({line:w},"Processing reason line"),w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let g=JSON.parse(w.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){T.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)}
232
+ `))};try{for(;;){let{done:g,value:p}=await C.read();if(g){f.trim()&&v(f,m,n);break}if(!p||p.length===0)continue;let k;try{k=r.decode(p,{stream:!0})}catch(E){console.warn("Failed to decode chunk",E);continue}if(k.length===0)continue;if(f+=k,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let E=f.split(`
233
+ `);f=E.pop()||"";for(let D of E)if(D.trim())try{b(D,{controller:m,encoder:n,hasTextContent:()=>s,setHasTextContent:F=>s=F,reasoningContent:()=>a,appendReasoningContent:F=>a+=F,isReasoningComplete:()=>c,setReasoningComplete:F=>c=F})}catch(F){console.error("Error processing line:",D,F),m.enqueue(n.encode(D+`
234
+ `))}continue}let y=f.split(`
235
+ `);f=y.pop()||"";for(let E of y)if(E.trim())try{b(E,{controller:m,encoder:n,hasTextContent:()=>s,setHasTextContent:D=>s=D,reasoningContent:()=>a,appendReasoningContent:D=>a+=D,isReasoningComplete:()=>c,setReasoningComplete:D=>c=D})}catch(D){console.error("Error processing line:",E,D),m.enqueue(n.encode(E+`
236
+ `))}}}catch(g){console.error("Stream error:",g),m.error(g)}finally{try{C.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}m.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var La=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,o="",s=!1,a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(C,v,A)=>{let b=C.split(`
237
+ `);for(let g of b)g.trim()&&v.enqueue(A.encode(g+`
238
+ `))},m=(C,v)=>{let{controller:A,encoder:b}=v;if(this.logger?.debug({line:C},"Processing reason line"),C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let g=JSON.parse(C.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){v.appendReasoningContent(g.choices[0].delta.reasoning_content);let p={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete p.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(p)}
239
239
 
240
- `;S.enqueue(_.encode(k));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&T.reasoningContent()&&!T.isReasoningComplete()){T.setReasoningComplete(!0);let m=Date.now().toString(),k={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:T.reasoningContent(),signature:m}}}]};delete k.choices[0].delta.reasoning_content;let y=`data: ${JSON.stringify(k)}
240
+ `;A.enqueue(b.encode(k));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&v.reasoningContent()&&!v.isReasoningComplete()){v.setReasoningComplete(!0);let p=Date.now().toString(),k={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:v.reasoningContent(),signature:p}}}]};delete k.choices[0].delta.reasoning_content;let y=`data: ${JSON.stringify(k)}
241
241
 
242
- `;S.enqueue(_.encode(y))}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){T.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
242
+ `;A.enqueue(b.encode(y))}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 p=`data: ${JSON.stringify(g)}
243
243
 
244
- `;S.enqueue(_.encode(m))}}catch{S.enqueue(_.encode(w+`
245
- `))}else S.enqueue(_.encode(w+`
246
- `))};try{for(;;){let{done:w,value:T}=await h.read();if(w){a.trim()&&d(a,l,n);break}let S=r.decode(T,{stream:!0});a+=S;let _=a.split(`
247
- `);a=_.pop()||"";for(let g of _)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>o,appendReasoningContent:m=>o+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
248
- `))}}}catch(w){console.error("Stream error:",w),l.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}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 Na=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 Ba=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function Jy(t){let e=[];for(let n=0;n<t.messages.length;n++){let o=t.messages[n],s=n===t.messages.length-1,a=o.role==="assistant",c=[];typeof o.content=="string"?c.push({type:"text",text:o.content}):Array.isArray(o.content)&&o.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}})}),!(!s&&c.length===0&&!o.tool_calls&&!o.content)&&(s&&a&&c.length===0&&o.tool_calls&&c.push({type:"text",text:""}),e.push({role:o.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 Vy(t){let e=t,n={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),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(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.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 Ky(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json(),o;n.tool_use&&n.tool_use.length>0&&(o=n.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],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(s),{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,o=new TextEncoder,s=(c,l)=>{if(c.startsWith("data: ")){let h=c.slice(6).trim();if(h){r?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
244
+ `;A.enqueue(b.encode(p))}}catch{A.enqueue(b.encode(C+`
245
+ `))}else A.enqueue(b.encode(C+`
246
+ `))};try{for(;;){let{done:C,value:v}=await f.read();if(C){a.trim()&&d(a,l,n);break}let A=r.decode(v,{stream:!0});a+=A;let b=a.split(`
247
+ `);a=b.pop()||"";for(let g of b)if(g.trim())try{m(g,{controller:l,encoder:n,reasoningContent:()=>o,appendReasoningContent:p=>o+=p,isReasoningComplete:()=>s,setReasoningComplete:p=>s=p})}catch(p){console.error("Error processing line:",g,p),l.enqueue(n.encode(g+`
248
+ `))}}}catch(C){console.error("Stream error:",C),l.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}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 Ua=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 $a=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function e0(t){let e=[];for(let n=0;n<t.messages.length;n++){let o=t.messages[n],s=n===t.messages.length-1,a=o.role==="assistant",c=[];typeof o.content=="string"?c.push({type:"text",text:o.content}):Array.isArray(o.content)&&o.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}})}),!(!s&&c.length===0&&!o.tool_calls&&!o.content)&&(s&&a&&c.length===0&&o.tool_calls&&c.push({type:"text",text:""}),e.push({role:o.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 t0(t){let e=t,n={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),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(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.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 r0(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json(),o;n.tool_use&&n.tool_use.length>0&&(o=n.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],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(s),{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,o=new TextEncoder,s=(c,l)=>{if(c.startsWith("data: ")){let f=c.slice(6).trim();if(f){r?.debug({chunkStr:f},`${e} chunk:`);try{let d=JSON.parse(f);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let m={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
249
249
 
250
- `))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
250
+ `))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let m={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
251
251
 
252
- `))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
252
+ `))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let m={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
253
253
 
254
- `))}else if(d.type==="message_delta"){let p={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
254
+ `))}else if(d.type==="message_delta"){let m={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
255
255
 
256
256
  `))}else if(d.type==="message_stop")l.enqueue(o.encode(`data: [DONE]
257
257
 
258
- `));else{let p={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
258
+ `));else{let m={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
259
259
 
260
- `))}}catch(d){r?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),h="";try{for(;;){let{done:d,value:p}=await l.read();if(d){h&&s(h,c);break}h+=n.decode(p,{stream:!0});let w=h.split(`
261
- `);h=w.pop()||"";for(let T of w)s(T,c)}}catch(d){c.error(d)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function yk(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>je(gd(),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:
260
+ `))}}catch(d){r?.error(`Error parsing ${e} stream chunk`,f,d.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),f="";try{for(;;){let{done:d,value:m}=await l.read();if(d){f&&s(f,c);break}f+=n.decode(m,{stream:!0});let C=f.split(`
261
+ `);f=C.pop()||"";for(let v of C)s(v,c)}}catch(d){c.error(d)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function vk(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Me(wd(),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:
262
262
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
263
263
  2. Run "gcloud auth application-default login"
264
- 3. Use Google Cloud environment with default service account`)}}var ja=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=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(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}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 s=await yk();return{body:Jy(e),config:{url:new URL(`/v1/projects/${n}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return Vy(e)}async transformResponseOut(e){return Ky(e,this.name,this.logger)}};var La=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 Ma=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ua=class{name="OpenAI";endPoint="/v1/chat/completions"};var qa=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[o,s]of n)if(o in r)if(typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null)r[o]=this.deepMergeObjects(r[o],s);else continue;else r[o]=this.cloneValue(s);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[o,s]of Object.entries(r))o in n&&typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null?n[o]=this.deepMergeObjects(n[o],s):n[o]=this.cloneValue(s);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,o]of Object.entries(e))r[n]=this.cloneValue(o);return r}};var $a=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,o=!1,s="",a=!1,c=!1,l="",h=new ReadableStream({async start(d){let p=e.body.getReader(),w=(S,_,g)=>{let m=S.split(`
265
- `);for(let k of m)k.trim()&&_.enqueue(g.encode(k+`
266
- `))},T=(S,_)=>{let{controller:g,encoder:m}=_;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let k=S.slice(6);try{let y=JSON.parse(k);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:c},"usage"),y.choices[0].finish_reason=c?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"&&g.enqueue(m.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
264
+ 3. Use Google Cloud environment with default service account`)}}var qa=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=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(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}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 s=await vk();return{body:e0(e),config:{url:new URL(`/v1/projects/${n}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return t0(e)}async transformResponseOut(e){return r0(e,this.name,this.logger)}};var za=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 Ha=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Wa=class{name="OpenAI";endPoint="/v1/chat/completions"};var Ga=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[o,s]of n)if(o in r)if(typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null)r[o]=this.deepMergeObjects(r[o],s);else continue;else r[o]=this.cloneValue(s);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[o,s]of Object.entries(r))o in n&&typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null?n[o]=this.deepMergeObjects(n[o],s):n[o]=this.cloneValue(s);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,o]of Object.entries(e))r[n]=this.cloneValue(o);return r}};var Ja=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,o=!1,s="",a=!1,c=!1,l="",f=new ReadableStream({async start(d){let m=e.body.getReader(),C=(A,b,g)=>{let p=A.split(`
265
+ `);for(let k of p)k.trim()&&b.enqueue(g.encode(k+`
266
+ `))},v=(A,b)=>{let{controller:g,encoder:p}=b;if(A.startsWith("data: ")&&A.trim()!=="data: [DONE]"){let k=A.slice(6);try{let y=JSON.parse(k);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:c},"usage"),y.choices[0].finish_reason=c?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"&&g.enqueue(p.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
267
267
 
268
- `)),y.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0),y.choices?.[0]?.delta?.reasoning){_.appendReasoningContent(y.choices[0].delta.reasoning);let D={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning}}}]};D.choices?.[0]?.delta&&delete D.choices[0].delta.reasoning;let F=`data: ${JSON.stringify(D)}
268
+ `)),y.choices?.[0]?.delta?.content&&!b.hasTextContent()&&b.setHasTextContent(!0),y.choices?.[0]?.delta?.reasoning){b.appendReasoningContent(y.choices[0].delta.reasoning);let D={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning}}}]};D.choices?.[0]?.delta&&delete D.choices[0].delta.reasoning;let F=`data: ${JSON.stringify(D)}
269
269
 
270
- `;g.enqueue(m.encode(F));return}if(y.choices?.[0]?.delta?.content&&_.reasoningContent()&&!_.isReasoningComplete()){_.setReasoningComplete(!0);let D=Date.now().toString(),F={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:_.reasoningContent(),signature:D}}}]};F.choices?.[0]?.delta&&delete F.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(F)}
270
+ `;g.enqueue(p.encode(F));return}if(y.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let D=Date.now().toString(),F={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:D}}}]};F.choices?.[0]?.delta&&delete F.choices[0].delta.reasoning;let q=`data: ${JSON.stringify(F)}
271
271
 
272
- `;g.enqueue(m.encode($))}y.choices?.[0]?.delta?.reasoning&&delete y.choices[0].delta.reasoning,y.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(y.choices?.[0]?.delta?.tool_calls[0].id,10))&&y.choices?.[0]?.delta?.tool_calls.forEach(D=>{D.id=`call_${Qt()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),y.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof y.choices[0].index=="number"?y.choices[0].index+=1:y.choices[0].index=1);let E=`data: ${JSON.stringify(y)}
272
+ `;g.enqueue(p.encode(q))}y.choices?.[0]?.delta?.reasoning&&delete y.choices[0].delta.reasoning,y.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(y.choices?.[0]?.delta?.tool_calls[0].id,10))&&y.choices?.[0]?.delta?.tool_calls.forEach(D=>{D.id=`call_${Xt()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),y.choices?.[0]?.delta?.tool_calls?.length&&b.hasTextContent()&&(typeof y.choices[0].index=="number"?y.choices[0].index+=1:y.choices[0].index=1);let E=`data: ${JSON.stringify(y)}
273
273
 
274
- `;g.enqueue(m.encode(E))}catch{g.enqueue(m.encode(S+`
275
- `))}}else g.enqueue(m.encode(S+`
276
- `))};try{for(;;){let{done:S,value:_}=await p.read();if(S){l.trim()&&w(l,d,n);break}if(!_||_.length===0)continue;let g;try{g=r.decode(_,{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(`
277
- `);l=k.pop()||"";for(let y of k)if(y.trim())try{T(y,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",y,E),d.enqueue(n.encode(y+`
278
- `))}continue}let m=l.split(`
279
- `);l=m.pop()||"";for(let k of m)if(k.trim())try{T(k,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:y=>o=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",k,y),d.enqueue(n.encode(k+`
280
- `))}}}catch(S){console.error("Stream error:",S),d.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}d.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 za=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(o=>o.role==="system");if(n.length>0){let o=n[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),r.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,r.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{r.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}r.push(o)}}),e.input=r,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&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 o=this.convertResponseToChat(n);return new Response(JSON.stringify(o),{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,o=new TextEncoder,s="",a=!1,c=this,l=new ReadableStream({async start(h){let d=e.body.getReader(),p=-1,w="",T=S=>(S!==w&&(p++,w=S),p);try{for(;;){let{done:S,value:_}=await d.read();if(S){a||h.enqueue(o.encode(`data: [DONE]
274
+ `;g.enqueue(p.encode(E))}catch{g.enqueue(p.encode(A+`
275
+ `))}}else g.enqueue(p.encode(A+`
276
+ `))};try{for(;;){let{done:A,value:b}=await m.read();if(A){l.trim()&&C(l,d,n);break}if(!b||b.length===0)continue;let g;try{g=r.decode(b,{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(`
277
+ `);l=k.pop()||"";for(let y of k)if(y.trim())try{v(y,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",y,E),d.enqueue(n.encode(y+`
278
+ `))}continue}let p=l.split(`
279
+ `);l=p.pop()||"";for(let k of p)if(k.trim())try{v(k,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:y=>o=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",k,y),d.enqueue(n.encode(k+`
280
+ `))}}}catch(A){console.error("Stream error:",A),d.error(A)}finally{try{m.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}d.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 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(o=>o.role==="system");if(n.length>0){let o=n[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),r.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,r.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{r.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}r.push(o)}}),e.input=r,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&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 o=this.convertResponseToChat(n);return new Response(JSON.stringify(o),{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,o=new TextEncoder,s="",a=!1,c=this,l=new ReadableStream({async start(f){let d=e.body.getReader(),m=-1,C="",v=A=>(A!==C&&(m++,C=A),m);try{for(;;){let{done:A,value:b}=await d.read();if(A){a||f.enqueue(o.encode(`data: [DONE]
281
281
 
282
- `));break}let g=n.decode(_,{stream:!0});s+=g;let m=s.split(/\r?\n/);s=m.pop()||"";for(let k of m)if(k.trim())try{if(k.startsWith("event: "))continue;if(k.startsWith("data: ")){let y=k.slice(5).trim();if(y==="[DONE]"){a=!0,h.enqueue(o.encode(`data: [DONE]
282
+ `));break}let g=n.decode(b,{stream:!0});s+=g;let p=s.split(/\r?\n/);s=p.pop()||"";for(let k of p)if(k.trim())try{if(k.startsWith("event: "))continue;if(k.startsWith("data: ")){let y=k.slice(5).trim();if(y==="[DONE]"){a=!0,f.enqueue(o.encode(`data: [DONE]
283
283
 
284
- `));continue}try{let E=JSON.parse(y);if(E.type==="response.output_text.delta"){let D={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:T(E.type),delta:{content:E.delta||""},finish_reason:null}]};h.enqueue(o.encode(`data: ${JSON.stringify(D)}
284
+ `));continue}try{let E=JSON.parse(y);if(E.type==="response.output_text.delta"){let D={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}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
285
285
 
286
- `))}else if(E.type==="response.output_item.added"&&E.item?.type==="function_call"){let D={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:T(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(o.encode(`data: ${JSON.stringify(D)}
286
+ `))}else if(E.type==="response.output_item.added"&&E.item?.type==="function_call"){let D={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}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
287
287
 
288
- `))}else if(E.type==="response.output_item.added"&&E.item?.type==="message"){let D=[];(E.item.content||[]).forEach($=>{$.type==="output_text"&&D.push({type:"text",text:$.text||""})});let F={role:"assistant"};if(D.length===1&&D[0].type==="text"?F.content=D[0].text:D.length>0&&(F.content=D),F.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:T(E.type),delta:F,finish_reason:null}]};h.enqueue(o.encode(`data: ${JSON.stringify($)}
288
+ `))}else if(E.type==="response.output_item.added"&&E.item?.type==="message"){let D=[];(E.item.content||[]).forEach(q=>{q.type==="output_text"&&D.push({type:"text",text:q.text||""})});let F={role:"assistant"};if(D.length===1&&D[0].type==="text"?F.content=D[0].text:D.length>0&&(F.content=D),F.content){let q={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:F,finish_reason:null}]};f.enqueue(o.encode(`data: ${JSON.stringify(q)}
289
289
 
290
- `))}}else if(E.type==="response.output_text.annotation.added"){let D={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:T(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(o.encode(`data: ${JSON.stringify(D)}
290
+ `))}}else if(E.type==="response.output_text.annotation.added"){let D={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}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
291
291
 
292
- `))}else if(E.type==="response.function_call_arguments.delta"){let D={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:T(E.type),delta:{tool_calls:[{index:0,function:{arguments:E.delta||""}}]},finish_reason:null}]};h.enqueue(o.encode(`data: ${JSON.stringify(D)}
292
+ `))}else if(E.type==="response.function_call_arguments.delta"){let D={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}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
293
293
 
294
- `))}else if(E.type==="response.completed"){let D=E.response?.output?.some($=>$.type==="function_call")?"tool_calls":"stop",F={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:D}]};h.enqueue(o.encode(`data: ${JSON.stringify(F)}
294
+ `))}else if(E.type==="response.completed"){let D=E.response?.output?.some(q=>q.type==="function_call")?"tool_calls":"stop",F={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:D}]};f.enqueue(o.encode(`data: ${JSON.stringify(F)}
295
295
 
296
- `)),a=!0}else if(E.type==="response.reasoning_summary_text.delta"){let D={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:T(E.type),delta:{thinking:{content:E.delta||""}},finish_reason:null}]};h.enqueue(o.encode(`data: ${JSON.stringify(D)}
296
+ `)),a=!0}else if(E.type==="response.reasoning_summary_text.delta"){let D={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}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
297
297
 
298
- `))}else if(E.type==="response.reasoning_summary_part.done"&&E.part){let D={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(o.encode(`data: ${JSON.stringify(D)}
298
+ `))}else if(E.type==="response.reasoning_summary_part.done"&&E.part){let D={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:m,delta:{thinking:{signature:E.item_id}},finish_reason:null}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
299
299
 
300
- `))}}catch{h.enqueue(o.encode(k+`
301
- `))}}else h.enqueue(o.encode(k+`
302
- `))}catch(y){console.error("Error processing line:",k,y),h.enqueue(o.encode(k+`
303
- `))}}s.trim()&&h.enqueue(o.encode(s+`
304
- `)),a||h.enqueue(o.encode(`data: [DONE]
300
+ `))}}catch{f.enqueue(o.encode(k+`
301
+ `))}}else f.enqueue(o.encode(k+`
302
+ `))}catch(y){console.error("Error processing line:",k,y),f.enqueue(o.encode(k+`
303
+ `))}}s.trim()&&f.enqueue(o.encode(s+`
304
+ `)),a||f.enqueue(o.encode(`data: [DONE]
305
305
 
306
- `))}catch(S){console.error("Stream error:",S),h.error(S)}finally{try{d.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 o={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}convertResponseToChat(e){let r=e.output?.find(h=>h.type==="message"),n=e.output?.find(h=>h.type==="function_call"),o;r?.content?.length&&r?.content[0].annotations&&(o=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:o,type:"url_citation"});let s=null,a=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let h=[],d=[];if(r.content.forEach(p=>{if(p.type==="output_text")h.push(p.text||"");else if(p.type==="output_image"){let w=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});w&&d.push(w)}else if(p.type==="output_image_base64"){let w=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});w&&d.push(w)}}),d.length>0){let p=[];h.length>0&&p.push({type:"text",text:h.join("")}),p.push(...d),s=p}else s=h.join("")}return n&&(a=[{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:s||null,tool_calls:a,thinking:c,annotations:o},logprobs:null,finish_reason:a?"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 Dd=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
306
+ `))}catch(A){console.error("Stream error:",A),f.error(A)}finally{try{d.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}f.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 o={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}convertResponseToChat(e){let r=e.output?.find(f=>f.type==="message"),n=e.output?.find(f=>f.type==="function_call"),o;r?.content?.length&&r?.content[0].annotations&&(o=r.content[0].annotations.map(f=>({type:"url_citation",url_citation:{url:f.url||"",title:f.title||"",content:"",start_index:f.start_index||0,end_index:f.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let f=[],d=[];if(r.content.forEach(m=>{if(m.type==="output_text")f.push(m.text||"");else if(m.type==="output_image"){let C=this.buildImageContent({url:m.image_url,mime_type:m.mime_type});C&&d.push(C)}else if(m.type==="output_image_base64"){let C=this.buildImageContent({b64_json:m.image_base64,mime_type:m.mime_type});C&&d.push(C)}}),d.length>0){let m=[];f.length>0&&m.push({type:"text",text:f.join("")}),m.push(...d),s=m}else s=f.join("")}return n&&(a=[{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:s||null,tool_calls:a,thinking:c,annotations:o},logprobs:null,finish_reason:a?"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 Pd=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
307
307
 
308
308
  Output format:
309
309
  <reasoning_content>
310
310
  Your detailed thinking process goes here
311
311
  </reasoning_content>
312
- Your final answer must follow after the closing tag above.`,_k=10,Ha=class{name="forcereasoning";async transformRequestIn(e){let r=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||r<_k)&&(r++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
313
- ${o.content}`),delete o.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:Dd}):n.content=[{type:"text",text:Dd},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Dd}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,c=new ReadableStream({async start(l){let h=e.body.getReader(),d="",p="SEARCHING",w="",T="",S=(_,g)=>{if(typeof g!="string"){_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0&&!_.choices[0].delta.content&&(_.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(_)}
312
+ Your final answer must follow after the closing tag above.`,Tk=10,Ka=class{name="forcereasoning";async transformRequestIn(e){let r=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||r<Tk)&&(r++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
313
+ ${o.content}`),delete o.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:Pd}):n.content=[{type:"text",text:Pd},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Pd}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,c=new ReadableStream({async start(l){let f=e.body.getReader(),d="",m="SEARCHING",C="",v="",A=(b,g)=>{if(typeof g!="string"){b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0&&!b.choices[0].delta.content&&(b.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(b)}
314
314
 
315
- `)));return}let m=w+g;for(w="";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 y=r.length-1;y>0;y--)if(m.endsWith(r.substring(0,y))){w=m.substring(m.length-y);break}m=""}}else if(p==="REASONING"){let k=m.indexOf(n);if(k!==-1){let y=m.substring(0,k);if(y.length>0){let F={..._.choices[0].delta,thinking:{content:y}};delete F.content;let $={..._,choices:[{..._.choices[0],delta:F,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify($)}
315
+ `)));return}let p=C+g;for(C="";p.length>0;)if(m==="SEARCHING"){let k=p.indexOf(r);if(k!==-1)p=p.substring(k+r.length),m="REASONING";else{for(let y=r.length-1;y>0;y--)if(p.endsWith(r.substring(0,y))){C=p.substring(p.length-y);break}p=""}}else if(m==="REASONING"){let k=p.indexOf(n);if(k!==-1){let y=p.substring(0,k);if(y.length>0){let F={...b.choices[0].delta,thinking:{content:y}};delete F.content;let q={...b,choices:[{...b.choices[0],delta:F,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(q)}
316
316
 
317
- `))}let E={..._.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete E.content;let D={..._,choices:[{..._.choices[0],delta:E,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
317
+ `))}let E={...b.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete E.content;let D={...b,choices:[{...b.choices[0],delta:E,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
318
318
 
319
- `)),o++,m=m.substring(k+n.length),p="FINAL"}else{let y=m;for(let E=n.length-1;E>0;E--)if(m.endsWith(n.substring(0,E))){w=m.substring(m.length-E),y=m.substring(0,m.length-E);break}if(y.length>0){let E={..._.choices[0].delta,thinking:{content:y}};delete E.content;let D={..._,choices:[{..._.choices[0],delta:E,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
319
+ `)),o++,p=p.substring(k+n.length),m="FINAL"}else{let y=p;for(let E=n.length-1;E>0;E--)if(p.endsWith(n.substring(0,E))){C=p.substring(p.length-E),y=p.substring(0,p.length-E);break}if(y.length>0){let E={...b.choices[0].delta,thinking:{content:y}};delete E.content;let D={...b,choices:[{...b.choices[0],delta:E,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
320
320
 
321
- `))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))T+=m;else{let y=T+m,E={..._.choices[0].delta,content:y};E.thinking&&delete E.thinking;let D={..._,choices:[{..._.choices[0],delta:E}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
321
+ `))}p=""}}else if(m==="FINAL"){if(p.length>0)if(/^\s*$/.test(p))v+=p;else{let y=v+p,E={...b.choices[0].delta,content:y};E.thinking&&delete E.thinking;let D={...b,choices:[{...b.choices[0],delta:E}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
322
322
 
323
- `)),T=""}o++,m=""}};try{for(;;){let{done:_,value:g}=await h.read();if(_)break;let m=s.decode(g,{stream:!0});d+=m;let k=d.split(`
323
+ `)),v=""}o++,p=""}};try{for(;;){let{done:b,value:g}=await f.read();if(b)break;let p=s.decode(g,{stream:!0});d+=p;let k=d.split(`
324
324
  `);d=k.pop()||"";for(let y of k)if(y.trim()){if(y.trim()==="data: [DONE]"){l.enqueue(a.encode(y+`
325
325
 
326
- `));break}if(y.startsWith("data:"))try{let E=JSON.parse(y.slice(5));S(E,E.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(y+`
326
+ `));break}if(y.startsWith("data:"))try{let E=JSON.parse(y.slice(5));A(E,E.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(y+`
327
327
  `))}else l.enqueue(a.encode(y+`
328
- `))}}}catch(_){console.error("Stream error:",_),l.error(_)}finally{try{h.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}if(p==="REASONING"){let g={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(g)}
328
+ `))}}}catch(b){console.error("Stream error:",b),l.error(b)}finally{try{f.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}if(m==="REASONING"){let g={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(g)}
329
329
 
330
- `))}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 Wa=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 o=n.thinking?.content,s=n.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(n.reasoning_content=o,s&&(n.reasoning_content_signature=s)),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,o=new TextEncoder,s="",a="",c=new ReadableStream({async start(l){let h=e.body.getReader();try{for(;;){let{done:d,value:p}=await h.read();if(d){a.trim()&&l.enqueue(o.encode(a+`
331
- `));break}let w=n.decode(p,{stream:!0});a+=w;let T=a.split(`
332
- `);a=T.pop()||"";for(let S of T)if(S.trim())if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]")try{let _=JSON.parse(S.slice(6));if(_.choices?.[0]?.delta?.reasoning_content){s+=_.choices[0].delta.reasoning_content;let g={..._,choices:[{..._.choices[0],delta:{thinking:{content:_.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(g)}
330
+ `))}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 Ya=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 o=n.thinking?.content,s=n.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(n.reasoning_content=o,s&&(n.reasoning_content_signature=s)),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,o=new TextEncoder,s="",a="",c=new ReadableStream({async start(l){let f=e.body.getReader();try{for(;;){let{done:d,value:m}=await f.read();if(d){a.trim()&&l.enqueue(o.encode(a+`
331
+ `));break}let C=n.decode(m,{stream:!0});a+=C;let v=a.split(`
332
+ `);a=v.pop()||"";for(let A of v)if(A.trim())if(A.startsWith("data: ")&&A.trim()!=="data: [DONE]")try{let b=JSON.parse(A.slice(6));if(b.choices?.[0]?.delta?.reasoning_content){s+=b.choices[0].delta.reasoning_content;let g={...b,choices:[{...b.choices[0],delta:{thinking:{content:b.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(g)}
333
333
 
334
- `));continue}if(_.choices?.[0]?.delta?.content&&s&&!_.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),m={..._,choices:[{..._.choices[0],delta:{content:null,thinking:{content:s,signature:g}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
334
+ `));continue}if(b.choices?.[0]?.delta?.content&&s&&!b.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),p={...b,choices:[{...b.choices[0],delta:{content:null,thinking:{content:s,signature:g}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
335
335
 
336
- `)),s=""}_.choices?.[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0&&l.enqueue(o.encode(`data: ${JSON.stringify(_)}
336
+ `)),s=""}b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0&&l.enqueue(o.encode(`data: ${JSON.stringify(b)}
337
337
 
338
- `))}catch{l.enqueue(o.encode(S+`
339
- `))}else l.enqueue(o.encode(S+`
340
- `))}}catch(d){l.error(d)}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 Yy={AnthropicTransformer:oi,GeminiTransformer:ui,VertexGeminiTransformer:ka,VertexClaudeTransformer:ja,DeepseekTransformer:va,TooluseTransformer:Ta,OpenrouterTransformer:Da,OpenAITransformer:Ua,MaxTokenTransformer:Ra,GroqTransformer:xa,CleancacheTransformer:Oa,EnhanceToolTransformer:Pa,ReasoningTransformer:Ia,SamplingTransformer:Na,MaxCompletionTokens:Ba,CerebrasTransformer:La,StreamOptionsTransformer:Ma,CustomParamsTransformer:qa,VercelTransformer:$a,OpenAIResponsesTransformer:za,ForceReasoningTransformer:Ha,KimiTransformer:Wa};var wn=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=require(require.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})
338
+ `))}catch{l.enqueue(o.encode(A+`
339
+ `))}else l.enqueue(o.encode(A+`
340
+ `))}}catch(d){l.error(d)}finally{try{f.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 n0={AnthropicTransformer:ci,GeminiTransformer:hi,VertexGeminiTransformer:xa,VertexClaudeTransformer:qa,DeepseekTransformer:Oa,TooluseTransformer:Fa,OpenrouterTransformer:Pa,OpenAITransformer:Wa,MaxTokenTransformer:Ia,GroqTransformer:Na,CleancacheTransformer:Ba,EnhanceToolTransformer:ja,ReasoningTransformer:La,SamplingTransformer:Ua,MaxCompletionTokens:$a,CerebrasTransformer:za,StreamOptionsTransformer:Ha,CustomParamsTransformer:Ga,VercelTransformer:Ja,OpenAIResponsesTransformer:Va,ForceReasoningTransformer:Ka,KimiTransformer:Ya};var An=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=require(require.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})
341
341
  error: ${r.message}
342
342
  stack: ${r.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
343
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Yy).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)}};var Qy=require("tiktoken"),ds=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,Qy.get_encoding)(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:o,system:s,tools:a}=e;return Array.isArray(o)&&o.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 s=="string"?n+=r.encode(s).length:Array.isArray(s)&&s.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}))}),a&&a.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)}};var ms=require("path"),h0=require("os"),ho=require("fs"),gs=require("fs");var bk=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 o=0;o<r.length;++o){let s=r[o];n=n[s]??=Object.create(null)}n.end=r}return e}split(t){let e=[],r=t.length,n=0,o=0;for(;o<r;){let s=this.trie,a=null,c=o;for(;c<r&&(s=s[t[c]]);)s.end&&(a=s.end),++c;a?(o>n&&e.push(t.slice(n,o)),e.push(a),o+=a.length,n=o):++o}return n<r&&e.push(t.slice(n)),e}},Ck=bk,wk=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}},Ek=wk,o0=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),r=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+r),r+=1);let n=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,n[s]]))})(),Ak=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),Sk=Ak(o0),Xy=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",kk=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|[${Xy}])]+`,` ?[^\\s${Xy}]+`]]),fs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",hO=new RegExp(`^[${fs}]+$`,"gu"),xd=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"),Ga=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,o]of kk)r=r.replaceAll(n,o);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=vk(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},vk=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Tk=(t,e,r)=>{let n=[],o=0;for(;o<t.length;){if(n.push(t[o]),(e.get(t[o])??r)!==r){++o;continue}for(;++o<t.length&&(e.get(t[o])??r)===r;)e.get(n.at(-1))!==r&&(n[n.length-1]+=t[o])}return n},Dk=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,Rk=t=>Number.isInteger(t)||typeof t=="bigint",xk=t=>{let e=0;for(let r of t)++e;return e},Ok=t=>s0(t.toLowerCase()),Pt=(...t)=>Array.prototype.concat.apply([],t),Od=t=>new Map(Object.entries(t)),Fk=(t,e)=>{let r=[],n=0;for(let o of t.matchAll(e)){let s=o[0];n<o.index&&r.push(t.slice(n,o.index)),s.length>0&&r.push(s),n=o.index+s.length}return n<t.length&&r.push(t.slice(n)),r},s0=t=>t.replace(new RegExp("\\p{M}","gu"),""),Zy=(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},Pk=t=>t.match(/\S+/g)||[],Ik=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},hs=Ik,Nk=class extends hs{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Dr=Nk,Bk=class extends Dr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],o=n.charCodeAt(0);Dk(o)?(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`
344
- `: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}},jk=Bk,Lk=class extends Dr{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}},Mk=Lk,Uk=class extends Dr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>i0(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},qk=Uk,$k=class extends Dr{normalize(t){let e=Ga(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},zk=$k,Hk=class extends Dr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ja=Hk,Wk=class extends Ja{constructor(){super(...arguments),this.form="NFC"}},Gk=Wk,Jk=class extends Ja{constructor(){super(...arguments),this.form="NFD"}},Vk=Jk,Kk=class extends Ja{constructor(){super(...arguments),this.form="NFKC"}},Yk=Kk,Qk=class extends Ja{constructor(){super(...arguments),this.form="NFKD"}},Xk=Qk,Zk=class extends Dr{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}},ev=Zk,tv=class extends Dr{normalize(t){return s0(t)}},rv=tv,nv=class extends Dr{normalize(t){return t.toLowerCase()}},ov=nv,sv=class extends Dr{normalize(t){return t=this.config.prepend+t,t}},iv=sv;function av(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new jk(t);case"Precompiled":return new Mk(t);case"Sequence":return new qk(t);case"Replace":return new zk(t);case"NFC":return new Gk(t);case"NFD":return new Vk(t);case"NFKC":return new Yk(t);case"NFKD":return new Xk(t);case"Strip":return new ev(t);case"StripAccents":return new rv(t);case"Lowercase":return new ov(t);case"Prepend":return new iv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var i0=av,uv=class extends hs{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)}},cr=uv,cv=class extends cr{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=o0,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(""))}},lv=cv,dv=class extends cr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},fv=dv,hv=class extends cr{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]}},pv=hv,mv=class extends cr{constructor(t){super(),this.config=t,this.pattern=Ga(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):Fk(t,this.pattern)}},gv=mv,yv=class extends cr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${fs}]+|[${fs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},_v=yv,bv=class extends cr{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)||[]}},Cv=bv,wv=class extends cr{constructor(){super(),this.pattern=new RegExp(`[^\\s${fs}]+|[${fs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Ev=wv,Av=class extends cr{constructor(t){super(),this.config=t,this.pattern=Ga(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Sv=Av,kv=class extends cr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>a0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},vv=kv,Tv=class extends cr{pre_tokenize_text(t){return Pk(t)}},Dv=Tv;function Rv(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Ev;case"Sequence":return new vv(t);case"Whitespace":return new fv;case"WhitespaceSplit":return new Dv;case"Metaspace":return new pv(t);case"ByteLevel":return new lv(t);case"Split":return new gv(t);case"Punctuation":return new _v(t);case"Digits":return new Cv(t);case"Replace":return new Sv(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var a0=Rv,xv=class extends hs{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=Tk(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)}},Va=xv,Ov=class extends Va{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=Od(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 o=!1,s=0,a=[];for(;s<n.length;){let c=n.length,l=null;for(;s<c;){let h=n.slice(s,c).join("");if(s>0&&(h=this.config.continuing_subword_prefix+h),this.tokens_to_ids.has(h)){l=h;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},e0=Ov,t0=class u0{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new u0(!1,new Map)}},Fv=class{constructor(){this.root=t0.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=t0.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)}}},Pv=Fv,Rd=class c0{constructor(e,r,n,o,s){this.token_id=e,this.node_id=r,this.pos=n,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new c0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},Iv=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 Rd(this.bos_token_id??0,0,0,0,0),o=new Rd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(n)}insert(t,e,r,n){let o=this.nodes.length,s=new Rd(n,o,t,e,r);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,c=null;for(let l of this.end_nodes[e]){let h=l.backtrace_score+s.score;(c===null||h>a)&&(c=l.clone(),a=h)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.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)}},Nv=Iv;function Bv(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 jv=class extends Va{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,o)=>[n,o])),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=Bv(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Pv,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 o=!1,s=[],a=e.slice(n).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let h=this.tokens_to_ids.get(l),d=this.scores[h],p=xk(l);t.insert(n,p,d,h),!o&&p===r&&(o=!0)}o||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new Nv(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}},r0=jv,Lv=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}},Mv=Lv,Uv=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()}},qv=Uv,$v=class extends Va{constructor(t){super(t),this.tokens_to_ids=Od(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 qv(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 o=new Mv((c,l)=>c.score<l.score),s={token:r[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[c],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let c=o.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:s=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(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let c=s;c!==null;c=c.next)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let o=0;o<n.length-1;++o)n[o]+=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 o of n)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},n0=$v,zv=class extends Va{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Od(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,o]of this.tokens_to_ids)this.vocab[o]=n}encode(t){return t}},Hv=zv;function Wv(t,e){switch(t.type){case"WordPiece":return new e0(t);case"Unigram":return new r0(t,e.eos_token);case"BPE":return new n0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new r0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new n0(t):new e0(t):new Hv(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 Gv=Wv,Jv=class extends hs{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ps=Jv,Vv=class extends ps{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of n)"SpecialToken"in a?r&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Pt(o,t),s=Pt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Pt(o,e),s=Pt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},Kv=Vv,Yv=class extends ps{post_process(t,e=null){return{tokens:e?Pt(t,e):t}}},Qv=Yv,Xv=class extends ps{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Pt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=[],s=r?[this.sep[0]]:[];t=Pt(t,o,e,s),n=Pt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},Zv=Xv,eT=class extends ps{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Pt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=r?[this.sep[0]]:[],s=r?[this.sep[0]]:[];t=Pt(t,o,e,s),n=Pt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},tT=eT,rT=class extends ps{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>l0(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let o of this.processors)n=o.post_process(n.tokens,e,r);return n}},nT=rT;function oT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new Kv(t);case"ByteLevel":return new Qv(t);case"BertProcessing":return new Zv(t);case"RobertaProcessing":return new tT(t);case"Sequence":return new nT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var l0=oT,sT=class extends hs{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("")}},lr=sT,iT=class extends lr{constructor(t){super(t),this.byte_decoder=Sk,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(o=>o.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}},aT=iT,uT=class extends lr{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=xd(e)),e})}},cT=uT,lT=class extends lr{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}},dT=lT,fT=class extends lr{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},hT=fT,pT=class extends lr{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=xd(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},mT=pT,gT=class extends lr{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>d0(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},yT=gT,_T=class extends lr{decode_chain(t){let e=Ga(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},bT=_T,CT=class extends lr{decode_chain(t){return[t.join("")]}},wT=CT,ET=class extends lr{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 o=0;o<this.start&&e[o]===this.content;++o)r=o+1;let n=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){n=s;continue}else break}return e.slice(r,n)})}},AT=ET,ST=class extends lr{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let o=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let s=parseInt(n.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)r.push(o);else{if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},kT=ST;function vT(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new aT(t);case"WordPiece":return new cT(t);case"Metaspace":return new dT(t);case"BPEDecoder":return new hT(t);case"CTC":return new mT(t);case"Sequence":return new yT(t);case"Replace":return new bT(t);case"Fuse":return new wT(t);case"Strip":return new AT(t);case"ByteFallback":return new kT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var d0=vT,TT=class{constructor(t,e){let r=Zy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Zy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=i0(this.tokenizer.normalizer),this.pre_tokenizer=a0(this.tokenizer.pre_tokenizer),this.model=Gv(this.tokenizer.model,this.config),this.post_processor=l0(this.tokenizer.post_processor),this.decoder=d0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new Ek(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),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 Ck(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),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:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return n&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!Rk(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(o=>!this.special_tokens.includes(o)));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=xd(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 o=this.added_tokens_map.get(r);o&&(o.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),o.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=Ok(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(n,o,r):{tokens:Pt(n??[],o??[])}}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}},f0=TT;var Ka=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||(0,ms.join)((0,h0.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,ms.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,ms.join)(e,"tokenizer.json"),tokenizerConfig:(0,ms.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,ho.existsSync)(e)||(0,ho.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,ho.existsSync)(e.tokenizerJson)||!(0,ho.existsSync)(e.tokenizerConfig))return null;let[r,n]=await Promise.all([gs.promises.readFile(e.tokenizerJson,"utf-8"),gs.promises.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,o=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[c,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([gs.promises.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),gs.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(o)}}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 f0(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:o,tools:s}=e;if(Array.isArray(n)){for(let a of n)if(typeof a.content=="string")r.push(a.content);else if(Array.isArray(a.content))for(let c of a.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 o=="string")r.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")r.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&r.push(c)}}if(s)for(let a of s)a.name&&r.push(a.name),a.description&&r.push(a.description),a.input_schema&&r.push(JSON.stringify(a.input_schema));return r.join(" ")}};var Ya=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 o=new URL(e.url);this.name=`api-${o.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},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(r),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let c=await a.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(o=>{o&&r.push(o)}))}),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("."),o=e;for(let s of n){if(o==null)throw new Error(`Field path '${r}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${r}', got ${typeof o}`);return o}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 En=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 ds("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 ds(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ka(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new Ya(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(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.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 o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[r]?o.tokenizer.models[r]:o.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)}`}}};var m0=require("tiktoken");var Fd=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())}},Qa=new Fd(100);var Xa=require("fs/promises"),tu=require("fs/promises"),Za=require("path"),mo=require("@wengine-ai/claude-code-router-shared");var Rr=(0,m0.get_encoding)("cl100k_base"),Id=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?n+=Rr.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?n+=Rr.encode(s.text).length:s.type==="tool_use"?n+=Rr.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(n+=Rr.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?n+=Rr.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?n+=Rr.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{n+=Rr.encode(s||"").length}))}),r&&r.forEach(o=>{o.description&&(n+=Rr.encode(o.name+o.description).length),o.input_schema&&(n+=Rr.encode(JSON.stringify(o.input_schema)).length)}),n},g0=async(t,e)=>{if(t.sessionId){let r=await Nd(t.sessionId);if(r){let n=(0,Za.join)(mo.HOME_DIR,r,"config.json"),o=(0,Za.join)(mo.HOME_DIR,r,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,Xa.readFile)(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await(0,Xa.readFile)(n,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function eu(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 y0(t){let e=eu(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),o=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:r};let s=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:r}:{family:null,extended:r}}function DT(t,e){if(!e||!t)return null;let r=eu(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=y0(t);if(n&&e[n])return e[n];for(let[o,s]of Object.entries(e)){let a=eu(o);if(a&&r.includes(a))return s}return null}function _0(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function RT(t){if(!t?.includes(","))return null;let[e,...r]=t.split(","),n=e.trim(),o=r.join(",").trim();return!n||!o?null:{providerName:n,routeModel:o}}function Vt(t,e,r){let n=RT(t);if(!n)return t;let{providerName:o,routeModel:s}=n;if(!r&&!At().isAvailable(o,s))return null;let a=e.find(l=>l.name.toLowerCase()===o.toLowerCase()),c=a?.models?.find(l=>String(l).toLowerCase()===s.toLowerCase());return a&&c?`${a.name},${c}`:t}function po(t,e,r,n,o){let s=At(),a=[r?.[t],n?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let h=Vt(l,e);if(h)return h}return null}function xT(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 OT(t){let e=eu(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 FT(t,e,r,n,o,s,a){let c=r.longContextThreshold||6e4,l=Math.max(e,_0(o)),h=t.modelFamily;if((s||l>2e5)&&r.extendedContext){let T=Vt(r.extendedContext,n);if(T)return t.log.info(`Family: using extended context model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:T,scenarioType:"extendedContext",isFallback:!1};let S=po("extendedContext",n,r.fallback,a,h);if(S)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:S,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(l>c&&(r.longContext||r.fallback?.longContext?.length||a?.longContext?.length)){let T=r.longContext?Vt(r.longContext,n):null;if(T)return t.log.info(`Family: using long context model, tokens: ${l}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!1};let S=po("longContext",n,r.fallback,a,h);if(S)return t.log.info(`Family: using long context fallback model, tokens: ${l}, estimated: ${e}`),{model:S,scenarioType:"longContext",isFallback:!0};let _=r.longContext?Vt(r.longContext,n,!0):null;if(_)return t.log.warn("Family: no healthy longContext model, forcing primary to keep scenarioType=longContext"),{model:_,scenarioType:"longContext",isFallback:!0};let g=[...r.fallback?.longContext||[],...a?.longContext||[]].map(m=>Vt(m,n,!0)).find(Boolean);if(g)return t.log.warn("Family: no healthy longContext model, forcing fallback to keep scenarioType=longContext"),{model:g,scenarioType:"longContext",isFallback:!0}}if(Array.isArray(t.body.tools)&&t.body.tools.some(T=>T.type?.startsWith("web_search"))&&r.webSearch){let T=Vt(r.webSearch,n);if(T)return{model:T,scenarioType:"webSearch",isFallback:!1};let S=po("webSearch",n,r.fallback,a,h);if(S)return t.log.info("Family: using webSearch fallback model"),{model:S,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let T=Vt(r.think,n);if(T)return{model:T,scenarioType:"think",isFallback:!1};let S=po("think",n,r.fallback,a,h);if(S)return t.log.info("Family: using think fallback model"),{model:S,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let T=Vt(r.default,n);if(T)return{model:T,scenarioType:"default",isFallback:!1};let S=po("default",n,r.fallback,a,h);if(S)return t.log.info("Family: using default fallback model"),{model:S,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var PT=async(t,e,r,n)=>{let o=await g0(t,r),s=r.get("providers")||[],a=o||r.get("Router"),c=r.get("fallback");if(t.body.model.includes(",")){let m=Vt(t.body.model,s);if(m)return{model:m,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let k=po("default",s,void 0,c);if(k)return t.log.info(`Using fallback for explicit model: ${k}`),{model:k,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:l,extended:h}=y0(t.body.model),d=a?.families?.[l||""];if(d){t.log.info(`Using model family routing for: ${l}${h?" (1M)":""}`),t.modelFamily=l,t.familyFallback=d.fallback;let m=FT(t,e,d,s,n,h,c);if(m)return{model:m.model,scenarioType:m.scenarioType}}let p=DT(t.body.model,a?.models);if(p){let m=Vt(p,s);if(m)return t.log.info(`Using mapped model for ${t.body.model}: ${p}`),{model:m,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${p} unavailable (fail pool), skipping`)}let w=Math.max(e,_0(n)),T=a?.extendedContextThreshold||2e5;if(w>T&&a?.extendedContext)return t.log.info(`Using extended context (1M) model due to token count: ${w}, estimated: ${e}, threshold: ${T}`),{model:a.extendedContext,scenarioType:"extendedContext"};let S=a?.longContextThreshold||6e4;if(w>S&&a?.longContext)return t.log.info(`Using long context model due to token count: ${w}, estimated: ${e}, threshold: ${S}`),{model:a.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let m=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(m)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${m[1]}</CCR-SUBAGENT-MODEL>`,""),{model:m[1],scenarioType:"default"}}let g=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&g?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:g.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(m=>m.type?.startsWith("web_search"))&&a?.webSearch?{model:a.webSearch,scenarioType:"webSearch"}:t.body.thinking&&a?.think?(t.log.info(`Using think model for ${t.body.thinking}`),{model:a.think,scenarioType:"think"}):{model:a?.default,scenarioType:"default"}},ru=async(t,e,r)=>{let{configService:n,event:o}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let T=t.body.metadata.user_id.split("_session_");T.length>1&&(t.sessionId=T[1])}let a=await g0(t,n)||n.get("Router"),c=n.get("providers")||[],l=Qa.get(t.sessionId),{messages:h,system:d=[],tools:p}=t.body,w=n.get("REWRITE_SYSTEM_PROMPT");if(w&&d.length>1&&d[1]?.text?.includes("<env>")){let T=await(0,Xa.readFile)(w,"utf-8");d[1].text=`${T}<env>${d[1].text.split("<env>").pop()}`}try{let[T,S]=t.body.model.split(","),_=r.tokenizerService?.getTokenizerConfigForModel(T,S),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:h,system:d,tools:p},_)).tokenCount:g=Id(h,d,p),t.tokenCount=g;let m,k=n.get("CUSTOM_ROUTER_PATH");if(k)try{m=await require(k)(t,n.getAll(),{event:o})}catch(y){t.log.error(`failed to load custom router: ${y.message}`)}if(m)t.scenarioType="default";else{let y=await PT(t,g,n,l);m=y.model,t.scenarioType=y.scenarioType}if(a?.image&&m!==a.image&&xT(t)&&!OT(m)){let y=Vt(a.image,c);y?(t.log.info(`Using image model fallback for ${m}`),m=y,t.scenarioType="image"):t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(T){t.log.error(`Error in router middleware: ${T.message}`),t.body.model=a?.default,t.scenarioType="default"}},xr=new Map,p0=1e3;function Pd(){if(xr.size<=p0)return;let t=[...xr.keys()].slice(0,xr.size-p0);for(let e of t)xr.delete(e)}var Nd=async t=>{if(xr.has(t)){let e=xr.get(t);return!e||e===""?null:e}try{let e=await(0,tu.opendir)(mo.CLAUDE_PROJECTS_DIR),r=[];for await(let s of e)s.isDirectory()&&r.push(s.name);let n=r.map(async s=>{let a=(0,Za.join)(mo.CLAUDE_PROJECTS_DIR,s,`${t}.jsonl`);try{return(await(0,tu.stat)(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(n);for(let s of o)if(s)return xr.set(t,s),Pd(),s;return xr.set(t,""),Pd(),null}catch(e){return console.error("Error searching for project by session:",e),xr.set(t,""),Pd(),null}};var go=class{async fetchJson(e,r,n,o){if(!r.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.apiKey}`},signal:AbortSignal.timeout(n)};if(o)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(o).toString())}catch{}try{let a=await fetch(e,s);return a.ok?await a.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},Bd=class extends go{async queryQuota(e,r,n){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,r,n),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>Kt(l?.total_balance)!==void 0);if(!a)return null;let c=Kt(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},jd=class extends go{async queryQuota(e,r,n){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,r,n))?.data;if(!s||typeof s!="object")return null;let a={},c=Kt(s.limit),l=Kt(s.limit_remaining),h=Kt(s.usage),d=Kt(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),h!==void 0&&(a.usedBalance=h),d!==void 0&&(a.usedDailyBalance=d),this.hasQuotaData(a)?a:null}},Ld=class extends go{async queryQuota(e,r,n){let o=LT(e.baseUrl),a=(await this.fetchJson(o,e,r,n))?.data;if(!a||typeof a!="object")return null;let c={},l=Kt(a.totalBalance),h=Kt(a.balance);return l!==void 0&&(c.totalBalance=l),h!==void 0&&(c.remainingBalance=h),l!==void 0&&h!==void 0&&(c.usedBalance=Math.max(0,l-h)),this.hasQuotaData(c)?c:null}},Md=class extends go{async queryQuota(e,r,n){if(!e.quotaToken)return null;let o={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e.quotaToken}`},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:s}=await import("undici");o.dispatcher=new s(new URL(n).toString())}catch{}try{let s=await fetch("https://bigmodel.cn/api/monitor/usage/quota/limit",o);if(!s.ok)return null;let a=await s.json(),c=Array.isArray(a?.data?.limits)?a.data.limits:[],l={};for(let h of c)if(h.type==="TIME_LIMIT"){let d=Kt(h.usage),p=Kt(h.currentValue),w=Kt(h.remaining);d!==void 0&&(l.usedDailyBalance=d),p!==void 0&&w!==void 0?l.limitDaily=p+w:d!==void 0&&w!==void 0&&(l.limitDaily=d+w),h.nextResetTime&&(l.resetTime=new Date(h.nextResetTime).toISOString())}return this.hasQuotaData(l)?l:null}catch{return null}}},IT=new Bd,NT=new jd,BT=new Ld,jT=new Md;function nu(t){let e=b0(t);return e?e==="deepseek.com"||e.endsWith(".deepseek.com")?IT:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?NT:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?BT:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?jT:null:null}function LT(t){let e=b0(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function b0(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Kt(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let r=Number(e);return Number.isFinite(r)?r:void 0}var Ud=new Map;function ou(t,e){t&&Ud.set(t,{...e,provider:t,capturedAt:Date.now()})}function C0(t){let e=Ud.get(t);return e?{...e}:void 0}function w0(){return Array.from(Ud.values()).map(t=>({...t}))}var MT={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function UT(t){try{let e=new URL(t),r=e.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),e.pathname=`${r}/models`,e.toString()}catch{return null}}function qT(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function qd(t,e,r){let n=UT(t.baseUrl);if(!n)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let o={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=await fetch(n,o);if(s.headers&&Oo(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===401||s.status===403)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(o){return{success:!1,error:o?.message||o?.toString()||"Unknown probe error"}}}var ys=class{config;quotaProbeTimer;healthProbeTimer;getProviders;getHttpsProxy;logger;running=!1;constructor(e,r,n,o){this.config={...MT,...r},this.getProviders=e,this.getHttpsProxy=n,this.logger=o}start(){!this.config.enabled||this.running||(this.running=!0,setTimeout(()=>{this.running&&(this.runQuotaProbe(),this.runHealthProbe())},this.config.initialDelayMs),this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(e.length===0)return;let n=[];for(let s of e){let a=nu(s.baseUrl);a&&n.push({provider:s.name,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,r).then(c=>{c&&(ou(s.name,c),this.logger?.debug?.(`Stored quota probe result for ${s.name}`))})}),qT(s.baseUrl)&&n.push({provider:s.name,type:"rate-limit-headers",promise:qd(s,this.config.probeTimeoutMs,r).then(()=>{})})}if(n.length===0)return;this.logger?.debug?.(`Running quota probe with ${n.length} tasks for ${e.length} providers`);let o=await Promise.allSettled(n.map(s=>s.promise));for(let s=0;s<n.length;s++){let a=o[s];if(a.status==="rejected"){let c=n[s];this.logger?.warn?.(`Quota probe failed for ${c.provider} (${c.type}): ${a.reason}`)}}}async runHealthProbe(){let e=At(),r=this.getProviders(),n=this.getHttpsProxy?.(),o=e.getFailPoolModels(),s=[];for(let c of o){let[l,h]=c.split(","),d=e.getState(l,h);if(d&&d.status==="open"&&e.needsProbe(d)){let p=r.find(w=>w.name===l);p&&!this.config.excludeProviders.includes(l)&&s.push({provider:p,model:h,state:d})}}if(s.length===0)return;this.logger?.debug?.(`Running health probe for ${s.length} open models`);for(let{provider:c,model:l}of s)e.markProbeAttempt(c.name,l);let a=await Promise.allSettled(s.map(({provider:c})=>qd(c,this.config.probeTimeoutMs,n)));for(let c=0;c<s.length;c++){let{provider:l,model:h}=s[c],d=a[c];if(d.status==="fulfilled"){let p=d.value;if(p.success){for(let w of l.models)e.recordSuccess(l.name,w);this.logger?.info?.(`Health probe succeeded for ${l.name}`)}else{for(let w of l.models)e.recordFailure(l.name,w,p.error);this.logger?.warn?.(`Health probe failed for ${l.name}: ${p.error}`)}}else{for(let p of l.models)e.recordFailure(l.name,p,d.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${l.name}: ${d.reason}`)}}}async probeProviderManually(e){let n=this.getProviders().find(a=>a.name===e);if(!n)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;let o=this.getHttpsProxy?.(),s=await qd(n,this.config.probeTimeoutMs,o);if(s.success)for(let a of n.models)At().recordSuccess(n.name,a);else for(let a of n.models)At().recordFailure(n.name,a,s.error);return s.success}},Yr=null;function $d(t,e,r,n){return Yr||(Yr=new ys(t,e,r,n)),Yr}function su(t,e,r,n){let o=$d(t,e,r,n);return o.start(),o}function iu(){Yr&&Yr.stop()}function E0(){Yr&&(Yr.stop(),Yr=null)}var zd=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),o=this.pluginInstances.get(e);if(!n||!o)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(o.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${r}: ${s}`)}}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()}},Hd=new zd;var F0=je(T0(),1);var An=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
345
- `);this.buffer=n.pop()||"";for(let o of n){let s=this.processLine(o);s&&r.enqueue(s)}},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 _s=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
343
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(n0).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)}};var o0=require("tiktoken"),ps=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,o0.get_encoding)(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:o,system:s,tools:a}=e;return Array.isArray(o)&&o.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 f=typeof l.content=="string"?l.content:JSON.stringify(l.content);n+=r.encode(f).length}})}),typeof s=="string"?n+=r.encode(s).length:Array.isArray(s)&&s.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}))}),a&&a.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)}};var _s=require("path"),C0=require("os"),go=require("fs"),bs=require("fs");var Dk=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 o=0;o<r.length;++o){let s=r[o];n=n[s]??=Object.create(null)}n.end=r}return e}split(t){let e=[],r=t.length,n=0,o=0;for(;o<r;){let s=this.trie,a=null,c=o;for(;c<r&&(s=s[t[c]]);)s.end&&(a=s.end),++c;a?(o>n&&e.push(t.slice(n,o)),e.push(a),o+=a.length,n=o):++o}return n<r&&e.push(t.slice(n)),e}},Rk=Dk,xk=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}},Ok=xk,d0=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),r=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+r),r+=1);let n=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,n[s]]))})(),Fk=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),Pk=Fk(d0),s0=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",Ik=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|[${s0}])]+`,` ?[^\\s${s0}]+`]]),ms="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",AO=new RegExp(`^[${ms}]+$`,"gu"),Nd=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"),Qa=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,o]of Ik)r=r.replaceAll(n,o);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=Nk(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},Nk=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Bk=(t,e,r)=>{let n=[],o=0;for(;o<t.length;){if(n.push(t[o]),(e.get(t[o])??r)!==r){++o;continue}for(;++o<t.length&&(e.get(t[o])??r)===r;)e.get(n.at(-1))!==r&&(n[n.length-1]+=t[o])}return n},Mk=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,jk=t=>Number.isInteger(t)||typeof t=="bigint",Lk=t=>{let e=0;for(let r of t)++e;return e},Uk=t=>f0(t.toLowerCase()),Nt=(...t)=>Array.prototype.concat.apply([],t),Bd=t=>new Map(Object.entries(t)),$k=(t,e)=>{let r=[],n=0;for(let o of t.matchAll(e)){let s=o[0];n<o.index&&r.push(t.slice(n,o.index)),s.length>0&&r.push(s),n=o.index+s.length}return n<t.length&&r.push(t.slice(n)),r},f0=t=>t.replace(new RegExp("\\p{M}","gu"),""),i0=(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},qk=t=>t.match(/\S+/g)||[],zk=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},gs=zk,Hk=class extends gs{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Rr=Hk,Wk=class extends Rr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],o=n.charCodeAt(0);Mk(o)?(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`
344
+ `: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}},Gk=Wk,Jk=class extends Rr{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}},Vk=Jk,Kk=class extends Rr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>h0(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},Yk=Kk,Qk=class extends Rr{normalize(t){let e=Qa(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},Xk=Qk,Zk=class extends Rr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Xa=Zk,ev=class extends Xa{constructor(){super(...arguments),this.form="NFC"}},tv=ev,rv=class extends Xa{constructor(){super(...arguments),this.form="NFD"}},nv=rv,ov=class extends Xa{constructor(){super(...arguments),this.form="NFKC"}},sv=ov,iv=class extends Xa{constructor(){super(...arguments),this.form="NFKD"}},av=iv,uv=class extends Rr{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}},cv=uv,lv=class extends Rr{normalize(t){return f0(t)}},dv=lv,fv=class extends Rr{normalize(t){return t.toLowerCase()}},hv=fv,pv=class extends Rr{normalize(t){return t=this.config.prepend+t,t}},mv=pv;function gv(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new Gk(t);case"Precompiled":return new Vk(t);case"Sequence":return new Yk(t);case"Replace":return new Xk(t);case"NFC":return new tv(t);case"NFD":return new nv(t);case"NFKC":return new sv(t);case"NFKD":return new av(t);case"Strip":return new cv(t);case"StripAccents":return new dv(t);case"Lowercase":return new hv(t);case"Prepend":return new mv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var h0=gv,yv=class extends gs{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)}},lr=yv,_v=class extends lr{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=d0,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(""))}},bv=_v,Cv=class extends lr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},wv=Cv,Ev=class extends lr{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]}},Av=Ev,Sv=class extends lr{constructor(t){super(),this.config=t,this.pattern=Qa(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):$k(t,this.pattern)}},kv=Sv,vv=class extends lr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${ms}]+|[${ms}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Tv=vv,Dv=class extends lr{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)||[]}},Rv=Dv,xv=class extends lr{constructor(){super(),this.pattern=new RegExp(`[^\\s${ms}]+|[${ms}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Ov=xv,Fv=class extends lr{constructor(t){super(),this.config=t,this.pattern=Qa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Pv=Fv,Iv=class extends lr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>p0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Nv=Iv,Bv=class extends lr{pre_tokenize_text(t){return qk(t)}},Mv=Bv;function jv(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Ov;case"Sequence":return new Nv(t);case"Whitespace":return new wv;case"WhitespaceSplit":return new Mv;case"Metaspace":return new Av(t);case"ByteLevel":return new bv(t);case"Split":return new kv(t);case"Punctuation":return new Tv(t);case"Digits":return new Rv(t);case"Replace":return new Pv(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var p0=jv,Lv=class extends gs{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=Bk(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)}},Za=Lv,Uv=class extends Za{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=Bd(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 o=!1,s=0,a=[];for(;s<n.length;){let c=n.length,l=null;for(;s<c;){let f=n.slice(s,c).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){l=f;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},a0=Uv,u0=class m0{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new m0(!1,new Map)}},$v=class{constructor(){this.root=u0.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=u0.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)}}},qv=$v,Id=class g0{constructor(e,r,n,o,s){this.token_id=e,this.node_id=r,this.pos=n,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new g0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},zv=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 Id(this.bos_token_id??0,0,0,0,0),o=new Id(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(n)}insert(t,e,r,n){let o=this.nodes.length,s=new Id(n,o,t,e,r);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,c=null;for(let l of this.end_nodes[e]){let f=l.backtrace_score+s.score;(c===null||f>a)&&(c=l.clone(),a=f)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.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)}},Hv=zv;function Wv(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 Gv=class extends Za{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,o)=>[n,o])),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=Wv(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new qv,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 o=!1,s=[],a=e.slice(n).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let f=this.tokens_to_ids.get(l),d=this.scores[f],m=Lk(l);t.insert(n,m,d,f),!o&&m===r&&(o=!0)}o||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new Hv(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}},c0=Gv,Jv=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}},Vv=Jv,Kv=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()}},Yv=Kv,Qv=class extends Za{constructor(t){super(t),this.tokens_to_ids=Bd(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 Yv(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 o=new Vv((c,l)=>c.score<l.score),s={token:r[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[c],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let c=o.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let f={...c.prev};c.prev.deleted=!0,c.prev=f,f.prev?f.prev.next=f:s=f}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(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let c=s;c!==null;c=c.next)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let o=0;o<n.length-1;++o)n[o]+=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 o of n)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},l0=Qv,Xv=class extends Za{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Bd(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,o]of this.tokens_to_ids)this.vocab[o]=n}encode(t){return t}},Zv=Xv;function eT(t,e){switch(t.type){case"WordPiece":return new a0(t);case"Unigram":return new c0(t,e.eos_token);case"BPE":return new l0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new c0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new l0(t):new a0(t):new Zv(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 tT=eT,rT=class extends gs{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ys=rT,nT=class extends ys{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of n)"SpecialToken"in a?r&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Nt(o,t),s=Nt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Nt(o,e),s=Nt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},oT=nT,sT=class extends ys{post_process(t,e=null){return{tokens:e?Nt(t,e):t}}},iT=sT,aT=class extends ys{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Nt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=[],s=r?[this.sep[0]]:[];t=Nt(t,o,e,s),n=Nt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},uT=aT,cT=class extends ys{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Nt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=r?[this.sep[0]]:[],s=r?[this.sep[0]]:[];t=Nt(t,o,e,s),n=Nt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},lT=cT,dT=class extends ys{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>y0(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let o of this.processors)n=o.post_process(n.tokens,e,r);return n}},fT=dT;function hT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new oT(t);case"ByteLevel":return new iT(t);case"BertProcessing":return new uT(t);case"RobertaProcessing":return new lT(t);case"Sequence":return new fT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var y0=hT,pT=class extends gs{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("")}},dr=pT,mT=class extends dr{constructor(t){super(t),this.byte_decoder=Pk,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(o=>o.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}},gT=mT,yT=class extends dr{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=Nd(e)),e})}},_T=yT,bT=class extends dr{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}},CT=bT,wT=class extends dr{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},ET=wT,AT=class extends dr{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=Nd(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},ST=AT,kT=class extends dr{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>_0(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},vT=kT,TT=class extends dr{decode_chain(t){let e=Qa(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},DT=TT,RT=class extends dr{decode_chain(t){return[t.join("")]}},xT=RT,OT=class extends dr{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 o=0;o<this.start&&e[o]===this.content;++o)r=o+1;let n=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){n=s;continue}else break}return e.slice(r,n)})}},FT=OT,PT=class extends dr{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let o=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let s=parseInt(n.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)r.push(o);else{if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},IT=PT;function NT(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new gT(t);case"WordPiece":return new _T(t);case"Metaspace":return new CT(t);case"BPEDecoder":return new ET(t);case"CTC":return new ST(t);case"Sequence":return new vT(t);case"Replace":return new DT(t);case"Fuse":return new xT(t);case"Strip":return new FT(t);case"ByteFallback":return new IT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var _0=NT,BT=class{constructor(t,e){let r=i0(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=i0(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=h0(this.tokenizer.normalizer),this.pre_tokenizer=p0(this.tokenizer.pre_tokenizer),this.model=tT(this.tokenizer.model,this.config),this.post_processor=y0(this.tokenizer.post_processor),this.decoder=_0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new Ok(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),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 Rk(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),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:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return n&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!jk(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(o=>!this.special_tokens.includes(o)));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=Nd(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 o=this.added_tokens_map.get(r);o&&(o.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),o.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=Uk(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(n,o,r):{tokens:Nt(n??[],o??[])}}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}},b0=BT;var eu=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||(0,_s.join)((0,C0.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,_s.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,_s.join)(e,"tokenizer.json"),tokenizerConfig:(0,_s.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,go.existsSync)(e)||(0,go.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,go.existsSync)(e.tokenizerJson)||!(0,go.existsSync)(e.tokenizerConfig))return null;let[r,n]=await Promise.all([bs.promises.readFile(e.tokenizerJson,"utf-8"),bs.promises.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,o=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[c,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([bs.promises.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),bs.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(o)}}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 b0(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:o,tools:s}=e;if(Array.isArray(n)){for(let a of n)if(typeof a.content=="string")r.push(a.content);else if(Array.isArray(a.content))for(let c of a.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 o=="string")r.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")r.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&r.push(c)}}if(s)for(let a of s)a.name&&r.push(a.name),a.description&&r.push(a.description),a.input_schema&&r.push(JSON.stringify(a.input_schema));return r.join(" ")}};var tu=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 o=new URL(e.url);this.name=`api-${o.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},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(r),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let c=await a.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(o=>{o&&r.push(o)}))}),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("."),o=e;for(let s of n){if(o==null)throw new Error(`Field path '${r}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${r}', got ${typeof o}`);return o}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 Sn=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 ps("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 ps(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new eu(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new tu(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(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.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 o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[r]?o.tokenizer.models[r]:o.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)}`}}};var A0=require("tiktoken");var Md=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())}},ru=new Md(100);var nu=require("fs/promises"),iu=require("fs/promises"),ou=require("path"),yo=require("@wengine-ai/claude-code-router-shared");Un();ii();var xr=(0,A0.get_encoding)("cl100k_base"),Ld=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?n+=xr.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?n+=xr.encode(s.text).length:s.type==="tool_use"?n+=xr.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(n+=xr.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?n+=xr.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?n+=xr.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{n+=xr.encode(s||"").length}))}),r&&r.forEach(o=>{o.description&&(n+=xr.encode(o.name+o.description).length),o.input_schema&&(n+=xr.encode(JSON.stringify(o.input_schema)).length)}),n},S0=async(t,e)=>{if(t.sessionId){let r=await Ud(t.sessionId);if(r){let n=(0,ou.join)(yo.HOME_DIR,r,"config.json"),o=(0,ou.join)(yo.HOME_DIR,r,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,nu.readFile)(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await(0,nu.readFile)(n,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function su(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 k0(t){let e=su(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),o=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:r};let s=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:r}:{family:null,extended:r}}function MT(t,e){if(!e||!t)return null;let r=su(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=k0(t);if(n&&e[n])return e[n];for(let[o,s]of Object.entries(e)){let a=su(o);if(a&&r.includes(a))return s}return null}function v0(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function w0(t){if(!t?.includes(","))return null;let[e,...r]=t.split(","),n=e.trim(),o=r.join(",").trim();return!n||!o?null:{providerName:n,routeModel:o}}function rt(t,e,r,n){let o=w0(t);if(!o)return t;let{providerName:s,routeModel:a}=o;if(n&&!r){let f=Fo(),d=f.getPromotion(s,a,n,e);if(d){let m=w0(d);if(m){let C=e.find(A=>A.name.toLowerCase()===m.providerName.toLowerCase()),v=C?.models?.find(A=>String(A).toLowerCase()===m.routeModel.toLowerCase());if(C&&v)return`${C.name},${v}`}f.clear(s,a,n)}}if(!r&&!st().isAvailable(s,a))return null;let c=e.find(f=>f.name.toLowerCase()===s.toLowerCase()),l=c?.models?.find(f=>String(f).toLowerCase()===a.toLowerCase());return c&&l?`${c.name},${l}`:t}function Yt(t,e,r,n,o){let s=st(),a=[r?.[t],n?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let f=rt(l,e);if(f)return f}return null}function jT(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 LT(t){let e=su(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 UT(t,e,r,n,o,s,a){let c=r.longContextThreshold||6e4,l=Math.max(e,v0(o)),f=t.modelFamily;if((s||l>2e5)&&r.extendedContext){let v=rt(r.extendedContext,n,!1,"extendedContext");if(v)return t.log.info(`Family: using extended context model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:v,scenarioType:"extendedContext",isFallback:!1};let A=Yt("extendedContext",n,r.fallback,a,f);if(A)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:A,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(l>c&&(r.longContext||r.fallback?.longContext?.length||a?.longContext?.length)){let v=r.longContext?rt(r.longContext,n,!1,"longContext"):null;if(v)return t.log.info(`Family: using long context model, tokens: ${l}, estimated: ${e}`),{model:v,scenarioType:"longContext",isFallback:!1};let A=Yt("longContext",n,r.fallback,a,f);if(A)return t.log.info(`Family: using long context fallback model, tokens: ${l}, estimated: ${e}`),{model:A,scenarioType:"longContext",isFallback:!0};t.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(t.body.tools)&&t.body.tools.some(v=>v.type?.startsWith("web_search"))&&r.webSearch){let v=rt(r.webSearch,n,!1,"webSearch");if(v)return{model:v,scenarioType:"webSearch",isFallback:!1};let A=Yt("webSearch",n,r.fallback,a,f);if(A)return t.log.info("Family: using webSearch fallback model"),{model:A,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let v=rt(r.think,n,!1,"think");if(v)return{model:v,scenarioType:"think",isFallback:!1};let A=Yt("think",n,r.fallback,a,f);if(A)return t.log.info("Family: using think fallback model"),{model:A,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let v=rt(r.default,n,!1,"default");if(v)return{model:v,scenarioType:"default",isFallback:!1};let A=Yt("default",n,r.fallback,a,f);if(A)return t.log.info("Family: using default fallback model"),{model:A,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var $T=async(t,e,r,n)=>{let o=await S0(t,r),s=r.get("providers")||[],a=o||r.get("Router"),c=r.get("fallback");if(t.body.model.includes(",")){let p=rt(t.body.model,s,!1,"default");if(p)return{model:p,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let k=Yt("default",s,void 0,c);if(k)return t.log.info(`Using fallback for explicit model: ${k}`),{model:k,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:l,extended:f}=k0(t.body.model),d=a?.families?.[l||""];if(d){t.log.info(`Using model family routing for: ${l}${f?" (1M)":""}`),t.modelFamily=l,t.familyFallback=d.fallback;let p=UT(t,e,d,s,n,f,c);if(p)return{model:p.model,scenarioType:p.scenarioType}}let m=MT(t.body.model,a?.models);if(m){let p=rt(m,s,!1,"modelMapping");if(p)return t.log.info(`Using mapped model for ${t.body.model}: ${m}`),{model:p,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${m} unavailable (fail pool), skipping`)}let C=Math.max(e,v0(n)),v=a?.extendedContextThreshold||2e5;if(C>v&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${C}, estimated: ${e}, threshold: ${v}`);let p=rt(a.extendedContext,s,!1,"extendedContext");if(p)return{model:p,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let k=Yt("extendedContext",s,void 0,c);if(k)return{model:k,scenarioType:"extendedContext"}}let A=a?.longContextThreshold||6e4;if(C>A&&a?.longContext){t.log.info(`Using long context model due to token count: ${C}, estimated: ${e}, threshold: ${A}`);let p=rt(a.longContext,s,!1,"longContext");if(p)return{model:p,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let k=Yt("longContext",s,void 0,c);if(k)return{model:k,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let p=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(p)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${p[1]}</CCR-SUBAGENT-MODEL>`,""),{model:p[1],scenarioType:"default"}}let g=r.get("Router");if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&g?.background){t.log.info(`Using background model for ${t.body.model}`);let p=rt(g.background,s,!1,"background");if(p)return{model:p,scenarioType:"background"};t.log.warn(`Background model ${g.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.type?.startsWith("web_search"))&&a?.webSearch){let p=rt(a.webSearch,s,!1,"webSearch");if(p)return{model:p,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let k=Yt("webSearch",s,void 0,c);if(k)return{model:k,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let p=rt(a.think,s,!1,"think");if(p)return{model:p,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let k=Yt("think",s,void 0,c);if(k)return{model:k,scenarioType:"think"}}if(a?.default){let p=rt(a.default,s,!1,"default");if(p)return{model:p,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let k=Yt("default",s,void 0,c);if(k)return{model:k,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},au=async(t,e,r)=>{let{configService:n,event:o}=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 a=await S0(t,n)||n.get("Router"),c=n.get("providers")||[],l=ru.get(t.sessionId),{messages:f,system:d=[],tools:m}=t.body,C=n.get("REWRITE_SYSTEM_PROMPT");if(C&&d.length>1&&d[1]?.text?.includes("<env>")){let v=await(0,nu.readFile)(C,"utf-8");d[1].text=`${v}<env>${d[1].text.split("<env>").pop()}`}try{let[v,A]=t.body.model.split(","),b=r.tokenizerService?.getTokenizerConfigForModel(v,A),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:f,system:d,tools:m},b)).tokenCount:g=Ld(f,d,m),t.tokenCount=g;let p,k=n.get("CUSTOM_ROUTER_PATH");if(k)try{p=await require(k)(t,n.getAll(),{event:o})}catch(y){t.log.error(`failed to load custom router: ${y.message}`)}if(p)t.scenarioType="default";else{let y=await $T(t,g,n,l);p=y.model,t.scenarioType=y.scenarioType}if(a?.image&&p!==a.image&&jT(t)&&!LT(p)){let y=rt(a.image,c,!1,"image");y?(t.log.info(`Using image model fallback for ${p}`),p=y,t.scenarioType="image"):t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${p}`)}t.body.model=p}catch(v){t.log.error(`Error in router middleware: ${v.message}`),t.body.model=a?.default,t.scenarioType="default"}},Or=new Map,E0=1e3;function jd(){if(Or.size<=E0)return;let t=[...Or.keys()].slice(0,Or.size-E0);for(let e of t)Or.delete(e)}var Ud=async t=>{if(Or.has(t)){let e=Or.get(t);return!e||e===""?null:e}try{let e=await(0,iu.opendir)(yo.CLAUDE_PROJECTS_DIR),r=[];for await(let s of e)s.isDirectory()&&r.push(s.name);let n=r.map(async s=>{let a=(0,ou.join)(yo.CLAUDE_PROJECTS_DIR,s,`${t}.jsonl`);try{return(await(0,iu.stat)(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(n);for(let s of o)if(s)return Or.set(t,s),jd(),s;return Or.set(t,""),jd(),null}catch(e){return console.error("Error searching for project by session:",e),Or.set(t,""),jd(),null}};Un();var _o=class{async fetchJson(e,r,n,o){if(!r.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.apiKey}`},signal:AbortSignal.timeout(n)};if(o)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(o).toString())}catch{}try{let a=await fetch(e,s);return a.ok?await a.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},$d=class extends _o{async queryQuota(e,r,n){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,r,n),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>lt(l?.total_balance)!==void 0);if(!a)return null;let c=lt(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},qd=class extends _o{async queryQuota(e,r,n){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,r,n))?.data;if(!s||typeof s!="object")return null;let a={},c=lt(s.limit),l=lt(s.limit_remaining),f=lt(s.usage),d=lt(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),f!==void 0&&(a.usedBalance=f),d!==void 0&&(a.usedDailyBalance=d),this.hasQuotaData(a)?a:null}},zd=class extends _o{async queryQuota(e,r,n){let o=GT(e.baseUrl),a=(await this.fetchJson(o,e,r,n))?.data;if(!a||typeof a!="object")return null;let c={},l=lt(a.totalBalance),f=lt(a.balance);return l!==void 0&&(c.totalBalance=l),f!==void 0&&(c.remainingBalance=f),l!==void 0&&f!==void 0&&(c.usedBalance=Math.max(0,l-f)),this.hasQuotaData(c)?c:null}},Hd=class extends _o{async queryQuota(e,r,n){if(!e.quotaToken)return null;let o={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e.quotaToken}`},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:s}=await import("undici");o.dispatcher=new s(new URL(n).toString())}catch{}try{let s=await fetch("https://bigmodel.cn/api/monitor/usage/quota/limit",o);if(!s.ok)return null;let a=await s.json(),c=Array.isArray(a?.data?.limits)?a.data.limits:[],l={};for(let f of c)if(f.type==="TIME_LIMIT"){let d=lt(f.usage),m=lt(f.currentValue),C=lt(f.remaining);d!==void 0&&(l.usedDailyBalance=d),m!==void 0&&C!==void 0?l.limitDaily=m+C:d!==void 0&&C!==void 0&&(l.limitDaily=d+C),f.nextResetTime&&!l.resetTime&&(l.resetTime=new Date(f.nextResetTime).toISOString())}else if(f.type==="TOKENS_LIMIT"){let d=lt(f.usage),m=lt(f.currentValue),C=lt(f.remaining);d!==void 0&&(l.usedDailyBalance=d),m!==void 0&&C!==void 0?l.limitDaily=m+C:d!==void 0&&C!==void 0&&(l.limitDaily=d+C),f.nextResetTime&&!l.resetTime&&(l.resetTime=new Date(f.nextResetTime).toISOString())}return this.hasQuotaData(l)?l:null}catch{return null}}},qT=new $d,zT=new qd,HT=new zd,WT=new Hd;function uu(t){let e=T0(t);return e?e==="deepseek.com"||e.endsWith(".deepseek.com")?qT:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?zT:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?HT:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?WT:null:null}function GT(t){let e=T0(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function T0(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function lt(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let r=Number(e);return Number.isFinite(r)?r:void 0}var Wd=new Map;function cu(t,e){t&&Wd.set(t,{...e,provider:t,capturedAt:Date.now()})}function D0(t){let e=Wd.get(t);return e?{...e}:void 0}function R0(){return Array.from(Wd.values()).map(t=>({...t}))}var JT={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function VT(t){try{let e=new URL(t),r=e.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),e.pathname=`${r}/models`,e.toString()}catch{return null}}function KT(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Gd(t,e,r){let n=VT(t.baseUrl);if(!n)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let o={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=await fetch(n,o);if(s.headers&&Io(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===401||s.status===403)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(o){return{success:!1,error:o?.message||o?.toString()||"Unknown probe error"}}}var Cs=class{config;quotaProbeTimer;healthProbeTimer;getProviders;getHttpsProxy;logger;running=!1;constructor(e,r,n,o){this.config={...JT,...r},this.getProviders=e,this.getHttpsProxy=n,this.logger=o}start(){!this.config.enabled||this.running||(this.running=!0,setTimeout(()=>{this.running&&(this.runQuotaProbe(),this.runHealthProbe())},this.config.initialDelayMs),this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(e.length===0)return;let n=[];for(let s of e){let a=uu(s.baseUrl);a&&n.push({provider:s.name,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,r).then(c=>{c&&(cu(s.name,c),this.logger?.debug?.(`Stored quota probe result for ${s.name}`))})}),KT(s.baseUrl)&&n.push({provider:s.name,type:"rate-limit-headers",promise:Gd(s,this.config.probeTimeoutMs,r).then(()=>{})})}if(n.length===0)return;this.logger?.debug?.(`Running quota probe with ${n.length} tasks for ${e.length} providers`);let o=await Promise.allSettled(n.map(s=>s.promise));for(let s=0;s<n.length;s++){let a=o[s];if(a.status==="rejected"){let c=n[s];this.logger?.warn?.(`Quota probe failed for ${c.provider} (${c.type}): ${a.reason}`)}}}async runHealthProbe(){let e=st(),r=this.getProviders(),n=this.getHttpsProxy?.(),o=e.getFailPoolModels(),s=[];for(let c of o){let[l,f]=c.split(","),d=e.getState(l,f);if(d&&d.status==="open"&&e.needsProbe(d)){let m=r.find(C=>C.name===l);m&&!this.config.excludeProviders.includes(l)&&s.push({provider:m,model:f,state:d})}}if(s.length===0)return;this.logger?.debug?.(`Running health probe for ${s.length} open models`);for(let{provider:c,model:l}of s)e.markProbeAttempt(c.name,l);let a=await Promise.allSettled(s.map(({provider:c})=>Gd(c,this.config.probeTimeoutMs,n)));for(let c=0;c<s.length;c++){let{provider:l,model:f}=s[c],d=a[c];if(d.status==="fulfilled"){let m=d.value;if(m.success){for(let C of l.models)e.recordSuccess(l.name,C);this.logger?.info?.(`Health probe succeeded for ${l.name}`)}else{for(let C of l.models)e.recordFailure(l.name,C,m.error);this.logger?.warn?.(`Health probe failed for ${l.name}: ${m.error}`)}}else{for(let m of l.models)e.recordFailure(l.name,m,d.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${l.name}: ${d.reason}`)}}}async probeProviderManually(e){let n=this.getProviders().find(a=>a.name===e);if(!n)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;let o=this.getHttpsProxy?.(),s=await Gd(n,this.config.probeTimeoutMs,o);if(s.success)for(let a of n.models)st().recordSuccess(n.name,a);else for(let a of n.models)st().recordFailure(n.name,a,s.error);return s.success}},Qr=null;function Jd(t,e,r,n){return Qr||(Qr=new Cs(t,e,r,n)),Qr}function lu(t,e,r,n){let o=Jd(t,e,r,n);return o.start(),o}function du(){Qr&&Qr.stop()}function x0(){Qr&&(Qr.stop(),Qr=null)}var Vd=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),o=this.pluginInstances.get(e);if(!n||!o)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(o.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${r}: ${s}`)}}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()}},Kd=new Vd;var U0=Me(N0(),1);var kn=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
345
+ `);this.buffer=n.pop()||"";for(let o of n){let s=this.processLine(o);s&&r.enqueue(s)}},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 ws=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
346
346
  `),e.id&&(n+=`id: ${e.id}
347
347
  `),e.retry&&(n+=`retry: ${e.retry}
348
348
  `),e.data&&(e.data.type==="done"?n+=`data: [DONE]
349
349
  `:n+=`data: ${JSON.stringify(e.data)}
350
350
  `),n+=`
351
- `,r.enqueue(n)}})}};var Jd=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:o,value:s}=await r.read();if(o){n.close();break}let a=await e(s,n);a!==void 0&&n.enqueue(a)}}catch(o){n.error(o)}finally{r.releaseLock()}}})};Vd();Kd();Qd();R0();var Es=new Map,Zd=new Map,JT=1,ef={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,F0.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)_o.registerHandlers(r.outputHandlers);else{let s=[];for(let a of n)a==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&_o.registerHandlers(s)}r.outputOptions&&_o.setDefaultOptions(r.outputOptions);let o=async s=>{let a=t.tokenizerService;if(!a)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let c=s.provider,l=s.model,h=`${c}:${l}`;if(Zd.has(h))return Zd.get(h);let d=a.getTokenizerConfigForModel(c,l);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await a.getTokenizer(d);return Zd.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 s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,a,c)=>{let l=s.requestStartTime;if(!l)return;let h=s.id||Date.now().toString(),d;try{let _=s.body?.metadata?.user_id;if(_&&typeof _=="string")try{let g=JSON.parse(_);g.session_id&&(d=g.session_id)}catch{let g=_.match(/_session_([a-f0-9-]+)/i);d=g?g[1]:void 0}}catch{}if(!d)return;let p=await o(s);if(c instanceof ReadableStream){Es.set(h,{requestId:h,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[_,g]=c.tee();return(async()=>{let k=null,y=async E=>{let D=Es.get(h);if(!D)return;let F=performance.now();if(E){let $=D.firstTokenTime?D.firstTokenTime-D.startTime:0,V=D.lastTokenTime-D.startTime;D.tokensPerSecond=x0(D.tokenCount,V,$)}else{let $=F-1e3;D.tokenTimestamps=D.tokenTimestamps.filter(V=>V>$),D.tokensPerSecond=D.tokenTimestamps.length}await O0(D,n,r.outputOptions,E).catch($=>{t.log?.warn(`Failed to output streaming stats: ${$.message}`)})};try{let D=g.pipeThrough(new TextDecoderStream).pipeThrough(new An).getReader();for(k=setInterval(async()=>{Es.get(h)&&await y(!1)},1e3);;){let{done:F,value:$}=await D.read();if(F)break;let V=$,B=Es.get(h);if(!B)continue;let Y=performance.now();if(!B.firstTokenTime&&(V.event==="content_block_start"||V.event==="content_block_delta"||V.event==="text_block"||V.event==="content_block")&&(B.firstTokenTime=Y,B.timeToFirstToken=Math.round(Y-B.startTime)),V.event==="content_block_delta"&&V.data?.delta){let te=V.data.delta.type,Z="";if(te==="text_delta"?Z=V.data.delta.text||"":te==="input_json_delta"?Z=V.data.delta.partial_json||"":te==="thinking_delta"&&(Z=V.data.delta.thinking||""),Z){let ue=p&&p.encodeText?p.encodeText(Z).length:As(Z);B.tokenCount+=ue,B.lastTokenTime=Y;for(let he=0;he<ue;he++)B.tokenTimestamps.push(Y)}}V.event==="message_stop"&&(k&&(clearInterval(k),k=null),await y(!0),Es.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}`)}),_}let w=performance.now(),T=0,S=!1;if(c&&typeof c=="string")try{let _=JSON.parse(c);if(typeof _.usage?.output_tokens=="number")T=_.usage.output_tokens,S=!0;else{let g=_.content??_.message?.content;if(g!==void 0)if(S=!0,p)Array.isArray(g)?T=g.reduce((m,k)=>{if(k.type==="text"){let y=k.text||"";return m+(p.encodeText?p.encodeText(y).length:As(y))}return m},0):typeof g=="string"&&(T=p.encodeText?p.encodeText(g).length:As(g));else{let m=Array.isArray(g)?g.map(k=>k.text).join(""):typeof g=="string"?g:"";T=As(m)}}}catch{}if(S){let _=Math.round(w-l),g=w-l,m={requestId:h,sessionId:d,startTime:l,lastTokenTime:w,tokenCount:T,tokensPerSecond:x0(T,g),timeToFirstToken:_,stream:!1,tokenTimestamps:[]};await O0(m,n,r.outputOptions,!0)}return c})})};function x0(t,e,r=0){if(t<=0)return 0;let n=Math.max((e-r)/1e3,JT);return Math.round(t/n)}function As(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function O0(t,e,r,n=!1){let o=n?"[Token Speed Final]":"[Token Speed]",s={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()},a={prefix:o,metadata:{sessionId:t.sessionId},...r};for(let c of e)try{await _o.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}function VT(t={}){let e=(0,P0.default)({bodyLimit:52428800,...t});return e.setErrorHandler(_h),e.register(I0.default),e}var tf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;constructor(e={}){let{initialConfig:r,...n}=e;this.app=VT({...n,logger:n.logger??!0}),this.configService=new un(e),this.transformerService=new wn(this.configService,this.app.log),this.tokenizerService=new En(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new cn(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}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 ru(l,h,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Ku(c)});return}if(!r)throw new Error("options is required");let n=new un({initialConfig:{providers:r.Providers,Router:r.Router}}),o=new wn(n,this.app.log);await o.initialize();let s=new cn(n,o,this.app.log),a=new En(n,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",n),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await ru(l,h,{configService:n,tokenizerService:a})}),await Ku(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,o,s)=>{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)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(n,o)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body)try{let a=n.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[c,...l]=a.model.split(",");a.model=l.join(","),n.provider=c,n.model=l;return}catch(a){return n.log.error({error:a},"Error in modelProviderMiddleware:"),o.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}`);try{let n={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=su(()=>this.providerService.getProviders(),n,()=>this.configService.getHttpsProxy(),this.app.log)}catch(n){this.app.log.warn?.(`Failed to start active probe service: ${n.message}`)}let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`);try{iu()}catch{}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)}}},KT=tf;0&&(module.exports={ActiveProbeService,ConfigService,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getHealthStore,getQuotaAdapter,getQuotaResult,getRateLimitInfo,pluginManager,resetActiveProbeService,rewriteStream,router,searchProjectBySession,sessionUsageCache,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin});
351
+ `,r.enqueue(n)}})}};var Xd=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:o,value:s}=await r.read();if(o){n.close();break}let a=await e(s,n);a!==void 0&&n.enqueue(a)}}catch(o){n.error(o)}finally{r.releaseLock()}}})};Zd();ef();rf();M0();var ks=new Map,of=new Map,tD=1,sf={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,U0.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)Co.registerHandlers(r.outputHandlers);else{let s=[];for(let a of n)a==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&Co.registerHandlers(s)}r.outputOptions&&Co.setDefaultOptions(r.outputOptions);let o=async s=>{let a=t.tokenizerService;if(!a)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let c=s.provider,l=s.model,f=`${c}:${l}`;if(of.has(f))return of.get(f);let d=a.getTokenizerConfigForModel(c,l);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let m=await a.getTokenizer(d);return of.set(f,m),t.log?.info(`Created tokenizer for ${c}:${l} - ${m.name}`),m}catch(m){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${m.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,a,c)=>{let l=s.requestStartTime;if(!l)return;let f=s.id||Date.now().toString(),d;try{let b=s.body?.metadata?.user_id;if(b&&typeof b=="string")try{let g=JSON.parse(b);g.session_id&&(d=g.session_id)}catch{let g=b.match(/_session_([a-f0-9-]+)/i);d=g?g[1]:void 0}}catch{}if(!d)return;let m=await o(s);if(c instanceof ReadableStream){ks.set(f,{requestId:f,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[b,g]=c.tee();return(async()=>{let k=null,y=async E=>{let D=ks.get(f);if(!D)return;let F=performance.now();if(E){let q=D.firstTokenTime?D.firstTokenTime-D.startTime:0,V=D.lastTokenTime-D.startTime;D.tokensPerSecond=j0(D.tokenCount,V,q)}else{let q=F-1e3;D.tokenTimestamps=D.tokenTimestamps.filter(V=>V>q),D.tokensPerSecond=D.tokenTimestamps.length}await L0(D,n,r.outputOptions,E).catch(q=>{t.log?.warn(`Failed to output streaming stats: ${q.message}`)})};try{let D=g.pipeThrough(new TextDecoderStream).pipeThrough(new kn).getReader();for(k=setInterval(async()=>{ks.get(f)&&await y(!1)},1e3);;){let{done:F,value:q}=await D.read();if(F)break;let V=q,B=ks.get(f);if(!B)continue;let Y=performance.now();if(!B.firstTokenTime&&(V.event==="content_block_start"||V.event==="content_block_delta"||V.event==="text_block"||V.event==="content_block")&&(B.firstTokenTime=Y,B.timeToFirstToken=Math.round(Y-B.startTime)),V.event==="content_block_delta"&&V.data?.delta){let te=V.data.delta.type,Z="";if(te==="text_delta"?Z=V.data.delta.text||"":te==="input_json_delta"?Z=V.data.delta.partial_json||"":te==="thinking_delta"&&(Z=V.data.delta.thinking||""),Z){let ue=m&&m.encodeText?m.encodeText(Z).length:vs(Z);B.tokenCount+=ue,B.lastTokenTime=Y;for(let he=0;he<ue;he++)B.tokenTimestamps.push(Y)}}V.event==="message_stop"&&(k&&(clearInterval(k),k=null),await y(!0),ks.delete(f))}}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}`)}),b}let C=performance.now(),v=0,A=!1;if(c&&typeof c=="string")try{let b=JSON.parse(c);if(typeof b.usage?.output_tokens=="number")v=b.usage.output_tokens,A=!0;else{let g=b.content??b.message?.content;if(g!==void 0)if(A=!0,m)Array.isArray(g)?v=g.reduce((p,k)=>{if(k.type==="text"){let y=k.text||"";return p+(m.encodeText?m.encodeText(y).length:vs(y))}return p},0):typeof g=="string"&&(v=m.encodeText?m.encodeText(g).length:vs(g));else{let p=Array.isArray(g)?g.map(k=>k.text).join(""):typeof g=="string"?g:"";v=vs(p)}}}catch{}if(A){let b=Math.round(C-l),g=C-l,p={requestId:f,sessionId:d,startTime:l,lastTokenTime:C,tokenCount:v,tokensPerSecond:j0(v,g),timeToFirstToken:b,stream:!1,tokenTimestamps:[]};await L0(p,n,r.outputOptions,!0)}return c})})};function j0(t,e,r=0){if(t<=0)return 0;let n=Math.max((e-r)/1e3,tD);return Math.round(t/n)}function vs(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function L0(t,e,r,n=!1){let o=n?"[Token Speed Final]":"[Token Speed]",s={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()},a={prefix:o,metadata:{sessionId:t.sessionId},...r};for(let c of e)try{await Co.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}Un();function rD(t={}){let e=(0,$0.default)({bodyLimit:52428800,...t});return e.setErrorHandler(Sh),e.register(q0.default),e}var af=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:r,...n}=e;this.app=rD({...n,logger:n.logger??!0}),this.configService=new cn(e),this.transformerService=new An(this.configService,this.app.log),this.tokenizerService=new Sn(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new dn(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}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.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await au(l,f,{configService:this.configService,tokenizerService:this.tokenizerService})}),await ec(c)});return}if(!r)throw new Error("options is required");let n=new cn({initialConfig:{providers:r.Providers,Router:r.Router}}),o=new An(n,this.app.log);await o.initialize();let s=new dn(n,o,this.app.log),a=new Sn(n,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",n),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await au(l,f,{configService:n,tokenizerService:a})}),await ec(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,o,s)=>{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)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(n,o)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body)try{let a=n.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[c,...l]=a.model.split(",");a.model=l.join(","),n.provider=c,n.model=l;return}catch(a){return n.log.error({error:a},"Error in modelProviderMiddleware:"),o.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}`);try{let n={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=lu(()=>this.providerService.getProviders(),n,()=>this.configService.getHttpsProxy(),this.app.log)}catch(n){this.app.log.warn?.(`Failed to start active probe service: ${n.message}`)}let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`);try{du()}catch{}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)}}},nD=af;0&&(module.exports={ActiveProbeService,ConfigService,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getHealthStore,getQuotaAdapter,getQuotaResult,getRateLimitInfo,pluginManager,resetActiveProbeService,rewriteStream,router,searchProjectBySession,sessionUsageCache,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin});
352
352
  /*! Bundled license information:
353
353
 
354
354
  web-streams-polyfill/dist/ponyfill.es2018.js: