@wengine-ai/llms 2.3.4 → 2.3.6
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.
- package/README.md +17 -3
- package/dist/cjs/server.cjs +204 -202
- package/dist/cjs/server.cjs.map +3 -3
- package/dist/esm/server.mjs +201 -199
- package/dist/esm/server.mjs.map +3 -3
- package/package.json +1 -1
package/dist/esm/server.mjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
var Wb=Object.create;var Js=Object.defineProperty;var Gb=Object.getOwnPropertyDescriptor;var Jb=Object.getOwnPropertyNames;var Vb=Object.getPrototypeOf,Kb=Object.prototype.hasOwnProperty;var oe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Le=(t,e)=>()=>(t&&(e=t(t=0)),e);var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Pu=(t,e)=>{for(var n in e)Js(t,n,{get:e[n],enumerable:!0})},yh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jb(e))!Kb.call(t,o)&&o!==n&&Js(t,o,{get:()=>e[o],enumerable:!(r=Gb(e,o))||r.enumerable});return t};var jn=(t,e,n)=>(n=t!=null?Wb(Vb(t)):{},yh(e||!t||!t.__esModule?Js(n,"default",{value:t,enumerable:!0}):n,t)),Yb=t=>yh(Js({},"__esModule",{value:!0}),t);var _h=X((NR,Vs)=>{Vs.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Vs.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]/;Vs.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 Iu=X((BR,bh)=>{var Fu=_h();bh.exports={isSpaceSeparator(t){return typeof t=="string"&&Fu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Fu.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"||Fu.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 Ah=X((MR,kh)=>{var We=Iu(),Bu,rt,bn,Ys,Un,Lt,Ge,ju,Oo;kh.exports=function(e,n){Bu=String(e),rt="start",bn=[],Ys=0,Un=1,Lt=0,Ge=void 0,ju=void 0,Oo=void 0;do Ge=Qb(),eC[rt]();while(Ge.type!=="eof");return typeof n=="function"?Mu({"":Oo},"",n):Oo};function Mu(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),a=Mu(r,s,n);a===void 0?delete r[s]:Object.defineProperty(r,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=Mu(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var _e,ye,xo,_n,Ee;function Qb(){for(_e="default",ye="",xo=!1,_n=1;;){Ee=Cn();let t=wh[_e]();if(t)return t}}function Cn(){if(Bu[Ys])return String.fromCodePoint(Bu.codePointAt(Ys))}function G(){let t=Cn();return t===`
|
|
2
|
-
`?(Un++,Lt=0):t?Lt+=t.length:Lt++,t&&(
|
|
3
|
-
`:case"\r":case"\u2028":case"\u2029":
|
|
4
|
-
`:case"\r":case"\u2028":case"\u2029":
|
|
5
|
-
`:case"\r":throw
|
|
6
|
-
`;case"r":return
|
|
7
|
-
`:case"\u2028":case"\u2029":return
|
|
8
|
-
`&&
|
|
9
|
-
`+s;S
|
|
10
|
-
`+s+
|
|
11
|
-
`+
|
|
12
|
-
`+s,
|
|
13
|
-
`+s+
|
|
14
|
-
`+g+"]"}return o.pop(),s=g,k}}});var $u=X((jR,vh)=>{var nC=Ah(),rC=Th(),oC={parse:nC,stringify:rC};vh.exports=oC});var $h={};Pu($h,{getFallbackPromotionStore:()=>Po,resetFallbackPromotionStore:()=>pC});function Po(t){return lr||(lr=new Hu,t&&lr.configure(t)),lr}function pC(){lr&&(lr.clearAll(),lr=null)}var hC,Hu,lr,ei=Le(()=>{"use strict";$n();hC=600*1e3,Hu=class{promotions=new Map;enabled=!0;ttlMs=hC;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,n,r){return`${e},${n}:${r}`}promote(e,n,r,o,s,a){if(!this.enabled)return;let c=this.getKey(e,n,r),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,n,r,o){if(!this.enabled)return null;let s=this.getKey(e,n,r),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...d]=a.promotedModel.split(","),f=d.join(",");if(!Ye().isAvailable(l,f))return this.promotions.delete(s),null;let m=o.find(C=>C.name.toLowerCase()===l.toLowerCase()),b=m?.models?.find(C=>String(C).toLowerCase()===f.toLowerCase());return!m||!b||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${b}`}clear(e,n,r){let o=this.getKey(e,n,r);this.promotions.delete(o)}clearByPrimary(e,n){let r=`${e},${n}:`,o=0;for(let s of this.promotions.keys())s.startsWith(r)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[n,r]of this.promotions)e-r.timestamp>=r.ttlMs&&this.promotions.delete(n)}getAllPromotions(){let e=Date.now(),n=[];for(let[r,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&n.push({key:r,promotedModel:o.promotedModel,remainingMs:s})}return n}},lr=null});import{existsSync as zh,mkdirSync as mC,readFileSync as gC,writeFileSync as yC}from"fs";import{join as Wh}from"path";import{HOME_DIR as _C}from"@wengine-ai/claude-code-router-shared";function EC(t){try{if(!zh(Gu))return;let e=JSON.parse(gC(Gu,"utf-8"));if(!Array.isArray(e))return;let n=Date.now();for(let r of e){if(!r||!r.provider||!r.model)continue;let o=r.updatedAt||r.lastFailureTime||0;o&&n-o>1440*60*1e3||t.restore({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount??0,successCount:r.successCount??0,lastFailureTime:r.lastFailureTime??0,lastProbeTime:r.lastProbeTime??0,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil})}}catch{}}function Hh(t){try{let e=t.getAllStates();if(e.length===0)return;zh(Wu)||mC(Wu,{recursive:!0});let n=e.map(r=>({...r,updatedAt:Date.now()}));yC(Gu,JSON.stringify(n,null,2),"utf-8")}catch{}}function Ju(){if(qh)return;qh=!0;let t=Ye();EC(t),wC=setInterval(()=>Hh(t),6e4),process.on("exit",()=>Hh(t))}function Ye(t){return zu||(zu=new ti(t)),zu}var bC,CC,ti,Wu,Gu,qh,wC,zu,$n=Le(()=>{"use strict";bC=120,CC={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},ti=class{states=new Map;config;probeTimer;constructor(e){this.config={...CC,...e}}getKey(e,n){return`${e},${n}`}recordSuccess(e,n){if(!this.config.enabled)return;let r=this.getKey(e,n),o=this.states.get(r);o&&(o.successCount++,!o.rateLimitUntil&&(o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,n),this.states.delete(r)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0)))}clearPromotionsForPrimary(e,n){try{let{getFallbackPromotionStore:r}=(ei(),Yb($h));r().clearByPrimary(e,n)}catch{}}recordFailure(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s||(s={provider:e,model:n,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,n){return this.states.get(this.getKey(e,n))}isAvailable(e,n){if(!this.config.enabled)return!0;let r=this.getState(e,n);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,n){if(!this.config.enabled)return 0;let r=this.getState(e,n);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&e.push(n);return e}getHalfOpenModels(){let e=[];for(let[n,r]of this.states)r.status==="half-open"&&e.push(n);return e}forceOpen(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=r,s.lastProbeTime=0):(s={provider:e,model:n,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r},this.states.set(o,s))}markRateLimited(e,n,r,o){if(!this.config.enabled)return;let s=this.getKey(e,n),a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=o||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:n,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o||"rate-limited"},this.states.set(s,a));let c=(r??bC)*1e3;a.rateLimitUntil=Date.now()+c}getRateLimitedModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&r.rateLimitUntil&&e.push(n);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,n){let r=this.getKey(e,n),o=this.states.get(r);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,n){let r=this.getKey(e,n);this.states.delete(r)}getAllStates(){return Array.from(this.states.values())}restore(e){this.states.set(this.getKey(e.provider,e.model),{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Wu=Wh(_C,"runtime"),Gu=Wh(Wu,"provider-health.json"),qh=!1,wC=null;zu=null});var dc=X((n1,Tp)=>{"use strict";var di=Object.prototype.hasOwnProperty,Sp=Object.prototype.toString,bp=Object.defineProperty,Cp=Object.getOwnPropertyDescriptor,wp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Sp.call(e)==="[object Array]"},Ep=function(e){if(!e||Sp.call(e)!=="[object Object]")return!1;var n=di.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&di.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||di.call(e,o)},kp=function(e,n){bp&&n.name==="__proto__"?bp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Ap=function(e,n){if(n==="__proto__")if(di.call(e,n)){if(Cp)return Cp(e,n).value}else return;return e[n]};Tp.exports=function t(){var e,n,r,o,s,a,c=arguments[0],l=1,d=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<d;++l)if(e=arguments[l],e!=null)for(n in e)r=Ap(c,n),o=Ap(e,n),c!==o&&(f&&o&&(Ep(o)||(s=wp(o)))?(s?(s=!1,a=r&&wp(r)?r:[]):a=r&&Ep(r)?r:{},kp(c,{name:n,newValue:t(f,a,o)})):typeof o<"u"&&kp(c,{name:n,newValue:o}));return c}});var vp=X((r1,cw)=>{cw.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 Rp=X((o1,Dp)=>{"use strict";var lw=vp();Dp.exports={pkg:lw}});var pc=X(St=>{"use strict";var Op=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=Pp;var xp=Op(dc()),dw=Op(Rp()),fc=dw.default.pkg;St.GAXIOS_ERROR_SYMBOL=Symbol.for(`${fc.name}-gaxios-error`);var hc=class t extends Error{config;response;code;status;error;[St.GAXIOS_ERROR_SYMBOL]=fc.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&St.GAXIOS_ERROR_SYMBOL in e&&e[St.GAXIOS_ERROR_SYMBOL]===fc.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,xp.default)(!0,{},n),this.response&&(this.response.config=(0,xp.default)(!0,{},this.response.config)),this.response){try{this.response.data=fw(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,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=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"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;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
|
-
`)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};St.GaxiosError=hc;function fw(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 Pp(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function r(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&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(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&&(Pp({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var Ip=X(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.getRetryConfig=hw;async function hw(t){let e=Fp(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 n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||pw)(t))return{shouldRetry:!1,config:t.config};let o=mw(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 pw(t){let e=Fp(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 n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Fp(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function mw(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var yc=X(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.GaxiosInterceptorManager=void 0;var gc=class extends Set{};fi.GaxiosInterceptorManager=gc});var Bp=X((u1,Np)=>{var qr=1e3,Hr=qr*60,zr=Hr*60,dr=zr*24,gw=dr*7,yw=dr*365.25;Np.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return _w(t);if(n==="number"&&isFinite(t))return e.long?Cw(t):bw(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function _w(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 n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*yw;case"weeks":case"week":case"w":return n*gw;case"days":case"day":case"d":return n*dr;case"hours":case"hour":case"hrs":case"hr":case"h":return n*zr;case"minutes":case"minute":case"mins":case"min":case"m":return n*Hr;case"seconds":case"second":case"secs":case"sec":case"s":return n*qr;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function bw(t){var e=Math.abs(t);return e>=dr?Math.round(t/dr)+"d":e>=zr?Math.round(t/zr)+"h":e>=Hr?Math.round(t/Hr)+"m":e>=qr?Math.round(t/qr)+"s":t+"ms"}function Cw(t){var e=Math.abs(t);return e>=dr?hi(t,e,dr,"day"):e>=zr?hi(t,e,zr,"hour"):e>=Hr?hi(t,e,Hr,"minute"):e>=qr?hi(t,e,qr,"second"):t+" ms"}function hi(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var _c=X((c1,Mp)=>{function ww(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=c,n.humanize=Bp(),n.destroy=d,Object.keys(t).forEach(f=>{n[f]=t[f]}),n.names=[],n.skips=[],n.formatters={};function e(f){let p=0;for(let m=0;m<f.length;m++)p=(p<<5)-p+f.charCodeAt(m),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(f){let p,m=null,b,C;function _(...g){if(!_.enabled)return;let y=_,k=Number(new Date),w=k-(p||k);y.diff=w,y.prev=p,y.curr=k,p=k,g[0]=n.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let S=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(v,$)=>{if(v==="%%")return"%";S++;let Y=n.formatters[$];if(typeof Y=="function"){let P=g[S];v=Y.call(y,P),g.splice(S,1),S--}return v}),n.formatArgs.call(y,g),(y.log||n.log).apply(y,g)}return _.namespace=f,_.useColors=n.useColors(),_.color=n.selectColor(f),_.extend=r,_.destroy=n.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(b!==n.namespaces&&(b=n.namespaces,C=n.enabled(f)),C),set:g=>{m=g}}),typeof n.init=="function"&&n.init(_),_}function r(f,p){let m=n(this.namespace+(typeof p>"u"?":":p)+f);return m.log=this.log,m}function o(f){n.save(f),n.namespaces=f,n.names=[],n.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of p)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function s(f,p){let m=0,b=0,C=-1,_=0;for(;m<f.length;)if(b<p.length&&(p[b]===f[m]||p[b]==="*"))p[b]==="*"?(C=b,_=m,b++):(m++,b++);else if(C!==-1)b=C+1,_++,m=_;else return!1;for(;b<p.length&&p[b]==="*";)b++;return b===p.length}function a(){let f=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),f}function c(f){for(let p of n.skips)if(s(f,p))return!1;for(let p of n.names)if(s(f,p))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function d(){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 n.enable(n.load()),n}Mp.exports=ww});var Lp=X((ut,pi)=>{ut.formatArgs=kw;ut.save=Aw;ut.load=Sw;ut.useColors=Ew;ut.storage=Tw();ut.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`."))}})();ut.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 Ew(){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 kw(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+pi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}ut.log=console.debug||console.log||(()=>{});function Aw(t){try{t?ut.storage.setItem("debug",t):ut.storage.removeItem("debug")}catch{}}function Sw(){let t;try{t=ut.storage.getItem("debug")||ut.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Tw(){try{return localStorage}catch{}}pi.exports=_c()(ut);var{formatters:vw}=pi.exports;vw.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Up=X((l1,jp)=>{"use strict";jp.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var Hp=X((d1,qp)=>{"use strict";var Dw=oe("os"),$p=oe("tty"),Tt=Up(),{env:Je}=process,qn;Tt("no-color")||Tt("no-colors")||Tt("color=false")||Tt("color=never")?qn=0:(Tt("color")||Tt("colors")||Tt("color=true")||Tt("color=always"))&&(qn=1);"FORCE_COLOR"in Je&&(Je.FORCE_COLOR==="true"?qn=1:Je.FORCE_COLOR==="false"?qn=0:qn=Je.FORCE_COLOR.length===0?1:Math.min(parseInt(Je.FORCE_COLOR,10),3));function bc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Cc(t,e){if(qn===0)return 0;if(Tt("color=16m")||Tt("color=full")||Tt("color=truecolor"))return 3;if(Tt("color=256"))return 2;if(t&&!e&&qn===void 0)return 0;let n=qn||0;if(Je.TERM==="dumb")return n;if(process.platform==="win32"){let r=Dw.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Je)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Je)||Je.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Je)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Je.TEAMCITY_VERSION)?1:0;if(Je.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Je){let r=parseInt((Je.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Je.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Je.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Je.TERM)||"COLORTERM"in Je?1:n}function Rw(t){let e=Cc(t,t&&t.isTTY);return bc(e)}qp.exports={supportsColor:Rw,stdout:bc(Cc(!0,$p.isatty(1))),stderr:bc(Cc(!0,$p.isatty(2)))}});var Wp=X((Ve,gi)=>{var xw=oe("tty"),mi=oe("util");Ve.init=Mw;Ve.log=Iw;Ve.formatArgs=Pw;Ve.save=Nw;Ve.load=Bw;Ve.useColors=Ow;Ve.destroy=mi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ve.colors=[6,2,3,4,5,1];try{let t=Hp();t&&(t.stderr||t).level>=2&&(Ve.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{}Ve.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function Ow(){return"colors"in Ve.inspectOpts?!!Ve.inspectOpts.colors:xw.isatty(process.stderr.fd)}function Pw(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
|
|
1
|
+
var Vb=Object.create;var Js=Object.defineProperty;var Kb=Object.getOwnPropertyDescriptor;var Qb=Object.getOwnPropertyNames;var Yb=Object.getPrototypeOf,Xb=Object.prototype.hasOwnProperty;var re=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Le=(t,e)=>()=>(t&&(e=t(t=0)),e);var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Pu=(t,e)=>{for(var n in e)Js(t,n,{get:e[n],enumerable:!0})},_h=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qb(e))!Xb.call(t,o)&&o!==n&&Js(t,o,{get:()=>e[o],enumerable:!(r=Kb(e,o))||r.enumerable});return t};var jn=(t,e,n)=>(n=t!=null?Vb(Yb(t)):{},_h(e||!t||!t.__esModule?Js(n,"default",{value:t,enumerable:!0}):n,t)),Zb=t=>_h(Js({},"__esModule",{value:!0}),t);var bh=X((UR,Vs)=>{Vs.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Vs.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]/;Vs.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 Iu=X(($R,Ch)=>{var Fu=bh();Ch.exports={isSpaceSeparator(t){return typeof t=="string"&&Fu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Fu.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"||Fu.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 Sh=X((qR,Ah)=>{var We=Iu(),Nu,rt,Cn,Qs,Un,Lt,Ge,ju,xo;Ah.exports=function(e,n){Nu=String(e),rt="start",Cn=[],Qs=0,Un=1,Lt=0,Ge=void 0,ju=void 0,xo=void 0;do Ge=eC(),rC[rt]();while(Ge.type!=="eof");return typeof n=="function"?Mu({"":xo},"",n):xo};function Mu(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),a=Mu(r,s,n);a===void 0?delete r[s]:Object.defineProperty(r,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=Mu(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var be,ye,Ro,bn,Ee;function eC(){for(be="default",ye="",Ro=!1,bn=1;;){Ee=wn();let t=Eh[be]();if(t)return t}}function wn(){if(Nu[Qs])return String.fromCodePoint(Nu.codePointAt(Qs))}function W(){let t=wn();return t===`
|
|
2
|
+
`?(Un++,Lt=0):t?Lt+=t.length:Lt++,t&&(Qs+=t.length),t}var Eh={default(){switch(Ee){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
|
|
3
|
+
`:case"\r":case"\u2028":case"\u2029":W();return;case"/":W(),be="comment";return;case void 0:return W(),Be("eof")}if(We.isSpaceSeparator(Ee)){W();return}return Eh[rt]()},comment(){switch(Ee){case"*":W(),be="multiLineComment";return;case"/":W(),be="singleLineComment";return}throw Ne(W())},multiLineComment(){switch(Ee){case"*":W(),be="multiLineCommentAsterisk";return;case void 0:throw Ne(W())}W()},multiLineCommentAsterisk(){switch(Ee){case"*":W();return;case"/":W(),be="default";return;case void 0:throw Ne(W())}W(),be="multiLineComment"},singleLineComment(){switch(Ee){case`
|
|
4
|
+
`:case"\r":case"\u2028":case"\u2029":W(),be="default";return;case void 0:return W(),Be("eof")}W()},value(){switch(Ee){case"{":case"[":return Be("punctuator",W());case"n":return W(),ur("ull"),Be("null",null);case"t":return W(),ur("rue"),Be("boolean",!0);case"f":return W(),ur("alse"),Be("boolean",!1);case"-":case"+":W()==="-"&&(bn=-1),be="sign";return;case".":ye=W(),be="decimalPointLeading";return;case"0":ye=W(),be="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":ye=W(),be="decimalInteger";return;case"I":return W(),ur("nfinity"),Be("numeric",1/0);case"N":return W(),ur("aN"),Be("numeric",NaN);case'"':case"'":Ro=W()==='"',ye="",be="string";return}throw Ne(W())},identifierNameStartEscape(){if(Ee!=="u")throw Ne(W());W();let t=Lu();switch(t){case"$":case"_":break;default:if(!We.isIdStartChar(t))throw wh();break}ye+=t,be="identifierName"},identifierName(){switch(Ee){case"$":case"_":case"\u200C":case"\u200D":ye+=W();return;case"\\":W(),be="identifierNameEscape";return}if(We.isIdContinueChar(Ee)){ye+=W();return}return Be("identifier",ye)},identifierNameEscape(){if(Ee!=="u")throw Ne(W());W();let t=Lu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!We.isIdContinueChar(t))throw wh();break}ye+=t,be="identifierName"},sign(){switch(Ee){case".":ye=W(),be="decimalPointLeading";return;case"0":ye=W(),be="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":ye=W(),be="decimalInteger";return;case"I":return W(),ur("nfinity"),Be("numeric",bn*(1/0));case"N":return W(),ur("aN"),Be("numeric",NaN)}throw Ne(W())},zero(){switch(Ee){case".":ye+=W(),be="decimalPoint";return;case"e":case"E":ye+=W(),be="decimalExponent";return;case"x":case"X":ye+=W(),be="hexadecimal";return}return Be("numeric",bn*0)},decimalInteger(){switch(Ee){case".":ye+=W(),be="decimalPoint";return;case"e":case"E":ye+=W(),be="decimalExponent";return}if(We.isDigit(Ee)){ye+=W();return}return Be("numeric",bn*Number(ye))},decimalPointLeading(){if(We.isDigit(Ee)){ye+=W(),be="decimalFraction";return}throw Ne(W())},decimalPoint(){switch(Ee){case"e":case"E":ye+=W(),be="decimalExponent";return}if(We.isDigit(Ee)){ye+=W(),be="decimalFraction";return}return Be("numeric",bn*Number(ye))},decimalFraction(){switch(Ee){case"e":case"E":ye+=W(),be="decimalExponent";return}if(We.isDigit(Ee)){ye+=W();return}return Be("numeric",bn*Number(ye))},decimalExponent(){switch(Ee){case"+":case"-":ye+=W(),be="decimalExponentSign";return}if(We.isDigit(Ee)){ye+=W(),be="decimalExponentInteger";return}throw Ne(W())},decimalExponentSign(){if(We.isDigit(Ee)){ye+=W(),be="decimalExponentInteger";return}throw Ne(W())},decimalExponentInteger(){if(We.isDigit(Ee)){ye+=W();return}return Be("numeric",bn*Number(ye))},hexadecimal(){if(We.isHexDigit(Ee)){ye+=W(),be="hexadecimalInteger";return}throw Ne(W())},hexadecimalInteger(){if(We.isHexDigit(Ee)){ye+=W();return}return Be("numeric",bn*Number(ye))},string(){switch(Ee){case"\\":W(),ye+=tC();return;case'"':if(Ro)return W(),Be("string",ye);ye+=W();return;case"'":if(!Ro)return W(),Be("string",ye);ye+=W();return;case`
|
|
5
|
+
`:case"\r":throw Ne(W());case"\u2028":case"\u2029":oC(Ee);break;case void 0:throw Ne(W())}ye+=W()},start(){switch(Ee){case"{":case"[":return Be("punctuator",W())}be="value"},beforePropertyName(){switch(Ee){case"$":case"_":ye=W(),be="identifierName";return;case"\\":W(),be="identifierNameStartEscape";return;case"}":return Be("punctuator",W());case'"':case"'":Ro=W()==='"',be="string";return}if(We.isIdStartChar(Ee)){ye+=W(),be="identifierName";return}throw Ne(W())},afterPropertyName(){if(Ee===":")return Be("punctuator",W());throw Ne(W())},beforePropertyValue(){be="value"},afterPropertyValue(){switch(Ee){case",":case"}":return Be("punctuator",W())}throw Ne(W())},beforeArrayValue(){if(Ee==="]")return Be("punctuator",W());be="value"},afterArrayValue(){switch(Ee){case",":case"]":return Be("punctuator",W())}throw Ne(W())},end(){throw Ne(W())}};function Be(t,e){return{type:t,value:e,line:Un,column:Lt}}function ur(t){for(let e of t){if(wn()!==e)throw Ne(W());W()}}function tC(){switch(wn()){case"b":return W(),"\b";case"f":return W(),"\f";case"n":return W(),`
|
|
6
|
+
`;case"r":return W(),"\r";case"t":return W()," ";case"v":return W(),"\v";case"0":if(W(),We.isDigit(wn()))throw Ne(W());return"\0";case"x":return W(),nC();case"u":return W(),Lu();case`
|
|
7
|
+
`:case"\u2028":case"\u2029":return W(),"";case"\r":return W(),wn()===`
|
|
8
|
+
`&&W(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ne(W());case void 0:throw Ne(W())}return W()}function nC(){let t="",e=wn();if(!We.isHexDigit(e)||(t+=W(),e=wn(),!We.isHexDigit(e)))throw Ne(W());return t+=W(),String.fromCodePoint(parseInt(t,16))}function Lu(){let t="",e=4;for(;e-- >0;){let n=wn();if(!We.isHexDigit(n))throw Ne(W());t+=W()}return String.fromCodePoint(parseInt(t,16))}var rC={start(){if(Ge.type==="eof")throw cr();Bu()},beforePropertyName(){switch(Ge.type){case"identifier":case"string":ju=Ge.value,rt="afterPropertyName";return;case"punctuator":Ks();return;case"eof":throw cr()}},afterPropertyName(){if(Ge.type==="eof")throw cr();rt="beforePropertyValue"},beforePropertyValue(){if(Ge.type==="eof")throw cr();Bu()},beforeArrayValue(){if(Ge.type==="eof")throw cr();if(Ge.type==="punctuator"&&Ge.value==="]"){Ks();return}Bu()},afterPropertyValue(){if(Ge.type==="eof")throw cr();switch(Ge.value){case",":rt="beforePropertyName";return;case"}":Ks()}},afterArrayValue(){if(Ge.type==="eof")throw cr();switch(Ge.value){case",":rt="beforeArrayValue";return;case"]":Ks()}},end(){}};function Bu(){let t;switch(Ge.type){case"punctuator":switch(Ge.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=Ge.value;break}if(xo===void 0)xo=t;else{let e=Cn[Cn.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,ju,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")Cn.push(t),Array.isArray(t)?rt="beforeArrayValue":rt="beforePropertyName";else{let e=Cn[Cn.length-1];e==null?rt="end":Array.isArray(e)?rt="afterArrayValue":rt="afterPropertyValue"}}function Ks(){Cn.pop();let t=Cn[Cn.length-1];t==null?rt="end":Array.isArray(t)?rt="afterArrayValue":rt="afterPropertyValue"}function Ne(t){return Ys(t===void 0?`JSON5: invalid end of input at ${Un}:${Lt}`:`JSON5: invalid character '${kh(t)}' at ${Un}:${Lt}`)}function cr(){return Ys(`JSON5: invalid end of input at ${Un}:${Lt}`)}function wh(){return Lt-=5,Ys(`JSON5: invalid identifier character at ${Un}:${Lt}`)}function oC(t){console.warn(`JSON5: '${kh(t)}' in strings is not valid ECMAScript; consider escaping`)}function kh(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 n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function Ys(t){let e=new SyntaxError(t);return e.lineNumber=Un,e.columnNumber=Lt,e}});var vh=X((zR,Th)=>{var Uu=Iu();Th.exports=function(e,n,r){let o=[],s="",a,c,l="",d;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,d=n.quote,n=n.replacer),typeof n=="function")c=n;else if(Array.isArray(n)){a=[];for(let _ of n){let y;typeof _=="string"?y=_:(typeof _=="number"||_ instanceof String||_ instanceof Number)&&(y=String(_)),y!==void 0&&a.indexOf(y)<0&&a.push(y)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),l=" ".substr(0,r)):typeof r=="string"&&(l=r.substr(0,10)),f("",{"":e});function f(_,y){let g=y[_];switch(g!=null&&(typeof g.toJSON5=="function"?g=g.toJSON5(_):typeof g.toJSON=="function"&&(g=g.toJSON(_))),c&&(g=c.call(y,_,g)),g instanceof Number?g=Number(g):g instanceof String?g=String(g):g instanceof Boolean&&(g=g.valueOf()),g){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof g=="string")return p(g,!1);if(typeof g=="number")return String(g);if(typeof g=="object")return Array.isArray(g)?C(g):m(g)}function p(_){let y={"'":.1,'"':.2},g={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},S="";for(let A=0;A<_.length;A++){let v=_[A];switch(v){case"'":case'"':y[v]++,S+=v;continue;case"\0":if(Uu.isDigit(_[A+1])){S+="\\x00";continue}}if(g[v]){S+=g[v];continue}if(v<" "){let R=v.charCodeAt(0).toString(16);S+="\\x"+("00"+R).substring(R.length);continue}S+=v}let w=d||Object.keys(y).reduce((A,v)=>y[A]<y[v]?A:v);return S=S.replace(new RegExp(w,"g"),g[w]),w+S+w}function m(_){if(o.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");o.push(_);let y=s;s=s+l;let g=a||Object.keys(_),S=[];for(let A of g){let v=f(A,_);if(v!==void 0){let R=b(A)+":";l!==""&&(R+=" "),R+=v,S.push(R)}}let w;if(S.length===0)w="{}";else{let A;if(l==="")A=S.join(","),w="{"+A+"}";else{let v=`,
|
|
9
|
+
`+s;A=S.join(v),w=`{
|
|
10
|
+
`+s+A+`,
|
|
11
|
+
`+y+"}"}}return o.pop(),s=y,w}function b(_){if(_.length===0)return p(_,!0);let y=String.fromCodePoint(_.codePointAt(0));if(!Uu.isIdStartChar(y))return p(_,!0);for(let g=y.length;g<_.length;g++)if(!Uu.isIdContinueChar(String.fromCodePoint(_.codePointAt(g))))return p(_,!0);return _}function C(_){if(o.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");o.push(_);let y=s;s=s+l;let g=[];for(let w=0;w<_.length;w++){let A=f(String(w),_);g.push(A!==void 0?A:"null")}let S;if(g.length===0)S="[]";else if(l==="")S="["+g.join(",")+"]";else{let w=`,
|
|
12
|
+
`+s,A=g.join(w);S=`[
|
|
13
|
+
`+s+A+`,
|
|
14
|
+
`+y+"]"}return o.pop(),s=y,S}}});var $u=X((HR,Dh)=>{var sC=Sh(),iC=vh(),aC={parse:sC,stringify:iC};Dh.exports=aC});var qh={};Pu(qh,{getFallbackPromotionStore:()=>Oo,resetFallbackPromotionStore:()=>yC});function Oo(t){return lr||(lr=new zu,t&&lr.configure(t)),lr}function yC(){lr&&(lr.clearAll(),lr=null)}var gC,zu,lr,ei=Le(()=>{"use strict";$n();gC=600*1e3,zu=class{promotions=new Map;enabled=!0;ttlMs=gC;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,n,r){return`${e},${n}:${r}`}promote(e,n,r,o,s,a){if(!this.enabled)return;let c=this.getKey(e,n,r),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,n,r,o){if(!this.enabled)return null;let s=this.getKey(e,n,r),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...d]=a.promotedModel.split(","),f=d.join(",");if(!Qe().isAvailable(l,f))return this.promotions.delete(s),null;let m=o.find(C=>C.name.toLowerCase()===l.toLowerCase()),b=m?.models?.find(C=>String(C).toLowerCase()===f.toLowerCase());return!m||!b||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${b}`}clear(e,n,r){let o=this.getKey(e,n,r);this.promotions.delete(o)}clearByPrimary(e,n){let r=`${e},${n}:`,o=0;for(let s of this.promotions.keys())s.startsWith(r)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[n,r]of this.promotions)e-r.timestamp>=r.ttlMs&&this.promotions.delete(n)}getAllPromotions(){let e=Date.now(),n=[];for(let[r,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&n.push({key:r,promotedModel:o.promotedModel,remainingMs:s})}return n}},lr=null});import{existsSync as Wh,mkdirSync as _C,readFileSync as bC,writeFileSync as CC}from"fs";import{join as Gh}from"path";import{HOME_DIR as wC}from"@wengine-ai/claude-code-router-shared";function SC(t){try{if(!Wh(Gu))return;let e=JSON.parse(bC(Gu,"utf-8"));if(!Array.isArray(e))return;let n=Date.now();for(let r of e){if(!r||!r.provider||!r.model)continue;let o=r.updatedAt||r.lastFailureTime||0;o&&n-o>1440*60*1e3||t.restore({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount??0,successCount:r.successCount??0,lastFailureTime:r.lastFailureTime??0,lastProbeTime:r.lastProbeTime??0,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil})}}catch{}}function Hh(t){try{let e=t.getAllStates();if(e.length===0)return;Wh(Wu)||_C(Wu,{recursive:!0});let n=e.map(r=>({...r,updatedAt:Date.now()}));CC(Gu,JSON.stringify(n,null,2),"utf-8")}catch{}}function Ju(){if(zh)return;zh=!0;let t=Qe();SC(t),AC=setInterval(()=>Hh(t),6e4),process.on("exit",()=>Hh(t))}function Qe(t){return Hu||(Hu=new ti(t)),Hu}var EC,kC,ti,Wu,Gu,zh,AC,Hu,$n=Le(()=>{"use strict";EC=120,kC={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},ti=class{states=new Map;config;probeTimer;constructor(e){this.config={...kC,...e}}getKey(e,n){return`${e},${n}`}recordSuccess(e,n){if(!this.config.enabled)return;let r=this.getKey(e,n),o=this.states.get(r);o&&(o.successCount++,!o.rateLimitUntil&&(o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,n),this.states.delete(r)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0)))}clearPromotionsForPrimary(e,n){try{let{getFallbackPromotionStore:r}=(ei(),Zb(qh));r().clearByPrimary(e,n)}catch{}}recordFailure(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s||(s={provider:e,model:n,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,n){return this.states.get(this.getKey(e,n))}isAvailable(e,n){if(!this.config.enabled)return!0;let r=this.getState(e,n);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,n){if(!this.config.enabled)return 0;let r=this.getState(e,n);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&e.push(n);return e}getHalfOpenModels(){let e=[];for(let[n,r]of this.states)r.status==="half-open"&&e.push(n);return e}forceOpen(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=r,s.lastProbeTime=0):(s={provider:e,model:n,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r},this.states.set(o,s))}markRateLimited(e,n,r,o){if(!this.config.enabled)return;let s=this.getKey(e,n),a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=o||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:n,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o||"rate-limited"},this.states.set(s,a));let c=(r??EC)*1e3;a.rateLimitUntil=Date.now()+c}getRateLimitedModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&r.rateLimitUntil&&e.push(n);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,n){let r=this.getKey(e,n),o=this.states.get(r);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,n){let r=this.getKey(e,n);this.states.delete(r)}getAllStates(){return Array.from(this.states.values())}restore(e){this.states.set(this.getKey(e.provider,e.model),{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Wu=Gh(wC,"runtime"),Gu=Gh(Wu,"provider-health.json"),zh=!1,AC=null;Hu=null});var dc=X((a1,vp)=>{"use strict";var di=Object.prototype.hasOwnProperty,Tp=Object.prototype.toString,Cp=Object.defineProperty,wp=Object.getOwnPropertyDescriptor,Ep=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Tp.call(e)==="[object Array]"},kp=function(e){if(!e||Tp.call(e)!=="[object Object]")return!1;var n=di.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&di.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||di.call(e,o)},Ap=function(e,n){Cp&&n.name==="__proto__"?Cp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Sp=function(e,n){if(n==="__proto__")if(di.call(e,n)){if(wp)return wp(e,n).value}else return;return e[n]};vp.exports=function t(){var e,n,r,o,s,a,c=arguments[0],l=1,d=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<d;++l)if(e=arguments[l],e!=null)for(n in e)r=Sp(c,n),o=Sp(e,n),c!==o&&(f&&o&&(kp(o)||(s=Ep(o)))?(s?(s=!1,a=r&&Ep(r)?r:[]):a=r&&kp(r)?r:{},Ap(c,{name:n,newValue:t(f,a,o)})):typeof o<"u"&&Ap(c,{name:n,newValue:o}));return c}});var Dp=X((u1,fw)=>{fw.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 xp=X((c1,Rp)=>{"use strict";var hw=Dp();Rp.exports={pkg:hw}});var pc=X(St=>{"use strict";var Pp=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=Fp;var Op=Pp(dc()),pw=Pp(xp()),fc=pw.default.pkg;St.GAXIOS_ERROR_SYMBOL=Symbol.for(`${fc.name}-gaxios-error`);var hc=class t extends Error{config;response;code;status;error;[St.GAXIOS_ERROR_SYMBOL]=fc.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&St.GAXIOS_ERROR_SYMBOL in e&&e[St.GAXIOS_ERROR_SYMBOL]===fc.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,Op.default)(!0,{},n),this.response&&(this.response.config=(0,Op.default)(!0,{},this.response.config)),this.response){try{this.response.data=mw(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,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=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"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;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
|
+
`)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};St.GaxiosError=hc;function mw(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 Fp(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function r(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&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(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&&(Fp({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var Bp=X(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.getRetryConfig=gw;async function gw(t){let e=Ip(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 n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||yw)(t))return{shouldRetry:!1,config:t.config};let o=_w(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 yw(t){let e=Ip(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 n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Ip(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function _w(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var yc=X(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.GaxiosInterceptorManager=void 0;var gc=class extends Set{};fi.GaxiosInterceptorManager=gc});var Mp=X((h1,Np)=>{var $r=1e3,qr=$r*60,zr=qr*60,dr=zr*24,bw=dr*7,Cw=dr*365.25;Np.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return ww(t);if(n==="number"&&isFinite(t))return e.long?kw(t):Ew(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function ww(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 n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*Cw;case"weeks":case"week":case"w":return n*bw;case"days":case"day":case"d":return n*dr;case"hours":case"hour":case"hrs":case"hr":case"h":return n*zr;case"minutes":case"minute":case"mins":case"min":case"m":return n*qr;case"seconds":case"second":case"secs":case"sec":case"s":return n*$r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function Ew(t){var e=Math.abs(t);return e>=dr?Math.round(t/dr)+"d":e>=zr?Math.round(t/zr)+"h":e>=qr?Math.round(t/qr)+"m":e>=$r?Math.round(t/$r)+"s":t+"ms"}function kw(t){var e=Math.abs(t);return e>=dr?hi(t,e,dr,"day"):e>=zr?hi(t,e,zr,"hour"):e>=qr?hi(t,e,qr,"minute"):e>=$r?hi(t,e,$r,"second"):t+" ms"}function hi(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var _c=X((p1,Lp)=>{function Aw(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=c,n.humanize=Mp(),n.destroy=d,Object.keys(t).forEach(f=>{n[f]=t[f]}),n.names=[],n.skips=[],n.formatters={};function e(f){let p=0;for(let m=0;m<f.length;m++)p=(p<<5)-p+f.charCodeAt(m),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(f){let p,m=null,b,C;function _(...y){if(!_.enabled)return;let g=_,S=Number(new Date),w=S-(p||S);g.diff=w,g.prev=p,g.curr=S,p=S,y[0]=n.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let A=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,$)=>{if(R==="%%")return"%";A++;let V=n.formatters[$];if(typeof V=="function"){let P=y[A];R=V.call(g,P),y.splice(A,1),A--}return R}),n.formatArgs.call(g,y),(g.log||n.log).apply(g,y)}return _.namespace=f,_.useColors=n.useColors(),_.color=n.selectColor(f),_.extend=r,_.destroy=n.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(b!==n.namespaces&&(b=n.namespaces,C=n.enabled(f)),C),set:y=>{m=y}}),typeof n.init=="function"&&n.init(_),_}function r(f,p){let m=n(this.namespace+(typeof p>"u"?":":p)+f);return m.log=this.log,m}function o(f){n.save(f),n.namespaces=f,n.names=[],n.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of p)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function s(f,p){let m=0,b=0,C=-1,_=0;for(;m<f.length;)if(b<p.length&&(p[b]===f[m]||p[b]==="*"))p[b]==="*"?(C=b,_=m,b++):(m++,b++);else if(C!==-1)b=C+1,_++,m=_;else return!1;for(;b<p.length&&p[b]==="*";)b++;return b===p.length}function a(){let f=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),f}function c(f){for(let p of n.skips)if(s(f,p))return!1;for(let p of n.names)if(s(f,p))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function d(){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 n.enable(n.load()),n}Lp.exports=Aw});var jp=X((ut,pi)=>{ut.formatArgs=Tw;ut.save=vw;ut.load=Dw;ut.useColors=Sw;ut.storage=Rw();ut.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`."))}})();ut.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 Sw(){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 Tw(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+pi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}ut.log=console.debug||console.log||(()=>{});function vw(t){try{t?ut.storage.setItem("debug",t):ut.storage.removeItem("debug")}catch{}}function Dw(){let t;try{t=ut.storage.getItem("debug")||ut.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Rw(){try{return localStorage}catch{}}pi.exports=_c()(ut);var{formatters:xw}=pi.exports;xw.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var $p=X((m1,Up)=>{"use strict";Up.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var Hp=X((g1,zp)=>{"use strict";var Ow=re("os"),qp=re("tty"),Tt=$p(),{env:Je}=process,qn;Tt("no-color")||Tt("no-colors")||Tt("color=false")||Tt("color=never")?qn=0:(Tt("color")||Tt("colors")||Tt("color=true")||Tt("color=always"))&&(qn=1);"FORCE_COLOR"in Je&&(Je.FORCE_COLOR==="true"?qn=1:Je.FORCE_COLOR==="false"?qn=0:qn=Je.FORCE_COLOR.length===0?1:Math.min(parseInt(Je.FORCE_COLOR,10),3));function bc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Cc(t,e){if(qn===0)return 0;if(Tt("color=16m")||Tt("color=full")||Tt("color=truecolor"))return 3;if(Tt("color=256"))return 2;if(t&&!e&&qn===void 0)return 0;let n=qn||0;if(Je.TERM==="dumb")return n;if(process.platform==="win32"){let r=Ow.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Je)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Je)||Je.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Je)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Je.TEAMCITY_VERSION)?1:0;if(Je.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Je){let r=parseInt((Je.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Je.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Je.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Je.TERM)||"COLORTERM"in Je?1:n}function Pw(t){let e=Cc(t,t&&t.isTTY);return bc(e)}zp.exports={supportsColor:Pw,stdout:bc(Cc(!0,qp.isatty(1))),stderr:bc(Cc(!0,qp.isatty(2)))}});var Gp=X((Ve,gi)=>{var Fw=re("tty"),mi=re("util");Ve.init=Uw;Ve.log=Mw;Ve.formatArgs=Bw;Ve.save=Lw;Ve.load=jw;Ve.useColors=Iw;Ve.destroy=mi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ve.colors=[6,2,3,4,5,1];try{let t=Hp();t&&(t.stderr||t).level>=2&&(Ve.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{}Ve.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function Iw(){return"colors"in Ve.inspectOpts?!!Ve.inspectOpts.colors:Fw.isatty(process.stderr.fd)}function Bw(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
|
|
16
16
|
`).join(`
|
|
17
|
-
`+s),t.push(o+"m+"+gi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=
|
|
18
|
-
`)}function
|
|
19
|
-
`).map(e=>e.trim()).join(" ")};
|
|
20
|
-
`).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new
|
|
17
|
+
`+s),t.push(o+"m+"+gi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Nw()+e+" "+t[0]}function Nw(){return Ve.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Mw(...t){return process.stderr.write(mi.formatWithOptions(Ve.inspectOpts,...t)+`
|
|
18
|
+
`)}function Lw(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function jw(){return process.env.DEBUG}function Uw(t){t.inspectOpts={};let e=Object.keys(Ve.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=Ve.inspectOpts[e[n]]}gi.exports=_c()(Ve);var{formatters:Wp}=gi.exports;Wp.o=function(t){return this.inspectOpts.colors=this.useColors,mi.inspect(t,this.inspectOpts).split(`
|
|
19
|
+
`).map(e=>e.trim()).join(" ")};Wp.O=function(t){return this.inspectOpts.colors=this.useColors,mi.inspect(t,this.inspectOpts)}});var Ec=X((y1,wc)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?wc.exports=jp():wc.exports=Gp()});var Kp=X(ct=>{"use strict";var $w=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),qw=ct&&ct.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Jp=ct&&ct.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&$w(e,t,n);return qw(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0});ct.req=ct.json=ct.toBuffer=void 0;var zw=Jp(re("http")),Hw=Jp(re("https"));async function Vp(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}ct.toBuffer=Vp;async function Ww(t){let n=(await Vp(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}ct.json=Ww;function Gw(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?Hw:zw).request(t,e),o=new Promise((s,a)=>{r.once("response",s).once("error",a).end()});return r.then=o.then.bind(o),r}ct.req=Gw});var Zp=X(pt=>{"use strict";var Yp=pt&&pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Jw=pt&&pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Xp=pt&&pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Yp(e,t,n);return Jw(e,t),e},Vw=pt&&pt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Yp(e,t,n)};Object.defineProperty(pt,"__esModule",{value:!0});pt.Agent=void 0;var Kw=Xp(re("net")),Qp=Xp(re("http")),Qw=re("https");Vw(Kp(),pt);var Yt=Symbol("AgentBaseInternalState"),kc=class extends Qp.Agent{constructor(e){super(e),this[Yt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
|
|
20
|
+
`).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new Kw.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Qw.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof Qp.Agent)try{return c.addRequest(e,o)}catch(l){return r(l)}this[Yt].currentSocket=c,super.createSocket(e,n,r)},c=>{this.decrementSockets(s,a),r(c)})}createConnection(){let e=this[Yt].currentSocket;if(this[Yt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Yt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Yt]&&(this[Yt].defaultPort=e)}get protocol(){return this[Yt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Yt]&&(this[Yt].protocol=e)}};pt.Agent=kc});var em=X(Hr=>{"use strict";var Yw=Hr&&Hr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Hr,"__esModule",{value:!0});Hr.parseProxyResponse=void 0;var Xw=Yw(Ec()),yi=(0,Xw.default)("https-proxy-agent:parse-proxy-response");function Zw(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let f=t.read();f?d(f):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),yi("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(f){a(),yi("onerror %o",f),n(f)}function d(f){o.push(f),r+=f.length;let p=Buffer.concat(o,r),m=p.indexOf(`\r
|
|
21
21
|
\r
|
|
22
22
|
`);if(m===-1){yi("have not received end of HTTP headers yet..."),s();return}let b=p.slice(0,m).toString("ascii").split(`\r
|
|
23
|
-
`),C=b.shift();if(!C)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let _=C.split(" "),
|
|
23
|
+
`),C=b.shift();if(!C)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let _=C.split(" "),y=+_[1],g=_.slice(2).join(" "),S={};for(let w of b){if(!w)continue;let A=w.indexOf(":");if(A===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${w}"`));let v=w.slice(0,A).toLowerCase(),R=w.slice(A+1).trimStart(),$=S[v];typeof $=="string"?S[v]=[$,R]:Array.isArray($)?$.push(R):S[v]=R}yi("got proxy server response: %o %o",C,S),a(),e({connect:{statusCode:y,statusText:g,headers:S},buffered:p})}t.on("error",l),t.on("end",c),s()})}Hr.parseProxyResponse=Zw});var im=X(vt=>{"use strict";var eE=vt&&vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),tE=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),om=vt&&vt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&eE(e,t,n);return tE(e,t),e},sm=vt&&vt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vt,"__esModule",{value:!0});vt.HttpsProxyAgent=void 0;var _i=om(re("net")),tm=om(re("tls")),nE=sm(re("assert")),rE=sm(Ec()),oE=Zp(),sE=re("url"),iE=em(),Bo=(0,rE.default)("https-proxy-agent"),nm=t=>t.servername===void 0&&t.host&&!_i.isIP(t.host)?{...t,servername:t.host}:t,bi=class extends oE.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new sE.URL(e):e,this.proxyHeaders=n?.headers??{},Bo("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(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"],...n?rm(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(Bo("Creating `tls.Socket`: %o",this.connectOpts),o=tm.connect(nm(this.connectOpts))):(Bo("Creating `net.Socket`: %o",this.connectOpts),o=_i.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=_i.isIPv6(n.host)?`[${n.host}]`:n.host,c=`CONNECT ${a}:${n.port} HTTP/1.1\r
|
|
24
24
|
`;if(r.username||r.password){let m=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(m).toString("base64")}`}s.Host=`${a}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let m of Object.keys(s))c+=`${m}: ${s[m]}\r
|
|
25
|
-
`;let l=(0,
|
|
26
|
-
`);let{connect:d,buffered:f}=await l;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),d.statusCode===200)return e.once("socket",oE),n.secureEndpoint?(Bo("Upgrading socket connection to TLS"),em.connect({...nm(tm(n),"host","path","port"),socket:o})):o;o.destroy();let p=new _i.Socket({writable:!1});return p.readable=!0,e.once("socket",m=>{Bo("Replaying proxy buffer for failed request"),(0,Zw.default)(m.listenerCount("data")>0),m.push(f),m.push(null)}),p}};bi.protocols=["http","https"];vt.HttpsProxyAgent=bi;function oE(t){t.resume()}function nm(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function sE(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 n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let f=1;f<n.length;f++)n[f]==="base64"?o=!0:n[f]&&(a+=`;${n[f]}`,n[f].indexOf("charset=")===0&&(r=n[f].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),d=Buffer.from(l,c);return d.type=s,d.typeFull=a,d.charset=r,d}var im,am=Le(()=>{im=sE});var cm=X((Ci,um)=>{(function(t,e){typeof Ci=="object"&&typeof um<"u"?e(Ci):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ci,(function(t){"use strict";function e(){}function n(i){return typeof i=="object"&&i!==null||typeof i=="function"}let r=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 d(i){return l(u=>u(i))}function f(i){return c(i)}function p(i,u,h){return a.call(i,u,h)}function m(i,u,h){p(p(i,u,h),void 0,r)}function b(i,u){m(i,u)}function C(i,u){m(i,void 0,u)}function _(i,u,h){return p(i,u,h)}function g(i){p(i,void 0,r)}let y=i=>{if(typeof queueMicrotask=="function")y=queueMicrotask;else{let u=d(void 0);y=h=>p(u,h)}return y(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 w(i,u,h){try{return d(k(i,u,h))}catch(A){return f(A)}}let S=16384;class R{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(u){let h=this._back,A=h;h._elements.length===S-1&&(A={_elements:[],_next:void 0}),h._elements.push(u),A!==h&&(this._back=A,h._next=A),++this._size}shift(){let u=this._front,h=u,A=this._cursor,x=A+1,j=u._elements,q=j[A];return x===S&&(h=u._next,x=0),--this._size,this._cursor=x,u!==h&&(this._front=h),j[A]=void 0,q}forEach(u){let h=this._cursor,A=this._front,x=A._elements;for(;(h!==x.length||A._next!==void 0)&&!(h===x.length&&(A=A._next,x=A._elements,h=0,x.length===0));)u(x[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let v=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),Y=Symbol("[[CancelSteps]]"),P=Symbol("[[PullSteps]]"),V=Symbol("[[ReleaseSteps]]");function H(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?ce(i):u._state==="closed"?me(i):re(i,u._storedError)}function Q(i,u){let h=i._ownerReadableStream;return Bt(h,u)}function J(i){let u=i._ownerReadableStream;u._state==="readable"?z(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Z(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[V](),u._reader=void 0,i._ownerReadableStream=void 0}function ee(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function ce(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function re(i,u){ce(i),z(i,u)}function me(i){ce(i),ie(i)}function z(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 Z(i,u){re(i,u)}function ie(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let Ue=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},Ae=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function K(i){return typeof i=="object"||typeof i=="function"}function ue(i,u){if(i!==void 0&&!K(i))throw new TypeError(`${u} is not an object.`)}function te(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}function ve(i){return typeof i=="object"&&i!==null||typeof i=="function"}function Oe(i,u){if(!ve(i))throw new TypeError(`${u} is not an object.`)}function je(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function E(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function T(i){return Number(i)}function D(i){return i===0?0:i}function M(i){return D(Ae(i))}function F(i,u){let A=Number.MAX_SAFE_INTEGER,x=Number(i);if(x=D(x),!Ue(x))throw new TypeError(`${u} is not a finite number`);if(x=M(x),x<0||x>A)throw new TypeError(`${u} is outside the accepted range of 0 to ${A}, inclusive`);return!Ue(x)||x===0?0:x}function N(i,u){if(!Nn(i))throw new TypeError(`${u} is not a ReadableStream.`)}function U(i){return new W(i)}function O(i,u){i._reader._readRequests.push(u)}function I(i,u,h){let x=i._reader._readRequests.shift();h?x._closeSteps():x._chunkSteps(u)}function L(i){return i._reader._readRequests.length}function B(i){let u=i._reader;return!(u===void 0||!se(u))}class W{constructor(u){if(je(u,1,"ReadableStreamDefaultReader"),N(u,"First parameter"),Bn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");H(this,u),this._readRequests=new R}get closed(){return se(this)?this._closedPromise:f(Me("closed"))}cancel(u=void 0){return se(this)?this._ownerReadableStream===void 0?f(ee("cancel")):Q(this,u):f(Me("cancel"))}read(){if(!se(this))return f(Me("read"));if(this._ownerReadableStream===void 0)return f(ee("read from"));let u,h,A=l((j,q)=>{u=j,h=q});return ae(this,{_chunkSteps:j=>u({value:j,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:j=>h(j)}),A}releaseLock(){if(!se(this))throw Me("releaseLock");this._ownerReadableStream!==void 0&&Se(this)}}Object.defineProperties(W.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(W.prototype.cancel,"cancel"),o(W.prototype.read,"read"),o(W.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(W.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function se(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof W}function ae(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[P](u)}function Se(i){J(i);let u=new TypeError("Reader was released");Ie(i,u)}function Ie(i,u){let h=i._readRequests;i._readRequests=new R,h.forEach(A=>{A._errorSteps(u)})}function Me(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let ke=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Te{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?_(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let h=()=>this._returnSteps(u);return this._ongoingPromise?_(this._ongoingPromise,h,h):h()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,h,A,x=l((q,ne)=>{h=q,A=ne});return ae(u,{_chunkSteps:q=>{this._ongoingPromise=void 0,y(()=>h({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,J(u),h({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,J(u),A(q)}}),x}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let A=Q(h,u);return J(h),_(A,()=>({value:u,done:!0}))}return J(h),d({value:u,done:!0})}}let qe={next(){return Er(this)?this._asyncIteratorImpl.next():f(kr("next"))},return(i){return Er(this)?this._asyncIteratorImpl.return(i):f(kr("return"))}};Object.setPrototypeOf(qe,ke);function wr(i,u){let h=U(i),A=new Te(h,u),x=Object.create(qe);return x._asyncIteratorImpl=A,x}function Er(i){if(!n(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Te}catch{return!1}}function kr(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let ft=Number.isNaN||function(i){return i!==i};var dn,Ze,He;function De(i){return i.slice()}function mf(i,u,h,A,x){new Uint8Array(i).set(new Uint8Array(h,A,x),u)}let fn=i=>(typeof i.transfer=="function"?fn=u=>u.transfer():typeof structuredClone=="function"?fn=u=>structuredClone(u,{transfer:[u]}):fn=u=>u,fn(i)),On=i=>(typeof i.detached=="boolean"?On=u=>u.detached:On=u=>u.byteLength===0,On(i));function gf(i,u,h){if(i.slice)return i.slice(u,h);let A=h-u,x=new ArrayBuffer(A);return mf(x,0,i,u,A),x}function Cs(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 l_(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),A=h.next;return{iterator:h,nextMethod:A,done:!1}}let su=(He=(dn=Symbol.asyncIterator)!==null&&dn!==void 0?dn:(Ze=Symbol.for)===null||Ze===void 0?void 0:Ze.call(Symbol,"Symbol.asyncIterator"))!==null&&He!==void 0?He:"@@asyncIterator";function yf(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=Cs(i,su),h===void 0){let j=Cs(i,Symbol.iterator),q=yf(i,"sync",j);return l_(q)}}else h=Cs(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let A=k(h,i,[]);if(!n(A))throw new TypeError("The iterator method must return an object");let x=A.next;return{iterator:A,nextMethod:x,done:!1}}function d_(i){let u=k(i.nextMethod,i.iterator,[]);if(!n(u))throw new TypeError("The iterator.next() method must return an object");return u}function f_(i){return!!i.done}function h_(i){return i.value}function p_(i){return!(typeof i!="number"||ft(i)||i<0)}function _f(i){let u=gf(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function iu(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function au(i,u,h){if(!p_(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 m_(i){return i._queue.peek().value}function Pn(i){i._queue=new R,i._queueTotalSize=0}function bf(i){return i===DataView}function g_(i){return bf(i.constructor)}function y_(i){return bf(i)?1:i.BYTES_PER_ELEMENT}class er{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!uu(this))throw hu("view");return this._view}respond(u){if(!uu(this))throw hu("respond");if(je(u,1,"respond"),u=F(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(On(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");As(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!uu(this))throw hu("respondWithNewView");if(je(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(On(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ss(this._associatedReadableByteStreamController,u)}}Object.defineProperties(er.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(er.prototype.respond,"respond"),o(er.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(er.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class hn{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!tr(this))throw ko("byobRequest");return fu(this)}get desiredSize(){if(!tr(this))throw ko("desiredSize");return Rf(this)}close(){if(!tr(this))throw ko("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`);Eo(this)}enqueue(u){if(!tr(this))throw ko("enqueue");if(je(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`);ks(this,u)}error(u=void 0){if(!tr(this))throw ko("error");kt(this,u)}[Y](u){Cf(this),Pn(this);let h=this._cancelAlgorithm(u);return Es(this),h}[P](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){Df(this,u);return}let A=this._autoAllocateChunkSize;if(A!==void 0){let x;try{x=new ArrayBuffer(A)}catch(q){u._errorSteps(q);return}let j={buffer:x,bufferByteLength:A,byteOffset:0,byteLength:A,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(j)}O(h,u),nr(this)}[V](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new R,this._pendingPullIntos.push(u)}}}Object.defineProperties(hn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(hn.prototype.close,"close"),o(hn.prototype.enqueue,"enqueue"),o(hn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function tr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof hn}function uu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof er}function nr(i){if(!E_(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,nr(i)),null),A=>(kt(i,A),null))}function Cf(i){lu(i),i._pendingPullIntos=new R}function cu(i,u){let h=!1;i._state==="closed"&&(h=!0);let A=wf(u);u.readerType==="default"?I(i,A,h):D_(i,A,h)}function wf(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function ws(i,u,h,A){i._queue.push({buffer:u,byteOffset:h,byteLength:A}),i._queueTotalSize+=A}function Ef(i,u,h,A){let x;try{x=gf(u,h,h+A)}catch(j){throw kt(i,j),j}ws(i,x,0,A)}function kf(i,u){u.bytesFilled>0&&Ef(i,u.buffer,u.byteOffset,u.bytesFilled),Ar(i)}function Af(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),A=u.bytesFilled+h,x=h,j=!1,q=A%u.elementSize,ne=A-q;ne>=u.minimumFill&&(x=ne-u.bytesFilled,j=!0);let pe=i._queue;for(;x>0;){let de=pe.peek(),ge=Math.min(x,de.byteLength),be=u.byteOffset+u.bytesFilled;mf(u.buffer,be,de.buffer,de.byteOffset,ge),de.byteLength===ge?pe.shift():(de.byteOffset+=ge,de.byteLength-=ge),i._queueTotalSize-=ge,Sf(i,ge,u),x-=ge}return j}function Sf(i,u,h){h.bytesFilled+=u}function Tf(i){i._queueTotalSize===0&&i._closeRequested?(Es(i),Ro(i._controlledReadableByteStream)):nr(i)}function lu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function du(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();Af(i,u)&&(Ar(i),cu(i._controlledReadableByteStream,u))}}function __(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();Df(i,h)}}function b_(i,u,h,A){let x=i._controlledReadableByteStream,j=u.constructor,q=y_(j),{byteOffset:ne,byteLength:pe}=u,de=h*q,ge;try{ge=fn(u.buffer)}catch(xe){A._errorSteps(xe);return}let be={buffer:ge,bufferByteLength:ge.byteLength,byteOffset:ne,byteLength:pe,bytesFilled:0,minimumFill:de,elementSize:q,viewConstructor:j,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(be),Pf(x,A);return}if(x._state==="closed"){let xe=new j(be.buffer,be.byteOffset,0);A._closeSteps(xe);return}if(i._queueTotalSize>0){if(Af(i,be)){let xe=wf(be);Tf(i),A._chunkSteps(xe);return}if(i._closeRequested){let xe=new TypeError("Insufficient bytes to fill elements in the given buffer");kt(i,xe),A._errorSteps(xe);return}}i._pendingPullIntos.push(be),Pf(x,A),nr(i)}function C_(i,u){u.readerType==="none"&&Ar(i);let h=i._controlledReadableByteStream;if(pu(h))for(;Ff(h)>0;){let A=Ar(i);cu(h,A)}}function w_(i,u,h){if(Sf(i,u,h),h.readerType==="none"){kf(i,h),du(i);return}if(h.bytesFilled<h.minimumFill)return;Ar(i);let A=h.bytesFilled%h.elementSize;if(A>0){let x=h.byteOffset+h.bytesFilled;Ef(i,h.buffer,x-A,A)}h.bytesFilled-=A,cu(i._controlledReadableByteStream,h),du(i)}function vf(i,u){let h=i._pendingPullIntos.peek();lu(i),i._controlledReadableByteStream._state==="closed"?C_(i,h):w_(i,u,h),nr(i)}function Ar(i){return i._pendingPullIntos.shift()}function E_(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(B(u)&&L(u)>0||pu(u)&&Ff(u)>0||Rf(i)>0)}function Es(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function Eo(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 A=new TypeError("Insufficient bytes to fill elements in the given buffer");throw kt(i,A),A}}Es(i),Ro(u)}}function ks(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:A,byteOffset:x,byteLength:j}=u;if(On(A))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=fn(A);if(i._pendingPullIntos.length>0){let ne=i._pendingPullIntos.peek();if(On(ne.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");lu(i),ne.buffer=fn(ne.buffer),ne.readerType==="none"&&kf(i,ne)}if(B(h))if(__(i),L(h)===0)ws(i,q,x,j);else{i._pendingPullIntos.length>0&&Ar(i);let ne=new Uint8Array(q,x,j);I(h,ne,!1)}else pu(h)?(ws(i,q,x,j),du(i)):ws(i,q,x,j);nr(i)}function kt(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(Cf(i),Pn(i),Es(i),rh(h,u))}function Df(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,Tf(i);let A=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(A)}function fu(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),A=Object.create(er.prototype);A_(A,i,h),i._byobRequest=A}return i._byobRequest}function Rf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function As(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=fn(h.buffer),vf(i,u)}function Ss(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 x=u.byteLength;h.buffer=fn(u.buffer),vf(i,x)}function xf(i,u,h,A,x,j,q){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Pn(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=j,u._pullAlgorithm=A,u._cancelAlgorithm=x,u._autoAllocateChunkSize=q,u._pendingPullIntos=new R,i._readableStreamController=u;let ne=h();m(d(ne),()=>(u._started=!0,nr(u),null),pe=>(kt(u,pe),null))}function k_(i,u,h){let A=Object.create(hn.prototype),x,j,q;u.start!==void 0?x=()=>u.start(A):x=()=>{},u.pull!==void 0?j=()=>u.pull(A):j=()=>d(void 0),u.cancel!==void 0?q=pe=>u.cancel(pe):q=()=>d(void 0);let ne=u.autoAllocateChunkSize;if(ne===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");xf(i,A,x,j,q,h,ne)}function A_(i,u,h){i._associatedReadableByteStreamController=u,i._view=h}function hu(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function ko(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function S_(i,u){ue(i,u);let h=i?.mode;return{mode:h===void 0?void 0:T_(h,`${u} has member 'mode' that`)}}function T_(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function v_(i,u){var h;ue(i,u);let A=(h=i?.min)!==null&&h!==void 0?h:1;return{min:F(A,`${u} has member 'min' that`)}}function Of(i){return new Fn(i)}function Pf(i,u){i._reader._readIntoRequests.push(u)}function D_(i,u,h){let x=i._reader._readIntoRequests.shift();h?x._closeSteps(u):x._chunkSteps(u)}function Ff(i){return i._reader._readIntoRequests.length}function pu(i){let u=i._reader;return!(u===void 0||!rr(u))}class Fn{constructor(u){if(je(u,1,"ReadableStreamBYOBReader"),N(u,"First parameter"),Bn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!tr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");H(this,u),this._readIntoRequests=new R}get closed(){return rr(this)?this._closedPromise:f(Ts("closed"))}cancel(u=void 0){return rr(this)?this._ownerReadableStream===void 0?f(ee("cancel")):Q(this,u):f(Ts("cancel"))}read(u,h={}){if(!rr(this))return f(Ts("read"));if(!ArrayBuffer.isView(u))return f(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(On(u.buffer))return f(new TypeError("view's buffer has been detached"));let A;try{A=v_(h,"options")}catch(de){return f(de)}let x=A.min;if(x===0)return f(new TypeError("options.min must be greater than 0"));if(g_(u)){if(x>u.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(x>u.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(ee("read from"));let j,q,ne=l((de,ge)=>{j=de,q=ge});return If(this,u,x,{_chunkSteps:de=>j({value:de,done:!1}),_closeSteps:de=>j({value:de,done:!0}),_errorSteps:de=>q(de)}),ne}releaseLock(){if(!rr(this))throw Ts("releaseLock");this._ownerReadableStream!==void 0&&R_(this)}}Object.defineProperties(Fn.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Fn.prototype.cancel,"cancel"),o(Fn.prototype.read,"read"),o(Fn.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fn.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function rr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Fn}function If(i,u,h,A){let x=i._ownerReadableStream;x._disturbed=!0,x._state==="errored"?A._errorSteps(x._storedError):b_(x._readableStreamController,u,h,A)}function R_(i){J(i);let u=new TypeError("Reader was released");Nf(i,u)}function Nf(i,u){let h=i._readIntoRequests;i._readIntoRequests=new R,h.forEach(A=>{A._errorSteps(u)})}function Ts(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(ft(h)||h<0)throw new RangeError("Invalid highWaterMark");return h}function vs(i){let{size:u}=i;return u||(()=>1)}function Ds(i,u){ue(i,u);let h=i?.highWaterMark,A=i?.size;return{highWaterMark:h===void 0?void 0:T(h),size:A===void 0?void 0:x_(A,`${u} has member 'size' that`)}}function x_(i,u){return te(i,u),h=>T(i(h))}function O_(i,u){ue(i,u);let h=i?.abort,A=i?.close,x=i?.start,j=i?.type,q=i?.write;return{abort:h===void 0?void 0:P_(h,i,`${u} has member 'abort' that`),close:A===void 0?void 0:F_(A,i,`${u} has member 'close' that`),start:x===void 0?void 0:I_(x,i,`${u} has member 'start' that`),write:q===void 0?void 0:N_(q,i,`${u} has member 'write' that`),type:j}}function P_(i,u,h){return te(i,h),A=>w(i,u,[A])}function F_(i,u,h){return te(i,h),()=>w(i,u,[])}function I_(i,u,h){return te(i,h),A=>k(i,u,[A])}function N_(i,u,h){return te(i,h),(A,x)=>w(i,u,[A,x])}function Bf(i,u){if(!Sr(i))throw new TypeError(`${u} is not a WritableStream.`)}function B_(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let M_=typeof AbortController=="function";function L_(){if(M_)return new AbortController}class In{constructor(u={},h={}){u===void 0?u=null:Oe(u,"First parameter");let A=Ds(h,"Second parameter"),x=O_(u,"First parameter");if(Lf(this),x.type!==void 0)throw new RangeError("Invalid type is specified");let q=vs(A),ne=Ao(A,1);X_(this,x,ne,q)}get locked(){if(!Sr(this))throw Fs("locked");return Tr(this)}abort(u=void 0){return Sr(this)?Tr(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Rs(this,u):f(Fs("abort"))}close(){return Sr(this)?Tr(this)?f(new TypeError("Cannot close a stream that already has a writer")):Yt(this)?f(new TypeError("Cannot close an already-closing stream")):jf(this):f(Fs("close"))}getWriter(){if(!Sr(this))throw Fs("getWriter");return Mf(this)}}Object.defineProperties(In.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(In.prototype.abort,"abort"),o(In.prototype.close,"close"),o(In.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(In.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Mf(i){return new pn(i)}function j_(i,u,h,A,x=1,j=()=>1){let q=Object.create(In.prototype);Lf(q);let ne=Object.create(vr.prototype);return Wf(q,ne,i,u,h,A,x,j),q}function Lf(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new R,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Sr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof In}function Tr(i){return i._writer!==void 0}function Rs(i,u){var h;if(i._state==="closed"||i._state==="errored")return d(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let A=i._state;if(A==="closed"||A==="errored")return d(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let x=!1;A==="erroring"&&(x=!0,u=void 0);let j=l((q,ne)=>{i._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:ne,_reason:u,_wasAlreadyErroring:x}});return i._pendingAbortRequest._promise=j,x||gu(i,u),j}function jf(i){let u=i._state;if(u==="closed"||u==="errored")return f(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((x,j)=>{let q={_resolve:x,_reject:j};i._closeRequest=q}),A=i._writer;return A!==void 0&&i._backpressure&&u==="writable"&&Au(A),Z_(i._writableStreamController),h}function U_(i){return l((h,A)=>{let x={_resolve:h,_reject:A};i._writeRequests.push(x)})}function mu(i,u){if(i._state==="writable"){gu(i,u);return}yu(i)}function gu(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let A=i._writer;A!==void 0&&$f(A,u),!W_(i)&&h._started&&yu(i)}function yu(i){i._state="errored",i._writableStreamController[$]();let u=i._storedError;if(i._writeRequests.forEach(x=>{x._reject(u)}),i._writeRequests=new R,i._pendingAbortRequest===void 0){xs(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),xs(i);return}let A=i._writableStreamController[v](h._reason);m(A,()=>(h._resolve(),xs(i),null),x=>(h._reject(x),xs(i),null))}function $_(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function q_(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,mu(i,u)}function H_(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&&Kf(h)}function z_(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),mu(i,u)}function Yt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function W_(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function G_(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function J_(i){i._inFlightWriteRequest=i._writeRequests.shift()}function xs(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&Eu(u,i._storedError)}function _u(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?ib(h):Au(h)),i._backpressure=u}class pn{constructor(u){if(je(u,1,"WritableStreamDefaultWriter"),Bf(u,"First parameter"),Tr(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")!Yt(u)&&u._backpressure?Ns(this):Yf(this),Is(this);else if(h==="erroring")ku(this,u._storedError),Is(this);else if(h==="closed")Yf(this),ob(this);else{let A=u._storedError;ku(this,A),Vf(this,A)}}get closed(){return or(this)?this._closedPromise:f(sr("closed"))}get desiredSize(){if(!or(this))throw sr("desiredSize");if(this._ownerWritableStream===void 0)throw To("desiredSize");return Q_(this)}get ready(){return or(this)?this._readyPromise:f(sr("ready"))}abort(u=void 0){return or(this)?this._ownerWritableStream===void 0?f(To("abort")):V_(this,u):f(sr("abort"))}close(){if(!or(this))return f(sr("close"));let u=this._ownerWritableStream;return u===void 0?f(To("close")):Yt(u)?f(new TypeError("Cannot close an already-closing stream")):Uf(this)}releaseLock(){if(!or(this))throw sr("releaseLock");this._ownerWritableStream!==void 0&&qf(this)}write(u=void 0){return or(this)?this._ownerWritableStream===void 0?f(To("write to")):Hf(this,u):f(sr("write"))}}Object.defineProperties(pn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(pn.prototype.abort,"abort"),o(pn.prototype.close,"close"),o(pn.prototype.releaseLock,"releaseLock"),o(pn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function or(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof pn}function V_(i,u){let h=i._ownerWritableStream;return Rs(h,u)}function Uf(i){let u=i._ownerWritableStream;return jf(u)}function K_(i){let u=i._ownerWritableStream,h=u._state;return Yt(u)||h==="closed"?d(void 0):h==="errored"?f(u._storedError):Uf(i)}function Y_(i,u){i._closedPromiseState==="pending"?Eu(i,u):sb(i,u)}function $f(i,u){i._readyPromiseState==="pending"?Qf(i,u):ab(i,u)}function Q_(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:Gf(u._writableStreamController)}function qf(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");$f(i,h),Y_(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function Hf(i,u){let h=i._ownerWritableStream,A=h._writableStreamController,x=eb(A,u);if(h!==i._ownerWritableStream)return f(To("write to"));let j=h._state;if(j==="errored")return f(h._storedError);if(Yt(h)||j==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(j==="erroring")return f(h._storedError);let q=U_(h);return tb(A,u,x),q}let zf={};class vr{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!bu(this))throw wu("abortReason");return this._abortReason}get signal(){if(!bu(this))throw wu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!bu(this))throw wu("error");this._controlledWritableStream._state==="writable"&&Jf(this,u)}[v](u){let h=this._abortAlgorithm(u);return Os(this),h}[$](){Pn(this)}}Object.defineProperties(vr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function bu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof vr}function Wf(i,u,h,A,x,j,q,ne){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Pn(u),u._abortReason=void 0,u._abortController=L_(),u._started=!1,u._strategySizeAlgorithm=ne,u._strategyHWM=q,u._writeAlgorithm=A,u._closeAlgorithm=x,u._abortAlgorithm=j;let pe=Cu(u);_u(i,pe);let de=h(),ge=d(de);m(ge,()=>(u._started=!0,Ps(u),null),be=>(u._started=!0,mu(i,be),null))}function X_(i,u,h,A){let x=Object.create(vr.prototype),j,q,ne,pe;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.write!==void 0?q=de=>u.write(de,x):q=()=>d(void 0),u.close!==void 0?ne=()=>u.close():ne=()=>d(void 0),u.abort!==void 0?pe=de=>u.abort(de):pe=()=>d(void 0),Wf(i,x,j,q,ne,pe,h,A)}function Os(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function Z_(i){au(i,zf,0),Ps(i)}function eb(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return So(i,h),1}}function Gf(i){return i._strategyHWM-i._queueTotalSize}function tb(i,u,h){try{au(i,u,h)}catch(x){So(i,x);return}let A=i._controlledWritableStream;if(!Yt(A)&&A._state==="writable"){let x=Cu(i);_u(A,x)}Ps(i)}function Ps(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){yu(u);return}if(i._queue.length===0)return;let A=m_(i);A===zf?nb(i):rb(i,A)}function So(i,u){i._controlledWritableStream._state==="writable"&&Jf(i,u)}function nb(i){let u=i._controlledWritableStream;G_(u),iu(i);let h=i._closeAlgorithm();Os(i),m(h,()=>(H_(u),null),A=>(z_(u,A),null))}function rb(i,u){let h=i._controlledWritableStream;J_(h);let A=i._writeAlgorithm(u);m(A,()=>{$_(h);let x=h._state;if(iu(i),!Yt(h)&&x==="writable"){let j=Cu(i);_u(h,j)}return Ps(i),null},x=>(h._state==="writable"&&Os(i),q_(h,x),null))}function Cu(i){return Gf(i)<=0}function Jf(i,u){let h=i._controlledWritableStream;Os(i),gu(h,u)}function Fs(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function wu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function sr(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function To(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Is(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function Vf(i,u){Is(i),Eu(i,u)}function ob(i){Is(i),Kf(i)}function Eu(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 sb(i,u){Vf(i,u)}function Kf(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 Ns(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function ku(i,u){Ns(i),Qf(i,u)}function Yf(i){Ns(i),Au(i)}function Qf(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 ib(i){Ns(i)}function ab(i,u){ku(i,u)}function Au(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 ub(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Su=ub();function cb(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function lb(){let i=Su?.DOMException;return cb(i)?i:void 0}function db(){let i=function(h,A){this.message=h||"",this.name=A||"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 fb=lb()||db();function Xf(i,u,h,A,x,j){let q=U(i),ne=Mf(u);i._disturbed=!0;let pe=!1,de=d(void 0);return l((ge,be)=>{let xe;if(j!==void 0){if(xe=()=>{let fe=j.reason!==void 0?j.reason:new fb("Aborted","AbortError"),we=[];A||we.push(()=>u._state==="writable"?Rs(u,fe):d(void 0)),x||we.push(()=>i._state==="readable"?Bt(i,fe):d(void 0)),at(()=>Promise.all(we.map(Pe=>Pe())),!0,fe)},j.aborted){xe();return}j.addEventListener("abort",xe)}function Mt(){return l((fe,we)=>{function Pe(ht){ht?fe():p(Or(),Pe,we)}Pe(!1)})}function Or(){return pe?d(!0):p(ne._readyPromise,()=>l((fe,we)=>{ae(q,{_chunkSteps:Pe=>{de=p(Hf(ne,Pe),void 0,e),fe(!1)},_closeSteps:()=>fe(!0),_errorSteps:we})}))}if(gn(i,q._closedPromise,fe=>(A?At(!0,fe):at(()=>Rs(u,fe),!0,fe),null)),gn(u,ne._closedPromise,fe=>(x?At(!0,fe):at(()=>Bt(i,fe),!0,fe),null)),nt(i,q._closedPromise,()=>(h?At():at(()=>K_(ne)),null)),Yt(u)||u._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");x?At(!0,fe):at(()=>Bt(i,fe),!0,fe)}g(Mt());function Ln(){let fe=de;return p(de,()=>fe!==de?Ln():void 0)}function gn(fe,we,Pe){fe._state==="errored"?Pe(fe._storedError):C(we,Pe)}function nt(fe,we,Pe){fe._state==="closed"?Pe():b(we,Pe)}function at(fe,we,Pe){if(pe)return;pe=!0,u._state==="writable"&&!Yt(u)?b(Ln(),ht):ht();function ht(){return m(fe(),()=>yn(we,Pe),Pr=>yn(!0,Pr)),null}}function At(fe,we){pe||(pe=!0,u._state==="writable"&&!Yt(u)?b(Ln(),()=>yn(fe,we)):yn(fe,we))}function yn(fe,we){return qf(ne),J(q),j!==void 0&&j.removeEventListener("abort",xe),fe?be(we):ge(void 0),null}})}class mn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bs(this))throw Ls("desiredSize");return Tu(this)}close(){if(!Bs(this))throw Ls("close");if(!Rr(this))throw new TypeError("The stream is not in a state that permits close");ir(this)}enqueue(u=void 0){if(!Bs(this))throw Ls("enqueue");if(!Rr(this))throw new TypeError("The stream is not in a state that permits enqueue");return Dr(this,u)}error(u=void 0){if(!Bs(this))throw Ls("error");Nt(this,u)}[Y](u){Pn(this);let h=this._cancelAlgorithm(u);return Ms(this),h}[P](u){let h=this._controlledReadableStream;if(this._queue.length>0){let A=iu(this);this._closeRequested&&this._queue.length===0?(Ms(this),Ro(h)):vo(this),u._chunkSteps(A)}else O(h,u),vo(this)}[V](){}}Object.defineProperties(mn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(mn.prototype.close,"close"),o(mn.prototype.enqueue,"enqueue"),o(mn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Bs(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof mn}function vo(i){if(!Zf(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,vo(i)),null),A=>(Nt(i,A),null))}function Zf(i){let u=i._controlledReadableStream;return!Rr(i)||!i._started?!1:!!(Bn(u)&&L(u)>0||Tu(i)>0)}function Ms(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function ir(i){if(!Rr(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Ms(i),Ro(u))}function Dr(i,u){if(!Rr(i))return;let h=i._controlledReadableStream;if(Bn(h)&&L(h)>0)I(h,u,!1);else{let A;try{A=i._strategySizeAlgorithm(u)}catch(x){throw Nt(i,x),x}try{au(i,u,A)}catch(x){throw Nt(i,x),x}}vo(i)}function Nt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Pn(i),Ms(i),rh(h,u))}function Tu(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function hb(i){return!Zf(i)}function Rr(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function eh(i,u,h,A,x,j,q){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Pn(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=q,u._strategyHWM=j,u._pullAlgorithm=A,u._cancelAlgorithm=x,i._readableStreamController=u;let ne=h();m(d(ne),()=>(u._started=!0,vo(u),null),pe=>(Nt(u,pe),null))}function pb(i,u,h,A){let x=Object.create(mn.prototype),j,q,ne;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.pull!==void 0?q=()=>u.pull(x):q=()=>d(void 0),u.cancel!==void 0?ne=pe=>u.cancel(pe):ne=()=>d(void 0),eh(i,x,j,q,ne,h,A)}function Ls(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function mb(i,u){return tr(i._readableStreamController)?yb(i):gb(i)}function gb(i,u){let h=U(i),A=!1,x=!1,j=!1,q=!1,ne,pe,de,ge,be,xe=l(nt=>{be=nt});function Mt(){return A?(x=!0,d(void 0)):(A=!0,ae(h,{_chunkSteps:at=>{y(()=>{x=!1;let At=at,yn=at;j||Dr(de._readableStreamController,At),q||Dr(ge._readableStreamController,yn),A=!1,x&&Mt()})},_closeSteps:()=>{A=!1,j||ir(de._readableStreamController),q||ir(ge._readableStreamController),(!j||!q)&&be(void 0)},_errorSteps:()=>{A=!1}}),d(void 0))}function Or(nt){if(j=!0,ne=nt,q){let at=De([ne,pe]),At=Bt(i,at);be(At)}return xe}function Ln(nt){if(q=!0,pe=nt,j){let at=De([ne,pe]),At=Bt(i,at);be(At)}return xe}function gn(){}return de=Do(gn,Mt,Or),ge=Do(gn,Mt,Ln),C(h._closedPromise,nt=>(Nt(de._readableStreamController,nt),Nt(ge._readableStreamController,nt),(!j||!q)&&be(void 0),null)),[de,ge]}function yb(i){let u=U(i),h=!1,A=!1,x=!1,j=!1,q=!1,ne,pe,de,ge,be,xe=l(fe=>{be=fe});function Mt(fe){C(fe._closedPromise,we=>(fe!==u||(kt(de._readableStreamController,we),kt(ge._readableStreamController,we),(!j||!q)&&be(void 0)),null))}function Or(){rr(u)&&(J(u),u=U(i),Mt(u)),ae(u,{_chunkSteps:we=>{y(()=>{A=!1,x=!1;let Pe=we,ht=we;if(!j&&!q)try{ht=_f(we)}catch(Pr){kt(de._readableStreamController,Pr),kt(ge._readableStreamController,Pr),be(Bt(i,Pr));return}j||ks(de._readableStreamController,Pe),q||ks(ge._readableStreamController,ht),h=!1,A?gn():x&&nt()})},_closeSteps:()=>{h=!1,j||Eo(de._readableStreamController),q||Eo(ge._readableStreamController),de._readableStreamController._pendingPullIntos.length>0&&As(de._readableStreamController,0),ge._readableStreamController._pendingPullIntos.length>0&&As(ge._readableStreamController,0),(!j||!q)&&be(void 0)},_errorSteps:()=>{h=!1}})}function Ln(fe,we){se(u)&&(J(u),u=Of(i),Mt(u));let Pe=we?ge:de,ht=we?de:ge;If(u,fe,1,{_chunkSteps:Fr=>{y(()=>{A=!1,x=!1;let Ir=we?q:j;if(we?j:q)Ir||Ss(Pe._readableStreamController,Fr);else{let gh;try{gh=_f(Fr)}catch(Ou){kt(Pe._readableStreamController,Ou),kt(ht._readableStreamController,Ou),be(Bt(i,Ou));return}Ir||Ss(Pe._readableStreamController,Fr),ks(ht._readableStreamController,gh)}h=!1,A?gn():x&&nt()})},_closeSteps:Fr=>{h=!1;let Ir=we?q:j,Gs=we?j:q;Ir||Eo(Pe._readableStreamController),Gs||Eo(ht._readableStreamController),Fr!==void 0&&(Ir||Ss(Pe._readableStreamController,Fr),!Gs&&ht._readableStreamController._pendingPullIntos.length>0&&As(ht._readableStreamController,0)),(!Ir||!Gs)&&be(void 0)},_errorSteps:()=>{h=!1}})}function gn(){if(h)return A=!0,d(void 0);h=!0;let fe=fu(de._readableStreamController);return fe===null?Or():Ln(fe._view,!1),d(void 0)}function nt(){if(h)return x=!0,d(void 0);h=!0;let fe=fu(ge._readableStreamController);return fe===null?Or():Ln(fe._view,!0),d(void 0)}function at(fe){if(j=!0,ne=fe,q){let we=De([ne,pe]),Pe=Bt(i,we);be(Pe)}return xe}function At(fe){if(q=!0,pe=fe,j){let we=De([ne,pe]),Pe=Bt(i,we);be(Pe)}return xe}function yn(){}return de=nh(yn,gn,at),ge=nh(yn,nt,At),Mt(u),[de,ge]}function _b(i){return n(i)&&typeof i.getReader<"u"}function bb(i){return _b(i)?wb(i.getReader()):Cb(i)}function Cb(i){let u,h=yf(i,"async"),A=e;function x(){let q;try{q=d_(h)}catch(pe){return f(pe)}let ne=d(q);return _(ne,pe=>{if(!n(pe))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(f_(pe))ir(u._readableStreamController);else{let ge=h_(pe);Dr(u._readableStreamController,ge)}})}function j(q){let ne=h.iterator,pe;try{pe=Cs(ne,"return")}catch(be){return f(be)}if(pe===void 0)return d(void 0);let de;try{de=k(pe,ne,[q])}catch(be){return f(be)}let ge=d(de);return _(ge,be=>{if(!n(be))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=Do(A,x,j,0),u}function wb(i){let u,h=e;function A(){let j;try{j=i.read()}catch(q){return f(q)}return _(j,q=>{if(!n(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)ir(u._readableStreamController);else{let ne=q.value;Dr(u._readableStreamController,ne)}})}function x(j){try{return d(i.cancel(j))}catch(q){return f(q)}}return u=Do(h,A,x,0),u}function Eb(i,u){ue(i,u);let h=i,A=h?.autoAllocateChunkSize,x=h?.cancel,j=h?.pull,q=h?.start,ne=h?.type;return{autoAllocateChunkSize:A===void 0?void 0:F(A,`${u} has member 'autoAllocateChunkSize' that`),cancel:x===void 0?void 0:kb(x,h,`${u} has member 'cancel' that`),pull:j===void 0?void 0:Ab(j,h,`${u} has member 'pull' that`),start:q===void 0?void 0:Sb(q,h,`${u} has member 'start' that`),type:ne===void 0?void 0:Tb(ne,`${u} has member 'type' that`)}}function kb(i,u,h){return te(i,h),A=>w(i,u,[A])}function Ab(i,u,h){return te(i,h),A=>w(i,u,[A])}function Sb(i,u,h){return te(i,h),A=>k(i,u,[A])}function Tb(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function vb(i,u){return ue(i,u),{preventCancel:!!i?.preventCancel}}function th(i,u){ue(i,u);let h=i?.preventAbort,A=i?.preventCancel,x=i?.preventClose,j=i?.signal;return j!==void 0&&Db(j,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!A,preventClose:!!x,signal:j}}function Db(i,u){if(!B_(i))throw new TypeError(`${u} is not an AbortSignal.`)}function Rb(i,u){ue(i,u);let h=i?.readable;E(h,"readable","ReadableWritablePair"),N(h,`${u} has member 'readable' that`);let A=i?.writable;return E(A,"writable","ReadableWritablePair"),Bf(A,`${u} has member 'writable' that`),{readable:h,writable:A}}class et{constructor(u={},h={}){u===void 0?u=null:Oe(u,"First parameter");let A=Ds(h,"Second parameter"),x=Eb(u,"First parameter");if(vu(this),x.type==="bytes"){if(A.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let j=Ao(A,0);k_(this,x,j)}else{let j=vs(A),q=Ao(A,1);pb(this,x,q,j)}}get locked(){if(!Nn(this))throw ar("locked");return Bn(this)}cancel(u=void 0){return Nn(this)?Bn(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Bt(this,u):f(ar("cancel"))}getReader(u=void 0){if(!Nn(this))throw ar("getReader");return S_(u,"First parameter").mode===void 0?U(this):Of(this)}pipeThrough(u,h={}){if(!Nn(this))throw ar("pipeThrough");je(u,1,"pipeThrough");let A=Rb(u,"First parameter"),x=th(h,"Second parameter");if(Bn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Tr(A.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let j=Xf(this,A.writable,x.preventClose,x.preventAbort,x.preventCancel,x.signal);return g(j),A.readable}pipeTo(u,h={}){if(!Nn(this))return f(ar("pipeTo"));if(u===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Sr(u))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let A;try{A=th(h,"Second parameter")}catch(x){return f(x)}return Bn(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Tr(u)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Xf(this,u,A.preventClose,A.preventAbort,A.preventCancel,A.signal)}tee(){if(!Nn(this))throw ar("tee");let u=mb(this);return De(u)}values(u=void 0){if(!Nn(this))throw ar("values");let h=vb(u,"First parameter");return wr(this,h.preventCancel)}[su](u){return this.values(u)}static from(u){return bb(u)}}Object.defineProperties(et,{from:{enumerable:!0}}),Object.defineProperties(et.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(et.from,"from"),o(et.prototype.cancel,"cancel"),o(et.prototype.getReader,"getReader"),o(et.prototype.pipeThrough,"pipeThrough"),o(et.prototype.pipeTo,"pipeTo"),o(et.prototype.tee,"tee"),o(et.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(et.prototype,su,{value:et.prototype.values,writable:!0,configurable:!0});function Do(i,u,h,A=1,x=()=>1){let j=Object.create(et.prototype);vu(j);let q=Object.create(mn.prototype);return eh(j,q,i,u,h,A,x),j}function nh(i,u,h){let A=Object.create(et.prototype);vu(A);let x=Object.create(hn.prototype);return xf(A,x,i,u,h,0,void 0),A}function vu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Nn(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof et}function Bn(i){return i._reader!==void 0}function Bt(i,u){if(i._disturbed=!0,i._state==="closed")return d(void 0);if(i._state==="errored")return f(i._storedError);Ro(i);let h=i._reader;if(h!==void 0&&rr(h)){let x=h._readIntoRequests;h._readIntoRequests=new R,x.forEach(j=>{j._closeSteps(void 0)})}let A=i._readableStreamController[Y](u);return _(A,e)}function Ro(i){i._state="closed";let u=i._reader;if(u!==void 0&&(ie(u),se(u))){let h=u._readRequests;u._readRequests=new R,h.forEach(A=>{A._closeSteps()})}}function rh(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(z(h,u),se(h)?Ie(h,u):Nf(h,u))}function ar(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function oh(i,u){ue(i,u);let h=i?.highWaterMark;return E(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:T(h)}}let sh=i=>i.byteLength;o(sh,"size");class js{constructor(u){je(u,1,"ByteLengthQueuingStrategy"),u=oh(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!ah(this))throw ih("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!ah(this))throw ih("size");return sh}}Object.defineProperties(js.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(js.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function ih(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function ah(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof js}let uh=()=>1;o(uh,"size");class Us{constructor(u){je(u,1,"CountQueuingStrategy"),u=oh(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!lh(this))throw ch("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!lh(this))throw ch("size");return uh}}Object.defineProperties(Us.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Us.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ch(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function lh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof Us}function xb(i,u){ue(i,u);let h=i?.cancel,A=i?.flush,x=i?.readableType,j=i?.start,q=i?.transform,ne=i?.writableType;return{cancel:h===void 0?void 0:Ib(h,i,`${u} has member 'cancel' that`),flush:A===void 0?void 0:Ob(A,i,`${u} has member 'flush' that`),readableType:x,start:j===void 0?void 0:Pb(j,i,`${u} has member 'start' that`),transform:q===void 0?void 0:Fb(q,i,`${u} has member 'transform' that`),writableType:ne}}function Ob(i,u,h){return te(i,h),A=>w(i,u,[A])}function Pb(i,u,h){return te(i,h),A=>k(i,u,[A])}function Fb(i,u,h){return te(i,h),(A,x)=>w(i,u,[A,x])}function Ib(i,u,h){return te(i,h),A=>w(i,u,[A])}class $s{constructor(u={},h={},A={}){u===void 0&&(u=null);let x=Ds(h,"Second parameter"),j=Ds(A,"Third parameter"),q=xb(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 ne=Ao(j,0),pe=vs(j),de=Ao(x,1),ge=vs(x),be,xe=l(Mt=>{be=Mt});Nb(this,xe,de,ge,ne,pe),Mb(this,q),q.start!==void 0?be(q.start(this._transformStreamController)):be(void 0)}get readable(){if(!dh(this))throw mh("readable");return this._readable}get writable(){if(!dh(this))throw mh("writable");return this._writable}}Object.defineProperties($s.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty($s.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Nb(i,u,h,A,x,j){function q(){return u}function ne(xe){return Ub(i,xe)}function pe(xe){return $b(i,xe)}function de(){return qb(i)}i._writable=j_(q,ne,de,pe,h,A);function ge(){return Hb(i)}function be(xe){return zb(i,xe)}i._readable=Do(q,ge,be,x,j),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,qs(i,!0),i._transformStreamController=void 0}function dh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof $s}function fh(i,u){Nt(i._readable._readableStreamController,u),Du(i,u)}function Du(i,u){zs(i._transformStreamController),So(i._writable._writableStreamController,u),Ru(i)}function Ru(i){i._backpressure&&qs(i,!1)}function qs(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class Mn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Hs(this))throw Ws("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return Tu(u)}enqueue(u=void 0){if(!Hs(this))throw Ws("enqueue");hh(this,u)}error(u=void 0){if(!Hs(this))throw Ws("error");Lb(this,u)}terminate(){if(!Hs(this))throw Ws("terminate");jb(this)}}Object.defineProperties(Mn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Mn.prototype.enqueue,"enqueue"),o(Mn.prototype.error,"error"),o(Mn.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mn.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Hs(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof Mn}function Bb(i,u,h,A,x){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=A,u._cancelAlgorithm=x,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function Mb(i,u){let h=Object.create(Mn.prototype),A,x,j;u.transform!==void 0?A=q=>u.transform(q,h):A=q=>{try{return hh(h,q),d(void 0)}catch(ne){return f(ne)}},u.flush!==void 0?x=()=>u.flush(h):x=()=>d(void 0),u.cancel!==void 0?j=q=>u.cancel(q):j=()=>d(void 0),Bb(i,h,A,x,j)}function zs(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function hh(i,u){let h=i._controlledTransformStream,A=h._readable._readableStreamController;if(!Rr(A))throw new TypeError("Readable side is not in a state that permits enqueue");try{Dr(A,u)}catch(j){throw Du(h,j),h._readable._storedError}hb(A)!==h._backpressure&&qs(h,!0)}function Lb(i,u){fh(i._controlledTransformStream,u)}function ph(i,u){let h=i._transformAlgorithm(u);return _(h,void 0,A=>{throw fh(i._controlledTransformStream,A),A})}function jb(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;ir(h);let A=new TypeError("TransformStream terminated");Du(u,A)}function Ub(i,u){let h=i._transformStreamController;if(i._backpressure){let A=i._backpressureChangePromise;return _(A,()=>{let x=i._writable;if(x._state==="erroring")throw x._storedError;return ph(h,u)})}return ph(h,u)}function $b(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let A=i._readable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return zs(h),m(x,()=>(A._state==="errored"?xr(h,A._storedError):(Nt(A._readableStreamController,u),xu(h)),null),j=>(Nt(A._readableStreamController,j),xr(h,j),null)),h._finishPromise}function qb(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let h=i._readable;u._finishPromise=l((x,j)=>{u._finishPromise_resolve=x,u._finishPromise_reject=j});let A=u._flushAlgorithm();return zs(u),m(A,()=>(h._state==="errored"?xr(u,h._storedError):(ir(h._readableStreamController),xu(u)),null),x=>(Nt(h._readableStreamController,x),xr(u,x),null)),u._finishPromise}function Hb(i){return qs(i,!1),i._backpressureChangePromise}function zb(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let A=i._writable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return zs(h),m(x,()=>(A._state==="errored"?xr(h,A._storedError):(So(A._writableStreamController,u),Ru(i),xu(h)),null),j=>(So(A._writableStreamController,j),Ru(i),xr(h,j),null)),h._finishPromise}function Ws(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function xu(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function xr(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 mh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=js,t.CountQueuingStrategy=Us,t.ReadableByteStreamController=hn,t.ReadableStream=et,t.ReadableStreamBYOBReader=Fn,t.ReadableStreamBYOBRequest=er,t.ReadableStreamDefaultController=mn,t.ReadableStreamDefaultReader=W,t.TransformStream=$s,t.TransformStreamDefaultController=Mn,t.WritableStream=In,t.WritableStreamDefaultController=vr,t.WritableStreamDefaultWriter=pn}))});var lm=X(()=>{if(!globalThis.ReadableStream)try{let t=oe("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,oe("node:stream/web")),t.emitWarning=e}catch(n){throw t.emitWarning=e,n}}catch{Object.assign(globalThis,cm())}try{let{Blob:t}=oe("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(r,Math.min(o.size,r+65536)).arrayBuffer();r+=c.byteLength,s.enqueue(new Uint8Array(c)),r===o.size&&s.close()}})})}catch{}});async function*Ac(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,dm),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let a=await o.slice(r,Math.min(o.size,r+dm)).arrayBuffer();r+=a.byteLength,yield new Uint8Array(a)}}}var C1,dm,fm,iE,$t,Mo=Le(()=>{C1=jn(lm(),1);dm=65536;fm=class Sc{#e=[];#t="";#n=0;#r="transparent";constructor(e=[],n={}){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 n!="object"&&typeof n!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");n===null&&(n={});let r=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 Sc?a=s:a=r.encode(`${s}`),this.#n+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#r=`${n.endings===void 0?"transparent":n.endings}`;let o=n.type===void 0?"":String(n.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#n}get type(){return this.#t}async text(){let e=new TextDecoder,n="";for await(let r of Ac(this.#e,!1))n+=e.decode(r,{stream:!0});return n+=e.decode(),n}async arrayBuffer(){let e=new Uint8Array(this.size),n=0;for await(let r of Ac(this.#e,!1))e.set(r,n),n+=r.length;return e.buffer}stream(){let e=Ac(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(n){let r=await e.next();r.done?n.close():n.enqueue(r.value)},async cancel(){await e.return()}})}slice(e=0,n=this.size,r=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=n<0?Math.max(o+n,0):Math.min(n,o),c=Math.max(a-s,0),l=this.#e,d=[],f=0;for(let m of l){if(f>=c)break;let b=ArrayBuffer.isView(m)?m.byteLength:m.size;if(s&&b<=s)s-=b,a-=b;else{let C;ArrayBuffer.isView(m)?(C=m.subarray(s,Math.min(b,a)),f+=C.byteLength):(C=m.slice(s,Math.min(b,a)),f+=C.size),a-=b,d.push(C),s=0}}let p=new Sc([],{type:String(r).toLowerCase()});return p.#n=c,p.#e=d,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(fm.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});iE=fm,$t=iE});var aE,uE,Hn,Tc=Le(()=>{Mo();aE=class extends $t{#e=0;#t="";constructor(e,n,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),r===null&&(r={});let o=r.lastModified===void 0?Date.now():Number(r.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(n)}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])}},uE=aE,Hn=uE});function mm(t,e=$t){var n=`${hm()}${hm()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
|
|
25
|
+
`;let l=(0,iE.parseProxyResponse)(o);o.write(`${c}\r
|
|
26
|
+
`);let{connect:d,buffered:f}=await l;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),d.statusCode===200)return e.once("socket",aE),n.secureEndpoint?(Bo("Upgrading socket connection to TLS"),tm.connect({...rm(nm(n),"host","path","port"),socket:o})):o;o.destroy();let p=new _i.Socket({writable:!1});return p.readable=!0,e.once("socket",m=>{Bo("Replaying proxy buffer for failed request"),(0,nE.default)(m.listenerCount("data")>0),m.push(f),m.push(null)}),p}};bi.protocols=["http","https"];vt.HttpsProxyAgent=bi;function aE(t){t.resume()}function rm(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function uE(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 n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let f=1;f<n.length;f++)n[f]==="base64"?o=!0:n[f]&&(a+=`;${n[f]}`,n[f].indexOf("charset=")===0&&(r=n[f].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),d=Buffer.from(l,c);return d.type=s,d.typeFull=a,d.charset=r,d}var am,um=Le(()=>{am=uE});var lm=X((Ci,cm)=>{(function(t,e){typeof Ci=="object"&&typeof cm<"u"?e(Ci):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ci,(function(t){"use strict";function e(){}function n(i){return typeof i=="object"&&i!==null||typeof i=="function"}let r=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 d(i){return l(u=>u(i))}function f(i){return c(i)}function p(i,u,h){return a.call(i,u,h)}function m(i,u,h){p(p(i,u,h),void 0,r)}function b(i,u){m(i,u)}function C(i,u){m(i,void 0,u)}function _(i,u,h){return p(i,u,h)}function y(i){p(i,void 0,r)}let g=i=>{if(typeof queueMicrotask=="function")g=queueMicrotask;else{let u=d(void 0);g=h=>p(u,h)}return g(i)};function S(i,u,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,h)}function w(i,u,h){try{return d(S(i,u,h))}catch(k){return f(k)}}let A=16384;class v{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,k=h;h._elements.length===A-1&&(k={_elements:[],_next:void 0}),h._elements.push(u),k!==h&&(this._back=k,h._next=k),++this._size}shift(){let u=this._front,h=u,k=this._cursor,x=k+1,j=u._elements,q=j[k];return x===A&&(h=u._next,x=0),--this._size,this._cursor=x,u!==h&&(this._front=h),j[k]=void 0,q}forEach(u){let h=this._cursor,k=this._front,x=k._elements;for(;(h!==x.length||k._next!==void 0)&&!(h===x.length&&(k=k._next,x=k._elements,h=0,x.length===0));)u(x[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let R=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),V=Symbol("[[CancelSteps]]"),P=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function z(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?ae(i):u._state==="closed"?me(i):se(i,u._storedError)}function K(i,u){let h=i._ownerReadableStream;return Nt(h,u)}function Y(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")):Z(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[Q](),u._reader=void 0,i._ownerReadableStream=void 0}function ee(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function ae(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function se(i,u){ae(i),G(i,u)}function me(i){ae(i),ie(i)}function G(i,u){i._closedPromise_reject!==void 0&&(y(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function Z(i,u){se(i,u)}function ie(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let Ue=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},Ae=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function J(i){return typeof i=="object"||typeof i=="function"}function ce(i,u){if(i!==void 0&&!J(i))throw new TypeError(`${u} is not an object.`)}function te(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}function ve(i){return typeof i=="object"&&i!==null||typeof i=="function"}function Oe(i,u){if(!ve(i))throw new TypeError(`${u} is not an object.`)}function je(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function E(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function T(i){return Number(i)}function D(i){return i===0?0:i}function M(i){return D(Ae(i))}function F(i,u){let k=Number.MAX_SAFE_INTEGER,x=Number(i);if(x=D(x),!Ue(x))throw new TypeError(`${u} is not a finite number`);if(x=M(x),x<0||x>k)throw new TypeError(`${u} is outside the accepted range of 0 to ${k}, inclusive`);return!Ue(x)||x===0?0:x}function B(i,u){if(!Bn(i))throw new TypeError(`${u} is not a ReadableStream.`)}function U(i){return new H(i)}function O(i,u){i._reader._readRequests.push(u)}function I(i,u,h){let x=i._reader._readRequests.shift();h?x._closeSteps():x._chunkSteps(u)}function L(i){return i._reader._readRequests.length}function N(i){let u=i._reader;return!(u===void 0||!oe(u))}class H{constructor(u){if(je(u,1,"ReadableStreamDefaultReader"),B(u,"First parameter"),Nn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");z(this,u),this._readRequests=new v}get closed(){return oe(this)?this._closedPromise:f(Me("closed"))}cancel(u=void 0){return oe(this)?this._ownerReadableStream===void 0?f(ee("cancel")):K(this,u):f(Me("cancel"))}read(){if(!oe(this))return f(Me("read"));if(this._ownerReadableStream===void 0)return f(ee("read from"));let u,h,k=l((j,q)=>{u=j,h=q});return ue(this,{_chunkSteps:j=>u({value:j,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:j=>h(j)}),k}releaseLock(){if(!oe(this))throw Me("releaseLock");this._ownerReadableStream!==void 0&&Se(this)}}Object.defineProperties(H.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(H.prototype.cancel,"cancel"),o(H.prototype.read,"read"),o(H.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(H.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function oe(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof H}function ue(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[P](u)}function Se(i){Y(i);let u=new TypeError("Reader was released");Ie(i,u)}function Ie(i,u){let h=i._readRequests;i._readRequests=new v,h.forEach(k=>{k._errorSteps(u)})}function Me(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let ke=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Te{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?_(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let h=()=>this._returnSteps(u);return this._ongoingPromise?_(this._ongoingPromise,h,h):h()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,h,k,x=l((q,ne)=>{h=q,k=ne});return ue(u,{_chunkSteps:q=>{this._ongoingPromise=void 0,g(()=>h({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Y(u),h({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,Y(u),k(q)}}),x}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let k=K(h,u);return Y(h),_(k,()=>({value:u,done:!0}))}return Y(h),d({value:u,done:!0})}}let qe={next(){return wr(this)?this._asyncIteratorImpl.next():f(Er("next"))},return(i){return wr(this)?this._asyncIteratorImpl.return(i):f(Er("return"))}};Object.setPrototypeOf(qe,ke);function Cr(i,u){let h=U(i),k=new Te(h,u),x=Object.create(qe);return x._asyncIteratorImpl=k,x}function wr(i){if(!n(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Te}catch{return!1}}function Er(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let ft=Number.isNaN||function(i){return i!==i};var fn,Ze,ze;function De(i){return i.slice()}function gf(i,u,h,k,x){new Uint8Array(i).set(new Uint8Array(h,k,x),u)}let hn=i=>(typeof i.transfer=="function"?hn=u=>u.transfer():typeof structuredClone=="function"?hn=u=>structuredClone(u,{transfer:[u]}):hn=u=>u,hn(i)),On=i=>(typeof i.detached=="boolean"?On=u=>u.detached:On=u=>u.byteLength===0,On(i));function yf(i,u,h){if(i.slice)return i.slice(u,h);let k=h-u,x=new ArrayBuffer(k);return gf(x,0,i,u,k),x}function Cs(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 h_(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),k=h.next;return{iterator:h,nextMethod:k,done:!1}}let su=(ze=(fn=Symbol.asyncIterator)!==null&&fn!==void 0?fn:(Ze=Symbol.for)===null||Ze===void 0?void 0:Ze.call(Symbol,"Symbol.asyncIterator"))!==null&&ze!==void 0?ze:"@@asyncIterator";function _f(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=Cs(i,su),h===void 0){let j=Cs(i,Symbol.iterator),q=_f(i,"sync",j);return h_(q)}}else h=Cs(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let k=S(h,i,[]);if(!n(k))throw new TypeError("The iterator method must return an object");let x=k.next;return{iterator:k,nextMethod:x,done:!1}}function p_(i){let u=S(i.nextMethod,i.iterator,[]);if(!n(u))throw new TypeError("The iterator.next() method must return an object");return u}function m_(i){return!!i.done}function g_(i){return i.value}function y_(i){return!(typeof i!="number"||ft(i)||i<0)}function bf(i){let u=yf(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function iu(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function au(i,u,h){if(!y_(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 __(i){return i._queue.peek().value}function Pn(i){i._queue=new v,i._queueTotalSize=0}function Cf(i){return i===DataView}function b_(i){return Cf(i.constructor)}function C_(i){return Cf(i)?1:i.BYTES_PER_ELEMENT}class er{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!uu(this))throw hu("view");return this._view}respond(u){if(!uu(this))throw hu("respond");if(je(u,1,"respond"),u=F(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(On(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");As(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!uu(this))throw hu("respondWithNewView");if(je(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(On(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ss(this._associatedReadableByteStreamController,u)}}Object.defineProperties(er.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(er.prototype.respond,"respond"),o(er.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(er.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class pn{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!tr(this))throw Eo("byobRequest");return fu(this)}get desiredSize(){if(!tr(this))throw Eo("desiredSize");return xf(this)}close(){if(!tr(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(!tr(this))throw Eo("enqueue");if(je(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`);ks(this,u)}error(u=void 0){if(!tr(this))throw Eo("error");kt(this,u)}[V](u){wf(this),Pn(this);let h=this._cancelAlgorithm(u);return Es(this),h}[P](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){Rf(this,u);return}let k=this._autoAllocateChunkSize;if(k!==void 0){let x;try{x=new ArrayBuffer(k)}catch(q){u._errorSteps(q);return}let j={buffer:x,bufferByteLength:k,byteOffset:0,byteLength:k,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(j)}O(h,u),nr(this)}[Q](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new v,this._pendingPullIntos.push(u)}}}Object.defineProperties(pn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(pn.prototype.close,"close"),o(pn.prototype.enqueue,"enqueue"),o(pn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function tr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof pn}function uu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof er}function nr(i){if(!S_(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,nr(i)),null),k=>(kt(i,k),null))}function wf(i){lu(i),i._pendingPullIntos=new v}function cu(i,u){let h=!1;i._state==="closed"&&(h=!0);let k=Ef(u);u.readerType==="default"?I(i,k,h):O_(i,k,h)}function Ef(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function ws(i,u,h,k){i._queue.push({buffer:u,byteOffset:h,byteLength:k}),i._queueTotalSize+=k}function kf(i,u,h,k){let x;try{x=yf(u,h,h+k)}catch(j){throw kt(i,j),j}ws(i,x,0,k)}function Af(i,u){u.bytesFilled>0&&kf(i,u.buffer,u.byteOffset,u.bytesFilled),kr(i)}function Sf(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),k=u.bytesFilled+h,x=h,j=!1,q=k%u.elementSize,ne=k-q;ne>=u.minimumFill&&(x=ne-u.bytesFilled,j=!0);let pe=i._queue;for(;x>0;){let de=pe.peek(),ge=Math.min(x,de.byteLength),Ce=u.byteOffset+u.bytesFilled;gf(u.buffer,Ce,de.buffer,de.byteOffset,ge),de.byteLength===ge?pe.shift():(de.byteOffset+=ge,de.byteLength-=ge),i._queueTotalSize-=ge,Tf(i,ge,u),x-=ge}return j}function Tf(i,u,h){h.bytesFilled+=u}function vf(i){i._queueTotalSize===0&&i._closeRequested?(Es(i),Do(i._controlledReadableByteStream)):nr(i)}function lu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function du(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();Sf(i,u)&&(kr(i),cu(i._controlledReadableByteStream,u))}}function w_(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();Rf(i,h)}}function E_(i,u,h,k){let x=i._controlledReadableByteStream,j=u.constructor,q=C_(j),{byteOffset:ne,byteLength:pe}=u,de=h*q,ge;try{ge=hn(u.buffer)}catch(xe){k._errorSteps(xe);return}let Ce={buffer:ge,bufferByteLength:ge.byteLength,byteOffset:ne,byteLength:pe,bytesFilled:0,minimumFill:de,elementSize:q,viewConstructor:j,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(Ce),Ff(x,k);return}if(x._state==="closed"){let xe=new j(Ce.buffer,Ce.byteOffset,0);k._closeSteps(xe);return}if(i._queueTotalSize>0){if(Sf(i,Ce)){let xe=Ef(Ce);vf(i),k._chunkSteps(xe);return}if(i._closeRequested){let xe=new TypeError("Insufficient bytes to fill elements in the given buffer");kt(i,xe),k._errorSteps(xe);return}}i._pendingPullIntos.push(Ce),Ff(x,k),nr(i)}function k_(i,u){u.readerType==="none"&&kr(i);let h=i._controlledReadableByteStream;if(pu(h))for(;If(h)>0;){let k=kr(i);cu(h,k)}}function A_(i,u,h){if(Tf(i,u,h),h.readerType==="none"){Af(i,h),du(i);return}if(h.bytesFilled<h.minimumFill)return;kr(i);let k=h.bytesFilled%h.elementSize;if(k>0){let x=h.byteOffset+h.bytesFilled;kf(i,h.buffer,x-k,k)}h.bytesFilled-=k,cu(i._controlledReadableByteStream,h),du(i)}function Df(i,u){let h=i._pendingPullIntos.peek();lu(i),i._controlledReadableByteStream._state==="closed"?k_(i,h):A_(i,u,h),nr(i)}function kr(i){return i._pendingPullIntos.shift()}function S_(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(N(u)&&L(u)>0||pu(u)&&If(u)>0||xf(i)>0)}function Es(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 k=new TypeError("Insufficient bytes to fill elements in the given buffer");throw kt(i,k),k}}Es(i),Do(u)}}function ks(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:k,byteOffset:x,byteLength:j}=u;if(On(k))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=hn(k);if(i._pendingPullIntos.length>0){let ne=i._pendingPullIntos.peek();if(On(ne.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");lu(i),ne.buffer=hn(ne.buffer),ne.readerType==="none"&&Af(i,ne)}if(N(h))if(w_(i),L(h)===0)ws(i,q,x,j);else{i._pendingPullIntos.length>0&&kr(i);let ne=new Uint8Array(q,x,j);I(h,ne,!1)}else pu(h)?(ws(i,q,x,j),du(i)):ws(i,q,x,j);nr(i)}function kt(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(wf(i),Pn(i),Es(i),oh(h,u))}function Rf(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,vf(i);let k=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(k)}function fu(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),k=Object.create(er.prototype);v_(k,i,h),i._byobRequest=k}return i._byobRequest}function xf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function As(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=hn(h.buffer),Df(i,u)}function Ss(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 x=u.byteLength;h.buffer=hn(u.buffer),Df(i,x)}function Of(i,u,h,k,x,j,q){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Pn(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=j,u._pullAlgorithm=k,u._cancelAlgorithm=x,u._autoAllocateChunkSize=q,u._pendingPullIntos=new v,i._readableStreamController=u;let ne=h();m(d(ne),()=>(u._started=!0,nr(u),null),pe=>(kt(u,pe),null))}function T_(i,u,h){let k=Object.create(pn.prototype),x,j,q;u.start!==void 0?x=()=>u.start(k):x=()=>{},u.pull!==void 0?j=()=>u.pull(k):j=()=>d(void 0),u.cancel!==void 0?q=pe=>u.cancel(pe):q=()=>d(void 0);let ne=u.autoAllocateChunkSize;if(ne===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Of(i,k,x,j,q,h,ne)}function v_(i,u,h){i._associatedReadableByteStreamController=u,i._view=h}function hu(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 D_(i,u){ce(i,u);let h=i?.mode;return{mode:h===void 0?void 0:R_(h,`${u} has member 'mode' that`)}}function R_(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function x_(i,u){var h;ce(i,u);let k=(h=i?.min)!==null&&h!==void 0?h:1;return{min:F(k,`${u} has member 'min' that`)}}function Pf(i){return new Fn(i)}function Ff(i,u){i._reader._readIntoRequests.push(u)}function O_(i,u,h){let x=i._reader._readIntoRequests.shift();h?x._closeSteps(u):x._chunkSteps(u)}function If(i){return i._reader._readIntoRequests.length}function pu(i){let u=i._reader;return!(u===void 0||!rr(u))}class Fn{constructor(u){if(je(u,1,"ReadableStreamBYOBReader"),B(u,"First parameter"),Nn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!tr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");z(this,u),this._readIntoRequests=new v}get closed(){return rr(this)?this._closedPromise:f(Ts("closed"))}cancel(u=void 0){return rr(this)?this._ownerReadableStream===void 0?f(ee("cancel")):K(this,u):f(Ts("cancel"))}read(u,h={}){if(!rr(this))return f(Ts("read"));if(!ArrayBuffer.isView(u))return f(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(On(u.buffer))return f(new TypeError("view's buffer has been detached"));let k;try{k=x_(h,"options")}catch(de){return f(de)}let x=k.min;if(x===0)return f(new TypeError("options.min must be greater than 0"));if(b_(u)){if(x>u.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(x>u.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(ee("read from"));let j,q,ne=l((de,ge)=>{j=de,q=ge});return Bf(this,u,x,{_chunkSteps:de=>j({value:de,done:!1}),_closeSteps:de=>j({value:de,done:!0}),_errorSteps:de=>q(de)}),ne}releaseLock(){if(!rr(this))throw Ts("releaseLock");this._ownerReadableStream!==void 0&&P_(this)}}Object.defineProperties(Fn.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Fn.prototype.cancel,"cancel"),o(Fn.prototype.read,"read"),o(Fn.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fn.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function rr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Fn}function Bf(i,u,h,k){let x=i._ownerReadableStream;x._disturbed=!0,x._state==="errored"?k._errorSteps(x._storedError):E_(x._readableStreamController,u,h,k)}function P_(i){Y(i);let u=new TypeError("Reader was released");Nf(i,u)}function Nf(i,u){let h=i._readIntoRequests;i._readIntoRequests=new v,h.forEach(k=>{k._errorSteps(u)})}function Ts(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function ko(i,u){let{highWaterMark:h}=i;if(h===void 0)return u;if(ft(h)||h<0)throw new RangeError("Invalid highWaterMark");return h}function vs(i){let{size:u}=i;return u||(()=>1)}function Ds(i,u){ce(i,u);let h=i?.highWaterMark,k=i?.size;return{highWaterMark:h===void 0?void 0:T(h),size:k===void 0?void 0:F_(k,`${u} has member 'size' that`)}}function F_(i,u){return te(i,u),h=>T(i(h))}function I_(i,u){ce(i,u);let h=i?.abort,k=i?.close,x=i?.start,j=i?.type,q=i?.write;return{abort:h===void 0?void 0:B_(h,i,`${u} has member 'abort' that`),close:k===void 0?void 0:N_(k,i,`${u} has member 'close' that`),start:x===void 0?void 0:M_(x,i,`${u} has member 'start' that`),write:q===void 0?void 0:L_(q,i,`${u} has member 'write' that`),type:j}}function B_(i,u,h){return te(i,h),k=>w(i,u,[k])}function N_(i,u,h){return te(i,h),()=>w(i,u,[])}function M_(i,u,h){return te(i,h),k=>S(i,u,[k])}function L_(i,u,h){return te(i,h),(k,x)=>w(i,u,[k,x])}function Mf(i,u){if(!Ar(i))throw new TypeError(`${u} is not a WritableStream.`)}function j_(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let U_=typeof AbortController=="function";function $_(){if(U_)return new AbortController}class In{constructor(u={},h={}){u===void 0?u=null:Oe(u,"First parameter");let k=Ds(h,"Second parameter"),x=I_(u,"First parameter");if(jf(this),x.type!==void 0)throw new RangeError("Invalid type is specified");let q=vs(k),ne=ko(k,1);tb(this,x,ne,q)}get locked(){if(!Ar(this))throw Fs("locked");return Sr(this)}abort(u=void 0){return Ar(this)?Sr(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Rs(this,u):f(Fs("abort"))}close(){return Ar(this)?Sr(this)?f(new TypeError("Cannot close a stream that already has a writer")):Qt(this)?f(new TypeError("Cannot close an already-closing stream")):Uf(this):f(Fs("close"))}getWriter(){if(!Ar(this))throw Fs("getWriter");return Lf(this)}}Object.defineProperties(In.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(In.prototype.abort,"abort"),o(In.prototype.close,"close"),o(In.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(In.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Lf(i){return new mn(i)}function q_(i,u,h,k,x=1,j=()=>1){let q=Object.create(In.prototype);jf(q);let ne=Object.create(Tr.prototype);return Gf(q,ne,i,u,h,k,x,j),q}function jf(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new v,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Ar(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof In}function Sr(i){return i._writer!==void 0}function Rs(i,u){var h;if(i._state==="closed"||i._state==="errored")return d(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let k=i._state;if(k==="closed"||k==="errored")return d(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let x=!1;k==="erroring"&&(x=!0,u=void 0);let j=l((q,ne)=>{i._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:ne,_reason:u,_wasAlreadyErroring:x}});return i._pendingAbortRequest._promise=j,x||gu(i,u),j}function Uf(i){let u=i._state;if(u==="closed"||u==="errored")return f(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((x,j)=>{let q={_resolve:x,_reject:j};i._closeRequest=q}),k=i._writer;return k!==void 0&&i._backpressure&&u==="writable"&&Au(k),nb(i._writableStreamController),h}function z_(i){return l((h,k)=>{let x={_resolve:h,_reject:k};i._writeRequests.push(x)})}function mu(i,u){if(i._state==="writable"){gu(i,u);return}yu(i)}function gu(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let k=i._writer;k!==void 0&&qf(k,u),!V_(i)&&h._started&&yu(i)}function yu(i){i._state="errored",i._writableStreamController[$]();let u=i._storedError;if(i._writeRequests.forEach(x=>{x._reject(u)}),i._writeRequests=new v,i._pendingAbortRequest===void 0){xs(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),xs(i);return}let k=i._writableStreamController[R](h._reason);m(k,()=>(h._resolve(),xs(i),null),x=>(h._reject(x),xs(i),null))}function H_(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function W_(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,mu(i,u)}function G_(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 J_(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),mu(i,u)}function Qt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function V_(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function K_(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function Q_(i){i._inFlightWriteRequest=i._writeRequests.shift()}function xs(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&Eu(u,i._storedError)}function _u(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?cb(h):Au(h)),i._backpressure=u}class mn{constructor(u){if(je(u,1,"WritableStreamDefaultWriter"),Mf(u,"First parameter"),Sr(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?Bs(this):Yf(this),Is(this);else if(h==="erroring")ku(this,u._storedError),Is(this);else if(h==="closed")Yf(this),ab(this);else{let k=u._storedError;ku(this,k),Kf(this,k)}}get closed(){return or(this)?this._closedPromise:f(sr("closed"))}get desiredSize(){if(!or(this))throw sr("desiredSize");if(this._ownerWritableStream===void 0)throw So("desiredSize");return eb(this)}get ready(){return or(this)?this._readyPromise:f(sr("ready"))}abort(u=void 0){return or(this)?this._ownerWritableStream===void 0?f(So("abort")):Y_(this,u):f(sr("abort"))}close(){if(!or(this))return f(sr("close"));let u=this._ownerWritableStream;return u===void 0?f(So("close")):Qt(u)?f(new TypeError("Cannot close an already-closing stream")):$f(this)}releaseLock(){if(!or(this))throw sr("releaseLock");this._ownerWritableStream!==void 0&&zf(this)}write(u=void 0){return or(this)?this._ownerWritableStream===void 0?f(So("write to")):Hf(this,u):f(sr("write"))}}Object.defineProperties(mn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(mn.prototype.abort,"abort"),o(mn.prototype.close,"close"),o(mn.prototype.releaseLock,"releaseLock"),o(mn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function or(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof mn}function Y_(i,u){let h=i._ownerWritableStream;return Rs(h,u)}function $f(i){let u=i._ownerWritableStream;return Uf(u)}function X_(i){let u=i._ownerWritableStream,h=u._state;return Qt(u)||h==="closed"?d(void 0):h==="errored"?f(u._storedError):$f(i)}function Z_(i,u){i._closedPromiseState==="pending"?Eu(i,u):ub(i,u)}function qf(i,u){i._readyPromiseState==="pending"?Xf(i,u):lb(i,u)}function eb(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:Jf(u._writableStreamController)}function zf(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");qf(i,h),Z_(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function Hf(i,u){let h=i._ownerWritableStream,k=h._writableStreamController,x=rb(k,u);if(h!==i._ownerWritableStream)return f(So("write to"));let j=h._state;if(j==="errored")return f(h._storedError);if(Qt(h)||j==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(j==="erroring")return f(h._storedError);let q=z_(h);return ob(k,u,x),q}let Wf={};class Tr{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!bu(this))throw wu("abortReason");return this._abortReason}get signal(){if(!bu(this))throw wu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!bu(this))throw wu("error");this._controlledWritableStream._state==="writable"&&Vf(this,u)}[R](u){let h=this._abortAlgorithm(u);return Os(this),h}[$](){Pn(this)}}Object.defineProperties(Tr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Tr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function bu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Tr}function Gf(i,u,h,k,x,j,q,ne){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Pn(u),u._abortReason=void 0,u._abortController=$_(),u._started=!1,u._strategySizeAlgorithm=ne,u._strategyHWM=q,u._writeAlgorithm=k,u._closeAlgorithm=x,u._abortAlgorithm=j;let pe=Cu(u);_u(i,pe);let de=h(),ge=d(de);m(ge,()=>(u._started=!0,Ps(u),null),Ce=>(u._started=!0,mu(i,Ce),null))}function tb(i,u,h,k){let x=Object.create(Tr.prototype),j,q,ne,pe;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.write!==void 0?q=de=>u.write(de,x):q=()=>d(void 0),u.close!==void 0?ne=()=>u.close():ne=()=>d(void 0),u.abort!==void 0?pe=de=>u.abort(de):pe=()=>d(void 0),Gf(i,x,j,q,ne,pe,h,k)}function Os(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function nb(i){au(i,Wf,0),Ps(i)}function rb(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return Ao(i,h),1}}function Jf(i){return i._strategyHWM-i._queueTotalSize}function ob(i,u,h){try{au(i,u,h)}catch(x){Ao(i,x);return}let k=i._controlledWritableStream;if(!Qt(k)&&k._state==="writable"){let x=Cu(i);_u(k,x)}Ps(i)}function Ps(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){yu(u);return}if(i._queue.length===0)return;let k=__(i);k===Wf?sb(i):ib(i,k)}function Ao(i,u){i._controlledWritableStream._state==="writable"&&Vf(i,u)}function sb(i){let u=i._controlledWritableStream;K_(u),iu(i);let h=i._closeAlgorithm();Os(i),m(h,()=>(G_(u),null),k=>(J_(u,k),null))}function ib(i,u){let h=i._controlledWritableStream;Q_(h);let k=i._writeAlgorithm(u);m(k,()=>{H_(h);let x=h._state;if(iu(i),!Qt(h)&&x==="writable"){let j=Cu(i);_u(h,j)}return Ps(i),null},x=>(h._state==="writable"&&Os(i),W_(h,x),null))}function Cu(i){return Jf(i)<=0}function Vf(i,u){let h=i._controlledWritableStream;Os(i),gu(h,u)}function Fs(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function wu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function sr(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function So(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Is(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function Kf(i,u){Is(i),Eu(i,u)}function ab(i){Is(i),Qf(i)}function Eu(i,u){i._closedPromise_reject!==void 0&&(y(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function ub(i,u){Kf(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 Bs(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function ku(i,u){Bs(i),Xf(i,u)}function Yf(i){Bs(i),Au(i)}function Xf(i,u){i._readyPromise_reject!==void 0&&(y(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function cb(i){Bs(i)}function lb(i,u){ku(i,u)}function Au(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 db(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Su=db();function fb(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function hb(){let i=Su?.DOMException;return fb(i)?i:void 0}function pb(){let i=function(h,k){this.message=h||"",this.name=k||"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 mb=hb()||pb();function Zf(i,u,h,k,x,j){let q=U(i),ne=Lf(u);i._disturbed=!0;let pe=!1,de=d(void 0);return l((ge,Ce)=>{let xe;if(j!==void 0){if(xe=()=>{let fe=j.reason!==void 0?j.reason:new mb("Aborted","AbortError"),we=[];k||we.push(()=>u._state==="writable"?Rs(u,fe):d(void 0)),x||we.push(()=>i._state==="readable"?Nt(i,fe):d(void 0)),at(()=>Promise.all(we.map(Pe=>Pe())),!0,fe)},j.aborted){xe();return}j.addEventListener("abort",xe)}function Mt(){return l((fe,we)=>{function Pe(ht){ht?fe():p(xr(),Pe,we)}Pe(!1)})}function xr(){return pe?d(!0):p(ne._readyPromise,()=>l((fe,we)=>{ue(q,{_chunkSteps:Pe=>{de=p(Hf(ne,Pe),void 0,e),fe(!1)},_closeSteps:()=>fe(!0),_errorSteps:we})}))}if(yn(i,q._closedPromise,fe=>(k?At(!0,fe):at(()=>Rs(u,fe),!0,fe),null)),yn(u,ne._closedPromise,fe=>(x?At(!0,fe):at(()=>Nt(i,fe),!0,fe),null)),nt(i,q._closedPromise,()=>(h?At():at(()=>X_(ne)),null)),Qt(u)||u._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");x?At(!0,fe):at(()=>Nt(i,fe),!0,fe)}y(Mt());function Ln(){let fe=de;return p(de,()=>fe!==de?Ln():void 0)}function yn(fe,we,Pe){fe._state==="errored"?Pe(fe._storedError):C(we,Pe)}function nt(fe,we,Pe){fe._state==="closed"?Pe():b(we,Pe)}function at(fe,we,Pe){if(pe)return;pe=!0,u._state==="writable"&&!Qt(u)?b(Ln(),ht):ht();function ht(){return m(fe(),()=>_n(we,Pe),Or=>_n(!0,Or)),null}}function At(fe,we){pe||(pe=!0,u._state==="writable"&&!Qt(u)?b(Ln(),()=>_n(fe,we)):_n(fe,we))}function _n(fe,we){return zf(ne),Y(q),j!==void 0&&j.removeEventListener("abort",xe),fe?Ce(we):ge(void 0),null}})}class gn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ns(this))throw Ls("desiredSize");return Tu(this)}close(){if(!Ns(this))throw Ls("close");if(!Dr(this))throw new TypeError("The stream is not in a state that permits close");ir(this)}enqueue(u=void 0){if(!Ns(this))throw Ls("enqueue");if(!Dr(this))throw new TypeError("The stream is not in a state that permits enqueue");return vr(this,u)}error(u=void 0){if(!Ns(this))throw Ls("error");Bt(this,u)}[V](u){Pn(this);let h=this._cancelAlgorithm(u);return Ms(this),h}[P](u){let h=this._controlledReadableStream;if(this._queue.length>0){let k=iu(this);this._closeRequested&&this._queue.length===0?(Ms(this),Do(h)):To(this),u._chunkSteps(k)}else O(h,u),To(this)}[Q](){}}Object.defineProperties(gn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(gn.prototype.close,"close"),o(gn.prototype.enqueue,"enqueue"),o(gn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ns(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof gn}function To(i){if(!eh(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,To(i)),null),k=>(Bt(i,k),null))}function eh(i){let u=i._controlledReadableStream;return!Dr(i)||!i._started?!1:!!(Nn(u)&&L(u)>0||Tu(i)>0)}function Ms(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function ir(i){if(!Dr(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Ms(i),Do(u))}function vr(i,u){if(!Dr(i))return;let h=i._controlledReadableStream;if(Nn(h)&&L(h)>0)I(h,u,!1);else{let k;try{k=i._strategySizeAlgorithm(u)}catch(x){throw Bt(i,x),x}try{au(i,u,k)}catch(x){throw Bt(i,x),x}}To(i)}function Bt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Pn(i),Ms(i),oh(h,u))}function Tu(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function gb(i){return!eh(i)}function Dr(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function th(i,u,h,k,x,j,q){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Pn(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=q,u._strategyHWM=j,u._pullAlgorithm=k,u._cancelAlgorithm=x,i._readableStreamController=u;let ne=h();m(d(ne),()=>(u._started=!0,To(u),null),pe=>(Bt(u,pe),null))}function yb(i,u,h,k){let x=Object.create(gn.prototype),j,q,ne;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.pull!==void 0?q=()=>u.pull(x):q=()=>d(void 0),u.cancel!==void 0?ne=pe=>u.cancel(pe):ne=()=>d(void 0),th(i,x,j,q,ne,h,k)}function Ls(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function _b(i,u){return tr(i._readableStreamController)?Cb(i):bb(i)}function bb(i,u){let h=U(i),k=!1,x=!1,j=!1,q=!1,ne,pe,de,ge,Ce,xe=l(nt=>{Ce=nt});function Mt(){return k?(x=!0,d(void 0)):(k=!0,ue(h,{_chunkSteps:at=>{g(()=>{x=!1;let At=at,_n=at;j||vr(de._readableStreamController,At),q||vr(ge._readableStreamController,_n),k=!1,x&&Mt()})},_closeSteps:()=>{k=!1,j||ir(de._readableStreamController),q||ir(ge._readableStreamController),(!j||!q)&&Ce(void 0)},_errorSteps:()=>{k=!1}}),d(void 0))}function xr(nt){if(j=!0,ne=nt,q){let at=De([ne,pe]),At=Nt(i,at);Ce(At)}return xe}function Ln(nt){if(q=!0,pe=nt,j){let at=De([ne,pe]),At=Nt(i,at);Ce(At)}return xe}function yn(){}return de=vo(yn,Mt,xr),ge=vo(yn,Mt,Ln),C(h._closedPromise,nt=>(Bt(de._readableStreamController,nt),Bt(ge._readableStreamController,nt),(!j||!q)&&Ce(void 0),null)),[de,ge]}function Cb(i){let u=U(i),h=!1,k=!1,x=!1,j=!1,q=!1,ne,pe,de,ge,Ce,xe=l(fe=>{Ce=fe});function Mt(fe){C(fe._closedPromise,we=>(fe!==u||(kt(de._readableStreamController,we),kt(ge._readableStreamController,we),(!j||!q)&&Ce(void 0)),null))}function xr(){rr(u)&&(Y(u),u=U(i),Mt(u)),ue(u,{_chunkSteps:we=>{g(()=>{k=!1,x=!1;let Pe=we,ht=we;if(!j&&!q)try{ht=bf(we)}catch(Or){kt(de._readableStreamController,Or),kt(ge._readableStreamController,Or),Ce(Nt(i,Or));return}j||ks(de._readableStreamController,Pe),q||ks(ge._readableStreamController,ht),h=!1,k?yn():x&&nt()})},_closeSteps:()=>{h=!1,j||wo(de._readableStreamController),q||wo(ge._readableStreamController),de._readableStreamController._pendingPullIntos.length>0&&As(de._readableStreamController,0),ge._readableStreamController._pendingPullIntos.length>0&&As(ge._readableStreamController,0),(!j||!q)&&Ce(void 0)},_errorSteps:()=>{h=!1}})}function Ln(fe,we){oe(u)&&(Y(u),u=Pf(i),Mt(u));let Pe=we?ge:de,ht=we?de:ge;Bf(u,fe,1,{_chunkSteps:Pr=>{g(()=>{k=!1,x=!1;let Fr=we?q:j;if(we?j:q)Fr||Ss(Pe._readableStreamController,Pr);else{let yh;try{yh=bf(Pr)}catch(Ou){kt(Pe._readableStreamController,Ou),kt(ht._readableStreamController,Ou),Ce(Nt(i,Ou));return}Fr||Ss(Pe._readableStreamController,Pr),ks(ht._readableStreamController,yh)}h=!1,k?yn():x&&nt()})},_closeSteps:Pr=>{h=!1;let Fr=we?q:j,Gs=we?j:q;Fr||wo(Pe._readableStreamController),Gs||wo(ht._readableStreamController),Pr!==void 0&&(Fr||Ss(Pe._readableStreamController,Pr),!Gs&&ht._readableStreamController._pendingPullIntos.length>0&&As(ht._readableStreamController,0)),(!Fr||!Gs)&&Ce(void 0)},_errorSteps:()=>{h=!1}})}function yn(){if(h)return k=!0,d(void 0);h=!0;let fe=fu(de._readableStreamController);return fe===null?xr():Ln(fe._view,!1),d(void 0)}function nt(){if(h)return x=!0,d(void 0);h=!0;let fe=fu(ge._readableStreamController);return fe===null?xr():Ln(fe._view,!0),d(void 0)}function at(fe){if(j=!0,ne=fe,q){let we=De([ne,pe]),Pe=Nt(i,we);Ce(Pe)}return xe}function At(fe){if(q=!0,pe=fe,j){let we=De([ne,pe]),Pe=Nt(i,we);Ce(Pe)}return xe}function _n(){}return de=rh(_n,yn,at),ge=rh(_n,nt,At),Mt(u),[de,ge]}function wb(i){return n(i)&&typeof i.getReader<"u"}function Eb(i){return wb(i)?Ab(i.getReader()):kb(i)}function kb(i){let u,h=_f(i,"async"),k=e;function x(){let q;try{q=p_(h)}catch(pe){return f(pe)}let ne=d(q);return _(ne,pe=>{if(!n(pe))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(m_(pe))ir(u._readableStreamController);else{let ge=g_(pe);vr(u._readableStreamController,ge)}})}function j(q){let ne=h.iterator,pe;try{pe=Cs(ne,"return")}catch(Ce){return f(Ce)}if(pe===void 0)return d(void 0);let de;try{de=S(pe,ne,[q])}catch(Ce){return f(Ce)}let ge=d(de);return _(ge,Ce=>{if(!n(Ce))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=vo(k,x,j,0),u}function Ab(i){let u,h=e;function k(){let j;try{j=i.read()}catch(q){return f(q)}return _(j,q=>{if(!n(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)ir(u._readableStreamController);else{let ne=q.value;vr(u._readableStreamController,ne)}})}function x(j){try{return d(i.cancel(j))}catch(q){return f(q)}}return u=vo(h,k,x,0),u}function Sb(i,u){ce(i,u);let h=i,k=h?.autoAllocateChunkSize,x=h?.cancel,j=h?.pull,q=h?.start,ne=h?.type;return{autoAllocateChunkSize:k===void 0?void 0:F(k,`${u} has member 'autoAllocateChunkSize' that`),cancel:x===void 0?void 0:Tb(x,h,`${u} has member 'cancel' that`),pull:j===void 0?void 0:vb(j,h,`${u} has member 'pull' that`),start:q===void 0?void 0:Db(q,h,`${u} has member 'start' that`),type:ne===void 0?void 0:Rb(ne,`${u} has member 'type' that`)}}function Tb(i,u,h){return te(i,h),k=>w(i,u,[k])}function vb(i,u,h){return te(i,h),k=>w(i,u,[k])}function Db(i,u,h){return te(i,h),k=>S(i,u,[k])}function Rb(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function xb(i,u){return ce(i,u),{preventCancel:!!i?.preventCancel}}function nh(i,u){ce(i,u);let h=i?.preventAbort,k=i?.preventCancel,x=i?.preventClose,j=i?.signal;return j!==void 0&&Ob(j,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!k,preventClose:!!x,signal:j}}function Ob(i,u){if(!j_(i))throw new TypeError(`${u} is not an AbortSignal.`)}function Pb(i,u){ce(i,u);let h=i?.readable;E(h,"readable","ReadableWritablePair"),B(h,`${u} has member 'readable' that`);let k=i?.writable;return E(k,"writable","ReadableWritablePair"),Mf(k,`${u} has member 'writable' that`),{readable:h,writable:k}}class et{constructor(u={},h={}){u===void 0?u=null:Oe(u,"First parameter");let k=Ds(h,"Second parameter"),x=Sb(u,"First parameter");if(vu(this),x.type==="bytes"){if(k.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let j=ko(k,0);T_(this,x,j)}else{let j=vs(k),q=ko(k,1);yb(this,x,q,j)}}get locked(){if(!Bn(this))throw ar("locked");return Nn(this)}cancel(u=void 0){return Bn(this)?Nn(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Nt(this,u):f(ar("cancel"))}getReader(u=void 0){if(!Bn(this))throw ar("getReader");return D_(u,"First parameter").mode===void 0?U(this):Pf(this)}pipeThrough(u,h={}){if(!Bn(this))throw ar("pipeThrough");je(u,1,"pipeThrough");let k=Pb(u,"First parameter"),x=nh(h,"Second parameter");if(Nn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Sr(k.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let j=Zf(this,k.writable,x.preventClose,x.preventAbort,x.preventCancel,x.signal);return y(j),k.readable}pipeTo(u,h={}){if(!Bn(this))return f(ar("pipeTo"));if(u===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Ar(u))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let k;try{k=nh(h,"Second parameter")}catch(x){return f(x)}return Nn(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Sr(u)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Zf(this,u,k.preventClose,k.preventAbort,k.preventCancel,k.signal)}tee(){if(!Bn(this))throw ar("tee");let u=_b(this);return De(u)}values(u=void 0){if(!Bn(this))throw ar("values");let h=xb(u,"First parameter");return Cr(this,h.preventCancel)}[su](u){return this.values(u)}static from(u){return Eb(u)}}Object.defineProperties(et,{from:{enumerable:!0}}),Object.defineProperties(et.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(et.from,"from"),o(et.prototype.cancel,"cancel"),o(et.prototype.getReader,"getReader"),o(et.prototype.pipeThrough,"pipeThrough"),o(et.prototype.pipeTo,"pipeTo"),o(et.prototype.tee,"tee"),o(et.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(et.prototype,su,{value:et.prototype.values,writable:!0,configurable:!0});function vo(i,u,h,k=1,x=()=>1){let j=Object.create(et.prototype);vu(j);let q=Object.create(gn.prototype);return th(j,q,i,u,h,k,x),j}function rh(i,u,h){let k=Object.create(et.prototype);vu(k);let x=Object.create(pn.prototype);return Of(k,x,i,u,h,0,void 0),k}function vu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Bn(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof et}function Nn(i){return i._reader!==void 0}function Nt(i,u){if(i._disturbed=!0,i._state==="closed")return d(void 0);if(i._state==="errored")return f(i._storedError);Do(i);let h=i._reader;if(h!==void 0&&rr(h)){let x=h._readIntoRequests;h._readIntoRequests=new v,x.forEach(j=>{j._closeSteps(void 0)})}let k=i._readableStreamController[V](u);return _(k,e)}function Do(i){i._state="closed";let u=i._reader;if(u!==void 0&&(ie(u),oe(u))){let h=u._readRequests;u._readRequests=new v,h.forEach(k=>{k._closeSteps()})}}function oh(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(G(h,u),oe(h)?Ie(h,u):Nf(h,u))}function ar(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function sh(i,u){ce(i,u);let h=i?.highWaterMark;return E(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:T(h)}}let ih=i=>i.byteLength;o(ih,"size");class js{constructor(u){je(u,1,"ByteLengthQueuingStrategy"),u=sh(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!uh(this))throw ah("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!uh(this))throw ah("size");return ih}}Object.defineProperties(js.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(js.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function ah(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function uh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof js}let ch=()=>1;o(ch,"size");class Us{constructor(u){je(u,1,"CountQueuingStrategy"),u=sh(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!dh(this))throw lh("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!dh(this))throw lh("size");return ch}}Object.defineProperties(Us.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Us.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function lh(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function dh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof Us}function Fb(i,u){ce(i,u);let h=i?.cancel,k=i?.flush,x=i?.readableType,j=i?.start,q=i?.transform,ne=i?.writableType;return{cancel:h===void 0?void 0:Mb(h,i,`${u} has member 'cancel' that`),flush:k===void 0?void 0:Ib(k,i,`${u} has member 'flush' that`),readableType:x,start:j===void 0?void 0:Bb(j,i,`${u} has member 'start' that`),transform:q===void 0?void 0:Nb(q,i,`${u} has member 'transform' that`),writableType:ne}}function Ib(i,u,h){return te(i,h),k=>w(i,u,[k])}function Bb(i,u,h){return te(i,h),k=>S(i,u,[k])}function Nb(i,u,h){return te(i,h),(k,x)=>w(i,u,[k,x])}function Mb(i,u,h){return te(i,h),k=>w(i,u,[k])}class $s{constructor(u={},h={},k={}){u===void 0&&(u=null);let x=Ds(h,"Second parameter"),j=Ds(k,"Third parameter"),q=Fb(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 ne=ko(j,0),pe=vs(j),de=ko(x,1),ge=vs(x),Ce,xe=l(Mt=>{Ce=Mt});Lb(this,xe,de,ge,ne,pe),Ub(this,q),q.start!==void 0?Ce(q.start(this._transformStreamController)):Ce(void 0)}get readable(){if(!fh(this))throw gh("readable");return this._readable}get writable(){if(!fh(this))throw gh("writable");return this._writable}}Object.defineProperties($s.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty($s.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Lb(i,u,h,k,x,j){function q(){return u}function ne(xe){return zb(i,xe)}function pe(xe){return Hb(i,xe)}function de(){return Wb(i)}i._writable=q_(q,ne,de,pe,h,k);function ge(){return Gb(i)}function Ce(xe){return Jb(i,xe)}i._readable=vo(q,ge,Ce,x,j),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,qs(i,!0),i._transformStreamController=void 0}function fh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof $s}function hh(i,u){Bt(i._readable._readableStreamController,u),Du(i,u)}function Du(i,u){Hs(i._transformStreamController),Ao(i._writable._writableStreamController,u),Ru(i)}function Ru(i){i._backpressure&&qs(i,!1)}function qs(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class Mn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!zs(this))throw Ws("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return Tu(u)}enqueue(u=void 0){if(!zs(this))throw Ws("enqueue");ph(this,u)}error(u=void 0){if(!zs(this))throw Ws("error");$b(this,u)}terminate(){if(!zs(this))throw Ws("terminate");qb(this)}}Object.defineProperties(Mn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Mn.prototype.enqueue,"enqueue"),o(Mn.prototype.error,"error"),o(Mn.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mn.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function zs(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof Mn}function jb(i,u,h,k,x){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=k,u._cancelAlgorithm=x,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function Ub(i,u){let h=Object.create(Mn.prototype),k,x,j;u.transform!==void 0?k=q=>u.transform(q,h):k=q=>{try{return ph(h,q),d(void 0)}catch(ne){return f(ne)}},u.flush!==void 0?x=()=>u.flush(h):x=()=>d(void 0),u.cancel!==void 0?j=q=>u.cancel(q):j=()=>d(void 0),jb(i,h,k,x,j)}function Hs(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function ph(i,u){let h=i._controlledTransformStream,k=h._readable._readableStreamController;if(!Dr(k))throw new TypeError("Readable side is not in a state that permits enqueue");try{vr(k,u)}catch(j){throw Du(h,j),h._readable._storedError}gb(k)!==h._backpressure&&qs(h,!0)}function $b(i,u){hh(i._controlledTransformStream,u)}function mh(i,u){let h=i._transformAlgorithm(u);return _(h,void 0,k=>{throw hh(i._controlledTransformStream,k),k})}function qb(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;ir(h);let k=new TypeError("TransformStream terminated");Du(u,k)}function zb(i,u){let h=i._transformStreamController;if(i._backpressure){let k=i._backpressureChangePromise;return _(k,()=>{let x=i._writable;if(x._state==="erroring")throw x._storedError;return mh(h,u)})}return mh(h,u)}function Hb(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let k=i._readable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return Hs(h),m(x,()=>(k._state==="errored"?Rr(h,k._storedError):(Bt(k._readableStreamController,u),xu(h)),null),j=>(Bt(k._readableStreamController,j),Rr(h,j),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((x,j)=>{u._finishPromise_resolve=x,u._finishPromise_reject=j});let k=u._flushAlgorithm();return Hs(u),m(k,()=>(h._state==="errored"?Rr(u,h._storedError):(ir(h._readableStreamController),xu(u)),null),x=>(Bt(h._readableStreamController,x),Rr(u,x),null)),u._finishPromise}function Gb(i){return qs(i,!1),i._backpressureChangePromise}function Jb(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let k=i._writable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return Hs(h),m(x,()=>(k._state==="errored"?Rr(h,k._storedError):(Ao(k._writableStreamController,u),Ru(i),xu(h)),null),j=>(Ao(k._writableStreamController,j),Ru(i),Rr(h,j),null)),h._finishPromise}function Ws(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function xu(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Rr(i,u){i._finishPromise_reject!==void 0&&(y(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function gh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=js,t.CountQueuingStrategy=Us,t.ReadableByteStreamController=pn,t.ReadableStream=et,t.ReadableStreamBYOBReader=Fn,t.ReadableStreamBYOBRequest=er,t.ReadableStreamDefaultController=gn,t.ReadableStreamDefaultReader=H,t.TransformStream=$s,t.TransformStreamDefaultController=Mn,t.WritableStream=In,t.WritableStreamDefaultController=Tr,t.WritableStreamDefaultWriter=mn}))});var dm=X(()=>{if(!globalThis.ReadableStream)try{let t=re("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,re("node:stream/web")),t.emitWarning=e}catch(n){throw t.emitWarning=e,n}}catch{Object.assign(globalThis,lm())}try{let{Blob:t}=re("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(r,Math.min(o.size,r+65536)).arrayBuffer();r+=c.byteLength,s.enqueue(new Uint8Array(c)),r===o.size&&s.close()}})})}catch{}});async function*Ac(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,fm),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let a=await o.slice(r,Math.min(o.size,r+fm)).arrayBuffer();r+=a.byteLength,yield new Uint8Array(a)}}}var S1,fm,hm,cE,$t,No=Le(()=>{S1=jn(dm(),1);fm=65536;hm=class Sc{#e=[];#t="";#n=0;#r="transparent";constructor(e=[],n={}){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 n!="object"&&typeof n!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");n===null&&(n={});let r=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 Sc?a=s:a=r.encode(`${s}`),this.#n+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#r=`${n.endings===void 0?"transparent":n.endings}`;let o=n.type===void 0?"":String(n.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#n}get type(){return this.#t}async text(){let e=new TextDecoder,n="";for await(let r of Ac(this.#e,!1))n+=e.decode(r,{stream:!0});return n+=e.decode(),n}async arrayBuffer(){let e=new Uint8Array(this.size),n=0;for await(let r of Ac(this.#e,!1))e.set(r,n),n+=r.length;return e.buffer}stream(){let e=Ac(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(n){let r=await e.next();r.done?n.close():n.enqueue(r.value)},async cancel(){await e.return()}})}slice(e=0,n=this.size,r=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=n<0?Math.max(o+n,0):Math.min(n,o),c=Math.max(a-s,0),l=this.#e,d=[],f=0;for(let m of l){if(f>=c)break;let b=ArrayBuffer.isView(m)?m.byteLength:m.size;if(s&&b<=s)s-=b,a-=b;else{let C;ArrayBuffer.isView(m)?(C=m.subarray(s,Math.min(b,a)),f+=C.byteLength):(C=m.slice(s,Math.min(b,a)),f+=C.size),a-=b,d.push(C),s=0}}let p=new Sc([],{type:String(r).toLowerCase()});return p.#n=c,p.#e=d,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(hm.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});cE=hm,$t=cE});var lE,dE,zn,Tc=Le(()=>{No();lE=class extends $t{#e=0;#t="";constructor(e,n,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),r===null&&(r={});let o=r.lastModified===void 0?Date.now():Number(r.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(n)}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])}},dE=lE,zn=dE});function gm(t,e=$t){var n=`${pm()}${pm()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
|
|
27
27
|
Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?r.push(o+vc(a)+`"\r
|
|
28
28
|
\r
|
|
29
29
|
${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
@@ -32,263 +32,265 @@ ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
|
32
32
|
Content-Type: ${s.type||"application/octet-stream"}\r
|
|
33
33
|
\r
|
|
34
34
|
`,s,`\r
|
|
35
|
-
`)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}var
|
|
36
|
-
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),fr=(t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},
|
|
37
|
-
--`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:d,flags:f}=this,p=this.boundary.length,m=p-1,b=e.length,C,_,g=S=>{this[S+"Mark"]=n},y=S=>{delete this[S+"Mark"]},k=(S,R,v,$)=>{(R===void 0||R!==v)&&this[S]($&&$.subarray(R,v))},w=(S,R)=>{let v=S+"Mark";v in this&&(R?(k(S,this[v],n,e),delete this[v]):(k(S,this[v],e.length,e),this[v]=0))};for(n=0;n<r;n++)switch(C=e[n],d){case Fe.START_BOUNDARY:if(l===a.length-2){if(C===Uo)f|=Wn.LAST_BOUNDARY;else if(C!==vi)return;l++;break}else if(l-1===a.length-2){if(f&Wn.LAST_BOUNDARY&&C===Uo)d=Fe.END,f=0;else if(!(f&Wn.LAST_BOUNDARY)&&C===Ti)l=0,k("onPartBegin"),d=Fe.HEADER_FIELD_START;else return;break}C!==a[l+2]&&(l=-2),C===a[l+2]&&l++;break;case Fe.HEADER_FIELD_START:d=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(C===vi){y("onHeaderField"),d=Fe.HEADERS_ALMOST_DONE;break}if(l++,C===Uo)break;if(C===gE){if(l===1)return;w("onHeaderField",!0),d=Fe.HEADER_VALUE_START;break}if(_=bE(C),_<yE||_>_E)return;break;case Fe.HEADER_VALUE_START:if(C===mE)break;g("onHeaderValue"),d=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:C===vi&&(w("onHeaderValue",!0),k("onHeaderEnd"),d=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(C!==Ti)return;d=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(C!==Ti)return;k("onHeadersEnd"),d=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:d=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(o=l,l===0){for(n+=m;n<b&&!(e[n]in c);)n+=p;n-=m,C=e[n]}if(l<a.length)a[l]===C?(l===0&&w("onPartData",!0),l++):l=0;else if(l===a.length)l++,C===vi?f|=Wn.PART_BOUNDARY:C===Uo?f|=Wn.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(f&Wn.PART_BOUNDARY){if(l=0,C===Ti){f&=~Wn.PART_BOUNDARY,k("onPartEnd"),k("onPartBegin"),d=Fe.HEADER_FIELD_START;break}}else f&Wn.LAST_BOUNDARY&&C===Uo?(k("onPartEnd"),d=Fe.END,f=0):l=0;if(l>0)s[l-1]=C;else if(o>0){let S=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);k("onPartData",0,o,S),o=0,g("onPartData"),n--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}w("onHeaderField"),w("onHeaderValue"),w("onPartData"),this.index=l,this.state=d,this.flags=f}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Gn,{PassThrough as Pm}from"node:stream";import{types as Fm,deprecate as Ic,promisify as EE}from"node:util";import{Buffer as Dt}from"node:buffer";async function Fc(t){if(t[lt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[lt].disturbed=!0,t[lt].error)throw t[lt].error;let{body:e}=t;if(e===null)return Dt.alloc(0);if(!(e instanceof Gn))return Dt.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new st(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof kn?o:new st(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?Dt.from(n.join("")):Dt.concat(n,r)}catch(o){throw new st(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new st(`Premature close of server response while trying to fetch ${t.url}`)}var kE,lt,Zt,Gr,AE,Di,Im,Nm,Ri=Le(()=>{Mo();wi();Dc();Ei();Ai();kE=EE(Gn.pipeline),lt=Symbol("Body internals"),Zt=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:Rc(e)?e=Dt.from(e.toString()):jo(e)||Dt.isBuffer(e)||(Fm.isAnyArrayBuffer(e)?e=Dt.from(e):ArrayBuffer.isView(e)?e=Dt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Gn||(e instanceof zn?(e=mm(e),r=e.type.split("=")[1]):e=Dt.from(String(e))));let o=e;Dt.isBuffer(e)?o=Gn.Readable.from(e):jo(e)&&(o=Gn.Readable.from(e.stream())),this[lt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Gn&&e.on("error",s=>{let a=s instanceof kn?s:new st(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[lt].error=a})}get body(){return this[lt].stream}get bodyUsed(){return this[lt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await Fc(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new zn,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>(Om(),xm));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[lt].body&&this[lt].body.type||"",n=await this.arrayBuffer();return new $t([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Fc(this);return new TextDecoder().decode(e)}buffer(){return Fc(this)}};Zt.prototype.buffer=Ic(Zt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Zt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Ic(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Gr=(t,e)=>{let n,r,{body:o}=t[lt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Gn&&typeof o.getBoundary!="function"&&(n=new Pm({highWaterMark:e}),r=new Pm({highWaterMark:e}),o.pipe(n),o.pipe(r),t[lt].stream=n,o=r),o},AE=Ic(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"),Di=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Rc(t)?"application/x-www-form-urlencoded;charset=UTF-8":jo(t)?t.type||null:Dt.isBuffer(t)||Fm.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof zn?`multipart/form-data; boundary=${e[lt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${AE(t)}`:t instanceof Gn?null:"text/plain;charset=UTF-8",Im=t=>{let{body:e}=t[lt];return e===null?0:jo(e)?e.size:Dt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Nm=async(t,{body:e})=>{e===null?t.end():await kE(e,t)}});import{types as Bm}from"node:util";import Oi from"node:http";function Mm(t=[]){return new dt(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return xi(e),Nc(e,String(n)),!0}catch{return!1}}))}var xi,Nc,dt,Pi=Le(()=>{xi=typeof Oi.validateHeaderName=="function"?Oi.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}},Nc=typeof Oi.validateHeaderValue=="function"?Oi.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},dt=class t extends URLSearchParams{constructor(e){let n=[];if(e instanceof t){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!Bm.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||Bm.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 n=n.length>0?n.map(([r,o])=>(xi(r),Nc(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,c)=>(xi(a),Nc(a,String(c)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(xi(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,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,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};Object.defineProperties(dt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var SE,$o,Bc=Le(()=>{SE=new Set([301,302,303,307,308]),$o=t=>SE.has(t)});var qt,mt,Lm=Le(()=>{Pi();Ri();Bc();qt=Symbol("Response internals"),mt=class t extends Zt{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new dt(n.headers);if(e!==null&&!o.has("Content-Type")){let s=Di(e,this);s&&o.append("Content-Type",s)}this[qt]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.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(Gr(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,n=302){if(!$o(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new t(null,{status:0,statusText:""});return e[qt].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new dt(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(r,{...n,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 jm,Um=Le(()=>{jm=t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""}});import{isIP as TE}from"node:net";function $m(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 zm(t){if(!qm.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function vE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=TE(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Jr(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:vE(t)}function Wm(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=$m(o),a=$m(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let c=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return Jr(s)&&!Jr(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:Jr(s)&&!Jr(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 Jr(s)&&!Jr(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function Gm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&qm.has(r)&&(n=r);return n}var qm,Hm,Mc=Le(()=>{qm=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Hm="strict-origin-when-cross-origin"});import{format as DE}from"node:url";import{deprecate as RE}from"node:util";var Ke,qo,xE,Jn,Jm,Vm=Le(()=>{Pi();Ri();Ai();Um();Mc();Ke=Symbol("Request internals"),qo=t=>typeof t=="object"&&typeof t[Ke]=="object",xE=RE(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Jn=class t extends Zt{constructor(e,n={}){let r;if(qo(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!qo(n)&&"data"in n&&xE(),(n.body!=null||qo(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:qo(e)&&e.body!==null?Gr(e):null;super(s,{size:n.size||e.size||0});let a=new dt(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let d=Di(s,this);d&&a.set("Content-Type",d)}let c=qo(e)?e.signal:null;if("signal"in n&&(c=n.signal),c!=null&&!gm(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let d=new URL(l);l=/^about:(\/\/)?client$/.test(d)?"client":d}else l=void 0;this[Ke]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:c,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ke].method}get url(){return DE(this[Ke].parsedURL)}get headers(){return this[Ke].headers}get redirect(){return this[Ke].redirect}get signal(){return this[Ke].signal}get referrer(){if(this[Ke].referrer==="no-referrer")return"";if(this[Ke].referrer==="client")return"about:client";if(this[Ke].referrer)return this[Ke].referrer.toString()}get referrerPolicy(){return this[Ke].referrerPolicy}set referrerPolicy(e){this[Ke].referrerPolicy=zm(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Jn.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}});Jm=t=>{let{parsedURL:e}=t[Ke],n=new dt(t[Ke].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let c=Im(t);typeof c=="number"&&!Number.isNaN(c)&&(r=String(c))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=Hm),t.referrer&&t.referrer!=="no-referrer"?t[Ke].referrer=Wm(t):t[Ke].referrer="no-referrer",t[Ke].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=jm(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var Ho,Km=Le(()=>{Ei();Ho=class extends kn{constructor(e,n="aborted"){super(e,n)}}});var Xm={};Pu(Xm,{AbortError:()=>Ho,Blob:()=>$t,FetchError:()=>st,File:()=>Hn,FormData:()=>zn,Headers:()=>dt,Request:()=>Jn,Response:()=>mt,blobFrom:()=>Am,blobFromSync:()=>km,default:()=>Lc,fileFrom:()=>Sm,fileFromSync:()=>Tm,isRedirect:()=>$o});import OE from"node:http";import PE from"node:https";import Vr from"node:zlib";import Ym,{PassThrough as Qm,pipeline as Kr}from"node:stream";import{Buffer as Fi}from"node:buffer";async function Lc(t,e){return new Promise((n,r)=>{let o=new Jn(t,e),{parsedURL:s,options:a}=Jm(o);if(!FE.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let C=im(o.url),_=new mt(C,{headers:{"Content-Type":C.typeFull}});n(_);return}let c=(s.protocol==="https:"?PE:OE).request,{signal:l}=o,d=null,f=()=>{let C=new Ho("The operation was aborted.");r(C),o.body&&o.body instanceof Ym.Readable&&o.body.destroy(C),!(!d||!d.body)&&d.body.emit("error",C)};if(l&&l.aborted){f();return}let p=()=>{f(),b()},m=c(s.toString(),a);l&&l.addEventListener("abort",p);let b=()=>{m.abort(),l&&l.removeEventListener("abort",p)};m.on("error",C=>{r(new st(`request to ${o.url} failed, reason: ${C.message}`,"system",C)),b()}),IE(m,C=>{d&&d.body&&d.body.destroy(C)}),process.version<"v14"&&m.on("socket",C=>{let _;C.prependListener("end",()=>{_=C._eventsCount}),C.prependListener("close",g=>{if(d&&_<C._eventsCount&&!g){let y=new Error("Premature close");y.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",y)}})}),m.on("response",C=>{m.setTimeout(0);let _=Mm(C.rawHeaders);if($o(C.statusCode)){let S=_.get("Location"),R=null;try{R=S===null?null:new URL(S,o.url)}catch{if(o.redirect!=="manual"){r(new st(`uri requested responds with an invalid redirect URL: ${S}`,"invalid-redirect")),b();return}}switch(o.redirect){case"error":r(new st(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),b();return;case"manual":break;case"follow":{if(R===null)break;if(o.counter>=o.follow){r(new st(`maximum redirect reached at: ${o.url}`,"max-redirect")),b();return}let v={headers:new dt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Gr(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!ym(o.url,R)||!_m(o.url,R))for(let Y of["authorization","www-authenticate","cookie","cookie2"])v.headers.delete(Y);if(C.statusCode!==303&&o.body&&e.body instanceof Ym.Readable){r(new st("Cannot follow redirect with body being a readable stream","unsupported-redirect")),b();return}(C.statusCode===303||(C.statusCode===301||C.statusCode===302)&&o.method==="POST")&&(v.method="GET",v.body=void 0,v.headers.delete("content-length"));let $=Gm(_);$&&(v.referrerPolicy=$),n(Lc(new Jn(R,v))),b();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&C.once("end",()=>{l.removeEventListener("abort",p)});let g=Kr(C,new Qm,S=>{S&&r(S)});process.version<"v12.10"&&C.on("aborted",p);let y={url:o.url,status:C.statusCode,statusText:C.statusMessage,headers:_,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},k=_.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||k===null||C.statusCode===204||C.statusCode===304){d=new mt(g,y),n(d);return}let w={flush:Vr.Z_SYNC_FLUSH,finishFlush:Vr.Z_SYNC_FLUSH};if(k==="gzip"||k==="x-gzip"){g=Kr(g,Vr.createGunzip(w),S=>{S&&r(S)}),d=new mt(g,y),n(d);return}if(k==="deflate"||k==="x-deflate"){let S=Kr(C,new Qm,R=>{R&&r(R)});S.once("data",R=>{(R[0]&15)===8?g=Kr(g,Vr.createInflate(),v=>{v&&r(v)}):g=Kr(g,Vr.createInflateRaw(),v=>{v&&r(v)}),d=new mt(g,y),n(d)}),S.once("end",()=>{d||(d=new mt(g,y),n(d))});return}if(k==="br"){g=Kr(g,Vr.createBrotliDecompress(),S=>{S&&r(S)}),d=new mt(g,y),n(d);return}d=new mt(g,y),n(d)}),Nm(m,o).catch(r)})}function IE(t,e){let n=Fi.from(`0\r
|
|
35
|
+
`)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}var Mo,fE,hE,pm,pE,mm,vc,fr,Hn,wi=Le(()=>{No();Tc();({toStringTag:Mo,iterator:fE,hasInstance:hE}=Symbol),pm=Math.random,pE="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),mm=(t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[Mo])?[(n=n!==void 0?n+"":e[Mo]=="File"?e.name:"blob",t),e.name!==n||e[Mo]=="blob"?new zn([e],n,e):e]:[t,e+""]),vc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
|
|
36
|
+
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),fr=(t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},Hn=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Mo](){return"FormData"}[fE](){return this.entries()}static[hE](e){return e&&typeof e=="object"&&e[Mo]==="FormData"&&!pE.some(n=>typeof e[n]!="function")}append(...e){fr("append",arguments,2),this.#e.push(mm(...e))}delete(e){fr("delete",arguments,1),e+="",this.#e=this.#e.filter(([n])=>n!==e)}get(e){fr("get",arguments,1),e+="";for(var n=this.#e,r=n.length,o=0;o<r;o++)if(n[o][0]===e)return n[o][1];return null}getAll(e,n){return fr("getAll",arguments,1),n=[],e+="",this.#e.forEach(r=>r[0]===e&&n.push(r[1])),n}has(e){return fr("has",arguments,1),e+="",this.#e.some(n=>n[0]===e)}forEach(e,n){fr("forEach",arguments,1);for(var[r,o]of this)e.call(n,o,r,this)}set(...e){fr("set",arguments,2);var n=[],r=!0;e=mm(...e),this.#e.forEach(o=>{o[0]===e[0]?r&&(r=!n.push(e)):n.push(o)}),r&&n.push(e),this.#e=n}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var An,Ei=Le(()=>{An=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var st,Dc=Le(()=>{Ei();st=class extends An{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}});var ki,Rc,Lo,ym,_m,bm,Ai=Le(()=>{ki=Symbol.toStringTag,Rc=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[ki]==="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[ki]),ym=t=>typeof t=="object"&&(t[ki]==="AbortSignal"||t[ki]==="EventTarget"),_m=(t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},bm=(t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r}});var wm=X((L1,Cm)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=re("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Cm.exports=globalThis.DOMException});import{statSync as Em,createReadStream as mE,promises as gE}from"node:fs";import{basename as yE}from"node:path";var km,xc,Am,Sm,Tm,vm,Dm,Rm,Si,Oc=Le(()=>{km=jn(wm(),1);Tc();No();({stat:xc}=gE),Am=(t,e)=>Dm(Em(t),t,e),Sm=(t,e)=>xc(t).then(n=>Dm(n,t,e)),Tm=(t,e)=>xc(t).then(n=>Rm(n,t,e)),vm=(t,e)=>Rm(Em(t),t,e),Dm=(t,e,n="")=>new $t([new Si({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),Rm=(t,e,n="")=>new zn([new Si({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],yE(e),{type:n,lastModified:t.mtimeMs}),Si=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new t({path:this.#e,lastModified:this.lastModified,size:n-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await xc(this.#e);if(e>this.lastModified)throw new km.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*mE(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Om={};Pu(Om,{toFormData:()=>AE});function kE(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function AE(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new Pc(n[1]||n[2]),o,s,a,c,l,d,f=[],p=new Hn,m=g=>{a+=y.decode(g,{stream:!0})},b=g=>{f.push(g)},C=()=>{let g=new zn(f,d,{type:l});p.append(c,g)},_=()=>{p.append(c,a)},y=new TextDecoder("utf-8");y.decode(),r.onPartBegin=function(){r.onPartData=m,r.onPartEnd=_,o="",s="",a="",c="",l="",d=null,f.length=0},r.onHeaderField=function(g){o+=y.decode(g,{stream:!0})},r.onHeaderValue=function(g){s+=y.decode(g,{stream:!0})},r.onHeaderEnd=function(){if(s+=y.decode(),o=o.toLowerCase(),o==="content-disposition"){let g=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);g&&(c=g[2]||g[3]||""),d=kE(s),d&&(r.onPartData=b,r.onPartEnd=C)}else o==="content-type"&&(l=s);s="",o=""};for await(let g of t)r.write(g);return r.end(),p}var Xt,Fe,xm,Wn,Ti,vi,_E,jo,bE,CE,wE,EE,hr,Pc,Pm=Le(()=>{Oc();wi();Xt=0,Fe={START_BOUNDARY:Xt++,HEADER_FIELD_START:Xt++,HEADER_FIELD:Xt++,HEADER_VALUE_START:Xt++,HEADER_VALUE:Xt++,HEADER_VALUE_ALMOST_DONE:Xt++,HEADERS_ALMOST_DONE:Xt++,PART_DATA_START:Xt++,PART_DATA:Xt++,END:Xt++},xm=1,Wn={PART_BOUNDARY:xm,LAST_BOUNDARY:xm*=2},Ti=10,vi=13,_E=32,jo=45,bE=58,CE=97,wE=122,EE=t=>t|32,hr=()=>{},Pc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=hr,this.onHeaderField=hr,this.onHeadersEnd=hr,this.onHeaderValue=hr,this.onPartBegin=hr,this.onPartData=hr,this.onPartEnd=hr,this.boundaryChars={},e=`\r
|
|
37
|
+
--`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:d,flags:f}=this,p=this.boundary.length,m=p-1,b=e.length,C,_,y=A=>{this[A+"Mark"]=n},g=A=>{delete this[A+"Mark"]},S=(A,v,R,$)=>{(v===void 0||v!==R)&&this[A]($&&$.subarray(v,R))},w=(A,v)=>{let R=A+"Mark";R in this&&(v?(S(A,this[R],n,e),delete this[R]):(S(A,this[R],e.length,e),this[R]=0))};for(n=0;n<r;n++)switch(C=e[n],d){case Fe.START_BOUNDARY:if(l===a.length-2){if(C===jo)f|=Wn.LAST_BOUNDARY;else if(C!==vi)return;l++;break}else if(l-1===a.length-2){if(f&Wn.LAST_BOUNDARY&&C===jo)d=Fe.END,f=0;else if(!(f&Wn.LAST_BOUNDARY)&&C===Ti)l=0,S("onPartBegin"),d=Fe.HEADER_FIELD_START;else return;break}C!==a[l+2]&&(l=-2),C===a[l+2]&&l++;break;case Fe.HEADER_FIELD_START:d=Fe.HEADER_FIELD,y("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(C===vi){g("onHeaderField"),d=Fe.HEADERS_ALMOST_DONE;break}if(l++,C===jo)break;if(C===bE){if(l===1)return;w("onHeaderField",!0),d=Fe.HEADER_VALUE_START;break}if(_=EE(C),_<CE||_>wE)return;break;case Fe.HEADER_VALUE_START:if(C===_E)break;y("onHeaderValue"),d=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:C===vi&&(w("onHeaderValue",!0),S("onHeaderEnd"),d=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(C!==Ti)return;d=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(C!==Ti)return;S("onHeadersEnd"),d=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:d=Fe.PART_DATA,y("onPartData");case Fe.PART_DATA:if(o=l,l===0){for(n+=m;n<b&&!(e[n]in c);)n+=p;n-=m,C=e[n]}if(l<a.length)a[l]===C?(l===0&&w("onPartData",!0),l++):l=0;else if(l===a.length)l++,C===vi?f|=Wn.PART_BOUNDARY:C===jo?f|=Wn.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(f&Wn.PART_BOUNDARY){if(l=0,C===Ti){f&=~Wn.PART_BOUNDARY,S("onPartEnd"),S("onPartBegin"),d=Fe.HEADER_FIELD_START;break}}else f&Wn.LAST_BOUNDARY&&C===jo?(S("onPartEnd"),d=Fe.END,f=0):l=0;if(l>0)s[l-1]=C;else if(o>0){let A=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);S("onPartData",0,o,A),o=0,y("onPartData"),n--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}w("onHeaderField"),w("onHeaderValue"),w("onPartData"),this.index=l,this.state=d,this.flags=f}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Gn,{PassThrough as Fm}from"node:stream";import{types as Im,deprecate as Ic,promisify as SE}from"node:util";import{Buffer as Dt}from"node:buffer";async function Fc(t){if(t[lt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[lt].disturbed=!0,t[lt].error)throw t[lt].error;let{body:e}=t;if(e===null)return Dt.alloc(0);if(!(e instanceof Gn))return Dt.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new st(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof An?o:new st(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?Dt.from(n.join("")):Dt.concat(n,r)}catch(o){throw new st(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new st(`Premature close of server response while trying to fetch ${t.url}`)}var TE,lt,Zt,Wr,vE,Di,Bm,Nm,Ri=Le(()=>{No();wi();Dc();Ei();Ai();TE=SE(Gn.pipeline),lt=Symbol("Body internals"),Zt=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:Rc(e)?e=Dt.from(e.toString()):Lo(e)||Dt.isBuffer(e)||(Im.isAnyArrayBuffer(e)?e=Dt.from(e):ArrayBuffer.isView(e)?e=Dt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Gn||(e instanceof Hn?(e=gm(e),r=e.type.split("=")[1]):e=Dt.from(String(e))));let o=e;Dt.isBuffer(e)?o=Gn.Readable.from(e):Lo(e)&&(o=Gn.Readable.from(e.stream())),this[lt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Gn&&e.on("error",s=>{let a=s instanceof An?s:new st(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[lt].error=a})}get body(){return this[lt].stream}get bodyUsed(){return this[lt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await Fc(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Hn,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>(Pm(),Om));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[lt].body&&this[lt].body.type||"",n=await this.arrayBuffer();return new $t([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Fc(this);return new TextDecoder().decode(e)}buffer(){return Fc(this)}};Zt.prototype.buffer=Ic(Zt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Zt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Ic(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Wr=(t,e)=>{let n,r,{body:o}=t[lt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Gn&&typeof o.getBoundary!="function"&&(n=new Fm({highWaterMark:e}),r=new Fm({highWaterMark:e}),o.pipe(n),o.pipe(r),t[lt].stream=n,o=r),o},vE=Ic(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"),Di=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Rc(t)?"application/x-www-form-urlencoded;charset=UTF-8":Lo(t)?t.type||null:Dt.isBuffer(t)||Im.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Hn?`multipart/form-data; boundary=${e[lt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${vE(t)}`:t instanceof Gn?null:"text/plain;charset=UTF-8",Bm=t=>{let{body:e}=t[lt];return e===null?0:Lo(e)?e.size:Dt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Nm=async(t,{body:e})=>{e===null?t.end():await TE(e,t)}});import{types as Mm}from"node:util";import Oi from"node:http";function Lm(t=[]){return new dt(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return xi(e),Bc(e,String(n)),!0}catch{return!1}}))}var xi,Bc,dt,Pi=Le(()=>{xi=typeof Oi.validateHeaderName=="function"?Oi.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}},Bc=typeof Oi.validateHeaderValue=="function"?Oi.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},dt=class t extends URLSearchParams{constructor(e){let n=[];if(e instanceof t){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!Mm.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||Mm.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 n=n.length>0?n.map(([r,o])=>(xi(r),Bc(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,c)=>(xi(a),Bc(a,String(c)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(xi(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,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,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};Object.defineProperties(dt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var DE,Uo,Nc=Le(()=>{DE=new Set([301,302,303,307,308]),Uo=t=>DE.has(t)});var qt,mt,jm=Le(()=>{Pi();Ri();Nc();qt=Symbol("Response internals"),mt=class t extends Zt{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new dt(n.headers);if(e!==null&&!o.has("Content-Type")){let s=Di(e,this);s&&o.append("Content-Type",s)}this[qt]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.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(Wr(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,n=302){if(!Uo(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new t(null,{status:0,statusText:""});return e[qt].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new dt(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(r,{...n,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 Um,$m=Le(()=>{Um=t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""}});import{isIP as RE}from"node:net";function qm(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 Wm(t){if(!zm.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function xE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=RE(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Gr(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:xE(t)}function Gm(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=qm(o),a=qm(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let c=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return Gr(s)&&!Gr(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:Gr(s)&&!Gr(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 Gr(s)&&!Gr(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function Jm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&zm.has(r)&&(n=r);return n}var zm,Hm,Mc=Le(()=>{zm=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Hm="strict-origin-when-cross-origin"});import{format as OE}from"node:url";import{deprecate as PE}from"node:util";var Ke,$o,FE,Jn,Vm,Km=Le(()=>{Pi();Ri();Ai();$m();Mc();Ke=Symbol("Request internals"),$o=t=>typeof t=="object"&&typeof t[Ke]=="object",FE=PE(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Jn=class t extends Zt{constructor(e,n={}){let r;if($o(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!$o(n)&&"data"in n&&FE(),(n.body!=null||$o(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:$o(e)&&e.body!==null?Wr(e):null;super(s,{size:n.size||e.size||0});let a=new dt(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let d=Di(s,this);d&&a.set("Content-Type",d)}let c=$o(e)?e.signal:null;if("signal"in n&&(c=n.signal),c!=null&&!ym(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let d=new URL(l);l=/^about:(\/\/)?client$/.test(d)?"client":d}else l=void 0;this[Ke]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:c,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ke].method}get url(){return OE(this[Ke].parsedURL)}get headers(){return this[Ke].headers}get redirect(){return this[Ke].redirect}get signal(){return this[Ke].signal}get referrer(){if(this[Ke].referrer==="no-referrer")return"";if(this[Ke].referrer==="client")return"about:client";if(this[Ke].referrer)return this[Ke].referrer.toString()}get referrerPolicy(){return this[Ke].referrerPolicy}set referrerPolicy(e){this[Ke].referrerPolicy=Wm(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Jn.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}});Vm=t=>{let{parsedURL:e}=t[Ke],n=new dt(t[Ke].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let c=Bm(t);typeof c=="number"&&!Number.isNaN(c)&&(r=String(c))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=Hm),t.referrer&&t.referrer!=="no-referrer"?t[Ke].referrer=Gm(t):t[Ke].referrer="no-referrer",t[Ke].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=Um(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var qo,Qm=Le(()=>{Ei();qo=class extends An{constructor(e,n="aborted"){super(e,n)}}});var Zm={};Pu(Zm,{AbortError:()=>qo,Blob:()=>$t,FetchError:()=>st,File:()=>zn,FormData:()=>Hn,Headers:()=>dt,Request:()=>Jn,Response:()=>mt,blobFrom:()=>Sm,blobFromSync:()=>Am,default:()=>Lc,fileFrom:()=>Tm,fileFromSync:()=>vm,isRedirect:()=>Uo});import IE from"node:http";import BE from"node:https";import Jr from"node:zlib";import Ym,{PassThrough as Xm,pipeline as Vr}from"node:stream";import{Buffer as Fi}from"node:buffer";async function Lc(t,e){return new Promise((n,r)=>{let o=new Jn(t,e),{parsedURL:s,options:a}=Vm(o);if(!NE.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let C=am(o.url),_=new mt(C,{headers:{"Content-Type":C.typeFull}});n(_);return}let c=(s.protocol==="https:"?BE:IE).request,{signal:l}=o,d=null,f=()=>{let C=new qo("The operation was aborted.");r(C),o.body&&o.body instanceof Ym.Readable&&o.body.destroy(C),!(!d||!d.body)&&d.body.emit("error",C)};if(l&&l.aborted){f();return}let p=()=>{f(),b()},m=c(s.toString(),a);l&&l.addEventListener("abort",p);let b=()=>{m.abort(),l&&l.removeEventListener("abort",p)};m.on("error",C=>{r(new st(`request to ${o.url} failed, reason: ${C.message}`,"system",C)),b()}),ME(m,C=>{d&&d.body&&d.body.destroy(C)}),process.version<"v14"&&m.on("socket",C=>{let _;C.prependListener("end",()=>{_=C._eventsCount}),C.prependListener("close",y=>{if(d&&_<C._eventsCount&&!y){let g=new Error("Premature close");g.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",g)}})}),m.on("response",C=>{m.setTimeout(0);let _=Lm(C.rawHeaders);if(Uo(C.statusCode)){let A=_.get("Location"),v=null;try{v=A===null?null:new URL(A,o.url)}catch{if(o.redirect!=="manual"){r(new st(`uri requested responds with an invalid redirect URL: ${A}`,"invalid-redirect")),b();return}}switch(o.redirect){case"error":r(new st(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),b();return;case"manual":break;case"follow":{if(v===null)break;if(o.counter>=o.follow){r(new st(`maximum redirect reached at: ${o.url}`,"max-redirect")),b();return}let R={headers:new dt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Wr(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!_m(o.url,v)||!bm(o.url,v))for(let V of["authorization","www-authenticate","cookie","cookie2"])R.headers.delete(V);if(C.statusCode!==303&&o.body&&e.body instanceof Ym.Readable){r(new st("Cannot follow redirect with body being a readable stream","unsupported-redirect")),b();return}(C.statusCode===303||(C.statusCode===301||C.statusCode===302)&&o.method==="POST")&&(R.method="GET",R.body=void 0,R.headers.delete("content-length"));let $=Jm(_);$&&(R.referrerPolicy=$),n(Lc(new Jn(v,R))),b();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&C.once("end",()=>{l.removeEventListener("abort",p)});let y=Vr(C,new Xm,A=>{A&&r(A)});process.version<"v12.10"&&C.on("aborted",p);let g={url:o.url,status:C.statusCode,statusText:C.statusMessage,headers:_,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},S=_.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||S===null||C.statusCode===204||C.statusCode===304){d=new mt(y,g),n(d);return}let w={flush:Jr.Z_SYNC_FLUSH,finishFlush:Jr.Z_SYNC_FLUSH};if(S==="gzip"||S==="x-gzip"){y=Vr(y,Jr.createGunzip(w),A=>{A&&r(A)}),d=new mt(y,g),n(d);return}if(S==="deflate"||S==="x-deflate"){let A=Vr(C,new Xm,v=>{v&&r(v)});A.once("data",v=>{(v[0]&15)===8?y=Vr(y,Jr.createInflate(),R=>{R&&r(R)}):y=Vr(y,Jr.createInflateRaw(),R=>{R&&r(R)}),d=new mt(y,g),n(d)}),A.once("end",()=>{d||(d=new mt(y,g),n(d))});return}if(S==="br"){y=Vr(y,Jr.createBrotliDecompress(),A=>{A&&r(A)}),d=new mt(y,g),n(d);return}d=new mt(y,g),n(d)}),Nm(m,o).catch(r)})}function ME(t,e){let n=Fi.from(`0\r
|
|
38
38
|
\r
|
|
39
|
-
`),r=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;r=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},l=d=>{o=Fi.compare(d.slice(-5),n)===0,!o&&s&&(o=Fi.compare(s.slice(-3),n.slice(0,3))===0&&Fi.compare(d.slice(-2),n.slice(3))===0),s=d};a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}var
|
|
39
|
+
`),r=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;r=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},l=d=>{o=Fi.compare(d.slice(-5),n)===0,!o&&s&&(o=Fi.compare(s.slice(-3),n.slice(0,3))===0&&Fi.compare(d.slice(-2),n.slice(3))===0),s=d};a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}var NE,eg=Le(()=>{um();Ri();jm();Pi();Km();Dc();Qm();Nc();wi();Ai();Mc();Oc();NE=new Set(["data:","http:","https:"])});var rg=X(Qr=>{"use strict";var LE=Qr&&Qr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Kr;Object.defineProperty(Qr,"__esModule",{value:!0});Qr.Gaxios=void 0;var jE=LE(dc()),UE=re("https"),pr=pc(),$E=Bp(),tg=re("stream"),ng=yc(),qE=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Ii=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new ng.GaxiosInterceptorManager,response:new ng.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Kr.mergeHeaders(s,n.headers),r&&Kr.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Kr.#u(),r={...e};delete r.data;let o=await n(e.url,r),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 n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=o.toString()}let r=pr.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new pr.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof pr.GaxiosError?r=n:n instanceof Error?r=new pr.GaxiosError(n.message,e,void 0,n):r=new pr.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,$E.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new pr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":return n.json();case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],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(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(r.hostname.endsWith(c))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Kr.mergeHeaders(n,e.headers);let r=(0,jE.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let c=r.url.toString().includes("?")?"&":"?";r.url=r.url+c+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[c,l]of new URLSearchParams(r.params))a.searchParams.append(c,l);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof tg.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await qE();n.set("content-type",`multipart/related; boundary=${a}`),r.body=tg.Readable.from(this.getMultipartRequest(r.multipart,a))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let a=await Kr.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new a(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new UE.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=pr.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\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 r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>jn(sm()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Zm(),Xm))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};Qr.Gaxios=Ii;Yr=Ii});var Xe=X(it=>{"use strict";var UE=it&&it.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$E=it&&it.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&UE(e,t,n)};Object.defineProperty(it,"__esModule",{value:!0});it.instance=it.Gaxios=it.GaxiosError=void 0;it.request=HE;var rg=ng();Object.defineProperty(it,"Gaxios",{enumerable:!0,get:function(){return rg.Gaxios}});var qE=pc();Object.defineProperty(it,"GaxiosError",{enumerable:!0,get:function(){return qE.GaxiosError}});$E(yc(),it);it.instance=new rg.Gaxios;async function HE(t){return it.instance.request(t)}});var jc=X((og,Ni)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,m=1e9;function b(R){var v,$,Y,P=K.prototype={constructor:K,toString:null,valueOf:null},V=new K(1),H=20,Q=4,J=-7,ee=21,ce=-1e7,re=1e7,me=!1,z=1,Z=0,ie={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ue="0123456789abcdefghijklmnopqrstuvwxyz",Ae=!0;function K(E,T){var D,M,F,N,U,O,I,L,B=this;if(!(B instanceof K))return new K(E,T);if(T==null){if(E&&E._isBigNumber===!0){B.s=E.s,!E.c||E.e>re?B.c=B.e=null:E.e<ce?B.c=[B.e=0]:(B.e=E.e,B.c=E.c.slice());return}if((O=typeof E=="number")&&E*0==0){if(B.s=1/E<0?(E=-E,-1):1,E===~~E){for(N=0,U=E;U>=10;U/=10,N++);N>re?B.c=B.e=null:(B.e=N,B.c=[E]);return}L=String(E)}else{if(!n.test(L=String(E)))return Y(B,L,O);B.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(N=L.indexOf("."))>-1&&(L=L.replace(".","")),(U=L.search(/e/i))>0?(N<0&&(N=U),N+=+L.slice(U+1),L=L.substring(0,U)):N<0&&(N=L.length)}else{if(y(T,2,Ue.length,"Base"),T==10&&Ae)return B=new K(E),Oe(B,H+B.e+1,Q);if(L=String(E),O=typeof E=="number"){if(E*0!=0)return Y(B,L,O,T);if(B.s=1/E<0?(L=L.slice(1),-1):1,K.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+E)}else B.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(D=Ue.slice(0,T),N=U=0,I=L.length;U<I;U++)if(D.indexOf(M=L.charAt(U))<0){if(M=="."){if(U>N){N=I;continue}}else if(!F&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){F=!0,U=-1,N=0;continue}return Y(B,String(E),O,T)}O=!1,L=$(L,T,10,B.s),(N=L.indexOf("."))>-1?L=L.replace(".",""):N=L.length}for(U=0;L.charCodeAt(U)===48;U++);for(I=L.length;L.charCodeAt(--I)===48;);if(L=L.slice(U,++I)){if(I-=U,O&&K.DEBUG&&I>15&&(E>d||E!==o(E)))throw Error(a+B.s*E);if((N=N-U-1)>re)B.c=B.e=null;else if(N<ce)B.c=[B.e=0];else{if(B.e=N,B.c=[],U=(N+1)%l,N<0&&(U+=l),U<I){for(U&&B.c.push(+L.slice(0,U)),I-=l;U<I;)B.c.push(+L.slice(U,U+=l));U=l-(L=L.slice(U)).length}else U-=I;for(;U--;L+="0");B.c.push(+L)}}else B.c=[B.e=0]}K.clone=b,K.ROUND_UP=0,K.ROUND_DOWN=1,K.ROUND_CEIL=2,K.ROUND_FLOOR=3,K.ROUND_HALF_UP=4,K.ROUND_HALF_DOWN=5,K.ROUND_HALF_EVEN=6,K.ROUND_HALF_CEIL=7,K.ROUND_HALF_FLOOR=8,K.EUCLID=9,K.config=K.set=function(E){var T,D;if(E!=null)if(typeof E=="object"){if(E.hasOwnProperty(T="DECIMAL_PLACES")&&(D=E[T],y(D,0,m,T),H=D),E.hasOwnProperty(T="ROUNDING_MODE")&&(D=E[T],y(D,0,8,T),Q=D),E.hasOwnProperty(T="EXPONENTIAL_AT")&&(D=E[T],D&&D.pop?(y(D[0],-m,0,T),y(D[1],0,m,T),J=D[0],ee=D[1]):(y(D,-m,m,T),J=-(ee=D<0?-D:D))),E.hasOwnProperty(T="RANGE"))if(D=E[T],D&&D.pop)y(D[0],-m,-1,T),y(D[1],1,m,T),ce=D[0],re=D[1];else if(y(D,-m,m,T),D)ce=-(re=D<0?-D:D);else throw Error(s+T+" cannot be zero: "+D);if(E.hasOwnProperty(T="CRYPTO"))if(D=E[T],D===!!D)if(D)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=D;else throw me=!D,Error(s+"crypto unavailable");else me=D;else throw Error(s+T+" not true or false: "+D);if(E.hasOwnProperty(T="MODULO_MODE")&&(D=E[T],y(D,0,9,T),z=D),E.hasOwnProperty(T="POW_PRECISION")&&(D=E[T],y(D,0,m,T),Z=D),E.hasOwnProperty(T="FORMAT"))if(D=E[T],typeof D=="object")ie=D;else throw Error(s+T+" not an object: "+D);if(E.hasOwnProperty(T="ALPHABET"))if(D=E[T],typeof D=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(D))Ae=D.slice(0,10)=="0123456789",Ue=D;else throw Error(s+T+" invalid: "+D)}else throw Error(s+"Object expected: "+E);return{DECIMAL_PLACES:H,ROUNDING_MODE:Q,EXPONENTIAL_AT:[J,ee],RANGE:[ce,re],CRYPTO:me,MODULO_MODE:z,POW_PRECISION:Z,FORMAT:ie,ALPHABET:Ue}},K.isBigNumber=function(E){if(!E||E._isBigNumber!==!0)return!1;if(!K.DEBUG)return!0;var T,D,M=E.c,F=E.e,N=E.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&F>=-m&&F<=m&&F===o(F)){if(M[0]===0){if(F===0&&M.length===1)return!0;break e}if(T=(F+1)%l,T<1&&(T+=l),String(M[0]).length==T){for(T=0;T<M.length;T++)if(D=M[T],D<0||D>=c||D!==o(D))break e;if(D!==0)return!0}}}else if(M===null&&F===null&&(N===null||N===1||N===-1))return!0;throw Error(s+"Invalid BigNumber: "+E)},K.maximum=K.max=function(){return te(arguments,-1)},K.minimum=K.min=function(){return te(arguments,1)},K.random=(function(){var E=9007199254740992,T=Math.random()*E&2097151?function(){return o(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var M,F,N,U,O,I=0,L=[],B=new K(V);if(D==null?D=H:y(D,0,m),U=r(D/l),me)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));I<U;)O=M[I]*131072+(M[I+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),M[I]=F[0],M[I+1]=F[1]):(L.push(O%1e14),I+=2);I=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);I<U;)O=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],O>=9e15?crypto.randomBytes(7).copy(M,I):(L.push(O%1e14),I+=7);I=U/7}else throw me=!1,Error(s+"crypto unavailable");if(!me)for(;I<U;)O=T(),O<9e15&&(L[I++]=O%1e14);for(U=L[--I],D%=l,U&&D&&(O=f[l-D],L[I]=o(U/O)*O);L[I]===0;L.pop(),I--);if(I<0)L=[N=0];else{for(N=-1;L[0]===0;L.splice(0,1),N-=l);for(I=1,O=L[0];O>=10;O/=10,I++);I<l&&(N-=l-I)}return B.e=N,B.c=L,B}})(),K.sum=function(){for(var E=1,T=arguments,D=new K(T[0]);E<T.length;)D=D.plus(T[E++]);return D},$=(function(){var E="0123456789";function T(D,M,F,N){for(var U,O=[0],I,L=0,B=D.length;L<B;){for(I=O.length;I--;O[I]*=M);for(O[0]+=N.indexOf(D.charAt(L++)),U=0;U<O.length;U++)O[U]>F-1&&(O[U+1]==null&&(O[U+1]=0),O[U+1]+=O[U]/F|0,O[U]%=F)}return O.reverse()}return function(D,M,F,N,U){var O,I,L,B,W,se,ae,Se,Ie=D.indexOf("."),Me=H,ke=Q;for(Ie>=0&&(B=Z,Z=0,D=D.replace(".",""),Se=new K(M),se=Se.pow(D.length-Ie),Z=B,Se.c=T(S(_(se.c),se.e,"0"),10,F,E),Se.e=Se.c.length),ae=T(D,M,F,U?(O=Ue,E):(O=E,Ue)),L=B=ae.length;ae[--B]==0;ae.pop());if(!ae[0])return O.charAt(0);if(Ie<0?--L:(se.c=ae,se.e=L,se.s=N,se=v(se,Se,Me,ke,F),ae=se.c,W=se.r,L=se.e),I=L+Me+1,Ie=ae[I],B=F/2,W=W||I<0||ae[I+1]!=null,W=ke<4?(Ie!=null||W)&&(ke==0||ke==(se.s<0?3:2)):Ie>B||Ie==B&&(ke==4||W||ke==6&&ae[I-1]&1||ke==(se.s<0?8:7)),I<1||!ae[0])D=W?S(O.charAt(1),-Me,O.charAt(0)):O.charAt(0);else{if(ae.length=I,W)for(--F;++ae[--I]>F;)ae[I]=0,I||(++L,ae=[1].concat(ae));for(B=ae.length;!ae[--B];);for(Ie=0,D="";Ie<=B;D+=O.charAt(ae[Ie++]));D=S(D,L,O.charAt(0))}return D}})(),v=(function(){function E(M,F,N){var U,O,I,L,B=0,W=M.length,se=F%p,ae=F/p|0;for(M=M.slice();W--;)I=M[W]%p,L=M[W]/p|0,U=ae*I+L*se,O=se*I+U%p*p+B,B=(O/N|0)+(U/p|0)+ae*L,M[W]=O%N;return B&&(M=[B].concat(M)),M}function T(M,F,N,U){var O,I;if(N!=U)I=N>U?1:-1;else for(O=I=0;O<N;O++)if(M[O]!=F[O]){I=M[O]>F[O]?1:-1;break}return I}function D(M,F,N,U){for(var O=0;N--;)M[N]-=O,O=M[N]<F[N]?1:0,M[N]=O*U+M[N]-F[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,F,N,U,O){var I,L,B,W,se,ae,Se,Ie,Me,ke,Te,qe,wr,Er,kr,ft,dn,Ze=M.s==F.s?1:-1,He=M.c,De=F.c;if(!He||!He[0]||!De||!De[0])return new K(!M.s||!F.s||(He?De&&He[0]==De[0]:!De)?NaN:He&&He[0]==0||!De?Ze*0:Ze/0);for(Ie=new K(Ze),Me=Ie.c=[],L=M.e-F.e,Ze=N+L+1,O||(O=c,L=C(M.e/l)-C(F.e/l),Ze=Ze/l|0),B=0;De[B]==(He[B]||0);B++);if(De[B]>(He[B]||0)&&L--,Ze<0)Me.push(1),W=!0;else{for(Er=He.length,ft=De.length,B=0,Ze+=2,se=o(O/(De[0]+1)),se>1&&(De=E(De,se,O),He=E(He,se,O),ft=De.length,Er=He.length),wr=ft,ke=He.slice(0,ft),Te=ke.length;Te<ft;ke[Te++]=0);dn=De.slice(),dn=[0].concat(dn),kr=De[0],De[1]>=O/2&&kr++;do{if(se=0,I=T(De,ke,ft,Te),I<0){if(qe=ke[0],ft!=Te&&(qe=qe*O+(ke[1]||0)),se=o(qe/kr),se>1)for(se>=O&&(se=O-1),ae=E(De,se,O),Se=ae.length,Te=ke.length;T(ae,ke,Se,Te)==1;)se--,D(ae,ft<Se?dn:De,Se,O),Se=ae.length,I=1;else se==0&&(I=se=1),ae=De.slice(),Se=ae.length;if(Se<Te&&(ae=[0].concat(ae)),D(ke,ae,Te,O),Te=ke.length,I==-1)for(;T(De,ke,ft,Te)<1;)se++,D(ke,ft<Te?dn:De,Te,O),Te=ke.length}else I===0&&(se++,ke=[0]);Me[B++]=se,ke[0]?ke[Te++]=He[wr]||0:(ke=[He[wr]],Te=1)}while((wr++<Er||ke[0]!=null)&&Ze--);W=ke[0]!=null,Me[0]||Me.splice(0,1)}if(O==c){for(B=1,Ze=Me[0];Ze>=10;Ze/=10,B++);Oe(Ie,N+(Ie.e=B+L*l-1)+1,U,W)}else Ie.e=L,Ie.r=+W;return Ie}})();function ue(E,T,D,M){var F,N,U,O,I;if(D==null?D=Q:y(D,0,8),!E.c)return E.toString();if(F=E.c[0],U=E.e,T==null)I=_(E.c),I=M==1||M==2&&(U<=J||U>=ee)?w(I,U):S(I,U,"0");else if(E=Oe(new K(E),T,D),N=E.e,I=_(E.c),O=I.length,M==1||M==2&&(T<=N||N<=J)){for(;O<T;I+="0",O++);I=w(I,N)}else if(T-=U+(M===2&&N>U),I=S(I,N,"0"),N+1>O){if(--T>0)for(I+=".";T--;I+="0");}else if(T+=N-O,T>0)for(N+1==O&&(I+=".");T--;I+="0");return E.s<0&&F?"-"+I:I}function te(E,T){for(var D,M,F=1,N=new K(E[0]);F<E.length;F++)M=new K(E[F]),(!M.s||(D=g(N,M))===T||D===0&&N.s===T)&&(N=M);return N}function ve(E,T,D){for(var M=1,F=T.length;!T[--F];T.pop());for(F=T[0];F>=10;F/=10,M++);return(D=M+D*l-1)>re?E.c=E.e=null:D<ce?E.c=[E.e=0]:(E.e=D,E.c=T),E}Y=(function(){var E=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,D=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,U,O,I){var L,B=O?U:U.replace(F,"");if(M.test(B))N.s=isNaN(B)?null:B<0?-1:1;else{if(!O&&(B=B.replace(E,function(W,se,ae){return L=(ae=ae.toLowerCase())=="x"?16:ae=="b"?2:8,!I||I==L?se:W}),I&&(L=I,B=B.replace(T,"$1").replace(D,"0.$1")),U!=B))return new K(B,L);if(K.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+U);N.s=null}N.c=N.e=null}})();function Oe(E,T,D,M){var F,N,U,O,I,L,B,W=E.c,se=f;if(W){e:{for(F=1,O=W[0];O>=10;O/=10,F++);if(N=T-F,N<0)N+=l,U=T,I=W[L=0],B=o(I/se[F-U-1]%10);else if(L=r((N+1)/l),L>=W.length)if(M){for(;W.length<=L;W.push(0));I=B=0,F=1,N%=l,U=N-l+1}else break e;else{for(I=O=W[L],F=1;O>=10;O/=10,F++);N%=l,U=N-l+F,B=U<0?0:o(I/se[F-U-1]%10)}if(M=M||T<0||W[L+1]!=null||(U<0?I:I%se[F-U-1]),M=D<4?(B||M)&&(D==0||D==(E.s<0?3:2)):B>5||B==5&&(D==4||M||D==6&&(N>0?U>0?I/se[F-U]:0:W[L-1])%10&1||D==(E.s<0?8:7)),T<1||!W[0])return W.length=0,M?(T-=E.e+1,W[0]=se[(l-T%l)%l],E.e=-T||0):W[0]=E.e=0,E;if(N==0?(W.length=L,O=1,L--):(W.length=L+1,O=se[l-N],W[L]=U>0?o(I/se[F-U]%se[U])*O:0),M)for(;;)if(L==0){for(N=1,U=W[0];U>=10;U/=10,N++);for(U=W[0]+=O,O=1;U>=10;U/=10,O++);N!=O&&(E.e++,W[0]==c&&(W[0]=1));break}else{if(W[L]+=O,W[L]!=c)break;W[L--]=0,O=1}for(N=W.length;W[--N]===0;W.pop());}E.e>re?E.c=E.e=null:E.e<ce&&(E.c=[E.e=0])}return E}function je(E){var T,D=E.e;return D===null?E.toString():(T=_(E.c),T=D<=J||D>=ee?w(T,D):S(T,D,"0"),E.s<0?"-"+T:T)}return P.absoluteValue=P.abs=function(){var E=new K(this);return E.s<0&&(E.s=1),E},P.comparedTo=function(E,T){return g(this,new K(E,T))},P.decimalPlaces=P.dp=function(E,T){var D,M,F,N=this;if(E!=null)return y(E,0,m),T==null?T=Q:y(T,0,8),Oe(new K(N),E+N.e+1,T);if(!(D=N.c))return null;if(M=((F=D.length-1)-C(this.e/l))*l,F=D[F])for(;F%10==0;F/=10,M--);return M<0&&(M=0),M},P.dividedBy=P.div=function(E,T){return v(this,new K(E,T),H,Q)},P.dividedToIntegerBy=P.idiv=function(E,T){return v(this,new K(E,T),0,1)},P.exponentiatedBy=P.pow=function(E,T){var D,M,F,N,U,O,I,L,B,W=this;if(E=new K(E),E.c&&!E.isInteger())throw Error(s+"Exponent not an integer: "+je(E));if(T!=null&&(T=new K(T)),O=E.e>14,!W.c||!W.c[0]||W.c[0]==1&&!W.e&&W.c.length==1||!E.c||!E.c[0])return B=new K(Math.pow(+je(W),O?E.s*(2-k(E)):+je(E))),T?B.mod(T):B;if(I=E.s<0,T){if(T.c?!T.c[0]:!T.s)return new K(NaN);M=!I&&W.isInteger()&&T.isInteger(),M&&(W=W.mod(T))}else{if(E.e>9&&(W.e>0||W.e<-1||(W.e==0?W.c[0]>1||O&&W.c[1]>=24e7:W.c[0]<8e13||O&&W.c[0]<=9999975e7)))return N=W.s<0&&k(E)?-0:0,W.e>-1&&(N=1/N),new K(I?1/N:N);Z&&(N=r(Z/l+2))}for(O?(D=new K(.5),I&&(E.s=1),L=k(E)):(F=Math.abs(+je(E)),L=F%2),B=new K(V);;){if(L){if(B=B.times(W),!B.c)break;N?B.c.length>N&&(B.c.length=N):M&&(B=B.mod(T))}if(F){if(F=o(F/2),F===0)break;L=F%2}else if(E=E.times(D),Oe(E,E.e+1,1),E.e>14)L=k(E);else{if(F=+je(E),F===0)break;L=F%2}W=W.times(W),N?W.c&&W.c.length>N&&(W.c.length=N):M&&(W=W.mod(T))}return M?B:(I&&(B=V.div(B)),T?B.mod(T):N?Oe(B,Z,Q,U):B)},P.integerValue=function(E){var T=new K(this);return E==null?E=Q:y(E,0,8),Oe(T,T.e+1,E)},P.isEqualTo=P.eq=function(E,T){return g(this,new K(E,T))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(E,T){return g(this,new K(E,T))>0},P.isGreaterThanOrEqualTo=P.gte=function(E,T){return(T=g(this,new K(E,T)))===1||T===0},P.isInteger=function(){return!!this.c&&C(this.e/l)>this.c.length-2},P.isLessThan=P.lt=function(E,T){return g(this,new K(E,T))<0},P.isLessThanOrEqualTo=P.lte=function(E,T){return(T=g(this,new K(E,T)))===-1||T===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(E,T){var D,M,F,N,U=this,O=U.s;if(E=new K(E,T),T=E.s,!O||!T)return new K(NaN);if(O!=T)return E.s=-T,U.plus(E);var I=U.e/l,L=E.e/l,B=U.c,W=E.c;if(!I||!L){if(!B||!W)return B?(E.s=-T,E):new K(W?U:NaN);if(!B[0]||!W[0])return W[0]?(E.s=-T,E):new K(B[0]?U:Q==3?-0:0)}if(I=C(I),L=C(L),B=B.slice(),O=I-L){for((N=O<0)?(O=-O,F=B):(L=I,F=W),F.reverse(),T=O;T--;F.push(0));F.reverse()}else for(M=(N=(O=B.length)<(T=W.length))?O:T,O=T=0;T<M;T++)if(B[T]!=W[T]){N=B[T]<W[T];break}if(N&&(F=B,B=W,W=F,E.s=-E.s),T=(M=W.length)-(D=B.length),T>0)for(;T--;B[D++]=0);for(T=c-1;M>O;){if(B[--M]<W[M]){for(D=M;D&&!B[--D];B[D]=T);--B[D],B[M]+=c}B[M]-=W[M]}for(;B[0]==0;B.splice(0,1),--L);return B[0]?ve(E,B,L):(E.s=Q==3?-1:1,E.c=[E.e=0],E)},P.modulo=P.mod=function(E,T){var D,M,F=this;return E=new K(E,T),!F.c||!E.s||E.c&&!E.c[0]?new K(NaN):!E.c||F.c&&!F.c[0]?new K(F):(z==9?(M=E.s,E.s=1,D=v(F,E,0,3),E.s=M,D.s*=M):D=v(F,E,0,z),E=F.minus(D.times(E)),!E.c[0]&&z==1&&(E.s=F.s),E)},P.multipliedBy=P.times=function(E,T){var D,M,F,N,U,O,I,L,B,W,se,ae,Se,Ie,Me,ke=this,Te=ke.c,qe=(E=new K(E,T)).c;if(!Te||!qe||!Te[0]||!qe[0])return!ke.s||!E.s||Te&&!Te[0]&&!qe||qe&&!qe[0]&&!Te?E.c=E.e=E.s=null:(E.s*=ke.s,!Te||!qe?E.c=E.e=null:(E.c=[0],E.e=0)),E;for(M=C(ke.e/l)+C(E.e/l),E.s*=ke.s,I=Te.length,W=qe.length,I<W&&(Se=Te,Te=qe,qe=Se,F=I,I=W,W=F),F=I+W,Se=[];F--;Se.push(0));for(Ie=c,Me=p,F=W;--F>=0;){for(D=0,se=qe[F]%Me,ae=qe[F]/Me|0,U=I,N=F+U;N>F;)L=Te[--U]%Me,B=Te[U]/Me|0,O=ae*L+B*se,L=se*L+O%Me*Me+Se[N]+D,D=(L/Ie|0)+(O/Me|0)+ae*B,Se[N--]=L%Ie;Se[N]=D}return D?++M:Se.splice(0,1),ve(E,Se,M)},P.negated=function(){var E=new K(this);return E.s=-E.s||null,E},P.plus=function(E,T){var D,M=this,F=M.s;if(E=new K(E,T),T=E.s,!F||!T)return new K(NaN);if(F!=T)return E.s=-T,M.minus(E);var N=M.e/l,U=E.e/l,O=M.c,I=E.c;if(!N||!U){if(!O||!I)return new K(F/0);if(!O[0]||!I[0])return I[0]?E:new K(O[0]?M:F*0)}if(N=C(N),U=C(U),O=O.slice(),F=N-U){for(F>0?(U=N,D=I):(F=-F,D=O),D.reverse();F--;D.push(0));D.reverse()}for(F=O.length,T=I.length,F-T<0&&(D=I,I=O,O=D,T=F),F=0;T;)F=(O[--T]=O[T]+I[T]+F)/c|0,O[T]=c===O[T]?0:O[T]%c;return F&&(O=[F].concat(O),++U),ve(E,O,U)},P.precision=P.sd=function(E,T){var D,M,F,N=this;if(E!=null&&E!==!!E)return y(E,1,m),T==null?T=Q:y(T,0,8),Oe(new K(N),E,T);if(!(D=N.c))return null;if(F=D.length-1,M=F*l+1,F=D[F]){for(;F%10==0;F/=10,M--);for(F=D[0];F>=10;F/=10,M++);}return E&&N.e+1>M&&(M=N.e+1),M},P.shiftedBy=function(E){return y(E,-d,d),this.times("1e"+E)},P.squareRoot=P.sqrt=function(){var E,T,D,M,F,N=this,U=N.c,O=N.s,I=N.e,L=H+4,B=new K("0.5");if(O!==1||!U||!U[0])return new K(!O||O<0&&(!U||U[0])?NaN:U?N:1/0);if(O=Math.sqrt(+je(N)),O==0||O==1/0?(T=_(U),(T.length+I)%2==0&&(T+="0"),O=Math.sqrt(+T),I=C((I+1)/2)-(I<0||I%2),O==1/0?T="5e"+I:(T=O.toExponential(),T=T.slice(0,T.indexOf("e")+1)+I),D=new K(T)):D=new K(O+""),D.c[0]){for(I=D.e,O=I+L,O<3&&(O=0);;)if(F=D,D=B.times(F.plus(v(N,F,L,1))),_(F.c).slice(0,O)===(T=_(D.c)).slice(0,O))if(D.e<I&&--O,T=T.slice(O-3,O+1),T=="9999"||!M&&T=="4999"){if(!M&&(Oe(F,F.e+H+2,0),F.times(F).eq(N))){D=F;break}L+=4,O+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(Oe(D,D.e+H+2,1),E=!D.times(D).eq(N));break}}return Oe(D,D.e+H+1,Q,E)},P.toExponential=function(E,T){return E!=null&&(y(E,0,m),E++),ue(this,E,T,1)},P.toFixed=function(E,T){return E!=null&&(y(E,0,m),E=E+this.e+1),ue(this,E,T)},P.toFormat=function(E,T,D){var M,F=this;if(D==null)E!=null&&T&&typeof T=="object"?(D=T,T=null):E&&typeof E=="object"?(D=E,E=T=null):D=ie;else if(typeof D!="object")throw Error(s+"Argument not an object: "+D);if(M=F.toFixed(E,T),F.c){var N,U=M.split("."),O=+D.groupSize,I=+D.secondaryGroupSize,L=D.groupSeparator||"",B=U[0],W=U[1],se=F.s<0,ae=se?B.slice(1):B,Se=ae.length;if(I&&(N=O,O=I,I=N,Se-=N),O>0&&Se>0){for(N=Se%O||O,B=ae.substr(0,N);N<Se;N+=O)B+=L+ae.substr(N,O);I>0&&(B+=L+ae.slice(N)),se&&(B="-"+B)}M=W?B+(D.decimalSeparator||"")+((I=+D.fractionGroupSize)?W.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):W):B}return(D.prefix||"")+M+(D.suffix||"")},P.toFraction=function(E){var T,D,M,F,N,U,O,I,L,B,W,se,ae=this,Se=ae.c;if(E!=null&&(O=new K(E),!O.isInteger()&&(O.c||O.s!==1)||O.lt(V)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+je(O));if(!Se)return new K(ae);for(T=new K(V),L=D=new K(V),M=I=new K(V),se=_(Se),N=T.e=se.length-ae.e-1,T.c[0]=f[(U=N%l)<0?l+U:U],E=!E||O.comparedTo(T)>0?N>0?T:L:O,U=re,re=1/0,O=new K(se),I.c[0]=0;B=v(O,T,0,1),F=D.plus(B.times(M)),F.comparedTo(E)!=1;)D=M,M=F,L=I.plus(B.times(F=L)),I=F,T=O.minus(B.times(F=T)),O=F;return F=v(E.minus(D),M,0,1),I=I.plus(F.times(L)),D=D.plus(F.times(M)),I.s=L.s=ae.s,N=N*2,W=v(L,M,N,Q).minus(ae).abs().comparedTo(v(I,D,N,Q).minus(ae).abs())<1?[L,M]:[I,D],re=U,W},P.toNumber=function(){return+je(this)},P.toPrecision=function(E,T){return E!=null&&y(E,1,m),ue(this,E,T,2)},P.toString=function(E){var T,D=this,M=D.s,F=D.e;return F===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(E==null?T=F<=J||F>=ee?w(_(D.c),F):S(_(D.c),F,"0"):E===10&&Ae?(D=Oe(new K(D),H+F+1,Q),T=S(_(D.c),D.e,"0")):(y(E,2,Ue.length,"Base"),T=$(S(_(D.c),F,"0"),10,E,M,!0)),M<0&&D.c[0]&&(T="-"+T)),T},P.valueOf=P.toJSON=function(){return je(this)},P._isBigNumber=!0,R!=null&&K.set(R),K}function C(R){var v=R|0;return R>0||R===v?v:v-1}function _(R){for(var v,$,Y=1,P=R.length,V=R[0]+"";Y<P;){for(v=R[Y++]+"",$=l-v.length;$--;v="0"+v);V+=v}for(P=V.length;V.charCodeAt(--P)===48;);return V.slice(0,P+1||1)}function g(R,v){var $,Y,P=R.c,V=v.c,H=R.s,Q=v.s,J=R.e,ee=v.e;if(!H||!Q)return null;if($=P&&!P[0],Y=V&&!V[0],$||Y)return $?Y?0:-Q:H;if(H!=Q)return H;if($=H<0,Y=J==ee,!P||!V)return Y?0:!P^$?1:-1;if(!Y)return J>ee^$?1:-1;for(Q=(J=P.length)<(ee=V.length)?J:ee,H=0;H<Q;H++)if(P[H]!=V[H])return P[H]>V[H]^$?1:-1;return J==ee?0:J>ee^$?1:-1}function y(R,v,$,Y){if(R<v||R>$||R!==o(R))throw Error(s+(Y||"Argument")+(typeof R=="number"?R<v||R>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(R))}function k(R){var v=R.c.length-1;return C(R.e/l)==v&&R.c[v]%2!=0}function w(R,v){return(R.length>1?R.charAt(0)+"."+R.slice(1):R)+(v<0?"e":"e+")+v}function S(R,v,$){var Y,P;if(v<0){for(P=$+".";++v;P+=$);R=P+R}else if(Y=R.length,++v>Y){for(P=$,v-=Y;--v;P+=$);R+=P}else v<Y&&(R=R.slice(0,v)+"."+R.slice(v));return R}e=b(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Ni<"u"&&Ni.exports?Ni.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(og)});var ug=X((BO,ag)=>{var sg=jc(),ig=ag.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function l(d,f){var p,m,b,C,_=r,g,y=f[d],k=y!=null&&(y instanceof sg||sg.isBigNumber(y));switch(y&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(d)),typeof a=="function"&&(y=a.call(f,d,y)),typeof y){case"string":return k?y:c(y);case"number":return isFinite(y)?String(y):"null";case"boolean":case"null":case"bigint":return String(y);case"object":if(!y)return"null";if(r+=o,g=[],Object.prototype.toString.apply(y)==="[object Array]"){for(C=y.length,p=0;p<C;p+=1)g[p]=l(p,y)||"null";return b=g.length===0?"[]":r?`[
|
|
44
|
-
`+r+
|
|
43
|
+
`}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>jn(im()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(eg(),Zm))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};Qr.Gaxios=Ii;Kr=Ii});var Xe=X(it=>{"use strict";var zE=it&&it.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),HE=it&&it.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zE(e,t,n)};Object.defineProperty(it,"__esModule",{value:!0});it.instance=it.Gaxios=it.GaxiosError=void 0;it.request=GE;var og=rg();Object.defineProperty(it,"Gaxios",{enumerable:!0,get:function(){return og.Gaxios}});var WE=pc();Object.defineProperty(it,"GaxiosError",{enumerable:!0,get:function(){return WE.GaxiosError}});HE(yc(),it);it.instance=new og.Gaxios;async function GE(t){return it.instance.request(t)}});var jc=X((sg,Bi)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,m=1e9;function b(v){var R,$,V,P=J.prototype={constructor:J,toString:null,valueOf:null},Q=new J(1),z=20,K=4,Y=-7,ee=21,ae=-1e7,se=1e7,me=!1,G=1,Z=0,ie={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ue="0123456789abcdefghijklmnopqrstuvwxyz",Ae=!0;function J(E,T){var D,M,F,B,U,O,I,L,N=this;if(!(N instanceof J))return new J(E,T);if(T==null){if(E&&E._isBigNumber===!0){N.s=E.s,!E.c||E.e>se?N.c=N.e=null:E.e<ae?N.c=[N.e=0]:(N.e=E.e,N.c=E.c.slice());return}if((O=typeof E=="number")&&E*0==0){if(N.s=1/E<0?(E=-E,-1):1,E===~~E){for(B=0,U=E;U>=10;U/=10,B++);B>se?N.c=N.e=null:(N.e=B,N.c=[E]);return}L=String(E)}else{if(!n.test(L=String(E)))return V(N,L,O);N.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(B=L.indexOf("."))>-1&&(L=L.replace(".","")),(U=L.search(/e/i))>0?(B<0&&(B=U),B+=+L.slice(U+1),L=L.substring(0,U)):B<0&&(B=L.length)}else{if(g(T,2,Ue.length,"Base"),T==10&&Ae)return N=new J(E),Oe(N,z+N.e+1,K);if(L=String(E),O=typeof E=="number"){if(E*0!=0)return V(N,L,O,T);if(N.s=1/E<0?(L=L.slice(1),-1):1,J.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+E)}else N.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(D=Ue.slice(0,T),B=U=0,I=L.length;U<I;U++)if(D.indexOf(M=L.charAt(U))<0){if(M=="."){if(U>B){B=I;continue}}else if(!F&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){F=!0,U=-1,B=0;continue}return V(N,String(E),O,T)}O=!1,L=$(L,T,10,N.s),(B=L.indexOf("."))>-1?L=L.replace(".",""):B=L.length}for(U=0;L.charCodeAt(U)===48;U++);for(I=L.length;L.charCodeAt(--I)===48;);if(L=L.slice(U,++I)){if(I-=U,O&&J.DEBUG&&I>15&&(E>d||E!==o(E)))throw Error(a+N.s*E);if((B=B-U-1)>se)N.c=N.e=null;else if(B<ae)N.c=[N.e=0];else{if(N.e=B,N.c=[],U=(B+1)%l,B<0&&(U+=l),U<I){for(U&&N.c.push(+L.slice(0,U)),I-=l;U<I;)N.c.push(+L.slice(U,U+=l));U=l-(L=L.slice(U)).length}else U-=I;for(;U--;L+="0");N.c.push(+L)}}else N.c=[N.e=0]}J.clone=b,J.ROUND_UP=0,J.ROUND_DOWN=1,J.ROUND_CEIL=2,J.ROUND_FLOOR=3,J.ROUND_HALF_UP=4,J.ROUND_HALF_DOWN=5,J.ROUND_HALF_EVEN=6,J.ROUND_HALF_CEIL=7,J.ROUND_HALF_FLOOR=8,J.EUCLID=9,J.config=J.set=function(E){var T,D;if(E!=null)if(typeof E=="object"){if(E.hasOwnProperty(T="DECIMAL_PLACES")&&(D=E[T],g(D,0,m,T),z=D),E.hasOwnProperty(T="ROUNDING_MODE")&&(D=E[T],g(D,0,8,T),K=D),E.hasOwnProperty(T="EXPONENTIAL_AT")&&(D=E[T],D&&D.pop?(g(D[0],-m,0,T),g(D[1],0,m,T),Y=D[0],ee=D[1]):(g(D,-m,m,T),Y=-(ee=D<0?-D:D))),E.hasOwnProperty(T="RANGE"))if(D=E[T],D&&D.pop)g(D[0],-m,-1,T),g(D[1],1,m,T),ae=D[0],se=D[1];else if(g(D,-m,m,T),D)ae=-(se=D<0?-D:D);else throw Error(s+T+" cannot be zero: "+D);if(E.hasOwnProperty(T="CRYPTO"))if(D=E[T],D===!!D)if(D)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=D;else throw me=!D,Error(s+"crypto unavailable");else me=D;else throw Error(s+T+" not true or false: "+D);if(E.hasOwnProperty(T="MODULO_MODE")&&(D=E[T],g(D,0,9,T),G=D),E.hasOwnProperty(T="POW_PRECISION")&&(D=E[T],g(D,0,m,T),Z=D),E.hasOwnProperty(T="FORMAT"))if(D=E[T],typeof D=="object")ie=D;else throw Error(s+T+" not an object: "+D);if(E.hasOwnProperty(T="ALPHABET"))if(D=E[T],typeof D=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(D))Ae=D.slice(0,10)=="0123456789",Ue=D;else throw Error(s+T+" invalid: "+D)}else throw Error(s+"Object expected: "+E);return{DECIMAL_PLACES:z,ROUNDING_MODE:K,EXPONENTIAL_AT:[Y,ee],RANGE:[ae,se],CRYPTO:me,MODULO_MODE:G,POW_PRECISION:Z,FORMAT:ie,ALPHABET:Ue}},J.isBigNumber=function(E){if(!E||E._isBigNumber!==!0)return!1;if(!J.DEBUG)return!0;var T,D,M=E.c,F=E.e,B=E.s;e:if({}.toString.call(M)=="[object Array]"){if((B===1||B===-1)&&F>=-m&&F<=m&&F===o(F)){if(M[0]===0){if(F===0&&M.length===1)return!0;break e}if(T=(F+1)%l,T<1&&(T+=l),String(M[0]).length==T){for(T=0;T<M.length;T++)if(D=M[T],D<0||D>=c||D!==o(D))break e;if(D!==0)return!0}}}else if(M===null&&F===null&&(B===null||B===1||B===-1))return!0;throw Error(s+"Invalid BigNumber: "+E)},J.maximum=J.max=function(){return te(arguments,-1)},J.minimum=J.min=function(){return te(arguments,1)},J.random=(function(){var E=9007199254740992,T=Math.random()*E&2097151?function(){return o(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var M,F,B,U,O,I=0,L=[],N=new J(Q);if(D==null?D=z:g(D,0,m),U=r(D/l),me)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));I<U;)O=M[I]*131072+(M[I+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),M[I]=F[0],M[I+1]=F[1]):(L.push(O%1e14),I+=2);I=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);I<U;)O=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],O>=9e15?crypto.randomBytes(7).copy(M,I):(L.push(O%1e14),I+=7);I=U/7}else throw me=!1,Error(s+"crypto unavailable");if(!me)for(;I<U;)O=T(),O<9e15&&(L[I++]=O%1e14);for(U=L[--I],D%=l,U&&D&&(O=f[l-D],L[I]=o(U/O)*O);L[I]===0;L.pop(),I--);if(I<0)L=[B=0];else{for(B=-1;L[0]===0;L.splice(0,1),B-=l);for(I=1,O=L[0];O>=10;O/=10,I++);I<l&&(B-=l-I)}return N.e=B,N.c=L,N}})(),J.sum=function(){for(var E=1,T=arguments,D=new J(T[0]);E<T.length;)D=D.plus(T[E++]);return D},$=(function(){var E="0123456789";function T(D,M,F,B){for(var U,O=[0],I,L=0,N=D.length;L<N;){for(I=O.length;I--;O[I]*=M);for(O[0]+=B.indexOf(D.charAt(L++)),U=0;U<O.length;U++)O[U]>F-1&&(O[U+1]==null&&(O[U+1]=0),O[U+1]+=O[U]/F|0,O[U]%=F)}return O.reverse()}return function(D,M,F,B,U){var O,I,L,N,H,oe,ue,Se,Ie=D.indexOf("."),Me=z,ke=K;for(Ie>=0&&(N=Z,Z=0,D=D.replace(".",""),Se=new J(M),oe=Se.pow(D.length-Ie),Z=N,Se.c=T(A(_(oe.c),oe.e,"0"),10,F,E),Se.e=Se.c.length),ue=T(D,M,F,U?(O=Ue,E):(O=E,Ue)),L=N=ue.length;ue[--N]==0;ue.pop());if(!ue[0])return O.charAt(0);if(Ie<0?--L:(oe.c=ue,oe.e=L,oe.s=B,oe=R(oe,Se,Me,ke,F),ue=oe.c,H=oe.r,L=oe.e),I=L+Me+1,Ie=ue[I],N=F/2,H=H||I<0||ue[I+1]!=null,H=ke<4?(Ie!=null||H)&&(ke==0||ke==(oe.s<0?3:2)):Ie>N||Ie==N&&(ke==4||H||ke==6&&ue[I-1]&1||ke==(oe.s<0?8:7)),I<1||!ue[0])D=H?A(O.charAt(1),-Me,O.charAt(0)):O.charAt(0);else{if(ue.length=I,H)for(--F;++ue[--I]>F;)ue[I]=0,I||(++L,ue=[1].concat(ue));for(N=ue.length;!ue[--N];);for(Ie=0,D="";Ie<=N;D+=O.charAt(ue[Ie++]));D=A(D,L,O.charAt(0))}return D}})(),R=(function(){function E(M,F,B){var U,O,I,L,N=0,H=M.length,oe=F%p,ue=F/p|0;for(M=M.slice();H--;)I=M[H]%p,L=M[H]/p|0,U=ue*I+L*oe,O=oe*I+U%p*p+N,N=(O/B|0)+(U/p|0)+ue*L,M[H]=O%B;return N&&(M=[N].concat(M)),M}function T(M,F,B,U){var O,I;if(B!=U)I=B>U?1:-1;else for(O=I=0;O<B;O++)if(M[O]!=F[O]){I=M[O]>F[O]?1:-1;break}return I}function D(M,F,B,U){for(var O=0;B--;)M[B]-=O,O=M[B]<F[B]?1:0,M[B]=O*U+M[B]-F[B];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,F,B,U,O){var I,L,N,H,oe,ue,Se,Ie,Me,ke,Te,qe,Cr,wr,Er,ft,fn,Ze=M.s==F.s?1:-1,ze=M.c,De=F.c;if(!ze||!ze[0]||!De||!De[0])return new J(!M.s||!F.s||(ze?De&&ze[0]==De[0]:!De)?NaN:ze&&ze[0]==0||!De?Ze*0:Ze/0);for(Ie=new J(Ze),Me=Ie.c=[],L=M.e-F.e,Ze=B+L+1,O||(O=c,L=C(M.e/l)-C(F.e/l),Ze=Ze/l|0),N=0;De[N]==(ze[N]||0);N++);if(De[N]>(ze[N]||0)&&L--,Ze<0)Me.push(1),H=!0;else{for(wr=ze.length,ft=De.length,N=0,Ze+=2,oe=o(O/(De[0]+1)),oe>1&&(De=E(De,oe,O),ze=E(ze,oe,O),ft=De.length,wr=ze.length),Cr=ft,ke=ze.slice(0,ft),Te=ke.length;Te<ft;ke[Te++]=0);fn=De.slice(),fn=[0].concat(fn),Er=De[0],De[1]>=O/2&&Er++;do{if(oe=0,I=T(De,ke,ft,Te),I<0){if(qe=ke[0],ft!=Te&&(qe=qe*O+(ke[1]||0)),oe=o(qe/Er),oe>1)for(oe>=O&&(oe=O-1),ue=E(De,oe,O),Se=ue.length,Te=ke.length;T(ue,ke,Se,Te)==1;)oe--,D(ue,ft<Se?fn:De,Se,O),Se=ue.length,I=1;else oe==0&&(I=oe=1),ue=De.slice(),Se=ue.length;if(Se<Te&&(ue=[0].concat(ue)),D(ke,ue,Te,O),Te=ke.length,I==-1)for(;T(De,ke,ft,Te)<1;)oe++,D(ke,ft<Te?fn:De,Te,O),Te=ke.length}else I===0&&(oe++,ke=[0]);Me[N++]=oe,ke[0]?ke[Te++]=ze[Cr]||0:(ke=[ze[Cr]],Te=1)}while((Cr++<wr||ke[0]!=null)&&Ze--);H=ke[0]!=null,Me[0]||Me.splice(0,1)}if(O==c){for(N=1,Ze=Me[0];Ze>=10;Ze/=10,N++);Oe(Ie,B+(Ie.e=N+L*l-1)+1,U,H)}else Ie.e=L,Ie.r=+H;return Ie}})();function ce(E,T,D,M){var F,B,U,O,I;if(D==null?D=K:g(D,0,8),!E.c)return E.toString();if(F=E.c[0],U=E.e,T==null)I=_(E.c),I=M==1||M==2&&(U<=Y||U>=ee)?w(I,U):A(I,U,"0");else if(E=Oe(new J(E),T,D),B=E.e,I=_(E.c),O=I.length,M==1||M==2&&(T<=B||B<=Y)){for(;O<T;I+="0",O++);I=w(I,B)}else if(T-=U+(M===2&&B>U),I=A(I,B,"0"),B+1>O){if(--T>0)for(I+=".";T--;I+="0");}else if(T+=B-O,T>0)for(B+1==O&&(I+=".");T--;I+="0");return E.s<0&&F?"-"+I:I}function te(E,T){for(var D,M,F=1,B=new J(E[0]);F<E.length;F++)M=new J(E[F]),(!M.s||(D=y(B,M))===T||D===0&&B.s===T)&&(B=M);return B}function ve(E,T,D){for(var M=1,F=T.length;!T[--F];T.pop());for(F=T[0];F>=10;F/=10,M++);return(D=M+D*l-1)>se?E.c=E.e=null:D<ae?E.c=[E.e=0]:(E.e=D,E.c=T),E}V=(function(){var E=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,D=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(B,U,O,I){var L,N=O?U:U.replace(F,"");if(M.test(N))B.s=isNaN(N)?null:N<0?-1:1;else{if(!O&&(N=N.replace(E,function(H,oe,ue){return L=(ue=ue.toLowerCase())=="x"?16:ue=="b"?2:8,!I||I==L?oe:H}),I&&(L=I,N=N.replace(T,"$1").replace(D,"0.$1")),U!=N))return new J(N,L);if(J.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+U);B.s=null}B.c=B.e=null}})();function Oe(E,T,D,M){var F,B,U,O,I,L,N,H=E.c,oe=f;if(H){e:{for(F=1,O=H[0];O>=10;O/=10,F++);if(B=T-F,B<0)B+=l,U=T,I=H[L=0],N=o(I/oe[F-U-1]%10);else if(L=r((B+1)/l),L>=H.length)if(M){for(;H.length<=L;H.push(0));I=N=0,F=1,B%=l,U=B-l+1}else break e;else{for(I=O=H[L],F=1;O>=10;O/=10,F++);B%=l,U=B-l+F,N=U<0?0:o(I/oe[F-U-1]%10)}if(M=M||T<0||H[L+1]!=null||(U<0?I:I%oe[F-U-1]),M=D<4?(N||M)&&(D==0||D==(E.s<0?3:2)):N>5||N==5&&(D==4||M||D==6&&(B>0?U>0?I/oe[F-U]:0:H[L-1])%10&1||D==(E.s<0?8:7)),T<1||!H[0])return H.length=0,M?(T-=E.e+1,H[0]=oe[(l-T%l)%l],E.e=-T||0):H[0]=E.e=0,E;if(B==0?(H.length=L,O=1,L--):(H.length=L+1,O=oe[l-B],H[L]=U>0?o(I/oe[F-U]%oe[U])*O:0),M)for(;;)if(L==0){for(B=1,U=H[0];U>=10;U/=10,B++);for(U=H[0]+=O,O=1;U>=10;U/=10,O++);B!=O&&(E.e++,H[0]==c&&(H[0]=1));break}else{if(H[L]+=O,H[L]!=c)break;H[L--]=0,O=1}for(B=H.length;H[--B]===0;H.pop());}E.e>se?E.c=E.e=null:E.e<ae&&(E.c=[E.e=0])}return E}function je(E){var T,D=E.e;return D===null?E.toString():(T=_(E.c),T=D<=Y||D>=ee?w(T,D):A(T,D,"0"),E.s<0?"-"+T:T)}return P.absoluteValue=P.abs=function(){var E=new J(this);return E.s<0&&(E.s=1),E},P.comparedTo=function(E,T){return y(this,new J(E,T))},P.decimalPlaces=P.dp=function(E,T){var D,M,F,B=this;if(E!=null)return g(E,0,m),T==null?T=K:g(T,0,8),Oe(new J(B),E+B.e+1,T);if(!(D=B.c))return null;if(M=((F=D.length-1)-C(this.e/l))*l,F=D[F])for(;F%10==0;F/=10,M--);return M<0&&(M=0),M},P.dividedBy=P.div=function(E,T){return R(this,new J(E,T),z,K)},P.dividedToIntegerBy=P.idiv=function(E,T){return R(this,new J(E,T),0,1)},P.exponentiatedBy=P.pow=function(E,T){var D,M,F,B,U,O,I,L,N,H=this;if(E=new J(E),E.c&&!E.isInteger())throw Error(s+"Exponent not an integer: "+je(E));if(T!=null&&(T=new J(T)),O=E.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!E.c||!E.c[0])return N=new J(Math.pow(+je(H),O?E.s*(2-S(E)):+je(E))),T?N.mod(T):N;if(I=E.s<0,T){if(T.c?!T.c[0]:!T.s)return new J(NaN);M=!I&&H.isInteger()&&T.isInteger(),M&&(H=H.mod(T))}else{if(E.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||O&&H.c[1]>=24e7:H.c[0]<8e13||O&&H.c[0]<=9999975e7)))return B=H.s<0&&S(E)?-0:0,H.e>-1&&(B=1/B),new J(I?1/B:B);Z&&(B=r(Z/l+2))}for(O?(D=new J(.5),I&&(E.s=1),L=S(E)):(F=Math.abs(+je(E)),L=F%2),N=new J(Q);;){if(L){if(N=N.times(H),!N.c)break;B?N.c.length>B&&(N.c.length=B):M&&(N=N.mod(T))}if(F){if(F=o(F/2),F===0)break;L=F%2}else if(E=E.times(D),Oe(E,E.e+1,1),E.e>14)L=S(E);else{if(F=+je(E),F===0)break;L=F%2}H=H.times(H),B?H.c&&H.c.length>B&&(H.c.length=B):M&&(H=H.mod(T))}return M?N:(I&&(N=Q.div(N)),T?N.mod(T):B?Oe(N,Z,K,U):N)},P.integerValue=function(E){var T=new J(this);return E==null?E=K:g(E,0,8),Oe(T,T.e+1,E)},P.isEqualTo=P.eq=function(E,T){return y(this,new J(E,T))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(E,T){return y(this,new J(E,T))>0},P.isGreaterThanOrEqualTo=P.gte=function(E,T){return(T=y(this,new J(E,T)))===1||T===0},P.isInteger=function(){return!!this.c&&C(this.e/l)>this.c.length-2},P.isLessThan=P.lt=function(E,T){return y(this,new J(E,T))<0},P.isLessThanOrEqualTo=P.lte=function(E,T){return(T=y(this,new J(E,T)))===-1||T===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(E,T){var D,M,F,B,U=this,O=U.s;if(E=new J(E,T),T=E.s,!O||!T)return new J(NaN);if(O!=T)return E.s=-T,U.plus(E);var I=U.e/l,L=E.e/l,N=U.c,H=E.c;if(!I||!L){if(!N||!H)return N?(E.s=-T,E):new J(H?U:NaN);if(!N[0]||!H[0])return H[0]?(E.s=-T,E):new J(N[0]?U:K==3?-0:0)}if(I=C(I),L=C(L),N=N.slice(),O=I-L){for((B=O<0)?(O=-O,F=N):(L=I,F=H),F.reverse(),T=O;T--;F.push(0));F.reverse()}else for(M=(B=(O=N.length)<(T=H.length))?O:T,O=T=0;T<M;T++)if(N[T]!=H[T]){B=N[T]<H[T];break}if(B&&(F=N,N=H,H=F,E.s=-E.s),T=(M=H.length)-(D=N.length),T>0)for(;T--;N[D++]=0);for(T=c-1;M>O;){if(N[--M]<H[M]){for(D=M;D&&!N[--D];N[D]=T);--N[D],N[M]+=c}N[M]-=H[M]}for(;N[0]==0;N.splice(0,1),--L);return N[0]?ve(E,N,L):(E.s=K==3?-1:1,E.c=[E.e=0],E)},P.modulo=P.mod=function(E,T){var D,M,F=this;return E=new J(E,T),!F.c||!E.s||E.c&&!E.c[0]?new J(NaN):!E.c||F.c&&!F.c[0]?new J(F):(G==9?(M=E.s,E.s=1,D=R(F,E,0,3),E.s=M,D.s*=M):D=R(F,E,0,G),E=F.minus(D.times(E)),!E.c[0]&&G==1&&(E.s=F.s),E)},P.multipliedBy=P.times=function(E,T){var D,M,F,B,U,O,I,L,N,H,oe,ue,Se,Ie,Me,ke=this,Te=ke.c,qe=(E=new J(E,T)).c;if(!Te||!qe||!Te[0]||!qe[0])return!ke.s||!E.s||Te&&!Te[0]&&!qe||qe&&!qe[0]&&!Te?E.c=E.e=E.s=null:(E.s*=ke.s,!Te||!qe?E.c=E.e=null:(E.c=[0],E.e=0)),E;for(M=C(ke.e/l)+C(E.e/l),E.s*=ke.s,I=Te.length,H=qe.length,I<H&&(Se=Te,Te=qe,qe=Se,F=I,I=H,H=F),F=I+H,Se=[];F--;Se.push(0));for(Ie=c,Me=p,F=H;--F>=0;){for(D=0,oe=qe[F]%Me,ue=qe[F]/Me|0,U=I,B=F+U;B>F;)L=Te[--U]%Me,N=Te[U]/Me|0,O=ue*L+N*oe,L=oe*L+O%Me*Me+Se[B]+D,D=(L/Ie|0)+(O/Me|0)+ue*N,Se[B--]=L%Ie;Se[B]=D}return D?++M:Se.splice(0,1),ve(E,Se,M)},P.negated=function(){var E=new J(this);return E.s=-E.s||null,E},P.plus=function(E,T){var D,M=this,F=M.s;if(E=new J(E,T),T=E.s,!F||!T)return new J(NaN);if(F!=T)return E.s=-T,M.minus(E);var B=M.e/l,U=E.e/l,O=M.c,I=E.c;if(!B||!U){if(!O||!I)return new J(F/0);if(!O[0]||!I[0])return I[0]?E:new J(O[0]?M:F*0)}if(B=C(B),U=C(U),O=O.slice(),F=B-U){for(F>0?(U=B,D=I):(F=-F,D=O),D.reverse();F--;D.push(0));D.reverse()}for(F=O.length,T=I.length,F-T<0&&(D=I,I=O,O=D,T=F),F=0;T;)F=(O[--T]=O[T]+I[T]+F)/c|0,O[T]=c===O[T]?0:O[T]%c;return F&&(O=[F].concat(O),++U),ve(E,O,U)},P.precision=P.sd=function(E,T){var D,M,F,B=this;if(E!=null&&E!==!!E)return g(E,1,m),T==null?T=K:g(T,0,8),Oe(new J(B),E,T);if(!(D=B.c))return null;if(F=D.length-1,M=F*l+1,F=D[F]){for(;F%10==0;F/=10,M--);for(F=D[0];F>=10;F/=10,M++);}return E&&B.e+1>M&&(M=B.e+1),M},P.shiftedBy=function(E){return g(E,-d,d),this.times("1e"+E)},P.squareRoot=P.sqrt=function(){var E,T,D,M,F,B=this,U=B.c,O=B.s,I=B.e,L=z+4,N=new J("0.5");if(O!==1||!U||!U[0])return new J(!O||O<0&&(!U||U[0])?NaN:U?B:1/0);if(O=Math.sqrt(+je(B)),O==0||O==1/0?(T=_(U),(T.length+I)%2==0&&(T+="0"),O=Math.sqrt(+T),I=C((I+1)/2)-(I<0||I%2),O==1/0?T="5e"+I:(T=O.toExponential(),T=T.slice(0,T.indexOf("e")+1)+I),D=new J(T)):D=new J(O+""),D.c[0]){for(I=D.e,O=I+L,O<3&&(O=0);;)if(F=D,D=N.times(F.plus(R(B,F,L,1))),_(F.c).slice(0,O)===(T=_(D.c)).slice(0,O))if(D.e<I&&--O,T=T.slice(O-3,O+1),T=="9999"||!M&&T=="4999"){if(!M&&(Oe(F,F.e+z+2,0),F.times(F).eq(B))){D=F;break}L+=4,O+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(Oe(D,D.e+z+2,1),E=!D.times(D).eq(B));break}}return Oe(D,D.e+z+1,K,E)},P.toExponential=function(E,T){return E!=null&&(g(E,0,m),E++),ce(this,E,T,1)},P.toFixed=function(E,T){return E!=null&&(g(E,0,m),E=E+this.e+1),ce(this,E,T)},P.toFormat=function(E,T,D){var M,F=this;if(D==null)E!=null&&T&&typeof T=="object"?(D=T,T=null):E&&typeof E=="object"?(D=E,E=T=null):D=ie;else if(typeof D!="object")throw Error(s+"Argument not an object: "+D);if(M=F.toFixed(E,T),F.c){var B,U=M.split("."),O=+D.groupSize,I=+D.secondaryGroupSize,L=D.groupSeparator||"",N=U[0],H=U[1],oe=F.s<0,ue=oe?N.slice(1):N,Se=ue.length;if(I&&(B=O,O=I,I=B,Se-=B),O>0&&Se>0){for(B=Se%O||O,N=ue.substr(0,B);B<Se;B+=O)N+=L+ue.substr(B,O);I>0&&(N+=L+ue.slice(B)),oe&&(N="-"+N)}M=H?N+(D.decimalSeparator||"")+((I=+D.fractionGroupSize)?H.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):H):N}return(D.prefix||"")+M+(D.suffix||"")},P.toFraction=function(E){var T,D,M,F,B,U,O,I,L,N,H,oe,ue=this,Se=ue.c;if(E!=null&&(O=new J(E),!O.isInteger()&&(O.c||O.s!==1)||O.lt(Q)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+je(O));if(!Se)return new J(ue);for(T=new J(Q),L=D=new J(Q),M=I=new J(Q),oe=_(Se),B=T.e=oe.length-ue.e-1,T.c[0]=f[(U=B%l)<0?l+U:U],E=!E||O.comparedTo(T)>0?B>0?T:L:O,U=se,se=1/0,O=new J(oe),I.c[0]=0;N=R(O,T,0,1),F=D.plus(N.times(M)),F.comparedTo(E)!=1;)D=M,M=F,L=I.plus(N.times(F=L)),I=F,T=O.minus(N.times(F=T)),O=F;return F=R(E.minus(D),M,0,1),I=I.plus(F.times(L)),D=D.plus(F.times(M)),I.s=L.s=ue.s,B=B*2,H=R(L,M,B,K).minus(ue).abs().comparedTo(R(I,D,B,K).minus(ue).abs())<1?[L,M]:[I,D],se=U,H},P.toNumber=function(){return+je(this)},P.toPrecision=function(E,T){return E!=null&&g(E,1,m),ce(this,E,T,2)},P.toString=function(E){var T,D=this,M=D.s,F=D.e;return F===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(E==null?T=F<=Y||F>=ee?w(_(D.c),F):A(_(D.c),F,"0"):E===10&&Ae?(D=Oe(new J(D),z+F+1,K),T=A(_(D.c),D.e,"0")):(g(E,2,Ue.length,"Base"),T=$(A(_(D.c),F,"0"),10,E,M,!0)),M<0&&D.c[0]&&(T="-"+T)),T},P.valueOf=P.toJSON=function(){return je(this)},P._isBigNumber=!0,v!=null&&J.set(v),J}function C(v){var R=v|0;return v>0||v===R?R:R-1}function _(v){for(var R,$,V=1,P=v.length,Q=v[0]+"";V<P;){for(R=v[V++]+"",$=l-R.length;$--;R="0"+R);Q+=R}for(P=Q.length;Q.charCodeAt(--P)===48;);return Q.slice(0,P+1||1)}function y(v,R){var $,V,P=v.c,Q=R.c,z=v.s,K=R.s,Y=v.e,ee=R.e;if(!z||!K)return null;if($=P&&!P[0],V=Q&&!Q[0],$||V)return $?V?0:-K:z;if(z!=K)return z;if($=z<0,V=Y==ee,!P||!Q)return V?0:!P^$?1:-1;if(!V)return Y>ee^$?1:-1;for(K=(Y=P.length)<(ee=Q.length)?Y:ee,z=0;z<K;z++)if(P[z]!=Q[z])return P[z]>Q[z]^$?1:-1;return Y==ee?0:Y>ee^$?1:-1}function g(v,R,$,V){if(v<R||v>$||v!==o(v))throw Error(s+(V||"Argument")+(typeof v=="number"?v<R||v>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(v))}function S(v){var R=v.c.length-1;return C(v.e/l)==R&&v.c[R]%2!=0}function w(v,R){return(v.length>1?v.charAt(0)+"."+v.slice(1):v)+(R<0?"e":"e+")+R}function A(v,R,$){var V,P;if(R<0){for(P=$+".";++R;P+=$);v=P+v}else if(V=v.length,++R>V){for(P=$,R-=V;--R;P+=$);v+=P}else R<V&&(v=v.slice(0,R)+"."+v.slice(R));return v}e=b(),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)})(sg)});var cg=X(($O,ug)=>{var ig=jc(),ag=ug.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function l(d,f){var p,m,b,C,_=r,y,g=f[d],S=g!=null&&(g instanceof ig||ig.isBigNumber(g));switch(g&&typeof g=="object"&&typeof g.toJSON=="function"&&(g=g.toJSON(d)),typeof a=="function"&&(g=a.call(f,d,g)),typeof g){case"string":return S?g:c(g);case"number":return isFinite(g)?String(g):"null";case"boolean":case"null":case"bigint":return String(g);case"object":if(!g)return"null";if(r+=o,y=[],Object.prototype.toString.apply(g)==="[object Array]"){for(C=g.length,p=0;p<C;p+=1)y[p]=l(p,g)||"null";return b=y.length===0?"[]":r?`[
|
|
44
|
+
`+r+y.join(`,
|
|
45
45
|
`+r)+`
|
|
46
|
-
`+_+"]":"["+
|
|
47
|
-
`+r+
|
|
46
|
+
`+_+"]":"["+y.join(",")+"]",r=_,b}if(a&&typeof a=="object")for(C=a.length,p=0;p<C;p+=1)typeof a[p]=="string"&&(m=a[p],b=l(m,g),b&&y.push(c(m)+(r?": ":":")+b));else Object.keys(g).forEach(function(w){var A=l(w,g);A&&y.push(c(w)+(r?": ":":")+A)});return b=y.length===0?"{}":r?`{
|
|
47
|
+
`+r+y.join(`,
|
|
48
48
|
`+r)+`
|
|
49
|
-
`+_+"}":"{"+
|
|
50
|
-
`,r:"\r",t:" "},s,a=function(_){throw{name:"SyntaxError",message:_,at:n,text:s}},c=function(_){return _&&_!==r&&a("Expected '"+_+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var _,g="";for(r==="-"&&(g="-",c("-"));r>="0"&&r<="9";)g+=r,c();if(r===".")for(g+=".";c()&&r>="0"&&r<="9";)g+=r;if(r==="e"||r==="E")for(g+=r,c(),(r==="-"||r==="+")&&(g+=r,c());r>="0"&&r<="9";)g+=r,c();if(_=+g,!isFinite(_))a("Bad number");else return Bi==null&&(Bi=jc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Bi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new Bi(_):_},d=function(){var _,g,y="",k;if(r==='"')for(var w=n;c();){if(r==='"')return n-1>w&&(y+=s.substring(w,n-1)),c(),y;if(r==="\\"){if(n-1>w&&(y+=s.substring(w,n-1)),c(),r==="u"){for(k=0,g=0;g<4&&(_=parseInt(c(),16),!!isFinite(_));g+=1)k=k*16+_;y+=String.fromCharCode(k)}else if(typeof o[r]=="string")y+=o[r];else break;w=n}}a("Bad string")},f=function(){for(;r&&r<=" ";)c()},p=function(){switch(r){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 '"+r+"'")},m,b=function(){var _=[];if(r==="["){if(c("["),f(),r==="]")return c("]"),_;for(;r;){if(_.push(m()),f(),r==="]")return c("]"),_;c(","),f()}}a("Bad array")},C=function(){var _,g=Object.create(null);if(r==="{"){if(c("{"),f(),r==="}")return c("}"),g;for(;r;){if(_=d(),f(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,_)&&a('Duplicate key "'+_+'"'),zE.test(_)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():g[_]=m():WE.test(_)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():g[_]=m():g[_]=m(),f(),r==="}")return c("}"),g;c(","),f()}}a("Bad object")};return m=function(){switch(f(),r){case"{":return C();case"[":return b();case'"':return d();case"-":return l();default:return r>="0"&&r<="9"?l():p()}},function(_,g){var y;return s=_+"",n=0,r=" ",y=m(),f(),r&&a("Syntax error"),typeof g=="function"?(function k(w,S){var R,v,$=w[S];return $&&typeof $=="object"&&Object.keys($).forEach(function(Y){v=k($,Y),v!==void 0?$[Y]=v:delete $[Y]}),g.call(w,S,$)})({"":y},""):y}};cg.exports=GE});var hg=X((LO,Mi)=>{var dg=ug().stringify,fg=lg();Mi.exports=function(t){return{parse:fg(t),stringify:dg}};Mi.exports.parse=fg();Mi.exports.stringify=dg});var Uc=X(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GCE_LINUX_BIOS_PATHS=void 0;Ht.isGoogleCloudServerless=gg;Ht.isGoogleComputeEngineLinux=yg;Ht.isGoogleComputeEngineMACAddress=_g;Ht.isGoogleComputeEngine=bg;Ht.detectGCPResidency=VE;var pg=oe("fs"),mg=oe("os");Ht.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var JE=/^42:01/;function gg(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function yg(){if((0,mg.platform)()!=="linux")return!1;try{(0,pg.statSync)(Ht.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,pg.readFileSync)(Ht.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function _g(){let t=(0,mg.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(JE.test(n))return!0}return!1}function bg(){return yg()||_g()}function VE(){return gg()||bg()}});var Cg=X(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.Colours=void 0;var tt=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=tt;tt.enabled=!1;tt.reset="";tt.bright="";tt.dim="";tt.red="";tt.green="";tt.yellow="";tt.blue="";tt.magenta="";tt.cyan="";tt.white="";tt.grey="";tt.refresh()});var Ag=X(Re=>{"use strict";var KE=Re&&Re.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),YE=Re&&Re.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),wg=Re&&Re.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&KE(n,e,r[o]);return YE(n,e),n}})();Object.defineProperty(Re,"__esModule",{value:!0});Re.env=Re.DebugLogBackendBase=Re.placeholder=Re.AdhocDebugLogger=Re.LogSeverity=void 0;Re.getNodeBackend=qc;Re.getDebugBackend=XE;Re.getStructuredBackend=ZE;Re.setBackend=ek;Re.log=kg;var QE=oe("events"),zo=wg(oe("process")),Eg=wg(oe("util")),gt=Cg(),zt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(zt||(Re.LogSeverity=zt={}));var Wo=class extends QE.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(zt.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(zt.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(zt.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(zt.ERROR,...r),this.func.sublog=r=>kg(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Re.AdhocDebugLogger=Wo;Re.placeholder=new Wo("",()=>{}).func;var Xr=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=zo.env[Re.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){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(n,...r)}catch(o){console.error(o)}}};Re.DebugLogBackendBase=Xr;var $c=class extends Xr{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${gt.Colours.green}${e}${gt.Colours.reset}`,a=`${gt.Colours.yellow}${zo.pid}${gt.Colours.reset}`,c;switch(n.severity){case zt.ERROR:c=`${gt.Colours.red}${n.severity}${gt.Colours.reset}`;break;case zt.INFO:c=`${gt.Colours.magenta}${n.severity}${gt.Colours.reset}`;break;case zt.WARNING:c=`${gt.Colours.yellow}${n.severity}${gt.Colours.reset}`;break;default:c=(o=n.severity)!==null&&o!==void 0?o:zt.DEFAULT;break}let l=Eg.formatWithOptions({colors:gt.Colours.enabled},...r),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${gt.Colours.grey}${f}${gt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function qc(){return new $c}var Hc=class extends Xr{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=zo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";zo.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function XE(t){return new Hc(t)}var zc=class extends Xr{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:zt.INFO,l=Object.assign({severity:c,message:Eg.format(...s)},o),d=JSON.stringify(l);r?r(o,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function ZE(t){return new zc(t)}Re.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Wc=new Map,yt;function ek(t){yt=t,Wc.clear()}function kg(t,e){if(!yt&&!zo.env[Re.env.nodeEnables]||!t)return Re.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Wc.get(t);if(n)return n.func;if(yt===null)return Re.placeholder;yt===void 0&&(yt=qc());let r=(()=>{let o;return new Wo(t,(a,...c)=>{if(o!==yt){if(yt===null)return;yt===void 0&&(yt=qc()),o=yt}yt?.log(t,a,...c)})})();return Wc.set(t,r),r.func}});var Gc=X(mr=>{"use strict";var tk=mr&&mr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),nk=mr&&mr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&tk(e,t,n)};Object.defineProperty(mr,"__esModule",{value:!0});nk(Ag(),mr)});var Jo=X(he=>{"use strict";var Tg=he&&he.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),rk=he&&he.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ok=he&&he.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&Tg(n,e,r[o]);return rk(n,e),n}})(),sk=he&&he.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tg(e,t,n)};Object.defineProperty(he,"__esModule",{value:!0});he.gcpResidencyCache=he.METADATA_SERVER_DETECTION=he.HEADERS=he.HEADER_VALUE=he.HEADER_NAME=he.SECONDARY_HOST_ADDRESS=he.HOST_ADDRESS=he.BASE_PATH=void 0;he.instance=dk;he.project=fk;he.universe=hk;he.bulk=pk;he.isAvailable=gk;he.resetIsAvailableCache=yk;he.getGCPResidency=Kc;he.setGCPResidency=vg;he.requestTimeout=Dg;var Jc=Xe(),ik=hg(),ak=Uc(),uk=ok(Gc());he.BASE_PATH="/computeMetadata/v1";he.HOST_ADDRESS="http://169.254.169.254";he.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";he.HEADER_NAME="Metadata-Flavor";he.HEADER_VALUE="Google";he.HEADERS=Object.freeze({[he.HEADER_NAME]:he.HEADER_VALUE});var Sg=uk.log("gcp-metadata");he.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 Vc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||he.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(he.BASE_PATH,t).href}function ck(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 Go(t,e={},n=3,r=!1){let o=new Headers(he.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((m,b)=>o.set(b,m)),s=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(ck(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,m)=>o.set(m,p)),a=e.params||a);let c=r?lk:Jc.request,l={url:`${Vc()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:Dg()};Sg.info("instance request %j",l);let d=await c(l);Sg.info("instance metadata is %s",d.data);let f=d.headers.get(he.HEADER_NAME);if(f!==he.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${he.HEADER_NAME} header. Expected '${he.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return ik.parse(d.data)}catch{}return d.data}async function lk(t){let e={...t,url:t.url?.toString().replace(Vc(),Vc(he.SECONDARY_HOST_ADDRESS))},n=(0,Jc.request)(t),r=(0,Jc.request)(e);return Promise.any([n,r])}function dk(t){return Go("instance",t)}function fk(t){return Go("project",t)}function hk(t){return Go("universe",t)}async function pk(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await Go(n),o=n.metadataKey;e[o]=r})())),e}function mk(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var ji;async function gk(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in he.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(he.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Kc();case"ping-only":}}try{return ji===void 0&&(ji=Go("instance",void 0,mk(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await ji,!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 n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function yk(){ji=void 0}he.gcpResidencyCache=null;function Kc(){return he.gcpResidencyCache===null&&vg(),he.gcpResidencyCache}function vg(t=null){he.gcpResidencyCache=t!==null?t:(0,ak.detectGCPResidency)()}function Dg(){return Kc()?0:3e3}sk(Uc(),he)});var Og=X(Ui=>{"use strict";Ui.byteLength=bk;Ui.toByteArray=wk;Ui.fromByteArray=Ak;var en=[],Rt=[],_k=typeof Uint8Array<"u"?Uint8Array:Array,Yc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(gr=0,Rg=Yc.length;gr<Rg;++gr)en[gr]=Yc[gr],Rt[Yc.charCodeAt(gr)]=gr;var gr,Rg;Rt[45]=62;Rt[95]=63;function xg(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function bk(t){var e=xg(t),n=e[0],r=e[1];return(n+r)*3/4-r}function Ck(t,e,n){return(e+n)*3/4-n}function wk(t){var e,n=xg(t),r=n[0],o=n[1],s=new _k(Ck(t,r,o)),a=0,c=o>0?r-4:r,l;for(l=0;l<c;l+=4)e=Rt[t.charCodeAt(l)]<<18|Rt[t.charCodeAt(l+1)]<<12|Rt[t.charCodeAt(l+2)]<<6|Rt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Rt[t.charCodeAt(l)]<<2|Rt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Rt[t.charCodeAt(l)]<<10|Rt[t.charCodeAt(l+1)]<<4|Rt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function Ek(t){return en[t>>18&63]+en[t>>12&63]+en[t>>6&63]+en[t&63]}function kk(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(Ek(r));return o.join("")}function Ak(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,c=n-r;a<c;a+=s)o.push(kk(t,a,a+s>c?c:a+s));return r===1?(e=t[n-1],o.push(en[e>>2]+en[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(en[e>>10]+en[e>>4&63]+en[e<<2&63]+"=")),o.join("")}});var Xc=X(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.fromArrayBufferToHex=Sk;function Sk(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Pg=X($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.BrowserCrypto=void 0;var Zr=Og(),Tk=Xc(),Zc=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 n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return Zr.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Zr.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=Zr.toByteArray(t.padBase64(r)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return Zr.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=Zr.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Zr.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,Tk.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};$i.BrowserCrypto=Zc});var Fg=X(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.NodeCrypto=void 0;var eo=oe("crypto"),el=class{async sha256DigestBase64(e){return eo.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return eo.randomBytes(e).toString("base64")}async verify(e,n,r){let o=eo.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=eo.createSign("RSA-SHA256");return r.update(n),r.end(),r.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 eo.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:Dk(e);return vk(eo.createHmac("sha256",r).update(n).digest())}};qi.NodeCrypto=el;function vk(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Dk(t){return Buffer.from(t)}});var Vo=X(An=>{"use strict";var Rk=An&&An.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),xk=An&&An.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Rk(e,t,n)};Object.defineProperty(An,"__esModule",{value:!0});An.createCrypto=Fk;An.hasBrowserCrypto=Ig;var Ok=Pg(),Pk=Fg();xk(Xc(),An);function Fk(){return Ig()?new Ok.BrowserCrypto:new Pk.NodeCrypto}function Ig(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var to=X((tl,Bg)=>{var Hi=oe("buffer"),tn=Hi.Buffer;function Ng(t,e){for(var n in t)e[n]=t[n]}tn.from&&tn.alloc&&tn.allocUnsafe&&tn.allocUnsafeSlow?Bg.exports=Hi:(Ng(Hi,tl),tl.Buffer=yr);function yr(t,e,n){return tn(t,e,n)}yr.prototype=Object.create(tn.prototype);Ng(tn,yr);yr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return tn(t,e,n)};yr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=tn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};yr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return tn(t)};yr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Hi.SlowBuffer(t)}});var Lg=X((KO,Mg)=>{"use strict";function nl(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Ik={ES256:nl(256),ES384:nl(384),ES512:nl(521)};function Nk(t){var e=Ik[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Mg.exports=Nk});var rl=X((YO,zg)=>{"use strict";var zi=to().Buffer,Ug=Lg(),Wi=128,$g=0,Bk=32,Mk=16,Lk=2,qg=Mk|Bk|$g<<6,Gi=Lk|$g<<6;function jk(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Hg(t){if(zi.isBuffer(t))return t;if(typeof t=="string")return zi.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Uk(t,e){t=Hg(t);var n=Ug(e),r=n+1,o=t.length,s=0;if(t[s++]!==qg)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(Wi|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==Gi)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(r<c)throw new Error('"r" specified length of "'+c+'", max of "'+r+'" is acceptable');var l=s;if(s+=c,t[s++]!==Gi)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-c,m=n-d,b=zi.allocUnsafe(p+c+m+d);for(s=0;s<p;++s)b[s]=0;t.copy(b,s,l+Math.max(-p,0),l+c),s=n;for(var C=s;s<C+m;++s)b[s]=0;return t.copy(b,s,f+Math.max(-m,0),f+d),b=b.toString("base64"),b=jk(b),b}function jg(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Wi;return o&&--r,r}function $k(t,e){t=Hg(t);var n=Ug(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=jg(t,0,n),s=jg(t,n,t.length),a=n-o,c=n-s,l=2+a+1+1+c,d=l<Wi,f=zi.allocUnsafe((d?2:3)+l),p=0;return f[p++]=qg,d?f[p++]=l:(f[p++]=Wi|1,f[p++]=l&255),f[p++]=Gi,f[p++]=a,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=Gi,f[p++]=c,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}zg.exports={derToJose:Uk,joseToDer:$k}});var Wt=X(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.LRUCache=void 0;Sn.snakeToCamel=Gg;Sn.originalOrCamelOptions=Wk;Sn.removeUndefinedValuesInObject=Gk;Sn.isValidFile=Jk;Sn.getWellKnownCertificateConfigFileLocation=Vk;var qk=oe("fs"),Hk=oe("os"),ol=oe("path"),zk="certificate_config.json",Wg="gcloud";function Gg(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Wk(t){function e(n){let r=t||{};return r[n]??r[Gg(n)]}return{get:e}}var sl=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};Sn.LRUCache=sl;function Gk(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Jk(t){try{return(await qk.promises.lstat(t)).isFile()}catch{return!1}}function Vk(){let t=process.env.CLOUDSDK_CONFIG||(Kk()?ol.join(process.env.APPDATA||"",Wg):ol.join(process.env.HOME||"",".config",Wg));return ol.join(t,zk)}function Kk(){return Hk.platform().startsWith("win")}});var Jg=X((XO,Yk)=>{Yk.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 il=X(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.USER_AGENT=Vn.PRODUCT_NAME=Vn.pkg=void 0;var Vg=Jg();Vn.pkg=Vg;var Kg="google-api-nodejs-client";Vn.PRODUCT_NAME=Kg;var Qk=`${Kg}/${Vg.version}`;Vn.USER_AGENT=Qk});var _t=X(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AuthClient=Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Gt.DEFAULT_UNIVERSE=void 0;var Xk=oe("events"),al=Xe(),Zk=Wt(),eA=Gc(),ul=il();Gt.DEFAULT_UNIVERSE="googleapis.com";Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var cl=class t extends Xk.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 n=(0,Zk.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??Gt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new al.Gaxios(e.transporterOptions),n.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 n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&al.Gaxios.mergeHeaders(s,n.headers),r&&al.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,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,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,eA.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${ul.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${ul.USER_AGENT}`):e.headers.set("User-Agent",ul.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[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 n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Gt.AuthClient=cl});var dl=X(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.LoginTicket=void 0;var ll=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}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()}}};Ji.LoginTicket=ll});var _r=X(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.OAuth2Client=nn.ClientAuthentication=nn.CertificateFormat=nn.CodeChallengeMethod=void 0;var Yg=Xe(),tA=oe("querystring"),nA=oe("stream"),rA=rl(),Qg=Wt(),fl=Vo(),no=_t(),oA=dl(),Xg;(function(t){t.Plain="plain",t.S256="S256"})(Xg||(nn.CodeChallengeMethod=Xg={}));var Tn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Tn||(nn.CertificateFormat=Tn={}));var Ko;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Ko||(nn.ClientAuthentication=Ko={}));var hl=class t extends no.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Tn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),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||Ko.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()+"?"+tA.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,fl.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=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===Ko.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Ko.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Qg.removeUndefinedValuesInObject)(o)),headers:r};no.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 n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={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:n,data:new URLSearchParams((0,Qg.removeUndefinedValuesInObject)(r))};no.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof Yg.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(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let c=new Headers({authorization:n.token_type+" "+n.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 r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.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:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(no.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),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,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=Yg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.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 nA.Readable,d=s===401||s===403;if(!n&&d&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!l&&c){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=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()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,fl.hasBrowserCrypto)()?Tn.JWK:Tn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Tn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Tn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};no.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let s=r?.headers.get("cache-control"),a=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let c={};switch(n){case Tn.PEM:c=r.data;break;case Tn.JWK:for(let d of r.data.keys)c[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=n,{certs:c,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};no.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,fl.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],d=c[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token envelope: ${c[0]}': ${w.message}`),w}if(!f)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token payload '${c[0]}`),w}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let m=n[f.kid];if(f.alg==="ES256"&&(d=rA.joseToDer(d,"ES256").toString("base64")),!await a.verify(m,l,d))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 C=Number(p.iat);if(isNaN(C))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 y=C-t.CLOCK_SKEW_SECS_,k=_+t.CLOCK_SKEW_SECS_;if(g<y)throw new Error("Token used too early, "+g+" < "+y+": "+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 r<"u"&&r!==null){let w=p.aud,S=!1;if(r.constructor===Array?S=r.indexOf(w)>-1:S=w===r,!S)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new oA.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};nn.OAuth2Client=hl});var ml=X(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.Compute=void 0;var sA=Xe(),Zg=Jo(),iA=_r(),pl=class extends iA.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`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await Zg.instance(o)}catch(o){throw o instanceof sA.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await Zg.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.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:n.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))}};Vi.Compute=pl});var yl=X(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.IdTokenClient=void 0;var aA=_r(),gl=class extends aA.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 n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Ki.IdTokenClient=gl});var _l=X(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.GCPEnv=void 0;ro.clear=uA;ro.getEnv=cA;var ey=Jo(),rn;(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"})(rn||(ro.GCPEnv=rn={}));var Yo;function uA(){Yo=void 0}async function cA(){return Yo||(Yo=lA(),Yo)}async function lA(){let t=rn.NONE;return dA()?t=rn.APP_ENGINE:fA()?t=rn.CLOUD_FUNCTIONS:await gA()?await mA()?t=rn.KUBERNETES_ENGINE:hA()?t=rn.CLOUD_RUN:pA()?t=rn.CLOUD_RUN_JOBS:t=rn.COMPUTE_ENGINE:t=rn.NONE,t}function dA(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function fA(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function hA(){return!!process.env.K_CONFIGURATION}function pA(){return!!process.env.CLOUD_RUN_JOB}async function mA(){try{return await ey.instance("attributes/cluster-name"),!0}catch{return!1}}async function gA(){return ey.isAvailable()}});var bl=X((iP,ty)=>{var Yi=to().Buffer,yA=oe("stream"),_A=oe("util");function Qi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Yi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Yi.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+")")}_A.inherits(Qi,yA);Qi.prototype.write=function(e){this.buffer=Yi.concat([this.buffer,Yi.from(e)]),this.emit("data",e)};Qi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};ty.exports=Qi});var ry=X((aP,ny)=>{"use strict";var Qo=oe("buffer").Buffer,Cl=oe("buffer").SlowBuffer;ny.exports=Xi;function Xi(t,e){if(!Qo.isBuffer(t)||!Qo.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Xi.install=function(){Qo.prototype.equal=Cl.prototype.equal=function(e){return Xi(this,e)}};var bA=Qo.prototype.equal,CA=Cl.prototype.equal;Xi.restore=function(){Qo.prototype.equal=bA,Cl.prototype.equal=CA}});var Al=X((uP,fy)=>{var so=to().Buffer,xt=oe("crypto"),sy=rl(),oy=oe("util"),wA=`"%s" is not a valid algorithm.
|
|
49
|
+
`+_+"}":"{"+y.join(",")+"}",r=_,b}}typeof ag.stringify!="function"&&(ag.stringify=function(d,f,p){var m;if(r="",o="",typeof p=="number")for(m=0;m<p;m+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return l("",{"":d})})})()});var dg=X((qO,lg)=>{var Ni=null,JE=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,VE=/(?: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)/,KE=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 n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
50
|
+
`,r:"\r",t:" "},s,a=function(_){throw{name:"SyntaxError",message:_,at:n,text:s}},c=function(_){return _&&_!==r&&a("Expected '"+_+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var _,y="";for(r==="-"&&(y="-",c("-"));r>="0"&&r<="9";)y+=r,c();if(r===".")for(y+=".";c()&&r>="0"&&r<="9";)y+=r;if(r==="e"||r==="E")for(y+=r,c(),(r==="-"||r==="+")&&(y+=r,c());r>="0"&&r<="9";)y+=r,c();if(_=+y,!isFinite(_))a("Bad number");else return Ni==null&&(Ni=jc()),y.length>15?e.storeAsString?y:e.useNativeBigInt?BigInt(y):new Ni(y):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new Ni(_):_},d=function(){var _,y,g="",S;if(r==='"')for(var w=n;c();){if(r==='"')return n-1>w&&(g+=s.substring(w,n-1)),c(),g;if(r==="\\"){if(n-1>w&&(g+=s.substring(w,n-1)),c(),r==="u"){for(S=0,y=0;y<4&&(_=parseInt(c(),16),!!isFinite(_));y+=1)S=S*16+_;g+=String.fromCharCode(S)}else if(typeof o[r]=="string")g+=o[r];else break;w=n}}a("Bad string")},f=function(){for(;r&&r<=" ";)c()},p=function(){switch(r){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 '"+r+"'")},m,b=function(){var _=[];if(r==="["){if(c("["),f(),r==="]")return c("]"),_;for(;r;){if(_.push(m()),f(),r==="]")return c("]"),_;c(","),f()}}a("Bad array")},C=function(){var _,y=Object.create(null);if(r==="{"){if(c("{"),f(),r==="}")return c("}"),y;for(;r;){if(_=d(),f(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(y,_)&&a('Duplicate key "'+_+'"'),JE.test(_)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():y[_]=m():VE.test(_)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():y[_]=m():y[_]=m(),f(),r==="}")return c("}"),y;c(","),f()}}a("Bad object")};return m=function(){switch(f(),r){case"{":return C();case"[":return b();case'"':return d();case"-":return l();default:return r>="0"&&r<="9"?l():p()}},function(_,y){var g;return s=_+"",n=0,r=" ",g=m(),f(),r&&a("Syntax error"),typeof y=="function"?(function S(w,A){var v,R,$=w[A];return $&&typeof $=="object"&&Object.keys($).forEach(function(V){R=S($,V),R!==void 0?$[V]=R:delete $[V]}),y.call(w,A,$)})({"":g},""):g}};lg.exports=KE});var pg=X((zO,Mi)=>{var fg=cg().stringify,hg=dg();Mi.exports=function(t){return{parse:hg(t),stringify:fg}};Mi.exports.parse=hg();Mi.exports.stringify=fg});var Uc=X(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.GCE_LINUX_BIOS_PATHS=void 0;zt.isGoogleCloudServerless=yg;zt.isGoogleComputeEngineLinux=_g;zt.isGoogleComputeEngineMACAddress=bg;zt.isGoogleComputeEngine=Cg;zt.detectGCPResidency=YE;var mg=re("fs"),gg=re("os");zt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var QE=/^42:01/;function yg(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function _g(){if((0,gg.platform)()!=="linux")return!1;try{(0,mg.statSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,mg.readFileSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function bg(){let t=(0,gg.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(QE.test(n))return!0}return!1}function Cg(){return _g()||bg()}function YE(){return yg()||Cg()}});var wg=X(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.Colours=void 0;var tt=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=tt;tt.enabled=!1;tt.reset="";tt.bright="";tt.dim="";tt.red="";tt.green="";tt.yellow="";tt.blue="";tt.magenta="";tt.cyan="";tt.white="";tt.grey="";tt.refresh()});var Sg=X(Re=>{"use strict";var XE=Re&&Re.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ZE=Re&&Re.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Eg=Re&&Re.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&XE(n,e,r[o]);return ZE(n,e),n}})();Object.defineProperty(Re,"__esModule",{value:!0});Re.env=Re.DebugLogBackendBase=Re.placeholder=Re.AdhocDebugLogger=Re.LogSeverity=void 0;Re.getNodeBackend=qc;Re.getDebugBackend=tk;Re.getStructuredBackend=nk;Re.setBackend=rk;Re.log=Ag;var ek=re("events"),zo=Eg(re("process")),kg=Eg(re("util")),gt=wg(),Ht;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Ht||(Re.LogSeverity=Ht={}));var Ho=class extends ek.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(Ht.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Ht.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Ht.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Ht.ERROR,...r),this.func.sublog=r=>Ag(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Re.AdhocDebugLogger=Ho;Re.placeholder=new Ho("",()=>{}).func;var Yr=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=zo.env[Re.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){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(n,...r)}catch(o){console.error(o)}}};Re.DebugLogBackendBase=Yr;var $c=class extends Yr{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${gt.Colours.green}${e}${gt.Colours.reset}`,a=`${gt.Colours.yellow}${zo.pid}${gt.Colours.reset}`,c;switch(n.severity){case Ht.ERROR:c=`${gt.Colours.red}${n.severity}${gt.Colours.reset}`;break;case Ht.INFO:c=`${gt.Colours.magenta}${n.severity}${gt.Colours.reset}`;break;case Ht.WARNING:c=`${gt.Colours.yellow}${n.severity}${gt.Colours.reset}`;break;default:c=(o=n.severity)!==null&&o!==void 0?o:Ht.DEFAULT;break}let l=kg.formatWithOptions({colors:gt.Colours.enabled},...r),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${gt.Colours.grey}${f}${gt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function qc(){return new $c}var zc=class extends Yr{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=zo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";zo.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function tk(t){return new zc(t)}var Hc=class extends Yr{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.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:kg.format(...s)},o),d=JSON.stringify(l);r?r(o,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function nk(t){return new Hc(t)}Re.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Wc=new Map,yt;function rk(t){yt=t,Wc.clear()}function Ag(t,e){if(!yt&&!zo.env[Re.env.nodeEnables]||!t)return Re.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Wc.get(t);if(n)return n.func;if(yt===null)return Re.placeholder;yt===void 0&&(yt=qc());let r=(()=>{let o;return new Ho(t,(a,...c)=>{if(o!==yt){if(yt===null)return;yt===void 0&&(yt=qc()),o=yt}yt?.log(t,a,...c)})})();return Wc.set(t,r),r.func}});var Gc=X(mr=>{"use strict";var ok=mr&&mr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sk=mr&&mr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ok(e,t,n)};Object.defineProperty(mr,"__esModule",{value:!0});sk(Sg(),mr)});var Go=X(he=>{"use strict";var vg=he&&he.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ik=he&&he.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ak=he&&he.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&vg(n,e,r[o]);return ik(n,e),n}})(),uk=he&&he.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vg(e,t,n)};Object.defineProperty(he,"__esModule",{value:!0});he.gcpResidencyCache=he.METADATA_SERVER_DETECTION=he.HEADERS=he.HEADER_VALUE=he.HEADER_NAME=he.SECONDARY_HOST_ADDRESS=he.HOST_ADDRESS=he.BASE_PATH=void 0;he.instance=pk;he.project=mk;he.universe=gk;he.bulk=yk;he.isAvailable=bk;he.resetIsAvailableCache=Ck;he.getGCPResidency=Kc;he.setGCPResidency=Dg;he.requestTimeout=Rg;var Jc=Xe(),ck=pg(),lk=Uc(),dk=ak(Gc());he.BASE_PATH="/computeMetadata/v1";he.HOST_ADDRESS="http://169.254.169.254";he.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";he.HEADER_NAME="Metadata-Flavor";he.HEADER_VALUE="Google";he.HEADERS=Object.freeze({[he.HEADER_NAME]:he.HEADER_VALUE});var Tg=dk.log("gcp-metadata");he.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 Vc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||he.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(he.BASE_PATH,t).href}function fk(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={},n=3,r=!1){let o=new Headers(he.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((m,b)=>o.set(b,m)),s=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(fk(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,m)=>o.set(m,p)),a=e.params||a);let c=r?hk:Jc.request,l={url:`${Vc()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:Rg()};Tg.info("instance request %j",l);let d=await c(l);Tg.info("instance metadata is %s",d.data);let f=d.headers.get(he.HEADER_NAME);if(f!==he.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${he.HEADER_NAME} header. Expected '${he.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return ck.parse(d.data)}catch{}return d.data}async function hk(t){let e={...t,url:t.url?.toString().replace(Vc(),Vc(he.SECONDARY_HOST_ADDRESS))},n=(0,Jc.request)(t),r=(0,Jc.request)(e);return Promise.any([n,r])}function pk(t){return Wo("instance",t)}function mk(t){return Wo("project",t)}function gk(t){return Wo("universe",t)}async function yk(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await Wo(n),o=n.metadataKey;e[o]=r})())),e}function _k(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var ji;async function bk(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in he.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(he.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Kc();case"ping-only":}}try{return ji===void 0&&(ji=Wo("instance",void 0,_k(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await ji,!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 n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function Ck(){ji=void 0}he.gcpResidencyCache=null;function Kc(){return he.gcpResidencyCache===null&&Dg(),he.gcpResidencyCache}function Dg(t=null){he.gcpResidencyCache=t!==null?t:(0,lk.detectGCPResidency)()}function Rg(){return Kc()?0:3e3}uk(Uc(),he)});var Pg=X(Ui=>{"use strict";Ui.byteLength=Ek;Ui.toByteArray=Ak;Ui.fromByteArray=vk;var en=[],Rt=[],wk=typeof Uint8Array<"u"?Uint8Array:Array,Qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(gr=0,xg=Qc.length;gr<xg;++gr)en[gr]=Qc[gr],Rt[Qc.charCodeAt(gr)]=gr;var gr,xg;Rt[45]=62;Rt[95]=63;function Og(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Ek(t){var e=Og(t),n=e[0],r=e[1];return(n+r)*3/4-r}function kk(t,e,n){return(e+n)*3/4-n}function Ak(t){var e,n=Og(t),r=n[0],o=n[1],s=new wk(kk(t,r,o)),a=0,c=o>0?r-4:r,l;for(l=0;l<c;l+=4)e=Rt[t.charCodeAt(l)]<<18|Rt[t.charCodeAt(l+1)]<<12|Rt[t.charCodeAt(l+2)]<<6|Rt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Rt[t.charCodeAt(l)]<<2|Rt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Rt[t.charCodeAt(l)]<<10|Rt[t.charCodeAt(l+1)]<<4|Rt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function Sk(t){return en[t>>18&63]+en[t>>12&63]+en[t>>6&63]+en[t&63]}function Tk(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(Sk(r));return o.join("")}function vk(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,c=n-r;a<c;a+=s)o.push(Tk(t,a,a+s>c?c:a+s));return r===1?(e=t[n-1],o.push(en[e>>2]+en[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(en[e>>10]+en[e>>4&63]+en[e<<2&63]+"=")),o.join("")}});var Xc=X(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.fromArrayBufferToHex=Dk;function Dk(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Fg=X($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.BrowserCrypto=void 0;var Xr=Pg(),Rk=Xc(),Zc=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 n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return Xr.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Xr.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=Xr.toByteArray(t.padBase64(r)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return Xr.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=Xr.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Xr.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,Rk.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};$i.BrowserCrypto=Zc});var Ig=X(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.NodeCrypto=void 0;var Zr=re("crypto"),el=class{async sha256DigestBase64(e){return Zr.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Zr.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Zr.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Zr.createSign("RSA-SHA256");return r.update(n),r.end(),r.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 Zr.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:Ok(e);return xk(Zr.createHmac("sha256",r).update(n).digest())}};qi.NodeCrypto=el;function xk(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Ok(t){return Buffer.from(t)}});var Jo=X(Sn=>{"use strict";var Pk=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Fk=Sn&&Sn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Pk(e,t,n)};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.createCrypto=Nk;Sn.hasBrowserCrypto=Bg;var Ik=Fg(),Bk=Ig();Fk(Xc(),Sn);function Nk(){return Bg()?new Ik.BrowserCrypto:new Bk.NodeCrypto}function Bg(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var eo=X((tl,Mg)=>{var zi=re("buffer"),tn=zi.Buffer;function Ng(t,e){for(var n in t)e[n]=t[n]}tn.from&&tn.alloc&&tn.allocUnsafe&&tn.allocUnsafeSlow?Mg.exports=zi:(Ng(zi,tl),tl.Buffer=yr);function yr(t,e,n){return tn(t,e,n)}yr.prototype=Object.create(tn.prototype);Ng(tn,yr);yr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return tn(t,e,n)};yr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=tn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};yr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return tn(t)};yr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return zi.SlowBuffer(t)}});var jg=X((eP,Lg)=>{"use strict";function nl(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Mk={ES256:nl(256),ES384:nl(384),ES512:nl(521)};function Lk(t){var e=Mk[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Lg.exports=Lk});var rl=X((tP,Wg)=>{"use strict";var Hi=eo().Buffer,$g=jg(),Wi=128,qg=0,jk=32,Uk=16,$k=2,zg=Uk|jk|qg<<6,Gi=$k|qg<<6;function qk(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Hg(t){if(Hi.isBuffer(t))return t;if(typeof t=="string")return Hi.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function zk(t,e){t=Hg(t);var n=$g(e),r=n+1,o=t.length,s=0;if(t[s++]!==zg)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(Wi|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==Gi)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(r<c)throw new Error('"r" specified length of "'+c+'", max of "'+r+'" is acceptable');var l=s;if(s+=c,t[s++]!==Gi)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-c,m=n-d,b=Hi.allocUnsafe(p+c+m+d);for(s=0;s<p;++s)b[s]=0;t.copy(b,s,l+Math.max(-p,0),l+c),s=n;for(var C=s;s<C+m;++s)b[s]=0;return t.copy(b,s,f+Math.max(-m,0),f+d),b=b.toString("base64"),b=qk(b),b}function Ug(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Wi;return o&&--r,r}function Hk(t,e){t=Hg(t);var n=$g(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=Ug(t,0,n),s=Ug(t,n,t.length),a=n-o,c=n-s,l=2+a+1+1+c,d=l<Wi,f=Hi.allocUnsafe((d?2:3)+l),p=0;return f[p++]=zg,d?f[p++]=l:(f[p++]=Wi|1,f[p++]=l&255),f[p++]=Gi,f[p++]=a,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=Gi,f[p++]=c,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}Wg.exports={derToJose:zk,joseToDer:Hk}});var Wt=X(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.LRUCache=void 0;Tn.snakeToCamel=Jg;Tn.originalOrCamelOptions=Vk;Tn.removeUndefinedValuesInObject=Kk;Tn.isValidFile=Qk;Tn.getWellKnownCertificateConfigFileLocation=Yk;var Wk=re("fs"),Gk=re("os"),ol=re("path"),Jk="certificate_config.json",Gg="gcloud";function Jg(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Vk(t){function e(n){let r=t||{};return r[n]??r[Jg(n)]}return{get:e}}var sl=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};Tn.LRUCache=sl;function Kk(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Qk(t){try{return(await Wk.promises.lstat(t)).isFile()}catch{return!1}}function Yk(){let t=process.env.CLOUDSDK_CONFIG||(Xk()?ol.join(process.env.APPDATA||"",Gg):ol.join(process.env.HOME||"",".config",Gg));return ol.join(t,Jk)}function Xk(){return Gk.platform().startsWith("win")}});var Vg=X((rP,Zk)=>{Zk.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 il=X(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.USER_AGENT=Vn.PRODUCT_NAME=Vn.pkg=void 0;var Kg=Vg();Vn.pkg=Kg;var Qg="google-api-nodejs-client";Vn.PRODUCT_NAME=Qg;var eA=`${Qg}/${Kg.version}`;Vn.USER_AGENT=eA});var _t=X(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AuthClient=Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Gt.DEFAULT_UNIVERSE=void 0;var tA=re("events"),al=Xe(),nA=Wt(),rA=Gc(),ul=il();Gt.DEFAULT_UNIVERSE="googleapis.com";Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var cl=class t extends tA.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 n=(0,nA.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??Gt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new al.Gaxios(e.transporterOptions),n.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 n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&al.Gaxios.mergeHeaders(s,n.headers),r&&al.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,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,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,rA.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${ul.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${ul.USER_AGENT}`):e.headers.set("User-Agent",ul.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[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 n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Gt.AuthClient=cl});var dl=X(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.LoginTicket=void 0;var ll=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}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()}}};Ji.LoginTicket=ll});var _r=X(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.OAuth2Client=nn.ClientAuthentication=nn.CertificateFormat=nn.CodeChallengeMethod=void 0;var Yg=Xe(),oA=re("querystring"),sA=re("stream"),iA=rl(),Xg=Wt(),fl=Jo(),to=_t(),aA=dl(),Zg;(function(t){t.Plain="plain",t.S256="S256"})(Zg||(nn.CodeChallengeMethod=Zg={}));var vn;(function(t){t.PEM="PEM",t.JWK="JWK"})(vn||(nn.CertificateFormat=vn={}));var Vo;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Vo||(nn.ClientAuthentication=Vo={}));var hl=class t extends to.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=vn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),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()+"?"+oA.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,fl.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=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}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Vo.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Xg.removeUndefinedValuesInObject)(o)),headers:r};to.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 n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={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:n,data:new URLSearchParams((0,Xg.removeUndefinedValuesInObject)(r))};to.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof Yg.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(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let c=new Headers({authorization:n.token_type+" "+n.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 r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.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:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(to.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),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,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=Yg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.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 sA.Readable,d=s===401||s===403;if(!n&&d&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!l&&c){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=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()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,fl.hasBrowserCrypto)()?vn.JWK:vn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case vn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case vn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};to.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let s=r?.headers.get("cache-control"),a=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let c={};switch(n){case vn.PEM:c=r.data;break;case vn.JWK:for(let d of r.data.keys)c[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=n,{certs:c,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};to.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,fl.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],d=c[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token envelope: ${c[0]}': ${w.message}`),w}if(!f)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token payload '${c[0]}`),w}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let m=n[f.kid];if(f.alg==="ES256"&&(d=iA.joseToDer(d,"ES256").toString("base64")),!await a.verify(m,l,d))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 C=Number(p.iat);if(isNaN(C))throw new Error("iat field using invalid format");let _=Number(p.exp);if(isNaN(_))throw new Error("exp field using invalid format");let y=new Date().getTime()/1e3;if(_>=y+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let g=C-t.CLOCK_SKEW_SECS_,S=_+t.CLOCK_SKEW_SECS_;if(y<g)throw new Error("Token used too early, "+y+" < "+g+": "+JSON.stringify(p));if(y>S)throw new Error("Token used too late, "+y+" > "+S+": "+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 r<"u"&&r!==null){let w=p.aud,A=!1;if(r.constructor===Array?A=r.indexOf(w)>-1:A=w===r,!A)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new aA.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};nn.OAuth2Client=hl});var ml=X(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.Compute=void 0;var uA=Xe(),ey=Go(),cA=_r(),pl=class extends cA.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`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await ey.instance(o)}catch(o){throw o instanceof uA.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await ey.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.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:n.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))}};Vi.Compute=pl});var yl=X(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.IdTokenClient=void 0;var lA=_r(),gl=class extends lA.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 n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Ki.IdTokenClient=gl});var _l=X(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.GCPEnv=void 0;no.clear=dA;no.getEnv=fA;var ty=Go(),rn;(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"})(rn||(no.GCPEnv=rn={}));var Ko;function dA(){Ko=void 0}async function fA(){return Ko||(Ko=hA(),Ko)}async function hA(){let t=rn.NONE;return pA()?t=rn.APP_ENGINE:mA()?t=rn.CLOUD_FUNCTIONS:await bA()?await _A()?t=rn.KUBERNETES_ENGINE:gA()?t=rn.CLOUD_RUN:yA()?t=rn.CLOUD_RUN_JOBS:t=rn.COMPUTE_ENGINE:t=rn.NONE,t}function pA(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function mA(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function gA(){return!!process.env.K_CONFIGURATION}function yA(){return!!process.env.CLOUD_RUN_JOB}async function _A(){try{return await ty.instance("attributes/cluster-name"),!0}catch{return!1}}async function bA(){return ty.isAvailable()}});var bl=X((dP,ny)=>{var Qi=eo().Buffer,CA=re("stream"),wA=re("util");function Yi(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+")")}wA.inherits(Yi,CA);Yi.prototype.write=function(e){this.buffer=Qi.concat([this.buffer,Qi.from(e)]),this.emit("data",e)};Yi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};ny.exports=Yi});var oy=X((fP,ry)=>{"use strict";var Qo=re("buffer").Buffer,Cl=re("buffer").SlowBuffer;ry.exports=Xi;function Xi(t,e){if(!Qo.isBuffer(t)||!Qo.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Xi.install=function(){Qo.prototype.equal=Cl.prototype.equal=function(e){return Xi(this,e)}};var EA=Qo.prototype.equal,kA=Cl.prototype.equal;Xi.restore=function(){Qo.prototype.equal=EA,Cl.prototype.equal=kA}});var Al=X((hP,hy)=>{var oo=eo().Buffer,xt=re("crypto"),iy=rl(),sy=re("util"),AA=`"%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".`,Xo="secret must be a string or buffer",oo="key must be a string or a buffer",EA="key must be a string, a buffer or an object",El=typeof xt.createPublicKey=="function";El&&(oo+=" or a KeyObject",Xo+="or a KeyObject");function iy(t){if(!so.isBuffer(t)&&typeof t!="string"&&(!El||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Jt(oo)}function ay(t){if(!so.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Jt(EA)}function kA(t){if(!so.isBuffer(t)){if(typeof t=="string")return t;if(!El||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Jt(Xo)}}function kl(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function uy(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Jt(t){var e=[].slice.call(arguments,1),n=oy.format.bind(oy,t).apply(null,e);return new TypeError(n)}function AA(t){return so.isBuffer(t)||typeof t=="string"}function Zo(t){return AA(t)||(t=JSON.stringify(t)),t}function cy(t){return function(n,r){kA(r),n=Zo(n);var o=xt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return kl(s)}}var wl,SA="timingSafeEqual"in xt?function(e,n){return e.byteLength!==n.byteLength?!1:xt.timingSafeEqual(e,n)}:function(e,n){return wl||(wl=ry()),wl(e,n)};function TA(t){return function(n,r,o){var s=cy(t)(n,o);return SA(so.from(r),so.from(s))}}function ly(t){return function(n,r){ay(r),n=Zo(n);var o=xt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return kl(s)}}function dy(t){return function(n,r,o){iy(o),n=Zo(n),r=uy(r);var s=xt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function vA(t){return function(n,r){ay(r),n=Zo(n);var o=xt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:xt.constants.RSA_PKCS1_PSS_PADDING,saltLength:xt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return kl(s)}}function DA(t){return function(n,r,o){iy(o),n=Zo(n),r=uy(r);var s=xt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:xt.constants.RSA_PKCS1_PSS_PADDING,saltLength:xt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function RA(t){var e=ly(t);return function(){var r=e.apply(null,arguments);return r=sy.derToJose(r,"ES"+t),r}}function xA(t){var e=dy(t);return function(r,o,s){o=sy.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function OA(){return function(){return""}}function PA(){return function(e,n){return n===""}}fy.exports=function(e){var n={hs:cy,rs:ly,ps:vA,es:RA,none:OA},r={hs:TA,rs:dy,ps:DA,es:xA,none:PA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Jt(wA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Sl=X((cP,hy)=>{var FA=oe("buffer").Buffer;hy.exports=function(e){return typeof e=="string"?e:typeof e=="number"||FA.isBuffer(e)?e.toString():JSON.stringify(e)}});var by=X((lP,_y)=>{var IA=to().Buffer,py=bl(),NA=Al(),BA=oe("stream"),my=Sl(),Tl=oe("util");function gy(t,e){return IA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function MA(t,e,n){n=n||"utf8";var r=gy(my(t),"binary"),o=gy(my(e),n);return Tl.format("%s.%s",r,o)}function yy(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=NA(e.alg),a=MA(e,n,o),c=s.sign(a,r);return Tl.format("%s.%s",a,c)}function Zi(t){var e=t.secret||t.privateKey||t.key,n=new py(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new py(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))}Tl.inherits(Zi,BA);Zi.prototype.sign=function(){try{var e=yy({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(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Zi.sign=yy;_y.exports=Zi});var Ry=X((dP,Dy)=>{var wy=to().Buffer,Cy=bl(),LA=Al(),jA=oe("stream"),Ey=Sl(),UA=oe("util"),$A=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function qA(t){return Object.prototype.toString.call(t)==="[object Object]"}function HA(t){if(qA(t))return t;try{return JSON.parse(t)}catch{return}}function ky(t){var e=t.split(".",1)[0];return HA(wy.from(e,"base64").toString("binary"))}function zA(t){return t.split(".",2).join(".")}function Ay(t){return t.split(".")[2]}function WA(t,e){e=e||"utf8";var n=t.split(".")[1];return wy.from(n,"base64").toString(e)}function Sy(t){return $A.test(t)&&!!ky(t)}function Ty(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Ey(t);var o=Ay(t),s=zA(t),a=LA(e);return a.verify(s,o,n)}function vy(t,e){if(e=e||{},t=Ey(t),!Sy(t))return null;var n=ky(t);if(!n)return null;var r=WA(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Ay(t)}}function io(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new Cy(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Cy(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))}UA.inherits(io,jA);io.prototype.verify=function(){try{var e=Ty(this.signature.buffer,this.algorithm,this.key.buffer),n=vy(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};io.decode=vy;io.isValid=Sy;io.verify=Ty;Dy.exports=io});var vl=X(Kn=>{var xy=by(),ea=Ry(),GA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Kn.ALGORITHMS=GA;Kn.sign=xy.sign;Kn.verify=ea.verify;Kn.decode=ea.decode;Kn.isValid=ea.isValid;Kn.createSign=function(e){return new xy(e)};Kn.createVerify=function(e){return new ea(e)}});var Wy=X(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.GoogleToken=void 0;var Oy=ta(oe("fs")),JA=Xe(),VA=ta(vl()),KA=ta(oe("path")),YA=oe("util");function ta(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(ta=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,d={__proto__:null,default:s};if(s===null||vn(s)!="object"&&typeof s!="function")return d;if(c=a?r:n){if(c.has(s))return c.get(s);c.set(s,d)}for(var f in s)f!=="default"&&{}.hasOwnProperty.call(s,f)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,f))&&(l.get||l.set)?c(d,f,l):d[f]=s[f]);return d})(t,e)}function vn(t){"@babel/helpers - typeof";return vn=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},vn(t)}function QA(t,e){Uy(t,e),e.add(t)}function XA(t,e,n){Uy(t,e),e.set(t,n)}function Uy(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Py(t,e,n){return t.set(Vt(t,e),n),n}function Fy(t,e){return t.get(Vt(t,e))}function Vt(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function Iy(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,Hy(r.key),r)}}function $y(t,e,n){return e&&Iy(t.prototype,e),n&&Iy(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function qy(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function ZA(t,e,n){return e=rs(e),eS(t,Fl()?Reflect.construct(e,n||[],rs(t).constructor):e.apply(t,n))}function eS(t,e){if(e&&(vn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return tS(t)}function tS(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function nS(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&&ns(t,e)}function Dl(t){var e=typeof Map=="function"?new Map:void 0;return Dl=function(r){if(r===null||!oS(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return rS(r,arguments,rs(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),ns(o,r)},Dl(t)}function rS(t,e,n){if(Fl())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&ns(o,n.prototype),o}function Fl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Fl=function(){return!!t})()}function oS(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function ns(t,e){return ns=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},ns(t,e)}function rs(t){return rs=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},rs(t)}function bt(t,e,n){return(e=Hy(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Hy(t){var e=sS(t,"string");return vn(e)=="symbol"?e:e+""}function sS(t,e){if(vn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(vn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wt(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(b,C,_,g){var y=C&&C.prototype instanceof c?C:c,k=Object.create(y.prototype);return Ct(k,"_invoke",(function(w,S,R){var v,$,Y,P=0,V=R||[],H=!1,Q={p:0,n:0,v:t,a:J,f:J.bind(t,4),d:function(ce,re){return v=ce,$=0,Y=t,Q.n=re,a}};function J(ee,ce){for($=ee,Y=ce,e=0;!H&&P&&!re&&e<V.length;e++){var re,me=V[e],z=Q.p,Z=me[2];ee>3?(re=Z===ce)&&(Y=me[($=me[4])?5:($=3,3)],me[4]=me[5]=t):me[0]<=z&&((re=ee<2&&z<me[1])?($=0,Q.v=ce,Q.n=me[1]):z<Z&&(re=ee<3||me[0]>ce||ce>Z)&&(me[4]=ee,me[5]=ce,Q.n=Z,$=0))}if(re||ee>1)return a;throw H=!0,ce}return function(ee,ce,re){if(P>1)throw TypeError("Generator is already running");for(H&&ce===1&&J(ce,re),$=ce,Y=re;(e=$<2?t:Y)||!H;){v||($?$<3?($>1&&(Q.n=-1),J($,Y)):Q.n=Y:Q.v=Y);try{if(P=2,v){if($||(ee="next"),e=v[ee]){if(!(e=e.call(v,Y)))throw TypeError("iterator result is not an object");if(!e.done)return e;Y=e.value,$<2&&($=0)}else $===1&&(e=v.return)&&e.call(v),$<2&&(Y=TypeError("The iterator does not provide a '"+ee+"' method"),$=1);v=t}else if((e=(H=Q.n<0)?Y:w.call(S,Q))!==a)break}catch(me){v=t,$=1,Y=me}finally{P=1}}return{value:e,done:H}}})(b,_,g),!0),k}var a={};function c(){}function l(){}function d(){}e=Object.getPrototypeOf;var f=[][r]?e(e([][r]())):(Ct(e={},r,function(){return this}),e),p=d.prototype=c.prototype=Object.create(f);function m(b){return Object.setPrototypeOf?Object.setPrototypeOf(b,d):(b.__proto__=d,Ct(b,o,"GeneratorFunction")),b.prototype=Object.create(p),b}return l.prototype=d,Ct(p,"constructor",d),Ct(d,"constructor",l),l.displayName="GeneratorFunction",Ct(d,o,"GeneratorFunction"),Ct(p),Ct(p,o,"Generator"),Ct(p,r,function(){return this}),Ct(p,"toString",function(){return"[object Generator]"}),(wt=function(){return{w:s,m}})()}function Ct(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}Ct=function(a,c,l,d){if(c)o?o(a,c,{value:l,enumerable:!d,configurable:!d,writable:!d}):a[c]=l;else{var f=function(m,b){Ct(a,m,function(C){return this._invoke(m,b,C)})};f("next",0),f("throw",1),f("return",2)}},Ct(t,e,n,r)}function Ny(t,e,n,r,o,s,a){try{var c=t[s](a),l=c.value}catch(d){return void n(d)}c.done?e(l):Promise.resolve(l).then(r,o)}function ao(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){Ny(s,r,o,a,c,"next",l)}function c(l){Ny(s,r,o,a,c,"throw",l)}a(void 0)})}}var By=Oy.readFile?(0,YA.promisify)(Oy.readFile):ao(wt().m(function t(){return wt().w(function(e){for(;;)switch(e.n){case 0:throw new ts("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),My="https://oauth2.googleapis.com/token",iS="https://oauth2.googleapis.com/revoke?token=",ts=(function(t){function e(n,r){var o;return qy(this,e),o=ZA(this,e,[n]),bt(o,"code",void 0),o.code=r,o}return nS(e,t),$y(e)})(Dl(Error)),es=new WeakMap,on=new WeakSet,hP=na.GoogleToken=(function(){function t(e){qy(this,t),QA(this,on),bt(this,"expiresAt",void 0),bt(this,"key",void 0),bt(this,"keyFile",void 0),bt(this,"iss",void 0),bt(this,"sub",void 0),bt(this,"scope",void 0),bt(this,"rawToken",void 0),bt(this,"tokenExpires",void 0),bt(this,"email",void 0),bt(this,"additionalClaims",void 0),bt(this,"eagerRefreshThresholdMillis",void 0),bt(this,"transporter",{request:function(r){return(0,JA.request)(r)}}),XA(this,es,void 0),Vt(on,this,zy).call(this,e)}return $y(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 n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(vn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;Vt(on,this,Ly).call(this,r).then(function(s){return o(null,s)},n);return}return Vt(on,this,Ly).call(this,r)}},{key:"getCredentials",value:(function(){var e=ao(wt().m(function r(o){var s,a,c,l,d,f,p;return wt().w(function(m){for(;;)switch(m.n){case 0:s=KA.extname(o),p=s,m.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return m.n=2,By(o,"utf8");case 2:if(a=m.v,c=JSON.parse(a),l=c.private_key,d=c.client_email,!(!l||!d)){m.n=3;break}throw new ts("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:d});case 4:return m.n=5,By(o,"utf8");case 5:return f=m.v,m.a(2,{privateKey:f});case 6:throw new ts("*.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 ts("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return m.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){Vt(on,this,jy).call(this).then(function(){return n()},n);return}return Vt(on,this,jy).call(this)}}])})();function Ly(t){return Rl.apply(this,arguments)}function Rl(){return Rl=ao(wt().m(function t(e){return wt().w(function(n){for(;;)switch(n.n){case 0:if(!(Fy(es,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,Fy(es,this));case 1:return n.p=1,n.n=2,Py(es,this,Vt(on,this,aS).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,Py(es,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),Rl.apply(this,arguments)}function aS(t){return xl.apply(this,arguments)}function xl(){return xl=ao(wt().m(function t(e){var n;return wt().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||Vt(on,this,uS).call(this);case 4:return r.a(2,Vt(on,this,cS).call(this))}},t,this)})),xl.apply(this,arguments)}function uS(){if(!this.iss)throw new ts("email is required.","MISSING_CREDENTIALS")}function jy(){return Ol.apply(this,arguments)}function Ol(){return Ol=ao(wt().m(function t(){var e;return wt().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=iS+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:Vt(on,this,zy).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),Ol.apply(this,arguments)}function zy(){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,vn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function cS(){return Pl.apply(this,arguments)}function Pl(){return Pl=ao(wt().m(function t(){var e,n,r,o,s,a,c,l,d,f;return wt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:My,exp:e+3600,iat:e,sub:this.sub},n),o=VA.sign({header:{alg:"RS256"},payload:r,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:My,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,f=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=f.response&&(a=f.response)!==null&&a!==void 0&&a.data?(c=f.response)===null||c===void 0?void 0:c.data:{},l.error&&(d=l.error_description?": ".concat(l.error_description):"",f.message="".concat(l.error).concat(d)),f;case 4:return p.a(2)}},t,this,[[1,3]])})),Pl.apply(this,arguments)}});var Nl=X(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.JWTAccess=void 0;var lS=vl(),dS=Wt(),Gy={alg:"RS256",typ:"JWT"},Il=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new dS.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),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),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:l,iat:c}:d={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},n){for(let C in d)if(n[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Gy,kid:this.keyId}:Gy,p=Object.assign(d,n),m=lS.sign({header:f,payload:p,secret:this.key}),b=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:b}),b}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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(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",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};ra.JWTAccess=Il});var Ml=X(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.JWT=void 0;var Jy=Wy(),fS=Nl(),hS=_r(),oa=_t(),Bl=class t extends hS.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 n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==oa.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==oa.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${oa.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new fS.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==oa.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Jy.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 n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.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(n=>e(null,n),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(),r={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",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new Jy.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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(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 n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};sa.JWT=Bl});var jl=X(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.UserRefreshClient=uo.USER_REFRESH_ACCOUNT_TYPE=void 0;var pS=_r(),mS=_t();uo.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Ll=class t extends pS.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,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 n={...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 mS.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};uo.UserRefreshClient=Ll});var $l=X(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.Impersonated=co.IMPERSONATED_ACCOUNT_TYPE=void 0;var Vy=_r(),gS=Xe(),yS=Wt();co.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Ul=class t extends Vy.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 Vy.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,yS.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 n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,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 n=0,r="";throw e instanceof gS.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};co.Impersonated=Ul});var Hl=X(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.OAuthClientAuthHandler=void 0;os.getErrorFromOAuthErrorResponse=CS;var lo=Xe(),_S=Vo(),bS=["PUT","POST","PATCH"],ql=class{#e=(0,_S.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new lo.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new lo.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=lo.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=lo.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=lo.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);lo.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!bS.includes(n))throw new Error(`${n} 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"]}}}};os.OAuthClientAuthHandler=ql;function CS(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),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 aa=X(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.StsCredentials=void 0;var wS=Xe(),ES=_t(),Ky=Hl(),kS=Wt(),zl=class t extends Ky.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){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:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,kS.removeUndefinedValuesInObject)(o))};ES.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 wS.GaxiosError&&a.response?(0,Ky.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};ia.StsCredentials=zl});var Yn=X(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.BaseExternalAccountClient=Ot.CLOUD_RESOURCE_MANAGER=Ot.EXTERNAL_ACCOUNT_TYPE=Ot.EXPIRATION_TIME_OFFSET=void 0;var AS=Xe(),SS=oe("stream"),Wl=_t(),TS=aa(),Yy=Wt(),vS=il(),DS="urn:ietf:params:oauth:grant-type:token-exchange",RS="urn:ietf:params:oauth:token-type:access_token",Gl="https://www.googleapis.com/auth/cloud-platform",xS=3600;Ot.EXPIRATION_TIME_OFFSET=300*1e3;Ot.EXTERNAL_ACCOUNT_TYPE="external_account";Ot.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var OS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",PS="https://sts.{universeDomain}/v1/token",Jl=class t extends Wl.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,Yy.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Ot.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Ot.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??PS.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),c=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,Yy.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new TS.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Gl],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(OS);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=xS),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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};Wl.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=AS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof SS.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:DS,audience:this.audience,requestedTokenType:RS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Gl]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);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 n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};Wl.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Gl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${vS.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Ot.BaseExternalAccountClient=Jl});var Qy=X(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.FileSubjectTokenSupplier=void 0;var Kl=oe("util"),Yl=oe("fs"),FS=(0,Kl.promisify)(Yl.readFile??(()=>{})),IS=(0,Kl.promisify)(Yl.realpath??(()=>{})),NS=(0,Kl.promisify)(Yl.lstat??(()=>{})),Vl=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 NS(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,r=await FS(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};ua.FileSubjectTokenSupplier=Vl});var Xy=X(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.UrlSubjectTokenSupplier=void 0;var BS=_t(),Ql=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 n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};BS.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};ca.UrlSubjectTokenSupplier=Ql});var Zy=X(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.CertificateSubjectTokenSupplier=Et.InvalidConfigurationError=Et.CertificateSourceUnavailableError=Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var la=Wt(),da=oe("fs"),fa=oe("crypto"),MS=oe("https");Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var sn=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Et.CertificateSourceUnavailableError=sn;var Pt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Et.InvalidConfigurationError=Pt;var Xl=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 MS.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,la.isValidFile)(e))return e;throw new sn(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,la.isValidFile)(n))return n;throw new sn(`Path from environment variable "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,la.getWellKnownCertificateConfigFileLocation)();if(await(0,la.isValidFile)(r))return r;throw new sn(`Could not find certificate configuration file. Searched override path, the "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await da.promises.readFile(e,"utf8")}catch{throw new sn(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.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(r){throw r instanceof Pt?r:new Pt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await da.promises.readFile(e),new fa.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sn(`Failed to read certificate file at ${e}: ${a}`)}try{o=await da.promises.readFile(n),(0,fa.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sn(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new fa.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await da.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,d)=>{try{return new fa.X509Certificate(l)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Pt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),c;if(a===-1)c=[n,...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(r){if(r instanceof Pt)throw r;let o=r instanceof Error?r.message:String(r);throw new sn(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Et.CertificateSubjectTokenSupplier=Xl});var td=X(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.IdentityPoolClient=void 0;var LS=Yn(),Zl=Wt(),jS=Qy(),US=Xy(),e0=Zy(),$S=aa(),t0=Xe(),ed=class t extends LS.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Zl.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&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,Zl.originalOrCamelOptions)(r),a=(0,Zl.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 d=s.get("file"),f=s.get("url"),p=s.get("certificate"),m=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new jS.FileSubjectTokenSupplier({filePath:d,formatType:c,subjectTokenFieldName:l});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new US.UrlSubjectTokenSupplier({url:f,formatType:c,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let b=new e0.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=b}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 e0.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new $S.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new t0.Gaxios({agent:n})}),this.transporter=new t0.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};ha.IdentityPoolClient=ed});var rd=X(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.AwsRequestSigner=void 0;var pa=Xe(),r0=Vo(),n0="AWS4-HMAC-SHA256",qS="aws4_request",nd=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,r0.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,c=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await zS({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}),f=pa.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:l.host},a||{});c.token&&pa.Gaxios.mergeHeaders(f,{"x-amz-security-token":c.token});let p={url:r,method:o,headers:f};return s!==void 0&&(p.body=s),p}};ma.AwsRequestSigner=nd;async function ss(t,e,n){return await t.signWithHmacSha256(e,n)}async function HS(t,e,n,r,o){let s=await ss(t,`AWS4${e}`,n),a=await ss(t,s,r),c=await ss(t,a,o);return await ss(t,c,"aws4_request")}async function zS(t){let e=pa.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=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=pa.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",d=[...c.keys()].sort();d.forEach(k=>{l+=`${k}:${c.get(k)}
|
|
52
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Yo="secret must be a string or buffer",ro="key must be a string or a buffer",SA="key must be a string, a buffer or an object",El=typeof xt.createPublicKey=="function";El&&(ro+=" or a KeyObject",Yo+="or a KeyObject");function ay(t){if(!oo.isBuffer(t)&&typeof t!="string"&&(!El||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Jt(ro)}function uy(t){if(!oo.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Jt(SA)}function TA(t){if(!oo.isBuffer(t)){if(typeof t=="string")return t;if(!El||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Jt(Yo)}}function kl(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cy(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Jt(t){var e=[].slice.call(arguments,1),n=sy.format.bind(sy,t).apply(null,e);return new TypeError(n)}function vA(t){return oo.isBuffer(t)||typeof t=="string"}function Xo(t){return vA(t)||(t=JSON.stringify(t)),t}function ly(t){return function(n,r){TA(r),n=Xo(n);var o=xt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return kl(s)}}var wl,DA="timingSafeEqual"in xt?function(e,n){return e.byteLength!==n.byteLength?!1:xt.timingSafeEqual(e,n)}:function(e,n){return wl||(wl=oy()),wl(e,n)};function RA(t){return function(n,r,o){var s=ly(t)(n,o);return DA(oo.from(r),oo.from(s))}}function dy(t){return function(n,r){uy(r),n=Xo(n);var o=xt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return kl(s)}}function fy(t){return function(n,r,o){ay(o),n=Xo(n),r=cy(r);var s=xt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function xA(t){return function(n,r){uy(r),n=Xo(n);var o=xt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:xt.constants.RSA_PKCS1_PSS_PADDING,saltLength:xt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return kl(s)}}function OA(t){return function(n,r,o){ay(o),n=Xo(n),r=cy(r);var s=xt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:xt.constants.RSA_PKCS1_PSS_PADDING,saltLength:xt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function PA(t){var e=dy(t);return function(){var r=e.apply(null,arguments);return r=iy.derToJose(r,"ES"+t),r}}function FA(t){var e=fy(t);return function(r,o,s){o=iy.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function IA(){return function(){return""}}function BA(){return function(e,n){return n===""}}hy.exports=function(e){var n={hs:ly,rs:dy,ps:xA,es:PA,none:IA},r={hs:RA,rs:fy,ps:OA,es:FA,none:BA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Jt(AA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Sl=X((pP,py)=>{var NA=re("buffer").Buffer;py.exports=function(e){return typeof e=="string"?e:typeof e=="number"||NA.isBuffer(e)?e.toString():JSON.stringify(e)}});var Cy=X((mP,by)=>{var MA=eo().Buffer,my=bl(),LA=Al(),jA=re("stream"),gy=Sl(),Tl=re("util");function yy(t,e){return MA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function UA(t,e,n){n=n||"utf8";var r=yy(gy(t),"binary"),o=yy(gy(e),n);return Tl.format("%s.%s",r,o)}function _y(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=LA(e.alg),a=UA(e,n,o),c=s.sign(a,r);return Tl.format("%s.%s",a,c)}function Zi(t){var e=t.secret||t.privateKey||t.key,n=new my(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new my(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))}Tl.inherits(Zi,jA);Zi.prototype.sign=function(){try{var e=_y({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(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Zi.sign=_y;by.exports=Zi});var xy=X((gP,Ry)=>{var Ey=eo().Buffer,wy=bl(),$A=Al(),qA=re("stream"),ky=Sl(),zA=re("util"),HA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function WA(t){return Object.prototype.toString.call(t)==="[object Object]"}function GA(t){if(WA(t))return t;try{return JSON.parse(t)}catch{return}}function Ay(t){var e=t.split(".",1)[0];return GA(Ey.from(e,"base64").toString("binary"))}function JA(t){return t.split(".",2).join(".")}function Sy(t){return t.split(".")[2]}function VA(t,e){e=e||"utf8";var n=t.split(".")[1];return Ey.from(n,"base64").toString(e)}function Ty(t){return HA.test(t)&&!!Ay(t)}function vy(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=ky(t);var o=Sy(t),s=JA(t),a=$A(e);return a.verify(s,o,n)}function Dy(t,e){if(e=e||{},t=ky(t),!Ty(t))return null;var n=Ay(t);if(!n)return null;var r=VA(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Sy(t)}}function so(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new wy(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new wy(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))}zA.inherits(so,qA);so.prototype.verify=function(){try{var e=vy(this.signature.buffer,this.algorithm,this.key.buffer),n=Dy(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};so.decode=Dy;so.isValid=Ty;so.verify=vy;Ry.exports=so});var vl=X(Kn=>{var Oy=Cy(),ea=xy(),KA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Kn.ALGORITHMS=KA;Kn.sign=Oy.sign;Kn.verify=ea.verify;Kn.decode=ea.decode;Kn.isValid=ea.isValid;Kn.createSign=function(e){return new Oy(e)};Kn.createVerify=function(e){return new ea(e)}});var Gy=X(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.GoogleToken=void 0;var Py=ta(re("fs")),QA=Xe(),YA=ta(vl()),XA=ta(re("path")),ZA=re("util");function ta(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(ta=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,d={__proto__:null,default:s};if(s===null||Dn(s)!="object"&&typeof s!="function")return d;if(c=a?r:n){if(c.has(s))return c.get(s);c.set(s,d)}for(var f in s)f!=="default"&&{}.hasOwnProperty.call(s,f)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,f))&&(l.get||l.set)?c(d,f,l):d[f]=s[f]);return d})(t,e)}function Dn(t){"@babel/helpers - typeof";return Dn=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},Dn(t)}function eS(t,e){$y(t,e),e.add(t)}function tS(t,e,n){$y(t,e),e.set(t,n)}function $y(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Fy(t,e,n){return t.set(Vt(t,e),n),n}function Iy(t,e){return t.get(Vt(t,e))}function Vt(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function By(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,Hy(r.key),r)}}function qy(t,e,n){return e&&By(t.prototype,e),n&&By(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function zy(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function nS(t,e,n){return e=ns(e),rS(t,Fl()?Reflect.construct(e,n||[],ns(t).constructor):e.apply(t,n))}function rS(t,e){if(e&&(Dn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oS(t)}function oS(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function sS(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 Dl(t){var e=typeof Map=="function"?new Map:void 0;return Dl=function(r){if(r===null||!aS(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return iS(r,arguments,ns(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),ts(o,r)},Dl(t)}function iS(t,e,n){if(Fl())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&ts(o,n.prototype),o}function Fl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Fl=function(){return!!t})()}function aS(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(n,r){return n.__proto__=r,n},ts(t,e)}function ns(t){return ns=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ns(t)}function bt(t,e,n){return(e=Hy(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Hy(t){var e=uS(t,"string");return Dn(e)=="symbol"?e:e+""}function uS(t,e){if(Dn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Dn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wt(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(b,C,_,y){var g=C&&C.prototype instanceof c?C:c,S=Object.create(g.prototype);return Ct(S,"_invoke",(function(w,A,v){var R,$,V,P=0,Q=v||[],z=!1,K={p:0,n:0,v:t,a:Y,f:Y.bind(t,4),d:function(ae,se){return R=ae,$=0,V=t,K.n=se,a}};function Y(ee,ae){for($=ee,V=ae,e=0;!z&&P&&!se&&e<Q.length;e++){var se,me=Q[e],G=K.p,Z=me[2];ee>3?(se=Z===ae)&&(V=me[($=me[4])?5:($=3,3)],me[4]=me[5]=t):me[0]<=G&&((se=ee<2&&G<me[1])?($=0,K.v=ae,K.n=me[1]):G<Z&&(se=ee<3||me[0]>ae||ae>Z)&&(me[4]=ee,me[5]=ae,K.n=Z,$=0))}if(se||ee>1)return a;throw z=!0,ae}return function(ee,ae,se){if(P>1)throw TypeError("Generator is already running");for(z&&ae===1&&Y(ae,se),$=ae,V=se;(e=$<2?t:V)||!z;){R||($?$<3?($>1&&(K.n=-1),Y($,V)):K.n=V:K.v=V);try{if(P=2,R){if($||(ee="next"),e=R[ee]){if(!(e=e.call(R,V)))throw TypeError("iterator result is not an object");if(!e.done)return e;V=e.value,$<2&&($=0)}else $===1&&(e=R.return)&&e.call(R),$<2&&(V=TypeError("The iterator does not provide a '"+ee+"' method"),$=1);R=t}else if((e=(z=K.n<0)?V:w.call(A,K))!==a)break}catch(me){R=t,$=1,V=me}finally{P=1}}return{value:e,done:z}}})(b,_,y),!0),S}var a={};function c(){}function l(){}function d(){}e=Object.getPrototypeOf;var f=[][r]?e(e([][r]())):(Ct(e={},r,function(){return this}),e),p=d.prototype=c.prototype=Object.create(f);function m(b){return Object.setPrototypeOf?Object.setPrototypeOf(b,d):(b.__proto__=d,Ct(b,o,"GeneratorFunction")),b.prototype=Object.create(p),b}return l.prototype=d,Ct(p,"constructor",d),Ct(d,"constructor",l),l.displayName="GeneratorFunction",Ct(d,o,"GeneratorFunction"),Ct(p),Ct(p,o,"Generator"),Ct(p,r,function(){return this}),Ct(p,"toString",function(){return"[object Generator]"}),(wt=function(){return{w:s,m}})()}function Ct(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}Ct=function(a,c,l,d){if(c)o?o(a,c,{value:l,enumerable:!d,configurable:!d,writable:!d}):a[c]=l;else{var f=function(m,b){Ct(a,m,function(C){return this._invoke(m,b,C)})};f("next",0),f("throw",1),f("return",2)}},Ct(t,e,n,r)}function Ny(t,e,n,r,o,s,a){try{var c=t[s](a),l=c.value}catch(d){return void n(d)}c.done?e(l):Promise.resolve(l).then(r,o)}function io(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){Ny(s,r,o,a,c,"next",l)}function c(l){Ny(s,r,o,a,c,"throw",l)}a(void 0)})}}var My=Py.readFile?(0,ZA.promisify)(Py.readFile):io(wt().m(function t(){return wt().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)})),Ly="https://oauth2.googleapis.com/token",cS="https://oauth2.googleapis.com/revoke?token=",es=(function(t){function e(n,r){var o;return zy(this,e),o=nS(this,e,[n]),bt(o,"code",void 0),o.code=r,o}return sS(e,t),qy(e)})(Dl(Error)),Zo=new WeakMap,on=new WeakSet,_P=na.GoogleToken=(function(){function t(e){zy(this,t),eS(this,on),bt(this,"expiresAt",void 0),bt(this,"key",void 0),bt(this,"keyFile",void 0),bt(this,"iss",void 0),bt(this,"sub",void 0),bt(this,"scope",void 0),bt(this,"rawToken",void 0),bt(this,"tokenExpires",void 0),bt(this,"email",void 0),bt(this,"additionalClaims",void 0),bt(this,"eagerRefreshThresholdMillis",void 0),bt(this,"transporter",{request:function(r){return(0,QA.request)(r)}}),tS(this,Zo,void 0),Vt(on,this,Wy).call(this,e)}return qy(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 n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Dn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;Vt(on,this,jy).call(this,r).then(function(s){return o(null,s)},n);return}return Vt(on,this,jy).call(this,r)}},{key:"getCredentials",value:(function(){var e=io(wt().m(function r(o){var s,a,c,l,d,f,p;return wt().w(function(m){for(;;)switch(m.n){case 0:s=XA.extname(o),p=s,m.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return m.n=2,My(o,"utf8");case 2:if(a=m.v,c=JSON.parse(a),l=c.private_key,d=c.client_email,!(!l||!d)){m.n=3;break}throw new es("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:d});case 4:return m.n=5,My(o,"utf8");case 5:return f=m.v,m.a(2,{privateKey:f});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 m.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){Vt(on,this,Uy).call(this).then(function(){return n()},n);return}return Vt(on,this,Uy).call(this)}}])})();function jy(t){return Rl.apply(this,arguments)}function Rl(){return Rl=io(wt().m(function t(e){return wt().w(function(n){for(;;)switch(n.n){case 0:if(!(Iy(Zo,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,Iy(Zo,this));case 1:return n.p=1,n.n=2,Fy(Zo,this,Vt(on,this,lS).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,Fy(Zo,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),Rl.apply(this,arguments)}function lS(t){return xl.apply(this,arguments)}function xl(){return xl=io(wt().m(function t(e){var n;return wt().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||Vt(on,this,dS).call(this);case 4:return r.a(2,Vt(on,this,fS).call(this))}},t,this)})),xl.apply(this,arguments)}function dS(){if(!this.iss)throw new es("email is required.","MISSING_CREDENTIALS")}function Uy(){return Ol.apply(this,arguments)}function Ol(){return Ol=io(wt().m(function t(){var e;return wt().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=cS+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:Vt(on,this,Wy).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),Ol.apply(this,arguments)}function Wy(){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,Dn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function fS(){return Pl.apply(this,arguments)}function Pl(){return Pl=io(wt().m(function t(){var e,n,r,o,s,a,c,l,d,f;return wt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:Ly,exp:e+3600,iat:e,sub:this.sub},n),o=YA.sign({header:{alg:"RS256"},payload:r,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Ly,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,f=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=f.response&&(a=f.response)!==null&&a!==void 0&&a.data?(c=f.response)===null||c===void 0?void 0:c.data:{},l.error&&(d=l.error_description?": ".concat(l.error_description):"",f.message="".concat(l.error).concat(d)),f;case 4:return p.a(2)}},t,this,[[1,3]])})),Pl.apply(this,arguments)}});var Bl=X(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.JWTAccess=void 0;var hS=vl(),pS=Wt(),Jy={alg:"RS256",typ:"JWT"},Il=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new pS.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),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),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:l,iat:c}:d={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},n){for(let C in d)if(n[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Jy,kid:this.keyId}:Jy,p=Object.assign(d,n),m=hS.sign({header:f,payload:p,secret:this.key}),b=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:b}),b}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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(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",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};ra.JWTAccess=Il});var Ml=X(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.JWT=void 0;var Vy=Gy(),mS=Bl(),gS=_r(),oa=_t(),Nl=class t extends gS.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 n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==oa.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==oa.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${oa.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new mS.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==oa.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Vy.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 n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.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(n=>e(null,n),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(),r={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",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new Vy.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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(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 n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};sa.JWT=Nl});var jl=X(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.UserRefreshClient=ao.USER_REFRESH_ACCOUNT_TYPE=void 0;var yS=_r(),_S=_t();ao.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Ll=class t extends yS.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,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 n={...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 _S.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};ao.UserRefreshClient=Ll});var $l=X(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.Impersonated=uo.IMPERSONATED_ACCOUNT_TYPE=void 0;var Ky=_r(),bS=Xe(),CS=Wt();uo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Ul=class t extends Ky.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 Ky.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,CS.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 n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,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 n=0,r="";throw e instanceof bS.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};uo.Impersonated=Ul});var zl=X(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.OAuthClientAuthHandler=void 0;rs.getErrorFromOAuthErrorResponse=kS;var co=Xe(),wS=Jo(),ES=["PUT","POST","PATCH"],ql=class{#e=(0,wS.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new co.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new co.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=co.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=co.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=co.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);co.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!ES.includes(n))throw new Error(`${n} 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"]}}}};rs.OAuthClientAuthHandler=ql;function kS(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),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 aa=X(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.StsCredentials=void 0;var AS=Xe(),SS=_t(),Qy=zl(),TS=Wt(),Hl=class t extends Qy.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){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:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,TS.removeUndefinedValuesInObject)(o))};SS.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 AS.GaxiosError&&a.response?(0,Qy.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};ia.StsCredentials=Hl});var Qn=X(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.BaseExternalAccountClient=Ot.CLOUD_RESOURCE_MANAGER=Ot.EXTERNAL_ACCOUNT_TYPE=Ot.EXPIRATION_TIME_OFFSET=void 0;var vS=Xe(),DS=re("stream"),Wl=_t(),RS=aa(),Yy=Wt(),xS=il(),OS="urn:ietf:params:oauth:grant-type:token-exchange",PS="urn:ietf:params:oauth:token-type:access_token",Gl="https://www.googleapis.com/auth/cloud-platform",FS=3600;Ot.EXPIRATION_TIME_OFFSET=300*1e3;Ot.EXTERNAL_ACCOUNT_TYPE="external_account";Ot.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var IS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",BS="https://sts.{universeDomain}/v1/token",Jl=class t extends Wl.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,Yy.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Ot.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Ot.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??BS.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),c=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,Yy.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new RS.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Gl],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(IS);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=FS),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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};Wl.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=vS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof DS.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:OS,audience:this.audience,requestedTokenType:PS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Gl]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);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 n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};Wl.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Gl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${xS.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Ot.BaseExternalAccountClient=Jl});var Xy=X(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.FileSubjectTokenSupplier=void 0;var Kl=re("util"),Ql=re("fs"),NS=(0,Kl.promisify)(Ql.readFile??(()=>{})),MS=(0,Kl.promisify)(Ql.realpath??(()=>{})),LS=(0,Kl.promisify)(Ql.lstat??(()=>{})),Vl=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 LS(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,r=await NS(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};ua.FileSubjectTokenSupplier=Vl});var Zy=X(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.UrlSubjectTokenSupplier=void 0;var jS=_t(),Yl=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 n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};jS.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};ca.UrlSubjectTokenSupplier=Yl});var e0=X(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.CertificateSubjectTokenSupplier=Et.InvalidConfigurationError=Et.CertificateSourceUnavailableError=Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var la=Wt(),da=re("fs"),fa=re("crypto"),US=re("https");Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var sn=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Et.CertificateSourceUnavailableError=sn;var Pt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Et.InvalidConfigurationError=Pt;var Xl=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 US.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,la.isValidFile)(e))return e;throw new sn(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,la.isValidFile)(n))return n;throw new sn(`Path from environment variable "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,la.getWellKnownCertificateConfigFileLocation)();if(await(0,la.isValidFile)(r))return r;throw new sn(`Could not find certificate configuration file. Searched override path, the "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await da.promises.readFile(e,"utf8")}catch{throw new sn(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.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(r){throw r instanceof Pt?r:new Pt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await da.promises.readFile(e),new fa.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sn(`Failed to read certificate file at ${e}: ${a}`)}try{o=await da.promises.readFile(n),(0,fa.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sn(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new fa.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await da.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,d)=>{try{return new fa.X509Certificate(l)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Pt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),c;if(a===-1)c=[n,...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(r){if(r instanceof Pt)throw r;let o=r instanceof Error?r.message:String(r);throw new sn(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Et.CertificateSubjectTokenSupplier=Xl});var td=X(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.IdentityPoolClient=void 0;var $S=Qn(),Zl=Wt(),qS=Xy(),zS=Zy(),t0=e0(),HS=aa(),n0=Xe(),ed=class t extends $S.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Zl.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&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,Zl.originalOrCamelOptions)(r),a=(0,Zl.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 d=s.get("file"),f=s.get("url"),p=s.get("certificate"),m=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new qS.FileSubjectTokenSupplier({filePath:d,formatType:c,subjectTokenFieldName:l});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new zS.UrlSubjectTokenSupplier({url:f,formatType:c,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let b=new t0.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=b}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 t0.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new HS.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new n0.Gaxios({agent:n})}),this.transporter=new n0.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};ha.IdentityPoolClient=ed});var rd=X(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.AwsRequestSigner=void 0;var pa=Xe(),o0=Jo(),r0="AWS4-HMAC-SHA256",WS="aws4_request",nd=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,o0.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,c=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await JS({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}),f=pa.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:l.host},a||{});c.token&&pa.Gaxios.mergeHeaders(f,{"x-amz-security-token":c.token});let p={url:r,method:o,headers:f};return s!==void 0&&(p.body=s),p}};ma.AwsRequestSigner=nd;async function os(t,e,n){return await t.signWithHmacSha256(e,n)}async function GS(t,e,n,r,o){let s=await os(t,`AWS4${e}`,n),a=await os(t,s,r),c=await os(t,a,o);return await os(t,c,"aws4_request")}async function JS(t){let e=pa.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=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=pa.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",d=[...c.keys()].sort();d.forEach(S=>{l+=`${S}:${c.get(S)}
|
|
53
53
|
`});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),m=`${t.method.toUpperCase()}
|
|
54
54
|
${t.canonicalUri}
|
|
55
55
|
${t.canonicalQuerystring}
|
|
56
56
|
${l}
|
|
57
57
|
${f}
|
|
58
|
-
${p}`,b=`${a}/${t.region}/${r}/${
|
|
58
|
+
${p}`,b=`${a}/${t.region}/${r}/${WS}`,C=`${r0}
|
|
59
59
|
${s}
|
|
60
60
|
${b}
|
|
61
|
-
`+await t.crypto.sha256DigestHex(m),_=await HS(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),g=await ss(t.crypto,_,C),y=`${n0} Credential=${t.securityCredentials.accessKeyId}/${b}, SignedHeaders=${f}, Signature=${(0,r0.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:y,canonicalQuerystring:t.canonicalQuerystring}}});var o0=X(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.DefaultAwsSecurityCredentialsSupplier=void 0;var ga=_t(),od=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.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.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 r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};ga.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ga.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return ga.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return ga.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){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}};ya.DefaultAwsSecurityCredentialsSupplier=od});var id=X(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.AwsClient=void 0;var WS=rd(),GS=Yn(),JS=o0(),s0=Wt(),VS=Xe(),sd=class t extends GS.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 n=(0,s0.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&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,s0.originalOrCamelOptions)(r);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 JS.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 WS.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"}),n=[];return VS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};_a.AwsClient=sd});var dd=X($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.InvalidSubjectTokenError=$e.InvalidMessageFieldError=$e.InvalidCodeFieldError=$e.InvalidTokenTypeFieldError=$e.InvalidExpirationTimeFieldError=$e.InvalidSuccessFieldError=$e.InvalidVersionFieldError=$e.ExecutableResponseError=$e.ExecutableResponse=void 0;var ba="urn:ietf:params:oauth:token-type:saml2",ad="urn:ietf:params:oauth:token-type:id_token",ud="urn:ietf:params:oauth:token-type:jwt",cd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Ca("Executable response must contain a 'version' field.");if(e.success===void 0)throw new wa("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!==ba&&this.tokenType!==ad&&this.tokenType!==ud)throw new Ea(`Executable response must contain a 'token_type' field when successful and it must be one of ${ad}, ${ud}, or ${ba}.`);if(this.tokenType===ba){if(!e.saml_response)throw new is(`Executable response must contain a 'saml_response' field when token_type=${ba}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new is(`Executable response must contain a 'id_token' field when token_type=${ad} or ${ud}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ka("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Aa("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)}};$e.ExecutableResponse=cd;var an=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};$e.ExecutableResponseError=an;var Ca=class extends an{};$e.InvalidVersionFieldError=Ca;var wa=class extends an{};$e.InvalidSuccessFieldError=wa;var ld=class extends an{};$e.InvalidExpirationTimeFieldError=ld;var Ea=class extends an{};$e.InvalidTokenTypeFieldError=Ea;var ka=class extends an{};$e.InvalidCodeFieldError=ka;var Aa=class extends an{};$e.InvalidMessageFieldError=Aa;var is=class extends an{};$e.InvalidSubjectTokenError=is});var pd=X(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.PluggableAuthHandler=fo.ExecutableError=void 0;var br=dd(),KS=oe("child_process"),fd=oe("fs"),Sa=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};fo.ExecutableError=Sa;var hd=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((n,r)=>{let o=KS.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(),r(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),d=new br.ExecutableResponse(l);return n(d)}catch(l){return l instanceof br.ExecutableResponseError?r(l):r(new br.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new Sa(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await fd.promises.realpath(this.outputFile)}catch{return}if(!(await fd.promises.lstat(e)).isFile())return;let n=await fd.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new br.ExecutableResponse(r).isValid()?new br.ExecutableResponse(r):void 0}catch(r){throw r instanceof br.ExecutableResponseError?r:new br.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};fo.PluggableAuthHandler=hd});var gd=X(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.PluggableAuthClient=ho.ExecutableError=void 0;var YS=Yn(),QS=dd(),i0=pd(),XS=pd();Object.defineProperty(ho,"ExecutableError",{enumerable:!0,get:function(){return XS.ExecutableError}});var ZS=30*1e3,a0=5*1e3,u0=120*1e3,eT="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",c0=1,md=class extends YS.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=ZS;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<a0||this.timeoutMillis>u0)throw new Error(`Timeout must be between ${a0} and ${u0} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new i0.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[eT]!=="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 n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>c0)throw new Error(`Version of executable is not currently supported, maximum supported version is ${c0}.`);if(!e.success)throw new i0.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new QS.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}};ho.PluggableAuthClient=md});var _d=X(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ExternalAccountClient=void 0;var tT=Yn(),nT=td(),rT=id(),oT=gd(),yd=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===tT.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new rT.AwsClient(e):e.credential_source?.executable?new oT.PluggableAuthClient(e):new nT.IdentityPoolClient(e):null}};Ta.ExternalAccountClient=yd});var h0=X(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.ExternalAccountAuthorizedUserClient=po.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var d0=_t(),l0=Hl(),f0=Xe(),sT=oe("stream"),iT=Yn();po.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var aT="https://sts.{universeDomain}/v1/oauthtoken",bd=class t extends l0.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};d0.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof f0.GaxiosError&&o.response?(0,l0.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Cd=class extends d0.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new bd({tokenRefreshEndpoint:e.token_url??aT.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=iT.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=f0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof sT.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};po.ExternalAccountAuthorizedUserClient=Cd});var y0=X(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GoogleAuth=Kt.GoogleAuthExceptionMessages=void 0;var uT=oe("child_process"),as=oe("fs"),cT=Xe(),us=Jo(),lT=oe("os"),wd=oe("path"),dT=Vo(),fT=ml(),hT=yl(),pT=_l(),mo=Ml(),p0=jl(),go=$l(),mT=_d(),cs=Yn(),Ed=_t(),m0=h0(),g0=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.
|
|
61
|
+
`+await t.crypto.sha256DigestHex(m),_=await GS(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),y=await os(t.crypto,_,C),g=`${r0} Credential=${t.securityCredentials.accessKeyId}/${b}, SignedHeaders=${f}, Signature=${(0,o0.fromArrayBufferToHex)(y)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:g,canonicalQuerystring:t.canonicalQuerystring}}});var s0=X(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.DefaultAwsSecurityCredentialsSupplier=void 0;var ga=_t(),od=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.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.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 r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};ga.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ga.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return ga.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return ga.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){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}};ya.DefaultAwsSecurityCredentialsSupplier=od});var id=X(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.AwsClient=void 0;var VS=rd(),KS=Qn(),QS=s0(),i0=Wt(),YS=Xe(),sd=class t extends KS.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 n=(0,i0.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&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,i0.originalOrCamelOptions)(r);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 QS.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"}),n=[];return YS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};_a.AwsClient=sd});var dd=X($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.InvalidSubjectTokenError=$e.InvalidMessageFieldError=$e.InvalidCodeFieldError=$e.InvalidTokenTypeFieldError=$e.InvalidExpirationTimeFieldError=$e.InvalidSuccessFieldError=$e.InvalidVersionFieldError=$e.ExecutableResponseError=$e.ExecutableResponse=void 0;var ba="urn:ietf:params:oauth:token-type:saml2",ad="urn:ietf:params:oauth:token-type:id_token",ud="urn:ietf:params:oauth:token-type:jwt",cd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Ca("Executable response must contain a 'version' field.");if(e.success===void 0)throw new wa("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!==ba&&this.tokenType!==ad&&this.tokenType!==ud)throw new Ea(`Executable response must contain a 'token_type' field when successful and it must be one of ${ad}, ${ud}, or ${ba}.`);if(this.tokenType===ba){if(!e.saml_response)throw new ss(`Executable response must contain a 'saml_response' field when token_type=${ba}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new ss(`Executable response must contain a 'id_token' field when token_type=${ad} or ${ud}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ka("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Aa("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)}};$e.ExecutableResponse=cd;var an=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};$e.ExecutableResponseError=an;var Ca=class extends an{};$e.InvalidVersionFieldError=Ca;var wa=class extends an{};$e.InvalidSuccessFieldError=wa;var ld=class extends an{};$e.InvalidExpirationTimeFieldError=ld;var Ea=class extends an{};$e.InvalidTokenTypeFieldError=Ea;var ka=class extends an{};$e.InvalidCodeFieldError=ka;var Aa=class extends an{};$e.InvalidMessageFieldError=Aa;var ss=class extends an{};$e.InvalidSubjectTokenError=ss});var pd=X(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.PluggableAuthHandler=lo.ExecutableError=void 0;var br=dd(),XS=re("child_process"),fd=re("fs"),Sa=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};lo.ExecutableError=Sa;var hd=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((n,r)=>{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(),r(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),d=new br.ExecutableResponse(l);return n(d)}catch(l){return l instanceof br.ExecutableResponseError?r(l):r(new br.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new Sa(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await fd.promises.realpath(this.outputFile)}catch{return}if(!(await fd.promises.lstat(e)).isFile())return;let n=await fd.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new br.ExecutableResponse(r).isValid()?new br.ExecutableResponse(r):void 0}catch(r){throw r instanceof br.ExecutableResponseError?r:new br.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};lo.PluggableAuthHandler=hd});var gd=X(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.PluggableAuthClient=fo.ExecutableError=void 0;var ZS=Qn(),eT=dd(),a0=pd(),tT=pd();Object.defineProperty(fo,"ExecutableError",{enumerable:!0,get:function(){return tT.ExecutableError}});var nT=30*1e3,u0=5*1e3,c0=120*1e3,rT="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",l0=1,md=class extends ZS.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=nT;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<u0||this.timeoutMillis>c0)throw new Error(`Timeout must be between ${u0} and ${c0} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new a0.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[rT]!=="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 n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>l0)throw new Error(`Version of executable is not currently supported, maximum supported version is ${l0}.`);if(!e.success)throw new a0.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new eT.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}};fo.PluggableAuthClient=md});var _d=X(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ExternalAccountClient=void 0;var oT=Qn(),sT=td(),iT=id(),aT=gd(),yd=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===oT.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new iT.AwsClient(e):e.credential_source?.executable?new aT.PluggableAuthClient(e):new sT.IdentityPoolClient(e):null}};Ta.ExternalAccountClient=yd});var p0=X(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.ExternalAccountAuthorizedUserClient=ho.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var f0=_t(),d0=zl(),h0=Xe(),uT=re("stream"),cT=Qn();ho.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var lT="https://sts.{universeDomain}/v1/oauthtoken",bd=class t extends d0.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};f0.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof h0.GaxiosError&&o.response?(0,d0.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Cd=class extends f0.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new bd({tokenRefreshEndpoint:e.token_url??lT.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=cT.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=h0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof uT.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};ho.ExternalAccountAuthorizedUserClient=Cd});var _0=X(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GoogleAuth=Kt.GoogleAuthExceptionMessages=void 0;var dT=re("child_process"),is=re("fs"),fT=Xe(),as=Go(),hT=re("os"),wd=re("path"),pT=Jo(),mT=ml(),gT=yl(),yT=_l(),po=Ml(),m0=jl(),mo=$l(),_T=_d(),us=Qn(),Ed=_t(),g0=p0(),y0=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 kd=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(n=>e(null,n),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 us.universe("universe-domain"),e||=Ed.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ed.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,g0.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ed.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof mo.JWT?n.scopes=this.scopes:n instanceof cs.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof mo.JWT?n.scopes=this.scopes:n instanceof cs.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new fT.Compute(e));throw new Error(Kt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=us.getGCPResidency()||await us.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=wd.join(o,".config"))}return n&&(n=wd.join(n,"gcloud","application_default_credentials.json"),as.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=as.realpathSync(e),!as.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 r=as.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==go.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${go.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 n=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 r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new go.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){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 r,o=(0,g0.originalOrCamelOptions)(n).get("universe_domain");return e.type===p0.USER_REFRESH_ACCOUNT_TYPE?(r=new p0.UserRefreshClient(n),r.fromJSON(e)):e.type===go.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===cs.EXTERNAL_ACCOUNT_TYPE?(r=mT.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===m0.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new m0.ExternalAccountAuthorizedUserClient({...e,...n}):(n.scopes=this.scopes,r=new mo.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){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 n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,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,n);return r(c)}catch(a){if(!this.keyFilename)throw a;let c=new mo.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),r(c)}}catch(a){return o(a)}})})}fromAPIKey(e,n={}){return new mo.JWT({...n,apiKey:e})}_isWindows(){let e=lT.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,uT.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).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 n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==cs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await us.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof go.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof cs.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,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[n,r]=await Promise.all([us.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(Kt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=wd.resolve(this.keyFilename),n=as.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))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 hT.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=cT.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,pT.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof go.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,dT.createCrypto)();if(r instanceof mo.JWT&&r.key)return await s.sign(r.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,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Kt.GoogleAuth=kd});var _0=X(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.IAMAuth=void 0;var Ad=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};va.IAMAuth=Ad});var b0=X(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.DownscopedClient=un.EXPIRATION_TIME_OFFSET=un.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var gT=Xe(),yT=oe("stream"),Sd=_t(),_T=aa(),bT="urn:ietf:params:oauth:grant-type:token-exchange",CT="urn:ietf:params:oauth:token-type:access_token",wT="urn:ietf:params:oauth:token-type:access_token";un.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;un.EXPIRATION_TIME_OFFSET=300*1e3;var Td=class extends Sd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Sd.AuthClient?{}:e),e instanceof Sd.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(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>un.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${un.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new _T.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=gT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof yT.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:bT,requestedTokenType:CT,subjectToken:e,subjectTokenType:wT},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};un.DownscopedClient=Td});var C0=X(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.PassThroughClient=void 0;var ET=_t(),vd=class extends ET.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Da.PassThroughClient=vd});var Rd=X(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.GoogleAuth=le.auth=le.PassThroughClient=le.ExecutableError=le.PluggableAuthClient=le.DownscopedClient=le.BaseExternalAccountClient=le.ExternalAccountClient=le.IdentityPoolClient=le.AwsRequestSigner=le.AwsClient=le.UserRefreshClient=le.LoginTicket=le.ClientAuthentication=le.OAuth2Client=le.CodeChallengeMethod=le.Impersonated=le.JWT=le.JWTAccess=le.IdTokenClient=le.IAMAuth=le.GCPEnv=le.Compute=le.DEFAULT_UNIVERSE=le.AuthClient=le.gaxios=le.gcpMetadata=void 0;var w0=y0();Object.defineProperty(le,"GoogleAuth",{enumerable:!0,get:function(){return w0.GoogleAuth}});le.gcpMetadata=Jo();le.gaxios=Xe();var E0=_t();Object.defineProperty(le,"AuthClient",{enumerable:!0,get:function(){return E0.AuthClient}});Object.defineProperty(le,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return E0.DEFAULT_UNIVERSE}});var kT=ml();Object.defineProperty(le,"Compute",{enumerable:!0,get:function(){return kT.Compute}});var AT=_l();Object.defineProperty(le,"GCPEnv",{enumerable:!0,get:function(){return AT.GCPEnv}});var ST=_0();Object.defineProperty(le,"IAMAuth",{enumerable:!0,get:function(){return ST.IAMAuth}});var TT=yl();Object.defineProperty(le,"IdTokenClient",{enumerable:!0,get:function(){return TT.IdTokenClient}});var vT=Nl();Object.defineProperty(le,"JWTAccess",{enumerable:!0,get:function(){return vT.JWTAccess}});var DT=Ml();Object.defineProperty(le,"JWT",{enumerable:!0,get:function(){return DT.JWT}});var RT=$l();Object.defineProperty(le,"Impersonated",{enumerable:!0,get:function(){return RT.Impersonated}});var Dd=_r();Object.defineProperty(le,"CodeChallengeMethod",{enumerable:!0,get:function(){return Dd.CodeChallengeMethod}});Object.defineProperty(le,"OAuth2Client",{enumerable:!0,get:function(){return Dd.OAuth2Client}});Object.defineProperty(le,"ClientAuthentication",{enumerable:!0,get:function(){return Dd.ClientAuthentication}});var xT=dl();Object.defineProperty(le,"LoginTicket",{enumerable:!0,get:function(){return xT.LoginTicket}});var OT=jl();Object.defineProperty(le,"UserRefreshClient",{enumerable:!0,get:function(){return OT.UserRefreshClient}});var PT=id();Object.defineProperty(le,"AwsClient",{enumerable:!0,get:function(){return PT.AwsClient}});var FT=rd();Object.defineProperty(le,"AwsRequestSigner",{enumerable:!0,get:function(){return FT.AwsRequestSigner}});var IT=td();Object.defineProperty(le,"IdentityPoolClient",{enumerable:!0,get:function(){return IT.IdentityPoolClient}});var NT=_d();Object.defineProperty(le,"ExternalAccountClient",{enumerable:!0,get:function(){return NT.ExternalAccountClient}});var BT=Yn();Object.defineProperty(le,"BaseExternalAccountClient",{enumerable:!0,get:function(){return BT.BaseExternalAccountClient}});var MT=b0();Object.defineProperty(le,"DownscopedClient",{enumerable:!0,get:function(){return MT.DownscopedClient}});var k0=gd();Object.defineProperty(le,"PluggableAuthClient",{enumerable:!0,get:function(){return k0.PluggableAuthClient}});Object.defineProperty(le,"ExecutableError",{enumerable:!0,get:function(){return k0.ExecutableError}});var LT=C0();Object.defineProperty(le,"PassThroughClient",{enumerable:!0,get:function(){return LT.PassThroughClient}});var jT=new w0.GoogleAuth;le.auth=jT});var e_=X((_N,sf)=>{"use strict";var wR=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,ER=/(\w*(\.\w*)*)\..*/;sf.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,Z0(r.stack)}};function Z0(t){let e=t.match(wR);return e?e[1].split(/[/\\]/).slice(-1)[0].match(ER)[1]:"anonymous"}sf.exports.extractPluginName=Z0});var n_=X((bN,t_)=>{"use strict";t_.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var r_=X((CN,ru)=>{"use strict";var kR=e_(),AR=n_(),SR=0;function af(t,e={}){let n=!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||(n=!0,e.name=kR(t)+"-auto-"+SR++),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 r=AR(e.name);return!n&&!t[r]&&(t[r]=t),t}ru.exports=af;ru.exports.default=af;ru.exports.fastifyPlugin=af});var gs,uf=Le(()=>{"use strict";gs=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,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:a}=n||{},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} `),r){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 kd=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(n=>e(null,n),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 as.universe("universe-domain"),e||=Ed.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ed.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,y0.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ed.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof po.JWT?n.scopes=this.scopes:n instanceof us.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof po.JWT?n.scopes=this.scopes:n instanceof us.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new mT.Compute(e));throw new Error(Kt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=as.getGCPResidency()||await as.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=wd.join(o,".config"))}return n&&(n=wd.join(n,"gcloud","application_default_credentials.json"),is.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){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 r=is.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==mo.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${mo.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 n=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 r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new mo.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){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 r,o=(0,y0.originalOrCamelOptions)(n).get("universe_domain");return e.type===m0.USER_REFRESH_ACCOUNT_TYPE?(r=new m0.UserRefreshClient(n),r.fromJSON(e)):e.type===mo.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===us.EXTERNAL_ACCOUNT_TYPE?(r=_T.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===g0.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new g0.ExternalAccountAuthorizedUserClient({...e,...n}):(n.scopes=this.scopes,r=new po.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){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 n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,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,n);return r(c)}catch(a){if(!this.keyFilename)throw a;let c=new po.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),r(c)}}catch(a){return o(a)}})})}fromAPIKey(e,n={}){return new po.JWT({...n,apiKey:e})}_isWindows(){let e=hT.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,dT.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).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 n=await this.getClient();if(n&&n.projectId)return n.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(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof mo.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof us.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,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[n,r]=await Promise.all([as.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(Kt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=wd.resolve(this.keyFilename),n=is.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))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 gT.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=fT.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,yT.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof mo.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,pT.createCrypto)();if(r instanceof po.JWT&&r.key)return await s.sign(r.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,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Kt.GoogleAuth=kd});var b0=X(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.IAMAuth=void 0;var Ad=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};va.IAMAuth=Ad});var C0=X(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.DownscopedClient=un.EXPIRATION_TIME_OFFSET=un.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var bT=Xe(),CT=re("stream"),Sd=_t(),wT=aa(),ET="urn:ietf:params:oauth:grant-type:token-exchange",kT="urn:ietf:params:oauth:token-type:access_token",AT="urn:ietf:params:oauth:token-type:access_token";un.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;un.EXPIRATION_TIME_OFFSET=300*1e3;var Td=class extends Sd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Sd.AuthClient?{}:e),e instanceof Sd.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(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>un.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${un.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new wT.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=bT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof CT.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:ET,requestedTokenType:kT,subjectToken:e,subjectTokenType:AT},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};un.DownscopedClient=Td});var w0=X(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.PassThroughClient=void 0;var ST=_t(),vd=class extends ST.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Da.PassThroughClient=vd});var Rd=X(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.GoogleAuth=le.auth=le.PassThroughClient=le.ExecutableError=le.PluggableAuthClient=le.DownscopedClient=le.BaseExternalAccountClient=le.ExternalAccountClient=le.IdentityPoolClient=le.AwsRequestSigner=le.AwsClient=le.UserRefreshClient=le.LoginTicket=le.ClientAuthentication=le.OAuth2Client=le.CodeChallengeMethod=le.Impersonated=le.JWT=le.JWTAccess=le.IdTokenClient=le.IAMAuth=le.GCPEnv=le.Compute=le.DEFAULT_UNIVERSE=le.AuthClient=le.gaxios=le.gcpMetadata=void 0;var E0=_0();Object.defineProperty(le,"GoogleAuth",{enumerable:!0,get:function(){return E0.GoogleAuth}});le.gcpMetadata=Go();le.gaxios=Xe();var k0=_t();Object.defineProperty(le,"AuthClient",{enumerable:!0,get:function(){return k0.AuthClient}});Object.defineProperty(le,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return k0.DEFAULT_UNIVERSE}});var TT=ml();Object.defineProperty(le,"Compute",{enumerable:!0,get:function(){return TT.Compute}});var vT=_l();Object.defineProperty(le,"GCPEnv",{enumerable:!0,get:function(){return vT.GCPEnv}});var DT=b0();Object.defineProperty(le,"IAMAuth",{enumerable:!0,get:function(){return DT.IAMAuth}});var RT=yl();Object.defineProperty(le,"IdTokenClient",{enumerable:!0,get:function(){return RT.IdTokenClient}});var xT=Bl();Object.defineProperty(le,"JWTAccess",{enumerable:!0,get:function(){return xT.JWTAccess}});var OT=Ml();Object.defineProperty(le,"JWT",{enumerable:!0,get:function(){return OT.JWT}});var PT=$l();Object.defineProperty(le,"Impersonated",{enumerable:!0,get:function(){return PT.Impersonated}});var Dd=_r();Object.defineProperty(le,"CodeChallengeMethod",{enumerable:!0,get:function(){return Dd.CodeChallengeMethod}});Object.defineProperty(le,"OAuth2Client",{enumerable:!0,get:function(){return Dd.OAuth2Client}});Object.defineProperty(le,"ClientAuthentication",{enumerable:!0,get:function(){return Dd.ClientAuthentication}});var FT=dl();Object.defineProperty(le,"LoginTicket",{enumerable:!0,get:function(){return FT.LoginTicket}});var IT=jl();Object.defineProperty(le,"UserRefreshClient",{enumerable:!0,get:function(){return IT.UserRefreshClient}});var BT=id();Object.defineProperty(le,"AwsClient",{enumerable:!0,get:function(){return BT.AwsClient}});var NT=rd();Object.defineProperty(le,"AwsRequestSigner",{enumerable:!0,get:function(){return NT.AwsRequestSigner}});var MT=td();Object.defineProperty(le,"IdentityPoolClient",{enumerable:!0,get:function(){return MT.IdentityPoolClient}});var LT=_d();Object.defineProperty(le,"ExternalAccountClient",{enumerable:!0,get:function(){return LT.ExternalAccountClient}});var jT=Qn();Object.defineProperty(le,"BaseExternalAccountClient",{enumerable:!0,get:function(){return jT.BaseExternalAccountClient}});var UT=C0();Object.defineProperty(le,"DownscopedClient",{enumerable:!0,get:function(){return UT.DownscopedClient}});var A0=gd();Object.defineProperty(le,"PluggableAuthClient",{enumerable:!0,get:function(){return A0.PluggableAuthClient}});Object.defineProperty(le,"ExecutableError",{enumerable:!0,get:function(){return A0.ExecutableError}});var $T=w0();Object.defineProperty(le,"PassThroughClient",{enumerable:!0,get:function(){return $T.PassThroughClient}});var qT=new E0.GoogleAuth;le.auth=qT});var n_=X((kB,uf)=>{"use strict";var TR=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,vR=/(\w*(\.\w*)*)\..*/;uf.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,t_(r.stack)}};function t_(t){let e=t.match(TR);return e?e[1].split(/[/\\]/).slice(-1)[0].match(vR)[1]:"anonymous"}uf.exports.extractPluginName=t_});var o_=X((AB,r_)=>{"use strict";r_.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var s_=X((SB,ru)=>{"use strict";var DR=n_(),RR=o_(),xR=0;function cf(t,e={}){let n=!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||(n=!0,e.name=DR(t)+"-auto-"+xR++),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 r=RR(e.name);return!n&&!t[r]&&(t[r]=t),t}ru.exports=cf;ru.exports.default=cf;ru.exports.fastifyPlugin=cf});var ms,lf=Le(()=>{"use strict";ms=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,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:a}=n||{},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} `),r){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,n=0){let r=" ".repeat(n);return Array.isArray(e)?e.map(o=>typeof o=="object"?`${r}-
|
|
69
69
|
${this.toMarkdown(o,n+1)}`:`${r}- ${o}`).join(`
|
|
70
70
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([o,s])=>typeof s=="object"&&s!==null?`${r}${o}:
|
|
71
71
|
${this.toMarkdown(s,n+1)}`:`${r}${o}: ${s}`).join(`
|
|
72
|
-
`):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var ys,cf=Le(()=>{"use strict";ys=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 n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},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,n,r,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,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(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(c=d,l===a.maxAttempts)break;let f=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw c}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,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}`)}}}});import{writeFileSync as TR,existsSync as vR,mkdirSync as DR}from"fs";import{join as s_}from"path";import{tmpdir as RR}from"os";var _s,lf=Le(()=>{"use strict";_s=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=RR();this.baseDir=s_(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{vR(this.baseDir)||DR(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return s_(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return TR(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var df,wo,i_=Le(()=>{"use strict";uf();cf();lf();df=class{handlers=new Map;defaultOptions={};registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){console.error(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new gs(e.config);case"webhook":return new ys(e.config);case"temp-file":return new _s(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,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,r)?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,n,r){let o={...this.defaultOptions,...r},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(n,o)?s.success.push(c):s.failed.push(c)}catch(d){console.error(`[OutputManager] Handler ${c} failed:`,d),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},wo=new df});import OR from"fastify";import PR from"@fastify/cors";var xh=jn($u(),1);import{readFileSync as sC,existsSync as Dh}from"fs";import{join as Rh}from"path";import{config as iC}from"dotenv";var Nr=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:Rh(process.cwd(),this.options.jsonPath);if(Dh(e))try{let n=sC(e,"utf-8"),r=xh.default.parse(n);this.config={...this.config,...r},console.log(`Loaded JSON config from: ${e}`)}catch(n){console.warn(`Failed to load JSON config from ${e}:`,n)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Rh(process.cwd(),this.options.envPath);if(Dh(e))try{let n=iC({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){console.warn(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}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,n){this.config[e]=n}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 ze(t,e=500,n="internal_error",r="api_error"){let o=new Error(t);return o.statusCode=e,o.code=n,o.type=r,o}async function Oh(t,e,n){e.log.error(t);let r=t.statusCode||500;if(t.rawBody)try{let s=JSON.parse(t.rawBody);return n.code(r).send(s)}catch{return n.code(r).send(t.rawBody)}let o={error:{message:t.message+(t.stack||"Internal Server Error"),type:t.type||"api_error",code:t.code||"internal_error"}};return n.code(r).send(o)}import{ProxyAgent as aC}from"undici";function Ph(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([d,f])=>{f&&s.set(d,f)});let a,c=AbortSignal.timeout(n.TIMEOUT??60*1e3*60);if(n.signal){let d=new AbortController,f=()=>d.abort();n.signal.addEventListener("abort",f),c.addEventListener("abort",f),a=d.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return n.httpsProxy&&(l.dispatcher=new aC(new URL(n.httpsProxy).toString())),o?.debug({reqId:r.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:n.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var uC=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Br={maxBodyLength:4096,maxStreamChunks:100},qu=!1;function cC(t){qu=t}function lC(){return qu}function Xs(t){return qu||t.get("DEBUG_LOG")===!0}function Nh(t){let e=t.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Br:{maxBodyLength:e.maxBodyLength??Br.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Br.maxStreamChunks}}function Bh(t){let e={};for(let[n,r]of Object.entries(t))uC.has(n.toLowerCase())?e[n]="***MASKED***":e[n]=r;return e}function Zs(t,e){return t.length<=e?t:t.slice(0,e)+`...[truncated, total ${t.length} bytes]`}function Mh(t,e,n){let r=typeof n.body=="string"?n.body:JSON.stringify(n.body);t.info({debug_log:!0,reqId:e,phase:"provider_request",url:n.url,headers:Bh(n.headers),body:Zs(r,Br.maxBodyLength)})}function Lh(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_response",status:n.status,headers:Bh(n.headers),...n.body!==void 0?{body:Zs(n.body,Br.maxBodyLength)}:{}})}function Fh(t,e,n,r){let o=dC(r);t.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:n,...o?{usage_monitor:o}:{},data:Zs(r,Br.maxBodyLength)})}function dC(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!(!r||r==="[DONE]"))try{let o=JSON.parse(r),s=o?.usage||o?.response?.usage;s&&e.push({path:o?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(o?.choices)?o.choices.length:void 0,finishReason:o?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Zs(r,512)})}}if(e.length)return e.length===1?e[0]:e}function Ih(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:n})}function jh(t,e,n,r){(async()=>{let o=t.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:c,value:l}=await o.read();if(c)break;a+=l;let d=a.split(`
|
|
72
|
+
`):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var gs,df=Le(()=>{"use strict";gs=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 n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},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,n,r,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,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(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(c=d,l===a.maxAttempts)break;let f=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw c}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,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}`)}}}});import{writeFileSync as OR,existsSync as PR,mkdirSync as FR}from"fs";import{join as a_}from"path";import{tmpdir as IR}from"os";var ys,ff=Le(()=>{"use strict";ys=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=IR();this.baseDir=a_(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{PR(this.baseDir)||FR(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return a_(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return OR(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var hf,Co,u_=Le(()=>{"use strict";lf();df();ff();hf=class{handlers=new Map;defaultOptions={};registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){console.error(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new ms(e.config);case"webhook":return new gs(e.config);case"temp-file":return new ys(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,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,r)?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,n,r){let o={...this.defaultOptions,...r},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(n,o)?s.success.push(c):s.failed.push(c)}catch(d){console.error(`[OutputManager] Handler ${c} failed:`,d),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},Co=new hf});import NR from"fastify";import MR from"@fastify/cors";var Oh=jn($u(),1);import{readFileSync as uC,existsSync as Rh}from"fs";import{join as xh}from"path";import{config as cC}from"dotenv";var Ir=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:xh(process.cwd(),this.options.jsonPath);if(Rh(e))try{let n=uC(e,"utf-8"),r=Oh.default.parse(n);this.config={...this.config,...r},console.log(`Loaded JSON config from: ${e}`)}catch(n){console.warn(`Failed to load JSON config from ${e}:`,n)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:xh(process.cwd(),this.options.envPath);if(Rh(e))try{let n=cC({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){console.warn(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}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,n){this.config[e]=n}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 He(t,e=500,n="internal_error",r="api_error"){let o=new Error(t);return o.statusCode=e,o.code=n,o.type=r,o}async function Ph(t,e,n){e.log.error(t);let r=t.statusCode||500;if(t.rawBody)try{let s=JSON.parse(t.rawBody);return n.code(r).send(s)}catch{return n.code(r).send(t.rawBody)}let o={error:{message:t.message+(t.stack||"Internal Server Error"),type:t.type||"api_error",code:t.code||"internal_error"}};return n.code(r).send(o)}import{ProxyAgent as lC}from"undici";function Fh(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([d,f])=>{f&&s.set(d,f)});let a,c=AbortSignal.timeout(n.TIMEOUT??60*1e3*60);if(n.signal){let d=new AbortController,f=()=>d.abort();n.signal.addEventListener("abort",f),c.addEventListener("abort",f),a=d.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return n.httpsProxy&&(l.dispatcher=new lC(new URL(n.httpsProxy).toString())),o?.debug({reqId:r.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:n.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var dC=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Br={maxBodyLength:4096,maxStreamChunks:100},qu=!1;function fC(t){qu=t}function hC(){return qu}function Xs(t){return qu||t.get("DEBUG_LOG")===!0}function Nh(t){let e=t.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Br:{maxBodyLength:e.maxBodyLength??Br.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Br.maxStreamChunks}}function Mh(t){let e={};for(let[n,r]of Object.entries(t))dC.has(n.toLowerCase())?e[n]="***MASKED***":e[n]=r;return e}function Zs(t,e){return t.length<=e?t:t.slice(0,e)+`...[truncated, total ${t.length} bytes]`}function Lh(t,e,n){let r=typeof n.body=="string"?n.body:JSON.stringify(n.body);t.info({debug_log:!0,reqId:e,phase:"provider_request",url:n.url,headers:Mh(n.headers),body:Zs(r,Br.maxBodyLength)})}function jh(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_response",status:n.status,headers:Mh(n.headers),...n.body!==void 0?{body:Zs(n.body,Br.maxBodyLength)}:{}})}function Ih(t,e,n,r){let o=pC(r);t.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:n,...o?{usage_monitor:o}:{},data:Zs(r,Br.maxBodyLength)})}function pC(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!(!r||r==="[DONE]"))try{let o=JSON.parse(r),s=o?.usage||o?.response?.usage;s&&e.push({path:o?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(o?.choices)?o.choices.length:void 0,finishReason:o?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Zs(r,512)})}}if(e.length)return e.length===1?e[0]:e}function Bh(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:n})}function Uh(t,e,n,r){(async()=>{let o=t.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:c,value:l}=await o.read();if(c)break;a+=l;let d=a.split(`
|
|
73
73
|
|
|
74
|
-
`);a=d.pop()||"";for(let f of d)f.trim()&&(s<r.maxStreamChunks?
|
|
74
|
+
`);a=d.pop()||"";for(let f of d)f.trim()&&(s<r.maxStreamChunks?Ih(e,n,s,f):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&Ih(e,n,s,a.trim()),s++),Bh(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),Bh(e,n,s)}finally{o.releaseLock()}})()}var $h="2.3.6";$n();import{existsSync as Qh,mkdirSync as TC,readFileSync as vC,writeFileSync as DC}from"fs";import{join as Yh}from"path";import{HOME_DIR as RC}from"@wengine-ai/claude-code-router-shared";var Ku=Yh(RC,"runtime"),Qu=Yh(Ku,"rate-limit.json"),Nr=new Map,Jh=!1,xC=null,OC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],PC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],FC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Po(t,e,n){let r=c=>{if(n instanceof Headers)return n.get(c);let l=Object.keys(n).find(d=>d.toLowerCase()===c);return l?n[l]:null},o=Vu(r,OC),s=Vu(r,PC),a=Vu(r,FC);(o||s||a)&&Nr.set(t,{provider:t,remaining:Vh(o),limit:Vh(s),reset:NC(a),capturedAt:Date.now()})}function IC(t){return Nr.get(t)}function BC(){return Array.from(Nr.values())}function Vu(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function Vh(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function NC(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=MC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function MC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function LC(){try{if(!Qh(Qu))return;let t=JSON.parse(vC(Qu,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Nr.set(n.provider,n)}}catch{}}function Kh(){try{if(Nr.size===0)return;Qh(Ku)||TC(Ku,{recursive:!0}),DC(Qu,JSON.stringify(Array.from(Nr.values()),null,2),"utf-8")}catch{}}function Yu(){Jh||(Jh=!0,LC(),xC=setInterval(Kh,6e4),process.on("exit",Kh))}ei();var Mr=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let n=e?.input_tokens??e?.prompt_tokens??0,r=e?.output_tokens??e?.completion_tokens??0,o=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:n,output_tokens:r,total_tokens:e?.total_tokens??n+r,input_tokens_details:{cached_tokens:o,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:o,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[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),n.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,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,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 n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let[r,o]=e.body.tee(),s=r.getReader(),a="";try{let{value:y,done:g}=await s.read();!g&&y&&(a=new TextDecoder().decode(y))}finally{s.releaseLock()}if(r.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let y=this.prependToStream(a,o);return new Response(y,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let y=this.prependToStream(a,o);return new Response(y,{status:e.status,statusText:e.statusText,headers:e.headers})}let d=this.prependToStream(a,o),f=new TextDecoder,p=new TextEncoder,m="",b=!1,C=this,_=new ReadableStream({async start(y){let g=d.getReader(),S=-1,w="",A=v=>(v!==w&&(S++,w=v),S);try{for(;;){let{done:v,value:R}=await g.read();if(v){b||y.enqueue(p.encode(`data: [DONE]
|
|
75
75
|
|
|
76
|
-
`));break}let $=f.decode(
|
|
76
|
+
`));break}let $=f.decode(R,{stream:!0});m+=$;let V=m.split(/\r?\n/);m=V.pop()||"";for(let P of V)if(P.trim())try{if(P.startsWith("event: "))continue;if(P.startsWith("data: ")){let Q=P.slice(5).trim();if(Q==="[DONE]"){b=!0,y.enqueue(p.encode(`data: [DONE]
|
|
77
77
|
|
|
78
|
-
`));continue}try{let
|
|
78
|
+
`));continue}try{let z=JSON.parse(Q);if(z.type==="response.output_text.delta"){let K={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:A(z.type),delta:{content:z.delta||""},finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(K)}
|
|
79
79
|
|
|
80
|
-
`))}else if(
|
|
80
|
+
`))}else if(z.type==="response.output_item.added"&&z.item?.type==="function_call"){let K={id:z.item.call_id||z.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex-",choices:[{index:A(z.type),delta:{role:"assistant",tool_calls:[{index:0,id:z.item.call_id||z.item.id,function:{name:z.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(K)}
|
|
81
81
|
|
|
82
|
-
`))}else if(
|
|
82
|
+
`))}else if(z.type==="response.output_item.added"&&z.item?.type==="message"){let K=[];(z.item.content||[]).forEach(ee=>{ee.type==="output_text"&&K.push({type:"text",text:ee.text||""})});let Y={role:"assistant"};if(K.length===1&&K[0].type==="text"?Y.content=K[0].text:K.length>0&&(Y.content=K),Y.content){let ee={id:z.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:A(z.type),delta:Y,finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(ee)}
|
|
83
83
|
|
|
84
|
-
`))}}else if(
|
|
84
|
+
`))}}else if(z.type==="response.output_text.annotation.added"){let K={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex",choices:[{index:A(z.type),delta:{annotations:[{type:"url_citation",url_citation:{url:z.annotation?.url||"",title:z.annotation?.title||"",content:"",start_index:z.annotation?.start_index||0,end_index:z.annotation?.end_index||0}}]},finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(K)}
|
|
85
85
|
|
|
86
|
-
`))}else if(
|
|
86
|
+
`))}else if(z.type==="response.function_call_arguments.delta"){let K={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex-",choices:[{index:A(z.type),delta:{tool_calls:[{index:0,function:{arguments:z.delta||""}}]},finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(K)}
|
|
87
87
|
|
|
88
|
-
`))}else if(
|
|
88
|
+
`))}else if(z.type==="response.completed"){let K=z.response?.output?.some(ee=>ee.type==="function_call")?"tool_calls":"stop",Y={id:z.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:K}]};y.enqueue(p.encode(`data: ${JSON.stringify(Y)}
|
|
89
89
|
|
|
90
|
-
`)),b=!0}else if(
|
|
90
|
+
`)),b=!0}else if(z.type==="response.reasoning_summary_text.delta"){let K={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:A(z.type),delta:{thinking:{content:z.delta||""}},finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(K)}
|
|
91
91
|
|
|
92
|
-
`))}else if(
|
|
92
|
+
`))}else if(z.type==="response.reasoning_summary_part.done"&&z.part){let K={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:S,delta:{thinking:{signature:z.item_id}},finish_reason:null}]};y.enqueue(p.encode(`data: ${JSON.stringify(K)}
|
|
93
93
|
|
|
94
|
-
`))}}catch{
|
|
95
|
-
`))}}else
|
|
96
|
-
`))}catch(
|
|
97
|
-
`))}}m.trim()&&
|
|
98
|
-
`)),b||
|
|
94
|
+
`))}}catch{y.enqueue(p.encode(P+`
|
|
95
|
+
`))}}else y.enqueue(p.encode(P+`
|
|
96
|
+
`))}catch(Q){console.error("Error processing line:",P,Q),y.enqueue(p.encode(P+`
|
|
97
|
+
`))}}m.trim()&&y.enqueue(p.encode(m+`
|
|
98
|
+
`)),b||y.enqueue(p.encode(`data: [DONE]
|
|
99
99
|
|
|
100
|
-
`))}catch(
|
|
101
|
-
data: ${JSON.stringify(
|
|
100
|
+
`))}catch(v){console.error("Stream error:",v),y.error(v)}finally{try{g.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}y.close()}}});return new Response(_,{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,n){let r={...e};if(delete r.cache_control,e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[o,s]=e.body.tee(),a=o.getReader(),c="";try{let{value:m,done:b}=await a.read();!b&&m&&(c=new TextDecoder().decode(m))}finally{a.releaseLock()}o.cancel().catch(()=>{});let l=c.includes("message_start")||c.includes("content_block_start"),d=c.includes("chat.completion.chunk");if(c.includes("response.created")||c.includes("response.output_text.delta")||c.includes("response.in_progress")||c.includes("response.output_item.added"))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(d&&!l){let m=this.convertOpenAIChatStreamToResponsesAPI(s,n);return new Response(m,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let p=this.convertAnthropicStreamToResponsesAPI(s,n);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let o=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(o)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,n){let o=new TextEncoder().encode(e),s=n.getReader(),a=!1;return new ReadableStream({async pull(c){a||(a=!0,c.enqueue(o));try{let{done:l,value:d}=await s.read();l?c.close():c.enqueue(d)}catch(l){c.error(l)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,c=0,l=!1,d=!1,f="",p=-1,m=[],b=(_,y)=>o.encode(`event: ${_}
|
|
101
|
+
data: ${JSON.stringify(y)}
|
|
102
102
|
|
|
103
|
-
`),C=(_,
|
|
104
|
-
`);
|
|
103
|
+
`),C=(_,y=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:_,model:s,output:y,usage:this.buildResponsesUsage()});return new ReadableStream({async start(_){try{let y=e.getReader(),g="",S=!1,w=A=>{if(!S){S=!0;for(let v of m)if(v.type==="function_call"){let R=m.indexOf(v);_.enqueue(b("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:v.call_id||v.id,output_index:R,arguments:v.arguments||""})),v.status="completed",_.enqueue(b("response.output_item.done",{type:"response.output_item.done",output_index:R,item:v}))}for(let v of m)if(v.type==="message"){let R=m.indexOf(v);v.status="completed",_.enqueue(b("response.output_item.done",{type:"response.output_item.done",output_index:R,item:v}))}_.enqueue(b("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:A?.model||s,output:m.slice(),usage:A?.usage?{...this.buildResponsesUsage(A.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:A,value:v}=await y.read();if(A)break;g+=r.decode(v,{stream:!0});let R=g.split(`
|
|
104
|
+
`);g=R.pop()||"";for(let $ of R){let V=$.trim();if(!V||V.startsWith("event:")||!V.startsWith("data:"))continue;let P=V.slice(5).trim();if(P==="[DONE]"){w({}),_.enqueue(o.encode(`data: [DONE]
|
|
105
105
|
|
|
106
|
-
`));continue}let
|
|
107
|
-
data: ${JSON.stringify(
|
|
106
|
+
`));continue}let Q;try{Q=JSON.parse(P)}catch{continue}l||(l=!0,_.enqueue(b("response.created",{type:"response.created",response:C("in_progress")})),_.enqueue(b("response.in_progress",{type:"response.in_progress",response:C("in_progress")})));let z=Q.choices?.[0];if(!z)continue;let K=z.delta;if(K?.content){if(!d){d=!0;let Y=c++,ee={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};m.push(ee),_.enqueue(b("response.output_item.added",{type:"response.output_item.added",output_index:Y,item:ee}))}_.enqueue(b("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:c-1,content_index:0,delta:K.content}))}if(Array.isArray(K?.tool_calls))for(let Y of K.tool_calls){if(Y.id){f=Y.id,p=c++;let ee={id:Y.id,type:"function_call",status:"in_progress",call_id:Y.id,name:Y.function?.name||"",arguments:""};m.push(ee),_.enqueue(b("response.output_item.added",{type:"response.output_item.added",output_index:p,item:ee}))}if(Y.function?.arguments){_.enqueue(b("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:f,output_index:p,delta:Y.function.arguments}));let ee=m.find(ae=>ae.call_id===f);ee&&(ee.arguments+=Y.function.arguments)}}z.finish_reason&&w(Q)}}S||w({}),_.close()}catch(y){_.error(y)}}})}convertAnthropicStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,c="",l="",d=-1,f="",p="",m="",b=-1,C="",_="",y=-1,g=0,S=!1,w=!1,A=!1,v=!1,R=null,$=[],V=(ee,ae)=>o.encode(`event: ${ee}
|
|
107
|
+
data: ${JSON.stringify(ae)}
|
|
108
108
|
|
|
109
|
-
`),P=(ee,
|
|
110
|
-
`);
|
|
109
|
+
`),P=(ee,ae=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:ee,model:s,output:ae,usage:this.buildResponsesUsage()}),Q=()=>{S||(S=!0,Y.enqueue(V("response.created",{type:"response.created",response:P("in_progress")})),Y.enqueue(V("response.in_progress",{type:"response.in_progress",response:P("in_progress")})))},z=(ee,ae)=>{Y.enqueue(V("response.output_item.done",{type:"response.output_item.done",output_index:ee,item:{...ae,status:"completed"}}))},K=ee=>{if(!v){if(v=!0,w){let ae=$.find(se=>se.type==="message");ae&&(ae.content=[{type:"output_text",text:c}],ae.status="completed")}for(let ae of $)ae.type==="function_call"&&(ae.status="completed");return V("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:$,usage:ee?{...this.buildResponsesUsage(ee)}:this.buildResponsesUsage()}})}},Y;return new ReadableStream({async start(ee){Y=ee;try{let ae=e.getReader(),se="";for(;;){let{done:G,value:Z}=await ae.read();if(G)break;se+=r.decode(Z,{stream:!0});let ie=se.split(`
|
|
110
|
+
`);se=ie.pop()||"";for(let Ue of ie){let Ae=Ue.trim();if(!Ae||Ae.startsWith("event:")||!Ae.startsWith("data:"))continue;let J=Ae.slice(5).trim();if(J==="[DONE]")continue;let ce;try{ce=JSON.parse(J)}catch{continue}if(ce.type==="message_start"&&(a=ce.message?.id||a,Q()),ce.type==="content_block_start"){let te=ce.content_block;if(R=te?.type||null,te?.type==="tool_use"){f=te.id||"",p=te.name||"",m="",b=g++;let ve={id:f,type:"function_call",status:"in_progress",call_id:f,name:p,arguments:""};$.push(ve),Y.enqueue(V("response.output_item.added",{type:"response.output_item.added",output_index:b,item:ve}))}if(te?.type==="thinking"&&(C=te.thinking||"",!A)){A=!0,y=g++,_=`rs_${a}`;let ve={id:_,type:"reasoning",status:"in_progress",summary:[]};$.push(ve),Y.enqueue(V("response.output_item.added",{type:"response.output_item.added",output_index:y,item:ve}))}if(te?.type==="text"&&(c=te?.text||"",!w)){w=!0,d=g++,l=`${a}_msg`;let ve={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};$.push(ve),Y.enqueue(V("response.output_item.added",{type:"response.output_item.added",output_index:d,item:ve}))}}if(ce.type==="content_block_delta"){let te=ce.delta;if(te?.type==="text_delta"){if(!w){w=!0,d=g++,l=`${a}_msg`;let ve={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};$.push(ve),Y.enqueue(V("response.output_item.added",{type:"response.output_item.added",output_index:d,item:ve}))}c+=te.text||"",Y.enqueue(V("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:d,content_index:0,delta:te.text||""}))}te?.type==="thinking_delta"&&(C+=te.thinking||"",Y.enqueue(V("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:_||`rs_${a}`,output_index:y>=0?y:0,summary_index:0,delta:te.thinking||""}))),te?.type==="input_json_delta"&&(m+=te.partial_json||"",Y.enqueue(V("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:f||"call_0",output_index:b>=0?b:0,delta:te.partial_json||""})))}if(ce.type==="content_block_stop"){if(R==="tool_use"&&f){Y.enqueue(V("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:f,output_index:b,arguments:m}));let te=$.find(ve=>ve.call_id===f);te&&(te.arguments=m,te.status="completed"),te&&z(b,te)}if(R==="text"&&w){Y.enqueue(V("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:d,content_index:0,text:c}));let te=$.find(ve=>ve.type==="message");te&&(te.content=[{type:"output_text",text:c}],z(d,te))}if(R==="thinking"&&A){let te=$.find(ve=>ve.type==="reasoning");te&&(te.summary=[{type:"summary_text",text:C}],z(y,te))}R=null}if(ce.type==="message_delta"){let te=K(ce.usage);te&&Y.enqueue(te)}if(ce.type==="message_stop"){let te=K();te&&Y.enqueue(te),Y.enqueue(o.encode(`data: [DONE]
|
|
111
111
|
|
|
112
|
-
`))}}}V();let me=Q();me&&J.enqueue(me),re="",J.close()}catch(ce){J.error(ce)}}})}wrapChatInResponses(e){let n=e?.choices?.[0],r=[],o=[];if(n?.message?.content&&o.push({type:"output_text",text:n.message.content}),r.push({type:"message",role:"assistant",content:o}),Array.isArray(n?.message?.tool_calls))for(let s of n.message.tool_calls)r.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:r,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let n=e.output?.find(d=>d.type==="message"),r=e.output?.find(d=>d.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(d=>({type:"url_citation",url_citation:{url:d.url||"",title:d.title||"",content:"",start_index:d.start_index||0,end_index:d.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let m=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});m&&f.push(m)}else if(p.type==="output_image_base64"){let m=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});m&&f.push(m)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),s=p}else s=d.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.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,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}: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}};import{get_encoding as HC}from"tiktoken";var Xu=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Zu=new Xu(100);$n();import{readFile as ic}from"fs/promises";import{opendir as zC,stat as WC}from"fs/promises";import{join as ac}from"path";import{CLAUDE_PROJECTS_DIR as tp,HOME_DIR as np}from"@wengine-ai/claude-code-router-shared";import{existsSync as Zh,mkdirSync as BC,readFileSync as MC,writeFileSync as LC}from"fs";import{join as ep}from"path";import{HOME_DIR as jC}from"@wengine-ai/claude-code-router-shared";var ec=ep(jC,"runtime"),tc=ep(ec,"quota-store.json"),jr=new Map,Qh=!1,UC=null;function nc(t,e){t&&jr.set(t,{...e,provider:t,capturedAt:Date.now()})}function rc(t){let e=jr.get(t);return e?{...e}:void 0}function $C(){return Array.from(jr.values()).map(t=>({...t}))}function qC(){try{if(!Zh(tc))return;let t=JSON.parse(MC(tc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>1440*60*1e3)continue;jr.set(n.provider,n)}}catch{}}function Xh(){try{if(jr.size===0)return;Zh(ec)||BC(ec,{recursive:!0}),LC(tc,JSON.stringify(Array.from(jr.values()),null,2),"utf-8")}catch{}}function oc(){Qh||(Qh=!0,qC(),UC=setInterval(Xh,6e4),process.on("exit",Xh))}ei();var wn=HC("cl100k_base"),sp=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=wn.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=wn.encode(s.text).length:s.type==="tool_use"?r+=wn.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=wn.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=wn.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=wn.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=wn.encode(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=wn.encode(o.name+o.description).length),o.input_schema&&(r+=wn.encode(JSON.stringify(o.input_schema)).length)}),r},ip=async(t,e)=>{if(t.sessionId){let n=await cp(t.sessionId);if(n){let r=ac(np,n,"config.json"),o=ac(np,n,`${t.sessionId}.json`);try{let s=JSON.parse(await ic(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await ic(r,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function ni(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 ap(t){let e=ni(t),n=e.includes("[1m]")||e.endsWith("[1m"),r=e.replace(/\[1m\]|\[1m$/g,""),o=r.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:n};let s=r.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||r.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:n}:{family:null,extended:n}}function GC(t,e){if(!e||!t)return null;let n=ni(t);if(e[t])return e[t];if(e[n])return e[n];let{family:r}=ap(t);if(r&&e[r])return e[r];for(let[o,s]of Object.entries(e)){let a=ni(o);if(a&&n.includes(a))return s}return null}function up(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function rp(t){if(!t?.includes(","))return null;let[e,...n]=t.split(","),r=e.trim(),o=n.join(",").trim();return!r||!o?null:{providerName:r,routeModel:o}}function ot(t,e,n,r,o){let s=rp(t);if(!s)return t;let{providerName:a,routeModel:c}=s,l=e.find(p=>p.name.toLowerCase()===a.toLowerCase());if(l&&l.enabled===!1)return null;if(o===!0&&r&&!n){let p=Po(),m=p.getPromotion(a,c,r,e);if(m){let b=rp(m);if(b){let C=e.find(g=>g.name.toLowerCase()===b.providerName.toLowerCase()),_=C?.models?.find(g=>String(g).toLowerCase()===b.routeModel.toLowerCase());if(C&&_)return`${C.name},${_}`}p.clear(a,c,r)}}if(!n&&!Ye().isAvailable(a,c))return null;let d=rc(a);if(d){let p=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,m=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(p||m)return null}let f=l?.models?.find(p=>String(p).toLowerCase()===c.toLowerCase());return l&&f?`${l.name},${f}`:t}function jt(t,e,n,r,o){let s=Ye(),a=[n?.[t],r?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let d=ot(l,e);if(d)return d}return null}function JC(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(n=>n.type==="image"||n.type==="image_url"||Array.isArray(n?.content)&&n.content.some(r=>r.type==="image"||r.type==="image_url")))}function VC(t){let e=ni(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(r=>r.test(e))}function KC(t,e,n,r,o,s,a,c){let l=n.longContextThreshold||6e4,d=Math.max(e,up(o)),f=t.modelFamily;if((s||d>2e5)&&n.extendedContext){let C=ot(n.extendedContext,r,!1,"extendedContext",c);if(C)return t.log.info(`Family: using extended context model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:C,scenarioType:"extendedContext",isFallback:!1};let _=c?jt("extendedContext",r,n.fallback,a,f):null;if(_)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:_,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(d>l&&(n.longContext||n.fallback?.longContext?.length||a?.longContext?.length)){let C=n.longContext?ot(n.longContext,r,!1,"longContext",c):null;if(C)return t.log.info(`Family: using long context model, tokens: ${d}, estimated: ${e}`),{model:C,scenarioType:"longContext",isFallback:!1};let _=c?jt("longContext",r,n.fallback,a,f):null;if(_)return t.log.info(`Family: using long context fallback model, tokens: ${d}, estimated: ${e}`),{model:_,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(C=>C.type?.startsWith("web_search"))&&n.webSearch){let C=ot(n.webSearch,r,!1,"webSearch",c);if(C)return{model:C,scenarioType:"webSearch",isFallback:!1};let _=c?jt("webSearch",r,n.fallback,a,f):null;if(_)return t.log.info("Family: using webSearch fallback model"),{model:_,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&n.think){let C=ot(n.think,r,!1,"think",c);if(C)return{model:C,scenarioType:"think",isFallback:!1};let _=c?jt("think",r,n.fallback,a,f):null;if(_)return t.log.info("Family: using think fallback model"),{model:_,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(n.default){let C=ot(n.default,r,!1,"default",c);if(C)return{model:C,scenarioType:"default",isFallback:!1};let _=c?jt("default",r,n.fallback,a,f):null;if(_)return t.log.info("Family: using default fallback model"),{model:_,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var YC=async(t,e,n,r)=>{let o=await ip(t,n),s=n.get("providers")||[],a=o||n.get("Router"),c=a?.enableFallback===!0,l=c?n.get("fallback"):void 0;if(t.body.model.includes(",")){let k=ot(t.body.model,s,!1,"default",c);if(k)return{model:k,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let w=c?jt("default",s,void 0,l):null;if(w)return t.log.info(`Using fallback for explicit model: ${w}`),{model:w,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:d,extended:f}=ap(t.body.model),p=a?.families?.[d||""];if(p&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${d}${f?" (1M)":""}`),t.modelFamily=d,t.familyFallback=p.fallback;let k=KC(t,e,p,s,r,f,l,c);if(k)return{model:k.model,scenarioType:k.scenarioType}}let m=GC(t.body.model,a?.models);if(m)if(/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(t.body.model)&&!a?.enableFamilyRouting)t.log.info(`Skipping model mapping for ${t.body.model} because family routing is disabled`);else{let w=ot(m,s,!1,"modelMapping",c);if(w)return t.log.info(`Using mapped model for ${t.body.model}: ${m}`),{model:w,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${m} unavailable (fail pool), skipping`)}let b=Math.max(e,up(r)),C=a?.extendedContextThreshold||2e5;if(b>C&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${b}, estimated: ${e}, threshold: ${C}`);let k=ot(a.extendedContext,s,!1,"extendedContext",c);if(k)return{model:k,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let w=c?jt("extendedContext",s,void 0,l):null;if(w)return{model:w,scenarioType:"extendedContext"}}let _=a?.longContextThreshold||6e4;if(b>_&&a?.longContext){t.log.info(`Using long context model due to token count: ${b}, estimated: ${e}, threshold: ${_}`);let k=ot(a.longContext,s,!1,"longContext",c);if(k)return{model:k,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let w=c?jt("longContext",s,void 0,l):null;if(w)return{model:w,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let k=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(k)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${k[1]}</CCR-SUBAGENT-MODEL>`,""),{model:k[1],scenarioType:"default"}}let y=n.get("Router");if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&y?.background){t.log.info(`Using background model for ${t.body.model}`);let k=ot(y.background,s,!1,"background",c);if(k)return{model:k,scenarioType:"background"};t.log.warn(`Background model ${y.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(k=>k.type?.startsWith("web_search"))&&a?.webSearch){let k=ot(a.webSearch,s,!1,"webSearch",c);if(k)return{model:k,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let w=c?jt("webSearch",s,void 0,l):null;if(w)return{model:w,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let k=ot(a.think,s,!1,"think",c);if(k)return{model:k,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let w=c?jt("think",s,void 0,l):null;if(w)return{model:w,scenarioType:"think"}}if(a?.default){let k=ot(a.default,s,!1,"default",c);if(k)return{model:k,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let w=c?jt("default",s,void 0,l):null;if(w)return{model:w,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Io=async(t,e,n)=>{let{configService:r,event:o}=n;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let C=t.body.metadata.user_id.split("_session_");C.length>1&&(t.sessionId=C[1])}let a=await ip(t,r)||r.get("Router"),c=a?.enableFallback===!0,l=r.get("providers")||[],d=Zu.get(t.sessionId),{messages:f,system:p=[],tools:m}=t.body,b=r.get("REWRITE_SYSTEM_PROMPT");if(b&&p.length>1&&p[1]?.text?.includes("<env>")){let C=await ic(b,"utf-8");p[1].text=`${C}<env>${p[1].text.split("<env>").pop()}`}try{let[C,_]=t.body.model.split(","),g=n.tokenizerService?.getTokenizerConfigForModel(C,_),y;n.tokenizerService?y=(await n.tokenizerService.countTokens({messages:f,system:p,tools:m},g)).tokenCount:y=sp(f,p,m),t.tokenCount=y;let k,w=r.get("CUSTOM_ROUTER_PATH");if(w)try{k=await oe(w)(t,r.getAll(),{event:o})}catch(S){t.log.error(`failed to load custom router: ${S.message}`)}if(k)t.scenarioType="default";else{let S=await YC(t,y,r,d);k=S.model,t.scenarioType=S.scenarioType}if(a?.image&&k!==a.image&&JC(t)&&!VC(k)){let S=ot(a.image,l,!1,"image",c);S?(t.log.info(`Using image model fallback for ${k}`),k=S,t.scenarioType="image"):(t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${k}`),t.scenarioType="image")}t.body.model=k}catch(C){t.log.error(`Error in router middleware: ${C.message}`),t.body.model=a?.default,t.scenarioType="default"}},En=new Map,op=1e3;function sc(){if(En.size<=op)return;let t=[...En.keys()].slice(0,En.size-op);for(let e of t)En.delete(e)}var cp=async t=>{if(En.has(t)){let e=En.get(t);return!e||e===""?null:e}try{let e=await zC(tp),n=[];for await(let s of e)s.isDirectory()&&n.push(s.name);let r=n.map(async s=>{let a=ac(tp,s,`${t}.jsonl`);try{return(await WC(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(r);for(let s of o)if(s)return En.set(t,s),sc(),s;return En.set(t,""),sc(),null}catch(e){return console.error("Error searching for project by session:",e),En.set(t,""),sc(),null}};var QC=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;function lp(t){let e=[],n=Array.isArray(t.input)?t.input:[t.input];for(let r of n)if(r.type==="function_call")e.push({role:"assistant",tool_calls:[{id:r.call_id,type:"function",function:{name:r.name,arguments:r.arguments||"{}"}}]});else if(r.type==="function_call_output")e.push({role:"tool",tool_call_id:r.call_id,content:typeof r.output=="string"?r.output:JSON.stringify(r.output)});else if(r.role){let o=r.content;Array.isArray(o)&&(o=o.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:r.role,content:o})}t.messages=e,delete t.input,t.instructions&&typeof t.instructions=="string"&&(t.system=t.instructions,delete t.instructions),Array.isArray(t.tools)&&(t.tools=t.tools.filter(r=>r&&typeof r=="object").map(r=>r.type==="function"&&r.name&&!r.function?{type:"function",function:{name:r.name,description:r.description||"",parameters:r.parameters||{type:"object",properties:{}}}}:r.function?.name?r:r.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),t.reasoning&&typeof t.reasoning=="object"&&(t.reasoning={enabled:!0,effort:t.reasoning.effort})}async function XC(t,e,n,r){let o=t.body;r.endPoint==="/v1/responses"&&o?.input&&!o?.messages&&lp(o),r.endPoint==="/v1/responses"&&!t.provider&&typeof o?.model=="string"&&QC.test(o.model)&&await Io(t,e,{configService:n.configService,tokenizerService:n.tokenizerService});let s=t.provider;if(!s&&o?.model){let d=o.model.split(",");d.length>1&&(s=d[0],o.model=d.slice(1).join(","))}let a=s?n.providerService.getProvider(s):void 0;if(!a&&o?.model){let d=n.providerService.resolveModelRoute(o.model);d&&(a=d.provider,o.model=d.targetModel)}if(!a&&o?.model){let f=n.configService.get("Router")?.default;if(f&&f.includes(",")){let[p,...m]=f.split(","),b=n.providerService.getProvider(p);b&&(a=b,o.model=m.join(","))}}if(t.originalModel||(t.originalModel=o?.model),!a)throw ze(`Provider '${s}' not found`,404,"provider_not_found");t.provider=a.name||s;let c=tw(t),l=r.endPoint==="/v1/messages"&&c;c&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),t.isCodexOnMessagesEndpoint=l,t.codexDetected=c;try{r.endPoint==="/v1/responses"&&o.input&&!o.messages&&lp(o);let{requestBody:d,config:f,bypass:p}=await dp(o,a,r,t.headers,{req:t});if(d?.messages&&!p&&!t.isTargetAnthropic){let _=d.messages,g=new Set,y=[],k=[];for(let w of _){if(w?.role!=="system"){k.push(w);continue}let S=JSON.stringify(w.content??"");g.has(S)||(g.add(S),y.push(w))}y.length>0&&k.length>0&&(d.messages=[...k,...y])}let m=await fp(d,f,a,n,p,r,{req:t});try{a?.baseUrl&&m?.headers&&Fo(s,a.baseUrl,m.headers)}catch{}let b=await hp(d,m,a,r,p,{req:t,isCodexOnMessagesEndpoint:l});if(o.stream&&b?.body){let _=b.body.getReader(),g=await _.read();if(g.done)throw _.releaseLock(),ze(`Provider returned empty streaming response from ${s}`,400,"provider_response_error");let y=new TextDecoder().decode(g.value);if(y.includes("event: error")){_.releaseLock();let S=y.length<500?y:y.slice(0,500);throw ze(`Provider ${s} returned error in SSE stream: ${S}`,400,"provider_response_error")}if(y.split(`
|
|
113
|
-
`).filter(S=>S.startsWith("data:")&&S.trim().length>5).length===0){_.releaseLock();let S=y.length<500?y:y.slice(0,500);throw ze(`Provider ${s} returned streaming response with no SSE data lines: ${S}`,400,"provider_response_error")}let w=new ReadableStream({start:S=>{S.enqueue(g.value);let R=()=>{_.read().then(({done:v,value:$})=>{v?S.close():(S.enqueue($),R())}).catch(v=>S.error(v))};R()},cancel:()=>{_.cancel()}});b=new Response(w,{headers:b.headers,status:b.status,statusText:b.statusText})}let C=pp(b,e,o,n);try{let _=o.model||t.originalModel;s&&_&&Ye().recordSuccess(s,_)}catch{}return C}catch(d){let f=await ZC(t,e,n,r,d);if(f)return f;throw d}}async function ZC(t,e,n,r,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=n.configService.get("fallback"),d=Ye(),f=t.provider||"",p=t.body.model||"",m=new Set,b=o?.statusCode===429||o?.isRateLimit===!0||o?.rawBody&&ri(o.rawBody)||o?.message&&ri(o.message);if(f&&p&&(b?(d.markRateLimited(f,p,120,o?.message),t.log.warn(`Primary model ${f},${p} rate-limited, will try fallbacks`)):d.recordFailure(f,p,o?.message),m.add(`${f},${p}`),n.recordUsage?.({provider:f,model:p,originalModel:t.originalModel||p,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})),!n.configService.get("Router")?.enableFallback)return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let _=k=>{let[w,...S]=k.split(","),R=w?.trim(),v=S.join(",").trim();return!R||!v?null:{provider:R,model:v,key:`${R},${v}`}},g=[];if(c){let k=a?.[s];Array.isArray(k)&&k.length>0?g.push({name:`${c}/${s}`,models:k}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&g.push({name:`global/${s}`,models:l[s]}),g.length===0&&s!=="image"&&t.body?.messages?.some(S=>S.role==="user"&&Array.isArray(S.content)&&S.content.some(R=>R.type==="image"||R.type==="image_url"||Array.isArray(R?.content)&&R.content.some(v=>v.type==="image"||v.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(t.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),g.push({name:"global/image (auto-detected)",models:l.image})),g.length===0)return null;let y=g.reduce((k,w)=>k+w.models.length,0);t.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${g.length} fallback stage(s)`);for(let k of g){t.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let w of k.models){let S=_(w);if(!S){t.log.warn(`Fallback model '${w}' is invalid, skipping`);continue}if(m.has(S.key))continue;m.add(S.key);let R=S.provider,v=S.model;try{if(!d.isAvailable(R,v)){t.log.warn(`Fallback model ${w} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${w}`);let $={...t.body};$.model=v;let Y={...t,provider:R,body:$},P=n.providerService.getProvider(R);if(!P){t.log.warn(`Fallback provider '${R}' not found, skipping`);continue}if(P.enabled===!1){t.log.warn(`Fallback provider '${R}' is disabled, skipping`);continue}let{requestBody:V,config:H,bypass:Q}=await dp($,P,r,t.headers,{req:Y}),J=await fp(V,H,P,n,Q,r,{req:Y});try{P?.baseUrl&&J?.headers&&Fo(R,P.baseUrl,J.headers)}catch{}let ee=await hp(V,J,P,r,Q,{req:Y,isCodexOnMessagesEndpoint:t.isCodexOnMessagesEndpoint||!1});return t.log.info(`Fallback model ${w} succeeded`),d.recordSuccess(R,v),f&&p&&(Po().promote(f,p,s,R,v),t.log.info(`Promoted fallback model ${R},${v} for ${f},${p}:${s}`),b?t.log.info(`Rate-limited original model ${f},${p} already marked unavailable with cooldown`):(d.forceOpen(f,p,o?.message),t.log.info(`Marked original model ${f},${p} as unavailable`))),t.provider=R,t.body=$,pp(ee,e,$,n)}catch($){d.recordFailure(R,v,$.message),t.log.warn(`Fallback model ${S.key} failed: ${$.message}`),n.recordUsage?.({provider:R,model:v,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:$.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream,req:t});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function dp(t,e,n,r,o){let s=JSON.parse(JSON.stringify(t)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let d=0;d<a.length;d++){let f=a[d],p=typeof f=="string"?f:f?.text??"";if(p.includes("cch=")){let m=p.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof f=="string"?a[d]=m:typeof f?.text=="string"&&(f.text=m)}}let c={},l=!1;if(l=ew(e,n,t),l&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],c.headers=r),!l&&typeof n.transformRequestOut=="function"){let d=await n.transformRequestOut(s);d.body?(s=d.body,c=d.config||{}):s=d}if(!l&&e.transformer?.use?.length)for(let d of e.transformer.use){if(!d||typeof d.transformRequestIn!="function")continue;let f=await d.transformRequestIn(s,e,o);f.body?(s=f.body,c={...c,...f.config}):s=f}if(!l&&e.transformer?.[t.model]?.use?.length)for(let d of e.transformer[t.model].use)!d||typeof d.transformRequestIn!="function"||(s=await d.transformRequestIn(s,e,o));return{requestBody:s,config:c,bypass:l}}function ew(t,e,n){return e.endPoint==="/v1/chat/completions"&&Array.isArray(n?.system)?!1:t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}function tw(t){let e=t.headers||{},n=e["x-anthropic-billing-header"]||"";if(typeof n=="string"&&n.includes("cc_version="))return!1;let r=e["user-agent"]||"";if(typeof r=="string"&&/codex/i.test(r))return!0;let o=t.pathname||t.url||"";if(typeof o=="string"&&o.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=t.originalModel||t.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function fp(t,e,n,r,o,s,a){let c=e.url||new URL(n.baseUrl);if(!e.TIMEOUT){let f=r.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(o&&typeof s.auth=="function"){let f=await s.auth(t,n);if(f.body){t=f.body;let p=e.headers||{};f.config?.headers&&(p={...p,...f.config.headers},delete p.host,delete f.config.headers),e={...e,...f.config,headers:p}}else t=f}let l={Authorization:`Bearer ${n.apiKey}`,...e?.headers||{}};for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];Xs(r.configService)&&Mh(r.log,a.req.id,{url:String(c),headers:l,body:t});let d=await Ph(c,t,{httpsProxy:r.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,r.log);if(!d.ok){let f=await d.text();r.log.error(`[provider_response_error] Error from provider(${n.name},${t.model}: ${d.status}): ${f}`);let p=ze(`Error from provider(${n.name},${t.model}: ${d.status}): ${f}`,d.status,"provider_response_error");throw p.isRateLimit=d.status===429||ri(f),p.rawBody=f,p}if(d.ok){let f=d.headers.get("content-type")||"",p=t.stream===!0;if(r.log.info(`[hidden-error-check] provider=${n.name} model=${t.model} stream=${t.stream} isStreamRequest=${p} contentType=${f} ok=${d.ok} status=${d.status} hasBody=${!!d.body}`),!p||f.includes("application/json")){let m=d.clone(),b="";try{if(b=await m.text(),!b||b.trim()==="")throw new SyntaxError("Empty JSON body");let C=JSON.parse(b);if(C&&typeof C=="object"&&C.error&&(typeof C.error=="string"||typeof C.error=="object"&&Object.keys(C.error).length>0)){r.log.error(`[provider_response_error] Hidden error from provider(${n.name},${t.model}: ${d.status}): ${b}`);let g=ri(b),y=ze(`Error from provider(${n.name},${t.model}: ${d.status}): ${b}`,400,"provider_response_error");throw y.isRateLimit=g,y.rawBody=b,y}}catch(C){if(C instanceof SyntaxError){r.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${n.name},${t.model}: 200): "${b}"`);let _=ze(`API returned an empty or malformed response (HTTP 200) from ${n.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw _.rawBody=b,_}throw C}}}if(!t.stream&&Xs(r.configService)){let p=await d.clone().text();Lh(r.log,a.req.id,{status:d.status,headers:Object.fromEntries(d.headers.entries()),body:p})}return d}async function hp(t,e,n,r,o,s){let a=e;if(!o&&n.transformer?.use?.length)for(let c of Array.from(n.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&n.transformer?.[t.model]?.use?.length)for(let c of Array.from(n.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformResponseIn&&(s.provider||(s.provider=n),a=await r.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Lr().transformResponseIn(a,{...s,provider:n})}catch(c){console.error("Failed to apply Responses API conversion for codex client:",c)}return a}function pp(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&Xs(r.configService)){let[s,a]=t.body.tee(),c=Nh(r.configService);return jh(s,r.log,e.request.id,c),e.send(a)}return e.send(t.body)}else return t.json()}var uc=async t=>{t.get("/",async()=>({message:"LLMs API",version:Uh})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Ye().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>XC(r,o,t,n));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(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=n.body;if(!o?.trim())throw ze("Provider name is required",400,"invalid_request");if(!s||!nw(s))throw ze("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw ze("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw ze("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw ze(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw ze("Provider not found",404,"provider_not_found");return r}),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(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw ze("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw ze("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(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw ze("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function ri(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function nw(t){try{return new URL(t),!0}catch{return!1}}var Ur=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;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(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.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(n.transformer[o]?.use)&&(r[o]={use:n.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:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],quotaToken:n.quota_token,transformer:n.transformer?r:void 0,cacheMode:n.cache_mode||"exclusive",enabled:n.enabled!==!1,wakeupEnabled:n.wakeup_enabled===!0,wakeupTime:n.wakeup_time||"06:00",wakeupModel:n.wakeup_model||""}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}registerProvider(e){let n={...e,enabled:e.enabled!==!1,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,c={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){let r=this.providers.get(e);if(!r)return!1;r.enabled=n;let o=this.configService.get("providers");if(o&&Array.isArray(o)){let s=o.find(a=>a.name===e);s&&(s.enabled=n)}return!0}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var Qe=[];for(let t=0;t<256;++t)Qe.push((t+256).toString(16).slice(1));function mp(t,e=0){return(Qe[t[e+0]]+Qe[t[e+1]]+Qe[t[e+2]]+Qe[t[e+3]]+"-"+Qe[t[e+4]]+Qe[t[e+5]]+"-"+Qe[t[e+6]]+Qe[t[e+7]]+"-"+Qe[t[e+8]]+Qe[t[e+9]]+"-"+Qe[t[e+10]]+Qe[t[e+11]]+Qe[t[e+12]]+Qe[t[e+13]]+Qe[t[e+14]]+Qe[t[e+15]]).toLowerCase()}import{randomFillSync as rw}from"crypto";var si=new Uint8Array(256),oi=si.length;function cc(){return oi>si.length-16&&(rw(si),oi=0),si.slice(oi,oi+=16)}import{randomUUID as ow}from"crypto";var lc={randomUUID:ow};function sw(t,e,n){if(lc.randomUUID&&!e&&!t)return lc.randomUUID();t=t||{};let r=t.random??t.rng?.()??cc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return mp(r)}var Ut=sw;var gp=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var yp=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function iw(t){return t.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function _p(t){let e=[],n=[],r=m=>{if(typeof m=="string"){n.push({type:"text",text:m});return}Array.isArray(m)&&m.forEach(b=>{if(typeof b=="string"){n.push({type:"text",text:b});return}b&&typeof b=="object"&&b.type==="text"&&b.text&&n.push({...b})})},o=()=>{let m=new Map;for(let b=0;b<n.length;b++){let C=n[b],_=C?.text??JSON.stringify(C),g=m.get(_);if(g===void 0){m.set(_,b);continue}!n[g]?.cache_control&&C?.cache_control&&(n[g]=C),n.splice(b,1),b--}};t.messages.forEach(m=>{m.role==="system"?r(m.content):e.push(m)}),o();let s=[];for(let m=0;m<e.length;m++){let b=e[m];if(b.role==="tool"){let C=b.content;try{typeof b.content=="string"&&(C=JSON.parse(b.content))}catch{}C!=null&&typeof C!="object"&&typeof C!="string"&&(C=String(C));let _={type:"tool_result",tool_use_id:b.tool_call_id,content:C};b.cache_control&&(_.cache_control=b.cache_control);let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(_):s.push({role:"user",content:[_]})}else if(b.role==="user"){let C=[];typeof b.content=="string"?C.push({type:"text",text:b.content}):Array.isArray(b.content)&&b.content.forEach(g=>{g&&typeof g=="object"&&g.type==="image_url"&&g.image_url?.url?C.push({type:"image",source:{type:"base64",media_type:g.media_type||"image/jpeg",data:g.image_url.url.split(",")[1]||g.image_url.url}}):C.push(g)});let _=s[s.length-1];_&&_.role==="user"&&Array.isArray(_.content)?_.content.push(...C):s.push({role:"user",content:C.length>0?C:[{type:"text",text:" "}]})}else if(b.role==="assistant"){let C=[];b.content&&(typeof b.content=="string"?C.push({type:"text",text:b.content}):Array.isArray(b.content)&&C.push(...b.content)),b.tool_calls&&b.tool_calls.length>0&&b.tool_calls.forEach(g=>{let y={};try{y=JSON.parse(g.function.arguments)}catch{y=g.function.arguments}C.push({type:"tool_use",id:g.id,name:g.function.name,input:y})}),b.thinking&&C.unshift({type:"thinking",thinking:b.thinking.content,signature:b.thinking.signature});let _=s[s.length-1];_&&_.role==="assistant"&&Array.isArray(_.content)?_.content.push(...C):s.push({role:"assistant",content:C.length>0?C:[{type:"text",text:" "}]})}}let a=()=>{let m=n.filter(b=>b?.cache_control).length;for(let b of s)Array.isArray(b.content)&&(m+=b.content.filter(C=>C?.cache_control).length);return m},c=m=>m&&typeof m=="object"?{...m}:{type:"ephemeral"},l=()=>{for(let m=s.length-1;m>=0;m--){let b=s[m]?.content;if(!Array.isArray(b))continue;let C=b.find(_=>_?.cache_control);if(C?.cache_control)return C.cache_control}for(let m=n.length-1;m>=0;m--)if(n[m]?.cache_control)return n[m].cache_control;return{type:"ephemeral"}},d=(m,b)=>{if(!Array.isArray(m?.content)||m.content.some(_=>_?.cache_control))return!1;let C=m.content.find(_=>_&&typeof _=="object"&&!_.cache_control);return C?(C.cache_control=c(b),!0):!1};(()=>{let m=4-a();if(m<=0||s.length===0)return;let b=s,C=l(),_=[];for(let g=b.length-1;g>=0;g--)b[g]?.role!=="user"||!Array.isArray(b[g].content)||_.push(g);for(let g of _){if(m<=0)break;d(b[g],C)&&m--}})();let p={messages:s,model:t.model,max_tokens:t.max_tokens||4096,temperature:t.temperature,stream:t.stream};if(n.length>0){let m=n.some(b=>b?.cache_control);p.system=m?n:n.map(b=>b.text||"").join(`
|
|
112
|
+
`))}}}Q();let me=K();me&&Y.enqueue(me),se="",Y.close()}catch(ae){Y.error(ae)}}})}wrapChatInResponses(e){let n=e?.choices?.[0],r=[],o=[];if(n?.message?.content&&o.push({type:"output_text",text:n.message.content}),r.push({type:"message",role:"assistant",content:o}),Array.isArray(n?.message?.tool_calls))for(let s of n.message.tool_calls)r.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:r,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let n=e.output?.find(d=>d.type==="message"),r=e.output?.find(d=>d.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(d=>({type:"url_citation",url_citation:{url:d.url||"",title:d.title||"",content:"",start_index:d.start_index||0,end_index:d.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let m=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});m&&f.push(m)}else if(p.type==="output_image_base64"){let m=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});m&&f.push(m)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),s=p}else s=d.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.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,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}: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}};import{get_encoding as GC}from"tiktoken";var Xu=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Zu=new Xu(100);$n();import{readFile as ic}from"fs/promises";import{opendir as JC,stat as VC}from"fs/promises";import{join as ac}from"path";import{CLAUDE_PROJECTS_DIR as np,HOME_DIR as rp}from"@wengine-ai/claude-code-router-shared";import{existsSync as ep,mkdirSync as jC,readFileSync as UC,writeFileSync as $C}from"fs";import{join as tp}from"path";import{HOME_DIR as qC}from"@wengine-ai/claude-code-router-shared";var ec=tp(qC,"runtime"),tc=tp(ec,"quota-store.json"),Lr=new Map,Xh=!1,zC=null;function nc(t,e){t&&Lr.set(t,{...e,provider:t,capturedAt:Date.now()})}function rc(t){let e=Lr.get(t);return e?{...e}:void 0}function HC(){return Array.from(Lr.values()).map(t=>({...t}))}function WC(){try{if(!ep(tc))return;let t=JSON.parse(UC(tc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>1440*60*1e3)continue;Lr.set(n.provider,n)}}catch{}}function Zh(){try{if(Lr.size===0)return;ep(ec)||jC(ec,{recursive:!0}),$C(tc,JSON.stringify(Array.from(Lr.values()),null,2),"utf-8")}catch{}}function oc(){Xh||(Xh=!0,WC(),zC=setInterval(Zh,6e4),process.on("exit",Zh))}ei();var En=GC("cl100k_base"),ip=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=En.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=En.encode(s.text).length:s.type==="tool_use"?r+=En.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=En.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=En.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=En.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=En.encode(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=En.encode(o.name+o.description).length),o.input_schema&&(r+=En.encode(JSON.stringify(o.input_schema)).length)}),r},ap=async(t,e)=>{if(t.sessionId){let n=await lp(t.sessionId);if(n){let r=ac(rp,n,"config.json"),o=ac(rp,n,`${t.sessionId}.json`);try{let s=JSON.parse(await ic(o,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}try{let s=JSON.parse(await ic(r,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}}}};function ni(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 up(t){let e=ni(t),n=e.includes("[1m]")||e.endsWith("[1m"),r=e.replace(/\[1m\]|\[1m$/g,""),o=r.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:n};let s=r.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||r.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:n}:{family:null,extended:n}}function KC(t,e){if(!e||!t)return null;let n=ni(t);if(e[t])return e[t];if(e[n])return e[n];let{family:r}=up(t);if(r&&e[r])return e[r];for(let[o,s]of Object.entries(e)){let a=ni(o);if(a&&n.includes(a))return s}return null}function cp(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function op(t){if(!t?.includes(","))return null;let[e,...n]=t.split(","),r=e.trim(),o=n.join(",").trim();return!r||!o?null:{providerName:r,routeModel:o}}function ot(t,e,n,r,o){let s=op(t);if(!s)return t;let{providerName:a,routeModel:c}=s,l=e.find(p=>p.name.toLowerCase()===a.toLowerCase());if(l&&l.enabled===!1)return null;if(o===!0&&r&&!n){let p=Oo(),m=p.getPromotion(a,c,r,e);if(m){let b=op(m);if(b){let C=e.find(y=>y.name.toLowerCase()===b.providerName.toLowerCase()),_=C?.models?.find(y=>String(y).toLowerCase()===b.routeModel.toLowerCase());if(C&&_)return`${C.name},${_}`}p.clear(a,c,r)}}if(!n&&!Qe().isAvailable(a,c))return null;let d=rc(a);if(d){let p=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,m=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(p||m)return null}let f=l?.models?.find(p=>String(p).toLowerCase()===c.toLowerCase());return l&&f?`${l.name},${f}`:t}function jt(t,e,n,r,o){let s=Qe(),a=[n?.[t],r?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let d=ot(l,e);if(d)return d}return null}function QC(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(n=>n.type==="image"||n.type==="image_url"||Array.isArray(n?.content)&&n.content.some(r=>r.type==="image"||r.type==="image_url")))}function YC(t){let e=ni(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(r=>r.test(e))}function XC(t,e,n,r,o,s,a,c){let l=n.longContextThreshold||6e4,d=Math.max(e,cp(o)),f=t.modelFamily;if((s||d>2e5)&&n.extendedContext){let C=ot(n.extendedContext,r,!1,"extendedContext",c);if(C)return t.log.info(`Family: using extended context model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:C,scenarioType:"extendedContext",isFallback:!1};let _=c?jt("extendedContext",r,n.fallback,a,f):null;if(_)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:_,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(d>l&&(n.longContext||n.fallback?.longContext?.length||a?.longContext?.length)){let C=n.longContext?ot(n.longContext,r,!1,"longContext",c):null;if(C)return t.log.info(`Family: using long context model, tokens: ${d}, estimated: ${e}`),{model:C,scenarioType:"longContext",isFallback:!1};let _=c?jt("longContext",r,n.fallback,a,f):null;if(_)return t.log.info(`Family: using long context fallback model, tokens: ${d}, estimated: ${e}`),{model:_,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(C=>C.type?.startsWith("web_search"))&&n.webSearch){let C=ot(n.webSearch,r,!1,"webSearch",c);if(C)return{model:C,scenarioType:"webSearch",isFallback:!1};let _=c?jt("webSearch",r,n.fallback,a,f):null;if(_)return t.log.info("Family: using webSearch fallback model"),{model:_,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&n.think){let C=ot(n.think,r,!1,"think",c);if(C)return{model:C,scenarioType:"think",isFallback:!1};let _=c?jt("think",r,n.fallback,a,f):null;if(_)return t.log.info("Family: using think fallback model"),{model:_,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(n.default){let C=ot(n.default,r,!1,"default",c);if(C)return{model:C,scenarioType:"default",isFallback:!1};let _=c?jt("default",r,n.fallback,a,f):null;if(_)return t.log.info("Family: using default fallback model"),{model:_,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var ZC=async(t,e,n,r)=>{let o=await ap(t,n),s=n.get("providers")||[],a=o||n.get("Router"),c=a?.enableFallback===!0,l=c?a?.fallback||n.get("fallback"):void 0;if(t.body.model.includes(",")){let g=ot(t.body.model,s,!1,"default",c);if(g)return{model:g,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let S=c?jt("default",s,void 0,l):null;if(S)return t.log.info(`Using fallback for explicit model: ${S}`),{model:S,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:d,extended:f}=up(t.body.model),p=a?.families?.[d||""];if(p&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${d}${f?" (1M)":""}`),t.modelFamily=d,t.familyFallback=p.fallback;let g=XC(t,e,p,s,r,f,l,c);if(g)return{model:g.model,scenarioType:g.scenarioType}}let m=KC(t.body.model,a?.models);if(m){let g=ot(m,s,!1,"modelMapping",c);if(g)return t.log.info(`Using mapped model for ${t.body.model}: ${m}`),{model:g,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${m} unavailable (fail pool), skipping`)}let b=Math.max(e,cp(r)),C=a?.extendedContextThreshold||2e5;if(b>C&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${b}, estimated: ${e}, threshold: ${C}`);let g=ot(a.extendedContext,s,!1,"extendedContext",c);if(g)return{model:g,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let S=c?jt("extendedContext",s,void 0,l):null;if(S)return{model:S,scenarioType:"extendedContext"}}let _=a?.longContextThreshold||6e4;if(b>_&&a?.longContext){t.log.info(`Using long context model due to token count: ${b}, estimated: ${e}, threshold: ${_}`);let g=ot(a.longContext,s,!1,"longContext",c);if(g)return{model:g,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let S=c?jt("longContext",s,void 0,l):null;if(S)return{model:S,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let g=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(g)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${g[1]}</CCR-SUBAGENT-MODEL>`,""),{model:g[1],scenarioType:"default"}}if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&a?.background){t.log.info(`Using background model for ${t.body.model}`);let g=ot(a.background,s,!1,"background",c);if(g)return{model:g,scenarioType:"background"};t.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(g=>g.type?.startsWith("web_search"))&&a?.webSearch){let g=ot(a.webSearch,s,!1,"webSearch",c);if(g)return{model:g,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let S=c?jt("webSearch",s,void 0,l):null;if(S)return{model:S,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let g=ot(a.think,s,!1,"think",c);if(g)return{model:g,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let S=c?jt("think",s,void 0,l):null;if(S)return{model:S,scenarioType:"think"}}if(a?.default){let g=ot(a.default,s,!1,"default",c);if(g)return{model:g,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let S=c?jt("default",s,void 0,l):null;if(S)return{model:S,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Fo=async(t,e,n)=>{let{configService:r,event:o}=n;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let C=t.body.metadata.user_id.split("_session_");C.length>1&&(t.sessionId=C[1])}let a=await ap(t,r)||r.get("Router"),c=a?.enableFallback===!0,l=r.get("providers")||[],d=Zu.get(t.sessionId),{messages:f,system:p=[],tools:m}=t.body,b=r.get("REWRITE_SYSTEM_PROMPT");if(b&&p.length>1&&p[1]?.text?.includes("<env>")){let C=await ic(b,"utf-8");p[1].text=`${C}<env>${p[1].text.split("<env>").pop()}`}try{let[C,_]=t.body.model.split(","),y=n.tokenizerService?.getTokenizerConfigForModel(C,_),g;n.tokenizerService?g=(await n.tokenizerService.countTokens({messages:f,system:p,tools:m},y)).tokenCount:g=ip(f,p,m),t.tokenCount=g;let S,w=r.get("CUSTOM_ROUTER_PATH");if(w)try{S=await re(w)(t,r.getAll(),{event:o})}catch(A){t.log.error(`failed to load custom router: ${A.message}`)}if(S)t.scenarioType="default";else{let A=await ZC(t,g,r,d);S=A.model,t.scenarioType=A.scenarioType}if(a?.image&&S!==a.image&&QC(t)&&!YC(S)){let A=ot(a.image,l,!1,"image",c);A?(t.log.info(`Using image model fallback for ${S}`),S=A,t.scenarioType="image"):(t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${S}`),t.scenarioType="image")}t.body.model=S}catch(C){t.log.error(`Error in router middleware: ${C.message}`),t.body.model=a?.default,t.scenarioType="default"}},kn=new Map,sp=1e3;function sc(){if(kn.size<=sp)return;let t=[...kn.keys()].slice(0,kn.size-sp);for(let e of t)kn.delete(e)}var lp=async t=>{if(kn.has(t)){let e=kn.get(t);return!e||e===""?null:e}try{let e=await JC(np),n=[];for await(let s of e)s.isDirectory()&&n.push(s.name);let r=n.map(async s=>{let a=ac(np,s,`${t}.jsonl`);try{return(await VC(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(r);for(let s of o)if(s)return kn.set(t,s),sc(),s;return kn.set(t,""),sc(),null}catch(e){return console.error("Error searching for project by session:",e),kn.set(t,""),sc(),null}};var ew=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;function dp(t){let e=[],n=Array.isArray(t.input)?t.input:[t.input];for(let r of n)if(r.type==="function_call")e.push({role:"assistant",tool_calls:[{id:r.call_id,type:"function",function:{name:r.name,arguments:r.arguments||"{}"}}]});else if(r.type==="function_call_output")e.push({role:"tool",tool_call_id:r.call_id,content:typeof r.output=="string"?r.output:JSON.stringify(r.output)});else if(r.type==="reasoning"){let o=Array.isArray(r.summary)?r.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
113
|
+
`):"";o&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
|
|
114
|
+
${o}`}],_reasoningItem:!0})}else if(r.role){let o=r.content;Array.isArray(o)&&(o=o.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:r.role,content:o})}t.messages=e,delete t.input,t.instructions&&typeof t.instructions=="string"&&(t.system=t.instructions,delete t.instructions),Array.isArray(t.tools)&&(t.tools=t.tools.filter(r=>r&&typeof r=="object").map(r=>r.type==="function"&&r.name&&!r.function?{type:"function",function:{name:r.name,description:r.description||"",parameters:r.parameters||{type:"object",properties:{}}}}:r.function?.name?r:r.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),t.reasoning&&typeof t.reasoning=="object"&&(t.reasoning={enabled:!0,effort:t.reasoning.effort}),delete t.store,delete t.previous_response_id,delete t.include}async function tw(t,e,n,r){let o=t.body;r.endPoint==="/v1/responses"&&o?.input&&!o?.messages&&dp(o),r.endPoint==="/v1/responses"&&!t.provider&&typeof o?.model=="string"&&ew.test(o.model)&&await Fo(t,e,{configService:n.configService,tokenizerService:n.tokenizerService});let s=t.provider;if(!s&&o?.model){let d=o.model.split(",");d.length>1&&(s=d[0],o.model=d.slice(1).join(","))}let a=s?n.providerService.getProvider(s):void 0;if(!a&&o?.model){let d=n.providerService.resolveModelRoute(o.model);d&&(a=d.provider,o.model=d.targetModel)}if(!a&&o?.model){let f=n.configService.get("Router")?.default;if(f&&f.includes(",")){let[p,...m]=f.split(","),b=n.providerService.getProvider(p);b&&(a=b,o.model=m.join(","))}}if(t.originalModel||(t.originalModel=o?.model),!a)throw He(`Provider '${s}' not found`,404,"provider_not_found");t.provider=a.name||s;let c=ow(t),l=r.endPoint==="/v1/messages"&&c;c&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),t.isCodexOnMessagesEndpoint=l,t.codexDetected=c;try{r.endPoint==="/v1/responses"&&o.input&&!o.messages&&dp(o);let{requestBody:d,config:f,bypass:p}=await fp(o,a,r,t.headers,{req:t});if(d?.messages&&!p&&!t.isTargetAnthropic){let _=d.messages,y=new Set,g=[],S=[];for(let w of _){if(w?.role!=="system"){S.push(w);continue}let A=JSON.stringify(w.content??"");y.has(A)||(y.add(A),g.push(w))}g.length>0&&S.length>0&&(d.messages=[...S,...g])}let m=await hp(d,f,a,n,p,r,{req:t});try{a?.baseUrl&&m?.headers&&Po(s,a.baseUrl,m.headers)}catch{}let b=await pp(d,m,a,r,p,{req:t,isCodexOnMessagesEndpoint:l});if(o.stream&&b?.body){let _=b.body.getReader(),y=await _.read();if(y.done)throw _.releaseLock(),He(`Provider returned empty streaming response from ${s}`,400,"provider_response_error");let g=new TextDecoder().decode(y.value);if(g.includes("event: error")){_.releaseLock();let A=g.length<500?g:g.slice(0,500);throw He(`Provider ${s} returned error in SSE stream: ${A}`,400,"provider_response_error")}if(g.split(`
|
|
115
|
+
`).filter(A=>A.startsWith("data:")&&A.trim().length>5).length===0){_.releaseLock();let A=g.length<500?g:g.slice(0,500);throw He(`Provider ${s} returned streaming response with no SSE data lines: ${A}`,400,"provider_response_error")}let w=new ReadableStream({start:A=>{A.enqueue(y.value);let v=()=>{_.read().then(({done:R,value:$})=>{R?A.close():(A.enqueue($),v())}).catch(R=>A.error(R))};v()},cancel:()=>{_.cancel()}});b=new Response(w,{headers:b.headers,status:b.status,statusText:b.statusText})}let C=mp(b,e,o,n);try{let _=o.model||t.originalModel;s&&_&&Qe().recordSuccess(s,_)}catch{}return C}catch(d){let f=await nw(t,e,n,r,d);if(f)return f;throw d}}async function nw(t,e,n,r,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=n.configService.get("fallback"),d=Qe(),f=t.provider||"",p=t.body.model||"",m=new Set,b=o?.statusCode===429||o?.isRateLimit===!0||o?.rawBody&&ri(o.rawBody)||o?.message&&ri(o.message);if(f&&p&&(b?(d.markRateLimited(f,p,120,o?.message),t.log.warn(`Primary model ${f},${p} rate-limited, will try fallbacks`)):d.recordFailure(f,p,o?.message),m.add(`${f},${p}`),n.recordUsage?.({provider:f,model:p,originalModel:t.originalModel||p,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})),!n.configService.get("Router")?.enableFallback)return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let _=S=>{let[w,...A]=S.split(","),v=w?.trim(),R=A.join(",").trim();return!v||!R?null:{provider:v,model:R,key:`${v},${R}`}},y=[];if(c){let S=a?.[s];Array.isArray(S)&&S.length>0?y.push({name:`${c}/${s}`,models:S}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&y.push({name:`global/${s}`,models:l[s]}),y.length===0&&s!=="image"&&t.body?.messages?.some(A=>A.role==="user"&&Array.isArray(A.content)&&A.content.some(v=>v.type==="image"||v.type==="image_url"||Array.isArray(v?.content)&&v.content.some(R=>R.type==="image"||R.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(t.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),y.push({name:"global/image (auto-detected)",models:l.image})),y.length===0)return null;let g=y.reduce((S,w)=>S+w.models.length,0);t.log.warn(`Request failed for ${s}, trying ${g} fallback models across ${y.length} fallback stage(s)`);for(let S of y){t.log.info(`Trying ${S.name} fallback stage with ${S.models.length} models`);for(let w of S.models){let A=_(w);if(!A){t.log.warn(`Fallback model '${w}' is invalid, skipping`);continue}if(m.has(A.key))continue;m.add(A.key);let v=A.provider,R=A.model;try{if(!d.isAvailable(v,R)){t.log.warn(`Fallback model ${w} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${w}`);let $={...t.body};$.model=R;let V={...t,provider:v,body:$},P=n.providerService.getProvider(v);if(!P){t.log.warn(`Fallback provider '${v}' not found, skipping`);continue}if(P.enabled===!1){t.log.warn(`Fallback provider '${v}' is disabled, skipping`);continue}let{requestBody:Q,config:z,bypass:K}=await fp($,P,r,t.headers,{req:V}),Y=await hp(Q,z,P,n,K,r,{req:V});try{P?.baseUrl&&Y?.headers&&Po(v,P.baseUrl,Y.headers)}catch{}let ee=await pp(Q,Y,P,r,K,{req:V,isCodexOnMessagesEndpoint:t.isCodexOnMessagesEndpoint||!1});return t.log.info(`Fallback model ${w} succeeded`),d.recordSuccess(v,R),f&&p&&(Oo().promote(f,p,s,v,R),t.log.info(`Promoted fallback model ${v},${R} for ${f},${p}:${s}`),b?t.log.info(`Rate-limited original model ${f},${p} already marked unavailable with cooldown`):(d.forceOpen(f,p,o?.message),t.log.info(`Marked original model ${f},${p} as unavailable`))),t.provider=v,t.body=$,mp(ee,e,$,n)}catch($){d.recordFailure(v,R,$.message),t.log.warn(`Fallback model ${A.key} failed: ${$.message}`),n.recordUsage?.({provider:v,model:R,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:$.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream,req:t});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function fp(t,e,n,r,o){let s=JSON.parse(JSON.stringify(t)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let d=0;d<a.length;d++){let f=a[d],p=typeof f=="string"?f:f?.text??"";if(p.includes("cch=")){let m=p.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof f=="string"?a[d]=m:typeof f?.text=="string"&&(f.text=m)}}let c={},l=!1;if(l=rw(e,n,t),l&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],c.headers=r),!l&&typeof n.transformRequestOut=="function"){let d=await n.transformRequestOut(s);d.body?(s=d.body,c=d.config||{}):s=d}if(!l&&e.transformer?.use?.length)for(let d of e.transformer.use){if(!d||typeof d.transformRequestIn!="function")continue;let f=await d.transformRequestIn(s,e,o);f.body?(s=f.body,c={...c,...f.config}):s=f}if(!l&&e.transformer?.[t.model]?.use?.length)for(let d of e.transformer[t.model].use)!d||typeof d.transformRequestIn!="function"||(s=await d.transformRequestIn(s,e,o));return{requestBody:s,config:c,bypass:l}}function rw(t,e,n){return e.endPoint==="/v1/chat/completions"&&Array.isArray(n?.system)?!1:t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}function ow(t){let e=t.headers||{},n=e["x-anthropic-billing-header"]||"";if(typeof n=="string"&&n.includes("cc_version="))return!1;let r=e["user-agent"]||"";if(typeof r=="string"&&/codex/i.test(r))return!0;let o=t.pathname||t.url||"";if(typeof o=="string"&&o.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=t.originalModel||t.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function hp(t,e,n,r,o,s,a){let c=e.url||new URL(n.baseUrl);if(!e.TIMEOUT){let f=r.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(o&&typeof s.auth=="function"){let f=await s.auth(t,n);if(f.body){t=f.body;let p=e.headers||{};f.config?.headers&&(p={...p,...f.config.headers},delete p.host,delete f.config.headers),e={...e,...f.config,headers:p}}else t=f}let l={Authorization:`Bearer ${n.apiKey}`,...e?.headers||{}};for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];Xs(r.configService)&&Lh(r.log,a.req.id,{url:String(c),headers:l,body:t});let d=await Fh(c,t,{httpsProxy:r.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,r.log);if(!d.ok){let f=await d.text();r.log.error(`[provider_response_error] Error from provider(${n.name},${t.model}: ${d.status}): ${f}`);let p=He(`Error from provider(${n.name},${t.model}: ${d.status}): ${f}`,d.status,"provider_response_error");throw p.isRateLimit=d.status===429||ri(f),p.rawBody=f,p}if(d.ok){let f=d.headers.get("content-type")||"",p=t.stream===!0;if(r.log.info(`[hidden-error-check] provider=${n.name} model=${t.model} stream=${t.stream} isStreamRequest=${p} contentType=${f} ok=${d.ok} status=${d.status} hasBody=${!!d.body}`),!p||f.includes("application/json")){let m=d.clone(),b="";try{if(b=await m.text(),!b||b.trim()==="")throw new SyntaxError("Empty JSON body");let C=JSON.parse(b);if(C&&typeof C=="object"&&C.error&&(typeof C.error=="string"||typeof C.error=="object"&&Object.keys(C.error).length>0)){r.log.error(`[provider_response_error] Hidden error from provider(${n.name},${t.model}: ${d.status}): ${b}`);let y=ri(b),g=He(`Error from provider(${n.name},${t.model}: ${d.status}): ${b}`,400,"provider_response_error");throw g.isRateLimit=y,g.rawBody=b,g}}catch(C){if(C instanceof SyntaxError){r.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${n.name},${t.model}: 200): "${b}"`);let _=He(`API returned an empty or malformed response (HTTP 200) from ${n.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw _.rawBody=b,_}throw C}}}if(!t.stream&&Xs(r.configService)){let p=await d.clone().text();jh(r.log,a.req.id,{status:d.status,headers:Object.fromEntries(d.headers.entries()),body:p})}return d}async function pp(t,e,n,r,o,s){let a=e;if(!o&&n.transformer?.use?.length)for(let c of Array.from(n.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&n.transformer?.[t.model]?.use?.length)for(let c of Array.from(n.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformResponseIn&&(s.provider||(s.provider=n),a=await r.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Mr().transformResponseIn(a,{...s,provider:n})}catch(c){console.error("Failed to apply Responses API conversion for codex client:",c)}return a}function mp(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&Xs(r.configService)){let[s,a]=t.body.tee(),c=Nh(r.configService);return Uh(s,r.log,e.request.id,c),e.send(a)}return e.send(t.body)}else return t.json()}var uc=async t=>{t.get("/",async()=>({message:"LLMs API",version:$h})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Qe().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>tw(r,o,t,n));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(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=n.body;if(!o?.trim())throw He("Provider name is required",400,"invalid_request");if(!s||!sw(s))throw He("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw He("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw He("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw He(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw He("Provider not found",404,"provider_not_found");return r}),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(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw He("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw He("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(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw He("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function ri(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function sw(t){try{return new URL(t),!0}catch{return!1}}var jr=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;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(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.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(n.transformer[o]?.use)&&(r[o]={use:n.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:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],quotaToken:n.quota_token,transformer:n.transformer?r:void 0,cacheMode:n.cache_mode||"exclusive",enabled:n.enabled!==!1,wakeupEnabled:n.wakeup_enabled===!0,wakeupTime:n.wakeup_time||"06:00",wakeupModel:n.wakeup_model||""}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}registerProvider(e){let n={...e,enabled:e.enabled!==!1,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,c={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){let r=this.providers.get(e);if(!r)return!1;r.enabled=n;let o=this.configService.get("providers");if(o&&Array.isArray(o)){let s=o.find(a=>a.name===e);s&&(s.enabled=n)}return!0}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var Ye=[];for(let t=0;t<256;++t)Ye.push((t+256).toString(16).slice(1));function gp(t,e=0){return(Ye[t[e+0]]+Ye[t[e+1]]+Ye[t[e+2]]+Ye[t[e+3]]+"-"+Ye[t[e+4]]+Ye[t[e+5]]+"-"+Ye[t[e+6]]+Ye[t[e+7]]+"-"+Ye[t[e+8]]+Ye[t[e+9]]+"-"+Ye[t[e+10]]+Ye[t[e+11]]+Ye[t[e+12]]+Ye[t[e+13]]+Ye[t[e+14]]+Ye[t[e+15]]).toLowerCase()}import{randomFillSync as iw}from"crypto";var si=new Uint8Array(256),oi=si.length;function cc(){return oi>si.length-16&&(iw(si),oi=0),si.slice(oi,oi+=16)}import{randomUUID as aw}from"crypto";var lc={randomUUID:aw};function uw(t,e,n){if(lc.randomUUID&&!e&&!t)return lc.randomUUID();t=t||{};let r=t.random??t.rng?.()??cc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return gp(r)}var Ut=uw;var yp=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var _p=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function cw(t){return t.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function bp(t){let e=[],n=[],r=m=>{if(typeof m=="string"){n.push({type:"text",text:m});return}Array.isArray(m)&&m.forEach(b=>{if(typeof b=="string"){n.push({type:"text",text:b});return}b&&typeof b=="object"&&b.type==="text"&&b.text&&n.push({...b})})},o=()=>{let m=new Map;for(let b=0;b<n.length;b++){let C=n[b],_=C?.text??JSON.stringify(C),y=m.get(_);if(y===void 0){m.set(_,b);continue}!n[y]?.cache_control&&C?.cache_control&&(n[y]=C),n.splice(b,1),b--}};t.messages.forEach(m=>{m.role==="system"?r(m.content):e.push(m)}),o();let s=[];for(let m=0;m<e.length;m++){let b=e[m];if(b.role==="tool"){let C=b.content;try{typeof b.content=="string"&&(C=JSON.parse(b.content))}catch{}C!=null&&typeof C!="object"&&typeof C!="string"&&(C=String(C));let _={type:"tool_result",tool_use_id:b.tool_call_id,content:C};b.cache_control&&(_.cache_control=b.cache_control);let y=s[s.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(_):s.push({role:"user",content:[_]})}else if(b.role==="user"){let C=[];typeof b.content=="string"?C.push({type:"text",text:b.content}):Array.isArray(b.content)&&b.content.forEach(y=>{y&&typeof y=="object"&&y.type==="image_url"&&y.image_url?.url?C.push({type:"image",source:{type:"base64",media_type:y.media_type||"image/jpeg",data:y.image_url.url.split(",")[1]||y.image_url.url}}):C.push(y)});let _=s[s.length-1];_&&_.role==="user"&&Array.isArray(_.content)?_.content.push(...C):s.push({role:"user",content:C.length>0?C:[{type:"text",text:" "}]})}else if(b.role==="assistant"){let C=[];b.content&&(typeof b.content=="string"?C.push({type:"text",text:b.content}):Array.isArray(b.content)&&C.push(...b.content)),b.tool_calls&&b.tool_calls.length>0&&b.tool_calls.forEach(y=>{let g={};try{g=JSON.parse(y.function.arguments)}catch{g=y.function.arguments}C.push({type:"tool_use",id:y.id,name:y.function.name,input:g})}),b.thinking&&C.unshift({type:"thinking",thinking:b.thinking.content,signature:b.thinking.signature});let _=s[s.length-1];_&&_.role==="assistant"&&Array.isArray(_.content)?_.content.push(...C):s.push({role:"assistant",content:C.length>0?C:[{type:"text",text:" "}]})}}let a=()=>{let m=n.filter(b=>b?.cache_control).length;for(let b of s)Array.isArray(b.content)&&(m+=b.content.filter(C=>C?.cache_control).length);return m},c=m=>m&&typeof m=="object"?{...m}:{type:"ephemeral"},l=()=>{for(let m=s.length-1;m>=0;m--){let b=s[m]?.content;if(!Array.isArray(b))continue;let C=b.find(_=>_?.cache_control);if(C?.cache_control)return C.cache_control}for(let m=n.length-1;m>=0;m--)if(n[m]?.cache_control)return n[m].cache_control;return{type:"ephemeral"}},d=(m,b)=>{if(!Array.isArray(m?.content)||m.content.some(_=>_?.cache_control))return!1;let C=m.content.find(_=>_&&typeof _=="object"&&!_.cache_control);return C?(C.cache_control=c(b),!0):!1};(()=>{let m=4-a();if(m<=0||s.length===0)return;let b=s,C=l(),_=[];for(let y=b.length-1;y>=0;y--)b[y]?.role!=="user"||!Array.isArray(b[y].content)||_.push(y);for(let y of _){if(m<=0)break;d(b[y],C)&&m--}})();let p={messages:s,model:t.model,max_tokens:t.max_tokens||4096,temperature:t.temperature,stream:t.stream};if(n.length>0){let m=n.some(b=>b?.cache_control);p.system=m?n:n.map(b=>b.text||"").join(`
|
|
114
116
|
|
|
115
|
-
`)}return t.tools&&t.tools.length>0&&(p.tools=
|
|
116
|
-
`));let l=s.content.filter(f=>f.type==="tool_use"&&f.id);l.length&&(a.tool_calls=l.map(f=>({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input||{})}})));let d=s.content.find(f=>f.type==="thinking");d&&(a.thinking={content:d.thinking,signature:d.signature}),n.push(a)}return}}});let o={messages:n,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:
|
|
117
|
-
data: ${JSON.stringify(
|
|
117
|
+
`)}return t.tools&&t.tools.length>0&&(p.tools=cw(t.tools),t.tool_choice&&(t.tool_choice==="auto"?p.tool_choice={type:"auto"}:t.tool_choice==="any"||t.tool_choice==="required"?p.tool_choice={type:"any"}:typeof t.tool_choice=="string"?p.tool_choice={type:"tool",name:t.tool_choice}:typeof t.tool_choice=="object"&&t.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:t.tool_choice.function.name}))),p}var ii=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n){let r={};return this.useBearer?(r.authorization=`Bearer ${n.apiKey}`,r["x-api-key"]=void 0):(r["x-api-key"]=n.apiKey,r.authorization=void 0),{body:e,config:{headers:r}}}async transformRequestOut(e){let n=[];if(e.system){if(typeof e.system=="string")n.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}));n.push({role:"system",content:s})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(s=>{if(s.role==="system"){n.push({role:"system",content:s.content});return}if(s.role==="user"||s.role==="assistant"){if(typeof s.content=="string"){n.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 d={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};n.push(d)});let c=s.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&n.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?_p(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(f=>f.type==="text"&&f.text);c.length&&(a.content=c.map(f=>f.text).join(`
|
|
118
|
+
`));let l=s.content.filter(f=>f.type==="tool_use"&&f.id);l.length&&(a.tool_calls=l.map(f=>({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input||{})}})));let d=s.content.find(f=>f.type==="thinking");d&&(a.thinking={content:d.thinking,signature:d.signature}),n.push(a)}return}}});let o={messages:n,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:yp(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 transformRequestIn(e,n,r){if(!this.isAnthropicMessagesEndpoint(n.baseUrl))return e;r&&r.req&&(r.req.isTargetAnthropic=!0);let o=bp(e),s={};return this.useBearer?(s.authorization=`Bearer ${n.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=n.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:o,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,n){if(n?.req?.isTargetAnthropic)return e;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,n);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,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema}}))}async convertOpenAIStreamToAnthropic(e,n){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",d=!1,f=!1,p=!1,m=new Map,b=new Map,C=0,_=0,y=0,g=!1,S=!1,w=0,A=-1,v=()=>{let P=w;return w++,P},R=P=>{if(!g)try{o.enqueue(P);let Q=new TextDecoder().decode(P);this.logger.debug({reqId:n.req.id,data:Q,type:"send data"})}catch(Q){if(Q instanceof TypeError&&Q.message.includes("Controller is already closed"))g=!0;else throw this.logger.debug({reqId:n.req.id,error:Q instanceof Error?Q.message:String(Q),type:"send data error"}),Q}},$=()=>{if(!g)try{if(!d){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),o.close(),g=!0;return}if(A>=0){let Q={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
|
|
119
|
+
data: ${JSON.stringify(Q)}
|
|
118
120
|
|
|
119
|
-
`)),
|
|
121
|
+
`)),A=-1}if(c)R(s.encode(`event: message_delta
|
|
120
122
|
data: ${JSON.stringify(c)}
|
|
121
123
|
|
|
122
|
-
`)),c=null;else{let
|
|
123
|
-
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:
|
|
124
|
+
`)),c=null;else{let Q=n?.req?.tokenCount||0;R(s.encode(`event: message_delta
|
|
125
|
+
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:Q,output_tokens:0,cache_read_input_tokens:0}})}
|
|
124
126
|
|
|
125
|
-
`))}let P={type:"message_stop"};
|
|
127
|
+
`))}let P={type:"message_stop"};R(s.encode(`event: message_stop
|
|
126
128
|
data: ${JSON.stringify(P)}
|
|
127
129
|
|
|
128
|
-
`)),o.close(),
|
|
129
|
-
`);
|
|
130
|
-
data: ${JSON.stringify(
|
|
130
|
+
`)),o.close(),g=!0}catch(P){if(P instanceof TypeError&&P.message.includes("Controller is already closed"))g=!0;else throw P}},V=null;try{V=e.getReader();let P=new TextDecoder,Q="";for(;!g;){let{done:z,value:K}=await V.read();if(z)break;Q+=P.decode(K,{stream:!0});let Y=Q.split(`
|
|
131
|
+
`);Q=Y.pop()||"";for(let ee of Y){if(g||p)break;if(!ee.startsWith("data:"))continue;let ae=ee.slice(5).trim();if(this.logger.debug({reqId:n.req.id,type:"recieved data",data:ae}),ae!=="[DONE]")try{let se=JSON.parse(ae);if(C++,this.logger.debug({reqId:n.req.id,response:se,tppe:"Original Response"}),se.error){n?.req&&(n.req.sseError=se.error);let G={type:"error",message:{type:"api_error",message:JSON.stringify(se.error)}};R(s.encode(`event: error
|
|
132
|
+
data: ${JSON.stringify(G)}
|
|
131
133
|
|
|
132
|
-
`));continue}if(l=
|
|
134
|
+
`));continue}if(l=se.model||l,!d&&!g&&!p){d=!0;let G=n?.req?.tokenCount||0,Z={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:G,output_tokens:0}}};R(s.encode(`event: message_start
|
|
133
135
|
data: ${JSON.stringify(Z)}
|
|
134
136
|
|
|
135
|
-
`))}let me=
|
|
137
|
+
`))}let me=se.choices?.[0];if(se.usage){let G=se.usage?.prompt_tokens_details?.cached_tokens||0,ie=(se.usage?.prompt_tokens||0)-G;this.logger?.info({debug_log:!0,reqId:n.req.id,phase:"anthropic_transformer_usage",providerUsage:se.usage,mappedUsage:{input_tokens:ie,output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:G},choicesLength:Array.isArray(se.choices)?se.choices.length:void 0,finishReason:me?.finish_reason}),c?c.usage={input_tokens:ie,output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:G}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:ie,output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:G}}}if(!me)continue;if(me?.delta?.thinking&&!g&&!p&&!f){if(!S){let G=v(),Z={type:"content_block_start",index:G,content_block:{type:"thinking",thinking:""}};R(s.encode(`event: content_block_start
|
|
136
138
|
data: ${JSON.stringify(Z)}
|
|
137
139
|
|
|
138
|
-
`)),
|
|
139
|
-
data: ${JSON.stringify(
|
|
140
|
+
`)),A=G,S=!0}if(me.delta.thinking.signature){let G={type:"content_block_delta",index:A,delta:{type:"signature_delta",signature:me.delta.thinking.signature}};R(s.encode(`event: content_block_delta
|
|
141
|
+
data: ${JSON.stringify(G)}
|
|
140
142
|
|
|
141
|
-
`));let Z={type:"content_block_stop",index:
|
|
143
|
+
`));let Z={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
|
|
142
144
|
data: ${JSON.stringify(Z)}
|
|
143
145
|
|
|
144
|
-
`)),
|
|
145
|
-
data: ${JSON.stringify(
|
|
146
|
+
`)),A=-1}else if(me.delta.thinking.content){let G={type:"content_block_delta",index:A,delta:{type:"thinking_delta",thinking:me.delta.thinking.content||""}};R(s.encode(`event: content_block_delta
|
|
147
|
+
data: ${JSON.stringify(G)}
|
|
146
148
|
|
|
147
|
-
`))}}if(me?.delta?.content&&!
|
|
149
|
+
`))}}if(me?.delta?.content&&!g&&!p){if(_++,A>=0&&!f){let Z={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
|
|
148
150
|
data: ${JSON.stringify(Z)}
|
|
149
151
|
|
|
150
|
-
`)),
|
|
152
|
+
`)),A=-1}if(!f&&!p){f=!0;let G=v(),Z={type:"content_block_start",index:G,content_block:{type:"text",text:""}};R(s.encode(`event: content_block_start
|
|
151
153
|
data: ${JSON.stringify(Z)}
|
|
152
154
|
|
|
153
|
-
`)),
|
|
154
|
-
data: ${JSON.stringify(
|
|
155
|
+
`)),A=G}if(!g&&!p){let G={type:"content_block_delta",index:A,delta:{type:"text_delta",text:me.delta.content}};R(s.encode(`event: content_block_delta
|
|
156
|
+
data: ${JSON.stringify(G)}
|
|
155
157
|
|
|
156
|
-
`))}}if(me?.delta?.annotations?.length&&!
|
|
157
|
-
data: ${JSON.stringify(
|
|
158
|
+
`))}}if(me?.delta?.annotations?.length&&!g&&!p){if(A>=0&&f){let G={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
|
|
159
|
+
data: ${JSON.stringify(G)}
|
|
158
160
|
|
|
159
|
-
`)),
|
|
161
|
+
`)),A=-1,f=!1}me?.delta?.annotations.forEach(G=>{let Z=v(),ie={type:"content_block_start",index:Z,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Ut()}`,content:[{type:"web_search_result",title:G.url_citation.title,url:G.url_citation.url}]}};R(s.encode(`event: content_block_start
|
|
160
162
|
data: ${JSON.stringify(ie)}
|
|
161
163
|
|
|
162
|
-
`));let Ue={type:"content_block_stop",index:Z};
|
|
164
|
+
`));let Ue={type:"content_block_stop",index:Z};R(s.encode(`event: content_block_stop
|
|
163
165
|
data: ${JSON.stringify(Ue)}
|
|
164
166
|
|
|
165
|
-
`)),
|
|
167
|
+
`)),A=-1})}if(me?.delta?.tool_calls&&!g&&!p){y++;let G=new Set;for(let Z of me.delta.tool_calls){if(g)break;let ie=Z.index??0;if(G.has(ie))continue;if(G.add(ie),!b.has(ie)){if(A>=0){let Oe={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
|
|
166
168
|
data: ${JSON.stringify(Oe)}
|
|
167
169
|
|
|
168
|
-
`)),
|
|
170
|
+
`)),A=-1}let Ae=v();b.set(ie,Ae);let J=Z.id||`call_ccr_${ie}`,ce=Z.function?.name||`tool_${ie}`,te={type:"content_block_start",index:Ae,content_block:{type:"tool_use",id:J,name:ce,input:{}}};R(s.encode(`event: content_block_start
|
|
169
171
|
data: ${JSON.stringify(te)}
|
|
170
172
|
|
|
171
|
-
`)),
|
|
172
|
-
data: ${JSON.stringify(
|
|
173
|
+
`)),A=Ae;let ve={id:J,name:ce,arguments:"",contentBlockIndex:Ae};m.set(ie,ve)}else if(Z.id&&Z.function?.name){let Ae=m.get(ie);Ae.id.startsWith("call_")&&Ae.name.startsWith("tool_")&&(Ae.id=Z.id,Ae.name=Z.function.name)}if(Z.function?.arguments&&!g&&!p){let Ae=b.get(ie);if(Ae===void 0)continue;let J=m.get(ie);J&&(J.arguments+=Z.function.arguments);try{let ce={type:"content_block_delta",index:Ae,delta:{type:"input_json_delta",partial_json:Z.function.arguments}};R(s.encode(`event: content_block_delta
|
|
174
|
+
data: ${JSON.stringify(ce)}
|
|
173
175
|
|
|
174
|
-
`))}catch{try{let
|
|
176
|
+
`))}catch{try{let ce=Z.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),te={type:"content_block_delta",index:Ae,delta:{type:"input_json_delta",partial_json:ce}};R(s.encode(`event: content_block_delta
|
|
175
177
|
data: ${JSON.stringify(te)}
|
|
176
178
|
|
|
177
|
-
`))}catch(
|
|
178
|
-
data: ${JSON.stringify(
|
|
179
|
+
`))}catch(ce){console.error(ce)}}}}}if(me?.finish_reason&&!g&&!p){if(_===0&&y===0&&console.error("Warning: No content in the stream response!"),A>=0){let G={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
|
|
180
|
+
data: ${JSON.stringify(G)}
|
|
179
181
|
|
|
180
|
-
`)),
|
|
181
|
-
`)||"",f={id:r.responseId,choices:[{finish_reason:r.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:d,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:r.modelVersion,object:"chat.completion",usage:{completion_tokens:r.usageMetadata?.candidatesTokenCount||0,prompt_tokens:r.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:r.usageMetadata?.cachedContentTokenCount||0},total_tokens:r.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:r.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(f),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=!1,a=!1,c=!1,l="",d=0,f=-1,p=new ReadableStream({async start(m){let b=async(g
|
|
182
|
+
`)),A=-1}if(!g){let Z={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[me.finish_reason]||"end_turn",ie=se.usage?.prompt_tokens_details?.cached_tokens||0,Ae=(se.usage?.prompt_tokens||0)-ie;c={type:"message_delta",delta:{stop_reason:Z,stop_sequence:null},usage:{input_tokens:Ae,output_tokens:se.usage?.completion_tokens||0,cache_read_input_tokens:ie}}}break}}catch(se){this.logger?.error(`parseError: ${se.name} message: ${se.message} stack: ${se.stack} data: ${ae}`)}}}$()}catch(P){if(!g)try{o.error(P)}catch(Q){console.error(Q)}}finally{if(V)try{V.releaseLock()}catch(P){console.error(P)}}},cancel:o=>{this.logger.debug({reqId:n.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message.annotations){let l=`srvtoolu_${Ut()}`;o.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:l,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(l=>{let d={};try{let f=l.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:l.function.arguments||""}}o.push({type:"tool_use",id:l.id,name:l.function.name,input:d})}),r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,a=(e.usage?.prompt_tokens||0)-s,c={id:e.id?.startsWith("msg_")?e.id:`msg_${Ut().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":r.finish_reason==="length"?"max_tokens":r.finish_reason==="tool_calls"?"tool_use":r.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:n.req.id,result:c},"Conversion complete, final Anthropic response"),c}catch{throw He(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Ur={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function lw(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(Ur).includes(r)?r:Ur.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(Ur).includes(o)?o:Ur.TYPE_UNSPECIFIED})}}}function Io(t){let e={},n=["items"],r=["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)&&lw(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(Ur).includes(l)?l:Ur.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=Io(c);else if(r.includes(a)){let l=[];for(let d of c){if(d.type=="null"){e.nullable=!0;continue}l.push(Io(d))}e[a]=l}else if(o.includes(a)){let l={};for(let[d,f]of Object.entries(c))l[d]=Io(f);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function dw(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=Io(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Io(e.response));return t}function ai(t){let e=[],n=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));n?.length&&e.push(dw({functionDeclarations:n})),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 d;l.role==="assistant"?d="model":(["user","system"].includes(l.role),d="user");let f=[];if(typeof l.content=="string"){let p={text:l.content};l.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),f.push(p)}else Array.isArray(l.content)?f.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?f.push({text:l.content.text}):f.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&f.push(...l.tool_calls.map(p=>{let m={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return l.thinking?.signature&&(m.thoughtSignature=l.thinking.signature),m})),f.length===0&&f.push({text:""}),o.push({role:d,parts:f}),d==="model"&&l.tool_calls){let p=l.tool_calls.map(m=>{let b=s.find(C=>C.tool_call_id===m.id);return{functionResponse:{name:m?.function?.name,response:{result:b?.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],d,f=t.reasoning.max_tokens;typeof f<"u"&&(f>=l[0]&&f<=l[1]?d=f:f<l[0]?d=l[0]:f>l[1]&&(d=l[1]),a.thinkingConfig.thinkingBudget=d)}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 ui(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:r,max_tokens:o,temperature:s,stream:a,tool_choice:c};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?l.messages.push({role:"user",content:d}):typeof d.text=="string"?l.messages.push({role:"user",content:d.text||null}):d.role==="user"?l.messages.push({role:"user",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):d.role==="model"&&l.messages.push({role:"assistant",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(n)&&(l.tools=[],n.forEach(d=>{Array.isArray(d.functionDeclarations)&&d.functionDeclarations.forEach(f=>{l.tools.push({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})})})),l}async function ci(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json();n?.debug({response:r},`${e} response:`);let o="",s="",a=r.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||{})}}))||[],d=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
|
|
183
|
+
`)||"",f={id:r.responseId,choices:[{finish_reason:r.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:d,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:r.modelVersion,object:"chat.completion",usage:{completion_tokens:r.usageMetadata?.candidatesTokenCount||0,prompt_tokens:r.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:r.usageMetadata?.cachedContentTokenCount||0},total_tokens:r.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:r.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(f),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=!1,a=!1,c=!1,l="",d=0,f=-1,p=new ReadableStream({async start(m){let b=async(y,g)=>{if(y.startsWith("data: ")){let S=y.slice(6).trim();if(S){n?.debug({chunkStr:S},`${e} chunk:`);try{let w=JSON.parse(S);if(!w.candidates||!w.candidates[0]){n?.debug({chunkStr:S},"Invalid chunk structure");return}let A=w.candidates[0],v=A.content?.parts||[];v.filter(P=>P.text&&P.thought===!0).forEach(P=>{c||(c=!0);let Q={choices:[{delta:{role:"assistant",content:null,thinking:{content:P.text}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(Q)}
|
|
182
184
|
|
|
183
|
-
`))});let v
|
|
185
|
+
`))});let R=v.find(P=>P.thoughtSignature)?.thoughtSignature;if(R&&!s){if(!c){let Q={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(Q)}
|
|
184
186
|
|
|
185
|
-
`))}let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:
|
|
187
|
+
`))}let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:R}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(g.enqueue(o.encode(`data: ${JSON.stringify(P)}
|
|
186
188
|
|
|
187
|
-
`)),s=!0,d++,l){let
|
|
189
|
+
`)),s=!0,d++,l){let Q={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(Q)}
|
|
188
190
|
|
|
189
|
-
`)),l="",a||(a=!0)}}let $=
|
|
190
|
-
`);if(!
|
|
191
|
+
`)),l="",a||(a=!0)}}let $=v.filter(P=>P.functionCall).map(P=>({id:P.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:P.functionCall?.name,arguments:JSON.stringify(P.functionCall?.args||{})}})),V=v.filter(P=>P.text&&P.thought!==!0).map(P=>P.text).join(`
|
|
192
|
+
`);if(!V&&s&&!a){let P={choices:[{delta:{role:"assistant",content:"(no content)"},index:d,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(P)}
|
|
191
193
|
|
|
192
|
-
`)),a||(a=!0)}if(c&&
|
|
194
|
+
`)),a||(a=!0)}if(c&&V&&!s)if(w.modelVersion.includes("3")){l+=V;return}else{let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(P)}
|
|
193
195
|
|
|
194
|
-
`)),s=!0}if(
|
|
196
|
+
`)),s=!0}if(V){l||d++;let P={choices:[{delta:{role:"assistant",content:V},finish_reason:A.finishReason?.toLowerCase()||null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:w.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w.usageMetadata?.cachedContentTokenCount||0},total_tokens:w.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(P.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((Q,z)=>{let K=A?.groundingMetadata?.groundingSupports?.filter(Y=>Y.groundingChunkIndices?.includes(z));return{type:"url_citation",url_citation:{url:Q?.web?.uri||"",title:Q?.web?.title||"",content:K?.[0]?.segment?.text||"",start_index:K?.[0]?.segment?.startIndex||0,end_index:K?.[0]?.segment?.endIndex||0}}})),g.enqueue(o.encode(`data: ${JSON.stringify(P)}
|
|
195
197
|
|
|
196
|
-
`)),!a&&
|
|
198
|
+
`)),!a&&V&&(a=!0)}$.length>0&&($.forEach(P=>{d++,f++;let Q={choices:[{delta:{role:"assistant",tool_calls:[{...P,index:f}]},finish_reason:A.finishReason?.toLowerCase()||null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:w.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w.usageMetadata?.cachedContentTokenCount||0},total_tokens:w.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(Q.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((z,K)=>{let Y=A?.groundingMetadata?.groundingSupports?.filter(ee=>ee.groundingChunkIndices?.includes(K));return{type:"url_citation",url_citation:{url:z?.web?.uri||"",title:z?.web?.title||"",content:Y?.[0]?.segment?.text||"",start_index:Y?.[0]?.segment?.startIndex||0,end_index:Y?.[0]?.segment?.endIndex||0}}})),g.enqueue(o.encode(`data: ${JSON.stringify(Q)}
|
|
197
199
|
|
|
198
|
-
`))}),!a&&
|
|
199
|
-
`);_=
|
|
200
|
+
`))}),!a&&V&&(a=!0))}catch(w){n?.error(`Error parsing ${e} stream chunk`,S,w.message)}}}},C=t.body.getReader(),_="";try{for(;;){let{done:y,value:g}=await C.read();if(y){_&&await b(_,m);break}_+=r.decode(g,{stream:!0});let S=_.split(`
|
|
201
|
+
`);_=S.pop()||"";for(let w of S)await b(w,m)}}catch(y){m.error(y)}finally{m.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var li=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,n){return{body:ai(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}transformRequestOut=ui;async transformResponseOut(e){return ci(e,this.name,this.logger)}};async function zT(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>jn(Rd(),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:
|
|
200
202
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
201
203
|
2. Run "gcloud auth application-default login"
|
|
202
|
-
3. Use Google Cloud environment with default service account`)}}var Ra=class{name="vertex-gemini";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!r&&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&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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
|
|
203
|
-
`);for(let
|
|
204
|
-
`))},p=(m,b)=>{let{controller:C,encoder:_}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let
|
|
204
|
+
3. Use Google Cloud environment with default service account`)}}var Ra=class{name="vertex-gemini";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!r&&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&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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 zT();return{body:ai(e),config:{url:new URL(`./v1beta1/projects/${r}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return ui(e)}async transformResponseOut(e){return ci(e,this.name)}};var xa=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let n=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),r=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||n;return r&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,c="";if(typeof o.content=="string"){let d=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);d&&(c=d[1].trim(),o.content=o.content.replace(d[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):c&&(o.reasoning_content=c),r&&!o.reasoning_content&&(o.reasoning_content=" "),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(m,b,C)=>{let _=m.split(`
|
|
205
|
+
`);for(let y of _)y.trim()&&b.enqueue(C.encode(y+`
|
|
206
|
+
`))},p=(m,b)=>{let{controller:C,encoder:_}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let y=JSON.parse(m.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){b.appendReasoningContent(y.choices[0].delta.reasoning_content);let g={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(g)}
|
|
205
207
|
|
|
206
|
-
`;C.enqueue(_.encode(
|
|
208
|
+
`;C.enqueue(_.encode(S));return}if(y.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let g="ccr_think_signature",S=y.choices[0].delta.content,w={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:g}}}]};delete w.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(w)}
|
|
207
209
|
|
|
208
|
-
`;C.enqueue(_.encode(
|
|
210
|
+
`;C.enqueue(_.encode(A));let v={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:S}}]};delete v.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(v)}
|
|
209
211
|
|
|
210
|
-
`;C.enqueue(_.encode(
|
|
212
|
+
`;C.enqueue(_.encode(R));return}if(y.choices[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let g=`data: ${JSON.stringify(y)}
|
|
211
213
|
|
|
212
|
-
`;C.enqueue(_.encode(
|
|
214
|
+
`;C.enqueue(_.encode(g))}}catch{C.enqueue(_.encode(m+`
|
|
213
215
|
`))}else C.enqueue(_.encode(m+`
|
|
214
216
|
`))};try{for(;;){let{done:m,value:b}=await d.read();if(m){a.trim()&&f(a,l,r);break}let C=n.decode(b,{stream:!0});a+=C;let _=a.split(`
|
|
215
|
-
`);a=_.pop()||"";for(let
|
|
217
|
+
`);a=_.pop()||"";for(let y of _)if(y.trim())try{p(y,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:g=>o+=g,isReasoningComplete:()=>s,setReasoningComplete:g=>s=g})}catch(g){console.error("Error processing line:",y,g),l.enqueue(r.encode(y+`
|
|
216
218
|
`))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Oa=class{name="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.
|
|
217
219
|
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.
|
|
218
220
|
Examples:
|
|
219
221
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
220
222
|
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 n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=-1,s="",a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(m,b,C)=>{let _=m.split(`
|
|
221
|
-
`);for(let
|
|
222
|
-
`))},p=(m,b)=>{let{controller:C,encoder:_,exitToolIndex:
|
|
223
|
+
`);for(let y of _)y.trim()&&b.enqueue(C.encode(y+`
|
|
224
|
+
`))},p=(m,b)=>{let{controller:C,encoder:_,exitToolIndex:y,setExitToolIndex:g,appendExitToolResponse:S}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let w=JSON.parse(m.slice(6));if(w.choices[0]?.delta?.tool_calls?.length){let A=w.choices[0].delta.tool_calls[0];if(A.function?.name==="ExitTool"){g(A.index);return}else if(y()>-1&&A.index===y()&&A.function.arguments){S(A.function.arguments);try{let v=JSON.parse(b.exitToolResponse());w.choices=[{delta:{role:"assistant",content:v.response||""}}];let R=`data: ${JSON.stringify(w)}
|
|
223
225
|
|
|
224
|
-
`;C.enqueue(_.encode(
|
|
226
|
+
`;C.enqueue(_.encode(R))}catch{}return}}if(w.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0){let A=`data: ${JSON.stringify(w)}
|
|
225
227
|
|
|
226
|
-
`;C.enqueue(_.encode(
|
|
228
|
+
`;C.enqueue(_.encode(A))}}catch{C.enqueue(_.encode(m+`
|
|
227
229
|
`))}else C.enqueue(_.encode(m+`
|
|
228
230
|
`))};try{for(;;){let{done:m,value:b}=await d.read();if(m){a.trim()&&f(a,l,r);break}let C=n.decode(b,{stream:!0});a+=C;let _=a.split(`
|
|
229
|
-
`);a=_.pop()||"";for(let
|
|
230
|
-
`))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}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(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),m=(C,_,
|
|
231
|
-
`);for(let
|
|
232
|
-
`))},b=(C,_)=>{let{controller:
|
|
233
|
-
|
|
234
|
-
`));return}w.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0);let
|
|
235
|
-
|
|
236
|
-
`;
|
|
237
|
-
|
|
238
|
-
`;
|
|
239
|
-
|
|
240
|
-
`;
|
|
241
|
-
|
|
242
|
-
`;
|
|
243
|
-
`))}}else
|
|
244
|
-
`))};try{for(;;){let{done:C,value:_}=await p.read();if(C){l.trim()&&m(l,f,r);break}if(!_||_.length===0)continue;let
|
|
245
|
-
`);l=
|
|
246
|
-
`))}continue}let
|
|
247
|
-
`);l=
|
|
248
|
-
`))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.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 Fa=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 Ia=class{name="groq";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{delete n.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(d){let f=e.body.getReader(),p=(b,C,_)=>{let
|
|
249
|
-
`);for(let
|
|
250
|
-
`))},m=(b,C)=>{let{controller:_,encoder:
|
|
251
|
-
|
|
252
|
-
`;_.enqueue(
|
|
253
|
-
`))}}else _.enqueue(
|
|
254
|
-
`))};try{for(;;){let{done:b,value:C}=await f.read();if(b){c.trim()&&p(c,d,r);break}if(!C||C.length===0)continue;let _;try{_=n.decode(C,{stream:!0})}catch(
|
|
255
|
-
`);c=
|
|
256
|
-
`))}continue}let
|
|
257
|
-
`);c=
|
|
258
|
-
`))}}}catch(b){console.error("Stream error:",b),d.error(b)}finally{try{f.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}d.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
|
|
231
|
+
`);a=_.pop()||"";for(let y of _)if(y.trim())try{p(y,{controller:l,encoder:r,exitToolIndex:()=>o,setExitToolIndex:g=>o=g,exitToolResponse:()=>s,appendExitToolResponse:g=>s+=g})}catch(g){console.error("Error processing line:",y,g),l.enqueue(r.encode(y+`
|
|
232
|
+
`))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}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(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),m=(C,_,y)=>{let g=C.split(`
|
|
233
|
+
`);for(let S of g)S.trim()&&_.enqueue(y.encode(S+`
|
|
234
|
+
`))},b=(C,_)=>{let{controller:y,encoder:g}=_;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let S=C.slice(6);try{let w=JSON.parse(S);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:c},"usage"),w.choices[0].finish_reason=c?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"){y.enqueue(g.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
|
|
235
|
+
|
|
236
|
+
`));return}w.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0);let A=w.choices?.[0]?.delta?.reasoning||w.choices?.[0]?.delta?.reasoning_content;if(A){_.appendReasoningContent(A);let P={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:A}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content);let Q=`data: ${JSON.stringify(P)}
|
|
237
|
+
|
|
238
|
+
`;y.enqueue(g.encode(Q));return}if(w.choices?.[0]?.delta?.content&&_.reasoningContent()&&!_.isReasoningComplete()){_.setReasoningComplete(!0);let P="ccr_think_signature",Q=w.choices[0].delta.content,z={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:_.reasoningContent(),signature:P}}}]};z.choices?.[0]?.delta&&delete z.choices[0].delta.reasoning;let K=`data: ${JSON.stringify(z)}
|
|
239
|
+
|
|
240
|
+
`;y.enqueue(g.encode(K));let Y={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:Q}}]};Y.choices?.[0]?.delta&&(delete Y.choices[0].delta.reasoning,delete Y.choices[0].delta.reasoning_content);let ee=`data: ${JSON.stringify(Y)}
|
|
241
|
+
|
|
242
|
+
`;y.enqueue(g.encode(ee));return}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.reasoning_content&&delete w.choices[0].delta.reasoning_content,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(P=>{P.id=`call_${Ut()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0);let v=w.choices?.[0]?.delta,R=v&&Object.keys(v).length>0,$=w.choices?.[0]?.finish_reason,V=w.usage;if(R||$||V){let P=`data: ${JSON.stringify(w)}
|
|
243
|
+
|
|
244
|
+
`;y.enqueue(g.encode(P))}}catch{y.enqueue(g.encode(C+`
|
|
245
|
+
`))}}else y.enqueue(g.encode(C+`
|
|
246
|
+
`))};try{for(;;){let{done:C,value:_}=await p.read();if(C){l.trim()&&m(l,f,r);break}if(!_||_.length===0)continue;let y;try{y=n.decode(_,{stream:!0})}catch(S){console.warn("Failed to decode chunk",S);continue}if(y.length===0)continue;if(l+=y,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let S=l.split(`
|
|
247
|
+
`);l=S.pop()||"";for(let w of S)if(w.trim())try{b(w,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:A=>o=A,reasoningContent:()=>s,appendReasoningContent:A=>s+=A,isReasoningComplete:()=>a,setReasoningComplete:A=>a=A})}catch(A){console.error("Error processing line:",w,A),f.enqueue(r.encode(w+`
|
|
248
|
+
`))}continue}let g=l.split(`
|
|
249
|
+
`);l=g.pop()||"";for(let S of g)if(S.trim())try{b(S,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",S,w),f.enqueue(r.encode(S+`
|
|
250
|
+
`))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.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 Fa=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 Ia=class{name="groq";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{delete n.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(d){let f=e.body.getReader(),p=(b,C,_)=>{let y=b.split(`
|
|
251
|
+
`);for(let g of y)g.trim()&&C.enqueue(_.encode(g+`
|
|
252
|
+
`))},m=(b,C)=>{let{controller:_,encoder:y}=C;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let g=b.slice(6);try{let S=JSON.parse(g);if(S.error)throw new Error(JSON.stringify(S));S.choices?.[0]?.delta?.content&&!C.hasTextContent()&&C.setHasTextContent(!0),S.choices?.[0]?.delta?.tool_calls?.length&&S.choices?.[0]?.delta?.tool_calls.forEach(A=>{A.id=`call_${Ut()}`}),S.choices?.[0]?.delta?.tool_calls?.length&&C.hasTextContent()&&(typeof S.choices[0].index=="number"?S.choices[0].index+=1:S.choices[0].index=1);let w=`data: ${JSON.stringify(S)}
|
|
253
|
+
|
|
254
|
+
`;_.enqueue(y.encode(w))}catch{_.enqueue(y.encode(b+`
|
|
255
|
+
`))}}else _.enqueue(y.encode(b+`
|
|
256
|
+
`))};try{for(;;){let{done:b,value:C}=await f.read();if(b){c.trim()&&p(c,d,r);break}if(!C||C.length===0)continue;let _;try{_=n.decode(C,{stream:!0})}catch(g){console.warn("Failed to decode chunk",g);continue}if(_.length===0)continue;if(c+=_,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let g=c.split(`
|
|
257
|
+
`);c=g.pop()||"";for(let S of g)if(S.trim())try{m(S,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",S,w),d.enqueue(r.encode(S+`
|
|
258
|
+
`))}continue}let y=c.split(`
|
|
259
|
+
`);c=y.pop()||"";for(let g of y)if(g.trim())try{m(g,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>s,appendReasoningContent:S=>s+=S,isReasoningComplete:()=>a,setReasoningComplete:S=>a=S})}catch(S){console.error("Error processing line:",g,S),d.enqueue(r.encode(g+`
|
|
260
|
+
`))}}}catch(b){console.error("Stream error:",b),d.error(b)}finally{try{f.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}d.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(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),e}};var P0=jn($u());var Rn=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function S0(t){return/^[0-9A-Fa-f]$/.test(t)}function Xn(t){return t>="0"&&t<="9"}function T0(t){return t>=" "}function cs(t){return`,:[]/{}()
|
|
259
261
|
+`.includes(t)}function xd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Od(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Pd=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Fd=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Id(t){return`,[]/{}
|
|
260
|
-
+`.includes(t)}function
|
|
261
|
-
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function
|
|
262
|
-
`,r:"\r",t:" "};function jd(t){let e=0,n="";d(["```","[```","{```"]),s()||ee(),d(["```","```]","```}"]);let o=p(",");for(o&&a(),
|
|
263
|
-
`;)e++;return!0}return!1}function d(
|
|
262
|
+
+`.includes(t)}function Bd(t){return ls(t)||HT.test(t)}var HT=/^[[{\w-]$/;function v0(t){return t===`
|
|
263
|
+
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function Yn(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function D0(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function R0(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function ls(t){return Nd(t)||Na(t)}function Nd(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Md(t){return t==='"'}function Na(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Ld(t){return t==="'"}function go(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Ft(t,e){let n=t.length;if(!Yn(t,n-1))return t+e;for(;Yn(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function x0(t,e,n){return t.substring(0,e)+t.substring(e+n)}function O0(t){return/[,\n][ \t\r]*$/.test(t)}var WT={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},GT={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
264
|
+
`,r:"\r",t:" "};function jd(t){let e=0,n="";d(["```","[```","{```"]),s()||ee(),d(["```","```]","```}"]);let o=p(",");for(o&&a(),Bd(t[e])&&O0(n)?(o||(n=Ft(n,",")),g()):o&&(n=go(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;Y();function s(){a();let G=_()||y()||S()||A()||v()||$(!1)||V();return a(),G}function a(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,ie=c(G);do ie=l(),ie&&(ie=c(G));while(ie);return e>Z}function c(G){let Z=G?Yn:D0,ie="";for(;;)if(Z(t,e))ie+=t[e],e++;else if(R0(t,e))ie+=" ",e++;else break;return ie.length>0?(n+=ie,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!JT(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
265
|
+
`;)e++;return!0}return!1}function d(G){if(f(G)){if(xd(t[e]))for(;e<t.length&&Od(t[e]);)e++;return a(),!0}return!1}function f(G){c(!0);for(let Z of G){let ie=e+Z.length;if(t.slice(e,ie)===Z)return e=ie,!0}return!1}function p(G){return t[e]===G?(n+=t[e],e++,!0):!1}function m(G){return t[e]===G?(e++,!0):!1}function b(){return m("\\")}function C(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),m(","),!0):!1}function _(){if(t[e]==="{"){n+="{",e++,a(),m(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(G?(Z=!0,G=!1):(Z=p(","),Z||(n=Ft(n,",")),a()),C(),!(S()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=go(n,","):ae();break}a();let Ue=p(":"),Ae=e>=t.length;Ue||(Bd(t[e])||Ae?n=Ft(n,":"):se()),s()||(Ue||Ae?n+="null":se())}return t[e]==="}"?(n+="}",e++):n=Ft(n,"}"),!0}return!1}function y(){if(t[e]==="["){n+="[",e++,a(),m(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(n=Ft(n,",")),C(),!s()){n=go(n,",");break}return t[e]==="]"?(n+="]",e++):n=Ft(n,"]"),!0}return!1}function g(){let G=!0,Z=!0;for(;Z;)G?G=!1:p(",")||(n=Ft(n,",")),Z=s();Z||(n=go(n,",")),n=`[
|
|
264
266
|
${n}
|
|
265
|
-
]`}function
|
|
266
|
-
`);for(let
|
|
267
|
-
`))},C=(g,
|
|
267
|
+
]`}function S(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ie=t[e]==="\\";if(ie&&(e++,ie=!0),ls(t[e])){let Ue=Md(t[e])?Md:Ld(t[e])?Ld:Na(t[e])?Na:Nd,Ae=e,J=n.length,ce='"';for(e++;;){if(e>=t.length){let te=P(e-1);return!G&&cs(t.charAt(te))?(e=Ae,n=n.substring(0,J),S(!0)):(ce=Ft(ce,'"'),n+=ce,!0)}if(e===Z)return ce=Ft(ce,'"'),n+=ce,!0;if(Ue(t[e])){let te=e,ve=ce.length;if(ce+='"',e++,n+=ce,a(!1),G||e>=t.length||cs(t[e])||ls(t[e])||Xn(t[e]))return w(),!0;let Oe=P(te-1),je=t.charAt(Oe);if(je===",")return e=Ae,n=n.substring(0,J),S(!1,Oe);if(cs(je))return e=Ae,n=n.substring(0,J),S(!0);n=n.substring(0,J),e=te+1,ce=`${ce.substring(0,ve)}\\${ce.substring(ve)}`}else if(G&&Id(t[e])){if(t[e-1]===":"&&Pd.test(t.substring(Ae+1,e+2)))for(;e<t.length&&Fd.test(t[e]);)ce+=t[e],e++;return ce=Ft(ce,'"'),n+=ce,w(),!0}else if(t[e]==="\\"){let te=t.charAt(e+1);if(GT[te]!==void 0)ce+=t.slice(e,e+2),e+=2;else if(te==="u"){let Oe=2;for(;Oe<6&&S0(t[e+Oe]);)Oe++;Oe===6?(ce+=t.slice(e,e+6),e+=6):e+Oe>=t.length?e=t.length:me()}else ce+=te,e+=2}else{let te=t.charAt(e);te==='"'&&t[e-1]!=="\\"?(ce+=`\\${te}`,e++):v0(te)?(ce+=WT[te],e++):(T0(te)||K(te),ce+=te,e++)}ie&&b()}}return!1}function w(){let G=!1;for(a();t[e]==="+";){G=!0,e++,a(),n=go(n,'"',!0);let Z=n.length;S()?n=x0(n,Z,1):n=Ft(n,'"')}return G}function A(){let G=e;if(t[e]==="-"){if(e++,Q())return z(G),!0;if(!Xn(t[e]))return e=G,!1}for(;Xn(t[e]);)e++;if(t[e]==="."){if(e++,Q())return z(G),!0;if(!Xn(t[e]))return e=G,!1;for(;Xn(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Q())return z(G),!0;if(!Xn(t[e]))return e=G,!1;for(;Xn(t[e]);)e++}if(!Q())return e=G,!1;if(e>G){let Z=t.slice(G,e),ie=/^0\d/.test(Z);return n+=ie?`"${Z}"`:Z,!0}return!1}function v(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(G,Z){return t.slice(e,e+G.length)===G?(n+=Z,e+=G.length,!0):!1}function $(G){let Z=e;if(xd(t[e])){for(;e<t.length&&Od(t[e]);)e++;let ie=e;for(;Yn(t,ie);)ie++;if(t[ie]==="(")return e=ie+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Id(t[e])&&!ls(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&Pd.test(t.substring(Z,e+2)))for(;e<t.length&&Fd.test(t[e]);)e++;if(e>Z){for(;Yn(t,e-1)&&e>0;)e--;let ie=t.slice(Z,e);return n+=ie==="undefined"?"null":JSON.stringify(ie),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++,n+=`"${t.substring(G,e)}"`,!0}}function P(G){let Z=G;for(;Z>0&&Yn(t,Z);)Z--;return Z}function Q(){return e>=t.length||cs(t[e])||Yn(t,e)}function z(G){n+=`${t.slice(G,e)}0`}function K(G){throw new Rn(`Invalid character ${JSON.stringify(G)}`,e)}function Y(){throw new Rn(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ee(){throw new Rn("Unexpected end of json string",t.length)}function ae(){throw new Rn("Object key expected",e)}function se(){throw new Rn("Colon expected",e)}function me(){let G=t.slice(e,e+6);throw new Rn(`Invalid unicode character "${G}"`,e)}}function JT(t,e){return t[e]==="*"&&t[e+1]==="/"}function Ud(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(n){try{let r=P0.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=jd(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Ma=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=Ud(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,a="",c=!1,l=!1,d="",f=new ReadableStream({async start(p){let m=e.body.getReader(),b=(y,g,S)=>{let w=y.split(`
|
|
268
|
+
`);for(let A of w)A.trim()&&g.enqueue(S.encode(A+`
|
|
269
|
+
`))},C=(y,g,S)=>{let w="";try{w=Ud(o.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),w=o.arguments||""}let A={role:"assistant",tool_calls:[{function:{name:o.name,arguments:w},id:o.id,index:o.index,type:"function"}]},v={...y,choices:[{...y.choices[0],delta:A}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let R=`data: ${JSON.stringify(v)}
|
|
268
270
|
|
|
269
|
-
`;
|
|
271
|
+
`;g.enqueue(S.encode(R))},_=(y,g)=>{let{controller:S,encoder:w}=g;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let A=y.slice(6);try{let v=JSON.parse(A);if(v.choices?.[0]?.delta?.tool_calls?.length){let $=v.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(v)}
|
|
270
272
|
|
|
271
|
-
`;
|
|
273
|
+
`;S.enqueue(w.encode(V));return}else if(o.index===$.index){$.function?.arguments&&(o.arguments+=$.function.arguments);return}else{C(v,S,w),o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(v.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){C(v,S,w),o={};return}v.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let R=`data: ${JSON.stringify(v)}
|
|
272
274
|
|
|
273
|
-
`;
|
|
274
|
-
`))}}else
|
|
275
|
-
`))};try{for(;;){let{done:
|
|
276
|
-
`);d=
|
|
275
|
+
`;S.enqueue(w.encode(R))}catch{S.enqueue(w.encode(y+`
|
|
276
|
+
`))}}else S.enqueue(w.encode(y+`
|
|
277
|
+
`))};try{for(;;){let{done:y,value:g}=await m.read();if(y){d.trim()&&b(d,p,r);break}if(!g||g.length===0)continue;let S;try{S=n.decode(g,{stream:!0})}catch(A){console.warn("Failed to decode chunk",A);continue}if(S.length===0)continue;if(d+=S,d.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let A=d.split(`
|
|
278
|
+
`);d=A.pop()||"";for(let v of A)if(v.trim())try{_(v,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:R=>s=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>c,setReasoningComplete:R=>c=R})}catch(R){console.error("Error processing line:",v,R),p.enqueue(r.encode(v+`
|
|
277
279
|
`))}continue}let w=d.split(`
|
|
278
|
-
`);d=w.pop()||"";for(let
|
|
279
|
-
`))}}}catch(
|
|
280
|
-
`);for(let
|
|
281
|
-
`))},p=(m,b)=>{let{controller:C,encoder:_}=b;if(this.logger?.debug({line:m},"Processing reason line"),m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let
|
|
280
|
+
`);d=w.pop()||"";for(let A of w)if(A.trim())try{_(A,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>a,appendReasoningContent:v=>a+=v,isReasoningComplete:()=>c,setReasoningComplete:v=>c=v})}catch(v){console.error("Error processing line:",A,v),p.enqueue(r.encode(A+`
|
|
281
|
+
`))}}}catch(y){console.error("Stream error:",y),p.error(y)}finally{try{m.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}p.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var 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 n=await e.json();return n.choices[0]?.message.reasoning_content&&(n.thinking={content:n.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(m,b,C)=>{let _=m.split(`
|
|
282
|
+
`);for(let y of _)y.trim()&&b.enqueue(C.encode(y+`
|
|
283
|
+
`))},p=(m,b)=>{let{controller:C,encoder:_}=b;if(this.logger?.debug({line:m},"Processing reason line"),m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let y=JSON.parse(m.slice(6));if(console.log(JSON.stringify(y)),y.choices?.[0]?.delta?.reasoning_content){b.appendReasoningContent(y.choices[0].delta.reasoning_content);let g={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(g)}
|
|
282
284
|
|
|
283
|
-
`;C.enqueue(_.encode(
|
|
285
|
+
`;C.enqueue(_.encode(S));return}if(y.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let g="ccr_think_signature",S=y.choices[0].delta.content,w={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:g}}}]};delete w.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(w)}
|
|
284
286
|
|
|
285
|
-
`;C.enqueue(_.encode(
|
|
287
|
+
`;C.enqueue(_.encode(A))}if(y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){b.isReasoningComplete()&&y.choices[0].index++;let g=`data: ${JSON.stringify(y)}
|
|
286
288
|
|
|
287
|
-
`;C.enqueue(_.encode(
|
|
289
|
+
`;C.enqueue(_.encode(g))}}catch{C.enqueue(_.encode(m+`
|
|
288
290
|
`))}else C.enqueue(_.encode(m+`
|
|
289
291
|
`))};try{for(;;){let{done:m,value:b}=await d.read();if(m){a.trim()&&f(a,l,r);break}let C=n.decode(b,{stream:!0});a+=C;let _=a.split(`
|
|
290
|
-
`);a=_.pop()||"";for(let
|
|
291
|
-
`))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}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 ja=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 Ua=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function
|
|
292
|
+
`);a=_.pop()||"";for(let y of _)if(y.trim())try{p(y,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:g=>o+=g,isReasoningComplete:()=>s,setReasoningComplete:g=>s=g})}catch(g){console.error("Error processing line:",y,g),l.enqueue(r.encode(y+`
|
|
293
|
+
`))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}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 ja=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 Ua=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function F0(t){let e=[];for(let r=0;r<t.messages.length;r++){let o=t.messages[r],s=r===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 n={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&&(n.tools=t.tools.map(r=>({name:r.function.name,description:r.function.description,input_schema:r.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?n.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(n.tool_choice={type:"tool",name:t.tool_choice})),n}function I0(t){let e=t,r={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&&(r.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"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function B0(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o;r.tool_use&&r.tool_use.length>0&&(o=r.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:r.id,choices:[{finish_reason:r.stop_reason||null,index:0,message:{content:r.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:{completion_tokens:r.usage.output_tokens,prompt_tokens:r.usage.input_tokens,total_tokens:r.usage.input_tokens+r.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 r=new TextDecoder,o=new TextEncoder,s=(c,l)=>{if(c.startsWith("data: ")){let d=c.slice(6).trim();if(d){n?.debug({chunkStr:d},`${e} chunk:`);try{let f=JSON.parse(d);if(f.type==="content_block_delta"&&f.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:f.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
|
|
292
294
|
|
|
293
295
|
`))}else if(f.type==="content_block_delta"&&f.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:f.index||0,function:{arguments:f.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
|
|
294
296
|
|
|
@@ -301,71 +303,71 @@ ${n}
|
|
|
301
303
|
`));else{let p={choices:[{delta:{role:"assistant",content:f.content?.[0]?.text||""},finish_reason:f.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
|
|
302
304
|
|
|
303
305
|
`))}}catch(f){n?.error(`Error parsing ${e} stream chunk`,d,f.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),d="";try{for(;;){let{done:f,value:p}=await l.read();if(f){d&&s(d,c);break}d+=r.decode(p,{stream:!0});let m=d.split(`
|
|
304
|
-
`);d=m.pop()||"";for(let b of m)s(b,c)}}catch(f){c.error(f)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function
|
|
306
|
+
`);d=m.pop()||"";for(let b of m)s(b,c)}}catch(f){c.error(f)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function VT(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>jn(Rd(),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:
|
|
305
307
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
306
308
|
2. Run "gcloud auth application-default login"
|
|
307
|
-
3. Use Google Cloud environment with default service account`)}}var $a=class{name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&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&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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
|
|
308
|
-
`);for(let
|
|
309
|
-
`))},b=(C,_)=>{let{controller:
|
|
309
|
+
3. Use Google Cloud environment with default service account`)}}var $a=class{name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&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&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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 VT();return{body:F0(e),config:{url:new URL(`/v1/projects/${r}/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 I0(e)}async transformResponseOut(e){return B0(e,this.name,this.logger)}};var qa=class{name="cerebras";async transformRequestIn(e,n){let r=JSON.parse(JSON.stringify(e));return r.reasoning?delete r.reasoning:r.disable_reasoning=!1,{body:r,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var za=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ha=class{name="OpenAI";endPoint="/v1/chat/completions"};var Wa=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(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);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&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):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var Ga=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),m=(C,_,y)=>{let g=C.split(`
|
|
310
|
+
`);for(let S of g)S.trim()&&_.enqueue(y.encode(S+`
|
|
311
|
+
`))},b=(C,_)=>{let{controller:y,encoder:g}=_;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let S=C.slice(6);try{let w=JSON.parse(S);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:c},"usage"),w.choices[0].finish_reason=c?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"&&y.enqueue(g.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
|
|
310
312
|
|
|
311
|
-
`)),w.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0),w.choices?.[0]?.delta?.reasoning){_.appendReasoningContent(w.choices[0].delta.reasoning);let
|
|
313
|
+
`)),w.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0),w.choices?.[0]?.delta?.reasoning){_.appendReasoningContent(w.choices[0].delta.reasoning);let v={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:w.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let R=`data: ${JSON.stringify(v)}
|
|
312
314
|
|
|
313
|
-
`;
|
|
315
|
+
`;y.enqueue(g.encode(R));return}if(w.choices?.[0]?.delta?.content&&_.reasoningContent()&&!_.isReasoningComplete()){_.setReasoningComplete(!0);let R={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:_.reasoningContent(),signature:"ccr_think_signature"}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(R)}
|
|
314
316
|
|
|
315
|
-
`;
|
|
317
|
+
`;y.enqueue(g.encode($))}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(v=>{v.id=`call_${Ut()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),w.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof w.choices[0].index=="number"?w.choices[0].index+=1:w.choices[0].index=1);let A=`data: ${JSON.stringify(w)}
|
|
316
318
|
|
|
317
|
-
`;
|
|
318
|
-
`))}}else
|
|
319
|
-
`))};try{for(;;){let{done:C,value:_}=await p.read();if(C){l.trim()&&m(l,f,r);break}if(!_||_.length===0)continue;let
|
|
320
|
-
`);l=
|
|
321
|
-
`))}continue}let
|
|
322
|
-
`);l=
|
|
319
|
+
`;y.enqueue(g.encode(A))}catch{y.enqueue(g.encode(C+`
|
|
320
|
+
`))}}else y.enqueue(g.encode(C+`
|
|
321
|
+
`))};try{for(;;){let{done:C,value:_}=await p.read();if(C){l.trim()&&m(l,f,r);break}if(!_||_.length===0)continue;let y;try{y=n.decode(_,{stream:!0})}catch(S){console.warn("Failed to decode chunk",S);continue}if(y.length===0)continue;if(l+=y,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let S=l.split(`
|
|
322
|
+
`);l=S.pop()||"";for(let w of S)if(w.trim())try{b(w,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:A=>o=A,reasoningContent:()=>s,appendReasoningContent:A=>s+=A,isReasoningComplete:()=>a,setReasoningComplete:A=>a=A})}catch(A){console.error("Error processing line:",w,A),f.enqueue(r.encode(w+`
|
|
323
|
+
`))}continue}let g=l.split(`
|
|
324
|
+
`);l=g.pop()||"";for(let S of g)if(S.trim())try{b(S,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",S,w),f.enqueue(r.encode(S+`
|
|
323
325
|
`))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.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 $d=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
324
326
|
|
|
325
327
|
Output format:
|
|
326
328
|
<reasoning_content>
|
|
327
329
|
Your detailed thinking process goes here
|
|
328
330
|
</reasoning_content>
|
|
329
|
-
Your final answer must follow after the closing tag above.`,
|
|
330
|
-
${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:$d}):r.content=[{type:"text",text:$d},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:$d}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</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 d=e.body.getReader(),f="",p="SEARCHING",m="",b="",C=(_,
|
|
331
|
+
Your final answer must follow after the closing tag above.`,KT=10,Ja=class{name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<KT)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
|
|
332
|
+
${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:$d}):r.content=[{type:"text",text:$d},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:$d}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</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 d=e.body.getReader(),f="",p="SEARCHING",m="",b="",C=(_,y)=>{if(typeof y!="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(_)}
|
|
331
333
|
|
|
332
|
-
`)));return}let
|
|
334
|
+
`)));return}let g=m+y;for(m="";g.length>0;)if(p==="SEARCHING"){let S=g.indexOf(n);if(S!==-1)g=g.substring(S+n.length),p="REASONING";else{for(let w=n.length-1;w>0;w--)if(g.endsWith(n.substring(0,w))){m=g.substring(g.length-w);break}g=""}}else if(p==="REASONING"){let S=g.indexOf(r);if(S!==-1){let w=g.substring(0,S);if(w.length>0){let R={..._.choices[0].delta,thinking:{content:w}};delete R.content;let $={..._,choices:[{..._.choices[0],delta:R,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify($)}
|
|
333
335
|
|
|
334
|
-
`))}let
|
|
336
|
+
`))}let A={..._.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete A.content;let v={..._,choices:[{..._.choices[0],delta:A,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
335
337
|
|
|
336
|
-
`)),o++,
|
|
338
|
+
`)),o++,g=g.substring(S+r.length),p="FINAL"}else{let w=g;for(let A=r.length-1;A>0;A--)if(g.endsWith(r.substring(0,A))){m=g.substring(g.length-A),w=g.substring(0,g.length-A);break}if(w.length>0){let A={..._.choices[0].delta,thinking:{content:w}};delete A.content;let v={..._,choices:[{..._.choices[0],delta:A,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
337
339
|
|
|
338
|
-
`))}
|
|
340
|
+
`))}g=""}}else if(p==="FINAL"){if(g.length>0)if(/^\s*$/.test(g))b+=g;else{let w=b+g,A={..._.choices[0].delta,content:w};A.thinking&&delete A.thinking;let v={..._,choices:[{..._.choices[0],delta:A}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
339
341
|
|
|
340
|
-
`)),b=""}o++,
|
|
341
|
-
`);f=
|
|
342
|
+
`)),b=""}o++,g=""}};try{for(;;){let{done:_,value:y}=await d.read();if(_)break;let g=s.decode(y,{stream:!0});f+=g;let S=f.split(`
|
|
343
|
+
`);f=S.pop()||"";for(let w of S)if(w.trim()){if(w.trim()==="data: [DONE]"){l.enqueue(a.encode(w+`
|
|
342
344
|
|
|
343
|
-
`));break}if(w.startsWith("data:"))try{let
|
|
345
|
+
`));break}if(w.startsWith("data:"))try{let A=JSON.parse(w.slice(5));C(A,A.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(w+`
|
|
344
346
|
`))}else l.enqueue(a.encode(w+`
|
|
345
|
-
`))}}}catch(_){console.error("Stream error:",_),l.error(_)}finally{try{d.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}if(p==="REASONING"){let
|
|
347
|
+
`))}}}catch(_){console.error("Stream error:",_),l.error(_)}finally{try{d.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}if(p==="REASONING"){let y={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(y)}
|
|
346
348
|
|
|
347
349
|
`))}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 Va=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content))&&e.messages.forEach(r=>{if(r.role==="assistant"){let o=r.thinking?.content,s=r.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(r.reasoning_content=o,s&&(r.reasoning_content_signature=s)),r.tool_calls&&r.tool_calls.length>0&&(r.reasoning_content||(r.reasoning_content="")),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){let n=e.headers.get("Content-Type");if(n?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,o=new TextEncoder,s="",a="",c=new ReadableStream({async start(l){let d=e.body.getReader();try{for(;;){let{done:f,value:p}=await d.read();if(f){a.trim()&&l.enqueue(o.encode(a+`
|
|
348
350
|
`));break}let m=r.decode(p,{stream:!0});a+=m;let b=a.split(`
|
|
349
|
-
`);a=b.pop()||"";for(let C of b)if(C.trim())if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let _=JSON.parse(C.slice(6));if(_.choices?.[0]?.delta?.reasoning_content){s+=_.choices[0].delta.reasoning_content;let
|
|
351
|
+
`);a=b.pop()||"";for(let C of b)if(C.trim())if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let _=JSON.parse(C.slice(6));if(_.choices?.[0]?.delta?.reasoning_content){s+=_.choices[0].delta.reasoning_content;let y={..._,choices:[{..._.choices[0],delta:{thinking:{content:_.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(y)}
|
|
350
352
|
|
|
351
|
-
`));continue}if(_.choices?.[0]?.delta?.content&&s&&!_.choices[0]?.delta?.reasoning_content){let
|
|
353
|
+
`));continue}if(_.choices?.[0]?.delta?.content&&s&&!_.choices[0]?.delta?.reasoning_content){let y=Date.now().toString(),g={..._,choices:[{..._.choices[0],delta:{content:null,thinking:{content:s,signature:y}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(g)}
|
|
352
354
|
|
|
353
355
|
`)),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(_)}
|
|
354
356
|
|
|
355
357
|
`))}catch{l.enqueue(o.encode(C+`
|
|
356
358
|
`))}else l.enqueue(o.encode(C+`
|
|
357
|
-
`))}}catch(f){l.error(f)}finally{try{d.releaseLock()}catch{}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":n||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(n?.includes("application/json")){let r=await e.json();return r.choices?.[0]?.message?.reasoning_content&&(r.choices[0].message.thinking={content:r.choices[0].message.reasoning_content},delete r.choices[0].message.reasoning_content),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var N0={AnthropicTransformer:ii,GeminiTransformer:li,VertexGeminiTransformer:Ra,VertexClaudeTransformer:$a,DeepseekTransformer:xa,TooluseTransformer:Oa,OpenrouterTransformer:Pa,OpenAITransformer:
|
|
359
|
+
`))}}catch(f){l.error(f)}finally{try{d.releaseLock()}catch{}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":n||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(n?.includes("application/json")){let r=await e.json();return r.choices?.[0]?.message?.reasoning_content&&(r.choices[0].message.thinking={content:r.choices[0].message.reasoning_content},delete r.choices[0].message.reasoning_content),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var N0={AnthropicTransformer:ii,GeminiTransformer:li,VertexGeminiTransformer:Ra,VertexClaudeTransformer:$a,DeepseekTransformer:xa,TooluseTransformer:Oa,OpenrouterTransformer:Pa,OpenAITransformer:Ha,MaxTokenTransformer:Fa,GroqTransformer:Ia,CleancacheTransformer:Ba,EnhanceToolTransformer:Ma,ReasoningTransformer:La,SamplingTransformer:ja,MaxCompletionTokens:Ua,CerebrasTransformer:qa,StreamOptionsTransformer:za,CustomParamsTransformer:Wa,VercelTransformer:Ga,OpenAIResponsesTransformer:Mr,ForceReasoningTransformer:Ja,KimiTransformer:Va};var yo=class{constructor(e,n){this.configService=e;this.logger=n}transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&n.endPoint&&e.push({name:r,transformer:n})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=re(re.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
|
|
358
360
|
error: ${n.message}
|
|
359
361
|
stack: ${n.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
360
|
-
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 n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};import{get_encoding as
|
|
361
|
-
`: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 n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}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}},fv=dv,hv=class extends Rn{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}},pv=hv,mv=class extends Rn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>z0(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},gv=mv,yv=class extends Rn{normalize(t){let e=Ka(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},_v=yv,bv=class extends Rn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ya=bv,Cv=class extends Ya{constructor(){super(...arguments),this.form="NFC"}},wv=Cv,Ev=class extends Ya{constructor(){super(...arguments),this.form="NFD"}},kv=Ev,Av=class extends Ya{constructor(){super(...arguments),this.form="NFKC"}},Sv=Av,Tv=class extends Ya{constructor(){super(...arguments),this.form="NFKD"}},vv=Tv,Dv=class extends Rn{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}},Rv=Dv,xv=class extends Rn{normalize(t){return H0(t)}},Ov=xv,Pv=class extends Rn{normalize(t){return t.toLowerCase()}},Fv=Pv,Iv=class extends Rn{normalize(t){return t=this.config.prepend+t,t}},Nv=Iv;function Bv(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new fv(t);case"Precompiled":return new pv(t);case"Sequence":return new gv(t);case"Replace":return new _v(t);case"NFC":return new wv(t);case"NFD":return new kv(t);case"NFKC":return new Sv(t);case"NFKD":return new vv(t);case"Strip":return new Rv(t);case"StripAccents":return new Ov(t);case"Lowercase":return new Fv(t);case"Prepend":return new Nv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var z0=Bv,Mv=class extends ps{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},cn=Mv,Lv=class extends cn{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=q0,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(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},jv=Lv,Uv=class extends cn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},$v=Uv,qv=class extends cn{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:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},Hv=qv,zv=class extends cn{constructor(t){super(),this.config=t,this.pattern=Ka(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):av(t,this.pattern)}},Wv=zv,Gv=class extends cn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${hs}]+|[${hs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Jv=Gv,Vv=class extends cn{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)||[]}},Kv=Vv,Yv=class extends cn{constructor(){super(),this.pattern=new RegExp(`[^\\s${hs}]+|[${hs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Qv=Yv,Xv=class extends cn{constructor(t){super(),this.config=t,this.pattern=Ka(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Zv=Xv,eD=class extends cn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>W0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},tD=eD,nD=class extends cn{pre_tokenize_text(t){return uv(t)}},rD=nD;function oD(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Qv;case"Sequence":return new tD(t);case"Whitespace":return new $v;case"WhitespaceSplit":return new rD;case"Metaspace":return new Hv(t);case"ByteLevel":return new jv(t);case"Split":return new Wv(t);case"Punctuation":return new Jv(t);case"Digits":return new Kv(t);case"Replace":return new Zv(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var W0=oD,sD=class extends ps{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=nv(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)}},Qa=sD,iD=class extends Qa{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=zd(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,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let c=r.length,l=null;for(;s<c;){let d=r.slice(s,c).join("");if(s>0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){l=d;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},L0=iD,j0=class G0{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new G0(!1,new Map)}},aD=class{constructor(){this.root=j0.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=j0.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},uD=aD,qd=class J0{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new J0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},cD=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new qd(this.bos_token_id??0,0,0,0,0),o=new qd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new qd(r,o,t,e,n);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 d=l.backtrace_score+s.score;(c===null||d>a)&&(c=l.clone(),a=d)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}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)}},lD=cD;function dD(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var fD=class extends Qa{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,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=dD(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new uD,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let d=this.tokens_to_ids.get(l),f=this.scores[d],p=sv(l);t.insert(r,p,f,d),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new lD(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},U0=fD,hD=class{constructor(t=(n,r)=>n>r,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 n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}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 n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_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}},pD=hD,mD=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()}},gD=mD,yD=class extends Qa{constructor(t){super(t),this.tokens_to_ids=zd(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[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),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 gD(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 n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new pD((c,l)=>c.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<n.length;++c){let l={bias:c/n.length,token:n[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 d={...c.prev};c.prev.deleted=!0,c.prev=d,d.prev?d.prev.next=d:s=d}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)r.push(c.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)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}},$0=yD,_D=class extends Qa{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=zd(e.target_lang?n[e.target_lang]:n),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[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},bD=_D;function CD(t,e){switch(t.type){case"WordPiece":return new L0(t);case"Unigram":return new U0(t,e.eos_token);case"BPE":return new $0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new U0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new $0(t):new L0(t):new bD(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 wD=CD,ED=class extends ps{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ms=ED,kD=class extends ms{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=It(o,t),s=It(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=It(o,e),s=It(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},AD=kD,SD=class extends ms{post_process(t,e=null){return{tokens:e?It(t,e):t}}},TD=SD,vD=class extends ms{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=It([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=It(t,o,e,s),r=It(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},DD=vD,RD=class extends ms{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=It([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=It(t,o,e,s),r=It(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},xD=RD,OD=class extends ms{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>V0(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},PD=OD;function FD(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new AD(t);case"ByteLevel":return new TD(t);case"BertProcessing":return new DD(t);case"RobertaProcessing":return new xD(t);case"Sequence":return new PD(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var V0=FD,ID=class extends ps{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("")}},ln=ID,ND=class extends ln{constructor(t){super(t),this.byte_decoder=ZT,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(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},BD=ND,MD=class extends ln{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=Hd(e)),e})}},LD=MD,jD=class extends ln{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},UD=jD,$D=class extends ln{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},qD=$D,HD=class extends ln{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 r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=Hd(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},zD=HD,WD=class extends ln{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>K0(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},GD=WD,JD=class extends ln{decode_chain(t){let e=Ka(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},VD=JD,KD=class extends ln{decode_chain(t){return[t.join("")]}},YD=KD,QD=class extends ln{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 n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},XD=QD,ZD=class extends ln{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},eR=ZD;function tR(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new BD(t);case"WordPiece":return new LD(t);case"Metaspace":return new UD(t);case"BPEDecoder":return new qD(t);case"CTC":return new zD(t);case"Sequence":return new GD(t);case"Replace":return new VD(t);case"Fuse":return new YD(t);case"Strip":return new XD(t);case"ByteFallback":return new eR(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var K0=tR,nR=class{constructor(t,e){let n=M0(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=M0(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=z0(this.tokenizer.normalizer),this.pre_tokenizer=W0(this.tokenizer.pre_tokenizer),this.model=wD(this.tokenizer.model,this.config),this.post_processor=V0(this.tokenizer.post_processor),this.decoder=K0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new QT(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 KT(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:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!ov(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Hd(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=iv(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:It(r??[],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}},Y0=nR;var eu=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||Xa(rR(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Xa(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Xa(e,"tokenizer.json"),tokenizerConfig:Xa(e,"tokenizer_config.json")}}ensureDir(e){Wd(e)||oR(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Wd(e.tokenizerJson)||!Wd(e.tokenizerConfig))return null;let[n,r]=await Promise.all([Za.readFile(e.tokenizerJson,"utf-8"),Za.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={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 r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.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([Za.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Za.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 n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new Y0(n.tokenizerJson,n.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 n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}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 n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?n.push(c.text):c.type==="tool_use"&&c.input?n.push(JSON.stringify(c.input)):c.type==="tool_result"&&n.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&n.push(c)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var tu=class{type="api";name;config;logger;options;constructor(e,n,r={}){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=n,this.options=r;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 n=this.formatRequestBody(e),r={"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:r,body:JSON.stringify(n),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(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}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(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var bo=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new fs("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 n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new fs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new eu(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=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 r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}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,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),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)}`}}};$n();var xn=class{async fetchJson(e,n,r,o,s){let a=s||n.apiKey;if(!a)return null;let c={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(r)};if(o)try{let{ProxyAgent:l}=await import("undici");c.dispatcher=new l(new URL(o).toString())}catch{}try{let l=await fetch(e,c);return l.ok?await l.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}},Gd=class extends xn{async queryQuota(e,n,r){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,n,r),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>Ce(l?.total_balance)!==void 0);if(!a)return null;let c=Ce(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},Jd=class extends xn{async queryQuota(e,n,r){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,n,r))?.data;if(!s||typeof s!="object")return null;let a={},c=Ce(s.limit),l=Ce(s.limit_remaining),d=Ce(s.usage),f=Ce(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),d!==void 0&&(a.usedBalance=d),f!==void 0&&(a.usedDailyBalance=f),this.hasQuotaData(a)?a:null}},Vd=class extends xn{async queryQuota(e,n,r){let o=fR(e.baseUrl),a=(await this.fetchJson(o,e,n,r))?.data;if(!a||typeof a!="object")return null;let c={},l=Ce(a.totalBalance),d=Ce(a.balance);return l!==void 0&&(c.totalBalance=l),d!==void 0&&(c.remainingBalance=d),l!==void 0&&d!==void 0&&(c.usedBalance=Math.max(0,l-d)),this.hasQuotaData(c)?c:null}},Kd=class extends xn{async queryQuota(e,n,r){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let c=await a.json(),l=Array.isArray(c?.data?.limits)?c.data.limits:[],d=null,f=null,p=null;for(let b of l)b.type==="TOKENS_LIMIT"?b.unit===3?d=b:b.unit===6?f=b:d||(d=b):b.type==="TIME_LIMIT"&&(p=b);let m={};if(d){let b=Ce(d.currentValue),C=Ce(d.usage),_=Ce(d.remaining),g=Ce(d.percentage);b!==void 0?m.usedDailyBalance=b:g!==void 0&&(m.usedDailyBalance=g,m.limitDaily=100),C!==void 0?m.limitDaily=C:b!==void 0&&_!==void 0&&(m.limitDaily=b+_),d.nextResetTime&&(m.resetTime=new Date(d.nextResetTime).toISOString())}if(f){let b=Ce(f.currentValue),C=Ce(f.usage),_=Ce(f.remaining),g=Ce(f.percentage);b!==void 0?m.usedBalance=b:g!==void 0&&(m.usedBalance=g,m.totalBalance=100),C!==void 0?m.totalBalance=C:b!==void 0&&_!==void 0&&(m.totalBalance=b+_),f.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(f.nextResetTime).toISOString())}if(p){if(m.usedDailyBalance===void 0){let b=Ce(p.currentValue);b!==void 0&&(m.usedDailyBalance=b)}if(m.limitDaily===void 0){let b=Ce(p.usage),C=Ce(p.currentValue),_=Ce(p.remaining);b!==void 0?m.limitDaily=b:C!==void 0&&_!==void 0&&(m.limitDaily=C+_)}p.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(m)?m:null}catch{return null}}},Yd=class extends xn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{let c=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...o,body:a});if(!c.ok)return null;let d=(await c.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(d)||d.length===0)return null;let f=d[0]?.codingPlanQuotaInfo;if(!f)return null;let p={},m=Ce(f.per5HourUsedQuota),b=Ce(f.per5HourTotalQuota);m!==void 0&&(p.usedDailyBalance=m),b!==void 0&&(p.limitDaily=b);let C=Ce(f.perWeekUsedQuota),_=Ce(f.perWeekTotalQuota);return C!==void 0&&(p.usedBalance=C),_!==void 0&&(p.totalBalance=_),this.hasQuotaData(p)?p:null}catch{return null}}},Qd=class extends xn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let c=await a.json(),l={},d=Array.isArray(c?.limits)?c.limits:[];if(d.length>0&&d[0]?.detail){let p=d[0].detail,m=Ce(p.limit),b=Ce(p.remaining),C=p.resetTime;m!==void 0&&b!==void 0&&(l.usedDailyBalance=Math.max(0,m-b),l.limitDaily=m),C&&(l.resetTime=new Date(C).toISOString())}let f=c?.usage;if(f){let p=Ce(f.limit),m=Ce(f.remaining),b=Ce(f.used),C=f.resetTime;p!==void 0&&(l.totalBalance=p,b!==void 0?l.usedBalance=b:m!==void 0&&(l.usedBalance=Math.max(0,p-m),l.remainingBalance=m)),C&&(l.resetTime7d=new Date(C).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Xd=class extends xn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=ef(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let c=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let S of c)if(l=await this.fetchJson(S,e,n,r,o.trim()),l)break;if(!l)return null;if(l?.base_resp){let S=l.base_resp.status_code;if(S!==void 0&&S!==0)return null}let d=Array.isArray(l?.model_remains)?l.model_remains:[];if(d.length===0)return null;let f=d[0],p={},m=Ce(f.current_interval_total_count),b=Ce(f.current_interval_usage_count),C=Ce(f.current_interval_remaining_percent),_=Ce(f.end_time);m!==void 0&&b!==void 0&&m>0?(p.usedDailyBalance=Math.max(0,m-b),p.limitDaily=m):C!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-C)),_&&(p.resetTime=new Date(_).toISOString());let g=Ce(f.current_weekly_total_count),y=Ce(f.current_weekly_usage_count),k=Ce(f.current_weekly_remaining_percent),w=Ce(f.weekly_end_time);return g!==void 0&&y!==void 0&&g>0?(p.usedBalance=Math.max(0,g-y),p.remainingBalance=y,p.totalBalance=g):k!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-k),p.remainingBalance=k),w&&!p.resetTime&&(p.resetTime=new Date(w).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},sR=new Gd,iR=new Jd,aR=new Vd,uR=new Kd,cR=new Yd,lR=new Qd,dR=new Xd;function Zd(t){let e=ef(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?lR:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?dR:e==="deepseek.com"||e.endsWith(".deepseek.com")?sR:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?iR:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?aR:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?uR:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?cR:null:null}function fR(t){let e=ef(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function ef(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Ce(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 n=Number(e);return Number.isFinite(n)?n:void 0}var hR={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function pR(t){return t===!0||t==="true"||t===1||t==="1"}function mR(t){let e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`}function gR(t){try{let e=new URL(t),n=e.pathname;return n.endsWith("/v1/messages")?n=n.slice(0,-12):n.endsWith("/messages")?n=n.slice(0,-9):n.endsWith("/v1/chat/completions")?n=n.slice(0,-20):n.endsWith("/chat/completions")&&(n=n.slice(0,-17)),n.endsWith("/v1")||(n=n.endsWith("/")?`${n}v1`:`${n}/v1`),e.pathname=`${n}/models`,e.toString()}catch{return null}}function yR(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function tf(t,e,n){let r=gR(t.baseUrl);if(!r)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(n)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(n).toString())}catch{}let s=await fetch(r,o);if(s.headers&&Fo(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)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"}}}async function _R(t,e,n,r){let o=t.wakeupModel||(Array.isArray(t.models)?t.models[0]:void 0);if(!o)return{success:!1,error:"No models configured for provider"};let s=t.baseUrl.includes("anthropic")||o.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:o,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(n).toString())}catch{}r?.info(`Sending scheduled wake-up call to provider ${t.name} using model ${o}...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown wake-up error"}}}async function bR(t,e,n,r,o){let s=t.baseUrl.includes("anthropic")||e.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:e,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(r).toString())}catch{}o?.debug?.(`Sending independent ping to rate-limited model ${t.name} (${e})...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown ping error"}}}var nu=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,n,r,o,s){this.config={...hR,...n},this.getProviders=e,this.getHttpsProxy=r,this.logger=o,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*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.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&!this.config.excludeProviders.includes(a.name)),n=this.getHttpsProxy?.(),r=Ye();if(e.length===0)return;let o=[];for(let a of e){let c=Zd(a.baseUrl),l=Array.isArray(a.models)?a.models:[];c&&o.push({provider:a.name,models:l,type:"quota-adapter",promise:c.queryQuota(a,this.config.probeTimeoutMs,n).then(d=>{if(d){nc(a.name,d),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let f=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,p=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(f||p){let m=f?`Quota exhausted: 5h limit reached (${d.usedDailyBalance}/${d.limitDaily})`:`Quota exhausted: 7d balance depleted (${d.usedBalance}/${d.totalBalance})`;for(let b of l){if(r.getState(a.name,b)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${a.name} (${b}): already rate-limited with active cooldown`);continue}r.forceOpen(a.name,b,m)}this.logger?.warn?.(`${m} for ${a.name}, marked as unhealthy`)}else for(let m of l){let b=r.getState(a.name,m);b&&b.status==="open"&&b.lastError?.includes("Quota exhausted")&&(r.recover(a.name,m),this.logger?.info?.(`Quota recovered for ${a.name} (${m}), marked as healthy`))}}})}),yR(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:tf(a,this.config.probeTimeoutMs,n).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(o.map(a=>a.promise));for(let a=0;a<o.length;a++){let c=s[a];if(c.status==="rejected"){let l=o[a];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${c.reason}`)}}}async runHealthProbe(){let e=Ye(),n=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(n.length===0)return;this.logger?.debug?.(`Running health probe for ${n.length} providers`);let o=await Promise.allSettled(n.map(s=>tf(s,this.config.probeTimeoutMs,r)));for(let s=0;s<n.length;s++){let a=n[s],c=o[s],l=Array.isArray(a.models)?a.models:[];if(c.status==="fulfilled"){let d=c.value;if(d.success){let f=0;for(let p of l){let m=e.getState(a.name,p);if(m&&m.status==="open"){let b=m.lastError?.includes("Quota exhausted"),C=m.rateLimitUntil||m.lastError&&(m.lastError.includes("429")||m.lastError.toLowerCase().includes("rate limit")||m.lastError.toLowerCase().includes("rate_limit")||m.lastError.toLowerCase().includes("too many requests")||m.lastError.toLowerCase().includes("\u9650\u6D41"));if(b){this.logger?.debug?.(`Skipping health probe recovery for ${a.name} (${p}) because quota is exhausted`);continue}if(C||m.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${a.name} (${p})`);continue}}e.recordSuccess(a.name,p),f++}f>0&&this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let f of l)e.recordFailure(a.name,f,d.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${d.error}`)}}else{for(let d of l)e.recordFailure(a.name,d,c.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${c.reason}`)}}}async runRateLimitProbe(){let e=Ye(),n=e.getRateLimitedModels();if(n.length===0)return;let r=this.getProviders(),o=this.getHttpsProxy?.(),s=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${n.length} model(s)`);for(let a of n){let[c,...l]=a.split(","),d=l.join(",");if(!c||!d)continue;let f=e.getState(c,d);if(!f||!f.rateLimitUntil)continue;if(Date.now()>=f.rateLimitUntil){e.recover(c,d),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${a}`);continue}let p=r.find(m=>m?.name===c&&m.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${c} not found or disabled for rate-limit probe`);continue}try{let m=await bR(p,d,s,o,this.logger);if(m.success)this.logger?.info?.(`Rate-limit probe succeeded for ${a}, recovering model`),e.recover(c,d);else if(m.error&&(m.error.includes("429")||m.error.toLowerCase().includes("rate limit")||m.error.toLowerCase().includes("rate_limit")||m.error.toLowerCase().includes("too many requests")||m.error.toLowerCase().includes("\u9650\u6D41"))){let b=Date.now();f.rateLimitUntil&&f.rateLimitUntil>b?f.rateLimitUntil+=120*1e3:f.rateLimitUntil=b+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${a} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${a} returned non-rate-limit error: ${m.error?.slice(0,100)}`)}catch(m){this.logger?.warn?.(`Rate-limit probe exception for ${a}: ${m?.message||m}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let n=new Date,r=n.getHours(),o=n.getMinutes(),s=mR(n),a=this.getHttpsProxy?.(),c=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let d=l.wakeupTime||c,[f,p]=d.split(":"),m=parseInt(f,10),b=parseInt(p,10);if(isNaN(m)||isNaN(b))continue;let C=r>m||r===m&&o>=b,_=(m*60+b)*6e4-(r*60+o)*6e4,g=_>0&&_<=300*1e3;(C||g)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${d}`),_R(l,3e4,a,this.logger).then(y=>{y.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${y.error}`)}).catch(y=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${y}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?pR(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,n){return this.lastWakeupDate.get(e)===n?!0:(this.lastWakeupDate.set(e,n),!1)}async probeProviderManually(e){let r=this.getProviders().find(c=>c.name===e);if(!r)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(r.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let o=this.getHttpsProxy?.(),s=await tf(r,this.config.probeTimeoutMs,o),a=Array.isArray(r.models)?r.models:[];if(s.success)for(let c of a)Ye().recordSuccess(r.name,c);else for(let c of a)Ye().recordFailure(r.name,c,s.error);return s.success}},Zn=null;function Q0(t,e,n,r,o){return Zn||(Zn=new nu(t,e,n,r,o)),Zn}function nf(t,e,n,r,o){let s=Q0(t,e,n,r,o);return s.start(),s}function rf(){Zn&&Zn.stop()}function CR(){Zn&&(Zn.stop(),Zn=null)}$n();var of=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${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,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},X0=new of;var u_=jn(r_(),1);var Co=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
|
|
362
|
+
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 n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};import{get_encoding as QT}from"tiktoken";var ds=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=QT(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 n=this.encoding;if(!n)throw new Error("Encoding not initialized");let r=0,{messages:o,system:s,tools:a}=e;return Array.isArray(o)&&o.forEach(c=>{typeof c.content=="string"?r+=n.encode(c.content).length:Array.isArray(c.content)&&c.content.forEach(l=>{if(l.type==="text")r+=n.encode(l.text).length;else if(l.type==="tool_use")r+=n.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let d=typeof l.content=="string"?l.content:JSON.stringify(l.content);r+=n.encode(d).length}})}),typeof s=="string"?r+=n.encode(s).length:Array.isArray(s)&&s.forEach(c=>{c.type==="text"&&(typeof c.text=="string"?r+=n.encode(c.text).length:Array.isArray(c.text)&&c.text.forEach(l=>{r+=n.encode(l||"").length}))}),a&&a.forEach(c=>{c.description&&(r+=n.encode(c.name+c.description).length),c.input_schema&&(r+=n.encode(JSON.stringify(c.input_schema)).length)}),r}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Xa}from"path";import{homedir as iR}from"os";import{existsSync as Wd,mkdirSync as aR}from"fs";import{promises as Za}from"fs";var YT=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,a=null,c=o;for(;c<n&&(s=s[t[c]]);)s.end&&(a=s.end),++c;a?(o>r&&e.push(t.slice(r,o)),e.push(a),o+=a.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},XT=YT,ZT=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}},ev=ZT,z0=(()=>{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(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),tv=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),nv=tv(z0),M0=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",rv=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|[${M0}])]+`,` ?[^\\s${M0}]+`]]),fs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",tI=new RegExp(`^[${fs}]+$`,"gu"),zd=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"),Ka=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");for(let[r,o]of rv)n=n.replaceAll(r,o);return new RegExp(n,"gu")}else if(t.String!==void 0){let n=ov(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},ov=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),sv=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},iv=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,av=t=>Number.isInteger(t)||typeof t=="bigint",uv=t=>{let e=0;for(let n of t)++e;return e},cv=t=>H0(t.toLowerCase()),It=(...t)=>Array.prototype.concat.apply([],t),Hd=t=>new Map(Object.entries(t)),lv=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},H0=t=>t.replace(new RegExp("\\p{M}","gu"),""),L0=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},dv=t=>t.match(/\S+/g)||[],fv=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},hs=fv,hv=class extends hs{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},xn=hv,pv=class extends xn{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);iv(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
|
|
363
|
+
`: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 n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}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}},mv=pv,gv=class extends xn{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}},yv=gv,_v=class extends xn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>W0(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},bv=_v,Cv=class extends xn{normalize(t){let e=Ka(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},wv=Cv,Ev=class extends xn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Qa=Ev,kv=class extends Qa{constructor(){super(...arguments),this.form="NFC"}},Av=kv,Sv=class extends Qa{constructor(){super(...arguments),this.form="NFD"}},Tv=Sv,vv=class extends Qa{constructor(){super(...arguments),this.form="NFKC"}},Dv=vv,Rv=class extends Qa{constructor(){super(...arguments),this.form="NFKD"}},xv=Rv,Ov=class extends xn{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}},Pv=Ov,Fv=class extends xn{normalize(t){return H0(t)}},Iv=Fv,Bv=class extends xn{normalize(t){return t.toLowerCase()}},Nv=Bv,Mv=class extends xn{normalize(t){return t=this.config.prepend+t,t}},Lv=Mv;function jv(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new mv(t);case"Precompiled":return new yv(t);case"Sequence":return new bv(t);case"Replace":return new wv(t);case"NFC":return new Av(t);case"NFD":return new Tv(t);case"NFKC":return new Dv(t);case"NFKD":return new xv(t);case"Strip":return new Pv(t);case"StripAccents":return new Iv(t);case"Lowercase":return new Nv(t);case"Prepend":return new Lv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var W0=jv,Uv=class extends hs{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},cn=Uv,$v=class extends cn{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=z0,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(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},qv=$v,zv=class extends cn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Hv=zv,Wv=class extends cn{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:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},Gv=Wv,Jv=class extends cn{constructor(t){super(),this.config=t,this.pattern=Ka(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):lv(t,this.pattern)}},Vv=Jv,Kv=class extends cn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${fs}]+|[${fs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Qv=Kv,Yv=class extends cn{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)||[]}},Xv=Yv,Zv=class extends cn{constructor(){super(),this.pattern=new RegExp(`[^\\s${fs}]+|[${fs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},eD=Zv,tD=class extends cn{constructor(t){super(),this.config=t,this.pattern=Ka(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},nD=tD,rD=class extends cn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>G0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},oD=rD,sD=class extends cn{pre_tokenize_text(t){return dv(t)}},iD=sD;function aD(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new eD;case"Sequence":return new oD(t);case"Whitespace":return new Hv;case"WhitespaceSplit":return new iD;case"Metaspace":return new Gv(t);case"ByteLevel":return new qv(t);case"Split":return new Vv(t);case"Punctuation":return new Qv(t);case"Digits":return new Xv(t);case"Replace":return new nD(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var G0=aD,uD=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=sv(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)}},Ya=uD,cD=class extends Ya{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=Hd(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,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let c=r.length,l=null;for(;s<c;){let d=r.slice(s,c).join("");if(s>0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){l=d;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},j0=cD,U0=class J0{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new J0(!1,new Map)}},lD=class{constructor(){this.root=U0.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=U0.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},dD=lD,qd=class V0{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new V0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},fD=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new qd(this.bos_token_id??0,0,0,0,0),o=new qd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new qd(r,o,t,e,n);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 d=l.backtrace_score+s.score;(c===null||d>a)&&(c=l.clone(),a=d)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}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)}},hD=fD;function pD(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var mD=class extends Ya{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,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=pD(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new dD,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let d=this.tokens_to_ids.get(l),f=this.scores[d],p=uv(l);t.insert(r,p,f,d),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new hD(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},$0=mD,gD=class{constructor(t=(n,r)=>n>r,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 n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}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 n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_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}},yD=gD,_D=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()}},bD=_D,CD=class extends Ya{constructor(t){super(t),this.tokens_to_ids=Hd(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[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),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 bD(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 n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new yD((c,l)=>c.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<n.length;++c){let l={bias:c/n.length,token:n[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 d={...c.prev};c.prev.deleted=!0,c.prev=d,d.prev?d.prev.next=d:s=d}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)r.push(c.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)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}},q0=CD,wD=class extends Ya{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=Hd(e.target_lang?n[e.target_lang]:n),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[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},ED=wD;function kD(t,e){switch(t.type){case"WordPiece":return new j0(t);case"Unigram":return new $0(t,e.eos_token);case"BPE":return new q0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new $0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new q0(t):new j0(t):new ED(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 AD=kD,SD=class extends hs{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ps=SD,TD=class extends ps{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=It(o,t),s=It(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=It(o,e),s=It(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},vD=TD,DD=class extends ps{post_process(t,e=null){return{tokens:e?It(t,e):t}}},RD=DD,xD=class extends ps{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=It([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=It(t,o,e,s),r=It(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},OD=xD,PD=class extends ps{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=It([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=It(t,o,e,s),r=It(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},FD=PD,ID=class extends ps{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>K0(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},BD=ID;function ND(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new vD(t);case"ByteLevel":return new RD(t);case"BertProcessing":return new OD(t);case"RobertaProcessing":return new FD(t);case"Sequence":return new BD(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var K0=ND,MD=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("")}},ln=MD,LD=class extends ln{constructor(t){super(t),this.byte_decoder=nv,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(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},jD=LD,UD=class extends ln{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=zd(e)),e})}},$D=UD,qD=class extends ln{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},zD=qD,HD=class extends ln{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},WD=HD,GD=class extends ln{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 r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=zd(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},JD=GD,VD=class extends ln{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Q0(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},KD=VD,QD=class extends ln{decode_chain(t){let e=Ka(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},YD=QD,XD=class extends ln{decode_chain(t){return[t.join("")]}},ZD=XD,eR=class extends ln{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 n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},tR=eR,nR=class extends ln{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},rR=nR;function oR(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new jD(t);case"WordPiece":return new $D(t);case"Metaspace":return new zD(t);case"BPEDecoder":return new WD(t);case"CTC":return new JD(t);case"Sequence":return new KD(t);case"Replace":return new YD(t);case"Fuse":return new ZD(t);case"Strip":return new tR(t);case"ByteFallback":return new rR(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Q0=oR,sR=class{constructor(t,e){let n=L0(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=L0(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=W0(this.tokenizer.normalizer),this.pre_tokenizer=G0(this.tokenizer.pre_tokenizer),this.model=AD(this.tokenizer.model,this.config),this.post_processor=K0(this.tokenizer.post_processor),this.decoder=Q0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new ev(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 XT(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:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!av(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=zd(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=cv(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:It(r??[],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}},Y0=sR;var eu=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||Xa(iR(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Xa(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Xa(e,"tokenizer.json"),tokenizerConfig:Xa(e,"tokenizer_config.json")}}ensureDir(e){Wd(e)||aR(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Wd(e.tokenizerJson)||!Wd(e.tokenizerConfig))return null;let[n,r]=await Promise.all([Za.readFile(e.tokenizerJson,"utf-8"),Za.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={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 r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.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([Za.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Za.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 n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new Y0(n.tokenizerJson,n.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 n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}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 n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?n.push(c.text):c.type==="tool_use"&&c.input?n.push(JSON.stringify(c.input)):c.type==="tool_result"&&n.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&n.push(c)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var tu=class{type="api";name;config;logger;options;constructor(e,n,r={}){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=n,this.options=r;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 n=this.formatRequestBody(e),r={"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:r,body:JSON.stringify(n),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(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}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(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var _o=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}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 n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new ds(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new eu(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=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 r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}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,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),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)}`}}};$n();var dn=class{async fetchJson(e,n,r,o,s){let a=s||n.apiKey;if(!a)return null;let c={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(r)};if(o)try{let{ProxyAgent:l}=await import("undici");c.dispatcher=new l(new URL(o).toString())}catch{}try{let l=await fetch(e,c);return l.ok?await l.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}},Gd=class extends dn{async queryQuota(e,n,r){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,n,r),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>_e(l?.total_balance)!==void 0);if(!a)return null;let c=_e(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},Jd=class extends dn{async queryQuota(e,n,r){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,n,r))?.data;if(!s||typeof s!="object")return null;let a={},c=_e(s.limit),l=_e(s.limit_remaining),d=_e(s.usage),f=_e(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),d!==void 0&&(a.usedBalance=d),f!==void 0&&(a.usedDailyBalance=f),this.hasQuotaData(a)?a:null}},Vd=class extends dn{async queryQuota(e,n,r){let o=gR(e.baseUrl),a=(await this.fetchJson(o,e,n,r))?.data;if(!a||typeof a!="object")return null;let c={},l=_e(a.totalBalance),d=_e(a.balance);return l!==void 0&&(c.totalBalance=l),d!==void 0&&(c.remainingBalance=d),l!==void 0&&d!==void 0&&(c.usedBalance=Math.max(0,l-d)),this.hasQuotaData(c)?c:null}},Kd=class extends dn{async queryQuota(e,n,r){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let c=await a.json(),l=Array.isArray(c?.data?.limits)?c.data.limits:[],d=null,f=null,p=null;for(let b of l)b.type==="TOKENS_LIMIT"?b.unit===3?d=b:b.unit===6?f=b:d||(d=b):b.type==="TIME_LIMIT"&&(p=b);let m={};if(d){let b=_e(d.currentValue),C=_e(d.usage),_=_e(d.remaining),y=_e(d.percentage);b!==void 0?m.usedDailyBalance=b:y!==void 0&&(m.usedDailyBalance=y,m.limitDaily=100),C!==void 0?m.limitDaily=C:b!==void 0&&_!==void 0&&(m.limitDaily=b+_),d.nextResetTime&&(m.resetTime=new Date(d.nextResetTime).toISOString())}if(f){let b=_e(f.currentValue),C=_e(f.usage),_=_e(f.remaining),y=_e(f.percentage);b!==void 0?m.usedBalance=b:y!==void 0&&(m.usedBalance=y,m.totalBalance=100),C!==void 0?m.totalBalance=C:b!==void 0&&_!==void 0&&(m.totalBalance=b+_),f.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(f.nextResetTime).toISOString())}if(p){if(m.usedDailyBalance===void 0){let b=_e(p.currentValue);b!==void 0&&(m.usedDailyBalance=b)}if(m.limitDaily===void 0){let b=_e(p.usage),C=_e(p.currentValue),_=_e(p.remaining);b!==void 0?m.limitDaily=b:C!==void 0&&_!==void 0&&(m.limitDaily=C+_)}p.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(m)?m:null}catch{return null}}},Qd=class extends dn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{let c=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...o,body:a});if(!c.ok)return null;let d=(await c.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(d)||d.length===0)return null;let f=d[0]?.codingPlanQuotaInfo;if(!f)return null;let p={},m=_e(f.per5HourUsedQuota),b=_e(f.per5HourTotalQuota);m!==void 0&&(p.usedDailyBalance=m),b!==void 0&&(p.limitDaily=b);let C=_e(f.perWeekUsedQuota),_=_e(f.perWeekTotalQuota);return C!==void 0&&(p.usedBalance=C),_!==void 0&&(p.totalBalance=_),this.hasQuotaData(p)?p:null}catch{return null}}},Yd=class extends dn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(X0(e.quotaToken,"atp-auth-token")||X0(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let c=await a.json();if(c?.succeed===!1||c?.failed===!0)return null;let l=yR(c,e.apiKey),d=l?.codingPlanUsageDTO||l?.usage||l;if(!d||typeof d!="object")return null;let f={},p=_e(d.rp5hUsage),m=_e(d.rp5hLimit);p!==void 0&&(f.usedDailyBalance=p),m!==void 0&&(f.limitDaily=m);let b=_e(d.rpwUsage),C=_e(d.rpwLimit);return b!==void 0&&(f.usedBalance=b),C!==void 0&&(f.totalBalance=C),f.remainingBalance===void 0&&C!==void 0&&b!==void 0&&(f.remainingBalance=Math.max(0,C-b)),this.hasQuotaData(f)?f:null}catch{return null}}},Xd=class extends dn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let c=await a.json(),l={},d=Array.isArray(c?.limits)?c.limits:[];if(d.length>0&&d[0]?.detail){let p=d[0].detail,m=_e(p.limit),b=_e(p.remaining),C=p.resetTime;m!==void 0&&b!==void 0&&(l.usedDailyBalance=Math.max(0,m-b),l.limitDaily=m),C&&(l.resetTime=new Date(C).toISOString())}let f=c?.usage;if(f){let p=_e(f.limit),m=_e(f.remaining),b=_e(f.used),C=f.resetTime;p!==void 0&&(l.totalBalance=p,b!==void 0?l.usedBalance=b:m!==void 0&&(l.usedBalance=Math.max(0,p-m),l.remainingBalance=m)),C&&(l.resetTime7d=new Date(C).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Zd=class extends dn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=nf(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let c=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let A of c)if(l=await this.fetchJson(A,e,n,r,o.trim()),l)break;if(!l)return null;if(l?.base_resp){let A=l.base_resp.status_code;if(A!==void 0&&A!==0)return null}let d=Array.isArray(l?.model_remains)?l.model_remains:[];if(d.length===0)return null;let f=d[0],p={},m=_e(f.current_interval_total_count),b=_e(f.current_interval_usage_count),C=_e(f.current_interval_remaining_percent),_=_e(f.end_time);m!==void 0&&b!==void 0&&m>0?(p.usedDailyBalance=Math.max(0,m-b),p.limitDaily=m):C!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-C)),_&&(p.resetTime=new Date(_).toISOString());let y=_e(f.current_weekly_total_count),g=_e(f.current_weekly_usage_count),S=_e(f.current_weekly_remaining_percent),w=_e(f.weekly_end_time);return y!==void 0&&g!==void 0&&y>0?(p.usedBalance=Math.max(0,y-g),p.remainingBalance=g,p.totalBalance=y):S!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-S),p.remainingBalance=S),w&&!p.resetTime&&(p.resetTime=new Date(w).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},uR=new Gd,cR=new Jd,lR=new Vd,dR=new Kd,fR=new Qd,hR=new Yd,pR=new Xd,mR=new Zd;function tf(t){let e=nf(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?pR:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?mR:e==="deepseek.com"||e.endsWith(".deepseek.com")?uR:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?cR:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?lR:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?dR:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?fR:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?hR:null:null}function gR(t){let e=nf(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function yR(t,e){let n=ef(t);if(n.length===0)return null;let r=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return n.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,c=String(a?.apiKey||a?.api_key||"").trim();return c&&r.some(l=>l.includes(c)||c.includes(l))})||n[0]}function ef(t){return!t||typeof t!="object"?[]:!Array.isArray(t)&&t.codingPlanUsageDTO?[t]:Array.isArray(t)?t.flatMap(e=>ef(e)):Object.values(t).flatMap(e=>ef(e))}function X0(t,e){let n=t.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return n?decodeURIComponent(n[1]):void 0}function nf(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function _e(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 n=Number(e);return Number.isFinite(n)?n:void 0}var _R={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function bR(t){return t===!0||t==="true"||t===1||t==="1"}function CR(t){let e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`}function wR(t){try{let e=new URL(t),n=e.pathname;return n.endsWith("/v1/messages")?n=n.slice(0,-12):n.endsWith("/messages")?n=n.slice(0,-9):n.endsWith("/v1/chat/completions")?n=n.slice(0,-20):n.endsWith("/chat/completions")&&(n=n.slice(0,-17)),n.endsWith("/v1")||(n=n.endsWith("/")?`${n}v1`:`${n}/v1`),e.pathname=`${n}/models`,e.toString()}catch{return null}}function ER(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function rf(t,e,n){let r=wR(t.baseUrl);if(!r)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(n)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(n).toString())}catch{}let s=await fetch(r,o);if(s.headers&&Po(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)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"}}}async function kR(t,e,n,r){let o=t.wakeupModel||(Array.isArray(t.models)?t.models[0]:void 0);if(!o)return{success:!1,error:"No models configured for provider"};let s=t.baseUrl.includes("anthropic")||o.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:o,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(n).toString())}catch{}r?.info(`Sending scheduled wake-up call to provider ${t.name} using model ${o}...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown wake-up error"}}}async function AR(t,e,n,r,o){let s=t.baseUrl.includes("anthropic")||e.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:e,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(r).toString())}catch{}o?.debug?.(`Sending independent ping to rate-limited model ${t.name} (${e})...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown ping error"}}}var nu=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,n,r,o,s){this.config={..._R,...n},this.getProviders=e,this.getHttpsProxy=r,this.logger=o,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*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.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&!this.config.excludeProviders.includes(a.name)),n=this.getHttpsProxy?.(),r=Qe();if(e.length===0)return;let o=[];for(let a of e){let c=tf(a.baseUrl),l=Array.isArray(a.models)?a.models:[];c&&o.push({provider:a.name,models:l,type:"quota-adapter",promise:c.queryQuota(a,this.config.probeTimeoutMs,n).then(d=>{if(d){nc(a.name,d),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let f=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,p=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(f||p){let m=f?`Quota exhausted: 5h limit reached (${d.usedDailyBalance}/${d.limitDaily})`:`Quota exhausted: 7d balance depleted (${d.usedBalance}/${d.totalBalance})`;for(let b of l){if(r.getState(a.name,b)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${a.name} (${b}): already rate-limited with active cooldown`);continue}r.forceOpen(a.name,b,m)}this.logger?.warn?.(`${m} for ${a.name}, marked as unhealthy`)}else for(let m of l){let b=r.getState(a.name,m);b&&b.status==="open"&&b.lastError?.includes("Quota exhausted")&&(r.recover(a.name,m),this.logger?.info?.(`Quota recovered for ${a.name} (${m}), marked as healthy`))}}})}),ER(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:rf(a,this.config.probeTimeoutMs,n).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(o.map(a=>a.promise));for(let a=0;a<o.length;a++){let c=s[a];if(c.status==="rejected"){let l=o[a];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${c.reason}`)}}}async runHealthProbe(){let e=Qe(),n=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(n.length===0)return;this.logger?.debug?.(`Running health probe for ${n.length} providers`);let o=await Promise.allSettled(n.map(s=>rf(s,this.config.probeTimeoutMs,r)));for(let s=0;s<n.length;s++){let a=n[s],c=o[s],l=Array.isArray(a.models)?a.models:[];if(c.status==="fulfilled"){let d=c.value;if(d.success){let f=0;for(let p of l){let m=e.getState(a.name,p);if(m&&m.status==="open"){let b=m.lastError?.includes("Quota exhausted"),C=m.rateLimitUntil||m.lastError&&(m.lastError.includes("429")||m.lastError.toLowerCase().includes("rate limit")||m.lastError.toLowerCase().includes("rate_limit")||m.lastError.toLowerCase().includes("too many requests")||m.lastError.toLowerCase().includes("\u9650\u6D41"));if(b){this.logger?.debug?.(`Skipping health probe recovery for ${a.name} (${p}) because quota is exhausted`);continue}if(C||m.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${a.name} (${p})`);continue}}e.recordSuccess(a.name,p),f++}f>0&&this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let f of l)e.recordFailure(a.name,f,d.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${d.error}`)}}else{for(let d of l)e.recordFailure(a.name,d,c.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${c.reason}`)}}}async runRateLimitProbe(){let e=Qe(),n=e.getRateLimitedModels();if(n.length===0)return;let r=this.getProviders(),o=this.getHttpsProxy?.(),s=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${n.length} model(s)`);for(let a of n){let[c,...l]=a.split(","),d=l.join(",");if(!c||!d)continue;let f=e.getState(c,d);if(!f||!f.rateLimitUntil)continue;if(Date.now()>=f.rateLimitUntil){e.recover(c,d),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${a}`);continue}let p=r.find(m=>m?.name===c&&m.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${c} not found or disabled for rate-limit probe`);continue}try{let m=await AR(p,d,s,o,this.logger);if(m.success)this.logger?.info?.(`Rate-limit probe succeeded for ${a}, recovering model`),e.recover(c,d);else if(m.error&&(m.error.includes("429")||m.error.toLowerCase().includes("rate limit")||m.error.toLowerCase().includes("rate_limit")||m.error.toLowerCase().includes("too many requests")||m.error.toLowerCase().includes("\u9650\u6D41"))){let b=Date.now();f.rateLimitUntil&&f.rateLimitUntil>b?f.rateLimitUntil+=120*1e3:f.rateLimitUntil=b+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${a} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${a} returned non-rate-limit error: ${m.error?.slice(0,100)}`)}catch(m){this.logger?.warn?.(`Rate-limit probe exception for ${a}: ${m?.message||m}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let n=new Date,r=n.getHours(),o=n.getMinutes(),s=CR(n),a=this.getHttpsProxy?.(),c=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let d=l.wakeupTime||c,[f,p]=d.split(":"),m=parseInt(f,10),b=parseInt(p,10);if(isNaN(m)||isNaN(b))continue;let C=r>m||r===m&&o>=b,_=(m*60+b)*6e4-(r*60+o)*6e4,y=_>0&&_<=300*1e3;(C||y)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${d}`),kR(l,3e4,a,this.logger).then(g=>{g.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${g.error}`)}).catch(g=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${g}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?bR(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,n){return this.lastWakeupDate.get(e)===n?!0:(this.lastWakeupDate.set(e,n),!1)}async probeProviderManually(e){let r=this.getProviders().find(c=>c.name===e);if(!r)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(r.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let o=this.getHttpsProxy?.(),s=await rf(r,this.config.probeTimeoutMs,o),a=Array.isArray(r.models)?r.models:[];if(s.success)for(let c of a)Qe().recordSuccess(r.name,c);else for(let c of a)Qe().recordFailure(r.name,c,s.error);return s.success}},Zn=null;function Z0(t,e,n,r,o){return Zn||(Zn=new nu(t,e,n,r,o)),Zn}function of(t,e,n,r,o){let s=Z0(t,e,n,r,o);return s.start(),s}function sf(){Zn&&Zn.stop()}function SR(){Zn&&(Zn.stop(),Zn=null)}$n();var af=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${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,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},e_=new af;var d_=jn(s_(),1);var bo=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
|
|
362
364
|
`);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,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 ou=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
|
|
363
365
|
`),e.id&&(r+=`id: ${e.id}
|
|
364
366
|
`),e.retry&&(r+=`retry: ${e.retry}
|
|
365
367
|
`),e.data&&(e.data.type==="done"?r+=`data: [DONE]
|
|
366
368
|
`:r+=`data: ${JSON.stringify(e.data)}
|
|
367
369
|
`),r+=`
|
|
368
|
-
`,n.enqueue(r)}})}};var o_=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};uf();cf();lf();i_();var Cr=new Map,ff=new Map,xR=1,c_={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,u_.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)wo.registerHandlers(n.outputHandlers);else{let a=[];for(let c of r)c==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):c==="temp-file"?a.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):c==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&wo.registerHandlers(a)}n.outputOptions&&wo.setDefaultOptions(n.outputOptions);let o=async a=>{let c=t.tokenizerService;if(!c)return t.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,d=a.model,f=`${l}:${d}`;if(ff.has(f))return ff.get(f);let p=c.getTokenizerConfigForModel(l,d);if(!p)return t.log?.debug(`No tokenizer config for ${l}:${d}, using fallback`),null;try{let m=await c.getTokenizer(p);return ff.set(f,m),t.log?.info(`Created tokenizer for ${l}:${d} - ${m.name}`),m}catch(m){return t.log?.warn(`Failed to create tokenizer for ${l}:${d}: ${m.message}`),null}},s=a=>{let c=new URL(`http://127.0.0.1${a}`).pathname;return c.endsWith("/v1/messages")||c.endsWith("/v1/responses")};t.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),t.addHook("onSend",async(a,c,l)=>{let d=a.requestStartTime;if(!d)return;let f=a.id||Date.now().toString(),p;try{let g=a.body?.metadata?.user_id;if(g&&typeof g=="string")try{let y=JSON.parse(g);y.session_id&&(p=y.session_id)}catch{let y=g.match(/_session_([a-f0-9-]+)/i);p=y?y[1]:void 0}}catch{}if(!p){let g=a.headers?.["x-request-id"],y=Array.isArray(g)?g[0]:g;p=a.sessionId||(typeof y=="string"?y:void 0)||f}let m=await o(a);if(l instanceof ReadableStream){Cr.set(f,{requestId:f,sessionId:p,startTime:d,lastTokenTime:d,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let g=a,y=null;g.tokenSpeedStatsPromise=new Promise(v=>{y=v});let k=v=>{let $=v.firstTokenTime?Math.max(0,Math.round(v.firstTokenTime-v.startTime)):typeof v.timeToFirstToken=="number"?Math.max(0,Math.round(v.timeToFirstToken)):null,Y=Math.max(0,Math.round(v.lastTokenTime-v.startTime));g.tokenSpeedStats={requestId:v.requestId,sessionId:v.sessionId,tokenCount:v.tokenCount,tokensPerSecond:v.tokensPerSecond,timeToFirstToken:$,durationMs:Y,stream:v.stream,timestamp:Date.now()},y&&(y(g.tokenSpeedStats),y=null)},[w,S]=l.tee();return(async()=>{let v=null,$=!1,Y=async P=>{let V=Cr.get(f);if(!V)return;let H=performance.now();if(P){V.lastTokenTime=Math.max(V.lastTokenTime,H);let Q=V.firstTokenTime?V.firstTokenTime-V.startTime:0,J=V.lastTokenTime-V.startTime;V.tokensPerSecond=hf(V.tokenCount,J,Q),k(V),$=!0}else{let Q=H-1e3;V.tokenTimestamps=V.tokenTimestamps.filter(J=>J>Q),V.tokensPerSecond=V.tokenTimestamps.length}await a_(V,r,n.outputOptions,P).catch(Q=>{t.log?.warn(`Failed to output streaming stats: ${Q.message}`)})};try{let V=S.pipeThrough(new TextDecoderStream).pipeThrough(new Co).getReader();for(v=setInterval(async()=>{Cr.get(f)&&await Y(!1)},1e3);;){let{done:H,value:Q}=await V.read();if(H)break;let J=Q,ee=Cr.get(f);if(!ee)continue;let ce=performance.now(),re=J.event||J.data?.type,me=J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="text_block"||J.event==="content_block"||re==="response.output_text.delta"||re==="response.function_call_arguments.delta"||re==="response.reasoning_summary_text.delta";!ee.firstTokenTime&&me&&(ee.firstTokenTime=ce,ee.timeToFirstToken=Math.round(ce-ee.startTime));let z="";if(J.event==="content_block_delta"&&J.data?.delta){let Z=J.data.delta.type;Z==="text_delta"?z=J.data.delta.text||"":Z==="input_json_delta"?z=J.data.delta.partial_json||"":Z==="thinking_delta"&&(z=J.data.delta.thinking||"")}if((re==="response.output_text.delta"||re==="response.function_call_arguments.delta"||re==="response.reasoning_summary_text.delta")&&(z=typeof J.data?.delta=="string"?J.data.delta:""),z){let Z=m&&m.encodeText?m.encodeText(z).length:bs(z);ee.tokenCount+=Z,ee.lastTokenTime=ce;for(let ie=0;ie<Z;ie++)ee.tokenTimestamps.push(ce)}(J.event==="message_stop"||re==="response.completed"||re==="response.failed")&&(v&&(clearInterval(v),v=null),await Y(!0),Cr.delete(f))}}catch(P){P.name!=="AbortError"&&P.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${P.message}`)}finally{if(v&&clearInterval(v),!$){let P=Cr.get(f);if(P){let V=performance.now();P.lastTokenTime=Math.max(P.lastTokenTime,V);let H=P.firstTokenTime?P.firstTokenTime-P.startTime:0,Q=P.lastTokenTime-P.startTime;P.tokensPerSecond=hf(P.tokenCount,Q,H),k(P),Cr.delete(f)}else y&&(y(null),y=null)}}})().catch(v=>{console.log(v),t.log?.warn(`Background stats processing failed: ${v.message}`)}),w}let b=performance.now(),C=0,_=!1;if(l&&typeof l=="string")try{let g=JSON.parse(l);if(typeof g.usage?.output_tokens=="number")C=g.usage.output_tokens,_=!0;else{let y=g.content??g.message?.content;if(y!==void 0)if(_=!0,m)Array.isArray(y)?C=y.reduce((k,w)=>{if(w.type==="text"){let S=w.text||"";return k+(m.encodeText?m.encodeText(S).length:bs(S))}return k},0):typeof y=="string"&&(C=m.encodeText?m.encodeText(y).length:bs(y));else{let k=Array.isArray(y)?y.map(w=>w.text).join(""):typeof y=="string"?y:"";C=bs(k)}}}catch{}if(_){let g=Math.round(b-d),y=b-d,k={requestId:f,sessionId:p,startTime:d,lastTokenTime:b,tokenCount:C,tokensPerSecond:hf(C,y),timeToFirstToken:g,stream:!1,tokenTimestamps:[]},w=a;w.tokenSpeedStats={requestId:k.requestId,sessionId:k.sessionId,tokenCount:k.tokenCount,tokensPerSecond:k.tokensPerSecond,timeToFirstToken:Math.max(0,g),durationMs:Math.max(0,Math.round(y)),stream:!1,timestamp:Date.now()},await a_(k,r,n.outputOptions,!0)}return l})})};function hf(t,e,n=0){if(t<=0)return 0;let r=Math.max((e-n)/1e3,xR);return Math.round(t/r)}function bs(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function a_(t,e,n,r=!1){let o=r?"[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},...n};for(let c of e)try{await wo.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}$n();$n();function FR(t={}){let e=OR({bodyLimit:52428800,...t});return e.setErrorHandler(Oh),e.register(PR),e}var pf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:n,...r}=e;this.app=FR({...r,logger:r.logger??!0}),this.configService=new Nr(e),this.transformerService=new _o(this.configService,this.app.log),this.tokenizerService=new bo(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Ur(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){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,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Io(l,d,{configService:this.configService,tokenizerService:this.tokenizerService})}),await uc(c)});return}if(!n)throw new Error("options is required");let r=new Nr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new _o(r,this.app.log);await o.initialize();let s=new Ur(r,o,this.app.log),a=new bo(r,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",r),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Io(l,d,{configService:r,tokenizerService:a})}),await uc(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let c=r.body;r.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let c=a.model.split(","),l=a.model;if(c.length>1){let[d,...f]=c;l=f.join(","),a.model=l,r.provider=d}r.model=l;return}catch(a){return r.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{Qu()}catch{}try{oc()}catch{}try{Ju()}catch{}try{let r={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=nf(()=>this.providerService.getProviders(),r,()=>this.configService.getHttpsProxy(),this.app.log,o=>this.configService.get(o))}catch(r){this.app.log.warn?.(`Failed to start active probe service: ${r.message}`)}let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`);try{rf()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},JB=pf;export{nu as ActiveProbeService,Nr as ConfigService,ti as ProviderHealthStore,Ur as ProviderService,Co as SSEParserTransform,ou as SSESerializerTransform,bo as TokenizerService,_o as TransformerService,sp as calculateTokenCount,JB as default,Q0 as getActiveProbeService,$C as getAllQuotaResults,PC as getAllRateLimitInfo,Ye as getHealthStore,Zd as getQuotaAdapter,rc as getQuotaResult,OC as getRateLimitInfo,lC as getRuntimeDebugLog,Ju as initProviderHealthPersistence,oc as initQuotaStorePersistence,Qu as initRateLimitPersistence,X0 as pluginManager,CR as resetActiveProbeService,o_ as rewriteStream,Io as router,cp as searchProjectBySession,Zu as sessionUsageCache,cC as setRuntimeDebugLog,nf as startActiveProbe,rf as stopActiveProbe,nc as storeQuotaResult,c_ as tokenSpeedPlugin};
|
|
370
|
+
`,n.enqueue(r)}})}};var i_=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};lf();df();ff();u_();var _s=new Map,pf=new Map,BR=1,f_={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,d_.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)Co.registerHandlers(n.outputHandlers);else{let a=[];for(let c of r)c==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):c==="temp-file"?a.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):c==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&Co.registerHandlers(a)}n.outputOptions&&Co.setDefaultOptions(n.outputOptions);let o=async a=>{let c=t.tokenizerService;if(!c)return t.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,d=a.model,f=`${l}:${d}`;if(pf.has(f))return pf.get(f);let p=c.getTokenizerConfigForModel(l,d);if(!p)return t.log?.debug(`No tokenizer config for ${l}:${d}, using fallback`),null;try{let m=await c.getTokenizer(p);return pf.set(f,m),t.log?.info(`Created tokenizer for ${l}:${d} - ${m.name}`),m}catch(m){return t.log?.warn(`Failed to create tokenizer for ${l}:${d}: ${m.message}`),null}},s=a=>{let c=new URL(`http://127.0.0.1${a}`).pathname;return c.endsWith("/v1/messages")||c.endsWith("/v1/responses")};t.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),t.addHook("onSend",async(a,c,l)=>{let d=a.requestStartTime;if(!d)return;let f=a.id||Date.now().toString(),p;try{let y=a.body?.metadata?.user_id;if(y&&typeof y=="string")try{let g=JSON.parse(y);g.session_id&&(p=g.session_id)}catch{let g=y.match(/_session_([a-f0-9-]+)/i);p=g?g[1]:void 0}}catch{}if(!p){let y=a.headers?.["x-request-id"],g=Array.isArray(y)?y[0]:y;p=a.sessionId||(typeof g=="string"?g:void 0)||f}let m=await o(a);if(l instanceof ReadableStream){_s.set(f,{requestId:f,sessionId:p,startTime:d,lastTokenTime:d,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,g]=l.tee();return(async()=>{let w=null,A=async v=>{let R=_s.get(f);if(!R)return;let $=performance.now();if(v){let V=R.firstTokenTime?R.firstTokenTime-R.startTime:0,P=R.lastTokenTime-R.startTime;R.tokensPerSecond=c_(R.tokenCount,P,V)}else{let V=$-1e3;R.tokenTimestamps=R.tokenTimestamps.filter(P=>P>V),R.tokensPerSecond=R.tokenTimestamps.length}await l_(R,r,n.outputOptions,v).catch(V=>{t.log?.warn(`Failed to output streaming stats: ${V.message}`)})};try{let R=g.pipeThrough(new TextDecoderStream).pipeThrough(new bo).getReader();for(w=setInterval(async()=>{_s.get(f)&&await A(!1)},1e3);;){let{done:$,value:V}=await R.read();if($)break;let P=V,Q=_s.get(f);if(!Q)continue;let z=performance.now(),K=P.event||P.data?.type,Y=P.event==="content_block_start"||P.event==="content_block_delta"||P.event==="text_block"||P.event==="content_block"||K==="response.output_text.delta"||K==="response.function_call_arguments.delta"||K==="response.reasoning_summary_text.delta";!Q.firstTokenTime&&Y&&(Q.firstTokenTime=z,Q.timeToFirstToken=Math.round(z-Q.startTime));let ee="";if(P.event==="content_block_delta"&&P.data?.delta){let ae=P.data.delta.type;ae==="text_delta"?ee=P.data.delta.text||"":ae==="input_json_delta"?ee=P.data.delta.partial_json||"":ae==="thinking_delta"&&(ee=P.data.delta.thinking||"")}if((K==="response.output_text.delta"||K==="response.function_call_arguments.delta"||K==="response.reasoning_summary_text.delta")&&(ee=typeof P.data?.delta=="string"?P.data.delta:""),ee){let ae=m&&m.encodeText?m.encodeText(ee).length:bs(ee);Q.tokenCount+=ae,Q.lastTokenTime=z;for(let se=0;se<ae;se++)Q.tokenTimestamps.push(z)}(P.event==="message_stop"||K==="response.completed"||K==="response.failed")&&(w&&(clearInterval(w),w=null),await A(!0),_s.delete(f))}}catch(v){w&&clearInterval(w),v.name!=="AbortError"&&v.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${v.message}`)}})().catch(w=>{console.log(w),t.log?.warn(`Background stats processing failed: ${w.message}`)}),y}let b=performance.now(),C=0,_=!1;if(l&&typeof l=="string")try{let y=JSON.parse(l);if(typeof y.usage?.output_tokens=="number")C=y.usage.output_tokens,_=!0;else{let g=y.content??y.message?.content;if(g!==void 0)if(_=!0,m)Array.isArray(g)?C=g.reduce((S,w)=>{if(w.type==="text"){let A=w.text||"";return S+(m.encodeText?m.encodeText(A).length:bs(A))}return S},0):typeof g=="string"&&(C=m.encodeText?m.encodeText(g).length:bs(g));else{let S=Array.isArray(g)?g.map(w=>w.text).join(""):typeof g=="string"?g:"";C=bs(S)}}}catch{}if(_){let y=Math.round(b-d),g=b-d,S={requestId:f,sessionId:p,startTime:d,lastTokenTime:b,tokenCount:C,tokensPerSecond:c_(C,g),timeToFirstToken:y,stream:!1,tokenTimestamps:[]};await l_(S,r,n.outputOptions,!0)}return l})})};function c_(t,e,n=0){if(t<=0)return 0;let r=Math.max((e-n)/1e3,BR);return Math.round(t/r)}function bs(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function l_(t,e,n,r=!1){let o=r?"[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},...n};for(let c of e)try{await Co.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}$n();$n();function LR(t={}){let e=NR({bodyLimit:52428800,...t});return e.setErrorHandler(Ph),e.register(MR),e}var mf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:n,...r}=e;this.app=LR({...r,logger:r.logger??!0}),this.configService=new Ir(e),this.transformerService=new yo(this.configService,this.app.log),this.tokenizerService=new _o(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new jr(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){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,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Fo(l,d,{configService:this.configService,tokenizerService:this.tokenizerService})}),await uc(c)});return}if(!n)throw new Error("options is required");let r=new Ir({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new yo(r,this.app.log);await o.initialize();let s=new jr(r,o,this.app.log),a=new _o(r,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",r),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Fo(l,d,{configService:r,tokenizerService:a})}),await uc(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let c=r.body;r.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let c=a.model.split(","),l=a.model;if(c.length>1){let[d,...f]=c;l=f.join(","),a.model=l,r.provider=d}r.model=l;return}catch(a){return r.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{Yu()}catch{}try{oc()}catch{}try{Ju()}catch{}try{let r={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=of(()=>this.providerService.getProviders(),r,()=>this.configService.getHttpsProxy(),this.app.log,o=>this.configService.get(o))}catch(r){this.app.log.warn?.(`Failed to start active probe service: ${r.message}`)}let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`);try{sf()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},XN=mf;export{nu as ActiveProbeService,Ir as ConfigService,ti as ProviderHealthStore,jr as ProviderService,bo as SSEParserTransform,ou as SSESerializerTransform,_o as TokenizerService,yo as TransformerService,ip as calculateTokenCount,XN as default,Z0 as getActiveProbeService,HC as getAllQuotaResults,BC as getAllRateLimitInfo,Qe as getHealthStore,tf as getQuotaAdapter,rc as getQuotaResult,IC as getRateLimitInfo,hC as getRuntimeDebugLog,Ju as initProviderHealthPersistence,oc as initQuotaStorePersistence,Yu as initRateLimitPersistence,e_ as pluginManager,SR as resetActiveProbeService,i_ as rewriteStream,Fo as router,lp as searchProjectBySession,Zu as sessionUsageCache,fC as setRuntimeDebugLog,of as startActiveProbe,sf as stopActiveProbe,nc as storeQuotaResult,f_ as tokenSpeedPlugin};
|
|
369
371
|
/*! Bundled license information:
|
|
370
372
|
|
|
371
373
|
web-streams-polyfill/dist/ponyfill.es2018.js:
|