@n24q02m/workspace 0.7.0-beta.1 → 0.7.1-beta.1

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/bin/cli.mjs CHANGED
@@ -1,70 +1,70 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module';const require = createRequire(import.meta.url);
3
- var Af=Object.create;var io=Object.defineProperty;var Pf=Object.getOwnPropertyDescriptor;var If=Object.getOwnPropertyNames;var Of=Object.getPrototypeOf,kf=Object.prototype.hasOwnProperty;var Z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var G=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var X=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ra=(n,e)=>{for(var t in e)io(n,t,{get:e[t],enumerable:!0})},$f=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of If(e))!kf.call(n,o)&&o!==t&&io(n,o,{get:()=>e[o],enumerable:!(s=Pf(e,o))||s.enumerable});return n};var Ht=(n,e,t)=>(t=n!=null?Af(Of(n)):{},$f(e||!n||!n.__esModule?io(t,"default",{value:n,enumerable:!0}):t,n));var Ro=X((YS,Mc)=>{"use strict";var jn=Object.prototype.hasOwnProperty,Nc=Object.prototype.toString,Ic=Object.defineProperty,Oc=Object.getOwnPropertyDescriptor,kc=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Nc.call(e)==="[object Array]"},$c=function(e){if(!e||Nc.call(e)!=="[object Object]")return!1;var t=jn.call(e,"constructor"),s=e.constructor&&e.constructor.prototype&&jn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!s)return!1;var o;for(o in e);return typeof o>"u"||jn.call(e,o)},Dc=function(e,t){Ic&&t.name==="__proto__"?Ic(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},Lc=function(e,t){if(t==="__proto__")if(jn.call(e,t)){if(Oc)return Oc(e,t).value}else return;return e[t]};Mc.exports=function n(){var e,t,s,o,a,l,d=arguments[0],p=1,u=arguments.length,f=!1;for(typeof d=="boolean"&&(f=d,d=arguments[1]||{},p=2),(d==null||typeof d!="object"&&typeof d!="function")&&(d={});p<u;++p)if(e=arguments[p],e!=null)for(t in e)s=Lc(d,t),o=Lc(e,t),d!==o&&(f&&o&&($c(o)||(a=kc(o)))?(a?(a=!1,l=s&&kc(s)?s:[]):l=s&&$c(s)?s:{},Dc(d,{name:t,newValue:n(f,l,o)})):typeof o<"u"&&Dc(d,{name:t,newValue:o}));return d}});var Fc=X((ZS,Gp)=>{Gp.exports={name:"gaxios",version:"8.0.0",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","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=22"},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.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Uc=X((XS,Bc)=>{var Jp=Fc();Bc.exports={pkg:Jp}});var Hc=X((tw,zc)=>{var Zt=1e3,Xt=Zt*60,Qt=Xt*60,At=Qt*24,Xp=At*7,Qp=At*365.25;zc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Kp(n);if(t==="number"&&isFinite(n))return e.long?tm(n):em(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Kp(n){if(n=String(n),!(n.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(n);if(e){var t=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*Qp;case"weeks":case"week":case"w":return t*Xp;case"days":case"day":case"d":return t*At;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Qt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Xt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Zt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function em(n){var e=Math.abs(n);return e>=At?Math.round(n/At)+"d":e>=Qt?Math.round(n/Qt)+"h":e>=Xt?Math.round(n/Xt)+"m":e>=Zt?Math.round(n/Zt)+"s":n+"ms"}function tm(n){var e=Math.abs(n);return e>=At?Wn(n,e,At,"day"):e>=Qt?Wn(n,e,Qt,"hour"):e>=Xt?Wn(n,e,Xt,"minute"):e>=Zt?Wn(n,e,Zt,"second"):n+" ms"}function Wn(n,e,t,s){var o=e>=t*1.5;return Math.round(n/t)+" "+s+(o?"s":"")}});var Ao=X((rw,Gc)=>{function rm(n){t.debug=t,t.default=t,t.coerce=p,t.disable=l,t.enable=o,t.enabled=d,t.humanize=Hc(),t.destroy=u,Object.keys(n).forEach(f=>{t[f]=n[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let y=0;for(let g=0;g<f.length;g++)y=(y<<5)-y+f.charCodeAt(g),y|=0;return t.colors[Math.abs(y)%t.colors.length]}t.selectColor=e;function t(f){let y,g=null,_,S;function E(...R){if(!E.enabled)return;let v=E,A=Number(new Date),C=A-(y||A);v.diff=C,v.prev=y,v.curr=A,y=A,R[0]=t.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let x=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,($,H)=>{if($==="%%")return"%";x++;let Ve=t.formatters[H];if(typeof Ve=="function"){let ar=R[x];$=Ve.call(v,ar),R.splice(x,1),x--}return $}),t.formatArgs.call(v,R),(v.log||t.log).apply(v,R)}return E.namespace=f,E.useColors=t.useColors(),E.color=t.selectColor(f),E.extend=s,E.destroy=t.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(_!==t.namespaces&&(_=t.namespaces,S=t.enabled(f)),S),set:R=>{g=R}}),typeof t.init=="function"&&t.init(E),E}function s(f,y){let g=t(this.namespace+(typeof y>"u"?":":y)+f);return g.log=this.log,g}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let y=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of y)g[0]==="-"?t.skips.push(g.slice(1)):t.names.push(g)}function a(f,y){let g=0,_=0,S=-1,E=0;for(;g<f.length;)if(_<y.length&&(y[_]===f[g]||y[_]==="*"))y[_]==="*"?(S=_,E=g,_++):(g++,_++);else if(S!==-1)_=S+1,E++,g=E;else return!1;for(;_<y.length&&y[_]==="*";)_++;return _===y.length}function l(){let f=[...t.names,...t.skips.map(y=>"-"+y)].join(",");return t.enable(""),f}function d(f){for(let y of t.skips)if(a(f,y))return!1;for(let y of t.names)if(a(f,y))return!0;return!1}function p(f){return f instanceof Error?f.stack||f.message:f}function u(){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 t.enable(t.load()),t}Gc.exports=rm});var Jc=X((ne,zn)=>{ne.formatArgs=sm;ne.save=om;ne.load=im;ne.useColors=nm;ne.storage=am();ne.destroy=(()=>{let n=!1;return()=>{n||(n=!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`."))}})();ne.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 nm(){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 n;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&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function sm(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+zn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,s=0;n[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(s=t))}),n.splice(s,0,e)}ne.log=console.debug||console.log||(()=>{});function om(n){try{n?ne.storage.setItem("debug",n):ne.storage.removeItem("debug")}catch{}}function im(){let n;try{n=ne.storage.getItem("debug")||ne.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function am(){try{return localStorage}catch{}}zn.exports=Ao()(ne);var{formatters:cm}=zn.exports;cm.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Yc=X((nw,Vc)=>{"use strict";Vc.exports=(n,e=process.argv)=>{let t=n.startsWith("-")?"":n.length===1?"-":"--",s=e.indexOf(t+n),o=e.indexOf("--");return s!==-1&&(o===-1||s<o)}});var Qc=X((sw,Xc)=>{"use strict";var lm=Z("os"),Zc=Z("tty"),ge=Yc(),{env:J}=process,dt;ge("no-color")||ge("no-colors")||ge("color=false")||ge("color=never")?dt=0:(ge("color")||ge("colors")||ge("color=true")||ge("color=always"))&&(dt=1);"FORCE_COLOR"in J&&(J.FORCE_COLOR==="true"?dt=1:J.FORCE_COLOR==="false"?dt=0:dt=J.FORCE_COLOR.length===0?1:Math.min(parseInt(J.FORCE_COLOR,10),3));function Po(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function Io(n,e){if(dt===0)return 0;if(ge("color=16m")||ge("color=full")||ge("color=truecolor"))return 3;if(ge("color=256"))return 2;if(n&&!e&&dt===void 0)return 0;let t=dt||0;if(J.TERM==="dumb")return t;if(process.platform==="win32"){let s=lm.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in J)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in J)||J.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in J)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(J.TEAMCITY_VERSION)?1:0;if(J.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in J){let s=parseInt((J.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(J.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(J.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(J.TERM)||"COLORTERM"in J?1:t}function um(n){let e=Io(n,n&&n.isTTY);return Po(e)}Xc.exports={supportsColor:um,stdout:Po(Io(!0,Zc.isatty(1))),stderr:Po(Io(!0,Zc.isatty(2)))}});var el=X((V,Gn)=>{var dm=Z("tty"),Hn=Z("util");V.init=bm;V.log=hm;V.formatArgs=pm;V.save=gm;V.load=ym;V.useColors=fm;V.destroy=Hn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");V.colors=[6,2,3,4,5,1];try{let n=Qc();n&&(n.stderr||n).level>=2&&(V.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{}V.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,a)=>a.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),n[t]=s,n},{});function fm(){return"colors"in V.inspectOpts?!!V.inspectOpts.colors:dm.isatty(process.stderr.fd)}function pm(n){let{namespace:e,useColors:t}=this;if(t){let s=this.color,o="\x1B[3"+(s<8?s:"8;5;"+s),a=` ${o};1m${e} \x1B[0m`;n[0]=a+n[0].split(`
3
+ var Pf=Object.create;var ao=Object.defineProperty;var If=Object.getOwnPropertyDescriptor;var Of=Object.getOwnPropertyNames;var kf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty;var Z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var G=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var X=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ea=(n,e)=>{for(var t in e)ao(n,t,{get:e[t],enumerable:!0})},Df=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Of(e))!$f.call(n,o)&&o!==t&&ao(n,o,{get:()=>e[o],enumerable:!(s=If(e,o))||s.enumerable});return n};var Ht=(n,e,t)=>(t=n!=null?Pf(kf(n)):{},Df(e||!n||!n.__esModule?ao(t,"default",{value:n,enumerable:!0}):t,n));var Eo=X((XS,Fc)=>{"use strict";var Wn=Object.prototype.hasOwnProperty,Mc=Object.prototype.toString,Oc=Object.defineProperty,kc=Object.getOwnPropertyDescriptor,$c=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Mc.call(e)==="[object Array]"},Dc=function(e){if(!e||Mc.call(e)!=="[object Object]")return!1;var t=Wn.call(e,"constructor"),s=e.constructor&&e.constructor.prototype&&Wn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!s)return!1;var o;for(o in e);return typeof o>"u"||Wn.call(e,o)},Lc=function(e,t){Oc&&t.name==="__proto__"?Oc(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},Nc=function(e,t){if(t==="__proto__")if(Wn.call(e,t)){if(kc)return kc(e,t).value}else return;return e[t]};Fc.exports=function n(){var e,t,s,o,a,l,d=arguments[0],p=1,u=arguments.length,f=!1;for(typeof d=="boolean"&&(f=d,d=arguments[1]||{},p=2),(d==null||typeof d!="object"&&typeof d!="function")&&(d={});p<u;++p)if(e=arguments[p],e!=null)for(t in e)s=Nc(d,t),o=Nc(e,t),d!==o&&(f&&o&&(Dc(o)||(a=$c(o)))?(a?(a=!1,l=s&&$c(s)?s:[]):l=s&&Dc(s)?s:{},Lc(d,{name:t,newValue:n(f,l,o)})):typeof o<"u"&&Lc(d,{name:t,newValue:o}));return d}});var Bc=X((QS,Jp)=>{Jp.exports={name:"gaxios",version:"8.0.0",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","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=22"},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.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var qc=X((KS,Uc)=>{var Vp=Bc();Uc.exports={pkg:Vp}});var Gc=X((nw,Hc)=>{var Xt=1e3,Qt=Xt*60,Kt=Qt*60,At=Kt*24,Qp=At*7,Kp=At*365.25;Hc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return em(n);if(t==="number"&&isFinite(n))return e.long?rm(n):tm(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function em(n){if(n=String(n),!(n.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(n);if(e){var t=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*Kp;case"weeks":case"week":case"w":return t*Qp;case"days":case"day":case"d":return t*At;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Kt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Qt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Xt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function tm(n){var e=Math.abs(n);return e>=At?Math.round(n/At)+"d":e>=Kt?Math.round(n/Kt)+"h":e>=Qt?Math.round(n/Qt)+"m":e>=Xt?Math.round(n/Xt)+"s":n+"ms"}function rm(n){var e=Math.abs(n);return e>=At?zn(n,e,At,"day"):e>=Kt?zn(n,e,Kt,"hour"):e>=Qt?zn(n,e,Qt,"minute"):e>=Xt?zn(n,e,Xt,"second"):n+" ms"}function zn(n,e,t,s){var o=e>=t*1.5;return Math.round(n/t)+" "+s+(o?"s":"")}});var Po=X((sw,Jc)=>{function nm(n){t.debug=t,t.default=t,t.coerce=p,t.disable=l,t.enable=o,t.enabled=d,t.humanize=Gc(),t.destroy=u,Object.keys(n).forEach(f=>{t[f]=n[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let y=0;for(let g=0;g<f.length;g++)y=(y<<5)-y+f.charCodeAt(g),y|=0;return t.colors[Math.abs(y)%t.colors.length]}t.selectColor=e;function t(f){let y,g=null,_,S;function E(...R){if(!E.enabled)return;let x=E,A=Number(new Date),C=A-(y||A);x.diff=C,x.prev=y,x.curr=A,y=A,R[0]=t.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let v=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,($,H)=>{if($==="%%")return"%";v++;let Ve=t.formatters[H];if(typeof Ve=="function"){let cr=R[v];$=Ve.call(x,cr),R.splice(v,1),v--}return $}),t.formatArgs.call(x,R),(x.log||t.log).apply(x,R)}return E.namespace=f,E.useColors=t.useColors(),E.color=t.selectColor(f),E.extend=s,E.destroy=t.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(_!==t.namespaces&&(_=t.namespaces,S=t.enabled(f)),S),set:R=>{g=R}}),typeof t.init=="function"&&t.init(E),E}function s(f,y){let g=t(this.namespace+(typeof y>"u"?":":y)+f);return g.log=this.log,g}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let y=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of y)g[0]==="-"?t.skips.push(g.slice(1)):t.names.push(g)}function a(f,y){let g=0,_=0,S=-1,E=0;for(;g<f.length;)if(_<y.length&&(y[_]===f[g]||y[_]==="*"))y[_]==="*"?(S=_,E=g,_++):(g++,_++);else if(S!==-1)_=S+1,E++,g=E;else return!1;for(;_<y.length&&y[_]==="*";)_++;return _===y.length}function l(){let f=[...t.names,...t.skips.map(y=>"-"+y)].join(",");return t.enable(""),f}function d(f){for(let y of t.skips)if(a(f,y))return!1;for(let y of t.names)if(a(f,y))return!0;return!1}function p(f){return f instanceof Error?f.stack||f.message:f}function u(){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 t.enable(t.load()),t}Jc.exports=nm});var Vc=X((ne,Hn)=>{ne.formatArgs=om;ne.save=im;ne.load=am;ne.useColors=sm;ne.storage=cm();ne.destroy=(()=>{let n=!1;return()=>{n||(n=!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`."))}})();ne.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 sm(){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 n;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&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function om(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Hn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,s=0;n[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(s=t))}),n.splice(s,0,e)}ne.log=console.debug||console.log||(()=>{});function im(n){try{n?ne.storage.setItem("debug",n):ne.storage.removeItem("debug")}catch{}}function am(){let n;try{n=ne.storage.getItem("debug")||ne.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function cm(){try{return localStorage}catch{}}Hn.exports=Po()(ne);var{formatters:lm}=Hn.exports;lm.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Zc=X((ow,Yc)=>{"use strict";Yc.exports=(n,e=process.argv)=>{let t=n.startsWith("-")?"":n.length===1?"-":"--",s=e.indexOf(t+n),o=e.indexOf("--");return s!==-1&&(o===-1||s<o)}});var Kc=X((iw,Qc)=>{"use strict";var um=Z("os"),Xc=Z("tty"),ge=Zc(),{env:J}=process,dt;ge("no-color")||ge("no-colors")||ge("color=false")||ge("color=never")?dt=0:(ge("color")||ge("colors")||ge("color=true")||ge("color=always"))&&(dt=1);"FORCE_COLOR"in J&&(J.FORCE_COLOR==="true"?dt=1:J.FORCE_COLOR==="false"?dt=0:dt=J.FORCE_COLOR.length===0?1:Math.min(parseInt(J.FORCE_COLOR,10),3));function Io(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function Oo(n,e){if(dt===0)return 0;if(ge("color=16m")||ge("color=full")||ge("color=truecolor"))return 3;if(ge("color=256"))return 2;if(n&&!e&&dt===void 0)return 0;let t=dt||0;if(J.TERM==="dumb")return t;if(process.platform==="win32"){let s=um.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in J)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in J)||J.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in J)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(J.TEAMCITY_VERSION)?1:0;if(J.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in J){let s=parseInt((J.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(J.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(J.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(J.TERM)||"COLORTERM"in J?1:t}function dm(n){let e=Oo(n,n&&n.isTTY);return Io(e)}Qc.exports={supportsColor:dm,stdout:Io(Oo(!0,Xc.isatty(1))),stderr:Io(Oo(!0,Xc.isatty(2)))}});var tl=X((V,Jn)=>{var fm=Z("tty"),Gn=Z("util");V.init=Sm;V.log=gm;V.formatArgs=mm;V.save=ym;V.load=bm;V.useColors=pm;V.destroy=Gn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");V.colors=[6,2,3,4,5,1];try{let n=Kc();n&&(n.stderr||n).level>=2&&(V.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{}V.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,a)=>a.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),n[t]=s,n},{});function pm(){return"colors"in V.inspectOpts?!!V.inspectOpts.colors:fm.isatty(process.stderr.fd)}function mm(n){let{namespace:e,useColors:t}=this;if(t){let s=this.color,o="\x1B[3"+(s<8?s:"8;5;"+s),a=` ${o};1m${e} \x1B[0m`;n[0]=a+n[0].split(`
4
4
  `).join(`
5
- `+a),n.push(o+"m+"+Gn.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=mm()+e+" "+n[0]}function mm(){return V.inspectOpts.hideDate?"":new Date().toISOString()+" "}function hm(...n){return process.stderr.write(Hn.formatWithOptions(V.inspectOpts,...n)+`
6
- `)}function gm(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function ym(){return process.env.DEBUG}function bm(n){n.inspectOpts={};let e=Object.keys(V.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=V.inspectOpts[e[t]]}Gn.exports=Ao()(V);var{formatters:Kc}=Gn.exports;Kc.o=function(n){return this.inspectOpts.colors=this.useColors,Hn.inspect(n,this.inspectOpts).split(`
7
- `).map(e=>e.trim()).join(" ")};Kc.O=function(n){return this.inspectOpts.colors=this.useColors,Hn.inspect(n,this.inspectOpts)}});var ko=X((ow,Oo)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Oo.exports=Jc():Oo.exports=el()});var nl=X(se=>{"use strict";var Sm=se&&se.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),wm=se&&se.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),tl=se&&se.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&Sm(e,n,t);return wm(e,n),e};Object.defineProperty(se,"__esModule",{value:!0});se.req=se.json=se.toBuffer=void 0;var _m=tl(Z("http")),Tm=tl(Z("https"));async function rl(n){let e=0,t=[];for await(let s of n)e+=s.length,t.push(s);return Buffer.concat(t,e)}se.toBuffer=rl;async function Rm(n){let t=(await rl(n)).toString("utf8");try{return JSON.parse(t)}catch(s){let o=s;throw o.message+=` (input: ${t})`,o}}se.json=Rm;function Em(n,e={}){let s=((typeof n=="string"?n:n.href).startsWith("https:")?Tm:_m).request(n,e),o=new Promise((a,l)=>{s.once("response",a).once("error",l).end()});return s.then=o.then.bind(o),s}se.req=Em});var al=X(ue=>{"use strict";var ol=ue&&ue.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),vm=ue&&ue.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),il=ue&&ue.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&ol(e,n,t);return vm(e,n),e},xm=ue&&ue.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&ol(e,n,t)};Object.defineProperty(ue,"__esModule",{value:!0});ue.Agent=void 0;var Cm=il(Z("net")),sl=il(Z("http")),Am=Z("https");xm(nl(),ue);var ke=Symbol("AgentBaseInternalState"),$o=class extends sl.Agent{constructor(e){super(e),this[ke]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
8
- `).some(s=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new Cm.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let s=this.sockets[e],o=s.indexOf(t);o!==-1&&(s.splice(o,1),this.totalSocketCount--,s.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Am.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,s){let o={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(o),l=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,o)).then(d=>{if(this.decrementSockets(a,l),d instanceof sl.Agent)try{return d.addRequest(e,o)}catch(p){return s(p)}this[ke].currentSocket=d,super.createSocket(e,t,s)},d=>{this.decrementSockets(a,l),s(d)})}createConnection(){let e=this[ke].currentSocket;if(this[ke].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[ke].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[ke]&&(this[ke].defaultPort=e)}get protocol(){return this[ke].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[ke]&&(this[ke].protocol=e)}};ue.Agent=$o});var cl=X(Kt=>{"use strict";var Pm=Kt&&Kt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.parseProxyResponse=void 0;var Im=Pm(ko()),Jn=(0,Im.default)("https-proxy-agent:parse-proxy-response");function Om(n){return new Promise((e,t)=>{let s=0,o=[];function a(){let f=n.read();f?u(f):n.once("readable",a)}function l(){n.removeListener("end",d),n.removeListener("error",p),n.removeListener("readable",a)}function d(){l(),Jn("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function p(f){l(),Jn("onerror %o",f),t(f)}function u(f){o.push(f),s+=f.length;let y=Buffer.concat(o,s),g=y.indexOf(`\r
5
+ `+a),n.push(o+"m+"+Jn.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=hm()+e+" "+n[0]}function hm(){return V.inspectOpts.hideDate?"":new Date().toISOString()+" "}function gm(...n){return process.stderr.write(Gn.formatWithOptions(V.inspectOpts,...n)+`
6
+ `)}function ym(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function bm(){return process.env.DEBUG}function Sm(n){n.inspectOpts={};let e=Object.keys(V.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=V.inspectOpts[e[t]]}Jn.exports=Po()(V);var{formatters:el}=Jn.exports;el.o=function(n){return this.inspectOpts.colors=this.useColors,Gn.inspect(n,this.inspectOpts).split(`
7
+ `).map(e=>e.trim()).join(" ")};el.O=function(n){return this.inspectOpts.colors=this.useColors,Gn.inspect(n,this.inspectOpts)}});var $o=X((aw,ko)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ko.exports=Vc():ko.exports=tl()});var sl=X(se=>{"use strict";var wm=se&&se.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),_m=se&&se.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),rl=se&&se.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&wm(e,n,t);return _m(e,n),e};Object.defineProperty(se,"__esModule",{value:!0});se.req=se.json=se.toBuffer=void 0;var Tm=rl(Z("http")),Rm=rl(Z("https"));async function nl(n){let e=0,t=[];for await(let s of n)e+=s.length,t.push(s);return Buffer.concat(t,e)}se.toBuffer=nl;async function Em(n){let t=(await nl(n)).toString("utf8");try{return JSON.parse(t)}catch(s){let o=s;throw o.message+=` (input: ${t})`,o}}se.json=Em;function xm(n,e={}){let s=((typeof n=="string"?n:n.href).startsWith("https:")?Rm:Tm).request(n,e),o=new Promise((a,l)=>{s.once("response",a).once("error",l).end()});return s.then=o.then.bind(o),s}se.req=xm});var cl=X(ue=>{"use strict";var il=ue&&ue.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),vm=ue&&ue.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),al=ue&&ue.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&il(e,n,t);return vm(e,n),e},Cm=ue&&ue.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&il(e,n,t)};Object.defineProperty(ue,"__esModule",{value:!0});ue.Agent=void 0;var Am=al(Z("net")),ol=al(Z("http")),Pm=Z("https");Cm(sl(),ue);var ke=Symbol("AgentBaseInternalState"),Do=class extends ol.Agent{constructor(e){super(e),this[ke]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
8
+ `).some(s=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new Am.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let s=this.sockets[e],o=s.indexOf(t);o!==-1&&(s.splice(o,1),this.totalSocketCount--,s.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Pm.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,s){let o={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(o),l=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,o)).then(d=>{if(this.decrementSockets(a,l),d instanceof ol.Agent)try{return d.addRequest(e,o)}catch(p){return s(p)}this[ke].currentSocket=d,super.createSocket(e,t,s)},d=>{this.decrementSockets(a,l),s(d)})}createConnection(){let e=this[ke].currentSocket;if(this[ke].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[ke].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[ke]&&(this[ke].defaultPort=e)}get protocol(){return this[ke].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[ke]&&(this[ke].protocol=e)}};ue.Agent=Do});var ll=X(er=>{"use strict";var Im=er&&er.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(er,"__esModule",{value:!0});er.parseProxyResponse=void 0;var Om=Im($o()),Vn=(0,Om.default)("https-proxy-agent:parse-proxy-response");function km(n){return new Promise((e,t)=>{let s=0,o=[];function a(){let f=n.read();f?u(f):n.once("readable",a)}function l(){n.removeListener("end",d),n.removeListener("error",p),n.removeListener("readable",a)}function d(){l(),Vn("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function p(f){l(),Vn("onerror %o",f),t(f)}function u(f){o.push(f),s+=f.length;let y=Buffer.concat(o,s),g=y.indexOf(`\r
9
9
  \r
10
- `);if(g===-1){Jn("have not received end of HTTP headers yet..."),a();return}let _=y.slice(0,g).toString("ascii").split(`\r
11
- `),S=_.shift();if(!S)return n.destroy(),t(new Error("No header received from proxy CONNECT response"));let E=S.split(" "),R=+E[1],v=E.slice(2).join(" "),A={};for(let C of _){if(!C)continue;let x=C.indexOf(":");if(x===-1)return n.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let k=C.slice(0,x).toLowerCase(),$=C.slice(x+1).trimStart(),H=A[k];typeof H=="string"?A[k]=[H,$]:Array.isArray(H)?H.push($):A[k]=$}Jn("got proxy server response: %o %o",S,A),l(),e({connect:{statusCode:R,statusText:v,headers:A},buffered:y})}n.on("error",p),n.on("end",d),a()})}Kt.parseProxyResponse=Om});var ml=X(ye=>{"use strict";var km=ye&&ye.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),$m=ye&&ye.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),fl=ye&&ye.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&km(e,n,t);return $m(e,n),e},pl=ye&&ye.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(ye,"__esModule",{value:!0});ye.HttpsProxyAgent=void 0;var Vn=fl(Z("net")),ll=fl(Z("tls")),Dm=pl(Z("assert")),Lm=pl(ko()),Nm=al(),Mm=Z("url"),Fm=cl(),Er=(0,Lm.default)("https-proxy-agent"),ul=n=>n.servername===void 0&&n.host&&!Vn.isIP(n.host)?{...n,servername:n.host}:n,Yn=class extends Nm.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new Mm.URL(e):e,this.proxyHeaders=t?.headers??{},Er("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let s=(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"],...t?dl(t,"headers"):null,host:s,port:o}}async connect(e,t){let{proxy:s}=this;if(!t.host)throw new TypeError('No "host" provided');let o;s.protocol==="https:"?(Er("Creating `tls.Socket`: %o",this.connectOpts),o=ll.connect(ul(this.connectOpts))):(Er("Creating `net.Socket`: %o",this.connectOpts),o=Vn.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},l=Vn.isIPv6(t.host)?`[${t.host}]`:t.host,d=`CONNECT ${l}:${t.port} HTTP/1.1\r
10
+ `);if(g===-1){Vn("have not received end of HTTP headers yet..."),a();return}let _=y.slice(0,g).toString("ascii").split(`\r
11
+ `),S=_.shift();if(!S)return n.destroy(),t(new Error("No header received from proxy CONNECT response"));let E=S.split(" "),R=+E[1],x=E.slice(2).join(" "),A={};for(let C of _){if(!C)continue;let v=C.indexOf(":");if(v===-1)return n.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let k=C.slice(0,v).toLowerCase(),$=C.slice(v+1).trimStart(),H=A[k];typeof H=="string"?A[k]=[H,$]:Array.isArray(H)?H.push($):A[k]=$}Vn("got proxy server response: %o %o",S,A),l(),e({connect:{statusCode:R,statusText:x,headers:A},buffered:y})}n.on("error",p),n.on("end",d),a()})}er.parseProxyResponse=km});var hl=X(ye=>{"use strict";var $m=ye&&ye.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),Dm=ye&&ye.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),pl=ye&&ye.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&$m(e,n,t);return Dm(e,n),e},ml=ye&&ye.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(ye,"__esModule",{value:!0});ye.HttpsProxyAgent=void 0;var Yn=pl(Z("net")),ul=pl(Z("tls")),Lm=ml(Z("assert")),Nm=ml($o()),Mm=cl(),Fm=Z("url"),Bm=ll(),vr=(0,Nm.default)("https-proxy-agent"),dl=n=>n.servername===void 0&&n.host&&!Yn.isIP(n.host)?{...n,servername:n.host}:n,Zn=class extends Mm.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new Fm.URL(e):e,this.proxyHeaders=t?.headers??{},vr("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let s=(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"],...t?fl(t,"headers"):null,host:s,port:o}}async connect(e,t){let{proxy:s}=this;if(!t.host)throw new TypeError('No "host" provided');let o;s.protocol==="https:"?(vr("Creating `tls.Socket`: %o",this.connectOpts),o=ul.connect(dl(this.connectOpts))):(vr("Creating `net.Socket`: %o",this.connectOpts),o=Yn.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},l=Yn.isIPv6(t.host)?`[${t.host}]`:t.host,d=`CONNECT ${l}:${t.port} HTTP/1.1\r
12
12
  `;if(s.username||s.password){let g=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(g).toString("base64")}`}a.Host=`${l}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let g of Object.keys(a))d+=`${g}: ${a[g]}\r
13
- `;let p=(0,Fm.parseProxyResponse)(o);o.write(`${d}\r
14
- `);let{connect:u,buffered:f}=await p;if(e.emit("proxyConnect",u),this.emit("proxyConnect",u,e),u.statusCode===200)return e.once("socket",Bm),t.secureEndpoint?(Er("Upgrading socket connection to TLS"),ll.connect({...dl(ul(t),"host","path","port"),socket:o})):o;o.destroy();let y=new Vn.Socket({writable:!1});return y.readable=!0,e.once("socket",g=>{Er("Replaying proxy buffer for failed request"),(0,Dm.default)(g.listenerCount("data")>0),g.push(f),g.push(null)}),y}};Yn.protocols=["http","https"];ye.HttpsProxyAgent=Yn;function Bm(n){n.resume()}function dl(n,...e){let t={},s;for(s in n)e.includes(s)||(t[s]=n[s]);return t}});function Um(n){if(!/^data:/i.test(n))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');n=n.replace(/\r?\n/g,"");let e=n.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=n.substring(5,e).split(";"),s="",o=!1,a=t[0]||"text/plain",l=a;for(let f=1;f<t.length;f++)t[f]==="base64"?o=!0:t[f]&&(l+=`;${t[f]}`,t[f].indexOf("charset=")===0&&(s=t[f].substring(8)));!t[0]&&!s.length&&(l+=";charset=US-ASCII",s="US-ASCII");let d=o?"base64":"ascii",p=unescape(n.substring(e+1)),u=Buffer.from(p,d);return u.type=a,u.typeFull=l,u.charset=s,u}var hl,gl=G(()=>{hl=Um});var bl=X((Zn,yl)=>{(function(n,e){typeof Zn=="object"&&typeof yl<"u"?e(Zn):typeof define=="function"&&define.amd?define(["exports"],e):(n=typeof globalThis<"u"?globalThis:n||self,e(n.WebStreamsPolyfill={}))})(Zn,(function(n){"use strict";function e(){}function t(r){return typeof r=="object"&&r!==null||typeof r=="function"}let s=e;function o(r,i){try{Object.defineProperty(r,"name",{value:i,configurable:!0})}catch{}}let a=Promise,l=Promise.prototype.then,d=Promise.reject.bind(a);function p(r){return new a(r)}function u(r){return p(i=>i(r))}function f(r){return d(r)}function y(r,i,c){return l.call(r,i,c)}function g(r,i,c){y(y(r,i,c),void 0,s)}function _(r,i){g(r,i)}function S(r,i){g(r,void 0,i)}function E(r,i,c){return y(r,i,c)}function R(r){y(r,void 0,s)}let v=r=>{if(typeof queueMicrotask=="function")v=queueMicrotask;else{let i=u(void 0);v=c=>y(i,c)}return v(r)};function A(r,i,c){if(typeof r!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(r,i,c)}function C(r,i,c){try{return u(A(r,i,c))}catch(h){return f(h)}}let x=16384;class k{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(i){let c=this._back,h=c;c._elements.length===x-1&&(h={_elements:[],_next:void 0}),c._elements.push(i),h!==c&&(this._back=h,c._next=h),++this._size}shift(){let i=this._front,c=i,h=this._cursor,b=h+1,w=i._elements,T=w[h];return b===x&&(c=i._next,b=0),--this._size,this._cursor=b,i!==c&&(this._front=c),w[h]=void 0,T}forEach(i){let c=this._cursor,h=this._front,b=h._elements;for(;(c!==b.length||h._next!==void 0)&&!(c===b.length&&(h=h._next,b=h._elements,c=0,b.length===0));)i(b[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let $=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),Ve=Symbol("[[CancelSteps]]"),ar=Symbol("[[PullSteps]]"),_s=Symbol("[[ReleaseSteps]]");function ai(r,i){r._ownerReadableStream=i,i._reader=r,i._state==="readable"?Rs(r):i._state==="closed"?Mu(r):ci(r,i._storedError)}function Ts(r,i){let c=r._ownerReadableStream;return _e(c,i)}function Le(r){let i=r._ownerReadableStream;i._state==="readable"?Es(r,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Fu(r,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[_s](),i._reader=void 0,r._ownerReadableStream=void 0}function Dr(r){return new TypeError("Cannot "+r+" a stream using a released reader")}function Rs(r){r._closedPromise=p((i,c)=>{r._closedPromise_resolve=i,r._closedPromise_reject=c})}function ci(r,i){Rs(r),Es(r,i)}function Mu(r){Rs(r),li(r)}function Es(r,i){r._closedPromise_reject!==void 0&&(R(r._closedPromise),r._closedPromise_reject(i),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0)}function Fu(r,i){ci(r,i)}function li(r){r._closedPromise_resolve!==void 0&&(r._closedPromise_resolve(void 0),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0)}let ui=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Bu=Math.trunc||function(r){return r<0?Math.ceil(r):Math.floor(r)};function Uu(r){return typeof r=="object"||typeof r=="function"}function Ce(r,i){if(r!==void 0&&!Uu(r))throw new TypeError(`${i} is not an object.`)}function fe(r,i){if(typeof r!="function")throw new TypeError(`${i} is not a function.`)}function qu(r){return typeof r=="object"&&r!==null||typeof r=="function"}function di(r,i){if(!qu(r))throw new TypeError(`${i} is not an object.`)}function Ne(r,i,c){if(r===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function vs(r,i,c){if(r===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function xs(r){return Number(r)}function fi(r){return r===0?0:r}function ju(r){return fi(Bu(r))}function Cs(r,i){let h=Number.MAX_SAFE_INTEGER,b=Number(r);if(b=fi(b),!ui(b))throw new TypeError(`${i} is not a finite number`);if(b=ju(b),b<0||b>h)throw new TypeError(`${i} is outside the accepted range of 0 to ${h}, inclusive`);return!ui(b)||b===0?0:b}function As(r,i){if(!tt(r))throw new TypeError(`${i} is not a ReadableStream.`)}function $t(r){return new Ye(r)}function pi(r,i){r._reader._readRequests.push(i)}function Ps(r,i,c){let b=r._reader._readRequests.shift();c?b._closeSteps():b._chunkSteps(i)}function Lr(r){return r._reader._readRequests.length}function mi(r){let i=r._reader;return!(i===void 0||!Ze(i))}class Ye{constructor(i){if(Ne(i,1,"ReadableStreamDefaultReader"),As(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ai(this,i),this._readRequests=new k}get closed(){return Ze(this)?this._closedPromise:f(Nr("closed"))}cancel(i=void 0){return Ze(this)?this._ownerReadableStream===void 0?f(Dr("cancel")):Ts(this,i):f(Nr("cancel"))}read(){if(!Ze(this))return f(Nr("read"));if(this._ownerReadableStream===void 0)return f(Dr("read from"));let i,c,h=p((w,T)=>{i=w,c=T});return cr(this,{_chunkSteps:w=>i({value:w,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:w=>c(w)}),h}releaseLock(){if(!Ze(this))throw Nr("releaseLock");this._ownerReadableStream!==void 0&&Wu(this)}}Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ye.prototype.cancel,"cancel"),o(Ye.prototype.read,"read"),o(Ye.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ze(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readRequests")?!1:r instanceof Ye}function cr(r,i){let c=r._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[ar](i)}function Wu(r){Le(r);let i=new TypeError("Reader was released");hi(r,i)}function hi(r,i){let c=r._readRequests;r._readRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Nr(r){return new TypeError(`ReadableStreamDefaultReader.prototype.${r} can only be used on a ReadableStreamDefaultReader`)}let zu=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class gi{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?E(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?E(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,h,b=p((T,P)=>{c=T,h=P});return cr(i,{_chunkSteps:T=>{this._ongoingPromise=void 0,v(()=>c({value:T,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),c({value:void 0,done:!0})},_errorSteps:T=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),h(T)}}),b}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let h=Ts(c,i);return Le(c),E(h,()=>({value:i,done:!0}))}return Le(c),u({value:i,done:!0})}}let yi={next(){return bi(this)?this._asyncIteratorImpl.next():f(Si("next"))},return(r){return bi(this)?this._asyncIteratorImpl.return(r):f(Si("return"))}};Object.setPrototypeOf(yi,zu);function Hu(r,i){let c=$t(r),h=new gi(c,i),b=Object.create(yi);return b._asyncIteratorImpl=h,b}function bi(r){if(!t(r)||!Object.prototype.hasOwnProperty.call(r,"_asyncIteratorImpl"))return!1;try{return r._asyncIteratorImpl instanceof gi}catch{return!1}}function Si(r){return new TypeError(`ReadableStreamAsyncIterator.${r} can only be used on a ReadableSteamAsyncIterator`)}let wi=Number.isNaN||function(r){return r!==r};var Is,Os,ks;function lr(r){return r.slice()}function _i(r,i,c,h,b){new Uint8Array(r).set(new Uint8Array(c,h,b),i)}let Me=r=>(typeof r.transfer=="function"?Me=i=>i.transfer():typeof structuredClone=="function"?Me=i=>structuredClone(i,{transfer:[i]}):Me=i=>i,Me(r)),Xe=r=>(typeof r.detached=="boolean"?Xe=i=>i.detached:Xe=i=>i.byteLength===0,Xe(r));function Ti(r,i,c){if(r.slice)return r.slice(i,c);let h=c-i,b=new ArrayBuffer(h);return _i(b,0,r,i,h),b}function Mr(r,i){let c=r[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function Gu(r){let i={[Symbol.iterator]:()=>r.iterator},c=(async function*(){return yield*i})(),h=c.next;return{iterator:c,nextMethod:h,done:!1}}let $s=(ks=(Is=Symbol.asyncIterator)!==null&&Is!==void 0?Is:(Os=Symbol.for)===null||Os===void 0?void 0:Os.call(Symbol,"Symbol.asyncIterator"))!==null&&ks!==void 0?ks:"@@asyncIterator";function Ri(r,i="sync",c){if(c===void 0)if(i==="async"){if(c=Mr(r,$s),c===void 0){let w=Mr(r,Symbol.iterator),T=Ri(r,"sync",w);return Gu(T)}}else c=Mr(r,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let h=A(c,r,[]);if(!t(h))throw new TypeError("The iterator method must return an object");let b=h.next;return{iterator:h,nextMethod:b,done:!1}}function Ju(r){let i=A(r.nextMethod,r.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function Vu(r){return!!r.done}function Yu(r){return r.value}function Zu(r){return!(typeof r!="number"||wi(r)||r<0)}function Ei(r){let i=Ti(r.buffer,r.byteOffset,r.byteOffset+r.byteLength);return new Uint8Array(i)}function Ds(r){let i=r._queue.shift();return r._queueTotalSize-=i.size,r._queueTotalSize<0&&(r._queueTotalSize=0),i.value}function Ls(r,i,c){if(!Zu(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");r._queue.push({value:i,size:c}),r._queueTotalSize+=c}function Xu(r){return r._queue.peek().value}function Qe(r){r._queue=new k,r._queueTotalSize=0}function vi(r){return r===DataView}function Qu(r){return vi(r.constructor)}function Ku(r){return vi(r)?1:r.BYTES_PER_ELEMENT}class bt{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ns(this))throw qs("view");return this._view}respond(i){if(!Ns(this))throw qs("respond");if(Ne(i,1,"respond"),i=Cs(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Xe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");qr(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!Ns(this))throw qs("respondWithNewView");if(Ne(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))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(Xe(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");jr(this._associatedReadableByteStreamController,i)}}Object.defineProperties(bt.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(bt.prototype.respond,"respond"),o(bt.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bt.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Fe{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!St(this))throw dr("byobRequest");return Us(this)}get desiredSize(){if(!St(this))throw dr("desiredSize");return Li(this)}close(){if(!St(this))throw dr("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);ur(this)}enqueue(i){if(!St(this))throw dr("enqueue");if(Ne(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.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 c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);Ur(this,i)}error(i=void 0){if(!St(this))throw dr("error");pe(this,i)}[Ve](i){xi(this),Qe(this);let c=this._cancelAlgorithm(i);return Br(this),c}[ar](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){Di(this,i);return}let h=this._autoAllocateChunkSize;if(h!==void 0){let b;try{b=new ArrayBuffer(h)}catch(T){i._errorSteps(T);return}let w={buffer:b,bufferByteLength:h,byteOffset:0,byteLength:h,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(w)}pi(c,i),wt(this)}[_s](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new k,this._pendingPullIntos.push(i)}}}Object.defineProperties(Fe.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Fe.prototype.close,"close"),o(Fe.prototype.enqueue,"enqueue"),o(Fe.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fe.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function St(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledReadableByteStream")?!1:r instanceof Fe}function Ns(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_associatedReadableByteStreamController")?!1:r instanceof bt}function wt(r){if(!sd(r))return;if(r._pulling){r._pullAgain=!0;return}r._pulling=!0;let c=r._pullAlgorithm();g(c,()=>(r._pulling=!1,r._pullAgain&&(r._pullAgain=!1,wt(r)),null),h=>(pe(r,h),null))}function xi(r){Fs(r),r._pendingPullIntos=new k}function Ms(r,i){let c=!1;r._state==="closed"&&(c=!0);let h=Ci(i);i.readerType==="default"?Ps(r,h,c):ud(r,h,c)}function Ci(r){let i=r.bytesFilled,c=r.elementSize;return new r.viewConstructor(r.buffer,r.byteOffset,i/c)}function Fr(r,i,c,h){r._queue.push({buffer:i,byteOffset:c,byteLength:h}),r._queueTotalSize+=h}function Ai(r,i,c,h){let b;try{b=Ti(i,c,c+h)}catch(w){throw pe(r,w),w}Fr(r,b,0,h)}function Pi(r,i){i.bytesFilled>0&&Ai(r,i.buffer,i.byteOffset,i.bytesFilled),Dt(r)}function Ii(r,i){let c=Math.min(r._queueTotalSize,i.byteLength-i.bytesFilled),h=i.bytesFilled+c,b=c,w=!1,T=h%i.elementSize,P=h-T;P>=i.minimumFill&&(b=P-i.bytesFilled,w=!0);let D=r._queue;for(;b>0;){let I=D.peek(),L=Math.min(b,I.byteLength),N=i.byteOffset+i.bytesFilled;_i(i.buffer,N,I.buffer,I.byteOffset,L),I.byteLength===L?D.shift():(I.byteOffset+=L,I.byteLength-=L),r._queueTotalSize-=L,Oi(r,L,i),b-=L}return w}function Oi(r,i,c){c.bytesFilled+=i}function ki(r){r._queueTotalSize===0&&r._closeRequested?(Br(r),yr(r._controlledReadableByteStream)):wt(r)}function Fs(r){r._byobRequest!==null&&(r._byobRequest._associatedReadableByteStreamController=void 0,r._byobRequest._view=null,r._byobRequest=null)}function Bs(r){for(;r._pendingPullIntos.length>0;){if(r._queueTotalSize===0)return;let i=r._pendingPullIntos.peek();Ii(r,i)&&(Dt(r),Ms(r._controlledReadableByteStream,i))}}function ed(r){let i=r._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(r._queueTotalSize===0)return;let c=i._readRequests.shift();Di(r,c)}}function td(r,i,c,h){let b=r._controlledReadableByteStream,w=i.constructor,T=Ku(w),{byteOffset:P,byteLength:D}=i,I=c*T,L;try{L=Me(i.buffer)}catch(B){h._errorSteps(B);return}let N={buffer:L,bufferByteLength:L.byteLength,byteOffset:P,byteLength:D,bytesFilled:0,minimumFill:I,elementSize:T,viewConstructor:w,readerType:"byob"};if(r._pendingPullIntos.length>0){r._pendingPullIntos.push(N),Fi(b,h);return}if(b._state==="closed"){let B=new w(N.buffer,N.byteOffset,0);h._closeSteps(B);return}if(r._queueTotalSize>0){if(Ii(r,N)){let B=Ci(N);ki(r),h._chunkSteps(B);return}if(r._closeRequested){let B=new TypeError("Insufficient bytes to fill elements in the given buffer");pe(r,B),h._errorSteps(B);return}}r._pendingPullIntos.push(N),Fi(b,h),wt(r)}function rd(r,i){i.readerType==="none"&&Dt(r);let c=r._controlledReadableByteStream;if(js(c))for(;Bi(c)>0;){let h=Dt(r);Ms(c,h)}}function nd(r,i,c){if(Oi(r,i,c),c.readerType==="none"){Pi(r,c),Bs(r);return}if(c.bytesFilled<c.minimumFill)return;Dt(r);let h=c.bytesFilled%c.elementSize;if(h>0){let b=c.byteOffset+c.bytesFilled;Ai(r,c.buffer,b-h,h)}c.bytesFilled-=h,Ms(r._controlledReadableByteStream,c),Bs(r)}function $i(r,i){let c=r._pendingPullIntos.peek();Fs(r),r._controlledReadableByteStream._state==="closed"?rd(r,c):nd(r,i,c),wt(r)}function Dt(r){return r._pendingPullIntos.shift()}function sd(r){let i=r._controlledReadableByteStream;return i._state!=="readable"||r._closeRequested||!r._started?!1:!!(mi(i)&&Lr(i)>0||js(i)&&Bi(i)>0||Li(r)>0)}function Br(r){r._pullAlgorithm=void 0,r._cancelAlgorithm=void 0}function ur(r){let i=r._controlledReadableByteStream;if(!(r._closeRequested||i._state!=="readable")){if(r._queueTotalSize>0){r._closeRequested=!0;return}if(r._pendingPullIntos.length>0){let c=r._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let h=new TypeError("Insufficient bytes to fill elements in the given buffer");throw pe(r,h),h}}Br(r),yr(i)}}function Ur(r,i){let c=r._controlledReadableByteStream;if(r._closeRequested||c._state!=="readable")return;let{buffer:h,byteOffset:b,byteLength:w}=i;if(Xe(h))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let T=Me(h);if(r._pendingPullIntos.length>0){let P=r._pendingPullIntos.peek();if(Xe(P.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Fs(r),P.buffer=Me(P.buffer),P.readerType==="none"&&Pi(r,P)}if(mi(c))if(ed(r),Lr(c)===0)Fr(r,T,b,w);else{r._pendingPullIntos.length>0&&Dt(r);let P=new Uint8Array(T,b,w);Ps(c,P,!1)}else js(c)?(Fr(r,T,b,w),Bs(r)):Fr(r,T,b,w);wt(r)}function pe(r,i){let c=r._controlledReadableByteStream;c._state==="readable"&&(xi(r),Qe(r),Br(r),la(c,i))}function Di(r,i){let c=r._queue.shift();r._queueTotalSize-=c.byteLength,ki(r);let h=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(h)}function Us(r){if(r._byobRequest===null&&r._pendingPullIntos.length>0){let i=r._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),h=Object.create(bt.prototype);id(h,r,c),r._byobRequest=h}return r._byobRequest}function Li(r){let i=r._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:r._strategyHWM-r._queueTotalSize}function qr(r,i){let c=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=Me(c.buffer),$i(r,i)}function jr(r,i){let c=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let b=i.byteLength;c.buffer=Me(i.buffer),$i(r,b)}function Ni(r,i,c,h,b,w,T){i._controlledReadableByteStream=r,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,Qe(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,i._autoAllocateChunkSize=T,i._pendingPullIntos=new k,r._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,wt(i),null),D=>(pe(i,D),null))}function od(r,i,c){let h=Object.create(Fe.prototype),b,w,T;i.start!==void 0?b=()=>i.start(h):b=()=>{},i.pull!==void 0?w=()=>i.pull(h):w=()=>u(void 0),i.cancel!==void 0?T=D=>i.cancel(D):T=()=>u(void 0);let P=i.autoAllocateChunkSize;if(P===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ni(r,h,b,w,T,c,P)}function id(r,i,c){r._associatedReadableByteStreamController=i,r._view=c}function qs(r){return new TypeError(`ReadableStreamBYOBRequest.prototype.${r} can only be used on a ReadableStreamBYOBRequest`)}function dr(r){return new TypeError(`ReadableByteStreamController.prototype.${r} can only be used on a ReadableByteStreamController`)}function ad(r,i){Ce(r,i);let c=r?.mode;return{mode:c===void 0?void 0:cd(c,`${i} has member 'mode' that`)}}function cd(r,i){if(r=`${r}`,r!=="byob")throw new TypeError(`${i} '${r}' is not a valid enumeration value for ReadableStreamReaderMode`);return r}function ld(r,i){var c;Ce(r,i);let h=(c=r?.min)!==null&&c!==void 0?c:1;return{min:Cs(h,`${i} has member 'min' that`)}}function Mi(r){return new Ke(r)}function Fi(r,i){r._reader._readIntoRequests.push(i)}function ud(r,i,c){let b=r._reader._readIntoRequests.shift();c?b._closeSteps(i):b._chunkSteps(i)}function Bi(r){return r._reader._readIntoRequests.length}function js(r){let i=r._reader;return!(i===void 0||!_t(i))}class Ke{constructor(i){if(Ne(i,1,"ReadableStreamBYOBReader"),As(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!St(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ai(this,i),this._readIntoRequests=new k}get closed(){return _t(this)?this._closedPromise:f(Wr("closed"))}cancel(i=void 0){return _t(this)?this._ownerReadableStream===void 0?f(Dr("cancel")):Ts(this,i):f(Wr("cancel"))}read(i,c={}){if(!_t(this))return f(Wr("read"));if(!ArrayBuffer.isView(i))return f(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(Xe(i.buffer))return f(new TypeError("view's buffer has been detached"));let h;try{h=ld(c,"options")}catch(I){return f(I)}let b=h.min;if(b===0)return f(new TypeError("options.min must be greater than 0"));if(Qu(i)){if(b>i.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(b>i.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(Dr("read from"));let w,T,P=p((I,L)=>{w=I,T=L});return Ui(this,i,b,{_chunkSteps:I=>w({value:I,done:!1}),_closeSteps:I=>w({value:I,done:!0}),_errorSteps:I=>T(I)}),P}releaseLock(){if(!_t(this))throw Wr("releaseLock");this._ownerReadableStream!==void 0&&dd(this)}}Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ke.prototype.cancel,"cancel"),o(Ke.prototype.read,"read"),o(Ke.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function _t(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readIntoRequests")?!1:r instanceof Ke}function Ui(r,i,c,h){let b=r._ownerReadableStream;b._disturbed=!0,b._state==="errored"?h._errorSteps(b._storedError):td(b._readableStreamController,i,c,h)}function dd(r){Le(r);let i=new TypeError("Reader was released");qi(r,i)}function qi(r,i){let c=r._readIntoRequests;r._readIntoRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Wr(r){return new TypeError(`ReadableStreamBYOBReader.prototype.${r} can only be used on a ReadableStreamBYOBReader`)}function fr(r,i){let{highWaterMark:c}=r;if(c===void 0)return i;if(wi(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function zr(r){let{size:i}=r;return i||(()=>1)}function Hr(r,i){Ce(r,i);let c=r?.highWaterMark,h=r?.size;return{highWaterMark:c===void 0?void 0:xs(c),size:h===void 0?void 0:fd(h,`${i} has member 'size' that`)}}function fd(r,i){return fe(r,i),c=>xs(r(c))}function pd(r,i){Ce(r,i);let c=r?.abort,h=r?.close,b=r?.start,w=r?.type,T=r?.write;return{abort:c===void 0?void 0:md(c,r,`${i} has member 'abort' that`),close:h===void 0?void 0:hd(h,r,`${i} has member 'close' that`),start:b===void 0?void 0:gd(b,r,`${i} has member 'start' that`),write:T===void 0?void 0:yd(T,r,`${i} has member 'write' that`),type:w}}function md(r,i,c){return fe(r,c),h=>C(r,i,[h])}function hd(r,i,c){return fe(r,c),()=>C(r,i,[])}function gd(r,i,c){return fe(r,c),h=>A(r,i,[h])}function yd(r,i,c){return fe(r,c),(h,b)=>C(r,i,[h,b])}function ji(r,i){if(!Lt(r))throw new TypeError(`${i} is not a WritableStream.`)}function bd(r){if(typeof r!="object"||r===null)return!1;try{return typeof r.aborted=="boolean"}catch{return!1}}let Sd=typeof AbortController=="function";function wd(){if(Sd)return new AbortController}class et{constructor(i={},c={}){i===void 0?i=null:di(i,"First parameter");let h=Hr(c,"Second parameter"),b=pd(i,"First parameter");if(zi(this),b.type!==void 0)throw new RangeError("Invalid type is specified");let T=zr(h),P=fr(h,1);Dd(this,b,P,T)}get locked(){if(!Lt(this))throw Zr("locked");return Nt(this)}abort(i=void 0){return Lt(this)?Nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Gr(this,i):f(Zr("abort"))}close(){return Lt(this)?Nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):Ae(this)?f(new TypeError("Cannot close an already-closing stream")):Hi(this):f(Zr("close"))}getWriter(){if(!Lt(this))throw Zr("getWriter");return Wi(this)}}Object.defineProperties(et.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(et.prototype.abort,"abort"),o(et.prototype.close,"close"),o(et.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Wi(r){return new Be(r)}function _d(r,i,c,h,b=1,w=()=>1){let T=Object.create(et.prototype);zi(T);let P=Object.create(Mt.prototype);return Xi(T,P,r,i,c,h,b,w),T}function zi(r){r._state="writable",r._storedError=void 0,r._writer=void 0,r._writableStreamController=void 0,r._writeRequests=new k,r._inFlightWriteRequest=void 0,r._closeRequest=void 0,r._inFlightCloseRequest=void 0,r._pendingAbortRequest=void 0,r._backpressure=!1}function Lt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_writableStreamController")?!1:r instanceof et}function Nt(r){return r._writer!==void 0}function Gr(r,i){var c;if(r._state==="closed"||r._state==="errored")return u(void 0);r._writableStreamController._abortReason=i,(c=r._writableStreamController._abortController)===null||c===void 0||c.abort(i);let h=r._state;if(h==="closed"||h==="errored")return u(void 0);if(r._pendingAbortRequest!==void 0)return r._pendingAbortRequest._promise;let b=!1;h==="erroring"&&(b=!0,i=void 0);let w=p((T,P)=>{r._pendingAbortRequest={_promise:void 0,_resolve:T,_reject:P,_reason:i,_wasAlreadyErroring:b}});return r._pendingAbortRequest._promise=w,b||zs(r,i),w}function Hi(r){let i=r._state;if(i==="closed"||i==="errored")return f(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=p((b,w)=>{let T={_resolve:b,_reject:w};r._closeRequest=T}),h=r._writer;return h!==void 0&&r._backpressure&&i==="writable"&&Qs(h),Ld(r._writableStreamController),c}function Td(r){return p((c,h)=>{let b={_resolve:c,_reject:h};r._writeRequests.push(b)})}function Ws(r,i){if(r._state==="writable"){zs(r,i);return}Hs(r)}function zs(r,i){let c=r._writableStreamController;r._state="erroring",r._storedError=i;let h=r._writer;h!==void 0&&Ji(h,i),!Cd(r)&&c._started&&Hs(r)}function Hs(r){r._state="errored",r._writableStreamController[H]();let i=r._storedError;if(r._writeRequests.forEach(b=>{b._reject(i)}),r._writeRequests=new k,r._pendingAbortRequest===void 0){Jr(r);return}let c=r._pendingAbortRequest;if(r._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Jr(r);return}let h=r._writableStreamController[$](c._reason);g(h,()=>(c._resolve(),Jr(r),null),b=>(c._reject(b),Jr(r),null))}function Rd(r){r._inFlightWriteRequest._resolve(void 0),r._inFlightWriteRequest=void 0}function Ed(r,i){r._inFlightWriteRequest._reject(i),r._inFlightWriteRequest=void 0,Ws(r,i)}function vd(r){r._inFlightCloseRequest._resolve(void 0),r._inFlightCloseRequest=void 0,r._state==="erroring"&&(r._storedError=void 0,r._pendingAbortRequest!==void 0&&(r._pendingAbortRequest._resolve(),r._pendingAbortRequest=void 0)),r._state="closed";let c=r._writer;c!==void 0&&ta(c)}function xd(r,i){r._inFlightCloseRequest._reject(i),r._inFlightCloseRequest=void 0,r._pendingAbortRequest!==void 0&&(r._pendingAbortRequest._reject(i),r._pendingAbortRequest=void 0),Ws(r,i)}function Ae(r){return!(r._closeRequest===void 0&&r._inFlightCloseRequest===void 0)}function Cd(r){return!(r._inFlightWriteRequest===void 0&&r._inFlightCloseRequest===void 0)}function Ad(r){r._inFlightCloseRequest=r._closeRequest,r._closeRequest=void 0}function Pd(r){r._inFlightWriteRequest=r._writeRequests.shift()}function Jr(r){r._closeRequest!==void 0&&(r._closeRequest._reject(r._storedError),r._closeRequest=void 0);let i=r._writer;i!==void 0&&Zs(i,r._storedError)}function Gs(r,i){let c=r._writer;c!==void 0&&i!==r._backpressure&&(i?jd(c):Qs(c)),r._backpressure=i}class Be{constructor(i){if(Ne(i,1,"WritableStreamDefaultWriter"),ji(i,"First parameter"),Nt(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Ae(i)&&i._backpressure?Qr(this):ra(this),Xr(this);else if(c==="erroring")Xs(this,i._storedError),Xr(this);else if(c==="closed")ra(this),Ud(this);else{let h=i._storedError;Xs(this,h),ea(this,h)}}get closed(){return Tt(this)?this._closedPromise:f(Rt("closed"))}get desiredSize(){if(!Tt(this))throw Rt("desiredSize");if(this._ownerWritableStream===void 0)throw mr("desiredSize");return $d(this)}get ready(){return Tt(this)?this._readyPromise:f(Rt("ready"))}abort(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(mr("abort")):Id(this,i):f(Rt("abort"))}close(){if(!Tt(this))return f(Rt("close"));let i=this._ownerWritableStream;return i===void 0?f(mr("close")):Ae(i)?f(new TypeError("Cannot close an already-closing stream")):Gi(this)}releaseLock(){if(!Tt(this))throw Rt("releaseLock");this._ownerWritableStream!==void 0&&Vi(this)}write(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(mr("write to")):Yi(this,i):f(Rt("write"))}}Object.defineProperties(Be.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(Be.prototype.abort,"abort"),o(Be.prototype.close,"close"),o(Be.prototype.releaseLock,"releaseLock"),o(Be.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Be.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Tt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_ownerWritableStream")?!1:r instanceof Be}function Id(r,i){let c=r._ownerWritableStream;return Gr(c,i)}function Gi(r){let i=r._ownerWritableStream;return Hi(i)}function Od(r){let i=r._ownerWritableStream,c=i._state;return Ae(i)||c==="closed"?u(void 0):c==="errored"?f(i._storedError):Gi(r)}function kd(r,i){r._closedPromiseState==="pending"?Zs(r,i):qd(r,i)}function Ji(r,i){r._readyPromiseState==="pending"?na(r,i):Wd(r,i)}function $d(r){let i=r._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:Qi(i._writableStreamController)}function Vi(r){let i=r._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Ji(r,c),kd(r,c),i._writer=void 0,r._ownerWritableStream=void 0}function Yi(r,i){let c=r._ownerWritableStream,h=c._writableStreamController,b=Nd(h,i);if(c!==r._ownerWritableStream)return f(mr("write to"));let w=c._state;if(w==="errored")return f(c._storedError);if(Ae(c)||w==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(w==="erroring")return f(c._storedError);let T=Td(c);return Md(h,i,b),T}let Zi={};class Mt{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Js(this))throw Ys("abortReason");return this._abortReason}get signal(){if(!Js(this))throw Ys("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!Js(this))throw Ys("error");this._controlledWritableStream._state==="writable"&&Ki(this,i)}[$](i){let c=this._abortAlgorithm(i);return Vr(this),c}[H](){Qe(this)}}Object.defineProperties(Mt.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Js(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledWritableStream")?!1:r instanceof Mt}function Xi(r,i,c,h,b,w,T,P){i._controlledWritableStream=r,r._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._abortReason=void 0,i._abortController=wd(),i._started=!1,i._strategySizeAlgorithm=P,i._strategyHWM=T,i._writeAlgorithm=h,i._closeAlgorithm=b,i._abortAlgorithm=w;let D=Vs(i);Gs(r,D);let I=c(),L=u(I);g(L,()=>(i._started=!0,Yr(i),null),N=>(i._started=!0,Ws(r,N),null))}function Dd(r,i,c,h){let b=Object.create(Mt.prototype),w,T,P,D;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.write!==void 0?T=I=>i.write(I,b):T=()=>u(void 0),i.close!==void 0?P=()=>i.close():P=()=>u(void 0),i.abort!==void 0?D=I=>i.abort(I):D=()=>u(void 0),Xi(r,b,w,T,P,D,c,h)}function Vr(r){r._writeAlgorithm=void 0,r._closeAlgorithm=void 0,r._abortAlgorithm=void 0,r._strategySizeAlgorithm=void 0}function Ld(r){Ls(r,Zi,0),Yr(r)}function Nd(r,i){try{return r._strategySizeAlgorithm(i)}catch(c){return pr(r,c),1}}function Qi(r){return r._strategyHWM-r._queueTotalSize}function Md(r,i,c){try{Ls(r,i,c)}catch(b){pr(r,b);return}let h=r._controlledWritableStream;if(!Ae(h)&&h._state==="writable"){let b=Vs(r);Gs(h,b)}Yr(r)}function Yr(r){let i=r._controlledWritableStream;if(!r._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){Hs(i);return}if(r._queue.length===0)return;let h=Xu(r);h===Zi?Fd(r):Bd(r,h)}function pr(r,i){r._controlledWritableStream._state==="writable"&&Ki(r,i)}function Fd(r){let i=r._controlledWritableStream;Ad(i),Ds(r);let c=r._closeAlgorithm();Vr(r),g(c,()=>(vd(i),null),h=>(xd(i,h),null))}function Bd(r,i){let c=r._controlledWritableStream;Pd(c);let h=r._writeAlgorithm(i);g(h,()=>{Rd(c);let b=c._state;if(Ds(r),!Ae(c)&&b==="writable"){let w=Vs(r);Gs(c,w)}return Yr(r),null},b=>(c._state==="writable"&&Vr(r),Ed(c,b),null))}function Vs(r){return Qi(r)<=0}function Ki(r,i){let c=r._controlledWritableStream;Vr(r),zs(c,i)}function Zr(r){return new TypeError(`WritableStream.prototype.${r} can only be used on a WritableStream`)}function Ys(r){return new TypeError(`WritableStreamDefaultController.prototype.${r} can only be used on a WritableStreamDefaultController`)}function Rt(r){return new TypeError(`WritableStreamDefaultWriter.prototype.${r} can only be used on a WritableStreamDefaultWriter`)}function mr(r){return new TypeError("Cannot "+r+" a stream using a released writer")}function Xr(r){r._closedPromise=p((i,c)=>{r._closedPromise_resolve=i,r._closedPromise_reject=c,r._closedPromiseState="pending"})}function ea(r,i){Xr(r),Zs(r,i)}function Ud(r){Xr(r),ta(r)}function Zs(r,i){r._closedPromise_reject!==void 0&&(R(r._closedPromise),r._closedPromise_reject(i),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0,r._closedPromiseState="rejected")}function qd(r,i){ea(r,i)}function ta(r){r._closedPromise_resolve!==void 0&&(r._closedPromise_resolve(void 0),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0,r._closedPromiseState="resolved")}function Qr(r){r._readyPromise=p((i,c)=>{r._readyPromise_resolve=i,r._readyPromise_reject=c}),r._readyPromiseState="pending"}function Xs(r,i){Qr(r),na(r,i)}function ra(r){Qr(r),Qs(r)}function na(r,i){r._readyPromise_reject!==void 0&&(R(r._readyPromise),r._readyPromise_reject(i),r._readyPromise_resolve=void 0,r._readyPromise_reject=void 0,r._readyPromiseState="rejected")}function jd(r){Qr(r)}function Wd(r,i){Xs(r,i)}function Qs(r){r._readyPromise_resolve!==void 0&&(r._readyPromise_resolve(void 0),r._readyPromise_resolve=void 0,r._readyPromise_reject=void 0,r._readyPromiseState="fulfilled")}function zd(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Ks=zd();function Hd(r){if(!(typeof r=="function"||typeof r=="object")||r.name!=="DOMException")return!1;try{return new r,!0}catch{return!1}}function Gd(){let r=Ks?.DOMException;return Hd(r)?r:void 0}function Jd(){let r=function(c,h){this.message=c||"",this.name=h||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(r,"DOMException"),r.prototype=Object.create(Error.prototype),Object.defineProperty(r.prototype,"constructor",{value:r,writable:!0,configurable:!0}),r}let Vd=Gd()||Jd();function sa(r,i,c,h,b,w){let T=$t(r),P=Wi(i);r._disturbed=!0;let D=!1,I=u(void 0);return p((L,N)=>{let B;if(w!==void 0){if(B=()=>{let O=w.reason!==void 0?w.reason:new Vd("Aborted","AbortError"),M=[];h||M.push(()=>i._state==="writable"?Gr(i,O):u(void 0)),b||M.push(()=>r._state==="readable"?_e(r,O):u(void 0)),re(()=>Promise.all(M.map(q=>q())),!0,O)},w.aborted){B();return}w.addEventListener("abort",B)}function Te(){return p((O,M)=>{function q(ae){ae?O():y(qt(),q,M)}q(!1)})}function qt(){return D?u(!0):y(P._readyPromise,()=>p((O,M)=>{cr(T,{_chunkSteps:q=>{I=y(Yi(P,q),void 0,e),O(!1)},_closeSteps:()=>O(!0),_errorSteps:M})}))}if(qe(r,T._closedPromise,O=>(h?me(!0,O):re(()=>Gr(i,O),!0,O),null)),qe(i,P._closedPromise,O=>(b?me(!0,O):re(()=>_e(r,O),!0,O),null)),ee(r,T._closedPromise,()=>(c?me():re(()=>Od(P)),null)),Ae(i)||i._state==="closed"){let O=new TypeError("the destination writable stream closed before all data could be piped to it");b?me(!0,O):re(()=>_e(r,O),!0,O)}R(Te());function st(){let O=I;return y(I,()=>O!==I?st():void 0)}function qe(O,M,q){O._state==="errored"?q(O._storedError):S(M,q)}function ee(O,M,q){O._state==="closed"?q():_(M,q)}function re(O,M,q){if(D)return;D=!0,i._state==="writable"&&!Ae(i)?_(st(),ae):ae();function ae(){return g(O(),()=>je(M,q),jt=>je(!0,jt)),null}}function me(O,M){D||(D=!0,i._state==="writable"&&!Ae(i)?_(st(),()=>je(O,M)):je(O,M))}function je(O,M){return Vi(P),Le(T),w!==void 0&&w.removeEventListener("abort",B),O?N(M):L(void 0),null}})}class Ue{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Kr(this))throw tn("desiredSize");return eo(this)}close(){if(!Kr(this))throw tn("close");if(!Bt(this))throw new TypeError("The stream is not in a state that permits close");Et(this)}enqueue(i=void 0){if(!Kr(this))throw tn("enqueue");if(!Bt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Ft(this,i)}error(i=void 0){if(!Kr(this))throw tn("error");we(this,i)}[Ve](i){Qe(this);let c=this._cancelAlgorithm(i);return en(this),c}[ar](i){let c=this._controlledReadableStream;if(this._queue.length>0){let h=Ds(this);this._closeRequested&&this._queue.length===0?(en(this),yr(c)):hr(this),i._chunkSteps(h)}else pi(c,i),hr(this)}[_s](){}}Object.defineProperties(Ue.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Ue.prototype.close,"close"),o(Ue.prototype.enqueue,"enqueue"),o(Ue.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ue.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Kr(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledReadableStream")?!1:r instanceof Ue}function hr(r){if(!oa(r))return;if(r._pulling){r._pullAgain=!0;return}r._pulling=!0;let c=r._pullAlgorithm();g(c,()=>(r._pulling=!1,r._pullAgain&&(r._pullAgain=!1,hr(r)),null),h=>(we(r,h),null))}function oa(r){let i=r._controlledReadableStream;return!Bt(r)||!r._started?!1:!!(rt(i)&&Lr(i)>0||eo(r)>0)}function en(r){r._pullAlgorithm=void 0,r._cancelAlgorithm=void 0,r._strategySizeAlgorithm=void 0}function Et(r){if(!Bt(r))return;let i=r._controlledReadableStream;r._closeRequested=!0,r._queue.length===0&&(en(r),yr(i))}function Ft(r,i){if(!Bt(r))return;let c=r._controlledReadableStream;if(rt(c)&&Lr(c)>0)Ps(c,i,!1);else{let h;try{h=r._strategySizeAlgorithm(i)}catch(b){throw we(r,b),b}try{Ls(r,i,h)}catch(b){throw we(r,b),b}}hr(r)}function we(r,i){let c=r._controlledReadableStream;c._state==="readable"&&(Qe(r),en(r),la(c,i))}function eo(r){let i=r._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:r._strategyHWM-r._queueTotalSize}function Yd(r){return!oa(r)}function Bt(r){let i=r._controlledReadableStream._state;return!r._closeRequested&&i==="readable"}function ia(r,i,c,h,b,w,T){i._controlledReadableStream=r,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=T,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,r._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,hr(i),null),D=>(we(i,D),null))}function Zd(r,i,c,h){let b=Object.create(Ue.prototype),w,T,P;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.pull!==void 0?T=()=>i.pull(b):T=()=>u(void 0),i.cancel!==void 0?P=D=>i.cancel(D):P=()=>u(void 0),ia(r,b,w,T,P,c,h)}function tn(r){return new TypeError(`ReadableStreamDefaultController.prototype.${r} can only be used on a ReadableStreamDefaultController`)}function Xd(r,i){return St(r._readableStreamController)?Kd(r):Qd(r)}function Qd(r,i){let c=$t(r),h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(ee=>{N=ee});function Te(){return h?(b=!0,u(void 0)):(h=!0,cr(c,{_chunkSteps:re=>{v(()=>{b=!1;let me=re,je=re;w||Ft(I._readableStreamController,me),T||Ft(L._readableStreamController,je),h=!1,b&&Te()})},_closeSteps:()=>{h=!1,w||Et(I._readableStreamController),T||Et(L._readableStreamController),(!w||!T)&&N(void 0)},_errorSteps:()=>{h=!1}}),u(void 0))}function qt(ee){if(w=!0,P=ee,T){let re=lr([P,D]),me=_e(r,re);N(me)}return B}function st(ee){if(T=!0,D=ee,w){let re=lr([P,D]),me=_e(r,re);N(me)}return B}function qe(){}return I=gr(qe,Te,qt),L=gr(qe,Te,st),S(c._closedPromise,ee=>(we(I._readableStreamController,ee),we(L._readableStreamController,ee),(!w||!T)&&N(void 0),null)),[I,L]}function Kd(r){let i=$t(r),c=!1,h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(O=>{N=O});function Te(O){S(O._closedPromise,M=>(O!==i||(pe(I._readableStreamController,M),pe(L._readableStreamController,M),(!w||!T)&&N(void 0)),null))}function qt(){_t(i)&&(Le(i),i=$t(r),Te(i)),cr(i,{_chunkSteps:M=>{v(()=>{h=!1,b=!1;let q=M,ae=M;if(!w&&!T)try{ae=Ei(M)}catch(jt){pe(I._readableStreamController,jt),pe(L._readableStreamController,jt),N(_e(r,jt));return}w||Ur(I._readableStreamController,q),T||Ur(L._readableStreamController,ae),c=!1,h?qe():b&&ee()})},_closeSteps:()=>{c=!1,w||ur(I._readableStreamController),T||ur(L._readableStreamController),I._readableStreamController._pendingPullIntos.length>0&&qr(I._readableStreamController,0),L._readableStreamController._pendingPullIntos.length>0&&qr(L._readableStreamController,0),(!w||!T)&&N(void 0)},_errorSteps:()=>{c=!1}})}function st(O,M){Ze(i)&&(Le(i),i=Mi(r),Te(i));let q=M?L:I,ae=M?I:L;Ui(i,O,1,{_chunkSteps:Wt=>{v(()=>{h=!1,b=!1;let zt=M?T:w;if(M?w:T)zt||jr(q._readableStreamController,Wt);else{let Ta;try{Ta=Ei(Wt)}catch(oo){pe(q._readableStreamController,oo),pe(ae._readableStreamController,oo),N(_e(r,oo));return}zt||jr(q._readableStreamController,Wt),Ur(ae._readableStreamController,Ta)}c=!1,h?qe():b&&ee()})},_closeSteps:Wt=>{c=!1;let zt=M?T:w,un=M?w:T;zt||ur(q._readableStreamController),un||ur(ae._readableStreamController),Wt!==void 0&&(zt||jr(q._readableStreamController,Wt),!un&&ae._readableStreamController._pendingPullIntos.length>0&&qr(ae._readableStreamController,0)),(!zt||!un)&&N(void 0)},_errorSteps:()=>{c=!1}})}function qe(){if(c)return h=!0,u(void 0);c=!0;let O=Us(I._readableStreamController);return O===null?qt():st(O._view,!1),u(void 0)}function ee(){if(c)return b=!0,u(void 0);c=!0;let O=Us(L._readableStreamController);return O===null?qt():st(O._view,!0),u(void 0)}function re(O){if(w=!0,P=O,T){let M=lr([P,D]),q=_e(r,M);N(q)}return B}function me(O){if(T=!0,D=O,w){let M=lr([P,D]),q=_e(r,M);N(q)}return B}function je(){}return I=ca(je,qe,re),L=ca(je,ee,me),Te(i),[I,L]}function ef(r){return t(r)&&typeof r.getReader<"u"}function tf(r){return ef(r)?nf(r.getReader()):rf(r)}function rf(r){let i,c=Ri(r,"async"),h=e;function b(){let T;try{T=Ju(c)}catch(D){return f(D)}let P=u(T);return E(P,D=>{if(!t(D))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Vu(D))Et(i._readableStreamController);else{let L=Yu(D);Ft(i._readableStreamController,L)}})}function w(T){let P=c.iterator,D;try{D=Mr(P,"return")}catch(N){return f(N)}if(D===void 0)return u(void 0);let I;try{I=A(D,P,[T])}catch(N){return f(N)}let L=u(I);return E(L,N=>{if(!t(N))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=gr(h,b,w,0),i}function nf(r){let i,c=e;function h(){let w;try{w=r.read()}catch(T){return f(T)}return E(w,T=>{if(!t(T))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(T.done)Et(i._readableStreamController);else{let P=T.value;Ft(i._readableStreamController,P)}})}function b(w){try{return u(r.cancel(w))}catch(T){return f(T)}}return i=gr(c,h,b,0),i}function sf(r,i){Ce(r,i);let c=r,h=c?.autoAllocateChunkSize,b=c?.cancel,w=c?.pull,T=c?.start,P=c?.type;return{autoAllocateChunkSize:h===void 0?void 0:Cs(h,`${i} has member 'autoAllocateChunkSize' that`),cancel:b===void 0?void 0:of(b,c,`${i} has member 'cancel' that`),pull:w===void 0?void 0:af(w,c,`${i} has member 'pull' that`),start:T===void 0?void 0:cf(T,c,`${i} has member 'start' that`),type:P===void 0?void 0:lf(P,`${i} has member 'type' that`)}}function of(r,i,c){return fe(r,c),h=>C(r,i,[h])}function af(r,i,c){return fe(r,c),h=>C(r,i,[h])}function cf(r,i,c){return fe(r,c),h=>A(r,i,[h])}function lf(r,i){if(r=`${r}`,r!=="bytes")throw new TypeError(`${i} '${r}' is not a valid enumeration value for ReadableStreamType`);return r}function uf(r,i){return Ce(r,i),{preventCancel:!!r?.preventCancel}}function aa(r,i){Ce(r,i);let c=r?.preventAbort,h=r?.preventCancel,b=r?.preventClose,w=r?.signal;return w!==void 0&&df(w,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!h,preventClose:!!b,signal:w}}function df(r,i){if(!bd(r))throw new TypeError(`${i} is not an AbortSignal.`)}function ff(r,i){Ce(r,i);let c=r?.readable;vs(c,"readable","ReadableWritablePair"),As(c,`${i} has member 'readable' that`);let h=r?.writable;return vs(h,"writable","ReadableWritablePair"),ji(h,`${i} has member 'writable' that`),{readable:c,writable:h}}class Q{constructor(i={},c={}){i===void 0?i=null:di(i,"First parameter");let h=Hr(c,"Second parameter"),b=sf(i,"First parameter");if(to(this),b.type==="bytes"){if(h.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let w=fr(h,0);od(this,b,w)}else{let w=zr(h),T=fr(h,1);Zd(this,b,T,w)}}get locked(){if(!tt(this))throw vt("locked");return rt(this)}cancel(i=void 0){return tt(this)?rt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):_e(this,i):f(vt("cancel"))}getReader(i=void 0){if(!tt(this))throw vt("getReader");return ad(i,"First parameter").mode===void 0?$t(this):Mi(this)}pipeThrough(i,c={}){if(!tt(this))throw vt("pipeThrough");Ne(i,1,"pipeThrough");let h=ff(i,"First parameter"),b=aa(c,"Second parameter");if(rt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Nt(h.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let w=sa(this,h.writable,b.preventClose,b.preventAbort,b.preventCancel,b.signal);return R(w),h.readable}pipeTo(i,c={}){if(!tt(this))return f(vt("pipeTo"));if(i===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Lt(i))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let h;try{h=aa(c,"Second parameter")}catch(b){return f(b)}return rt(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Nt(i)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):sa(this,i,h.preventClose,h.preventAbort,h.preventCancel,h.signal)}tee(){if(!tt(this))throw vt("tee");let i=Xd(this);return lr(i)}values(i=void 0){if(!tt(this))throw vt("values");let c=uf(i,"First parameter");return Hu(this,c.preventCancel)}[$s](i){return this.values(i)}static from(i){return tf(i)}}Object.defineProperties(Q,{from:{enumerable:!0}}),Object.defineProperties(Q.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Q.from,"from"),o(Q.prototype.cancel,"cancel"),o(Q.prototype.getReader,"getReader"),o(Q.prototype.pipeThrough,"pipeThrough"),o(Q.prototype.pipeTo,"pipeTo"),o(Q.prototype.tee,"tee"),o(Q.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Q.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Q.prototype,$s,{value:Q.prototype.values,writable:!0,configurable:!0});function gr(r,i,c,h=1,b=()=>1){let w=Object.create(Q.prototype);to(w);let T=Object.create(Ue.prototype);return ia(w,T,r,i,c,h,b),w}function ca(r,i,c){let h=Object.create(Q.prototype);to(h);let b=Object.create(Fe.prototype);return Ni(h,b,r,i,c,0,void 0),h}function to(r){r._state="readable",r._reader=void 0,r._storedError=void 0,r._disturbed=!1}function tt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readableStreamController")?!1:r instanceof Q}function rt(r){return r._reader!==void 0}function _e(r,i){if(r._disturbed=!0,r._state==="closed")return u(void 0);if(r._state==="errored")return f(r._storedError);yr(r);let c=r._reader;if(c!==void 0&&_t(c)){let b=c._readIntoRequests;c._readIntoRequests=new k,b.forEach(w=>{w._closeSteps(void 0)})}let h=r._readableStreamController[Ve](i);return E(h,e)}function yr(r){r._state="closed";let i=r._reader;if(i!==void 0&&(li(i),Ze(i))){let c=i._readRequests;i._readRequests=new k,c.forEach(h=>{h._closeSteps()})}}function la(r,i){r._state="errored",r._storedError=i;let c=r._reader;c!==void 0&&(Es(c,i),Ze(c)?hi(c,i):qi(c,i))}function vt(r){return new TypeError(`ReadableStream.prototype.${r} can only be used on a ReadableStream`)}function ua(r,i){Ce(r,i);let c=r?.highWaterMark;return vs(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:xs(c)}}let da=r=>r.byteLength;o(da,"size");class rn{constructor(i){Ne(i,1,"ByteLengthQueuingStrategy"),i=ua(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!pa(this))throw fa("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!pa(this))throw fa("size");return da}}Object.defineProperties(rn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(rn.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function fa(r){return new TypeError(`ByteLengthQueuingStrategy.prototype.${r} can only be used on a ByteLengthQueuingStrategy`)}function pa(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_byteLengthQueuingStrategyHighWaterMark")?!1:r instanceof rn}let ma=()=>1;o(ma,"size");class nn{constructor(i){Ne(i,1,"CountQueuingStrategy"),i=ua(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ga(this))throw ha("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ga(this))throw ha("size");return ma}}Object.defineProperties(nn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nn.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ha(r){return new TypeError(`CountQueuingStrategy.prototype.${r} can only be used on a CountQueuingStrategy`)}function ga(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_countQueuingStrategyHighWaterMark")?!1:r instanceof nn}function pf(r,i){Ce(r,i);let c=r?.cancel,h=r?.flush,b=r?.readableType,w=r?.start,T=r?.transform,P=r?.writableType;return{cancel:c===void 0?void 0:yf(c,r,`${i} has member 'cancel' that`),flush:h===void 0?void 0:mf(h,r,`${i} has member 'flush' that`),readableType:b,start:w===void 0?void 0:hf(w,r,`${i} has member 'start' that`),transform:T===void 0?void 0:gf(T,r,`${i} has member 'transform' that`),writableType:P}}function mf(r,i,c){return fe(r,c),h=>C(r,i,[h])}function hf(r,i,c){return fe(r,c),h=>A(r,i,[h])}function gf(r,i,c){return fe(r,c),(h,b)=>C(r,i,[h,b])}function yf(r,i,c){return fe(r,c),h=>C(r,i,[h])}class sn{constructor(i={},c={},h={}){i===void 0&&(i=null);let b=Hr(c,"Second parameter"),w=Hr(h,"Third parameter"),T=pf(i,"First parameter");if(T.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(T.writableType!==void 0)throw new RangeError("Invalid writableType specified");let P=fr(w,0),D=zr(w),I=fr(b,1),L=zr(b),N,B=p(Te=>{N=Te});bf(this,B,I,L,P,D),wf(this,T),T.start!==void 0?N(T.start(this._transformStreamController)):N(void 0)}get readable(){if(!ya(this))throw _a("readable");return this._readable}get writable(){if(!ya(this))throw _a("writable");return this._writable}}Object.defineProperties(sn.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sn.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function bf(r,i,c,h,b,w){function T(){return i}function P(B){return Rf(r,B)}function D(B){return Ef(r,B)}function I(){return vf(r)}r._writable=_d(T,P,I,D,c,h);function L(){return xf(r)}function N(B){return Cf(r,B)}r._readable=gr(T,L,N,b,w),r._backpressure=void 0,r._backpressureChangePromise=void 0,r._backpressureChangePromise_resolve=void 0,on(r,!0),r._transformStreamController=void 0}function ya(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_transformStreamController")?!1:r instanceof sn}function ba(r,i){we(r._readable._readableStreamController,i),ro(r,i)}function ro(r,i){cn(r._transformStreamController),pr(r._writable._writableStreamController,i),no(r)}function no(r){r._backpressure&&on(r,!1)}function on(r,i){r._backpressureChangePromise!==void 0&&r._backpressureChangePromise_resolve(),r._backpressureChangePromise=p(c=>{r._backpressureChangePromise_resolve=c}),r._backpressure=i}class nt{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!an(this))throw ln("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return eo(i)}enqueue(i=void 0){if(!an(this))throw ln("enqueue");Sa(this,i)}error(i=void 0){if(!an(this))throw ln("error");_f(this,i)}terminate(){if(!an(this))throw ln("terminate");Tf(this)}}Object.defineProperties(nt.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(nt.prototype.enqueue,"enqueue"),o(nt.prototype.error,"error"),o(nt.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nt.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function an(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledTransformStream")?!1:r instanceof nt}function Sf(r,i,c,h,b){i._controlledTransformStream=r,r._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=h,i._cancelAlgorithm=b,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function wf(r,i){let c=Object.create(nt.prototype),h,b,w;i.transform!==void 0?h=T=>i.transform(T,c):h=T=>{try{return Sa(c,T),u(void 0)}catch(P){return f(P)}},i.flush!==void 0?b=()=>i.flush(c):b=()=>u(void 0),i.cancel!==void 0?w=T=>i.cancel(T):w=()=>u(void 0),Sf(r,c,h,b,w)}function cn(r){r._transformAlgorithm=void 0,r._flushAlgorithm=void 0,r._cancelAlgorithm=void 0}function Sa(r,i){let c=r._controlledTransformStream,h=c._readable._readableStreamController;if(!Bt(h))throw new TypeError("Readable side is not in a state that permits enqueue");try{Ft(h,i)}catch(w){throw ro(c,w),c._readable._storedError}Yd(h)!==c._backpressure&&on(c,!0)}function _f(r,i){ba(r._controlledTransformStream,i)}function wa(r,i){let c=r._transformAlgorithm(i);return E(c,void 0,h=>{throw ba(r._controlledTransformStream,h),h})}function Tf(r){let i=r._controlledTransformStream,c=i._readable._readableStreamController;Et(c);let h=new TypeError("TransformStream terminated");ro(i,h)}function Rf(r,i){let c=r._transformStreamController;if(r._backpressure){let h=r._backpressureChangePromise;return E(h,()=>{let b=r._writable;if(b._state==="erroring")throw b._storedError;return wa(c,i)})}return wa(c,i)}function Ef(r,i){let c=r._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=r._readable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return cn(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(we(h._readableStreamController,i),so(c)),null),w=>(we(h._readableStreamController,w),Ut(c,w),null)),c._finishPromise}function vf(r){let i=r._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=r._readable;i._finishPromise=p((b,w)=>{i._finishPromise_resolve=b,i._finishPromise_reject=w});let h=i._flushAlgorithm();return cn(i),g(h,()=>(c._state==="errored"?Ut(i,c._storedError):(Et(c._readableStreamController),so(i)),null),b=>(we(c._readableStreamController,b),Ut(i,b),null)),i._finishPromise}function xf(r){return on(r,!1),r._backpressureChangePromise}function Cf(r,i){let c=r._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=r._writable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return cn(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(pr(h._writableStreamController,i),no(r),so(c)),null),w=>(pr(h._writableStreamController,w),no(r),Ut(c,w),null)),c._finishPromise}function ln(r){return new TypeError(`TransformStreamDefaultController.prototype.${r} can only be used on a TransformStreamDefaultController`)}function so(r){r._finishPromise_resolve!==void 0&&(r._finishPromise_resolve(),r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0)}function Ut(r,i){r._finishPromise_reject!==void 0&&(R(r._finishPromise),r._finishPromise_reject(i),r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0)}function _a(r){return new TypeError(`TransformStream.prototype.${r} can only be used on a TransformStream`)}n.ByteLengthQueuingStrategy=rn,n.CountQueuingStrategy=nn,n.ReadableByteStreamController=Fe,n.ReadableStream=Q,n.ReadableStreamBYOBReader=Ke,n.ReadableStreamBYOBRequest=bt,n.ReadableStreamDefaultController=Ue,n.ReadableStreamDefaultReader=Ye,n.TransformStream=sn,n.TransformStreamDefaultController=nt,n.WritableStream=et,n.WritableStreamDefaultController=Mt,n.WritableStreamDefaultWriter=Be}))});var Sl=X(()=>{if(!globalThis.ReadableStream)try{let n=Z("node:process"),{emitWarning:e}=n;try{n.emitWarning=()=>{},Object.assign(globalThis,Z("node:stream/web")),n.emitWarning=e}catch(t){throw n.emitWarning=e,t}}catch{Object.assign(globalThis,bl())}try{let{Blob:n}=Z("buffer");n&&!n.prototype.stream&&(n.prototype.stream=function(t){let s=0,o=this;return new ReadableStream({type:"bytes",async pull(a){let d=await o.slice(s,Math.min(o.size,s+65536)).arrayBuffer();s+=d.byteLength,a.enqueue(new Uint8Array(d)),s===o.size&&a.close()}})})}catch{}});async function*Do(n,e=!0){for(let t of n)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let s=t.byteOffset,o=t.byteOffset+t.byteLength;for(;s!==o;){let a=Math.min(o-s,wl),l=t.buffer.slice(s,s+a);s+=l.byteLength,yield new Uint8Array(l)}}else yield t;else{let s=0,o=t;for(;s!==o.size;){let l=await o.slice(s,Math.min(o.size,s+wl)).arrayBuffer();s+=l.byteLength,yield new Uint8Array(l)}}}var pw,wl,_l,qm,Ee,vr=G(()=>{pw=Ht(Sl(),1);wl=65536;_l=class Lo{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){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 t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let s=new TextEncoder;for(let a of e){let l;ArrayBuffer.isView(a)?l=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?l=new Uint8Array(a.slice(0)):a instanceof Lo?l=a:l=s.encode(`${a}`),this.#r+=ArrayBuffer.isView(l)?l.byteLength:l.size,this.#e.push(l)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let o=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let s of Do(this.#e,!1))t+=e.decode(s,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let s of Do(this.#e,!1))e.set(s,t),t+=s.length;return e.buffer}stream(){let e=Do(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let s=await e.next();s.done?t.close():t.enqueue(s.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,s=""){let{size:o}=this,a=e<0?Math.max(o+e,0):Math.min(e,o),l=t<0?Math.max(o+t,0):Math.min(t,o),d=Math.max(l-a,0),p=this.#e,u=[],f=0;for(let g of p){if(f>=d)break;let _=ArrayBuffer.isView(g)?g.byteLength:g.size;if(a&&_<=a)a-=_,l-=_;else{let S;ArrayBuffer.isView(g)?(S=g.subarray(a,Math.min(_,l)),f+=S.byteLength):(S=g.slice(a,Math.min(_,l)),f+=S.size),l-=_,u.push(S),a=0}}let y=new Lo([],{type:String(s).toLowerCase()});return y.#r=d,y.#e=u,y}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(_l.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});qm=_l,Ee=qm});var jm,Wm,ft,No=G(()=>{vr();jm=class extends Ee{#e=0;#t="";constructor(e,t,s={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,s),s===null&&(s={});let o=s.lastModified===void 0?Date.now():Number(s.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Ee&&/^(File)$/.test(e[Symbol.toStringTag])}},Wm=jm,ft=Wm});function El(n,e=Ee){var t=`${Tl()}${Tl()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),s=[],o=`--${t}\r
15
- Content-Disposition: form-data; name="`;return n.forEach((a,l)=>typeof a=="string"?s.push(o+Mo(l)+`"\r
13
+ `;let p=(0,Bm.parseProxyResponse)(o);o.write(`${d}\r
14
+ `);let{connect:u,buffered:f}=await p;if(e.emit("proxyConnect",u),this.emit("proxyConnect",u,e),u.statusCode===200)return e.once("socket",Um),t.secureEndpoint?(vr("Upgrading socket connection to TLS"),ul.connect({...fl(dl(t),"host","path","port"),socket:o})):o;o.destroy();let y=new Yn.Socket({writable:!1});return y.readable=!0,e.once("socket",g=>{vr("Replaying proxy buffer for failed request"),(0,Lm.default)(g.listenerCount("data")>0),g.push(f),g.push(null)}),y}};Zn.protocols=["http","https"];ye.HttpsProxyAgent=Zn;function Um(n){n.resume()}function fl(n,...e){let t={},s;for(s in n)e.includes(s)||(t[s]=n[s]);return t}});function qm(n){if(!/^data:/i.test(n))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');n=n.replace(/\r?\n/g,"");let e=n.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=n.substring(5,e).split(";"),s="",o=!1,a=t[0]||"text/plain",l=a;for(let f=1;f<t.length;f++)t[f]==="base64"?o=!0:t[f]&&(l+=`;${t[f]}`,t[f].indexOf("charset=")===0&&(s=t[f].substring(8)));!t[0]&&!s.length&&(l+=";charset=US-ASCII",s="US-ASCII");let d=o?"base64":"ascii",p=unescape(n.substring(e+1)),u=Buffer.from(p,d);return u.type=a,u.typeFull=l,u.charset=s,u}var gl,yl=G(()=>{gl=qm});var Sl=X((Xn,bl)=>{(function(n,e){typeof Xn=="object"&&typeof bl<"u"?e(Xn):typeof define=="function"&&define.amd?define(["exports"],e):(n=typeof globalThis<"u"?globalThis:n||self,e(n.WebStreamsPolyfill={}))})(Xn,(function(n){"use strict";function e(){}function t(r){return typeof r=="object"&&r!==null||typeof r=="function"}let s=e;function o(r,i){try{Object.defineProperty(r,"name",{value:i,configurable:!0})}catch{}}let a=Promise,l=Promise.prototype.then,d=Promise.reject.bind(a);function p(r){return new a(r)}function u(r){return p(i=>i(r))}function f(r){return d(r)}function y(r,i,c){return l.call(r,i,c)}function g(r,i,c){y(y(r,i,c),void 0,s)}function _(r,i){g(r,i)}function S(r,i){g(r,void 0,i)}function E(r,i,c){return y(r,i,c)}function R(r){y(r,void 0,s)}let x=r=>{if(typeof queueMicrotask=="function")x=queueMicrotask;else{let i=u(void 0);x=c=>y(i,c)}return x(r)};function A(r,i,c){if(typeof r!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(r,i,c)}function C(r,i,c){try{return u(A(r,i,c))}catch(h){return f(h)}}let v=16384;class k{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(i){let c=this._back,h=c;c._elements.length===v-1&&(h={_elements:[],_next:void 0}),c._elements.push(i),h!==c&&(this._back=h,c._next=h),++this._size}shift(){let i=this._front,c=i,h=this._cursor,b=h+1,w=i._elements,T=w[h];return b===v&&(c=i._next,b=0),--this._size,this._cursor=b,i!==c&&(this._front=c),w[h]=void 0,T}forEach(i){let c=this._cursor,h=this._front,b=h._elements;for(;(c!==b.length||h._next!==void 0)&&!(c===b.length&&(h=h._next,b=h._elements,c=0,b.length===0));)i(b[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let $=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),Ve=Symbol("[[CancelSteps]]"),cr=Symbol("[[PullSteps]]"),Ts=Symbol("[[ReleaseSteps]]");function ci(r,i){r._ownerReadableStream=i,i._reader=r,i._state==="readable"?Es(r):i._state==="closed"?Fu(r):li(r,i._storedError)}function Rs(r,i){let c=r._ownerReadableStream;return _e(c,i)}function Le(r){let i=r._ownerReadableStream;i._state==="readable"?xs(r,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Bu(r,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[Ts](),i._reader=void 0,r._ownerReadableStream=void 0}function Nr(r){return new TypeError("Cannot "+r+" a stream using a released reader")}function Es(r){r._closedPromise=p((i,c)=>{r._closedPromise_resolve=i,r._closedPromise_reject=c})}function li(r,i){Es(r),xs(r,i)}function Fu(r){Es(r),ui(r)}function xs(r,i){r._closedPromise_reject!==void 0&&(R(r._closedPromise),r._closedPromise_reject(i),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0)}function Bu(r,i){li(r,i)}function ui(r){r._closedPromise_resolve!==void 0&&(r._closedPromise_resolve(void 0),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0)}let di=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Uu=Math.trunc||function(r){return r<0?Math.ceil(r):Math.floor(r)};function qu(r){return typeof r=="object"||typeof r=="function"}function Ce(r,i){if(r!==void 0&&!qu(r))throw new TypeError(`${i} is not an object.`)}function fe(r,i){if(typeof r!="function")throw new TypeError(`${i} is not a function.`)}function ju(r){return typeof r=="object"&&r!==null||typeof r=="function"}function fi(r,i){if(!ju(r))throw new TypeError(`${i} is not an object.`)}function Ne(r,i,c){if(r===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function vs(r,i,c){if(r===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function Cs(r){return Number(r)}function pi(r){return r===0?0:r}function Wu(r){return pi(Uu(r))}function As(r,i){let h=Number.MAX_SAFE_INTEGER,b=Number(r);if(b=pi(b),!di(b))throw new TypeError(`${i} is not a finite number`);if(b=Wu(b),b<0||b>h)throw new TypeError(`${i} is outside the accepted range of 0 to ${h}, inclusive`);return!di(b)||b===0?0:b}function Ps(r,i){if(!tt(r))throw new TypeError(`${i} is not a ReadableStream.`)}function $t(r){return new Ye(r)}function mi(r,i){r._reader._readRequests.push(i)}function Is(r,i,c){let b=r._reader._readRequests.shift();c?b._closeSteps():b._chunkSteps(i)}function Mr(r){return r._reader._readRequests.length}function hi(r){let i=r._reader;return!(i===void 0||!Ze(i))}class Ye{constructor(i){if(Ne(i,1,"ReadableStreamDefaultReader"),Ps(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ci(this,i),this._readRequests=new k}get closed(){return Ze(this)?this._closedPromise:f(Fr("closed"))}cancel(i=void 0){return Ze(this)?this._ownerReadableStream===void 0?f(Nr("cancel")):Rs(this,i):f(Fr("cancel"))}read(){if(!Ze(this))return f(Fr("read"));if(this._ownerReadableStream===void 0)return f(Nr("read from"));let i,c,h=p((w,T)=>{i=w,c=T});return lr(this,{_chunkSteps:w=>i({value:w,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:w=>c(w)}),h}releaseLock(){if(!Ze(this))throw Fr("releaseLock");this._ownerReadableStream!==void 0&&zu(this)}}Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ye.prototype.cancel,"cancel"),o(Ye.prototype.read,"read"),o(Ye.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ze(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readRequests")?!1:r instanceof Ye}function lr(r,i){let c=r._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[cr](i)}function zu(r){Le(r);let i=new TypeError("Reader was released");gi(r,i)}function gi(r,i){let c=r._readRequests;r._readRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Fr(r){return new TypeError(`ReadableStreamDefaultReader.prototype.${r} can only be used on a ReadableStreamDefaultReader`)}let Hu=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class yi{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?E(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?E(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,h,b=p((T,P)=>{c=T,h=P});return lr(i,{_chunkSteps:T=>{this._ongoingPromise=void 0,x(()=>c({value:T,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),c({value:void 0,done:!0})},_errorSteps:T=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),h(T)}}),b}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let h=Rs(c,i);return Le(c),E(h,()=>({value:i,done:!0}))}return Le(c),u({value:i,done:!0})}}let bi={next(){return Si(this)?this._asyncIteratorImpl.next():f(wi("next"))},return(r){return Si(this)?this._asyncIteratorImpl.return(r):f(wi("return"))}};Object.setPrototypeOf(bi,Hu);function Gu(r,i){let c=$t(r),h=new yi(c,i),b=Object.create(bi);return b._asyncIteratorImpl=h,b}function Si(r){if(!t(r)||!Object.prototype.hasOwnProperty.call(r,"_asyncIteratorImpl"))return!1;try{return r._asyncIteratorImpl instanceof yi}catch{return!1}}function wi(r){return new TypeError(`ReadableStreamAsyncIterator.${r} can only be used on a ReadableSteamAsyncIterator`)}let _i=Number.isNaN||function(r){return r!==r};var Os,ks,$s;function ur(r){return r.slice()}function Ti(r,i,c,h,b){new Uint8Array(r).set(new Uint8Array(c,h,b),i)}let Me=r=>(typeof r.transfer=="function"?Me=i=>i.transfer():typeof structuredClone=="function"?Me=i=>structuredClone(i,{transfer:[i]}):Me=i=>i,Me(r)),Xe=r=>(typeof r.detached=="boolean"?Xe=i=>i.detached:Xe=i=>i.byteLength===0,Xe(r));function Ri(r,i,c){if(r.slice)return r.slice(i,c);let h=c-i,b=new ArrayBuffer(h);return Ti(b,0,r,i,h),b}function Br(r,i){let c=r[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function Ju(r){let i={[Symbol.iterator]:()=>r.iterator},c=(async function*(){return yield*i})(),h=c.next;return{iterator:c,nextMethod:h,done:!1}}let Ds=($s=(Os=Symbol.asyncIterator)!==null&&Os!==void 0?Os:(ks=Symbol.for)===null||ks===void 0?void 0:ks.call(Symbol,"Symbol.asyncIterator"))!==null&&$s!==void 0?$s:"@@asyncIterator";function Ei(r,i="sync",c){if(c===void 0)if(i==="async"){if(c=Br(r,Ds),c===void 0){let w=Br(r,Symbol.iterator),T=Ei(r,"sync",w);return Ju(T)}}else c=Br(r,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let h=A(c,r,[]);if(!t(h))throw new TypeError("The iterator method must return an object");let b=h.next;return{iterator:h,nextMethod:b,done:!1}}function Vu(r){let i=A(r.nextMethod,r.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function Yu(r){return!!r.done}function Zu(r){return r.value}function Xu(r){return!(typeof r!="number"||_i(r)||r<0)}function xi(r){let i=Ri(r.buffer,r.byteOffset,r.byteOffset+r.byteLength);return new Uint8Array(i)}function Ls(r){let i=r._queue.shift();return r._queueTotalSize-=i.size,r._queueTotalSize<0&&(r._queueTotalSize=0),i.value}function Ns(r,i,c){if(!Xu(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");r._queue.push({value:i,size:c}),r._queueTotalSize+=c}function Qu(r){return r._queue.peek().value}function Qe(r){r._queue=new k,r._queueTotalSize=0}function vi(r){return r===DataView}function Ku(r){return vi(r.constructor)}function ed(r){return vi(r)?1:r.BYTES_PER_ELEMENT}class bt{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ms(this))throw js("view");return this._view}respond(i){if(!Ms(this))throw js("respond");if(Ne(i,1,"respond"),i=As(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Xe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Wr(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!Ms(this))throw js("respondWithNewView");if(Ne(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))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(Xe(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");zr(this._associatedReadableByteStreamController,i)}}Object.defineProperties(bt.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(bt.prototype.respond,"respond"),o(bt.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bt.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Fe{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!St(this))throw fr("byobRequest");return qs(this)}get desiredSize(){if(!St(this))throw fr("desiredSize");return Ni(this)}close(){if(!St(this))throw fr("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);dr(this)}enqueue(i){if(!St(this))throw fr("enqueue");if(Ne(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.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 c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);jr(this,i)}error(i=void 0){if(!St(this))throw fr("error");pe(this,i)}[Ve](i){Ci(this),Qe(this);let c=this._cancelAlgorithm(i);return qr(this),c}[cr](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){Li(this,i);return}let h=this._autoAllocateChunkSize;if(h!==void 0){let b;try{b=new ArrayBuffer(h)}catch(T){i._errorSteps(T);return}let w={buffer:b,bufferByteLength:h,byteOffset:0,byteLength:h,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(w)}mi(c,i),wt(this)}[Ts](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new k,this._pendingPullIntos.push(i)}}}Object.defineProperties(Fe.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Fe.prototype.close,"close"),o(Fe.prototype.enqueue,"enqueue"),o(Fe.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fe.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function St(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledReadableByteStream")?!1:r instanceof Fe}function Ms(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_associatedReadableByteStreamController")?!1:r instanceof bt}function wt(r){if(!od(r))return;if(r._pulling){r._pullAgain=!0;return}r._pulling=!0;let c=r._pullAlgorithm();g(c,()=>(r._pulling=!1,r._pullAgain&&(r._pullAgain=!1,wt(r)),null),h=>(pe(r,h),null))}function Ci(r){Bs(r),r._pendingPullIntos=new k}function Fs(r,i){let c=!1;r._state==="closed"&&(c=!0);let h=Ai(i);i.readerType==="default"?Is(r,h,c):dd(r,h,c)}function Ai(r){let i=r.bytesFilled,c=r.elementSize;return new r.viewConstructor(r.buffer,r.byteOffset,i/c)}function Ur(r,i,c,h){r._queue.push({buffer:i,byteOffset:c,byteLength:h}),r._queueTotalSize+=h}function Pi(r,i,c,h){let b;try{b=Ri(i,c,c+h)}catch(w){throw pe(r,w),w}Ur(r,b,0,h)}function Ii(r,i){i.bytesFilled>0&&Pi(r,i.buffer,i.byteOffset,i.bytesFilled),Dt(r)}function Oi(r,i){let c=Math.min(r._queueTotalSize,i.byteLength-i.bytesFilled),h=i.bytesFilled+c,b=c,w=!1,T=h%i.elementSize,P=h-T;P>=i.minimumFill&&(b=P-i.bytesFilled,w=!0);let D=r._queue;for(;b>0;){let I=D.peek(),L=Math.min(b,I.byteLength),N=i.byteOffset+i.bytesFilled;Ti(i.buffer,N,I.buffer,I.byteOffset,L),I.byteLength===L?D.shift():(I.byteOffset+=L,I.byteLength-=L),r._queueTotalSize-=L,ki(r,L,i),b-=L}return w}function ki(r,i,c){c.bytesFilled+=i}function $i(r){r._queueTotalSize===0&&r._closeRequested?(qr(r),br(r._controlledReadableByteStream)):wt(r)}function Bs(r){r._byobRequest!==null&&(r._byobRequest._associatedReadableByteStreamController=void 0,r._byobRequest._view=null,r._byobRequest=null)}function Us(r){for(;r._pendingPullIntos.length>0;){if(r._queueTotalSize===0)return;let i=r._pendingPullIntos.peek();Oi(r,i)&&(Dt(r),Fs(r._controlledReadableByteStream,i))}}function td(r){let i=r._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(r._queueTotalSize===0)return;let c=i._readRequests.shift();Li(r,c)}}function rd(r,i,c,h){let b=r._controlledReadableByteStream,w=i.constructor,T=ed(w),{byteOffset:P,byteLength:D}=i,I=c*T,L;try{L=Me(i.buffer)}catch(B){h._errorSteps(B);return}let N={buffer:L,bufferByteLength:L.byteLength,byteOffset:P,byteLength:D,bytesFilled:0,minimumFill:I,elementSize:T,viewConstructor:w,readerType:"byob"};if(r._pendingPullIntos.length>0){r._pendingPullIntos.push(N),Bi(b,h);return}if(b._state==="closed"){let B=new w(N.buffer,N.byteOffset,0);h._closeSteps(B);return}if(r._queueTotalSize>0){if(Oi(r,N)){let B=Ai(N);$i(r),h._chunkSteps(B);return}if(r._closeRequested){let B=new TypeError("Insufficient bytes to fill elements in the given buffer");pe(r,B),h._errorSteps(B);return}}r._pendingPullIntos.push(N),Bi(b,h),wt(r)}function nd(r,i){i.readerType==="none"&&Dt(r);let c=r._controlledReadableByteStream;if(Ws(c))for(;Ui(c)>0;){let h=Dt(r);Fs(c,h)}}function sd(r,i,c){if(ki(r,i,c),c.readerType==="none"){Ii(r,c),Us(r);return}if(c.bytesFilled<c.minimumFill)return;Dt(r);let h=c.bytesFilled%c.elementSize;if(h>0){let b=c.byteOffset+c.bytesFilled;Pi(r,c.buffer,b-h,h)}c.bytesFilled-=h,Fs(r._controlledReadableByteStream,c),Us(r)}function Di(r,i){let c=r._pendingPullIntos.peek();Bs(r),r._controlledReadableByteStream._state==="closed"?nd(r,c):sd(r,i,c),wt(r)}function Dt(r){return r._pendingPullIntos.shift()}function od(r){let i=r._controlledReadableByteStream;return i._state!=="readable"||r._closeRequested||!r._started?!1:!!(hi(i)&&Mr(i)>0||Ws(i)&&Ui(i)>0||Ni(r)>0)}function qr(r){r._pullAlgorithm=void 0,r._cancelAlgorithm=void 0}function dr(r){let i=r._controlledReadableByteStream;if(!(r._closeRequested||i._state!=="readable")){if(r._queueTotalSize>0){r._closeRequested=!0;return}if(r._pendingPullIntos.length>0){let c=r._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let h=new TypeError("Insufficient bytes to fill elements in the given buffer");throw pe(r,h),h}}qr(r),br(i)}}function jr(r,i){let c=r._controlledReadableByteStream;if(r._closeRequested||c._state!=="readable")return;let{buffer:h,byteOffset:b,byteLength:w}=i;if(Xe(h))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let T=Me(h);if(r._pendingPullIntos.length>0){let P=r._pendingPullIntos.peek();if(Xe(P.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Bs(r),P.buffer=Me(P.buffer),P.readerType==="none"&&Ii(r,P)}if(hi(c))if(td(r),Mr(c)===0)Ur(r,T,b,w);else{r._pendingPullIntos.length>0&&Dt(r);let P=new Uint8Array(T,b,w);Is(c,P,!1)}else Ws(c)?(Ur(r,T,b,w),Us(r)):Ur(r,T,b,w);wt(r)}function pe(r,i){let c=r._controlledReadableByteStream;c._state==="readable"&&(Ci(r),Qe(r),qr(r),ua(c,i))}function Li(r,i){let c=r._queue.shift();r._queueTotalSize-=c.byteLength,$i(r);let h=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(h)}function qs(r){if(r._byobRequest===null&&r._pendingPullIntos.length>0){let i=r._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),h=Object.create(bt.prototype);ad(h,r,c),r._byobRequest=h}return r._byobRequest}function Ni(r){let i=r._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:r._strategyHWM-r._queueTotalSize}function Wr(r,i){let c=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=Me(c.buffer),Di(r,i)}function zr(r,i){let c=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let b=i.byteLength;c.buffer=Me(i.buffer),Di(r,b)}function Mi(r,i,c,h,b,w,T){i._controlledReadableByteStream=r,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,Qe(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,i._autoAllocateChunkSize=T,i._pendingPullIntos=new k,r._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,wt(i),null),D=>(pe(i,D),null))}function id(r,i,c){let h=Object.create(Fe.prototype),b,w,T;i.start!==void 0?b=()=>i.start(h):b=()=>{},i.pull!==void 0?w=()=>i.pull(h):w=()=>u(void 0),i.cancel!==void 0?T=D=>i.cancel(D):T=()=>u(void 0);let P=i.autoAllocateChunkSize;if(P===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Mi(r,h,b,w,T,c,P)}function ad(r,i,c){r._associatedReadableByteStreamController=i,r._view=c}function js(r){return new TypeError(`ReadableStreamBYOBRequest.prototype.${r} can only be used on a ReadableStreamBYOBRequest`)}function fr(r){return new TypeError(`ReadableByteStreamController.prototype.${r} can only be used on a ReadableByteStreamController`)}function cd(r,i){Ce(r,i);let c=r?.mode;return{mode:c===void 0?void 0:ld(c,`${i} has member 'mode' that`)}}function ld(r,i){if(r=`${r}`,r!=="byob")throw new TypeError(`${i} '${r}' is not a valid enumeration value for ReadableStreamReaderMode`);return r}function ud(r,i){var c;Ce(r,i);let h=(c=r?.min)!==null&&c!==void 0?c:1;return{min:As(h,`${i} has member 'min' that`)}}function Fi(r){return new Ke(r)}function Bi(r,i){r._reader._readIntoRequests.push(i)}function dd(r,i,c){let b=r._reader._readIntoRequests.shift();c?b._closeSteps(i):b._chunkSteps(i)}function Ui(r){return r._reader._readIntoRequests.length}function Ws(r){let i=r._reader;return!(i===void 0||!_t(i))}class Ke{constructor(i){if(Ne(i,1,"ReadableStreamBYOBReader"),Ps(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!St(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ci(this,i),this._readIntoRequests=new k}get closed(){return _t(this)?this._closedPromise:f(Hr("closed"))}cancel(i=void 0){return _t(this)?this._ownerReadableStream===void 0?f(Nr("cancel")):Rs(this,i):f(Hr("cancel"))}read(i,c={}){if(!_t(this))return f(Hr("read"));if(!ArrayBuffer.isView(i))return f(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(Xe(i.buffer))return f(new TypeError("view's buffer has been detached"));let h;try{h=ud(c,"options")}catch(I){return f(I)}let b=h.min;if(b===0)return f(new TypeError("options.min must be greater than 0"));if(Ku(i)){if(b>i.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(b>i.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(Nr("read from"));let w,T,P=p((I,L)=>{w=I,T=L});return qi(this,i,b,{_chunkSteps:I=>w({value:I,done:!1}),_closeSteps:I=>w({value:I,done:!0}),_errorSteps:I=>T(I)}),P}releaseLock(){if(!_t(this))throw Hr("releaseLock");this._ownerReadableStream!==void 0&&fd(this)}}Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ke.prototype.cancel,"cancel"),o(Ke.prototype.read,"read"),o(Ke.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function _t(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readIntoRequests")?!1:r instanceof Ke}function qi(r,i,c,h){let b=r._ownerReadableStream;b._disturbed=!0,b._state==="errored"?h._errorSteps(b._storedError):rd(b._readableStreamController,i,c,h)}function fd(r){Le(r);let i=new TypeError("Reader was released");ji(r,i)}function ji(r,i){let c=r._readIntoRequests;r._readIntoRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Hr(r){return new TypeError(`ReadableStreamBYOBReader.prototype.${r} can only be used on a ReadableStreamBYOBReader`)}function pr(r,i){let{highWaterMark:c}=r;if(c===void 0)return i;if(_i(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function Gr(r){let{size:i}=r;return i||(()=>1)}function Jr(r,i){Ce(r,i);let c=r?.highWaterMark,h=r?.size;return{highWaterMark:c===void 0?void 0:Cs(c),size:h===void 0?void 0:pd(h,`${i} has member 'size' that`)}}function pd(r,i){return fe(r,i),c=>Cs(r(c))}function md(r,i){Ce(r,i);let c=r?.abort,h=r?.close,b=r?.start,w=r?.type,T=r?.write;return{abort:c===void 0?void 0:hd(c,r,`${i} has member 'abort' that`),close:h===void 0?void 0:gd(h,r,`${i} has member 'close' that`),start:b===void 0?void 0:yd(b,r,`${i} has member 'start' that`),write:T===void 0?void 0:bd(T,r,`${i} has member 'write' that`),type:w}}function hd(r,i,c){return fe(r,c),h=>C(r,i,[h])}function gd(r,i,c){return fe(r,c),()=>C(r,i,[])}function yd(r,i,c){return fe(r,c),h=>A(r,i,[h])}function bd(r,i,c){return fe(r,c),(h,b)=>C(r,i,[h,b])}function Wi(r,i){if(!Lt(r))throw new TypeError(`${i} is not a WritableStream.`)}function Sd(r){if(typeof r!="object"||r===null)return!1;try{return typeof r.aborted=="boolean"}catch{return!1}}let wd=typeof AbortController=="function";function _d(){if(wd)return new AbortController}class et{constructor(i={},c={}){i===void 0?i=null:fi(i,"First parameter");let h=Jr(c,"Second parameter"),b=md(i,"First parameter");if(Hi(this),b.type!==void 0)throw new RangeError("Invalid type is specified");let T=Gr(h),P=pr(h,1);Ld(this,b,P,T)}get locked(){if(!Lt(this))throw Qr("locked");return Nt(this)}abort(i=void 0){return Lt(this)?Nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Vr(this,i):f(Qr("abort"))}close(){return Lt(this)?Nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):Ae(this)?f(new TypeError("Cannot close an already-closing stream")):Gi(this):f(Qr("close"))}getWriter(){if(!Lt(this))throw Qr("getWriter");return zi(this)}}Object.defineProperties(et.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(et.prototype.abort,"abort"),o(et.prototype.close,"close"),o(et.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function zi(r){return new Be(r)}function Td(r,i,c,h,b=1,w=()=>1){let T=Object.create(et.prototype);Hi(T);let P=Object.create(Mt.prototype);return Qi(T,P,r,i,c,h,b,w),T}function Hi(r){r._state="writable",r._storedError=void 0,r._writer=void 0,r._writableStreamController=void 0,r._writeRequests=new k,r._inFlightWriteRequest=void 0,r._closeRequest=void 0,r._inFlightCloseRequest=void 0,r._pendingAbortRequest=void 0,r._backpressure=!1}function Lt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_writableStreamController")?!1:r instanceof et}function Nt(r){return r._writer!==void 0}function Vr(r,i){var c;if(r._state==="closed"||r._state==="errored")return u(void 0);r._writableStreamController._abortReason=i,(c=r._writableStreamController._abortController)===null||c===void 0||c.abort(i);let h=r._state;if(h==="closed"||h==="errored")return u(void 0);if(r._pendingAbortRequest!==void 0)return r._pendingAbortRequest._promise;let b=!1;h==="erroring"&&(b=!0,i=void 0);let w=p((T,P)=>{r._pendingAbortRequest={_promise:void 0,_resolve:T,_reject:P,_reason:i,_wasAlreadyErroring:b}});return r._pendingAbortRequest._promise=w,b||Hs(r,i),w}function Gi(r){let i=r._state;if(i==="closed"||i==="errored")return f(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=p((b,w)=>{let T={_resolve:b,_reject:w};r._closeRequest=T}),h=r._writer;return h!==void 0&&r._backpressure&&i==="writable"&&Ks(h),Nd(r._writableStreamController),c}function Rd(r){return p((c,h)=>{let b={_resolve:c,_reject:h};r._writeRequests.push(b)})}function zs(r,i){if(r._state==="writable"){Hs(r,i);return}Gs(r)}function Hs(r,i){let c=r._writableStreamController;r._state="erroring",r._storedError=i;let h=r._writer;h!==void 0&&Vi(h,i),!Ad(r)&&c._started&&Gs(r)}function Gs(r){r._state="errored",r._writableStreamController[H]();let i=r._storedError;if(r._writeRequests.forEach(b=>{b._reject(i)}),r._writeRequests=new k,r._pendingAbortRequest===void 0){Yr(r);return}let c=r._pendingAbortRequest;if(r._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Yr(r);return}let h=r._writableStreamController[$](c._reason);g(h,()=>(c._resolve(),Yr(r),null),b=>(c._reject(b),Yr(r),null))}function Ed(r){r._inFlightWriteRequest._resolve(void 0),r._inFlightWriteRequest=void 0}function xd(r,i){r._inFlightWriteRequest._reject(i),r._inFlightWriteRequest=void 0,zs(r,i)}function vd(r){r._inFlightCloseRequest._resolve(void 0),r._inFlightCloseRequest=void 0,r._state==="erroring"&&(r._storedError=void 0,r._pendingAbortRequest!==void 0&&(r._pendingAbortRequest._resolve(),r._pendingAbortRequest=void 0)),r._state="closed";let c=r._writer;c!==void 0&&ra(c)}function Cd(r,i){r._inFlightCloseRequest._reject(i),r._inFlightCloseRequest=void 0,r._pendingAbortRequest!==void 0&&(r._pendingAbortRequest._reject(i),r._pendingAbortRequest=void 0),zs(r,i)}function Ae(r){return!(r._closeRequest===void 0&&r._inFlightCloseRequest===void 0)}function Ad(r){return!(r._inFlightWriteRequest===void 0&&r._inFlightCloseRequest===void 0)}function Pd(r){r._inFlightCloseRequest=r._closeRequest,r._closeRequest=void 0}function Id(r){r._inFlightWriteRequest=r._writeRequests.shift()}function Yr(r){r._closeRequest!==void 0&&(r._closeRequest._reject(r._storedError),r._closeRequest=void 0);let i=r._writer;i!==void 0&&Xs(i,r._storedError)}function Js(r,i){let c=r._writer;c!==void 0&&i!==r._backpressure&&(i?Wd(c):Ks(c)),r._backpressure=i}class Be{constructor(i){if(Ne(i,1,"WritableStreamDefaultWriter"),Wi(i,"First parameter"),Nt(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Ae(i)&&i._backpressure?en(this):na(this),Kr(this);else if(c==="erroring")Qs(this,i._storedError),Kr(this);else if(c==="closed")na(this),qd(this);else{let h=i._storedError;Qs(this,h),ta(this,h)}}get closed(){return Tt(this)?this._closedPromise:f(Rt("closed"))}get desiredSize(){if(!Tt(this))throw Rt("desiredSize");if(this._ownerWritableStream===void 0)throw hr("desiredSize");return Dd(this)}get ready(){return Tt(this)?this._readyPromise:f(Rt("ready"))}abort(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(hr("abort")):Od(this,i):f(Rt("abort"))}close(){if(!Tt(this))return f(Rt("close"));let i=this._ownerWritableStream;return i===void 0?f(hr("close")):Ae(i)?f(new TypeError("Cannot close an already-closing stream")):Ji(this)}releaseLock(){if(!Tt(this))throw Rt("releaseLock");this._ownerWritableStream!==void 0&&Yi(this)}write(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(hr("write to")):Zi(this,i):f(Rt("write"))}}Object.defineProperties(Be.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(Be.prototype.abort,"abort"),o(Be.prototype.close,"close"),o(Be.prototype.releaseLock,"releaseLock"),o(Be.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Be.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Tt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_ownerWritableStream")?!1:r instanceof Be}function Od(r,i){let c=r._ownerWritableStream;return Vr(c,i)}function Ji(r){let i=r._ownerWritableStream;return Gi(i)}function kd(r){let i=r._ownerWritableStream,c=i._state;return Ae(i)||c==="closed"?u(void 0):c==="errored"?f(i._storedError):Ji(r)}function $d(r,i){r._closedPromiseState==="pending"?Xs(r,i):jd(r,i)}function Vi(r,i){r._readyPromiseState==="pending"?sa(r,i):zd(r,i)}function Dd(r){let i=r._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:Ki(i._writableStreamController)}function Yi(r){let i=r._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Vi(r,c),$d(r,c),i._writer=void 0,r._ownerWritableStream=void 0}function Zi(r,i){let c=r._ownerWritableStream,h=c._writableStreamController,b=Md(h,i);if(c!==r._ownerWritableStream)return f(hr("write to"));let w=c._state;if(w==="errored")return f(c._storedError);if(Ae(c)||w==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(w==="erroring")return f(c._storedError);let T=Rd(c);return Fd(h,i,b),T}let Xi={};class Mt{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Vs(this))throw Zs("abortReason");return this._abortReason}get signal(){if(!Vs(this))throw Zs("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!Vs(this))throw Zs("error");this._controlledWritableStream._state==="writable"&&ea(this,i)}[$](i){let c=this._abortAlgorithm(i);return Zr(this),c}[H](){Qe(this)}}Object.defineProperties(Mt.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Vs(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledWritableStream")?!1:r instanceof Mt}function Qi(r,i,c,h,b,w,T,P){i._controlledWritableStream=r,r._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._abortReason=void 0,i._abortController=_d(),i._started=!1,i._strategySizeAlgorithm=P,i._strategyHWM=T,i._writeAlgorithm=h,i._closeAlgorithm=b,i._abortAlgorithm=w;let D=Ys(i);Js(r,D);let I=c(),L=u(I);g(L,()=>(i._started=!0,Xr(i),null),N=>(i._started=!0,zs(r,N),null))}function Ld(r,i,c,h){let b=Object.create(Mt.prototype),w,T,P,D;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.write!==void 0?T=I=>i.write(I,b):T=()=>u(void 0),i.close!==void 0?P=()=>i.close():P=()=>u(void 0),i.abort!==void 0?D=I=>i.abort(I):D=()=>u(void 0),Qi(r,b,w,T,P,D,c,h)}function Zr(r){r._writeAlgorithm=void 0,r._closeAlgorithm=void 0,r._abortAlgorithm=void 0,r._strategySizeAlgorithm=void 0}function Nd(r){Ns(r,Xi,0),Xr(r)}function Md(r,i){try{return r._strategySizeAlgorithm(i)}catch(c){return mr(r,c),1}}function Ki(r){return r._strategyHWM-r._queueTotalSize}function Fd(r,i,c){try{Ns(r,i,c)}catch(b){mr(r,b);return}let h=r._controlledWritableStream;if(!Ae(h)&&h._state==="writable"){let b=Ys(r);Js(h,b)}Xr(r)}function Xr(r){let i=r._controlledWritableStream;if(!r._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){Gs(i);return}if(r._queue.length===0)return;let h=Qu(r);h===Xi?Bd(r):Ud(r,h)}function mr(r,i){r._controlledWritableStream._state==="writable"&&ea(r,i)}function Bd(r){let i=r._controlledWritableStream;Pd(i),Ls(r);let c=r._closeAlgorithm();Zr(r),g(c,()=>(vd(i),null),h=>(Cd(i,h),null))}function Ud(r,i){let c=r._controlledWritableStream;Id(c);let h=r._writeAlgorithm(i);g(h,()=>{Ed(c);let b=c._state;if(Ls(r),!Ae(c)&&b==="writable"){let w=Ys(r);Js(c,w)}return Xr(r),null},b=>(c._state==="writable"&&Zr(r),xd(c,b),null))}function Ys(r){return Ki(r)<=0}function ea(r,i){let c=r._controlledWritableStream;Zr(r),Hs(c,i)}function Qr(r){return new TypeError(`WritableStream.prototype.${r} can only be used on a WritableStream`)}function Zs(r){return new TypeError(`WritableStreamDefaultController.prototype.${r} can only be used on a WritableStreamDefaultController`)}function Rt(r){return new TypeError(`WritableStreamDefaultWriter.prototype.${r} can only be used on a WritableStreamDefaultWriter`)}function hr(r){return new TypeError("Cannot "+r+" a stream using a released writer")}function Kr(r){r._closedPromise=p((i,c)=>{r._closedPromise_resolve=i,r._closedPromise_reject=c,r._closedPromiseState="pending"})}function ta(r,i){Kr(r),Xs(r,i)}function qd(r){Kr(r),ra(r)}function Xs(r,i){r._closedPromise_reject!==void 0&&(R(r._closedPromise),r._closedPromise_reject(i),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0,r._closedPromiseState="rejected")}function jd(r,i){ta(r,i)}function ra(r){r._closedPromise_resolve!==void 0&&(r._closedPromise_resolve(void 0),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0,r._closedPromiseState="resolved")}function en(r){r._readyPromise=p((i,c)=>{r._readyPromise_resolve=i,r._readyPromise_reject=c}),r._readyPromiseState="pending"}function Qs(r,i){en(r),sa(r,i)}function na(r){en(r),Ks(r)}function sa(r,i){r._readyPromise_reject!==void 0&&(R(r._readyPromise),r._readyPromise_reject(i),r._readyPromise_resolve=void 0,r._readyPromise_reject=void 0,r._readyPromiseState="rejected")}function Wd(r){en(r)}function zd(r,i){Qs(r,i)}function Ks(r){r._readyPromise_resolve!==void 0&&(r._readyPromise_resolve(void 0),r._readyPromise_resolve=void 0,r._readyPromise_reject=void 0,r._readyPromiseState="fulfilled")}function Hd(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let eo=Hd();function Gd(r){if(!(typeof r=="function"||typeof r=="object")||r.name!=="DOMException")return!1;try{return new r,!0}catch{return!1}}function Jd(){let r=eo?.DOMException;return Gd(r)?r:void 0}function Vd(){let r=function(c,h){this.message=c||"",this.name=h||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(r,"DOMException"),r.prototype=Object.create(Error.prototype),Object.defineProperty(r.prototype,"constructor",{value:r,writable:!0,configurable:!0}),r}let Yd=Jd()||Vd();function oa(r,i,c,h,b,w){let T=$t(r),P=zi(i);r._disturbed=!0;let D=!1,I=u(void 0);return p((L,N)=>{let B;if(w!==void 0){if(B=()=>{let O=w.reason!==void 0?w.reason:new Yd("Aborted","AbortError"),M=[];h||M.push(()=>i._state==="writable"?Vr(i,O):u(void 0)),b||M.push(()=>r._state==="readable"?_e(r,O):u(void 0)),re(()=>Promise.all(M.map(q=>q())),!0,O)},w.aborted){B();return}w.addEventListener("abort",B)}function Te(){return p((O,M)=>{function q(ae){ae?O():y(qt(),q,M)}q(!1)})}function qt(){return D?u(!0):y(P._readyPromise,()=>p((O,M)=>{lr(T,{_chunkSteps:q=>{I=y(Zi(P,q),void 0,e),O(!1)},_closeSteps:()=>O(!0),_errorSteps:M})}))}if(qe(r,T._closedPromise,O=>(h?me(!0,O):re(()=>Vr(i,O),!0,O),null)),qe(i,P._closedPromise,O=>(b?me(!0,O):re(()=>_e(r,O),!0,O),null)),ee(r,T._closedPromise,()=>(c?me():re(()=>kd(P)),null)),Ae(i)||i._state==="closed"){let O=new TypeError("the destination writable stream closed before all data could be piped to it");b?me(!0,O):re(()=>_e(r,O),!0,O)}R(Te());function st(){let O=I;return y(I,()=>O!==I?st():void 0)}function qe(O,M,q){O._state==="errored"?q(O._storedError):S(M,q)}function ee(O,M,q){O._state==="closed"?q():_(M,q)}function re(O,M,q){if(D)return;D=!0,i._state==="writable"&&!Ae(i)?_(st(),ae):ae();function ae(){return g(O(),()=>je(M,q),jt=>je(!0,jt)),null}}function me(O,M){D||(D=!0,i._state==="writable"&&!Ae(i)?_(st(),()=>je(O,M)):je(O,M))}function je(O,M){return Yi(P),Le(T),w!==void 0&&w.removeEventListener("abort",B),O?N(M):L(void 0),null}})}class Ue{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!tn(this))throw nn("desiredSize");return to(this)}close(){if(!tn(this))throw nn("close");if(!Bt(this))throw new TypeError("The stream is not in a state that permits close");Et(this)}enqueue(i=void 0){if(!tn(this))throw nn("enqueue");if(!Bt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Ft(this,i)}error(i=void 0){if(!tn(this))throw nn("error");we(this,i)}[Ve](i){Qe(this);let c=this._cancelAlgorithm(i);return rn(this),c}[cr](i){let c=this._controlledReadableStream;if(this._queue.length>0){let h=Ls(this);this._closeRequested&&this._queue.length===0?(rn(this),br(c)):gr(this),i._chunkSteps(h)}else mi(c,i),gr(this)}[Ts](){}}Object.defineProperties(Ue.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Ue.prototype.close,"close"),o(Ue.prototype.enqueue,"enqueue"),o(Ue.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ue.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function tn(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledReadableStream")?!1:r instanceof Ue}function gr(r){if(!ia(r))return;if(r._pulling){r._pullAgain=!0;return}r._pulling=!0;let c=r._pullAlgorithm();g(c,()=>(r._pulling=!1,r._pullAgain&&(r._pullAgain=!1,gr(r)),null),h=>(we(r,h),null))}function ia(r){let i=r._controlledReadableStream;return!Bt(r)||!r._started?!1:!!(rt(i)&&Mr(i)>0||to(r)>0)}function rn(r){r._pullAlgorithm=void 0,r._cancelAlgorithm=void 0,r._strategySizeAlgorithm=void 0}function Et(r){if(!Bt(r))return;let i=r._controlledReadableStream;r._closeRequested=!0,r._queue.length===0&&(rn(r),br(i))}function Ft(r,i){if(!Bt(r))return;let c=r._controlledReadableStream;if(rt(c)&&Mr(c)>0)Is(c,i,!1);else{let h;try{h=r._strategySizeAlgorithm(i)}catch(b){throw we(r,b),b}try{Ns(r,i,h)}catch(b){throw we(r,b),b}}gr(r)}function we(r,i){let c=r._controlledReadableStream;c._state==="readable"&&(Qe(r),rn(r),ua(c,i))}function to(r){let i=r._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:r._strategyHWM-r._queueTotalSize}function Zd(r){return!ia(r)}function Bt(r){let i=r._controlledReadableStream._state;return!r._closeRequested&&i==="readable"}function aa(r,i,c,h,b,w,T){i._controlledReadableStream=r,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=T,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,r._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,gr(i),null),D=>(we(i,D),null))}function Xd(r,i,c,h){let b=Object.create(Ue.prototype),w,T,P;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.pull!==void 0?T=()=>i.pull(b):T=()=>u(void 0),i.cancel!==void 0?P=D=>i.cancel(D):P=()=>u(void 0),aa(r,b,w,T,P,c,h)}function nn(r){return new TypeError(`ReadableStreamDefaultController.prototype.${r} can only be used on a ReadableStreamDefaultController`)}function Qd(r,i){return St(r._readableStreamController)?ef(r):Kd(r)}function Kd(r,i){let c=$t(r),h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(ee=>{N=ee});function Te(){return h?(b=!0,u(void 0)):(h=!0,lr(c,{_chunkSteps:re=>{x(()=>{b=!1;let me=re,je=re;w||Ft(I._readableStreamController,me),T||Ft(L._readableStreamController,je),h=!1,b&&Te()})},_closeSteps:()=>{h=!1,w||Et(I._readableStreamController),T||Et(L._readableStreamController),(!w||!T)&&N(void 0)},_errorSteps:()=>{h=!1}}),u(void 0))}function qt(ee){if(w=!0,P=ee,T){let re=ur([P,D]),me=_e(r,re);N(me)}return B}function st(ee){if(T=!0,D=ee,w){let re=ur([P,D]),me=_e(r,re);N(me)}return B}function qe(){}return I=yr(qe,Te,qt),L=yr(qe,Te,st),S(c._closedPromise,ee=>(we(I._readableStreamController,ee),we(L._readableStreamController,ee),(!w||!T)&&N(void 0),null)),[I,L]}function ef(r){let i=$t(r),c=!1,h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(O=>{N=O});function Te(O){S(O._closedPromise,M=>(O!==i||(pe(I._readableStreamController,M),pe(L._readableStreamController,M),(!w||!T)&&N(void 0)),null))}function qt(){_t(i)&&(Le(i),i=$t(r),Te(i)),lr(i,{_chunkSteps:M=>{x(()=>{h=!1,b=!1;let q=M,ae=M;if(!w&&!T)try{ae=xi(M)}catch(jt){pe(I._readableStreamController,jt),pe(L._readableStreamController,jt),N(_e(r,jt));return}w||jr(I._readableStreamController,q),T||jr(L._readableStreamController,ae),c=!1,h?qe():b&&ee()})},_closeSteps:()=>{c=!1,w||dr(I._readableStreamController),T||dr(L._readableStreamController),I._readableStreamController._pendingPullIntos.length>0&&Wr(I._readableStreamController,0),L._readableStreamController._pendingPullIntos.length>0&&Wr(L._readableStreamController,0),(!w||!T)&&N(void 0)},_errorSteps:()=>{c=!1}})}function st(O,M){Ze(i)&&(Le(i),i=Fi(r),Te(i));let q=M?L:I,ae=M?I:L;qi(i,O,1,{_chunkSteps:Wt=>{x(()=>{h=!1,b=!1;let zt=M?T:w;if(M?w:T)zt||zr(q._readableStreamController,Wt);else{let Ra;try{Ra=xi(Wt)}catch(io){pe(q._readableStreamController,io),pe(ae._readableStreamController,io),N(_e(r,io));return}zt||zr(q._readableStreamController,Wt),jr(ae._readableStreamController,Ra)}c=!1,h?qe():b&&ee()})},_closeSteps:Wt=>{c=!1;let zt=M?T:w,fn=M?w:T;zt||dr(q._readableStreamController),fn||dr(ae._readableStreamController),Wt!==void 0&&(zt||zr(q._readableStreamController,Wt),!fn&&ae._readableStreamController._pendingPullIntos.length>0&&Wr(ae._readableStreamController,0)),(!zt||!fn)&&N(void 0)},_errorSteps:()=>{c=!1}})}function qe(){if(c)return h=!0,u(void 0);c=!0;let O=qs(I._readableStreamController);return O===null?qt():st(O._view,!1),u(void 0)}function ee(){if(c)return b=!0,u(void 0);c=!0;let O=qs(L._readableStreamController);return O===null?qt():st(O._view,!0),u(void 0)}function re(O){if(w=!0,P=O,T){let M=ur([P,D]),q=_e(r,M);N(q)}return B}function me(O){if(T=!0,D=O,w){let M=ur([P,D]),q=_e(r,M);N(q)}return B}function je(){}return I=la(je,qe,re),L=la(je,ee,me),Te(i),[I,L]}function tf(r){return t(r)&&typeof r.getReader<"u"}function rf(r){return tf(r)?sf(r.getReader()):nf(r)}function nf(r){let i,c=Ei(r,"async"),h=e;function b(){let T;try{T=Vu(c)}catch(D){return f(D)}let P=u(T);return E(P,D=>{if(!t(D))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Yu(D))Et(i._readableStreamController);else{let L=Zu(D);Ft(i._readableStreamController,L)}})}function w(T){let P=c.iterator,D;try{D=Br(P,"return")}catch(N){return f(N)}if(D===void 0)return u(void 0);let I;try{I=A(D,P,[T])}catch(N){return f(N)}let L=u(I);return E(L,N=>{if(!t(N))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=yr(h,b,w,0),i}function sf(r){let i,c=e;function h(){let w;try{w=r.read()}catch(T){return f(T)}return E(w,T=>{if(!t(T))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(T.done)Et(i._readableStreamController);else{let P=T.value;Ft(i._readableStreamController,P)}})}function b(w){try{return u(r.cancel(w))}catch(T){return f(T)}}return i=yr(c,h,b,0),i}function of(r,i){Ce(r,i);let c=r,h=c?.autoAllocateChunkSize,b=c?.cancel,w=c?.pull,T=c?.start,P=c?.type;return{autoAllocateChunkSize:h===void 0?void 0:As(h,`${i} has member 'autoAllocateChunkSize' that`),cancel:b===void 0?void 0:af(b,c,`${i} has member 'cancel' that`),pull:w===void 0?void 0:cf(w,c,`${i} has member 'pull' that`),start:T===void 0?void 0:lf(T,c,`${i} has member 'start' that`),type:P===void 0?void 0:uf(P,`${i} has member 'type' that`)}}function af(r,i,c){return fe(r,c),h=>C(r,i,[h])}function cf(r,i,c){return fe(r,c),h=>C(r,i,[h])}function lf(r,i,c){return fe(r,c),h=>A(r,i,[h])}function uf(r,i){if(r=`${r}`,r!=="bytes")throw new TypeError(`${i} '${r}' is not a valid enumeration value for ReadableStreamType`);return r}function df(r,i){return Ce(r,i),{preventCancel:!!r?.preventCancel}}function ca(r,i){Ce(r,i);let c=r?.preventAbort,h=r?.preventCancel,b=r?.preventClose,w=r?.signal;return w!==void 0&&ff(w,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!h,preventClose:!!b,signal:w}}function ff(r,i){if(!Sd(r))throw new TypeError(`${i} is not an AbortSignal.`)}function pf(r,i){Ce(r,i);let c=r?.readable;vs(c,"readable","ReadableWritablePair"),Ps(c,`${i} has member 'readable' that`);let h=r?.writable;return vs(h,"writable","ReadableWritablePair"),Wi(h,`${i} has member 'writable' that`),{readable:c,writable:h}}class Q{constructor(i={},c={}){i===void 0?i=null:fi(i,"First parameter");let h=Jr(c,"Second parameter"),b=of(i,"First parameter");if(ro(this),b.type==="bytes"){if(h.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let w=pr(h,0);id(this,b,w)}else{let w=Gr(h),T=pr(h,1);Xd(this,b,T,w)}}get locked(){if(!tt(this))throw xt("locked");return rt(this)}cancel(i=void 0){return tt(this)?rt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):_e(this,i):f(xt("cancel"))}getReader(i=void 0){if(!tt(this))throw xt("getReader");return cd(i,"First parameter").mode===void 0?$t(this):Fi(this)}pipeThrough(i,c={}){if(!tt(this))throw xt("pipeThrough");Ne(i,1,"pipeThrough");let h=pf(i,"First parameter"),b=ca(c,"Second parameter");if(rt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Nt(h.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let w=oa(this,h.writable,b.preventClose,b.preventAbort,b.preventCancel,b.signal);return R(w),h.readable}pipeTo(i,c={}){if(!tt(this))return f(xt("pipeTo"));if(i===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Lt(i))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let h;try{h=ca(c,"Second parameter")}catch(b){return f(b)}return rt(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Nt(i)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):oa(this,i,h.preventClose,h.preventAbort,h.preventCancel,h.signal)}tee(){if(!tt(this))throw xt("tee");let i=Qd(this);return ur(i)}values(i=void 0){if(!tt(this))throw xt("values");let c=df(i,"First parameter");return Gu(this,c.preventCancel)}[Ds](i){return this.values(i)}static from(i){return rf(i)}}Object.defineProperties(Q,{from:{enumerable:!0}}),Object.defineProperties(Q.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Q.from,"from"),o(Q.prototype.cancel,"cancel"),o(Q.prototype.getReader,"getReader"),o(Q.prototype.pipeThrough,"pipeThrough"),o(Q.prototype.pipeTo,"pipeTo"),o(Q.prototype.tee,"tee"),o(Q.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Q.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Q.prototype,Ds,{value:Q.prototype.values,writable:!0,configurable:!0});function yr(r,i,c,h=1,b=()=>1){let w=Object.create(Q.prototype);ro(w);let T=Object.create(Ue.prototype);return aa(w,T,r,i,c,h,b),w}function la(r,i,c){let h=Object.create(Q.prototype);ro(h);let b=Object.create(Fe.prototype);return Mi(h,b,r,i,c,0,void 0),h}function ro(r){r._state="readable",r._reader=void 0,r._storedError=void 0,r._disturbed=!1}function tt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readableStreamController")?!1:r instanceof Q}function rt(r){return r._reader!==void 0}function _e(r,i){if(r._disturbed=!0,r._state==="closed")return u(void 0);if(r._state==="errored")return f(r._storedError);br(r);let c=r._reader;if(c!==void 0&&_t(c)){let b=c._readIntoRequests;c._readIntoRequests=new k,b.forEach(w=>{w._closeSteps(void 0)})}let h=r._readableStreamController[Ve](i);return E(h,e)}function br(r){r._state="closed";let i=r._reader;if(i!==void 0&&(ui(i),Ze(i))){let c=i._readRequests;i._readRequests=new k,c.forEach(h=>{h._closeSteps()})}}function ua(r,i){r._state="errored",r._storedError=i;let c=r._reader;c!==void 0&&(xs(c,i),Ze(c)?gi(c,i):ji(c,i))}function xt(r){return new TypeError(`ReadableStream.prototype.${r} can only be used on a ReadableStream`)}function da(r,i){Ce(r,i);let c=r?.highWaterMark;return vs(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Cs(c)}}let fa=r=>r.byteLength;o(fa,"size");class sn{constructor(i){Ne(i,1,"ByteLengthQueuingStrategy"),i=da(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ma(this))throw pa("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!ma(this))throw pa("size");return fa}}Object.defineProperties(sn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sn.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function pa(r){return new TypeError(`ByteLengthQueuingStrategy.prototype.${r} can only be used on a ByteLengthQueuingStrategy`)}function ma(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_byteLengthQueuingStrategyHighWaterMark")?!1:r instanceof sn}let ha=()=>1;o(ha,"size");class on{constructor(i){Ne(i,1,"CountQueuingStrategy"),i=da(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ya(this))throw ga("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ya(this))throw ga("size");return ha}}Object.defineProperties(on.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(on.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ga(r){return new TypeError(`CountQueuingStrategy.prototype.${r} can only be used on a CountQueuingStrategy`)}function ya(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_countQueuingStrategyHighWaterMark")?!1:r instanceof on}function mf(r,i){Ce(r,i);let c=r?.cancel,h=r?.flush,b=r?.readableType,w=r?.start,T=r?.transform,P=r?.writableType;return{cancel:c===void 0?void 0:bf(c,r,`${i} has member 'cancel' that`),flush:h===void 0?void 0:hf(h,r,`${i} has member 'flush' that`),readableType:b,start:w===void 0?void 0:gf(w,r,`${i} has member 'start' that`),transform:T===void 0?void 0:yf(T,r,`${i} has member 'transform' that`),writableType:P}}function hf(r,i,c){return fe(r,c),h=>C(r,i,[h])}function gf(r,i,c){return fe(r,c),h=>A(r,i,[h])}function yf(r,i,c){return fe(r,c),(h,b)=>C(r,i,[h,b])}function bf(r,i,c){return fe(r,c),h=>C(r,i,[h])}class an{constructor(i={},c={},h={}){i===void 0&&(i=null);let b=Jr(c,"Second parameter"),w=Jr(h,"Third parameter"),T=mf(i,"First parameter");if(T.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(T.writableType!==void 0)throw new RangeError("Invalid writableType specified");let P=pr(w,0),D=Gr(w),I=pr(b,1),L=Gr(b),N,B=p(Te=>{N=Te});Sf(this,B,I,L,P,D),_f(this,T),T.start!==void 0?N(T.start(this._transformStreamController)):N(void 0)}get readable(){if(!ba(this))throw Ta("readable");return this._readable}get writable(){if(!ba(this))throw Ta("writable");return this._writable}}Object.defineProperties(an.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(an.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Sf(r,i,c,h,b,w){function T(){return i}function P(B){return Ef(r,B)}function D(B){return xf(r,B)}function I(){return vf(r)}r._writable=Td(T,P,I,D,c,h);function L(){return Cf(r)}function N(B){return Af(r,B)}r._readable=yr(T,L,N,b,w),r._backpressure=void 0,r._backpressureChangePromise=void 0,r._backpressureChangePromise_resolve=void 0,cn(r,!0),r._transformStreamController=void 0}function ba(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_transformStreamController")?!1:r instanceof an}function Sa(r,i){we(r._readable._readableStreamController,i),no(r,i)}function no(r,i){un(r._transformStreamController),mr(r._writable._writableStreamController,i),so(r)}function so(r){r._backpressure&&cn(r,!1)}function cn(r,i){r._backpressureChangePromise!==void 0&&r._backpressureChangePromise_resolve(),r._backpressureChangePromise=p(c=>{r._backpressureChangePromise_resolve=c}),r._backpressure=i}class nt{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ln(this))throw dn("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return to(i)}enqueue(i=void 0){if(!ln(this))throw dn("enqueue");wa(this,i)}error(i=void 0){if(!ln(this))throw dn("error");Tf(this,i)}terminate(){if(!ln(this))throw dn("terminate");Rf(this)}}Object.defineProperties(nt.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(nt.prototype.enqueue,"enqueue"),o(nt.prototype.error,"error"),o(nt.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nt.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ln(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledTransformStream")?!1:r instanceof nt}function wf(r,i,c,h,b){i._controlledTransformStream=r,r._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=h,i._cancelAlgorithm=b,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function _f(r,i){let c=Object.create(nt.prototype),h,b,w;i.transform!==void 0?h=T=>i.transform(T,c):h=T=>{try{return wa(c,T),u(void 0)}catch(P){return f(P)}},i.flush!==void 0?b=()=>i.flush(c):b=()=>u(void 0),i.cancel!==void 0?w=T=>i.cancel(T):w=()=>u(void 0),wf(r,c,h,b,w)}function un(r){r._transformAlgorithm=void 0,r._flushAlgorithm=void 0,r._cancelAlgorithm=void 0}function wa(r,i){let c=r._controlledTransformStream,h=c._readable._readableStreamController;if(!Bt(h))throw new TypeError("Readable side is not in a state that permits enqueue");try{Ft(h,i)}catch(w){throw no(c,w),c._readable._storedError}Zd(h)!==c._backpressure&&cn(c,!0)}function Tf(r,i){Sa(r._controlledTransformStream,i)}function _a(r,i){let c=r._transformAlgorithm(i);return E(c,void 0,h=>{throw Sa(r._controlledTransformStream,h),h})}function Rf(r){let i=r._controlledTransformStream,c=i._readable._readableStreamController;Et(c);let h=new TypeError("TransformStream terminated");no(i,h)}function Ef(r,i){let c=r._transformStreamController;if(r._backpressure){let h=r._backpressureChangePromise;return E(h,()=>{let b=r._writable;if(b._state==="erroring")throw b._storedError;return _a(c,i)})}return _a(c,i)}function xf(r,i){let c=r._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=r._readable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return un(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(we(h._readableStreamController,i),oo(c)),null),w=>(we(h._readableStreamController,w),Ut(c,w),null)),c._finishPromise}function vf(r){let i=r._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=r._readable;i._finishPromise=p((b,w)=>{i._finishPromise_resolve=b,i._finishPromise_reject=w});let h=i._flushAlgorithm();return un(i),g(h,()=>(c._state==="errored"?Ut(i,c._storedError):(Et(c._readableStreamController),oo(i)),null),b=>(we(c._readableStreamController,b),Ut(i,b),null)),i._finishPromise}function Cf(r){return cn(r,!1),r._backpressureChangePromise}function Af(r,i){let c=r._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=r._writable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return un(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(mr(h._writableStreamController,i),so(r),oo(c)),null),w=>(mr(h._writableStreamController,w),so(r),Ut(c,w),null)),c._finishPromise}function dn(r){return new TypeError(`TransformStreamDefaultController.prototype.${r} can only be used on a TransformStreamDefaultController`)}function oo(r){r._finishPromise_resolve!==void 0&&(r._finishPromise_resolve(),r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0)}function Ut(r,i){r._finishPromise_reject!==void 0&&(R(r._finishPromise),r._finishPromise_reject(i),r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0)}function Ta(r){return new TypeError(`TransformStream.prototype.${r} can only be used on a TransformStream`)}n.ByteLengthQueuingStrategy=sn,n.CountQueuingStrategy=on,n.ReadableByteStreamController=Fe,n.ReadableStream=Q,n.ReadableStreamBYOBReader=Ke,n.ReadableStreamBYOBRequest=bt,n.ReadableStreamDefaultController=Ue,n.ReadableStreamDefaultReader=Ye,n.TransformStream=an,n.TransformStreamDefaultController=nt,n.WritableStream=et,n.WritableStreamDefaultController=Mt,n.WritableStreamDefaultWriter=Be}))});var wl=X(()=>{if(!globalThis.ReadableStream)try{let n=Z("node:process"),{emitWarning:e}=n;try{n.emitWarning=()=>{},Object.assign(globalThis,Z("node:stream/web")),n.emitWarning=e}catch(t){throw n.emitWarning=e,t}}catch{Object.assign(globalThis,Sl())}try{let{Blob:n}=Z("buffer");n&&!n.prototype.stream&&(n.prototype.stream=function(t){let s=0,o=this;return new ReadableStream({type:"bytes",async pull(a){let d=await o.slice(s,Math.min(o.size,s+65536)).arrayBuffer();s+=d.byteLength,a.enqueue(new Uint8Array(d)),s===o.size&&a.close()}})})}catch{}});async function*Lo(n,e=!0){for(let t of n)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let s=t.byteOffset,o=t.byteOffset+t.byteLength;for(;s!==o;){let a=Math.min(o-s,_l),l=t.buffer.slice(s,s+a);s+=l.byteLength,yield new Uint8Array(l)}}else yield t;else{let s=0,o=t;for(;s!==o.size;){let l=await o.slice(s,Math.min(o.size,s+_l)).arrayBuffer();s+=l.byteLength,yield new Uint8Array(l)}}}var hw,_l,Tl,jm,Ee,Cr=G(()=>{hw=Ht(wl(),1);_l=65536;Tl=class No{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){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 t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let s=new TextEncoder;for(let a of e){let l;ArrayBuffer.isView(a)?l=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?l=new Uint8Array(a.slice(0)):a instanceof No?l=a:l=s.encode(`${a}`),this.#r+=ArrayBuffer.isView(l)?l.byteLength:l.size,this.#e.push(l)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let o=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let s of Lo(this.#e,!1))t+=e.decode(s,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let s of Lo(this.#e,!1))e.set(s,t),t+=s.length;return e.buffer}stream(){let e=Lo(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let s=await e.next();s.done?t.close():t.enqueue(s.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,s=""){let{size:o}=this,a=e<0?Math.max(o+e,0):Math.min(e,o),l=t<0?Math.max(o+t,0):Math.min(t,o),d=Math.max(l-a,0),p=this.#e,u=[],f=0;for(let g of p){if(f>=d)break;let _=ArrayBuffer.isView(g)?g.byteLength:g.size;if(a&&_<=a)a-=_,l-=_;else{let S;ArrayBuffer.isView(g)?(S=g.subarray(a,Math.min(_,l)),f+=S.byteLength):(S=g.slice(a,Math.min(_,l)),f+=S.size),l-=_,u.push(S),a=0}}let y=new No([],{type:String(s).toLowerCase()});return y.#r=d,y.#e=u,y}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(Tl.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});jm=Tl,Ee=jm});var Wm,zm,ft,Mo=G(()=>{Cr();Wm=class extends Ee{#e=0;#t="";constructor(e,t,s={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,s),s===null&&(s={});let o=s.lastModified===void 0?Date.now():Number(s.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Ee&&/^(File)$/.test(e[Symbol.toStringTag])}},zm=Wm,ft=zm});function xl(n,e=Ee){var t=`${Rl()}${Rl()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),s=[],o=`--${t}\r
15
+ Content-Disposition: form-data; name="`;return n.forEach((a,l)=>typeof a=="string"?s.push(o+Fo(l)+`"\r
16
16
  \r
17
17
  ${a.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
18
18
  `)}\r
19
- `):s.push(o+Mo(l)+`"; filename="${Mo(a.name,1)}"\r
19
+ `):s.push(o+Fo(l)+`"; filename="${Fo(a.name,1)}"\r
20
20
  Content-Type: ${a.type||"application/octet-stream"}\r
21
21
  \r
22
22
  `,a,`\r
23
- `)),s.push(`--${t}--`),new e(s,{type:"multipart/form-data; boundary="+t})}var xr,zm,Hm,Tl,Gm,Rl,Mo,Pt,pt,Xn=G(()=>{vr();No();({toStringTag:xr,iterator:zm,hasInstance:Hm}=Symbol),Tl=Math.random,Gm="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Rl=(n,e,t)=>(n+="",/^(Blob|File)$/.test(e&&e[xr])?[(t=t!==void 0?t+"":e[xr]=="File"?e.name:"blob",n),e.name!==t||e[xr]=="blob"?new ft([e],t,e):e]:[n,e+""]),Mo=(n,e)=>(e?n:n.replace(/\r?\n|\r/g,`\r
24
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Pt=(n,e,t)=>{if(e.length<t)throw new TypeError(`Failed to execute '${n}' on 'FormData': ${t} arguments required, but only ${e.length} present.`)},pt=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[xr](){return"FormData"}[zm](){return this.entries()}static[Hm](e){return e&&typeof e=="object"&&e[xr]==="FormData"&&!Gm.some(t=>typeof e[t]!="function")}append(...e){Pt("append",arguments,2),this.#e.push(Rl(...e))}delete(e){Pt("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Pt("get",arguments,1),e+="";for(var t=this.#e,s=t.length,o=0;o<s;o++)if(t[o][0]===e)return t[o][1];return null}getAll(e,t){return Pt("getAll",arguments,1),t=[],e+="",this.#e.forEach(s=>s[0]===e&&t.push(s[1])),t}has(e){return Pt("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Pt("forEach",arguments,1);for(var[s,o]of this)e.call(t,o,s,this)}set(...e){Pt("set",arguments,2);var t=[],s=!0;e=Rl(...e),this.#e.forEach(o=>{o[0]===e[0]?s&&(s=!t.push(e)):t.push(o)}),s&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Je,Qn=G(()=>{Je=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var te,Fo=G(()=>{Qn();te=class extends Je{constructor(e,t,s){super(e,t),s&&(this.code=this.errno=s.code,this.erroredSysCall=s.syscall)}}});var Kn,Bo,Cr,vl,xl,Cl,es=G(()=>{Kn=Symbol.toStringTag,Bo=n=>typeof n=="object"&&typeof n.append=="function"&&typeof n.delete=="function"&&typeof n.get=="function"&&typeof n.getAll=="function"&&typeof n.has=="function"&&typeof n.set=="function"&&typeof n.sort=="function"&&n[Kn]==="URLSearchParams",Cr=n=>n&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&typeof n.constructor=="function"&&/^(Blob|File)$/.test(n[Kn]),vl=n=>typeof n=="object"&&(n[Kn]==="AbortSignal"||n[Kn]==="EventTarget"),xl=(n,e)=>{let t=new URL(e).hostname,s=new URL(n).hostname;return t===s||t.endsWith(`.${s}`)},Cl=(n,e)=>{let t=new URL(e).protocol,s=new URL(n).protocol;return t===s}});var Pl=X((xw,Al)=>{if(!globalThis.DOMException)try{let{MessageChannel:n}=Z("worker_threads"),e=new n().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(n){n.constructor.name==="DOMException"&&(globalThis.DOMException=n.constructor)}Al.exports=globalThis.DOMException});import{statSync as Il,createReadStream as Jm,promises as Vm}from"node:fs";import{basename as Ym}from"node:path";var Ol,Uo,kl,$l,Dl,Ll,Nl,Ml,ts,qo=G(()=>{Ol=Ht(Pl(),1);No();vr();({stat:Uo}=Vm),kl=(n,e)=>Nl(Il(n),n,e),$l=(n,e)=>Uo(n).then(t=>Nl(t,n,e)),Dl=(n,e)=>Uo(n).then(t=>Ml(t,n,e)),Ll=(n,e)=>Ml(Il(n),n,e),Nl=(n,e,t="")=>new Ee([new ts({path:e,size:n.size,lastModified:n.mtimeMs,start:0})],{type:t}),Ml=(n,e,t="")=>new ft([new ts({path:e,size:n.size,lastModified:n.mtimeMs,start:0})],Ym(e),{type:t,lastModified:n.mtimeMs}),ts=class n{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new n({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await Uo(this.#e);if(e>this.lastModified)throw new Ol.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*Jm(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Bl={};Ra(Bl,{toFormData:()=>rh});function th(n){let e=n.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",s=t.slice(t.lastIndexOf("\\")+1);return s=s.replace(/%22/g,'"'),s=s.replace(/&#(\d{4});/g,(o,a)=>String.fromCharCode(a)),s}async function rh(n,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let s=new jo(t[1]||t[2]),o,a,l,d,p,u,f=[],y=new pt,g=v=>{l+=R.decode(v,{stream:!0})},_=v=>{f.push(v)},S=()=>{let v=new ft(f,u,{type:p});y.append(d,v)},E=()=>{y.append(d,l)},R=new TextDecoder("utf-8");R.decode(),s.onPartBegin=function(){s.onPartData=g,s.onPartEnd=E,o="",a="",l="",d="",p="",u=null,f.length=0},s.onHeaderField=function(v){o+=R.decode(v,{stream:!0})},s.onHeaderValue=function(v){a+=R.decode(v,{stream:!0})},s.onHeaderEnd=function(){if(a+=R.decode(),o=o.toLowerCase(),o==="content-disposition"){let v=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);v&&(d=v[2]||v[3]||""),u=th(a),u&&(s.onPartData=_,s.onPartEnd=S)}else o==="content-type"&&(p=a);a="",o=""};for await(let v of n)s.write(v);return s.end(),y}var $e,j,Fl,mt,rs,ns,Zm,Ar,Xm,Qm,Km,eh,It,jo,Ul=G(()=>{qo();Xn();$e=0,j={START_BOUNDARY:$e++,HEADER_FIELD_START:$e++,HEADER_FIELD:$e++,HEADER_VALUE_START:$e++,HEADER_VALUE:$e++,HEADER_VALUE_ALMOST_DONE:$e++,HEADERS_ALMOST_DONE:$e++,PART_DATA_START:$e++,PART_DATA:$e++,END:$e++},Fl=1,mt={PART_BOUNDARY:Fl,LAST_BOUNDARY:Fl*=2},rs=10,ns=13,Zm=32,Ar=45,Xm=58,Qm=97,Km=122,eh=n=>n|32,It=()=>{},jo=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=It,this.onHeaderField=It,this.onHeadersEnd=It,this.onHeaderValue=It,this.onPartBegin=It,this.onPartData=It,this.onPartEnd=It,this.boundaryChars={},e=`\r
25
- --`+e;let t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s),this.boundaryChars[t[s]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=j.START_BOUNDARY}write(e){let t=0,s=e.length,o=this.index,{lookbehind:a,boundary:l,boundaryChars:d,index:p,state:u,flags:f}=this,y=this.boundary.length,g=y-1,_=e.length,S,E,R=x=>{this[x+"Mark"]=t},v=x=>{delete this[x+"Mark"]},A=(x,k,$,H)=>{(k===void 0||k!==$)&&this[x](H&&H.subarray(k,$))},C=(x,k)=>{let $=x+"Mark";$ in this&&(k?(A(x,this[$],t,e),delete this[$]):(A(x,this[$],e.length,e),this[$]=0))};for(t=0;t<s;t++)switch(S=e[t],u){case j.START_BOUNDARY:if(p===l.length-2){if(S===Ar)f|=mt.LAST_BOUNDARY;else if(S!==ns)return;p++;break}else if(p-1===l.length-2){if(f&mt.LAST_BOUNDARY&&S===Ar)u=j.END,f=0;else if(!(f&mt.LAST_BOUNDARY)&&S===rs)p=0,A("onPartBegin"),u=j.HEADER_FIELD_START;else return;break}S!==l[p+2]&&(p=-2),S===l[p+2]&&p++;break;case j.HEADER_FIELD_START:u=j.HEADER_FIELD,R("onHeaderField"),p=0;case j.HEADER_FIELD:if(S===ns){v("onHeaderField"),u=j.HEADERS_ALMOST_DONE;break}if(p++,S===Ar)break;if(S===Xm){if(p===1)return;C("onHeaderField",!0),u=j.HEADER_VALUE_START;break}if(E=eh(S),E<Qm||E>Km)return;break;case j.HEADER_VALUE_START:if(S===Zm)break;R("onHeaderValue"),u=j.HEADER_VALUE;case j.HEADER_VALUE:S===ns&&(C("onHeaderValue",!0),A("onHeaderEnd"),u=j.HEADER_VALUE_ALMOST_DONE);break;case j.HEADER_VALUE_ALMOST_DONE:if(S!==rs)return;u=j.HEADER_FIELD_START;break;case j.HEADERS_ALMOST_DONE:if(S!==rs)return;A("onHeadersEnd"),u=j.PART_DATA_START;break;case j.PART_DATA_START:u=j.PART_DATA,R("onPartData");case j.PART_DATA:if(o=p,p===0){for(t+=g;t<_&&!(e[t]in d);)t+=y;t-=g,S=e[t]}if(p<l.length)l[p]===S?(p===0&&C("onPartData",!0),p++):p=0;else if(p===l.length)p++,S===ns?f|=mt.PART_BOUNDARY:S===Ar?f|=mt.LAST_BOUNDARY:p=0;else if(p-1===l.length)if(f&mt.PART_BOUNDARY){if(p=0,S===rs){f&=~mt.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),u=j.HEADER_FIELD_START;break}}else f&mt.LAST_BOUNDARY&&S===Ar?(A("onPartEnd"),u=j.END,f=0):p=0;if(p>0)a[p-1]=S;else if(o>0){let x=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);A("onPartData",0,o,x),o=0,R("onPartData"),t--}break;case j.END:break;default:throw new Error(`Unexpected state entered: ${u}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=p,this.state=u,this.flags=f}end(){if(this.state===j.HEADER_FIELD_START&&this.index===0||this.state===j.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==j.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import ht,{PassThrough as ql}from"node:stream";import{types as jl,deprecate as zo,promisify as nh}from"node:util";import{Buffer as be}from"node:buffer";async function Wo(n){if(n[oe].disturbed)throw new TypeError(`body used already for: ${n.url}`);if(n[oe].disturbed=!0,n[oe].error)throw n[oe].error;let{body:e}=n;if(e===null)return be.alloc(0);if(!(e instanceof ht))return be.alloc(0);let t=[],s=0;try{for await(let o of e){if(n.size>0&&s+o.length>n.size){let a=new te(`content size at ${n.url} over limit: ${n.size}`,"max-size");throw e.destroy(a),a}s+=o.length,t.push(o)}}catch(o){throw o instanceof Je?o:new te(`Invalid response body while trying to fetch ${n.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(o=>typeof o=="string")?be.from(t.join("")):be.concat(t,s)}catch(o){throw new te(`Could not create Buffer from response body for ${n.url}: ${o.message}`,"system",o)}else throw new te(`Premature close of server response while trying to fetch ${n.url}`)}var sh,oe,De,er,oh,ss,Wl,zl,os=G(()=>{vr();Xn();Fo();Qn();es();sh=nh(ht.pipeline),oe=Symbol("Body internals"),De=class{constructor(e,{size:t=0}={}){let s=null;e===null?e=null:Bo(e)?e=be.from(e.toString()):Cr(e)||be.isBuffer(e)||(jl.isAnyArrayBuffer(e)?e=be.from(e):ArrayBuffer.isView(e)?e=be.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ht||(e instanceof pt?(e=El(e),s=e.type.split("=")[1]):e=be.from(String(e))));let o=e;be.isBuffer(e)?o=ht.Readable.from(e):Cr(e)&&(o=ht.Readable.from(e.stream())),this[oe]={body:e,stream:o,boundary:s,disturbed:!1,error:null},this.size=t,e instanceof ht&&e.on("error",a=>{let l=a instanceof Je?a:new te(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[oe].error=l})}get body(){return this[oe].stream}get bodyUsed(){return this[oe].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:s}=await Wo(this);return e.slice(t,t+s)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let s=new pt,o=new URLSearchParams(await this.text());for(let[a,l]of o)s.append(a,l);return s}let{toFormData:t}=await Promise.resolve().then(()=>(Ul(),Bl));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[oe].body&&this[oe].body.type||"",t=await this.arrayBuffer();return new Ee([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Wo(this);return new TextDecoder().decode(e)}buffer(){return Wo(this)}};De.prototype.buffer=zo(De.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(De.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:zo(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});er=(n,e)=>{let t,s,{body:o}=n[oe];if(n.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof ht&&typeof o.getBoundary!="function"&&(t=new ql({highWaterMark:e}),s=new ql({highWaterMark:e}),o.pipe(t),o.pipe(s),n[oe].stream=t,o=s),o},oh=zo(n=>n.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ss=(n,e)=>n===null?null:typeof n=="string"?"text/plain;charset=UTF-8":Bo(n)?"application/x-www-form-urlencoded;charset=UTF-8":Cr(n)?n.type||null:be.isBuffer(n)||jl.isAnyArrayBuffer(n)||ArrayBuffer.isView(n)?null:n instanceof pt?`multipart/form-data; boundary=${e[oe].boundary}`:n&&typeof n.getBoundary=="function"?`multipart/form-data;boundary=${oh(n)}`:n instanceof ht?null:"text/plain;charset=UTF-8",Wl=n=>{let{body:e}=n[oe];return e===null?0:Cr(e)?e.size:be.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},zl=async(n,{body:e})=>{e===null?n.end():await sh(e,n)}});import{types as Hl}from"node:util";import as from"node:http";function Gl(n=[]){return new ie(n.reduce((e,t,s,o)=>(s%2===0&&e.push(o.slice(s,s+2)),e),[]).filter(([e,t])=>{try{return is(e),Ho(e,String(t)),!0}catch{return!1}}))}var is,Ho,ie,cs=G(()=>{is=typeof as.validateHeaderName=="function"?as.validateHeaderName:n=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(n)){let e=new TypeError(`Header name must be a valid HTTP token [${n}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Ho=typeof as.validateHeaderValue=="function"?as.validateHeaderValue:(n,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${n}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},ie=class n extends URLSearchParams{constructor(e){let t=[];if(e instanceof n){let s=e.raw();for(let[o,a]of Object.entries(s))t.push(...a.map(l=>[o,l]))}else if(e!=null)if(typeof e=="object"&&!Hl.isBoxedPrimitive(e)){let s=e[Symbol.iterator];if(s==null)t.push(...Object.entries(e));else{if(typeof s!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(o=>{if(typeof o!="object"||Hl.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 t=t.length>0?t.map(([s,o])=>(is(s),Ho(s,String(o)),[String(s).toLowerCase(),String(o)])):void 0,super(t),new Proxy(this,{get(s,o,a){switch(o){case"append":case"set":return(l,d)=>(is(l),Ho(l,String(d)),URLSearchParams.prototype[o].call(s,String(l).toLowerCase(),String(d)));case"delete":case"has":case"getAll":return l=>(is(l),URLSearchParams.prototype[o].call(s,String(l).toLowerCase()));case"keys":return()=>(s.sort(),new Set(URLSearchParams.prototype.keys.call(s)).keys());default:return Reflect.get(s,o,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let s=t.join(", ");return/^content-encoding$/i.test(e)&&(s=s.toLowerCase()),s}forEach(e,t=void 0){for(let s of this.keys())Reflect.apply(e,t,[this.get(s),s,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,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let s=this.getAll(t);return t==="host"?e[t]=s[0]:e[t]=s.length>1?s:s[0],e},{})}};Object.defineProperties(ie.prototype,["get","entries","forEach","values"].reduce((n,e)=>(n[e]={enumerable:!0},n),{}))});var ih,Pr,Go=G(()=>{ih=new Set([301,302,303,307,308]),Pr=n=>ih.has(n)});var ve,de,Jl=G(()=>{cs();os();Go();ve=Symbol("Response internals"),de=class n extends De{constructor(e=null,t={}){super(e,t);let s=t.status!=null?t.status:200,o=new ie(t.headers);if(e!==null&&!o.has("Content-Type")){let a=ss(e,this);a&&o.append("Content-Type",a)}this[ve]={type:"default",url:t.url,status:s,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[ve].type}get url(){return this[ve].url||""}get status(){return this[ve].status}get ok(){return this[ve].status>=200&&this[ve].status<300}get redirected(){return this[ve].counter>0}get statusText(){return this[ve].statusText}get headers(){return this[ve].headers}get highWaterMark(){return this[ve].highWaterMark}clone(){return new n(er(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,t=302){if(!Pr(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new n(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new n(null,{status:0,statusText:""});return e[ve].type="error",e}static json(e=void 0,t={}){let s=JSON.stringify(e);if(s===void 0)throw new TypeError("data is not JSON serializable");let o=new ie(t&&t.headers);return o.has("content-type")||o.set("content-type","application/json"),new n(s,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(de.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 Vl,Yl=G(()=>{Vl=n=>{if(n.search)return n.search;let e=n.href.length-1,t=n.hash||(n.href[e]==="#"?"#":"");return n.href[e-t.length]==="?"?"?":""}});import{isIP as ah}from"node:net";function Zl(n,e=!1){return n==null||(n=new URL(n),/^(about|blob|data):$/.test(n.protocol))?"no-referrer":(n.username="",n.password="",n.hash="",e&&(n.pathname="",n.search=""),n)}function Kl(n){if(!Xl.has(n))throw new TypeError(`Invalid referrerPolicy: ${n}`);return n}function ch(n){if(/^(http|ws)s:$/.test(n.protocol))return!0;let e=n.host.replace(/(^\[)|(]$)/g,""),t=ah(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:n.host==="localhost"||n.host.endsWith(".localhost")?!1:n.protocol==="file:"}function tr(n){return/^about:(blank|srcdoc)$/.test(n)||n.protocol==="data:"||/^(blob|filesystem):$/.test(n.protocol)?!0:ch(n)}function eu(n,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(n.referrer==="no-referrer"||n.referrerPolicy==="")return null;let s=n.referrerPolicy;if(n.referrer==="about:client")return"no-referrer";let o=n.referrer,a=Zl(o),l=Zl(o,!0);a.toString().length>4096&&(a=l),e&&(a=e(a)),t&&(l=t(l));let d=new URL(n.url);switch(s){case"no-referrer":return"no-referrer";case"origin":return l;case"unsafe-url":return a;case"strict-origin":return tr(a)&&!tr(d)?"no-referrer":l.toString();case"strict-origin-when-cross-origin":return a.origin===d.origin?a:tr(a)&&!tr(d)?"no-referrer":l;case"same-origin":return a.origin===d.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===d.origin?a:l;case"no-referrer-when-downgrade":return tr(a)&&!tr(d)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${s}`)}}function tu(n){let e=(n.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let s of e)s&&Xl.has(s)&&(t=s);return t}var Xl,Ql,Jo=G(()=>{Xl=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Ql="strict-origin-when-cross-origin"});import{format as lh}from"node:url";import{deprecate as uh}from"node:util";var Y,Ir,dh,gt,ru,nu=G(()=>{cs();os();es();Yl();Jo();Y=Symbol("Request internals"),Ir=n=>typeof n=="object"&&typeof n[Y]=="object",dh=uh(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),gt=class n extends De{constructor(e,t={}){let s;if(Ir(e)?s=new URL(e.url):(s=new URL(e),e={}),s.username!==""||s.password!=="")throw new TypeError(`${s} is an url with embedded credentials.`);let o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!Ir(t)&&"data"in t&&dh(),(t.body!=null||Ir(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:Ir(e)&&e.body!==null?er(e):null;super(a,{size:t.size||e.size||0});let l=new ie(t.headers||e.headers||{});if(a!==null&&!l.has("Content-Type")){let u=ss(a,this);u&&l.set("Content-Type",u)}let d=Ir(e)?e.signal:null;if("signal"in t&&(d=t.signal),d!=null&&!vl(d))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let p=t.referrer==null?e.referrer:t.referrer;if(p==="")p="no-referrer";else if(p){let u=new URL(p);p=/^about:(\/\/)?client$/.test(u)?"client":u}else p=void 0;this[Y]={method:o,redirect:t.redirect||e.redirect||"follow",headers:l,parsedURL:s,signal:d,referrer:p},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Y].method}get url(){return lh(this[Y].parsedURL)}get headers(){return this[Y].headers}get redirect(){return this[Y].redirect}get signal(){return this[Y].signal}get referrer(){if(this[Y].referrer==="no-referrer")return"";if(this[Y].referrer==="client")return"about:client";if(this[Y].referrer)return this[Y].referrer.toString()}get referrerPolicy(){return this[Y].referrerPolicy}set referrerPolicy(e){this[Y].referrerPolicy=Kl(e)}clone(){return new n(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(gt.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}});ru=n=>{let{parsedURL:e}=n[Y],t=new ie(n[Y].headers);t.has("Accept")||t.set("Accept","*/*");let s=null;if(n.body===null&&/^(post|put)$/i.test(n.method)&&(s="0"),n.body!==null){let d=Wl(n);typeof d=="number"&&!Number.isNaN(d)&&(s=String(d))}s&&t.set("Content-Length",s),n.referrerPolicy===""&&(n.referrerPolicy=Ql),n.referrer&&n.referrer!=="no-referrer"?n[Y].referrer=eu(n):n[Y].referrer="no-referrer",n[Y].referrer instanceof URL&&t.set("Referer",n.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),n.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=n;typeof o=="function"&&(o=o(e));let a=Vl(e),l={path:e.pathname+a,method:n.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:n.insecureHTTPParser,agent:o};return{parsedURL:e,options:l}}});var Or,su=G(()=>{Qn();Or=class extends Je{constructor(e,t="aborted"){super(e,t)}}});var au={};Ra(au,{AbortError:()=>Or,Blob:()=>Ee,FetchError:()=>te,File:()=>ft,FormData:()=>pt,Headers:()=>ie,Request:()=>gt,Response:()=>de,blobFrom:()=>$l,blobFromSync:()=>kl,default:()=>Vo,fileFrom:()=>Dl,fileFromSync:()=>Ll,isRedirect:()=>Pr});import fh from"node:http";import ph from"node:https";import rr from"node:zlib";import ou,{PassThrough as iu,pipeline as nr}from"node:stream";import{Buffer as ls}from"node:buffer";async function Vo(n,e){return new Promise((t,s)=>{let o=new gt(n,e),{parsedURL:a,options:l}=ru(o);if(!mh.has(a.protocol))throw new TypeError(`node-fetch cannot load ${n}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let S=hl(o.url),E=new de(S,{headers:{"Content-Type":S.typeFull}});t(E);return}let d=(a.protocol==="https:"?ph:fh).request,{signal:p}=o,u=null,f=()=>{let S=new Or("The operation was aborted.");s(S),o.body&&o.body instanceof ou.Readable&&o.body.destroy(S),!(!u||!u.body)&&u.body.emit("error",S)};if(p&&p.aborted){f();return}let y=()=>{f(),_()},g=d(a.toString(),l);p&&p.addEventListener("abort",y);let _=()=>{g.abort(),p&&p.removeEventListener("abort",y)};g.on("error",S=>{s(new te(`request to ${o.url} failed, reason: ${S.message}`,"system",S)),_()}),hh(g,S=>{u&&u.body&&u.body.destroy(S)}),process.version<"v14"&&g.on("socket",S=>{let E;S.prependListener("end",()=>{E=S._eventsCount}),S.prependListener("close",R=>{if(u&&E<S._eventsCount&&!R){let v=new Error("Premature close");v.code="ERR_STREAM_PREMATURE_CLOSE",u.body.emit("error",v)}})}),g.on("response",S=>{g.setTimeout(0);let E=Gl(S.rawHeaders);if(Pr(S.statusCode)){let x=E.get("Location"),k=null;try{k=x===null?null:new URL(x,o.url)}catch{if(o.redirect!=="manual"){s(new te(`uri requested responds with an invalid redirect URL: ${x}`,"invalid-redirect")),_();return}}switch(o.redirect){case"error":s(new te(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),_();return;case"manual":break;case"follow":{if(k===null)break;if(o.counter>=o.follow){s(new te(`maximum redirect reached at: ${o.url}`,"max-redirect")),_();return}let $={headers:new ie(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:er(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!xl(o.url,k)||!Cl(o.url,k))for(let Ve of["authorization","www-authenticate","cookie","cookie2"])$.headers.delete(Ve);if(S.statusCode!==303&&o.body&&e.body instanceof ou.Readable){s(new te("Cannot follow redirect with body being a readable stream","unsupported-redirect")),_();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&o.method==="POST")&&($.method="GET",$.body=void 0,$.headers.delete("content-length"));let H=tu(E);H&&($.referrerPolicy=H),t(Vo(new gt(k,$))),_();return}default:return s(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}p&&S.once("end",()=>{p.removeEventListener("abort",y)});let R=nr(S,new iu,x=>{x&&s(x)});process.version<"v12.10"&&S.on("aborted",y);let v={url:o.url,status:S.statusCode,statusText:S.statusMessage,headers:E,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=E.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||S.statusCode===204||S.statusCode===304){u=new de(R,v),t(u);return}let C={flush:rr.Z_SYNC_FLUSH,finishFlush:rr.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){R=nr(R,rr.createGunzip(C),x=>{x&&s(x)}),u=new de(R,v),t(u);return}if(A==="deflate"||A==="x-deflate"){let x=nr(S,new iu,k=>{k&&s(k)});x.once("data",k=>{(k[0]&15)===8?R=nr(R,rr.createInflate(),$=>{$&&s($)}):R=nr(R,rr.createInflateRaw(),$=>{$&&s($)}),u=new de(R,v),t(u)}),x.once("end",()=>{u||(u=new de(R,v),t(u))});return}if(A==="br"){R=nr(R,rr.createBrotliDecompress(),x=>{x&&s(x)}),u=new de(R,v),t(u);return}u=new de(R,v),t(u)}),zl(g,o).catch(s)})}function hh(n,e){let t=ls.from(`0\r
23
+ `)),s.push(`--${t}--`),new e(s,{type:"multipart/form-data; boundary="+t})}var Ar,Hm,Gm,Rl,Jm,El,Fo,Pt,pt,Qn=G(()=>{Cr();Mo();({toStringTag:Ar,iterator:Hm,hasInstance:Gm}=Symbol),Rl=Math.random,Jm="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),El=(n,e,t)=>(n+="",/^(Blob|File)$/.test(e&&e[Ar])?[(t=t!==void 0?t+"":e[Ar]=="File"?e.name:"blob",n),e.name!==t||e[Ar]=="blob"?new ft([e],t,e):e]:[n,e+""]),Fo=(n,e)=>(e?n:n.replace(/\r?\n|\r/g,`\r
24
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Pt=(n,e,t)=>{if(e.length<t)throw new TypeError(`Failed to execute '${n}' on 'FormData': ${t} arguments required, but only ${e.length} present.`)},pt=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Ar](){return"FormData"}[Hm](){return this.entries()}static[Gm](e){return e&&typeof e=="object"&&e[Ar]==="FormData"&&!Jm.some(t=>typeof e[t]!="function")}append(...e){Pt("append",arguments,2),this.#e.push(El(...e))}delete(e){Pt("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Pt("get",arguments,1),e+="";for(var t=this.#e,s=t.length,o=0;o<s;o++)if(t[o][0]===e)return t[o][1];return null}getAll(e,t){return Pt("getAll",arguments,1),t=[],e+="",this.#e.forEach(s=>s[0]===e&&t.push(s[1])),t}has(e){return Pt("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Pt("forEach",arguments,1);for(var[s,o]of this)e.call(t,o,s,this)}set(...e){Pt("set",arguments,2);var t=[],s=!0;e=El(...e),this.#e.forEach(o=>{o[0]===e[0]?s&&(s=!t.push(e)):t.push(o)}),s&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Je,Kn=G(()=>{Je=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var te,Bo=G(()=>{Kn();te=class extends Je{constructor(e,t,s){super(e,t),s&&(this.code=this.errno=s.code,this.erroredSysCall=s.syscall)}}});var es,Uo,Pr,vl,Cl,Al,ts=G(()=>{es=Symbol.toStringTag,Uo=n=>typeof n=="object"&&typeof n.append=="function"&&typeof n.delete=="function"&&typeof n.get=="function"&&typeof n.getAll=="function"&&typeof n.has=="function"&&typeof n.set=="function"&&typeof n.sort=="function"&&n[es]==="URLSearchParams",Pr=n=>n&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&typeof n.constructor=="function"&&/^(Blob|File)$/.test(n[es]),vl=n=>typeof n=="object"&&(n[es]==="AbortSignal"||n[es]==="EventTarget"),Cl=(n,e)=>{let t=new URL(e).hostname,s=new URL(n).hostname;return t===s||t.endsWith(`.${s}`)},Al=(n,e)=>{let t=new URL(e).protocol,s=new URL(n).protocol;return t===s}});var Il=X((Aw,Pl)=>{if(!globalThis.DOMException)try{let{MessageChannel:n}=Z("worker_threads"),e=new n().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(n){n.constructor.name==="DOMException"&&(globalThis.DOMException=n.constructor)}Pl.exports=globalThis.DOMException});import{statSync as Ol,createReadStream as Vm,promises as Ym}from"node:fs";import{basename as Zm}from"node:path";var kl,qo,$l,Dl,Ll,Nl,Ml,Fl,rs,jo=G(()=>{kl=Ht(Il(),1);Mo();Cr();({stat:qo}=Ym),$l=(n,e)=>Ml(Ol(n),n,e),Dl=(n,e)=>qo(n).then(t=>Ml(t,n,e)),Ll=(n,e)=>qo(n).then(t=>Fl(t,n,e)),Nl=(n,e)=>Fl(Ol(n),n,e),Ml=(n,e,t="")=>new Ee([new rs({path:e,size:n.size,lastModified:n.mtimeMs,start:0})],{type:t}),Fl=(n,e,t="")=>new ft([new rs({path:e,size:n.size,lastModified:n.mtimeMs,start:0})],Zm(e),{type:t,lastModified:n.mtimeMs}),rs=class n{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new n({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await qo(this.#e);if(e>this.lastModified)throw new kl.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*Vm(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Ul={};Ea(Ul,{toFormData:()=>nh});function rh(n){let e=n.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",s=t.slice(t.lastIndexOf("\\")+1);return s=s.replace(/%22/g,'"'),s=s.replace(/&#(\d{4});/g,(o,a)=>String.fromCharCode(a)),s}async function nh(n,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let s=new Wo(t[1]||t[2]),o,a,l,d,p,u,f=[],y=new pt,g=x=>{l+=R.decode(x,{stream:!0})},_=x=>{f.push(x)},S=()=>{let x=new ft(f,u,{type:p});y.append(d,x)},E=()=>{y.append(d,l)},R=new TextDecoder("utf-8");R.decode(),s.onPartBegin=function(){s.onPartData=g,s.onPartEnd=E,o="",a="",l="",d="",p="",u=null,f.length=0},s.onHeaderField=function(x){o+=R.decode(x,{stream:!0})},s.onHeaderValue=function(x){a+=R.decode(x,{stream:!0})},s.onHeaderEnd=function(){if(a+=R.decode(),o=o.toLowerCase(),o==="content-disposition"){let x=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);x&&(d=x[2]||x[3]||""),u=rh(a),u&&(s.onPartData=_,s.onPartEnd=S)}else o==="content-type"&&(p=a);a="",o=""};for await(let x of n)s.write(x);return s.end(),y}var $e,j,Bl,mt,ns,ss,Xm,Ir,Qm,Km,eh,th,It,Wo,ql=G(()=>{jo();Qn();$e=0,j={START_BOUNDARY:$e++,HEADER_FIELD_START:$e++,HEADER_FIELD:$e++,HEADER_VALUE_START:$e++,HEADER_VALUE:$e++,HEADER_VALUE_ALMOST_DONE:$e++,HEADERS_ALMOST_DONE:$e++,PART_DATA_START:$e++,PART_DATA:$e++,END:$e++},Bl=1,mt={PART_BOUNDARY:Bl,LAST_BOUNDARY:Bl*=2},ns=10,ss=13,Xm=32,Ir=45,Qm=58,Km=97,eh=122,th=n=>n|32,It=()=>{},Wo=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=It,this.onHeaderField=It,this.onHeadersEnd=It,this.onHeaderValue=It,this.onPartBegin=It,this.onPartData=It,this.onPartEnd=It,this.boundaryChars={},e=`\r
25
+ --`+e;let t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s),this.boundaryChars[t[s]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=j.START_BOUNDARY}write(e){let t=0,s=e.length,o=this.index,{lookbehind:a,boundary:l,boundaryChars:d,index:p,state:u,flags:f}=this,y=this.boundary.length,g=y-1,_=e.length,S,E,R=v=>{this[v+"Mark"]=t},x=v=>{delete this[v+"Mark"]},A=(v,k,$,H)=>{(k===void 0||k!==$)&&this[v](H&&H.subarray(k,$))},C=(v,k)=>{let $=v+"Mark";$ in this&&(k?(A(v,this[$],t,e),delete this[$]):(A(v,this[$],e.length,e),this[$]=0))};for(t=0;t<s;t++)switch(S=e[t],u){case j.START_BOUNDARY:if(p===l.length-2){if(S===Ir)f|=mt.LAST_BOUNDARY;else if(S!==ss)return;p++;break}else if(p-1===l.length-2){if(f&mt.LAST_BOUNDARY&&S===Ir)u=j.END,f=0;else if(!(f&mt.LAST_BOUNDARY)&&S===ns)p=0,A("onPartBegin"),u=j.HEADER_FIELD_START;else return;break}S!==l[p+2]&&(p=-2),S===l[p+2]&&p++;break;case j.HEADER_FIELD_START:u=j.HEADER_FIELD,R("onHeaderField"),p=0;case j.HEADER_FIELD:if(S===ss){x("onHeaderField"),u=j.HEADERS_ALMOST_DONE;break}if(p++,S===Ir)break;if(S===Qm){if(p===1)return;C("onHeaderField",!0),u=j.HEADER_VALUE_START;break}if(E=th(S),E<Km||E>eh)return;break;case j.HEADER_VALUE_START:if(S===Xm)break;R("onHeaderValue"),u=j.HEADER_VALUE;case j.HEADER_VALUE:S===ss&&(C("onHeaderValue",!0),A("onHeaderEnd"),u=j.HEADER_VALUE_ALMOST_DONE);break;case j.HEADER_VALUE_ALMOST_DONE:if(S!==ns)return;u=j.HEADER_FIELD_START;break;case j.HEADERS_ALMOST_DONE:if(S!==ns)return;A("onHeadersEnd"),u=j.PART_DATA_START;break;case j.PART_DATA_START:u=j.PART_DATA,R("onPartData");case j.PART_DATA:if(o=p,p===0){for(t+=g;t<_&&!(e[t]in d);)t+=y;t-=g,S=e[t]}if(p<l.length)l[p]===S?(p===0&&C("onPartData",!0),p++):p=0;else if(p===l.length)p++,S===ss?f|=mt.PART_BOUNDARY:S===Ir?f|=mt.LAST_BOUNDARY:p=0;else if(p-1===l.length)if(f&mt.PART_BOUNDARY){if(p=0,S===ns){f&=~mt.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),u=j.HEADER_FIELD_START;break}}else f&mt.LAST_BOUNDARY&&S===Ir?(A("onPartEnd"),u=j.END,f=0):p=0;if(p>0)a[p-1]=S;else if(o>0){let v=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);A("onPartData",0,o,v),o=0,R("onPartData"),t--}break;case j.END:break;default:throw new Error(`Unexpected state entered: ${u}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=p,this.state=u,this.flags=f}end(){if(this.state===j.HEADER_FIELD_START&&this.index===0||this.state===j.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==j.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import ht,{PassThrough as jl}from"node:stream";import{types as Wl,deprecate as Ho,promisify as sh}from"node:util";import{Buffer as be}from"node:buffer";async function zo(n){if(n[oe].disturbed)throw new TypeError(`body used already for: ${n.url}`);if(n[oe].disturbed=!0,n[oe].error)throw n[oe].error;let{body:e}=n;if(e===null)return be.alloc(0);if(!(e instanceof ht))return be.alloc(0);let t=[],s=0;try{for await(let o of e){if(n.size>0&&s+o.length>n.size){let a=new te(`content size at ${n.url} over limit: ${n.size}`,"max-size");throw e.destroy(a),a}s+=o.length,t.push(o)}}catch(o){throw o instanceof Je?o:new te(`Invalid response body while trying to fetch ${n.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(o=>typeof o=="string")?be.from(t.join("")):be.concat(t,s)}catch(o){throw new te(`Could not create Buffer from response body for ${n.url}: ${o.message}`,"system",o)}else throw new te(`Premature close of server response while trying to fetch ${n.url}`)}var oh,oe,De,tr,ih,os,zl,Hl,is=G(()=>{Cr();Qn();Bo();Kn();ts();oh=sh(ht.pipeline),oe=Symbol("Body internals"),De=class{constructor(e,{size:t=0}={}){let s=null;e===null?e=null:Uo(e)?e=be.from(e.toString()):Pr(e)||be.isBuffer(e)||(Wl.isAnyArrayBuffer(e)?e=be.from(e):ArrayBuffer.isView(e)?e=be.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ht||(e instanceof pt?(e=xl(e),s=e.type.split("=")[1]):e=be.from(String(e))));let o=e;be.isBuffer(e)?o=ht.Readable.from(e):Pr(e)&&(o=ht.Readable.from(e.stream())),this[oe]={body:e,stream:o,boundary:s,disturbed:!1,error:null},this.size=t,e instanceof ht&&e.on("error",a=>{let l=a instanceof Je?a:new te(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[oe].error=l})}get body(){return this[oe].stream}get bodyUsed(){return this[oe].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:s}=await zo(this);return e.slice(t,t+s)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let s=new pt,o=new URLSearchParams(await this.text());for(let[a,l]of o)s.append(a,l);return s}let{toFormData:t}=await Promise.resolve().then(()=>(ql(),Ul));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[oe].body&&this[oe].body.type||"",t=await this.arrayBuffer();return new Ee([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await zo(this);return new TextDecoder().decode(e)}buffer(){return zo(this)}};De.prototype.buffer=Ho(De.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(De.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Ho(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});tr=(n,e)=>{let t,s,{body:o}=n[oe];if(n.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof ht&&typeof o.getBoundary!="function"&&(t=new jl({highWaterMark:e}),s=new jl({highWaterMark:e}),o.pipe(t),o.pipe(s),n[oe].stream=t,o=s),o},ih=Ho(n=>n.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),os=(n,e)=>n===null?null:typeof n=="string"?"text/plain;charset=UTF-8":Uo(n)?"application/x-www-form-urlencoded;charset=UTF-8":Pr(n)?n.type||null:be.isBuffer(n)||Wl.isAnyArrayBuffer(n)||ArrayBuffer.isView(n)?null:n instanceof pt?`multipart/form-data; boundary=${e[oe].boundary}`:n&&typeof n.getBoundary=="function"?`multipart/form-data;boundary=${ih(n)}`:n instanceof ht?null:"text/plain;charset=UTF-8",zl=n=>{let{body:e}=n[oe];return e===null?0:Pr(e)?e.size:be.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Hl=async(n,{body:e})=>{e===null?n.end():await oh(e,n)}});import{types as Gl}from"node:util";import cs from"node:http";function Jl(n=[]){return new ie(n.reduce((e,t,s,o)=>(s%2===0&&e.push(o.slice(s,s+2)),e),[]).filter(([e,t])=>{try{return as(e),Go(e,String(t)),!0}catch{return!1}}))}var as,Go,ie,ls=G(()=>{as=typeof cs.validateHeaderName=="function"?cs.validateHeaderName:n=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(n)){let e=new TypeError(`Header name must be a valid HTTP token [${n}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Go=typeof cs.validateHeaderValue=="function"?cs.validateHeaderValue:(n,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${n}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},ie=class n extends URLSearchParams{constructor(e){let t=[];if(e instanceof n){let s=e.raw();for(let[o,a]of Object.entries(s))t.push(...a.map(l=>[o,l]))}else if(e!=null)if(typeof e=="object"&&!Gl.isBoxedPrimitive(e)){let s=e[Symbol.iterator];if(s==null)t.push(...Object.entries(e));else{if(typeof s!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(o=>{if(typeof o!="object"||Gl.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 t=t.length>0?t.map(([s,o])=>(as(s),Go(s,String(o)),[String(s).toLowerCase(),String(o)])):void 0,super(t),new Proxy(this,{get(s,o,a){switch(o){case"append":case"set":return(l,d)=>(as(l),Go(l,String(d)),URLSearchParams.prototype[o].call(s,String(l).toLowerCase(),String(d)));case"delete":case"has":case"getAll":return l=>(as(l),URLSearchParams.prototype[o].call(s,String(l).toLowerCase()));case"keys":return()=>(s.sort(),new Set(URLSearchParams.prototype.keys.call(s)).keys());default:return Reflect.get(s,o,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let s=t.join(", ");return/^content-encoding$/i.test(e)&&(s=s.toLowerCase()),s}forEach(e,t=void 0){for(let s of this.keys())Reflect.apply(e,t,[this.get(s),s,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,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let s=this.getAll(t);return t==="host"?e[t]=s[0]:e[t]=s.length>1?s:s[0],e},{})}};Object.defineProperties(ie.prototype,["get","entries","forEach","values"].reduce((n,e)=>(n[e]={enumerable:!0},n),{}))});var ah,Or,Jo=G(()=>{ah=new Set([301,302,303,307,308]),Or=n=>ah.has(n)});var xe,de,Vl=G(()=>{ls();is();Jo();xe=Symbol("Response internals"),de=class n extends De{constructor(e=null,t={}){super(e,t);let s=t.status!=null?t.status:200,o=new ie(t.headers);if(e!==null&&!o.has("Content-Type")){let a=os(e,this);a&&o.append("Content-Type",a)}this[xe]={type:"default",url:t.url,status:s,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[xe].type}get url(){return this[xe].url||""}get status(){return this[xe].status}get ok(){return this[xe].status>=200&&this[xe].status<300}get redirected(){return this[xe].counter>0}get statusText(){return this[xe].statusText}get headers(){return this[xe].headers}get highWaterMark(){return this[xe].highWaterMark}clone(){return new n(tr(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,t=302){if(!Or(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new n(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new n(null,{status:0,statusText:""});return e[xe].type="error",e}static json(e=void 0,t={}){let s=JSON.stringify(e);if(s===void 0)throw new TypeError("data is not JSON serializable");let o=new ie(t&&t.headers);return o.has("content-type")||o.set("content-type","application/json"),new n(s,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(de.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 Yl,Zl=G(()=>{Yl=n=>{if(n.search)return n.search;let e=n.href.length-1,t=n.hash||(n.href[e]==="#"?"#":"");return n.href[e-t.length]==="?"?"?":""}});import{isIP as ch}from"node:net";function Xl(n,e=!1){return n==null||(n=new URL(n),/^(about|blob|data):$/.test(n.protocol))?"no-referrer":(n.username="",n.password="",n.hash="",e&&(n.pathname="",n.search=""),n)}function eu(n){if(!Ql.has(n))throw new TypeError(`Invalid referrerPolicy: ${n}`);return n}function lh(n){if(/^(http|ws)s:$/.test(n.protocol))return!0;let e=n.host.replace(/(^\[)|(]$)/g,""),t=ch(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:n.host==="localhost"||n.host.endsWith(".localhost")?!1:n.protocol==="file:"}function rr(n){return/^about:(blank|srcdoc)$/.test(n)||n.protocol==="data:"||/^(blob|filesystem):$/.test(n.protocol)?!0:lh(n)}function tu(n,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(n.referrer==="no-referrer"||n.referrerPolicy==="")return null;let s=n.referrerPolicy;if(n.referrer==="about:client")return"no-referrer";let o=n.referrer,a=Xl(o),l=Xl(o,!0);a.toString().length>4096&&(a=l),e&&(a=e(a)),t&&(l=t(l));let d=new URL(n.url);switch(s){case"no-referrer":return"no-referrer";case"origin":return l;case"unsafe-url":return a;case"strict-origin":return rr(a)&&!rr(d)?"no-referrer":l.toString();case"strict-origin-when-cross-origin":return a.origin===d.origin?a:rr(a)&&!rr(d)?"no-referrer":l;case"same-origin":return a.origin===d.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===d.origin?a:l;case"no-referrer-when-downgrade":return rr(a)&&!rr(d)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${s}`)}}function ru(n){let e=(n.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let s of e)s&&Ql.has(s)&&(t=s);return t}var Ql,Kl,Vo=G(()=>{Ql=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Kl="strict-origin-when-cross-origin"});import{format as uh}from"node:url";import{deprecate as dh}from"node:util";var Y,kr,fh,gt,nu,su=G(()=>{ls();is();ts();Zl();Vo();Y=Symbol("Request internals"),kr=n=>typeof n=="object"&&typeof n[Y]=="object",fh=dh(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),gt=class n extends De{constructor(e,t={}){let s;if(kr(e)?s=new URL(e.url):(s=new URL(e),e={}),s.username!==""||s.password!=="")throw new TypeError(`${s} is an url with embedded credentials.`);let o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!kr(t)&&"data"in t&&fh(),(t.body!=null||kr(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:kr(e)&&e.body!==null?tr(e):null;super(a,{size:t.size||e.size||0});let l=new ie(t.headers||e.headers||{});if(a!==null&&!l.has("Content-Type")){let u=os(a,this);u&&l.set("Content-Type",u)}let d=kr(e)?e.signal:null;if("signal"in t&&(d=t.signal),d!=null&&!vl(d))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let p=t.referrer==null?e.referrer:t.referrer;if(p==="")p="no-referrer";else if(p){let u=new URL(p);p=/^about:(\/\/)?client$/.test(u)?"client":u}else p=void 0;this[Y]={method:o,redirect:t.redirect||e.redirect||"follow",headers:l,parsedURL:s,signal:d,referrer:p},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Y].method}get url(){return uh(this[Y].parsedURL)}get headers(){return this[Y].headers}get redirect(){return this[Y].redirect}get signal(){return this[Y].signal}get referrer(){if(this[Y].referrer==="no-referrer")return"";if(this[Y].referrer==="client")return"about:client";if(this[Y].referrer)return this[Y].referrer.toString()}get referrerPolicy(){return this[Y].referrerPolicy}set referrerPolicy(e){this[Y].referrerPolicy=eu(e)}clone(){return new n(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(gt.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}});nu=n=>{let{parsedURL:e}=n[Y],t=new ie(n[Y].headers);t.has("Accept")||t.set("Accept","*/*");let s=null;if(n.body===null&&/^(post|put)$/i.test(n.method)&&(s="0"),n.body!==null){let d=zl(n);typeof d=="number"&&!Number.isNaN(d)&&(s=String(d))}s&&t.set("Content-Length",s),n.referrerPolicy===""&&(n.referrerPolicy=Kl),n.referrer&&n.referrer!=="no-referrer"?n[Y].referrer=tu(n):n[Y].referrer="no-referrer",n[Y].referrer instanceof URL&&t.set("Referer",n.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),n.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=n;typeof o=="function"&&(o=o(e));let a=Yl(e),l={path:e.pathname+a,method:n.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:n.insecureHTTPParser,agent:o};return{parsedURL:e,options:l}}});var $r,ou=G(()=>{Kn();$r=class extends Je{constructor(e,t="aborted"){super(e,t)}}});var cu={};Ea(cu,{AbortError:()=>$r,Blob:()=>Ee,FetchError:()=>te,File:()=>ft,FormData:()=>pt,Headers:()=>ie,Request:()=>gt,Response:()=>de,blobFrom:()=>Dl,blobFromSync:()=>$l,default:()=>Yo,fileFrom:()=>Ll,fileFromSync:()=>Nl,isRedirect:()=>Or});import ph from"node:http";import mh from"node:https";import nr from"node:zlib";import iu,{PassThrough as au,pipeline as sr}from"node:stream";import{Buffer as us}from"node:buffer";async function Yo(n,e){return new Promise((t,s)=>{let o=new gt(n,e),{parsedURL:a,options:l}=nu(o);if(!hh.has(a.protocol))throw new TypeError(`node-fetch cannot load ${n}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let S=gl(o.url),E=new de(S,{headers:{"Content-Type":S.typeFull}});t(E);return}let d=(a.protocol==="https:"?mh:ph).request,{signal:p}=o,u=null,f=()=>{let S=new $r("The operation was aborted.");s(S),o.body&&o.body instanceof iu.Readable&&o.body.destroy(S),!(!u||!u.body)&&u.body.emit("error",S)};if(p&&p.aborted){f();return}let y=()=>{f(),_()},g=d(a.toString(),l);p&&p.addEventListener("abort",y);let _=()=>{g.abort(),p&&p.removeEventListener("abort",y)};g.on("error",S=>{s(new te(`request to ${o.url} failed, reason: ${S.message}`,"system",S)),_()}),gh(g,S=>{u&&u.body&&u.body.destroy(S)}),process.version<"v14"&&g.on("socket",S=>{let E;S.prependListener("end",()=>{E=S._eventsCount}),S.prependListener("close",R=>{if(u&&E<S._eventsCount&&!R){let x=new Error("Premature close");x.code="ERR_STREAM_PREMATURE_CLOSE",u.body.emit("error",x)}})}),g.on("response",S=>{g.setTimeout(0);let E=Jl(S.rawHeaders);if(Or(S.statusCode)){let v=E.get("Location"),k=null;try{k=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){s(new te(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),_();return}}switch(o.redirect){case"error":s(new te(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),_();return;case"manual":break;case"follow":{if(k===null)break;if(o.counter>=o.follow){s(new te(`maximum redirect reached at: ${o.url}`,"max-redirect")),_();return}let $={headers:new ie(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:tr(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Cl(o.url,k)||!Al(o.url,k))for(let Ve of["authorization","www-authenticate","cookie","cookie2"])$.headers.delete(Ve);if(S.statusCode!==303&&o.body&&e.body instanceof iu.Readable){s(new te("Cannot follow redirect with body being a readable stream","unsupported-redirect")),_();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&o.method==="POST")&&($.method="GET",$.body=void 0,$.headers.delete("content-length"));let H=ru(E);H&&($.referrerPolicy=H),t(Yo(new gt(k,$))),_();return}default:return s(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}p&&S.once("end",()=>{p.removeEventListener("abort",y)});let R=sr(S,new au,v=>{v&&s(v)});process.version<"v12.10"&&S.on("aborted",y);let x={url:o.url,status:S.statusCode,statusText:S.statusMessage,headers:E,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=E.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||S.statusCode===204||S.statusCode===304){u=new de(R,x),t(u);return}let C={flush:nr.Z_SYNC_FLUSH,finishFlush:nr.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){R=sr(R,nr.createGunzip(C),v=>{v&&s(v)}),u=new de(R,x),t(u);return}if(A==="deflate"||A==="x-deflate"){let v=sr(S,new au,k=>{k&&s(k)});v.once("data",k=>{(k[0]&15)===8?R=sr(R,nr.createInflate(),$=>{$&&s($)}):R=sr(R,nr.createInflateRaw(),$=>{$&&s($)}),u=new de(R,x),t(u)}),v.once("end",()=>{u||(u=new de(R,x),t(u))});return}if(A==="br"){R=sr(R,nr.createBrotliDecompress(),v=>{v&&s(v)}),u=new de(R,x),t(u);return}u=new de(R,x),t(u)}),Hl(g,o).catch(s)})}function gh(n,e){let t=us.from(`0\r
26
26
  \r
27
- `),s=!1,o=!1,a;n.on("response",l=>{let{headers:d}=l;s=d["transfer-encoding"]==="chunked"&&!d["content-length"]}),n.on("socket",l=>{let d=()=>{if(s&&!o){let u=new Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",e(u)}},p=u=>{o=ls.compare(u.slice(-5),t)===0,!o&&a&&(o=ls.compare(a.slice(-3),t.slice(0,3))===0&&ls.compare(u.slice(-2),t.slice(3))===0),a=u};l.prependListener("close",d),l.on("data",p),n.on("close",()=>{l.removeListener("close",d),l.removeListener("data",p)})})}var mh,cu=G(()=>{gl();os();Jl();cs();nu();Fo();su();Go();Xn();es();Jo();qo();mh=new Set(["data:","http:","https:"])});import{realpathSync as Nu}from"node:fs";import{fileURLToPath as Pg}from"node:url";import{Server as Ig}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Og}from"@modelcontextprotocol/sdk/server/stdio.js";import{buildCli as kg}from"@n24q02m/hull";import{localAuthContext as Wf,runWithAuthContext as zf}from"@n24q02m/hull/token-auth";import{PerPluginStore as Df}from"@n24q02m/hull/storage";var ce="workspace",We="workspace",dn="better-workspace",Ea="https://accounts.google.com/o/oauth2/v2/auth",va="https://oauth2.googleapis.com/token",fn=["openid","email","profile"];function xt(n){if(typeof n!="string")return;let e=n.split(".")[1];if(e)try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}function xa(n){return n!==null&&n.version===void 0&&typeof n.access_token=="string"}var Ca="(unidentified)",br=n=>n.trim().toLowerCase(),pn=class{constructor(e=null){this.store=new Df(We,e)}async load(){let e=await this.store.load();if(e===null)return null;if(!xa(e)){let a=e;return a.version===2&&a.accounts?a:null}let t=e,s=xt(t.id_token);if(!s)return null;let o={version:2,accounts:{[s]:t},primary:s};return await this.store.save(o),o}async loadLegacy(){let e=await this.store.load();return xa(e)?e:null}async adoptLegacy(e){let t=await this.loadLegacy();if(!t)return null;let s=br(e);return await this.store.save({version:2,accounts:{[s]:t},primary:s}),t}async put(e,t,s={}){let o=br(e),a=await this.load(),l={};if(!a){let f=await this.loadLegacy();if(f){if(!s.absorbLegacy)throw new Error('Refusing to overwrite credentials stored in the older single-account layout. Adopt them first, or clear them deliberately with config(action="setup_reset") before adding a new account.');l={[Ca]:f}}}let d=a??{version:2,accounts:l,primary:o},p={...d.accounts,[o]:t},u=s.makePrimary||!d.accounts[d.primary]?o:d.primary;await this.store.save({version:2,accounts:p,primary:u})}async get(e){let t=await this.load();if(!t)return null;let s=e?br(e):t.primary,o=t.accounts[s];return o?{email:s,record:o}:null}async list(){let e=await this.load();return e?{accounts:Object.keys(e.accounts).sort(),primary:e.primary}:{accounts:[],primary:null}}async remove(e){let t=await this.load();if(!t)return{removed:!1,newPrimary:null};let s=br(e);if(!t.accounts[s])return{removed:!1,newPrimary:t.primary};let o={...t.accounts};delete o[s];let a=Object.keys(o);if(a.length===0)return await this.store.clear(),{removed:!0,newPrimary:null};let l=a.find(p=>p!==Ca)??a[0],d=t.primary===s?l:t.primary;return await this.store.save({version:2,accounts:o,primary:d}),{removed:!0,newPrimary:d}}async setPrimary(e){let t=await this.load(),s=br(e);if(!t?.accounts[s])throw new Error(`Account ${s} is not configured.`);await this.store.save({...t,primary:s})}async clear(){await this.store.clear()}};var Lf=1e4;function Sr(n){n.close().catch(e=>{console.error(`[${ce}] failed to close the consent callback server:`,e)})}function mn(n,e=Lf){let t=setTimeout(()=>Sr(n),e);typeof t.unref=="function"&&t.unref()}import{currentUser as Nf}from"@n24q02m/hull/token-auth";function hn(){let n=Nf();return n.mode==="no-auth"?void 0:n.namespace}import{google as Aa}from"googleapis";var gn=class{constructor(e,t=null){this.scopes=e;this.accounts=new pn(t)}async saveTokens(e,t={}){let s={...e},o=e.expires_in;s.expiry_date===void 0&&typeof o=="number"&&(s.expiry_date=Date.now()+o*1e3);let a=t.email?.trim().toLowerCase()??xt(e.id_token);if(!a)throw new Error("Cannot store Google tokens without an account email (no id_token email claim and none passed).");return await this.accounts.put(a,s,{makePrimary:t.makePrimary,absorbLegacy:!0}),a}async listAccounts(){return this.accounts.list()}async removeAccount(e){return this.accounts.remove(e)}async setPrimary(e){return this.accounts.setPrimary(e)}async clear(){await this.accounts.clear()}async fetchAccountEmail(e){try{let{data:t}=await Aa.oauth2({version:"v2",auth:e}).userinfo.get();return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}buildBareClient(e){let t=new Aa.auth.OAuth2({clientId:process.env.GOOGLE_OAUTH_CLIENT_ID,clientSecret:process.env.GOOGLE_OAUTH_CLIENT_SECRET});return t.setCredentials({access_token:e.access_token,refresh_token:e.refresh_token,expiry_date:e.expiry_date,scope:e.scope,token_type:e.token_type}),t}buildClient(e,t){let s=this.buildBareClient(t);return s.on("tokens",o=>{this.saveTokens({...t,...o},{email:e})}),s}async getAuthenticatedClient(e){let t=await this.accounts.get(e);if(t)return this.buildClient(t.email,t.record);if(!e){let s=await this.accounts.loadLegacy();if(s){let o=await this.fetchAccountEmail(this.buildBareClient(s));if(o)return await this.accounts.adoptLegacy(o),this.buildClient(o,s);throw new Error('Stored Google credentials are from an older single-account layout and the account email could not be resolved. Run config(action="account_add") to re-authorize, or re-authorize the existing account.')}}if(e){let{accounts:s}=await this.accounts.list(),o=s.length>0?` Configured accounts: ${s.join(", ")}.`:"";throw new Error(`Account ${e.trim().toLowerCase()} is not configured.${o}`)}throw new Error("Google account not configured. Run `workspace auth` on the host to complete the Google consent (see setup docs).")}};var Ia="",Pa=new Map,wr=new Map;function yn(){return hn()??Ia}function Ct(){return wr.get(yn())??"awaiting_setup"}function le(){let n=yn(),e=Pa.get(n);return e||(e=new gn(fn,n===Ia?null:n),Pa.set(n,e)),e}async function ot(){let n=yn(),e=le(),{accounts:t}=await e.listAccounts();if(t.length>0)return wr.set(n,"configured"),"configured";try{return await e.getAuthenticatedClient(),wr.set(n,"configured"),"configured"}catch{return wr.set(n,"awaiting_setup"),"awaiting_setup"}}async function Oa(){await le().clear(),wr.set(yn(),"awaiting_setup")}import{randomBytes as Mf,timingSafeEqual as Ff}from"node:crypto";import{createServer as Bf}from"node:http";var _r="127.0.0.1",ka="/callback";function ao(n){return n.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function it(n,e,t,s){n.writeHead(e,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),n.end(`<!doctype html><meta charset="utf-8"><title>${ao(t)}</title><h1>${ao(t)}</h1><p>${ao(s)}</p>`)}function Uf(n,e){let t=Buffer.from(n),s=Buffer.from(e);return t.length===s.length&&Ff(t,s)}async function qf(n,e,t){let s=new URLSearchParams({grant_type:"authorization_code",code:e,client_id:n.clientId,client_secret:n.clientSecret,redirect_uri:t}),o=await fetch(va,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!o.ok)throw new Error(`Google token exchange failed (HTTP ${o.status}).`);return await o.json()}async function bn(n){let e=Mf(16).toString("base64url"),t="",s=async(d,p)=>{let u=new URL(d.url??"/",`http://${_r}`);if(d.method!=="GET"){it(p,405,"Method not allowed","Use GET.");return}if(u.pathname==="/"){let g=new URL(Ea);g.search=new URLSearchParams({client_id:n.clientId,redirect_uri:t,response_type:"code",scope:n.scopes.join(" "),state:e,access_type:"offline",prompt:"consent"}).toString(),p.writeHead(302,{Location:g.toString(),"Cache-Control":"no-store"}),p.end();return}if(u.pathname!==ka){it(p,404,"Not found","Nothing here.");return}let f=u.searchParams.get("state")??"";if(!Uf(f,e)){it(p,400,"Authorization failed","The consent response did not match this session. Start again.");return}if(u.searchParams.get("error")){it(p,400,"Authorization cancelled","Google did not grant access. Nothing was stored.");return}let y=u.searchParams.get("code");if(!y){it(p,400,"Authorization failed","Google returned no authorization code.");return}try{let g=await qf(n,y,t);await n.onTokens(g),it(p,200,"Authorization complete","You can close this tab.")}catch(g){let _=g instanceof Error?g.message:"Authorization failed.";it(p,500,"Authorization failed",_)}},o=Bf((d,p)=>{s(d,p).catch(u=>{console.error("[workspace] consent request failed:",u),p.headersSent||it(p,500,"Authorization failed","Unexpected error.")})}),a=Promise.withResolvers();o.once("error",a.reject),o.listen(n.port??0,_r,()=>{o.off("error",a.reject),a.resolve()}),await a.promise;let{port:l}=o.address();return t=`http://${_r}:${l}${ka}`,{url:`http://${_r}:${l}/`,host:_r,port:l,close:()=>{let d=Promise.withResolvers();return o.close(p=>p?d.reject(p):d.resolve()),o.closeIdleConnections(),d.promise}}}var co=["openid","email","profile","https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/calendar","https://www.googleapis.com/auth/gmail.modify","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/presentations","https://www.googleapis.com/auth/tasks","https://www.googleapis.com/auth/chat.messages","https://www.googleapis.com/auth/contacts.readonly","https://www.googleapis.com/auth/forms.body","https://www.googleapis.com/auth/forms.responses.readonly"];async function $a(n={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required for OAuth setup.");let s=Promise.withResolvers(),o=null,a=await bn({clientId:e,clientSecret:t,scopes:co,onTokens:async l=>{if(o===null){o=le().saveTokens(l).then(p=>(s.resolve(),p),p=>{throw s.reject(p),p}),await o;return}let d=await o;if(xt(l.id_token)!==d)throw new Error(`Setup already completed for ${d}. Use config(action="account_add") to add another account.`)}});process.stderr.write(`[${ce}] Google authorization required. Open ${a.url} in a browser to continue.
28
- `);try{await s.promise}catch(l){throw Sr(a),l}mn(a,n.graceMs)}var jf=600*1e3;async function Sn(n={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required to add an account.");let s=Promise.withResolvers(),o=null,a=await bn({clientId:e,clientSecret:t,scopes:co,onTokens:async u=>{if(o===null){o=le().saveTokens(u,{makePrimary:n.makePrimary}).then(y=>(s.resolve(y),y),y=>{throw s.reject(y),y}),await o;return}let f=await o;if(xt(u.id_token)!==f)throw new Error(`This add-account flow already completed for ${f}. Call config(action="account_add") again to add a different account.`)}}),l=Promise.withResolvers(),d=setTimeout(()=>l.reject(new Error("Add-account flow timed out before the Google consent completed.")),n.ttlMs??jf);typeof d.unref=="function"&&d.unref();let p=Promise.race([s.promise,l.promise]);return p.then(()=>{clearTimeout(d),mn(a,n.graceMs)},()=>{clearTimeout(d),Sr(a)}),{url:a.url,done:p}}var Hf=/^[a-zA-Z0-9._-]+$/;function Gf(n){let e=n.indexOf("--user");if(e===-1)return{};let t=n[e+1];return!t||t.startsWith("--")?{error:"--user requires a namespace value."}:Hf.test(t)?{user:t}:{error:'--user must contain only letters, digits, ".", "_" or "-".'}}async function Da(){let n=await Sn();process.stderr.write(`[workspace] Google authorization required. Open ${n.url} in a browser to continue.
27
+ `),s=!1,o=!1,a;n.on("response",l=>{let{headers:d}=l;s=d["transfer-encoding"]==="chunked"&&!d["content-length"]}),n.on("socket",l=>{let d=()=>{if(s&&!o){let u=new Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",e(u)}},p=u=>{o=us.compare(u.slice(-5),t)===0,!o&&a&&(o=us.compare(a.slice(-3),t.slice(0,3))===0&&us.compare(u.slice(-2),t.slice(3))===0),a=u};l.prependListener("close",d),l.on("data",p),n.on("close",()=>{l.removeListener("close",d),l.removeListener("data",p)})})}var hh,lu=G(()=>{yl();is();Vl();ls();su();Bo();ou();Jo();Qn();ts();Vo();jo();hh=new Set(["data:","http:","https:"])});import{realpathSync as Mu}from"node:fs";import{fileURLToPath as Ig}from"node:url";import{Server as Og}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as kg}from"@modelcontextprotocol/sdk/server/stdio.js";import{buildCli as $g}from"@n24q02m/hull";import{localAuthContext as zf,runWithAuthContext as Hf}from"@n24q02m/hull/token-auth";import{PerPluginStore as Lf}from"@n24q02m/hull/storage";var ce="workspace",We="workspace",pn="better-workspace",xa="https://accounts.google.com/o/oauth2/v2/auth",va="https://oauth2.googleapis.com/token",mn=["openid","email","profile"];function vt(n){if(typeof n!="string")return;let e=n.split(".")[1];if(e)try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}function Ca(n){return n!==null&&n.version===void 0&&typeof n.access_token=="string"}var Aa="(unidentified)",Sr=n=>n.trim().toLowerCase(),hn=class{constructor(e=null){this.store=new Lf(We,e)}async load(){let e=await this.store.load();if(e===null)return null;if(!Ca(e)){let a=e;return a.version===2&&a.accounts?a:null}let t=e,s=vt(t.id_token);if(!s)return null;let o={version:2,accounts:{[s]:t},primary:s};return await this.store.save(o),o}async loadLegacy(){let e=await this.store.load();return Ca(e)?e:null}async adoptLegacy(e){let t=await this.loadLegacy();if(!t)return null;let s=Sr(e);return await this.store.save({version:2,accounts:{[s]:t},primary:s}),t}async put(e,t,s={}){let o=Sr(e),a=await this.load(),l={};if(!a){let f=await this.loadLegacy();if(f){if(!s.absorbLegacy)throw new Error('Refusing to overwrite credentials stored in the older single-account layout. Adopt them first, or clear them deliberately with config(action="setup_reset") before adding a new account.');l={[Aa]:f}}}let d=a??{version:2,accounts:l,primary:o},p={...d.accounts,[o]:t},u=s.makePrimary||!d.accounts[d.primary]?o:d.primary;await this.store.save({version:2,accounts:p,primary:u})}async get(e){let t=await this.load();if(!t)return null;let s=e?Sr(e):t.primary,o=t.accounts[s];return o?{email:s,record:o}:null}async list(){let e=await this.load();return e?{accounts:Object.keys(e.accounts).sort(),primary:e.primary}:{accounts:[],primary:null}}async remove(e){let t=await this.load();if(!t)return{removed:!1,newPrimary:null};let s=Sr(e);if(!t.accounts[s])return{removed:!1,newPrimary:t.primary};let o={...t.accounts};delete o[s];let a=Object.keys(o);if(a.length===0)return await this.store.clear(),{removed:!0,newPrimary:null};let l=a.find(p=>p!==Aa)??a[0],d=t.primary===s?l:t.primary;return await this.store.save({version:2,accounts:o,primary:d}),{removed:!0,newPrimary:d}}async setPrimary(e){let t=await this.load(),s=Sr(e);if(!t?.accounts[s])throw new Error(`Account ${s} is not configured.`);await this.store.save({...t,primary:s})}async clear(){await this.store.clear()}};var Nf=1e4;function wr(n){n.close().catch(e=>{console.error(`[${ce}] failed to close the consent callback server:`,e)})}function gn(n,e=Nf){let t=setTimeout(()=>wr(n),e);typeof t.unref=="function"&&t.unref()}import{currentUser as Mf}from"@n24q02m/hull/token-auth";function _r(){let n=Mf();return n.mode==="no-auth"?void 0:n.namespace}function Gt(){let n=_r();return n===void 0?"workspace auth":`workspace auth --user ${n}`}import{google as Pa}from"googleapis";var yn=class{constructor(e,t=null){this.scopes=e;this.accounts=new hn(t)}async saveTokens(e,t={}){let s={...e},o=e.expires_in;s.expiry_date===void 0&&typeof o=="number"&&(s.expiry_date=Date.now()+o*1e3);let a=t.email?.trim().toLowerCase()??vt(e.id_token);if(!a)throw new Error("Cannot store Google tokens without an account email (no id_token email claim and none passed).");return await this.accounts.put(a,s,{makePrimary:t.makePrimary,absorbLegacy:!0}),a}async listAccounts(){return this.accounts.list()}async removeAccount(e){return this.accounts.remove(e)}async setPrimary(e){return this.accounts.setPrimary(e)}async clear(){await this.accounts.clear()}async fetchAccountEmail(e){try{let{data:t}=await Pa.oauth2({version:"v2",auth:e}).userinfo.get();return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}buildBareClient(e){let t=new Pa.auth.OAuth2({clientId:process.env.GOOGLE_OAUTH_CLIENT_ID,clientSecret:process.env.GOOGLE_OAUTH_CLIENT_SECRET});return t.setCredentials({access_token:e.access_token,refresh_token:e.refresh_token,expiry_date:e.expiry_date,scope:e.scope,token_type:e.token_type}),t}buildClient(e,t){let s=this.buildBareClient(t);return s.on("tokens",o=>{this.saveTokens({...t,...o},{email:e})}),s}async getAuthenticatedClient(e){let t=await this.accounts.get(e);if(t)return this.buildClient(t.email,t.record);if(!e){let s=await this.accounts.loadLegacy();if(s){let o=await this.fetchAccountEmail(this.buildBareClient(s));if(o)return await this.accounts.adoptLegacy(o),this.buildClient(o,s);throw new Error('Stored Google credentials are from an older single-account layout and the account email could not be resolved. Run config(action="account_add") to re-authorize, or re-authorize the existing account.')}}if(e){let{accounts:s}=await this.accounts.list(),o=s.length>0?` Configured accounts: ${s.join(", ")}.`:"";throw new Error(`Account ${e.trim().toLowerCase()} is not configured.${o}`)}throw new Error(`Google account not configured. Run \`${Gt()}\` on the host to complete the Google consent (see setup docs).`)}};var Oa="",Ia=new Map,Tr=new Map;function bn(){return _r()??Oa}function Ct(){return Tr.get(bn())??"awaiting_setup"}function le(){let n=bn(),e=Ia.get(n);return e||(e=new yn(mn,n===Oa?null:n),Ia.set(n,e)),e}async function ot(){let n=bn(),e=le(),{accounts:t}=await e.listAccounts();if(t.length>0)return Tr.set(n,"configured"),"configured";try{return await e.getAuthenticatedClient(),Tr.set(n,"configured"),"configured"}catch{return Tr.set(n,"awaiting_setup"),"awaiting_setup"}}async function ka(){await le().clear(),Tr.set(bn(),"awaiting_setup")}import{randomBytes as Ff,timingSafeEqual as Bf}from"node:crypto";import{createServer as Uf}from"node:http";var Rr="127.0.0.1",$a="/callback";function co(n){return n.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function it(n,e,t,s){n.writeHead(e,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),n.end(`<!doctype html><meta charset="utf-8"><title>${co(t)}</title><h1>${co(t)}</h1><p>${co(s)}</p>`)}function qf(n,e){let t=Buffer.from(n),s=Buffer.from(e);return t.length===s.length&&Bf(t,s)}async function jf(n,e,t){let s=new URLSearchParams({grant_type:"authorization_code",code:e,client_id:n.clientId,client_secret:n.clientSecret,redirect_uri:t}),o=await fetch(va,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!o.ok)throw new Error(`Google token exchange failed (HTTP ${o.status}).`);return await o.json()}async function Sn(n){let e=Ff(16).toString("base64url"),t="",s=async(d,p)=>{let u=new URL(d.url??"/",`http://${Rr}`);if(d.method!=="GET"){it(p,405,"Method not allowed","Use GET.");return}if(u.pathname==="/"){let g=new URL(xa);g.search=new URLSearchParams({client_id:n.clientId,redirect_uri:t,response_type:"code",scope:n.scopes.join(" "),state:e,access_type:"offline",prompt:"consent"}).toString(),p.writeHead(302,{Location:g.toString(),"Cache-Control":"no-store"}),p.end();return}if(u.pathname!==$a){it(p,404,"Not found","Nothing here.");return}let f=u.searchParams.get("state")??"";if(!qf(f,e)){it(p,400,"Authorization failed","The consent response did not match this session. Start again.");return}if(u.searchParams.get("error")){it(p,400,"Authorization cancelled","Google did not grant access. Nothing was stored.");return}let y=u.searchParams.get("code");if(!y){it(p,400,"Authorization failed","Google returned no authorization code.");return}try{let g=await jf(n,y,t);await n.onTokens(g),it(p,200,"Authorization complete","You can close this tab.")}catch(g){let _=g instanceof Error?g.message:"Authorization failed.";it(p,500,"Authorization failed",_)}},o=Uf((d,p)=>{s(d,p).catch(u=>{console.error("[workspace] consent request failed:",u),p.headersSent||it(p,500,"Authorization failed","Unexpected error.")})}),a=Promise.withResolvers();o.once("error",a.reject),o.listen(n.port??0,Rr,()=>{o.off("error",a.reject),a.resolve()}),await a.promise;let{port:l}=o.address();return t=`http://${Rr}:${l}${$a}`,{url:`http://${Rr}:${l}/`,host:Rr,port:l,close:()=>{let d=Promise.withResolvers();return o.close(p=>p?d.reject(p):d.resolve()),o.closeIdleConnections(),d.promise}}}var lo=["openid","email","profile","https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/calendar","https://www.googleapis.com/auth/gmail.modify","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/presentations","https://www.googleapis.com/auth/tasks","https://www.googleapis.com/auth/chat.messages","https://www.googleapis.com/auth/contacts.readonly","https://www.googleapis.com/auth/forms.body","https://www.googleapis.com/auth/forms.responses.readonly"];async function Da(n={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required for OAuth setup.");let s=Promise.withResolvers(),o=null,a=await Sn({clientId:e,clientSecret:t,scopes:lo,onTokens:async l=>{if(o===null){o=le().saveTokens(l).then(p=>(s.resolve(),p),p=>{throw s.reject(p),p}),await o;return}let d=await o;if(vt(l.id_token)!==d)throw new Error(`Setup already completed for ${d}. Use config(action="account_add") to add another account.`)}});process.stderr.write(`[${ce}] Google authorization required. Open ${a.url} in a browser to continue.
28
+ `);try{await s.promise}catch(l){throw wr(a),l}gn(a,n.graceMs)}var Wf=600*1e3;async function wn(n={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required to add an account.");let s=Promise.withResolvers(),o=null,a=await Sn({clientId:e,clientSecret:t,scopes:lo,onTokens:async u=>{if(o===null){o=le().saveTokens(u,{makePrimary:n.makePrimary}).then(y=>(s.resolve(y),y),y=>{throw s.reject(y),y}),await o;return}let f=await o;if(vt(u.id_token)!==f)throw new Error(`This add-account flow already completed for ${f}. Call config(action="account_add") again to add a different account.`)}}),l=Promise.withResolvers(),d=setTimeout(()=>l.reject(new Error("Add-account flow timed out before the Google consent completed.")),n.ttlMs??Wf);typeof d.unref=="function"&&d.unref();let p=Promise.race([s.promise,l.promise]);return p.then(()=>{clearTimeout(d),gn(a,n.graceMs)},()=>{clearTimeout(d),wr(a)}),{url:a.url,done:p}}var Gf=/^[a-zA-Z0-9._-]+$/;function Jf(n){let e=n.indexOf("--user");if(e===-1)return{};let t=n[e+1];return!t||t.startsWith("--")?{error:"--user requires a namespace value."}:Gf.test(t)?{user:t}:{error:'--user must contain only letters, digits, ".", "_" or "-".'}}async function La(){let n=await wn();process.stderr.write(`[workspace] Google authorization required. Open ${n.url} in a browser to continue.
29
29
  `);let e=await n.done;return process.stdout.write(`Added ${e}
30
- `),0}async function La(n){let{user:e,error:t}=Gf(n);if(t)return process.stderr.write(`${t}
31
- `),2;try{return e===void 0?await Da():await zf({...Wf(),uid:e,namespace:e,mode:"multi"},Da)}catch(s){return process.stderr.write(`auth failed: ${s instanceof Error?s.message:String(s)}
32
- `),1}}import{readFile as Th}from"node:fs/promises";import{basename as Rh,dirname as Eh,isAbsolute as vh,join as Qo,relative as xh,sep as Ch}from"node:path";import{fileURLToPath as Ah}from"node:url";var U=class extends Error{constructor(t,s,o,a){super(t);this.message=t;this.code=s;this.suggestion=o;this.details=a;this.name="WorkspaceMCPError"}toJSON(){return{error:this.name,code:this.code,message:this.message,suggestion:this.suggestion,details:this.details}}};function Na(n){if(!n||typeof n!="object")return n;let e={message:n.message,name:n.name,code:n.code};return n.status&&(e.status=n.status),n.response?.status&&(e.status=n.response.status),e}var Jf=new Set(["authorization","proxy-authorization","x-api-key","x-auth-token","cookie","set-cookie"]);function Gt(n){if(!(!n||typeof n!="object"))for(let e of Object.keys(n))Jf.has(e.toLowerCase())&&delete n[e]}function Ma(n,e=new WeakSet){if(!(!n||typeof n!="object")&&!e.has(n)){e.add(n),delete n.sensitive_token,delete n.internal_config,delete n.user_email,Gt(n.headers),Gt(n._headers),n.request&&(Gt(n.request.headers),Gt(n.request._headers)),n.config&&Gt(n.config.headers),n.response&&Gt(n.response.headers);for(let t of Object.keys(n))typeof n[t]=="object"&&n[t]!==null&&Ma(n[t],e)}}function Vf(n){return!n||typeof n!="object"?null:n.message?.includes("ECONNREFUSED")||n.message?.includes("ENOTFOUND")?new U("Cannot connect to the Google API","NETWORK_ERROR","Check your internet connection and try again"):null}function Yf(n){return!n||typeof n!="object"||!n.code?null:new U(n.message||"Unknown error occurred",String(n.code).toUpperCase(),"Check the error details and try again",Na(n))}function Zf(n){return!n||typeof n!="object"?new U("Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again"):new U(n.message||"Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again",Na(n))}function Xf(n){return n instanceof U?n:(Ma(n),Vf(n)||Yf(n)||Zf(n))}function Fa(n,e){if(!n||e.length===0)return null;let t=n.toLowerCase(),s=null,o=0,a=t.length,l=Math.max(0,a-1),d=new Int32Array(l),p=0;for(let u=0;u<l;u++){let f=t.charCodeAt(u)|t.charCodeAt(u+1)<<16,y=!1;for(let g=0;g<p;g++)if(d[g]===f){y=!0;break}y||(d[p++]=f)}for(let u of e){let f=u.toLowerCase();if(f.startsWith(t)||t.startsWith(f))return u;let y=f.length,g=Math.max(0,y-1);if(g===0)continue;let _=new Int32Array(g),S=0;for(let v=0;v<g;v++){let A=f.charCodeAt(v)|f.charCodeAt(v+1)<<16,C=!1;for(let x=0;x<S;x++)if(_[x]===A){C=!0;break}C||(_[S++]=A)}let E=0;for(let v=0;v<p;v++){let A=d[v];for(let C=0;C<S;C++)if(_[C]===A){E++;break}}let R=2*E/(p+S);R>o&&R>.4&&(o=R,s=u)}return s}function Ba(n){let e=`Error: ${n.message}`,t=n.suggestion||ep(n).join(`
30
+ `),0}async function Na(n){let{user:e,error:t}=Jf(n);if(t)return process.stderr.write(`${t}
31
+ `),2;try{return e===void 0?await La():await Hf({...zf(),uid:e,namespace:e,mode:"multi"},La)}catch(s){return process.stderr.write(`auth failed: ${s instanceof Error?s.message:String(s)}
32
+ `),1}}import{readFile as Rh}from"node:fs/promises";import{basename as Eh,dirname as xh,isAbsolute as vh,join as Ko,relative as Ch,sep as Ah}from"node:path";import{fileURLToPath as Ph}from"node:url";var U=class extends Error{constructor(t,s,o,a){super(t);this.message=t;this.code=s;this.suggestion=o;this.details=a;this.name="WorkspaceMCPError"}toJSON(){return{error:this.name,code:this.code,message:this.message,suggestion:this.suggestion,details:this.details}}};function Ma(n){if(!n||typeof n!="object")return n;let e={message:n.message,name:n.name,code:n.code};return n.status&&(e.status=n.status),n.response?.status&&(e.status=n.response.status),e}var Vf=new Set(["authorization","proxy-authorization","x-api-key","x-auth-token","cookie","set-cookie"]);function Jt(n){if(!(!n||typeof n!="object"))for(let e of Object.keys(n))Vf.has(e.toLowerCase())&&delete n[e]}function Fa(n,e=new WeakSet){if(!(!n||typeof n!="object")&&!e.has(n)){e.add(n),delete n.sensitive_token,delete n.internal_config,delete n.user_email,Jt(n.headers),Jt(n._headers),n.request&&(Jt(n.request.headers),Jt(n.request._headers)),n.config&&Jt(n.config.headers),n.response&&Jt(n.response.headers);for(let t of Object.keys(n))typeof n[t]=="object"&&n[t]!==null&&Fa(n[t],e)}}function Yf(n){return!n||typeof n!="object"?null:n.message?.includes("ECONNREFUSED")||n.message?.includes("ENOTFOUND")?new U("Cannot connect to the Google API","NETWORK_ERROR","Check your internet connection and try again"):null}function Zf(n){return!n||typeof n!="object"||!n.code?null:new U(n.message||"Unknown error occurred",String(n.code).toUpperCase(),"Check the error details and try again",Ma(n))}function Xf(n){return!n||typeof n!="object"?new U("Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again"):new U(n.message||"Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again",Ma(n))}function Qf(n){return n instanceof U?n:(Fa(n),Yf(n)||Zf(n)||Xf(n))}function Ba(n,e){if(!n||e.length===0)return null;let t=n.toLowerCase(),s=null,o=0,a=t.length,l=Math.max(0,a-1),d=new Int32Array(l),p=0;for(let u=0;u<l;u++){let f=t.charCodeAt(u)|t.charCodeAt(u+1)<<16,y=!1;for(let g=0;g<p;g++)if(d[g]===f){y=!0;break}y||(d[p++]=f)}for(let u of e){let f=u.toLowerCase();if(f.startsWith(t)||t.startsWith(f))return u;let y=f.length,g=Math.max(0,y-1);if(g===0)continue;let _=new Int32Array(g),S=0;for(let x=0;x<g;x++){let A=f.charCodeAt(x)|f.charCodeAt(x+1)<<16,C=!1;for(let v=0;v<S;v++)if(_[v]===A){C=!0;break}C||(_[S++]=A)}let E=0;for(let x=0;x<p;x++){let A=d[x];for(let C=0;C<S;C++)if(_[C]===A){E++;break}}let R=2*E/(p+S);R>o&&R>.4&&(o=R,s=u)}return s}function Ua(n){let e=`Error: ${n.message}`,t=n.suggestion||tp(n).join(`
33
33
  - `);return t&&(e+=`
34
34
 
35
35
  Suggestion: ${n.suggestion?t:`
36
36
  - ${t}`}`),n.details&&(e+=`
37
37
 
38
- Details: ${JSON.stringify(n.details,null,2)}`),e}var Qf={},Kf=["Review request parameters","Try again in a few moments"];function ep(n){return Qf[n.code]||Kf}function wn(n){return async(...e)=>{try{return await n(...e)}catch(t){throw Xf(t)}}}var uo=["status","setup_start","setup_reset","setup_complete","set","cache_clear","account_add","account_list","account_remove","account_set_default"],tp=uo.join(", ");async function lo(){let n=Ct(),{accounts:e,primary:t}=await le().listAccounts();return JSON.stringify({state:n,configured:n==="configured",accounts:e,primary:t})}function Re(n){return{content:[{type:"text",text:n}]}}function Ua(n){if(!n.account)throw new U(`${n.action} requires an account`,"VALIDATION_ERROR",'Pass account="<email>" (see config action="account_list")');return n.account}function qa(n){return wn(async()=>{switch(n.action){case"status":return Re(await lo());case"setup_start":return Re("Run `workspace auth` on the host to start the Google consent flow, then retry the tool. Stdio servers start this flow automatically on first run.");case"setup_reset":return await Oa(),Re(await lo());case"setup_complete":return await ot(),Re(await lo());case"set":return Re("No mutable runtime settings in M1. To update credentials, use setup_reset then restart the server.");case"cache_clear":return Re("No client-side cache to clear in M1.");case"account_list":{let{accounts:e,primary:t}=await le().listAccounts();return Re(JSON.stringify({accounts:e,primary:t}))}case"account_remove":{let e=Ua(n),{removed:t,newPrimary:s}=await le().removeAccount(e);return await ot(),Re(JSON.stringify({removed:t,primary:s}))}case"account_set_default":{let e=Ua(n);return await le().setPrimary(e),Re(JSON.stringify({primary:e.trim().toLowerCase()}))}case"account_add":{let e=n.value==="primary",t=hn();if(t!==void 0)return Re(JSON.stringify({open:null,next:`Google consent cannot be started over HTTP. On the host where this server runs, run \`workspace auth --user ${t}\` and open the URL it prints. Then call config(action="account_list") to confirm.`,default_account:e?'value="primary" is not available over HTTP and was ignored. Adding an account does not change your default; call config(action="account_set_default", account="<email>") once it appears in account_list.':'Adding an account does not change your default. Call config(action="account_set_default", account="<email>") to change it. (If you had no accounts at all, the first one becomes the default.)'}));let s=await Sn({makePrimary:e});return s.done.catch(()=>{}),Re(JSON.stringify({open:s.url,next:'Complete the Google consent in the browser, then call config(action="account_list") to confirm.'}))}default:throw new U(`Unsupported action: ${n.action}`,"VALIDATION_ERROR",`Valid actions: ${tp}`)}})()}import cp from"node:crypto";import{google as lp}from"googleapis";var rp=!1;function m(n){rp&&process.stderr.write(`[workspace] ${n}
39
- `)}var W={retryConfig:{retry:3,noResponseRetries:3,retryDelay:1e3,httpMethodsToRetry:["GET","HEAD","OPTIONS","DELETE","PUT"],statusCodesToRetry:[[429,429],[500,599]],onRetryAttempt:n=>{let e=n.config;m(`Retrying request to ${e.url}, attempt #${e.retryConfig?.currentRetryAttempt}`),m(`Error: ${n.message}`)}},timeout:3e4},Ay={...W,timeout:6e4};import{z as K}from"zod";import*as ja from"node:path";var _n=K.string().email("Invalid email format"),at=K.union([_n,K.array(_n)]),Oy=K.object({filePath:K.string().refine(n=>ja.isAbsolute(n),{message:"filePath must be an absolute path"}).describe('Absolute local filesystem path to the file to attach (e.g., "/Users/name/downloads/report.pdf"). Use gmail.downloadAttachment first to save an email attachment locally before referencing it here.'),filename:K.string().optional().describe("Display name for the attachment in the email. Defaults to the filename portion of filePath."),mimeType:K.string().optional().describe('MIME type of the attachment (e.g., "application/pdf"). Inferred from the file extension when omitted; falls back to "application/octet-stream".')}),Jt=K.string().refine(n=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})$/.test(n)?!isNaN(Date.parse(n)):!1,{message:"Invalid ISO 8601 datetime format. Expected format: YYYY-MM-DDTHH:mm:ss[.sss][Z|\xB1HH:mm]"}),Wa=K.string().regex(/^[a-zA-Z0-9_-]+$/,"Invalid document ID format. Document IDs should only contain letters, numbers, hyphens, and underscores"),ky=K.string().regex(/^https:\/\/(docs|drive|sheets|slides)\.google\.com\/.+\/d\/([a-zA-Z0-9_-]+)/,"Invalid Google Workspace URL format"),$y=K.string().min(1,"Folder name cannot be empty").max(255,"Folder name too long (max 255 characters)").refine(n=>!/[<>:"/\\|?*\x00-\x1F]/.test(n),"Folder name contains invalid characters"),Dy=K.union([K.literal("primary"),_n]),Ly=K.string().transform(n=>n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')),Ny=K.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100");function fo(n,e){return t=>{try{return n.parse(t),{success:!0}}catch(s){return s instanceof K.ZodError?{success:!1,error:s.issues[0].message}:{success:!1,error:e}}}}var My=fo(_n,"Invalid email format"),Fy=fo(Jt,"Invalid datetime format"),By=fo(Wa,"Invalid document ID");function ct(n){if(Wa.safeParse(n).success)return n;let e=n.match(/\/d\/([a-zA-Z0-9_-]+)/);if(e&&e[1])return e[1];throw new Error("Invalid document ID or URL")}import{z as Ga}from"zod";var np=Ga.string().refine(n=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isNaN(e)?!1:new Date(e).toISOString().slice(0,10)===n},{message:"Invalid date format. Expected YYYY-MM-DD"});function ze(n,e){return new Ga.ZodError([{code:"custom",message:e,path:n}])}function za(n,e){let t=!!e.dateTime,s=!!e.date;if(!t&&!s||t&&s)throw ze([n],`${n} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Ha(n,e){if(!e)return;let t=!!e.dateTime,s=!!e.date;if(!t&&!s||t&&s)throw ze([n],`${n} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Tn(n,e){e.dateTime&&Jt.parse(e.dateTime),e.date&&np.parse(e.date)}function sp(n){if(!n)throw ze(["workingLocationProperties"],'workingLocationProperties is required when eventType is "workingLocation"');if(n.type==="officeLocation"&&!n.officeLocation)throw ze(["workingLocationProperties","officeLocation"],'officeLocation is required when workingLocationProperties.type is "officeLocation"');if(n.type==="customLocation"&&!n.customLocation)throw ze(["workingLocationProperties","customLocation"],'customLocation is required when workingLocationProperties.type is "customLocation"')}function op(n,e){let t=new Date(`${n}T00:00:00Z`);return t.setUTCDate(t.getUTCDate()+e),t.toISOString().slice(0,10)}function ip(n){if(n.eventType==="workingLocation"&&n.start.date&&n.end.date){if(n.end.date<n.start.date)throw ze(["start","end"],"end.date must be on or after start.date");if(op(n.start.date,1)!==n.end.date)throw ze(["start","end"],"all-day workingLocation events must span exactly one day")}}function ap(n){if(za("start",n.start),za("end",n.end),Tn("start",n.start),Tn("end",n.end),(!n.eventType||n.eventType==="default")&&!n.summary)throw ze(["summary"],"summary is required for regular events");if((n.eventType==="focusTime"||n.eventType==="outOfOffice")&&(n.start.date||n.end.date))throw ze(["start","end"],`${n.eventType} events cannot be all-day events; use dateTime instead of date`);n.eventType==="workingLocation"&&(sp(n.workingLocationProperties),ip(n)),n.attendees&&at.parse(n.attendees)}function Ja(n){ap({summary:n.summary,start:n.start,end:n.end,attendees:n.attendees,eventType:n.eventType,workingLocationProperties:n.workingLocationProperties})}function Va(n){Ha("start",n.start),Ha("end",n.end),n.start&&Tn("start",n.start),n.end&&Tn("end",n.end),n.attendees&&at.parse(n.attendees)}import{z as Ya}from"zod";var Rn=class{constructor(e){this.authManager=e;this.primaryCalendarId=null;this.listCalendars=async()=>{m("listCalendars called");try{m("Getting calendar instance...");let e=await this.getCalendar();m("Making API call to calendar.calendarList.list()...");let t=await e.calendarList.list();m(`Found ${t.data.items?.length} calendars.`);let s=t.data.items||[];return m(`Returning calendar data: ${JSON.stringify(s.map(o=>({id:o?.id,summary:o?.summary})))}`),{content:[{type:"text",text:JSON.stringify(s.map(o=>({id:o?.id,summary:o?.summary})))}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`Error during calendar.list: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.createEvent=async e=>{let{calendarId:t,description:s,start:o,end:a,attendees:l,sendUpdates:d,addGoogleMeet:p,attachments:u,eventType:f,focusTimeProperties:y,outOfOfficeProperties:g,workingLocationProperties:_}=e,S={focusTime:"Focus Time",outOfOffice:"Out of Office",workingLocation:"Working Location"},E=e.summary??(f?S[f]:void 0);try{Ja(e)}catch(A){return this.createValidationErrorResponse(A)}let R=t||await this.getPrimaryCalendarId();m(`Creating event in calendar: ${R}`),m(`Event summary: ${E}`),f&&m(`Event type: ${f}`),s&&m(`Event description: ${s}`),m(`Event start: ${o.dateTime||o.date}`),m(`Event end: ${a.dateTime||a.date}`),m(`Event attendees: ${l?.join(", ")}`),p&&m("Adding Google Meet link"),u?.length&&m(`Attachments: ${u.length} file(s)`);let v=d;v===void 0&&(v=l?.length?"all":"none"),v&&m(`Sending updates: ${v}`);try{let A={summary:E,description:s,start:o,end:a,attendees:l?.map($=>({email:$}))};if(f&&f!=="default"&&(A.eventType=f),f==="focusTime")A.transparency="opaque",A.focusTimeProperties={chatStatus:y?.chatStatus??"doNotDisturb",autoDeclineMode:y?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},y?.declineMessage!==void 0&&(A.focusTimeProperties.declineMessage=y.declineMessage);else if(f==="outOfOffice")A.transparency="opaque",A.outOfOfficeProperties={autoDeclineMode:g?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},g?.declineMessage!==void 0&&(A.outOfOfficeProperties.declineMessage=g.declineMessage);else if(f==="workingLocation"){let $=_;A.visibility="public",A.transparency="transparent";let H={type:$.type};$.type==="homeOffice"?H.homeOffice={}:$.type==="officeLocation"&&$.officeLocation?H.officeLocation={buildingId:$.officeLocation.buildingId,label:$.officeLocation.label}:$.type==="customLocation"&&$.customLocation&&(H.customLocation={label:$.customLocation.label}),A.workingLocationProperties=H}let C=await this.getCalendar(),x={calendarId:R,requestBody:A,sendUpdates:v};this.applyMeetAndAttachments(A,x,p,u,{allowEmptyAttachments:!1});let k=await C.events.insert(x);return m(`Successfully created event: ${k.data.id}`),{content:[{type:"text",text:JSON.stringify(k.data)}]}}catch(A){let C=this.extractErrorMessage(A);return m(`Error during calendar.createEvent: ${C}`),{content:[{type:"text",text:JSON.stringify({error:C})}]}}};this.listEvents=async e=>{let{calendarId:t,timeMin:s=new Date().toISOString(),attendeeResponseStatus:o=["accepted","tentative","needsAction"],eventTypes:a}=e,l=e.timeMax;if(!l){let p=new Date;p.setDate(p.getDate()+30),l=p.toISOString()}let d=t||await this.getPrimaryCalendarId();m(`Listing events for calendar: ${d}`);try{let p=await this.getCalendar(),u={calendarId:d,timeMin:s,timeMax:l,singleEvents:!0,fields:"nextPageToken, items(id,summary,start,end,description,htmlLink,attendees,status,eventType,focusTimeProperties,outOfOfficeProperties,workingLocationProperties,attachments(fileId,fileUrl,title,mimeType,iconLink))"};a&&a.length>0&&(u.eventTypes=a),e.maxResults!==void 0&&(u.maxResults=e.maxResults),e.pageToken!==void 0&&(u.pageToken=e.pageToken);let f=await p.events.list(u),y=f.data.items?.filter(g=>g.status!=="cancelled"&&(!!g.summary||g.eventType&&g.eventType!=="default")).filter(g=>{if(!g.attendees||g.attendees.length===0||g.attendees.length===1&&g.attendees[0].self)return!0;let _=g.attendees.find(S=>S.self);return _?o.includes(_.responseStatus||"needsAction"):!0});return m(`Found ${y?.length} events after filtering.`),{content:[{type:"text",text:JSON.stringify({events:y??[],nextPageToken:f.data.nextPageToken??null})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.listEvents: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.getEvent=async e=>{let{eventId:t,calendarId:s}=e,o=s||await this.getPrimaryCalendarId();m(`Getting event ${t} from calendar: ${o}`);try{let l=await(await this.getCalendar()).events.get({calendarId:o,eventId:t});return m(`Successfully retrieved event: ${l.data.id}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.getEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.deleteEvent=async e=>{let{eventId:t,calendarId:s}=e,o=s||await this.getPrimaryCalendarId();m(`Deleting event ${t} from calendar: ${o}`);try{return await(await this.getCalendar()).events.delete({calendarId:o,eventId:t}),m(`Successfully deleted event: ${t}`),{content:[{type:"text",text:JSON.stringify({message:`Successfully deleted event ${t}`})}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.deleteEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.updateEvent=async e=>{let{eventId:t,calendarId:s,summary:o,description:a,start:l,end:d,attendees:p,addGoogleMeet:u,attachments:f}=e;try{Va(e)}catch(g){return this.createValidationErrorResponse(g)}let y=s||await this.getPrimaryCalendarId();m(`Updating event ${t} in calendar: ${y}`),u&&m("Adding Google Meet link"),f?.length&&m(`Attachments: ${f.length} file(s)`);try{let g=await this.getCalendar(),_={};o!==void 0&&(_.summary=o),a!==void 0&&(_.description=a),l&&(_.start=l),d&&(_.end=d),p!==void 0&&(_.attendees=p.map(R=>({email:R})));let S={calendarId:y,eventId:t,requestBody:_};this.applyMeetAndAttachments(_,S,u,f,{allowEmptyAttachments:!0});let E=await g.events.patch(S);return m(`Successfully updated event: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify(E.data)}]}}catch(g){let _=this.extractErrorMessage(g);return m(`Error during calendar.updateEvent: ${_}`),{content:[{type:"text",text:JSON.stringify({error:_})}]}}};this.respondToEvent=async e=>{let{eventId:t,calendarId:s,responseStatus:o,sendNotification:a=!0,responseMessage:l}=e,d=s||await this.getPrimaryCalendarId();m(`Responding to event ${t} in calendar: ${d} with status: ${o}`),l&&m(`Response message: ${l}`);try{let p=await this.getCalendar(),u=await p.events.get({calendarId:d,eventId:t});if(!u.data.attendees||u.data.attendees.length===0)return m("Event has no attendees"),{content:[{type:"text",text:JSON.stringify({error:"Event has no attendees"})}]};let f=u.data.attendees.find(g=>g.self===!0);if(!f)return m("User is not an attendee of this event"),{content:[{type:"text",text:JSON.stringify({error:"You are not an attendee of this event"})}]};f.responseStatus=o,l!==void 0&&(f.comment=l);let y=await p.events.patch({calendarId:d,eventId:t,sendNotifications:a,requestBody:{attendees:u.data.attendees}});return m(`Successfully responded to event: ${y.data.id} with status: ${o}`),{content:[{type:"text",text:JSON.stringify({eventId:y.data.id,summary:y.data.summary,responseStatus:o,message:`Successfully ${o} the meeting invitation${l?" with message":""}`})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.respondToEvent: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.findFreeTime=async e=>{let{attendees:t,timeMin:s,timeMax:o,duration:a}=e;try{Jt.parse(s),Jt.parse(o)}catch(l){return this.createValidationErrorResponse(l)}m(`Finding free time for attendees: ${t.join(", ")}`),m(`Time range: ${s} - ${o}`),m(`Duration: ${a} minutes`);try{let l=await this.getCalendar(),d=await Promise.all(t.map(async R=>R==="me"?{id:await this.getPrimaryCalendarId()}:{id:R})),p=await l.freebusy.query({requestBody:{items:d,timeMin:s,timeMax:o}}),u=Object.values(p.data.calendars||{}).flatMap(R=>R.busy||[]);if(u.length===0)return m("No busy times found, returning the start of the time range."),{content:[{type:"text",text:JSON.stringify({start:s,end:new Date(Date.parse(s)+a*6e4).toISOString()})}]};let f=u.filter(R=>R.start&&R.end).map(R=>({start:Date.parse(R.start),end:Date.parse(R.end)})).sort((R,v)=>R.start-v.start),y=[];for(let R of f)if(y.length===0)y.push(R);else{let v=y[y.length-1];R.start<=v.end?v.end=Math.max(v.end,R.end):y.push(R)}let g=Date.parse(s),_=Date.parse(o),S=a*6e4;if(y.length===0){let R=new Date(g+S);return m(`No busy times, found free time: ${s} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:s,end:R.toISOString()})}]}}if(g+S<=y[0].start){let R=new Date(g+S);return m(`Found free time: ${s} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:s,end:R.toISOString()})}]}}for(let R=0;R<y.length-1;R++){let v=y[R].end;if(y[R+1].start-v>=S){let C=new Date(v),x=new Date(v+S);return m(`Found free time: ${C.toISOString()} - ${x.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:C.toISOString(),end:x.toISOString()})}]}}}let E=y[y.length-1].end;if(E+S<=_){let R=new Date(E),v=new Date(E+S);return m(`Found free time: ${R.toISOString()} - ${v.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:R.toISOString(),end:v.toISOString()})}]}}return m("No available free time found"),{content:[{type:"text",text:JSON.stringify({error:"No available free time found"})}]}}catch(l){let d=l instanceof Error?l.message:String(l);return m(`Error during calendar.findFreeTime: ${d}`),{content:[{type:"text",text:JSON.stringify({error:d})}]}}}}applyMeetAndAttachments(e,t,s,o,a){s&&(e.conferenceData={createRequest:{requestId:cp.randomUUID(),conferenceSolutionKey:{type:"hangoutsMeet"}}},t.conferenceDataVersion=1),o&&(o.length>0||a?.allowEmptyAttachments)&&(e.attachments=o.map(l=>({fileUrl:l.fileUrl,title:l.title,mimeType:l.mimeType})),t.supportsAttachments=!0)}createValidationErrorResponse(e){let t=e instanceof Ya.ZodError?e.issues.map(o=>o.path.length?`${o.path.join(".")}: ${o.message}`:o.message).join("; "):e instanceof Error?e.message:"Validation failed",s="Please use strict ISO 8601 format with seconds and timezone. Examples: 2024-01-15T10:30:00Z (UTC) or 2024-01-15T10:30:00-05:00 (EST)";return e instanceof Ya.ZodError&&e.issues.some(o=>o.path.includes("attendees")||o.message.includes("email"))&&(s="Please ensure all attendee emails are in a valid format."),{content:[{type:"text",text:JSON.stringify({error:"Invalid input format",details:t,help:s})}]}}extractErrorMessage(e){let t=e?.response?.data?.error;if(t){let s=t.message??"Unknown Error",o=t.code?` (code ${t.code})`:"";if(t.errors?.length){let a=t.errors.map(l=>{let p=[[l.domain,l.locationType,l.location].filter(Boolean).join("."),l.reason].filter(Boolean).join(" ");return p?`${p}: ${l.message}`:l.message}).join("; ");return t.errors.length===1&&(s===t.errors[0].message||s.includes(t.errors[0].message??""))?`${a}${o}`:`${s}${o}: ${a}`}return`${s}${o}`}return e instanceof Error?e.message:String(e)}async getCalendar(){m("Getting authenticated client for calendar...");let e=await this.authManager.getAuthenticatedClient();m("Got auth client, creating calendar instance...");let t={...W,auth:e};return lp.calendar({version:"v3",...t})}async getPrimaryCalendarId(){if(this.primaryCalendarId)return this.primaryCalendarId;m("Getting primary calendar ID...");let s=(await(await this.getCalendar()).calendarList.list()).data.items?.find(o=>o.primary);return s&&s.id?(m(`Found primary calendar: ${s.id}`),this.primaryCalendarId=s.id,s.id):(m('No primary calendar found, defaulting to "primary"'),"primary")}};var up="Pass full: true for the complete payload, or raise max_chars up to 100000.",dp="Pass full: true for every item, or narrow the request; this listing returns one response with no cursor.",fp="Request another page with pageToken, or raise max_chars up to 100000.",He=()=>({hint:up}),Pe=n=>({items:n,hint:dp}),Ie=()=>({hint:fp}),Za={getSuggestions:Pe(100)},Xa={getText:He(),getMetadata:Pe(100),getImages:Pe(100),getSpeakerNotes:Pe(100)},Qa={get:He(),search:Ie(),listLabels:Pe(100),modify:He(),modifyThread:He()},Ka={search:Ie(),getComments:Ie(),findFolder:Pe(50)},ec={listSpaces:Ie(),findSpaceByName:Pe(50),getMessages:Ie(),listThreads:Ie()},tc={listCalendars:Pe(100),listEvents:Ie(),getEvent:He(),findFreeTime:Pe(50)},rc={listTaskLists:Ie(),listTasks:Ie()},nc={getUserProfile:He(),getMe:He(),getUserRelations:Pe(50)},sc={get:He(),listResponses:Ie(),getResponse:He()};import{AsyncLocalStorage as pp}from"node:async_hooks";var oc=new pp;function ic(n,e){return oc.run({account:n},e)}function ac(){return oc.getStore()?.account}var En=class{constructor(e=[]){this.scopes=e}async getAuthenticatedClient(){return le().getAuthenticatedClient(ac())}};var he=Number.POSITIVE_INFINITY,vn={nextPageToken:!0,next_page_token:!0,nextPageCursor:!0,pageToken:!0,page_token:!0,nextSyncToken:!0,syncToken:!0,continuationToken:!0,cursor:!0};function mp(n){let e=n.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return{value:JSON.parse(e)}}catch{return}}function dc(n,e,t){let s=Math.max(n-e,0);return`[Content truncated: showing ${e} of ${n} characters (${s} omitted). ${t}]`}function fc(n,e={}){if(n.full===!0)return{chars:he,items:he};let t=e.items??he,s=n.max_chars;if(s===void 0)return{chars:e.chars??2e4,items:t};if(typeof s!="number"||!Number.isInteger(s)||s<1||s>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return{chars:s,items:t}}function cc(n,e){return typeof e=="number"?`${n}[${e}]`:`${n}.${e}`}function lc(n,e,t="$"){let s=[],o=(l,d)=>{if(Array.isArray(l)){let p=e.items===he?l:l.slice(0,e.items);return p.length<l.length&&s.push({path:d,returned:p.length,total:l.length}),p.map((u,f)=>o(u,cc(d,f)))}if(typeof l=="string")return e.stringChars===he||l.length<=e.stringChars?l:`${l.slice(0,e.stringChars)}[+${l.length-e.stringChars} chars]`;if(l&&typeof l=="object"){let p={};for(let[u,f]of Object.entries(l))p[u]=vn[u]?f:o(f,cc(d,u));return p}return l};return{value:o(n,t),lists:s}}function po(n,e,t,s,o){let a={truncated:!0,total_characters:t,returned_characters:s,note:dc(t,s,o)};if(e.length>0&&(a.omitted_items=e),Array.isArray(n))return JSON.stringify({items:n,_truncation:a});let l="_truncation"in n?"_response_truncation":"_truncation";return JSON.stringify({...n,[l]:a})}function uc(n,e,t){let s=n.length;if(e.chars===he||s<=e.chars)return{text:n,truncated:!1,totalCharacters:s};let o=n.slice(0,e.chars);return{text:`${o}
38
+ Details: ${JSON.stringify(n.details,null,2)}`),e}var Kf={},ep=["Review request parameters","Try again in a few moments"];function tp(n){return Kf[n.code]||ep}function _n(n){return async(...e)=>{try{return await n(...e)}catch(t){throw Qf(t)}}}var fo=["status","setup_start","setup_reset","setup_complete","set","cache_clear","account_add","account_list","account_remove","account_set_default"],rp=fo.join(", ");async function uo(){let n=Ct(),{accounts:e,primary:t}=await le().listAccounts();return JSON.stringify({state:n,configured:n==="configured",accounts:e,primary:t})}function Re(n){return{content:[{type:"text",text:n}]}}function qa(n){if(!n.account)throw new U(`${n.action} requires an account`,"VALIDATION_ERROR",'Pass account="<email>" (see config action="account_list")');return n.account}function ja(n){return _n(async()=>{switch(n.action){case"status":return Re(await uo());case"setup_start":return Re(`Run \`${Gt()}\` on the host to start the Google consent flow, then retry the tool. Stdio servers start this flow automatically on first run.`);case"setup_reset":return await ka(),Re(await uo());case"setup_complete":return await ot(),Re(await uo());case"set":return Re("No mutable runtime settings in M1. To update credentials, use setup_reset then restart the server.");case"cache_clear":return Re("No client-side cache to clear in M1.");case"account_list":{let{accounts:e,primary:t}=await le().listAccounts();return Re(JSON.stringify({accounts:e,primary:t}))}case"account_remove":{let e=qa(n),{removed:t,newPrimary:s}=await le().removeAccount(e);return await ot(),Re(JSON.stringify({removed:t,primary:s}))}case"account_set_default":{let e=qa(n);return await le().setPrimary(e),Re(JSON.stringify({primary:e.trim().toLowerCase()}))}case"account_add":{let e=n.value==="primary",t=_r();if(t!==void 0)return Re(JSON.stringify({open:null,next:`Google consent cannot be started over HTTP. On the host where this server runs, run \`workspace auth --user ${t}\` and open the URL it prints. Then call config(action="account_list") to confirm.`,default_account:e?'value="primary" is not available over HTTP and was ignored. Adding an account does not change your default; call config(action="account_set_default", account="<email>") once it appears in account_list.':'Adding an account does not change your default. Call config(action="account_set_default", account="<email>") to change it. (If you had no accounts at all, the first one becomes the default.)'}));let s=await wn({makePrimary:e});return s.done.catch(()=>{}),Re(JSON.stringify({open:s.url,next:'Complete the Google consent in the browser, then call config(action="account_list") to confirm.'}))}default:throw new U(`Unsupported action: ${n.action}`,"VALIDATION_ERROR",`Valid actions: ${rp}`)}})()}import lp from"node:crypto";import{google as up}from"googleapis";var np=!1;function m(n){np&&process.stderr.write(`[workspace] ${n}
39
+ `)}var W={retryConfig:{retry:3,noResponseRetries:3,retryDelay:1e3,httpMethodsToRetry:["GET","HEAD","OPTIONS","DELETE","PUT"],statusCodesToRetry:[[429,429],[500,599]],onRetryAttempt:n=>{let e=n.config;m(`Retrying request to ${e.url}, attempt #${e.retryConfig?.currentRetryAttempt}`),m(`Error: ${n.message}`)}},timeout:3e4},Iy={...W,timeout:6e4};import{z as K}from"zod";import*as Wa from"node:path";var Tn=K.string().email("Invalid email format"),at=K.union([Tn,K.array(Tn)]),$y=K.object({filePath:K.string().refine(n=>Wa.isAbsolute(n),{message:"filePath must be an absolute path"}).describe('Absolute local filesystem path to the file to attach (e.g., "/Users/name/downloads/report.pdf"). Use gmail.downloadAttachment first to save an email attachment locally before referencing it here.'),filename:K.string().optional().describe("Display name for the attachment in the email. Defaults to the filename portion of filePath."),mimeType:K.string().optional().describe('MIME type of the attachment (e.g., "application/pdf"). Inferred from the file extension when omitted; falls back to "application/octet-stream".')}),Vt=K.string().refine(n=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})$/.test(n)?!isNaN(Date.parse(n)):!1,{message:"Invalid ISO 8601 datetime format. Expected format: YYYY-MM-DDTHH:mm:ss[.sss][Z|\xB1HH:mm]"}),za=K.string().regex(/^[a-zA-Z0-9_-]+$/,"Invalid document ID format. Document IDs should only contain letters, numbers, hyphens, and underscores"),Dy=K.string().regex(/^https:\/\/(docs|drive|sheets|slides)\.google\.com\/.+\/d\/([a-zA-Z0-9_-]+)/,"Invalid Google Workspace URL format"),Ly=K.string().min(1,"Folder name cannot be empty").max(255,"Folder name too long (max 255 characters)").refine(n=>!/[<>:"/\\|?*\x00-\x1F]/.test(n),"Folder name contains invalid characters"),Ny=K.union([K.literal("primary"),Tn]),My=K.string().transform(n=>n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')),Fy=K.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100");function po(n,e){return t=>{try{return n.parse(t),{success:!0}}catch(s){return s instanceof K.ZodError?{success:!1,error:s.issues[0].message}:{success:!1,error:e}}}}var By=po(Tn,"Invalid email format"),Uy=po(Vt,"Invalid datetime format"),qy=po(za,"Invalid document ID");function ct(n){if(za.safeParse(n).success)return n;let e=n.match(/\/d\/([a-zA-Z0-9_-]+)/);if(e&&e[1])return e[1];throw new Error("Invalid document ID or URL")}import{z as Ja}from"zod";var sp=Ja.string().refine(n=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isNaN(e)?!1:new Date(e).toISOString().slice(0,10)===n},{message:"Invalid date format. Expected YYYY-MM-DD"});function ze(n,e){return new Ja.ZodError([{code:"custom",message:e,path:n}])}function Ha(n,e){let t=!!e.dateTime,s=!!e.date;if(!t&&!s||t&&s)throw ze([n],`${n} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Ga(n,e){if(!e)return;let t=!!e.dateTime,s=!!e.date;if(!t&&!s||t&&s)throw ze([n],`${n} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Rn(n,e){e.dateTime&&Vt.parse(e.dateTime),e.date&&sp.parse(e.date)}function op(n){if(!n)throw ze(["workingLocationProperties"],'workingLocationProperties is required when eventType is "workingLocation"');if(n.type==="officeLocation"&&!n.officeLocation)throw ze(["workingLocationProperties","officeLocation"],'officeLocation is required when workingLocationProperties.type is "officeLocation"');if(n.type==="customLocation"&&!n.customLocation)throw ze(["workingLocationProperties","customLocation"],'customLocation is required when workingLocationProperties.type is "customLocation"')}function ip(n,e){let t=new Date(`${n}T00:00:00Z`);return t.setUTCDate(t.getUTCDate()+e),t.toISOString().slice(0,10)}function ap(n){if(n.eventType==="workingLocation"&&n.start.date&&n.end.date){if(n.end.date<n.start.date)throw ze(["start","end"],"end.date must be on or after start.date");if(ip(n.start.date,1)!==n.end.date)throw ze(["start","end"],"all-day workingLocation events must span exactly one day")}}function cp(n){if(Ha("start",n.start),Ha("end",n.end),Rn("start",n.start),Rn("end",n.end),(!n.eventType||n.eventType==="default")&&!n.summary)throw ze(["summary"],"summary is required for regular events");if((n.eventType==="focusTime"||n.eventType==="outOfOffice")&&(n.start.date||n.end.date))throw ze(["start","end"],`${n.eventType} events cannot be all-day events; use dateTime instead of date`);n.eventType==="workingLocation"&&(op(n.workingLocationProperties),ap(n)),n.attendees&&at.parse(n.attendees)}function Va(n){cp({summary:n.summary,start:n.start,end:n.end,attendees:n.attendees,eventType:n.eventType,workingLocationProperties:n.workingLocationProperties})}function Ya(n){Ga("start",n.start),Ga("end",n.end),n.start&&Rn("start",n.start),n.end&&Rn("end",n.end),n.attendees&&at.parse(n.attendees)}import{z as Za}from"zod";var En=class{constructor(e){this.authManager=e;this.primaryCalendarId=null;this.listCalendars=async()=>{m("listCalendars called");try{m("Getting calendar instance...");let e=await this.getCalendar();m("Making API call to calendar.calendarList.list()...");let t=await e.calendarList.list();m(`Found ${t.data.items?.length} calendars.`);let s=t.data.items||[];return m(`Returning calendar data: ${JSON.stringify(s.map(o=>({id:o?.id,summary:o?.summary})))}`),{content:[{type:"text",text:JSON.stringify(s.map(o=>({id:o?.id,summary:o?.summary})))}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`Error during calendar.list: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.createEvent=async e=>{let{calendarId:t,description:s,start:o,end:a,attendees:l,sendUpdates:d,addGoogleMeet:p,attachments:u,eventType:f,focusTimeProperties:y,outOfOfficeProperties:g,workingLocationProperties:_}=e,S={focusTime:"Focus Time",outOfOffice:"Out of Office",workingLocation:"Working Location"},E=e.summary??(f?S[f]:void 0);try{Va(e)}catch(A){return this.createValidationErrorResponse(A)}let R=t||await this.getPrimaryCalendarId();m(`Creating event in calendar: ${R}`),m(`Event summary: ${E}`),f&&m(`Event type: ${f}`),s&&m(`Event description: ${s}`),m(`Event start: ${o.dateTime||o.date}`),m(`Event end: ${a.dateTime||a.date}`),m(`Event attendees: ${l?.join(", ")}`),p&&m("Adding Google Meet link"),u?.length&&m(`Attachments: ${u.length} file(s)`);let x=d;x===void 0&&(x=l?.length?"all":"none"),x&&m(`Sending updates: ${x}`);try{let A={summary:E,description:s,start:o,end:a,attendees:l?.map($=>({email:$}))};if(f&&f!=="default"&&(A.eventType=f),f==="focusTime")A.transparency="opaque",A.focusTimeProperties={chatStatus:y?.chatStatus??"doNotDisturb",autoDeclineMode:y?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},y?.declineMessage!==void 0&&(A.focusTimeProperties.declineMessage=y.declineMessage);else if(f==="outOfOffice")A.transparency="opaque",A.outOfOfficeProperties={autoDeclineMode:g?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},g?.declineMessage!==void 0&&(A.outOfOfficeProperties.declineMessage=g.declineMessage);else if(f==="workingLocation"){let $=_;A.visibility="public",A.transparency="transparent";let H={type:$.type};$.type==="homeOffice"?H.homeOffice={}:$.type==="officeLocation"&&$.officeLocation?H.officeLocation={buildingId:$.officeLocation.buildingId,label:$.officeLocation.label}:$.type==="customLocation"&&$.customLocation&&(H.customLocation={label:$.customLocation.label}),A.workingLocationProperties=H}let C=await this.getCalendar(),v={calendarId:R,requestBody:A,sendUpdates:x};this.applyMeetAndAttachments(A,v,p,u,{allowEmptyAttachments:!1});let k=await C.events.insert(v);return m(`Successfully created event: ${k.data.id}`),{content:[{type:"text",text:JSON.stringify(k.data)}]}}catch(A){let C=this.extractErrorMessage(A);return m(`Error during calendar.createEvent: ${C}`),{content:[{type:"text",text:JSON.stringify({error:C})}]}}};this.listEvents=async e=>{let{calendarId:t,timeMin:s=new Date().toISOString(),attendeeResponseStatus:o=["accepted","tentative","needsAction"],eventTypes:a}=e,l=e.timeMax;if(!l){let p=new Date;p.setDate(p.getDate()+30),l=p.toISOString()}let d=t||await this.getPrimaryCalendarId();m(`Listing events for calendar: ${d}`);try{let p=await this.getCalendar(),u={calendarId:d,timeMin:s,timeMax:l,singleEvents:!0,fields:"nextPageToken, items(id,summary,start,end,description,htmlLink,attendees,status,eventType,focusTimeProperties,outOfOfficeProperties,workingLocationProperties,attachments(fileId,fileUrl,title,mimeType,iconLink))"};a&&a.length>0&&(u.eventTypes=a),e.maxResults!==void 0&&(u.maxResults=e.maxResults),e.pageToken!==void 0&&(u.pageToken=e.pageToken);let f=await p.events.list(u),y=f.data.items?.filter(g=>g.status!=="cancelled"&&(!!g.summary||g.eventType&&g.eventType!=="default")).filter(g=>{if(!g.attendees||g.attendees.length===0||g.attendees.length===1&&g.attendees[0].self)return!0;let _=g.attendees.find(S=>S.self);return _?o.includes(_.responseStatus||"needsAction"):!0});return m(`Found ${y?.length} events after filtering.`),{content:[{type:"text",text:JSON.stringify({events:y??[],nextPageToken:f.data.nextPageToken??null})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.listEvents: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.getEvent=async e=>{let{eventId:t,calendarId:s}=e,o=s||await this.getPrimaryCalendarId();m(`Getting event ${t} from calendar: ${o}`);try{let l=await(await this.getCalendar()).events.get({calendarId:o,eventId:t});return m(`Successfully retrieved event: ${l.data.id}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.getEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.deleteEvent=async e=>{let{eventId:t,calendarId:s}=e,o=s||await this.getPrimaryCalendarId();m(`Deleting event ${t} from calendar: ${o}`);try{return await(await this.getCalendar()).events.delete({calendarId:o,eventId:t}),m(`Successfully deleted event: ${t}`),{content:[{type:"text",text:JSON.stringify({message:`Successfully deleted event ${t}`})}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.deleteEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.updateEvent=async e=>{let{eventId:t,calendarId:s,summary:o,description:a,start:l,end:d,attendees:p,addGoogleMeet:u,attachments:f}=e;try{Ya(e)}catch(g){return this.createValidationErrorResponse(g)}let y=s||await this.getPrimaryCalendarId();m(`Updating event ${t} in calendar: ${y}`),u&&m("Adding Google Meet link"),f?.length&&m(`Attachments: ${f.length} file(s)`);try{let g=await this.getCalendar(),_={};o!==void 0&&(_.summary=o),a!==void 0&&(_.description=a),l&&(_.start=l),d&&(_.end=d),p!==void 0&&(_.attendees=p.map(R=>({email:R})));let S={calendarId:y,eventId:t,requestBody:_};this.applyMeetAndAttachments(_,S,u,f,{allowEmptyAttachments:!0});let E=await g.events.patch(S);return m(`Successfully updated event: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify(E.data)}]}}catch(g){let _=this.extractErrorMessage(g);return m(`Error during calendar.updateEvent: ${_}`),{content:[{type:"text",text:JSON.stringify({error:_})}]}}};this.respondToEvent=async e=>{let{eventId:t,calendarId:s,responseStatus:o,sendNotification:a=!0,responseMessage:l}=e,d=s||await this.getPrimaryCalendarId();m(`Responding to event ${t} in calendar: ${d} with status: ${o}`),l&&m(`Response message: ${l}`);try{let p=await this.getCalendar(),u=await p.events.get({calendarId:d,eventId:t});if(!u.data.attendees||u.data.attendees.length===0)return m("Event has no attendees"),{content:[{type:"text",text:JSON.stringify({error:"Event has no attendees"})}]};let f=u.data.attendees.find(g=>g.self===!0);if(!f)return m("User is not an attendee of this event"),{content:[{type:"text",text:JSON.stringify({error:"You are not an attendee of this event"})}]};f.responseStatus=o,l!==void 0&&(f.comment=l);let y=await p.events.patch({calendarId:d,eventId:t,sendNotifications:a,requestBody:{attendees:u.data.attendees}});return m(`Successfully responded to event: ${y.data.id} with status: ${o}`),{content:[{type:"text",text:JSON.stringify({eventId:y.data.id,summary:y.data.summary,responseStatus:o,message:`Successfully ${o} the meeting invitation${l?" with message":""}`})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.respondToEvent: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.findFreeTime=async e=>{let{attendees:t,timeMin:s,timeMax:o,duration:a}=e;try{Vt.parse(s),Vt.parse(o)}catch(l){return this.createValidationErrorResponse(l)}m(`Finding free time for attendees: ${t.join(", ")}`),m(`Time range: ${s} - ${o}`),m(`Duration: ${a} minutes`);try{let l=await this.getCalendar(),d=await Promise.all(t.map(async R=>R==="me"?{id:await this.getPrimaryCalendarId()}:{id:R})),p=await l.freebusy.query({requestBody:{items:d,timeMin:s,timeMax:o}}),u=Object.values(p.data.calendars||{}).flatMap(R=>R.busy||[]);if(u.length===0)return m("No busy times found, returning the start of the time range."),{content:[{type:"text",text:JSON.stringify({start:s,end:new Date(Date.parse(s)+a*6e4).toISOString()})}]};let f=u.filter(R=>R.start&&R.end).map(R=>({start:Date.parse(R.start),end:Date.parse(R.end)})).sort((R,x)=>R.start-x.start),y=[];for(let R of f)if(y.length===0)y.push(R);else{let x=y[y.length-1];R.start<=x.end?x.end=Math.max(x.end,R.end):y.push(R)}let g=Date.parse(s),_=Date.parse(o),S=a*6e4;if(y.length===0){let R=new Date(g+S);return m(`No busy times, found free time: ${s} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:s,end:R.toISOString()})}]}}if(g+S<=y[0].start){let R=new Date(g+S);return m(`Found free time: ${s} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:s,end:R.toISOString()})}]}}for(let R=0;R<y.length-1;R++){let x=y[R].end;if(y[R+1].start-x>=S){let C=new Date(x),v=new Date(x+S);return m(`Found free time: ${C.toISOString()} - ${v.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:C.toISOString(),end:v.toISOString()})}]}}}let E=y[y.length-1].end;if(E+S<=_){let R=new Date(E),x=new Date(E+S);return m(`Found free time: ${R.toISOString()} - ${x.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:R.toISOString(),end:x.toISOString()})}]}}return m("No available free time found"),{content:[{type:"text",text:JSON.stringify({error:"No available free time found"})}]}}catch(l){let d=l instanceof Error?l.message:String(l);return m(`Error during calendar.findFreeTime: ${d}`),{content:[{type:"text",text:JSON.stringify({error:d})}]}}}}applyMeetAndAttachments(e,t,s,o,a){s&&(e.conferenceData={createRequest:{requestId:lp.randomUUID(),conferenceSolutionKey:{type:"hangoutsMeet"}}},t.conferenceDataVersion=1),o&&(o.length>0||a?.allowEmptyAttachments)&&(e.attachments=o.map(l=>({fileUrl:l.fileUrl,title:l.title,mimeType:l.mimeType})),t.supportsAttachments=!0)}createValidationErrorResponse(e){let t=e instanceof Za.ZodError?e.issues.map(o=>o.path.length?`${o.path.join(".")}: ${o.message}`:o.message).join("; "):e instanceof Error?e.message:"Validation failed",s="Please use strict ISO 8601 format with seconds and timezone. Examples: 2024-01-15T10:30:00Z (UTC) or 2024-01-15T10:30:00-05:00 (EST)";return e instanceof Za.ZodError&&e.issues.some(o=>o.path.includes("attendees")||o.message.includes("email"))&&(s="Please ensure all attendee emails are in a valid format."),{content:[{type:"text",text:JSON.stringify({error:"Invalid input format",details:t,help:s})}]}}extractErrorMessage(e){let t=e?.response?.data?.error;if(t){let s=t.message??"Unknown Error",o=t.code?` (code ${t.code})`:"";if(t.errors?.length){let a=t.errors.map(l=>{let p=[[l.domain,l.locationType,l.location].filter(Boolean).join("."),l.reason].filter(Boolean).join(" ");return p?`${p}: ${l.message}`:l.message}).join("; ");return t.errors.length===1&&(s===t.errors[0].message||s.includes(t.errors[0].message??""))?`${a}${o}`:`${s}${o}: ${a}`}return`${s}${o}`}return e instanceof Error?e.message:String(e)}async getCalendar(){m("Getting authenticated client for calendar...");let e=await this.authManager.getAuthenticatedClient();m("Got auth client, creating calendar instance...");let t={...W,auth:e};return up.calendar({version:"v3",...t})}async getPrimaryCalendarId(){if(this.primaryCalendarId)return this.primaryCalendarId;m("Getting primary calendar ID...");let s=(await(await this.getCalendar()).calendarList.list()).data.items?.find(o=>o.primary);return s&&s.id?(m(`Found primary calendar: ${s.id}`),this.primaryCalendarId=s.id,s.id):(m('No primary calendar found, defaulting to "primary"'),"primary")}};var dp="Pass full: true for the complete payload, or raise max_chars up to 100000.",fp="Pass full: true for every item, or narrow the request; this listing returns one response with no cursor.",pp="Request another page with pageToken, or raise max_chars up to 100000.",He=()=>({hint:dp}),Pe=n=>({items:n,hint:fp}),Ie=()=>({hint:pp}),Xa={getSuggestions:Pe(100)},Qa={getText:He(),getMetadata:Pe(100),getImages:Pe(100),getSpeakerNotes:Pe(100)},Ka={get:He(),search:Ie(),listLabels:Pe(100),modify:He(),modifyThread:He()},ec={search:Ie(),getComments:Ie(),findFolder:Pe(50)},tc={listSpaces:Ie(),findSpaceByName:Pe(50),getMessages:Ie(),listThreads:Ie()},rc={listCalendars:Pe(100),listEvents:Ie(),getEvent:He(),findFreeTime:Pe(50)},nc={listTaskLists:Ie(),listTasks:Ie()},sc={getUserProfile:He(),getMe:He(),getUserRelations:Pe(50)},oc={get:He(),listResponses:Ie(),getResponse:He()};import{AsyncLocalStorage as mp}from"node:async_hooks";var ic=new mp;function ac(n,e){return ic.run({account:n},e)}function cc(){return ic.getStore()?.account}var xn=class{constructor(e=[]){this.scopes=e}async getAuthenticatedClient(){return le().getAuthenticatedClient(cc())}};var he=Number.POSITIVE_INFINITY,vn={nextPageToken:!0,next_page_token:!0,nextPageCursor:!0,pageToken:!0,page_token:!0,nextSyncToken:!0,syncToken:!0,continuationToken:!0,cursor:!0};function hp(n){let e=n.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return{value:JSON.parse(e)}}catch{return}}function fc(n,e,t){let s=Math.max(n-e,0);return`[Content truncated: showing ${e} of ${n} characters (${s} omitted). ${t}]`}function pc(n,e={}){if(n.full===!0)return{chars:he,items:he};let t=e.items??he,s=n.max_chars;if(s===void 0)return{chars:e.chars??2e4,items:t};if(typeof s!="number"||!Number.isInteger(s)||s<1||s>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return{chars:s,items:t}}function lc(n,e){return typeof e=="number"?`${n}[${e}]`:`${n}.${e}`}function uc(n,e,t="$"){let s=[],o=(l,d)=>{if(Array.isArray(l)){let p=e.items===he?l:l.slice(0,e.items);return p.length<l.length&&s.push({path:d,returned:p.length,total:l.length}),p.map((u,f)=>o(u,lc(d,f)))}if(typeof l=="string")return e.stringChars===he||l.length<=e.stringChars?l:`${l.slice(0,e.stringChars)}[+${l.length-e.stringChars} chars]`;if(l&&typeof l=="object"){let p={};for(let[u,f]of Object.entries(l))p[u]=vn[u]?f:o(f,lc(d,u));return p}return l};return{value:o(n,t),lists:s}}function mo(n,e,t,s,o){let a={truncated:!0,total_characters:t,returned_characters:s,note:fc(t,s,o)};if(e.length>0&&(a.omitted_items=e),Array.isArray(n))return JSON.stringify({items:n,_truncation:a});let l="_truncation"in n?"_response_truncation":"_truncation";return JSON.stringify({...n,[l]:a})}function dc(n,e,t){let s=n.length;if(e.chars===he||s<=e.chars)return{text:n,truncated:!1,totalCharacters:s};let o=n.slice(0,e.chars);return{text:`${o}
40
40
 
41
- ${dc(s,o.length,t)}`,truncated:!0,totalCharacters:s}}function hp(n,e,t){let s=n.length;if(e.chars===he&&e.items===he)return{text:n,truncated:!1,totalCharacters:s};let o=mp(n);if(!o)return uc(n,e,t);let a=e.items===he?[he,1,0]:[e.items,Math.max(1,Math.floor(e.items/2)),1,0],l=[he,4e3,1e3,256,64],d=lc(o.value,{items:0,stringChars:64});for(let u of a)for(let f of l){let y=lc(o.value,{items:u,stringChars:f});if(y.lists.length===0&&f===he){if(s<=e.chars)return{text:n,truncated:!1,totalCharacters:s};continue}d=y;let _=JSON.stringify(y.value)??"",S=po(y.value,y.lists,s,_.length,t);if(S.length<=e.chars)return{text:S,truncated:!0,totalCharacters:s}}let p=gp(d.value,d.lists,s,t,e.chars);return p?{text:p,truncated:!0,totalCharacters:s}:uc(n,e,t)}function gp(n,e,t,s,o){let a=Array.isArray(n)?[["items",n]]:Object.entries(n);if(a.length===0)return;let l=[...a.filter(([u])=>vn[u]),...a.filter(([u])=>!vn[u])],d={};for(let[u,f]of l){let y={...d,[u]:f};(po(y,e,t,JSON.stringify(y).length,s).length<=o||vn[u])&&(d[u]=f)}let p=JSON.stringify(d)??"";return po(d,e,t,p.length,s)}function pc(n,e,t){if(n.isError)return n;let s=!1,o=n.content.map(a=>{if(a.type!=="text")return a;let l=hp(a.text,e,t);return l.truncated?(s=!0,{...a,text:l.text}):a});return s?{...n,content:o}:n}var yp=20,mc=100,bp="Pass full: true for the complete payload, or raise max_chars up to 100000.",Sp=["max_chars","full"];function wp(n,e){if(n===void 0)return yp;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n))throw new U(`${e} must be an integer`,"VALIDATION_ERROR",`Use an integer from 1 to ${mc}`);return Math.min(Math.max(n,1),mc)}function _p(n,e,t){let s={...e},o=t?.[n];return o&&(s[o]=wp(s[o],o)),s}function z(n,e,t={}){let s=t.noAuth?new n:new n(new En(fn));return function(a){return wn(async()=>{let{action:l,account:d,...p}=a;if(!e.includes(l))throw new U(`Unknown action: ${l}`,"VALIDATION_ERROR",`Valid actions: ${e.join(", ")}`);let u=_p(l,p,t.pagination),f=t.bounds?.[l];if(t.bounds)for(let S of Sp)delete u[S];let y=f?fc(p,f):void 0,g=s[l],_=await ic(d,()=>g(u));return!f||!y?_:pc(_,y,f.hint??bp)})()}}var xn=["listCalendars","createEvent","listEvents","getEvent","deleteEvent","updateEvent","respondToEvent","findFreeTime"],hc=z(Rn,xn,{pagination:{listEvents:"maxResults"},bounds:tc});import{google as gc}from"googleapis";var Cn=class{constructor(e){this.authManager=e;this.listSpaces=async({pageSize:e,pageToken:t}={})=>{m("Listing chat spaces");try{let o=await(await this.getChatClient()).spaces.list({...e!==void 0&&{pageSize:e},...t!==void 0&&{pageToken:t}}),a=o.data.spaces||[];return m(`Successfully listed ${a.length} chat spaces.`),{content:[{type:"text",text:JSON.stringify({spaces:a,nextPageToken:o.data.nextPageToken??null})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during chat.listSpaces: ${o}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing chat spaces.",details:o})}]}}};this.sendMessage=async({spaceName:e,message:t,threadName:s})=>{m(`Sending message to space: ${e}${s?` in thread: ${s}`:""}`);try{let a=await(await this.getChatClient()).spaces.messages.create({parent:e,messageReplyOption:s?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:s?{name:s}:void 0}});return m(`Successfully sent message to space: ${e}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.sendMessage: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the message.",details:a})}]}}};this.findSpaceByName=async({displayName:e})=>{m(`Finding space with display name: ${e}`);try{let t=await this.getChatClient(),s,o=[];do{let l=await t.spaces.list({pageToken:s}),d=l.data.spaces||[];o=o.concat(d),s=l.data.nextPageToken||void 0}while(s);let a=o.filter(l=>l.displayName===e);return a.length>0?(m(`Found ${a.length} space(s) with display name: ${e}`),{content:[{type:"text",text:JSON.stringify(a)}]}):(m(`No space found with display name: ${e}`),{content:[{type:"text",text:JSON.stringify({error:`No space found with display name: ${e}`})}]})}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during chat.findSpaceByName: ${s}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the space.",details:s})}]}}};this.getMessages=async({spaceName:e,unreadOnly:t,pageSize:s,pageToken:o,orderBy:a,threadName:l})=>{m(`Listing messages for space: ${e}`);try{let d=await this.getChatClient(),p=[];if(l&&p.push(`thread.name = "${l}"`),t){let E=(await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"metadata"})).data.metadata?.sources?.find(k=>k.type==="PROFILE")?.id;if(!E)throw new Error("Could not determine user ID.");let R=`users/${E}`,x=((await d.spaces.members.list({parent:e})).data.memberships||[]).find(k=>k.member?.name===R)?.lastReadTime;x?p.push(`createTime > "${x}"`):m(`No last read time found for user in space: ${e}`)}let u=p.join(" AND "),f=await d.spaces.messages.list({parent:e,filter:u||void 0,pageSize:s,pageToken:o,orderBy:a}),y=f.data.messages||[],g=t?`Successfully listed ${y.length} unread messages for space: ${e}`:`Successfully listed ${y.length} messages for space: ${e}`;return m(g),{content:[{type:"text",text:JSON.stringify({messages:y,nextPageToken:f.data.nextPageToken})}]}}catch(d){let p=d instanceof Error?d.message:String(d);return m(`Error during chat.getMessages: ${p}`),d instanceof Error&&d.stack&&m(`Stack trace: ${d.stack}`),m(`Full error object: ${JSON.stringify(d,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing messages.",details:p})}]}}};this.sendDm=async({email:e,message:t,threadName:s})=>{m(`chat.sendDm called with: email=${e}, message=${t}${s?`, threadName=${s}`:""}`);try{let a=(await this._setupDmSpace(e)).name;if(!a)throw new Error("Could not determine the space name for the DM.");let d=await(await this.getChatClient()).spaces.messages.create({parent:a,messageReplyOption:s?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:s?{name:s}:void 0}});return m(`Successfully sent DM to: ${e}`),{content:[{type:"text",text:JSON.stringify(d.data)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.sendDm: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the DM.",details:a})}]}}};this.findDmByEmail=async({email:e})=>{m(`Finding DM space with user: ${e}`);try{let t=await this._setupDmSpace(e);return m(`Found or created DM space: ${t.name}`),{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during chat.findDmByEmail: ${s}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the DM space.",details:s})}]}}};this.listThreads=async({spaceName:e,pageSize:t,pageToken:s})=>{m(`Listing threads for space: ${e}`);try{let a=await(await this.getChatClient()).spaces.messages.list({parent:e,pageSize:t,pageToken:s,orderBy:"createTime desc"}),l=a.data.messages||[],d=[],p=new Set;for(let u of l)u.thread?.name&&!p.has(u.thread.name)&&(d.push(u),p.add(u.thread.name));return m(`Successfully listed ${d.length} threads for space: ${e}`),{content:[{type:"text",text:JSON.stringify({threads:d,nextPageToken:a.data.nextPageToken})}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.listThreads: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing threads.",details:a})}]}}};this.setUpSpace=async({displayName:e,userNames:t})=>{m(`Creating space with display name: ${e}`);try{let s=t.map(l=>({member:{name:l,type:"HUMAN"}})),a=await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"SPACE",displayName:e},memberships:s}});return m(`Successfully created space: ${a.data.name}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during chat.createSpace: ${o}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while creating the space.",details:o})}]}}}}async getChatClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return gc.chat({version:"v1",...t})}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return gc.people({version:"v1",...t})}async _setupDmSpace(e){let t={name:`users/${e}`,type:"HUMAN"},a=(await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"DIRECT_MESSAGE"},memberships:[{member:t}]}})).data;if(!a)throw new Error("Could not find or create a DM space.");return a}};var An=["listSpaces","sendMessage","findSpaceByName","getMessages","sendDm","findDmByEmail","listThreads","setUpSpace"],yc=z(Cn,An,{pagination:{listSpaces:"pageSize",getMessages:"pageSize",listThreads:"pageSize"},bounds:ec});import{google as Ep}from"googleapis";var Tp=/\/d\/([a-zA-Z0-9-_]+)/;function F(n){if(m(`[IdUtils] Attempting to extract doc ID from URL: ${n}`),!n||typeof n!="string"){m("[IdUtils] Invalid input: URL is null or not a string.");return}let e=n.match(Tp);if(e&&e[1]){let t=e[1];return m(`[IdUtils] Successfully extracted doc ID: ${t}`),t}m("[IdUtils] Could not extract doc ID from URL.")}var Rp=Number.POSITIVE_INFINITY;function Vt(n,e,t){return`[Content truncated: showing ${e} of ${n} characters (${n-e} omitted). ${t}]`}function mo(n,e){if(e===!0)return Rp;if(n===void 0)return 2e4;if(typeof n!="number"||!Number.isInteger(n)||n<1||n>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return n}function bc(n,e,t){let s=n.length;return s<=e?{text:n,truncated:!1,totalCharacters:s,returnedCharacters:s}:{text:`${n.slice(0,e)}
41
+ ${fc(s,o.length,t)}`,truncated:!0,totalCharacters:s}}function gp(n,e,t){let s=n.length;if(e.chars===he&&e.items===he)return{text:n,truncated:!1,totalCharacters:s};let o=hp(n);if(!o)return dc(n,e,t);let a=e.items===he?[he,1,0]:[e.items,Math.max(1,Math.floor(e.items/2)),1,0],l=[he,4e3,1e3,256,64],d=uc(o.value,{items:0,stringChars:64});for(let u of a)for(let f of l){let y=uc(o.value,{items:u,stringChars:f});if(y.lists.length===0&&f===he){if(s<=e.chars)return{text:n,truncated:!1,totalCharacters:s};continue}d=y;let _=JSON.stringify(y.value)??"",S=mo(y.value,y.lists,s,_.length,t);if(S.length<=e.chars)return{text:S,truncated:!0,totalCharacters:s}}let p=yp(d.value,d.lists,s,t,e.chars);return p?{text:p,truncated:!0,totalCharacters:s}:dc(n,e,t)}function yp(n,e,t,s,o){let a=Array.isArray(n)?[["items",n]]:Object.entries(n);if(a.length===0)return;let l=[...a.filter(([u])=>vn[u]),...a.filter(([u])=>!vn[u])],d={};for(let[u,f]of l){let y={...d,[u]:f};(mo(y,e,t,JSON.stringify(y).length,s).length<=o||vn[u])&&(d[u]=f)}let p=JSON.stringify(d)??"";return mo(d,e,t,p.length,s)}function mc(n,e,t){if(n.isError)return n;let s=!1,o=n.content.map(a=>{if(a.type!=="text")return a;let l=gp(a.text,e,t);return l.truncated?(s=!0,{...a,text:l.text}):a});return s?{...n,content:o}:n}var bp=20,hc=100,Sp="Pass full: true for the complete payload, or raise max_chars up to 100000.",wp=["max_chars","full"];function _p(n,e){if(n===void 0)return bp;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n))throw new U(`${e} must be an integer`,"VALIDATION_ERROR",`Use an integer from 1 to ${hc}`);return Math.min(Math.max(n,1),hc)}function Tp(n,e,t){let s={...e},o=t?.[n];return o&&(s[o]=_p(s[o],o)),s}function z(n,e,t={}){let s=t.noAuth?new n:new n(new xn(mn));return function(a){return _n(async()=>{let{action:l,account:d,...p}=a;if(!e.includes(l))throw new U(`Unknown action: ${l}`,"VALIDATION_ERROR",`Valid actions: ${e.join(", ")}`);let u=Tp(l,p,t.pagination),f=t.bounds?.[l];if(t.bounds)for(let S of wp)delete u[S];let y=f?pc(p,f):void 0,g=s[l],_=await ac(d,()=>g(u));return!f||!y?_:mc(_,y,f.hint??Sp)})()}}var Cn=["listCalendars","createEvent","listEvents","getEvent","deleteEvent","updateEvent","respondToEvent","findFreeTime"],gc=z(En,Cn,{pagination:{listEvents:"maxResults"},bounds:rc});import{google as yc}from"googleapis";var An=class{constructor(e){this.authManager=e;this.listSpaces=async({pageSize:e,pageToken:t}={})=>{m("Listing chat spaces");try{let o=await(await this.getChatClient()).spaces.list({...e!==void 0&&{pageSize:e},...t!==void 0&&{pageToken:t}}),a=o.data.spaces||[];return m(`Successfully listed ${a.length} chat spaces.`),{content:[{type:"text",text:JSON.stringify({spaces:a,nextPageToken:o.data.nextPageToken??null})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during chat.listSpaces: ${o}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing chat spaces.",details:o})}]}}};this.sendMessage=async({spaceName:e,message:t,threadName:s})=>{m(`Sending message to space: ${e}${s?` in thread: ${s}`:""}`);try{let a=await(await this.getChatClient()).spaces.messages.create({parent:e,messageReplyOption:s?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:s?{name:s}:void 0}});return m(`Successfully sent message to space: ${e}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.sendMessage: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the message.",details:a})}]}}};this.findSpaceByName=async({displayName:e})=>{m(`Finding space with display name: ${e}`);try{let t=await this.getChatClient(),s,o=[];do{let l=await t.spaces.list({pageToken:s}),d=l.data.spaces||[];o=o.concat(d),s=l.data.nextPageToken||void 0}while(s);let a=o.filter(l=>l.displayName===e);return a.length>0?(m(`Found ${a.length} space(s) with display name: ${e}`),{content:[{type:"text",text:JSON.stringify(a)}]}):(m(`No space found with display name: ${e}`),{content:[{type:"text",text:JSON.stringify({error:`No space found with display name: ${e}`})}]})}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during chat.findSpaceByName: ${s}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the space.",details:s})}]}}};this.getMessages=async({spaceName:e,unreadOnly:t,pageSize:s,pageToken:o,orderBy:a,threadName:l})=>{m(`Listing messages for space: ${e}`);try{let d=await this.getChatClient(),p=[];if(l&&p.push(`thread.name = "${l}"`),t){let E=(await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"metadata"})).data.metadata?.sources?.find(k=>k.type==="PROFILE")?.id;if(!E)throw new Error("Could not determine user ID.");let R=`users/${E}`,v=((await d.spaces.members.list({parent:e})).data.memberships||[]).find(k=>k.member?.name===R)?.lastReadTime;v?p.push(`createTime > "${v}"`):m(`No last read time found for user in space: ${e}`)}let u=p.join(" AND "),f=await d.spaces.messages.list({parent:e,filter:u||void 0,pageSize:s,pageToken:o,orderBy:a}),y=f.data.messages||[],g=t?`Successfully listed ${y.length} unread messages for space: ${e}`:`Successfully listed ${y.length} messages for space: ${e}`;return m(g),{content:[{type:"text",text:JSON.stringify({messages:y,nextPageToken:f.data.nextPageToken})}]}}catch(d){let p=d instanceof Error?d.message:String(d);return m(`Error during chat.getMessages: ${p}`),d instanceof Error&&d.stack&&m(`Stack trace: ${d.stack}`),m(`Full error object: ${JSON.stringify(d,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing messages.",details:p})}]}}};this.sendDm=async({email:e,message:t,threadName:s})=>{m(`chat.sendDm called with: email=${e}, message=${t}${s?`, threadName=${s}`:""}`);try{let a=(await this._setupDmSpace(e)).name;if(!a)throw new Error("Could not determine the space name for the DM.");let d=await(await this.getChatClient()).spaces.messages.create({parent:a,messageReplyOption:s?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:s?{name:s}:void 0}});return m(`Successfully sent DM to: ${e}`),{content:[{type:"text",text:JSON.stringify(d.data)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.sendDm: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the DM.",details:a})}]}}};this.findDmByEmail=async({email:e})=>{m(`Finding DM space with user: ${e}`);try{let t=await this._setupDmSpace(e);return m(`Found or created DM space: ${t.name}`),{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during chat.findDmByEmail: ${s}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the DM space.",details:s})}]}}};this.listThreads=async({spaceName:e,pageSize:t,pageToken:s})=>{m(`Listing threads for space: ${e}`);try{let a=await(await this.getChatClient()).spaces.messages.list({parent:e,pageSize:t,pageToken:s,orderBy:"createTime desc"}),l=a.data.messages||[],d=[],p=new Set;for(let u of l)u.thread?.name&&!p.has(u.thread.name)&&(d.push(u),p.add(u.thread.name));return m(`Successfully listed ${d.length} threads for space: ${e}`),{content:[{type:"text",text:JSON.stringify({threads:d,nextPageToken:a.data.nextPageToken})}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.listThreads: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing threads.",details:a})}]}}};this.setUpSpace=async({displayName:e,userNames:t})=>{m(`Creating space with display name: ${e}`);try{let s=t.map(l=>({member:{name:l,type:"HUMAN"}})),a=await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"SPACE",displayName:e},memberships:s}});return m(`Successfully created space: ${a.data.name}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during chat.createSpace: ${o}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while creating the space.",details:o})}]}}}}async getChatClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return yc.chat({version:"v1",...t})}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return yc.people({version:"v1",...t})}async _setupDmSpace(e){let t={name:`users/${e}`,type:"HUMAN"},a=(await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"DIRECT_MESSAGE"},memberships:[{member:t}]}})).data;if(!a)throw new Error("Could not find or create a DM space.");return a}};var Pn=["listSpaces","sendMessage","findSpaceByName","getMessages","sendDm","findDmByEmail","listThreads","setUpSpace"],bc=z(An,Pn,{pagination:{listSpaces:"pageSize",getMessages:"pageSize",listThreads:"pageSize"},bounds:tc});import{google as xp}from"googleapis";var Rp=/\/d\/([a-zA-Z0-9-_]+)/;function F(n){if(m(`[IdUtils] Attempting to extract doc ID from URL: ${n}`),!n||typeof n!="string"){m("[IdUtils] Invalid input: URL is null or not a string.");return}let e=n.match(Rp);if(e&&e[1]){let t=e[1];return m(`[IdUtils] Successfully extracted doc ID: ${t}`),t}m("[IdUtils] Could not extract doc ID from URL.")}var Ep=Number.POSITIVE_INFINITY;function Yt(n,e,t){return`[Content truncated: showing ${e} of ${n} characters (${n-e} omitted). ${t}]`}function ho(n,e){if(e===!0)return Ep;if(n===void 0)return 2e4;if(typeof n!="number"||!Number.isInteger(n)||n<1||n>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return n}function Sc(n,e,t){let s=n.length;return s<=e?{text:n,truncated:!1,totalCharacters:s,returnedCharacters:s}:{text:`${n.slice(0,e)}
42
42
 
43
- ${Vt(s,e,t)}`,truncated:!0,totalCharacters:s,returnedCharacters:e}}function Sc(n,e,t){let s=JSON.stringify(n,null,2),o=Object.values(n).reduce((_,S)=>_+S.length,0);if(s.length<=e)return{text:s,truncated:!1,totalCharacters:s.length,returnedCharacters:s.length,returnedRows:o,totalRows:o};let l=Math.max(e-512,0),d={},p=0,u=0,f=!1;for(let[_,S]of Object.entries(n)){let E=[];d[_]=E,p+=JSON.stringify(_).length+4;for(let R of S){let v=JSON.stringify(R);if(p+v.length>l){f=!0;break}E.push(R),u+=1,p+=v.length+2}if(f)break}let y=JSON.stringify(d);return{text:JSON.stringify({...d,_truncation:{truncated:!0,total_characters:s.length,returned_characters:y.length,returned_rows:u,total_rows:o,note:Vt(s.length,y.length,t)}}),truncated:!0,totalCharacters:s.length,returnedCharacters:y.length,returnedRows:u,totalRows:o}}var ho="tabs(tabProperties,documentTab(body,headers,footers,footnotes))",vp=2e4,xp=2e3,yo=1e5;function go(n,e){let t=n.length;if(t<=e)return{text:n,truncated:!1,totalCharacters:t};let s=Vt(t,e,`Request a larger limit, up to ${yo}.`);return{text:`${n.slice(0,e)}
43
+ ${Yt(s,e,t)}`,truncated:!0,totalCharacters:s,returnedCharacters:e}}function wc(n,e,t){let s=JSON.stringify(n,null,2),o=Object.values(n).reduce((_,S)=>_+S.length,0);if(s.length<=e)return{text:s,truncated:!1,totalCharacters:s.length,returnedCharacters:s.length,returnedRows:o,totalRows:o};let l=Math.max(e-512,0),d={},p=0,u=0,f=!1;for(let[_,S]of Object.entries(n)){let E=[];d[_]=E,p+=JSON.stringify(_).length+4;for(let R of S){let x=JSON.stringify(R);if(p+x.length>l){f=!0;break}E.push(R),u+=1,p+=x.length+2}if(f)break}let y=JSON.stringify(d);return{text:JSON.stringify({...d,_truncation:{truncated:!0,total_characters:s.length,returned_characters:y.length,returned_rows:u,total_rows:o,note:Yt(s.length,y.length,t)}}),truncated:!0,totalCharacters:s.length,returnedCharacters:y.length,returnedRows:u,totalRows:o}}var go="tabs(tabProperties,documentTab(body,headers,footers,footnotes))",vp=2e4,Cp=2e3,bo=1e5;function yo(n,e){let t=n.length;if(t<=e)return{text:n,truncated:!1,totalCharacters:t};let s=Yt(t,e,`Request a larger limit, up to ${bo}.`);return{text:`${n.slice(0,e)}
44
44
 
45
- ${s}`,truncated:!0,totalCharacters:t}}var Pn=class n{constructor(e){this.authManager=e;this.getSuggestions=async({documentId:e})=>{m(`[DocsService] Starting getSuggestions for document: ${e}`);try{let t=F(e)||e,o=await(await this.getDocsClient()).documents.get({documentId:t,suggestionsViewMode:"SUGGESTIONS_INLINE",fields:"title,body"}),a=this._extractSuggestions(o.data.body);return m(`[DocsService] Found ${a.length} suggestions for document: ${t}`),{content:[{type:"text",text:JSON.stringify({title:o.data.title,suggestions:a},null,2)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[DocsService] Error during docs.getSuggestions: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.create=async({title:e,content:t})=>{m(`[DocsService] Starting create with title: ${e}, content: ${t?"true":"false"}`);try{m("[DocsService] Calling docs.documents.create");let s=await this.getDocsClient(),o=await s.documents.create({requestBody:{title:e}});m("[DocsService] docs.documents.create finished");let a=o.data.documentId,l=o.data.title;return t&&(m("[DocsService] Inserting content into new doc"),await s.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:1},text:t}}]}}),m("[DocsService] Content insertion finished")),{content:[{type:"text",text:JSON.stringify({documentId:a,title:l})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during docs.create: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.writeText=async({documentId:e,text:t,position:s="end",tabId:o})=>{m(`[DocsService] Starting writeText for document: ${e}, position: ${s}, tabId: ${o}`);try{let a=F(e)||e,l=await this.getDocsClient();if(s==="end"&&!o)await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{text:t}}]}});else{let d;if(s==="beginning")d=1;else if(s==="end"){let p=await l.documents.get({documentId:a,fields:ho,includeTabsContent:!0}),u=this._flattenTabs(p.data.tabs||[]),f;if(o){let _=u.find(S=>S.tabProperties?.tabId===o);if(!_)throw new Error(`Tab with ID ${o} not found.`);f=_.documentTab?.body?.content}else u.length>0&&(f=u[0].documentTab?.body?.content);let g=f?.[f.length-1]?.endIndex||1;d=Math.max(1,g-1)}else if(d=parseInt(s,10),isNaN(d)||d<1)throw new Error(`Invalid position: "${s}". Use "beginning", "end", or a positive integer index.`);await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:d,tabId:o},text:t}}]}})}return m(`[DocsService] Finished writeText for document: ${a}`),{content:[{type:"text",text:`Successfully wrote text to document ${a} at position ${s}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.writeText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.formatText=async({documentId:e,formats:t,tabId:s})=>{m(`[DocsService] Starting formatText for document: ${e}, ${t.length} format(s)`);try{let o=F(e)||e,a=[];for(let d of t){let p={startIndex:d.startIndex,endIndex:d.endIndex,tabId:s},u=n.HEADING_STYLES[d.style.toLowerCase()];if(u){a.push({updateParagraphStyle:{range:p,paragraphStyle:{namedStyleType:u},fields:"namedStyleType"}});continue}let f=n.TEXT_STYLES[d.style.toLowerCase()];if(f){a.push({updateTextStyle:{range:p,textStyle:f,fields:Object.keys(f).join(",")}});continue}if(d.style.toLowerCase()==="code"){a.push({updateTextStyle:{range:p,textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}});continue}if(d.style.toLowerCase()==="link"&&d.url){a.push({updateTextStyle:{range:p,textStyle:{link:{url:d.url}},fields:"link"}});continue}m(`[DocsService] Unknown format style: ${d.style}`)}return a.length===0?{content:[{type:"text",text:"No valid formatting requests to apply."}]}:(await(await this.getDocsClient()).documents.batchUpdate({documentId:o,requestBody:{requests:a}}),m(`[DocsService] Finished formatText for document: ${o}, applied ${a.length} format(s)`),{content:[{type:"text",text:`Successfully applied ${a.length} format(s) to document ${o}`}]})}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[DocsService] Error during docs.formatText: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getText=async({documentId:e,tabId:t,limit:s,preview:o=!1})=>{m(`[DocsService] Starting getText for document: ${e}, tabId: ${t}`);try{let a=s??(o?xp:vp);if(!Number.isInteger(a)||a<1||a>yo)throw new Error(`limit must be an integer from 1 to ${yo}.`);let l=ct(e),p=await(await this.getDocsClient()).documents.get({documentId:l,fields:`title,${ho}`,includeTabsContent:!0,suggestionsViewMode:"PREVIEW_WITHOUT_SUGGESTIONS"}),u=p.data.title,f=this._flattenTabs(p.data.tabs||[]);if(t){let g=f.find(E=>E.tabProperties?.tabId===t);if(!g)throw new Error(`Tab with ID ${t} not found.`);let _=g.documentTab?.body?.content;if(!_)return{content:[{type:"text",text:""}]};let S=u?`Document Title: ${u}
45
+ ${s}`,truncated:!0,totalCharacters:t}}var In=class n{constructor(e){this.authManager=e;this.getSuggestions=async({documentId:e})=>{m(`[DocsService] Starting getSuggestions for document: ${e}`);try{let t=F(e)||e,o=await(await this.getDocsClient()).documents.get({documentId:t,suggestionsViewMode:"SUGGESTIONS_INLINE",fields:"title,body"}),a=this._extractSuggestions(o.data.body);return m(`[DocsService] Found ${a.length} suggestions for document: ${t}`),{content:[{type:"text",text:JSON.stringify({title:o.data.title,suggestions:a},null,2)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[DocsService] Error during docs.getSuggestions: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.create=async({title:e,content:t})=>{m(`[DocsService] Starting create with title: ${e}, content: ${t?"true":"false"}`);try{m("[DocsService] Calling docs.documents.create");let s=await this.getDocsClient(),o=await s.documents.create({requestBody:{title:e}});m("[DocsService] docs.documents.create finished");let a=o.data.documentId,l=o.data.title;return t&&(m("[DocsService] Inserting content into new doc"),await s.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:1},text:t}}]}}),m("[DocsService] Content insertion finished")),{content:[{type:"text",text:JSON.stringify({documentId:a,title:l})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during docs.create: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.writeText=async({documentId:e,text:t,position:s="end",tabId:o})=>{m(`[DocsService] Starting writeText for document: ${e}, position: ${s}, tabId: ${o}`);try{let a=F(e)||e,l=await this.getDocsClient();if(s==="end"&&!o)await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{text:t}}]}});else{let d;if(s==="beginning")d=1;else if(s==="end"){let p=await l.documents.get({documentId:a,fields:go,includeTabsContent:!0}),u=this._flattenTabs(p.data.tabs||[]),f;if(o){let _=u.find(S=>S.tabProperties?.tabId===o);if(!_)throw new Error(`Tab with ID ${o} not found.`);f=_.documentTab?.body?.content}else u.length>0&&(f=u[0].documentTab?.body?.content);let g=f?.[f.length-1]?.endIndex||1;d=Math.max(1,g-1)}else if(d=parseInt(s,10),isNaN(d)||d<1)throw new Error(`Invalid position: "${s}". Use "beginning", "end", or a positive integer index.`);await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:d,tabId:o},text:t}}]}})}return m(`[DocsService] Finished writeText for document: ${a}`),{content:[{type:"text",text:`Successfully wrote text to document ${a} at position ${s}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.writeText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.formatText=async({documentId:e,formats:t,tabId:s})=>{m(`[DocsService] Starting formatText for document: ${e}, ${t.length} format(s)`);try{let o=F(e)||e,a=[];for(let d of t){let p={startIndex:d.startIndex,endIndex:d.endIndex,tabId:s},u=n.HEADING_STYLES[d.style.toLowerCase()];if(u){a.push({updateParagraphStyle:{range:p,paragraphStyle:{namedStyleType:u},fields:"namedStyleType"}});continue}let f=n.TEXT_STYLES[d.style.toLowerCase()];if(f){a.push({updateTextStyle:{range:p,textStyle:f,fields:Object.keys(f).join(",")}});continue}if(d.style.toLowerCase()==="code"){a.push({updateTextStyle:{range:p,textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}});continue}if(d.style.toLowerCase()==="link"&&d.url){a.push({updateTextStyle:{range:p,textStyle:{link:{url:d.url}},fields:"link"}});continue}m(`[DocsService] Unknown format style: ${d.style}`)}return a.length===0?{content:[{type:"text",text:"No valid formatting requests to apply."}]}:(await(await this.getDocsClient()).documents.batchUpdate({documentId:o,requestBody:{requests:a}}),m(`[DocsService] Finished formatText for document: ${o}, applied ${a.length} format(s)`),{content:[{type:"text",text:`Successfully applied ${a.length} format(s) to document ${o}`}]})}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[DocsService] Error during docs.formatText: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getText=async({documentId:e,tabId:t,limit:s,preview:o=!1})=>{m(`[DocsService] Starting getText for document: ${e}, tabId: ${t}`);try{let a=s??(o?Cp:vp);if(!Number.isInteger(a)||a<1||a>bo)throw new Error(`limit must be an integer from 1 to ${bo}.`);let l=ct(e),p=await(await this.getDocsClient()).documents.get({documentId:l,fields:`title,${go}`,includeTabsContent:!0,suggestionsViewMode:"PREVIEW_WITHOUT_SUGGESTIONS"}),u=p.data.title,f=this._flattenTabs(p.data.tabs||[]);if(t){let g=f.find(E=>E.tabProperties?.tabId===t);if(!g)throw new Error(`Tab with ID ${t} not found.`);let _=g.documentTab?.body?.content;if(!_)return{content:[{type:"text",text:""}]};let S=u?`Document Title: ${u}
46
46
 
47
- `:"";return _.forEach(E=>{S+=this._readStructuralElement(E)}),{content:[{type:"text",text:go(S,a).text}]}}if(f.length===0)return{content:[{type:"text",text:""}]};if(f.length===1){let g=f[0],_=u?`Document Title: ${u}
47
+ `:"";return _.forEach(E=>{S+=this._readStructuralElement(E)}),{content:[{type:"text",text:yo(S,a).text}]}}if(f.length===0)return{content:[{type:"text",text:""}]};if(f.length===1){let g=f[0],_=u?`Document Title: ${u}
48
48
 
49
- `:"";return g.documentTab?.body?.content?.forEach(S=>{_+=this._readStructuralElement(S)}),{content:[{type:"text",text:go(_,a).text}]}}let y=f.map((g,_)=>{let S="";g.documentTab?.body?.content?.forEach(R=>{S+=this._readStructuralElement(R)});let E=go(S,a);return{tabId:g.tabProperties?.tabId,title:g.tabProperties?.title,content:E.text,truncated:E.truncated,totalCharacters:E.totalCharacters,index:_}});return{content:[{type:"text",text:JSON.stringify({title:u,tabs:y},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.replaceText=async({documentId:e,findText:t,replaceText:s,tabId:o})=>{m(`[DocsService] Starting replaceText for document: ${e}, tabId: ${o}`);try{let a=F(e)||e,l=await this.getDocsClient(),d=await l.documents.get({documentId:a,fields:ho,includeTabsContent:!0}),p=this._flattenTabs(d.data.tabs||[]),u=[];if(o){let f=p.find(_=>_.tabProperties?.tabId===o);if(!f)throw new Error(`Tab with ID ${o} not found.`);let y=f.documentTab?.body?.content,g=this._generateReplacementRequests(y,o,t,s);for(let _ of g)u.push(_)}else for(let f of p){let y=f.tabProperties?.tabId,g=f.documentTab?.body?.content,_=this._generateReplacementRequests(g,y,t,s);for(let S of _)u.push(S)}return u.length>0&&await l.documents.batchUpdate({documentId:a,requestBody:{requests:u}}),m(`[DocsService] Finished replaceText for document: ${a}`),{content:[{type:"text",text:`Successfully replaced text in document ${a}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.replaceText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}}}_flattenTabs(e){return e.flatMap(t=>{let s=t.childTabs?this._flattenTabs(t.childTabs):[];return[t,...s]})}async getDocsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Ep.docs({version:"v1",...t})}_extractSuggestions(e){let t=[];if(!e?.content)return t;let s=o=>{o?.forEach(a=>{if(a.paragraph){if(a.paragraph.suggestedParagraphStyleChanges)for(let[l,d]of Object.entries(a.paragraph.suggestedParagraphStyleChanges))t.push({type:"paragraphStyleChange",text:this._getParagraphText(a.paragraph),suggestionIds:[l],namedStyleType:d?.paragraphStyle?.namedStyleType??void 0,startIndex:a.startIndex??void 0,endIndex:a.endIndex??void 0});a.paragraph.elements?.forEach(l=>{if(l.textRun){let d={text:l.textRun.content||"",startIndex:l.startIndex??void 0,endIndex:l.endIndex??void 0};l.textRun.suggestedInsertionIds&&t.push({...d,type:"insertion",suggestionIds:l.textRun.suggestedInsertionIds}),l.textRun.suggestedDeletionIds&&t.push({...d,type:"deletion",suggestionIds:l.textRun.suggestedDeletionIds}),l.textRun.suggestedTextStyleChanges&&t.push({...d,type:"styleChange",suggestionIds:Object.keys(l.textRun.suggestedTextStyleChanges),textStyle:l.textRun.textStyle})}})}else a.table&&a.table.tableRows?.forEach(l=>{l.tableCells?.forEach(d=>{s(d.content)})})})};return s(e.content),t}_getParagraphText(e){return e?.elements?e.elements.map(t=>t.textRun?.content||"").join(""):""}static{this.HEADING_STYLES={heading1:"HEADING_1",heading2:"HEADING_2",heading3:"HEADING_3",heading4:"HEADING_4",heading5:"HEADING_5",heading6:"HEADING_6",normalText:"NORMAL_TEXT"}}static{this.TEXT_STYLES={bold:{bold:!0},italic:{italic:!0},underline:{underline:!0},strikethrough:{strikethrough:!0}}}_readStructuralElement(e){let t="";return e.paragraph?e.paragraph.elements?.forEach(s=>{s.textRun&&s.textRun.content?t+=s.textRun.content:s.person?.personProperties?t+=this._renderPersonChip(s.person.personProperties):s.richLink?.richLinkProperties?t+=this._renderRichLinkChip(s.richLink.richLinkProperties):s.dateElement?.dateElementProperties&&(t+=this._renderDateChip(s.dateElement.dateElementProperties))}):e.table&&e.table.tableRows?.forEach(s=>{s.tableCells?.forEach(o=>{o.content?.forEach(a=>{t+=this._readStructuralElement(a)})})}),t}_renderPersonChip(e){let{name:t,email:s}=e;return s?`[${t||s}](mailto:${s})`:t||""}_renderRichLinkChip(e){let{title:t,uri:s}=e;return s?`[${t||s}](${s})`:t||""}_renderDateChip(e){let{displayText:t,timestamp:s}=e;return t||s||""}_generateReplacementRequests(e,t,s,o){let a=[],l=this._getFullDocumentText(e),d=[],p=0;for(;(p=l.indexOf(s,p))!==-1;)d.push(p+1),p+=s.length;let u=o.length-s.length,f=0;for(let y=0;y<d.length;y++){let _=d[y]+f;a.push({deleteContentRange:{range:{tabId:t,startIndex:_,endIndex:_+s.length}}}),a.push({insertText:{location:{tabId:t,index:_},text:o}}),f+=u}return a}_getFullDocumentText(e){let t="";return e&&e.forEach(s=>{t+=this._readStructuralElement(s)}),t}};var bo=["getText","create","writeText","getSuggestions","replaceText","formatText"],wc=z(Pn,bo,{bounds:Za});import{google as Ip}from"googleapis";function In(n){return n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import*as So from"node:fs";import*as lt from"node:path";import On from"node:path";import Cp from"node:fs";import{fileURLToPath as Ap}from"node:url";function Pp(){let n=On.dirname(Ap(import.meta.url));for(;n!==On.dirname(n);){if(Cp.existsSync(On.join(n,"package.json")))return n;n=On.dirname(n)}return process.cwd()}var kn=Pp();var Op=25,kp=new Set(["drive.google.com","docs.google.com"]);function $p(n){try{return kp.has(new URL(n).hostname)}catch{return!1}}var Dp=[{pattern:/\/folders\/([a-zA-Z0-9-_]+)/,type:"folder"},{pattern:/\/file\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/document\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/presentation\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/forms\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/[?&]id=([a-zA-Z0-9-_]+)/,type:"unknown"}],$n=class{constructor(e){this.authManager=e;this.findFolder=async({folderName:e})=>{m(`Searching for folder with name: ${e}`);try{let t=await this.getDriveClient(),s=`mimeType='application/vnd.google-apps.folder' and name = '${In(e)}'`;m(`Executing Drive API query: ${s}`);let a=(await t.files.list({q:s,fields:"files(id, name)",spaces:"drive",supportsAllDrives:!0,includeItemsFromAllDrives:!0})).data.files||[];return m(`Found ${a.length} folders.`),m(`API Response: ${JSON.stringify(a,null,2)}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){return this.handleError("drive.findFolder",t)}};this.createFolder=async({name:e,parentId:t})=>{m(`Creating folder with name: ${e} ${t?`in parent: ${t}`:""}`);try{let s=await this.getDriveClient(),o={name:e,mimeType:"application/vnd.google-apps.folder"};t&&(o.parents=[t]);let a=await s.files.create({requestBody:o,fields:"id, name",supportsAllDrives:!0});return m(`Created folder: ${a.data.name} (${a.data.id})`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during drive.createFolder: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.search=async({query:e,pageSize:t=10,pageToken:s,corpus:o,unreadOnly:a,sharedWithMe:l})=>{let d=await this.getDriveClient(),p=e,u=!1;if(e&&$p(e)){u=!0,m(`Detected Google Drive URL in query: ${e}`);let f=null,y="unknown";for(let g of Dp){let _=e.match(g.pattern);if(_){f=_[1],y=g.type;break}}if(f){let g=y==="folder";if(y==="unknown")try{(await d.files.get({fileId:f,fields:"mimeType",supportsAllDrives:!0})).data.mimeType==="application/vnd.google-apps.folder"&&(g=!0)}catch{m(`Could not determine type of ID from URL, treating as file: ${f}`)}if(g)p=`'${f}' in parents`,m(`Extracted Folder ID from URL: ${f}, using query: ${p}`);else{m(`Extracted File ID from URL: ${f}, using files.get`);try{let _=await d.files.get({fileId:f,fields:"id, name, modifiedTime, viewedByMeTime, mimeType, parents",supportsAllDrives:!0});return{content:[{type:"text",text:JSON.stringify({files:[_.data],nextPageToken:null})}]}}catch(_){let S=_ instanceof Error?_.message:String(_);return m(`Error during drive.files.get: ${S}`),{content:[{type:"text",text:JSON.stringify({error:S})}]}}}}else return m(`Could not extract file/folder ID from URL: ${e}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid Drive URL. Please provide a valid Google Drive URL or a search query.",details:"Could not extract file or folder ID from the provided URL."})}]}}if(e&&!u){let f="title:",y=e.trim();if(y.startsWith(f)){let g=y.substring(f.length).trim();(g.startsWith("'")&&g.endsWith("'")||g.startsWith('"')&&g.endsWith('"'))&&(g=g.substring(1,g.length-1)),p=`name contains '${In(g)}'`}else new RegExp(`^[a-zA-Z0-9-_]{${Op},}$`).test(y)&&!y.includes(" ")?(p=`'${y}' in parents`,m(`Detected Drive ID: ${y}, listing contents`)):/( and | or | not | contains | in |=)/.test(y)||(p=`fullText contains '${In(y)}'`)}l&&(m("Searching for files shared with the user."),p?p+=" and sharedWithMe":p="sharedWithMe"),m(`Executing Drive search with query: ${p}`),o&&m(`Using corpus: ${o}`),a&&m("Filtering for unread files only.");try{let f=await d.files.list({q:p,pageSize:t,pageToken:s,corpus:o,fields:"nextPageToken, files(id, name, modifiedTime, viewedByMeTime, mimeType, parents)",supportsAllDrives:!0,includeItemsFromAllDrives:!0}),y=f.data.files||[],g=f.data.nextPageToken;return a&&(y=y.filter(_=>!_.viewedByMeTime)),m(`Found ${y.length} files.`),g&&m(`Next page token: ${g}`),{content:[{type:"text",text:JSON.stringify({files:y,nextPageToken:g})}]}}catch(f){let y=f instanceof Error?f.message:String(f);return m(`Error during drive.search: ${y}`),{content:[{type:"text",text:JSON.stringify({error:y})}]}}};this.trashFile=async({fileId:e})=>{m(`Trashing Drive file: ${e}`);try{let t=await this.getDriveClient(),s=ct(e),o=await t.files.update({fileId:s,requestBody:{trashed:!0},fields:"id, name",supportsAllDrives:!0});return m(`Successfully trashed file: ${s}`),{content:[{type:"text",text:JSON.stringify({id:o.data.id,name:o.data.name,trashed:!0})}]}}catch(t){return this.handleError("drive.trashFile",t)}};this.renameFile=async({fileId:e,newName:t})=>{m(`Renaming Drive file: ${e} to "${t}"`);try{let s=await this.getDriveClient(),o=ct(e),a=await s.files.update({fileId:o,requestBody:{name:t},fields:"id, name",supportsAllDrives:!0});return m(`Successfully renamed file: ${o} to "${a.data.name}"`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(s){return this.handleError("drive.renameFile",s)}};this.getComments=async({fileId:e,pageSize:t,pageToken:s})=>{m(`[DriveService] Starting getComments for file: ${e}`);try{let o=await this.getDriveClient(),a=ct(e),l=await o.comments.list({fileId:a,...t!==void 0&&{pageSize:t},...s!==void 0&&{pageToken:s},fields:"nextPageToken, comments(id, content, author(displayName, emailAddress), createdTime, resolved, quotedFileContent(value), replies(id, content, author(displayName, emailAddress), createdTime, action))"}),d=l.data.comments||[];return m(`[DriveService] Found ${d.length} comments for file: ${e}`),{content:[{type:"text",text:JSON.stringify({comments:d,nextPageToken:l.data.nextPageToken??null},null,2)}]}}catch(o){return this.handleError("drive.getComments",o)}};this.moveFile=async({fileId:e,folderId:t,folderName:s})=>{m(`Moving Drive file: ${e} to ${t?`folder ID: ${t}`:`folder name: ${s}`}`);try{let o=await this.getDriveClient(),a=ct(e),l=t;if(!l&&s){let f=await this.findFolder({folderName:s}),y=JSON.parse(f.content[0].text);if(y.error)throw new Error(y.error);let g=y;if(g.length===0)throw new Error(`Folder not found: ${s}`);g.length>1&&m(`Warning: Found multiple folders with name "${s}". Using the first one found.`),l=g[0].id}if(!l)throw new Error("Either folderId or folderName must be provided.");let p=(await o.files.get({fileId:a,fields:"parents",supportsAllDrives:!0})).data.parents?.join(","),u=await o.files.update({fileId:a,addParents:l,removeParents:p,fields:"id, name, parents",supportsAllDrives:!0});return m(`Successfully moved file ${a} to folder ${l}`),{content:[{type:"text",text:JSON.stringify({id:u.data.id,name:u.data.name,parents:u.data.parents})}]}}catch(o){return this.handleError("drive.moveFile",o)}};this.downloadFile=async({fileId:e,localPath:t})=>{m(`Downloading Drive file ${e} to ${t}`);try{let s=await this.getDriveClient(),o=ct(e),a=await s.files.get({fileId:o,fields:"id, name, mimeType",supportsAllDrives:!0}),l=a.data.mimeType||"",d={"application/vnd.google-apps.document":{tool:"docs.getText",idName:"documentId",type:"Google Doc"},"application/vnd.google-apps.spreadsheet":{tool:"sheets.getText",idName:"spreadsheetId",type:"Google Sheet"},"application/vnd.google-apps.presentation":{tool:"slides.getText",idName:"presentationId",type:"Google Slide"}};if(l in d){let g=d[l];return{content:[{type:"text",text:`This is a ${g.type}. Direct download is not supported. Please use the '${g.tool}' tool with ${g.idName}: ${o}`}]}}if(l.includes("vnd.google-apps."))return{content:[{type:"text",text:`This is a Google Workspace file type (${l}). Direct media download is not supported. Please use specific tools (docs.getText, slides.getText, etc.) or export it if supported.`}]};let p=await s.files.get({fileId:o,alt:"media",supportsAllDrives:!0},{responseType:"arraybuffer"}),u=Buffer.from(p.data),f=lt.isAbsolute(t)?t:lt.resolve(kn,t);if(!f.startsWith(kn+lt.sep)&&f!==kn)throw new Error("localPath must be within the project root.");let y=lt.dirname(f);return await So.promises.mkdir(y,{recursive:!0}),await So.promises.writeFile(f,u),{content:[{type:"text",text:`Successfully downloaded file ${a.data.name} to ${f}`}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during drive.downloadFile: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}}}async getDriveClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Ip.drive({version:"v3",...t})}handleError(e,t){let s=t instanceof Error?t.message:String(t);return m(`Error during ${e}: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}};var wo=["findFolder","createFolder","search","trashFile","renameFile","getComments","moveFile","downloadFile"],_c=z($n,wo,{pagination:{search:"pageSize",getComments:"pageSize"},bounds:Ka});import{google as Lp}from"googleapis";var Np=/\/forms\/d\/e\/[\w-]+/,Mp=/\/forms\/d\/([\w-]+)/;function Dn(n){let e=n?.trim()??"";if(!e)throw new Error("formId is required.");if(!e.includes("/"))return e;if(Np.test(e))throw new Error(`"${e}" is a form's public responder link, which carries a different ID than the API uses. Open the form for editing and pass the ID from https://docs.google.com/forms/d/<formId>/edit instead.`);let t=e.match(Mp);if(t)return t[1];throw new Error(`Could not extract a form ID from "${e}". Pass the ID itself, or the editor URL https://docs.google.com/forms/d/<formId>/edit.`)}function Tr(n){return{content:[{type:"text",text:JSON.stringify(n)}]}}var Ln=class{constructor(e){this.authManager=e;this.create=async({title:e,documentTitle:t})=>{if(m(`[FormsService] create title=${e}`),!e?.trim())throw new Error("title is required to create a form.");let o=await(await this.getFormsClient()).forms.create({requestBody:{info:{title:e,...t?{documentTitle:t}:{}}}});return Tr({formId:o.data.formId,title:o.data.info?.title,responderUri:o.data.responderUri})};this.get=async({formId:e})=>{let t=Dn(e);m(`[FormsService] get formId=${t}`);let o=await(await this.getFormsClient()).forms.get({formId:t});return Tr(o.data)};this.batchUpdate=async({formId:e,requests:t})=>{let s=Dn(e);if(!Array.isArray(t)||t.length===0)throw new Error("batchUpdate needs at least one request in `requests`.");m(`[FormsService] batchUpdate formId=${s}, ${t.length} request(s)`);let a=await(await this.getFormsClient()).forms.batchUpdate({formId:s,requestBody:{requests:t}});return Tr(a.data)};this.listResponses=async({formId:e,pageSize:t,pageToken:s,filter:o})=>{let a=Dn(e);m(`[FormsService] listResponses formId=${a}`);let d=await(await this.getFormsClient()).forms.responses.list({formId:a,...t===void 0?{}:{pageSize:t},...s===void 0?{}:{pageToken:s},...o===void 0?{}:{filter:o}});return Tr({responses:d.data.responses??[],...d.data.nextPageToken?{nextPageToken:d.data.nextPageToken}:{}})};this.getResponse=async({formId:e,responseId:t})=>{let s=Dn(e);if(!t?.trim())throw new Error("responseId is required.");m(`[FormsService] getResponse formId=${s}, responseId=${t}`);let a=await(await this.getFormsClient()).forms.responses.get({formId:s,responseId:t});return Tr(a.data)}}async getFormsClient(){let e=await this.authManager.getAuthenticatedClient();return Lp.forms({version:"v1",...W,auth:e})}};var _o=["create","get","batchUpdate","listResponses","getResponse"],Tc=z(Ln,_o,{pagination:{listResponses:"pageSize"},bounds:sc});import{google as Up}from"googleapis";import*as ut from"node:fs/promises";import*as Ge from"node:path";import{randomUUID as Fp}from"node:crypto";var Yt=class n{static createMimeMessage({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:f=!1}){let y=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,g=[];o&&g.push(`From: ${o}`),g.push(`To: ${e}`),a&&g.push(`Cc: ${a}`),l&&g.push(`Bcc: ${l}`),d&&g.push(`Reply-To: ${d}`),p&&g.push(`In-Reply-To: ${n.sanitizeHeaderValue(p)}`),u&&g.push(`References: ${n.sanitizeHeaderValue(u)}`),g.push(`Subject: ${y}`),f?g.push("Content-Type: text/html; charset=utf-8"):g.push("Content-Type: text/plain; charset=utf-8"),g.push(""),g.push(s);let _=g.join(`\r
50
- `);return Buffer.from(_).toString("base64url")}static sanitizeHeaderValue(e){return e.replace(/[\r\n\x00-\x1f\x7f]/g,"")}static sanitizeHeaderFilename(e){return n.sanitizeHeaderValue(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}static createMimeMessageWithAttachments({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,attachments:f,isHtml:y=!1}){let g=`boundary_${Date.now()}_${Fp().replace(/-/g,"")}`,_=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,S=[];if(o&&S.push(`From: ${o}`),S.push(`To: ${e}`),a&&S.push(`Cc: ${a}`),l&&S.push(`Bcc: ${l}`),d&&S.push(`Reply-To: ${d}`),S.push(`Subject: ${_}`),S.push("MIME-Version: 1.0"),!f||f.length===0)return this.createMimeMessage({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:y});p&&S.push(`In-Reply-To: ${n.sanitizeHeaderValue(p)}`),u&&S.push(`References: ${n.sanitizeHeaderValue(u)}`),S.push(`Content-Type: multipart/mixed; boundary="${g}"`),S.push(""),S.push(`--${g}`),y?S.push("Content-Type: text/html; charset=utf-8"):S.push("Content-Type: text/plain; charset=utf-8"),S.push(""),S.push(s);for(let R of f){let v=n.sanitizeHeaderValue(R.contentType||"application/octet-stream"),A=n.sanitizeHeaderFilename(R.filename);S.push(`--${g}`),S.push(`Content-Type: ${v}`),S.push("Content-Transfer-Encoding: base64"),S.push(`Content-Disposition: attachment; filename="${A}"`),S.push("");let C=typeof R.content=="string"?R.content:R.content.toString("base64");for(let x=0;x<C.length;x+=76)S.push(C.slice(x,x+76))}S.push(`--${g}--`);let E=S.join(`\r
51
- `);return Buffer.from(E).toString("base64url")}static decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf-8")}};var To="No labels to add or remove were provided. No action taken.";import{ZodError as qp}from"zod";var jp={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".html":"text/html",".htm":"text/html",".json":"application/json",".xml":"application/xml",".zip":"application/zip",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".mp4":"video/mp4",".mp3":"audio/mpeg"},Ec=18*1024*1024;function vc(n){if(n>Ec)throw new Error(`Total attachment size (${(n/1024/1024).toFixed(2)}MB) exceeds the maximum allowed limit of ${Ec/1024/1024}MB.`)}function Wp(n){let e=Ge.extname(n).toLowerCase();return jp[e]??"application/octet-stream"}var Nn=class{constructor(e){this.authManager=e;this.search=async({query:e,maxResults:t=100,pageToken:s,labelIds:o,includeSpamTrash:a=!1})=>{try{m(`Gmail search - query: ${e}, maxResults: ${t}`);let d=await(await this.getGmailClient()).users.messages.list({userId:"me",q:e,maxResults:t,pageToken:s,labelIds:o,includeSpamTrash:a}),p=d.data.messages||[],u=d.data.nextPageToken,f=d.data.resultSizeEstimate;return m(`Found ${p.length} messages, estimated total: ${f}`),{content:[{type:"text",text:JSON.stringify({messages:p.map(y=>({id:y.id,threadId:y.threadId})),nextPageToken:u,resultSizeEstimate:f},null,2)}]}}catch(l){return this.handleError(l,"gmail.search")}};this.get=async({messageId:e,format:t="full"})=>{try{m(`Getting message ${e} with format: ${t}`);let a=(await(await this.getGmailClient()).users.messages.get({userId:"me",id:e,format:t})).data;if(t==="metadata"||t==="full"){let l=a.payload?.headers||[],d=S=>l.find(E=>E.name===S)?.value,p=d("Subject"),u=d("From"),f=d("To"),y=d("Date"),g="",_=[];if(t==="full"&&a.payload){let S=this.extractAttachmentsAndBody(a.payload);g=S.body,_=S.attachments}return{content:[{type:"text",text:JSON.stringify({id:a.id,threadId:a.threadId,labelIds:a.labelIds,snippet:a.snippet,subject:p,from:u,to:f,date:y,body:g||a.snippet,attachments:_},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(s){return this.handleError(s,"gmail.get")}};this.downloadAttachment=async({messageId:e,attachmentId:t,localPath:s})=>{try{if(m(`Downloading attachment ${t} from message ${e} to ${s}`),!Ge.isAbsolute(s))throw new Error("localPath must be an absolute path.");let l=(await(await this.getGmailClient()).users.messages.attachments.get({userId:"me",messageId:e,id:t})).data.data;if(!l)throw new Error("Attachment data is empty");await ut.mkdir(Ge.dirname(s),{recursive:!0});let d=Buffer.from(l,"base64url");return await ut.writeFile(s,d),m(`Attachment downloaded successfully to ${s}`),{content:[{type:"text",text:JSON.stringify({message:`Attachment downloaded successfully to ${s}`,path:s})}]}}catch(o){return this.handleError(o,"gmail.downloadAttachment")}};this.modify=async({messageId:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{m(`Modifying message ${e} with addLabelIds: ${t}, removeLabelIds: ${s}`);let l=(await(await this.getGmailClient()).users.messages.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:s}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(o){return this.handleError(o,"gmail.modify")}};this.batchModify=async({messageIds:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{if(t.length===0&&s.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:To})}]};if(e.length>1e3)throw new Error(`Too many message IDs. Maximum is ${1e3}, got ${e.length}.`);return m(`Batch modifying ${e.length} messages with addLabelIds: ${t}, removeLabelIds: ${s}`),await(await this.getGmailClient()).users.messages.batchModify({userId:"me",requestBody:{ids:e,addLabelIds:t,removeLabelIds:s}}),{content:[{type:"text",text:JSON.stringify({modifiedCount:e.length,addLabelIds:t,removeLabelIds:s,status:"success"},null,2)}]}}catch(o){return this.handleError(o,"gmail.batchModify")}};this.modifyThread=async({threadId:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{if(t.length===0&&s.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:To})}]};m(`Modifying thread ${e} with addLabelIds: ${t}, removeLabelIds: ${s}`);let l=(await(await this.getGmailClient()).users.threads.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:s}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(o){return this.handleError(o,"gmail.modifyThread")}};this.send=async({to:e,subject:t,body:s,cc:o,bcc:a,replyTo:l,isHtml:d=!1})=>{try{let p=this.validateEmailAddresses({to:e,cc:o,bcc:a,replyTo:l});if(p)return p;m(`Sending email to: ${e}, subject: ${t}`);let u=Yt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d}),y=await(await this.getGmailClient()).users.messages.send({userId:"me",requestBody:{raw:u}});return m(`Email sent successfully: ${y.data.id}`),{content:[{type:"text",text:JSON.stringify({id:y.data.id,threadId:y.data.threadId,labelIds:y.data.labelIds,status:"sent"},null,2)}]}}catch(p){return this.handleError(p,"gmail.send")}};this.createDraft=async({to:e,subject:t,body:s,cc:o,bcc:a,replyTo:l,isHtml:d=!1,threadId:p,attachments:u})=>{try{let f=this.validateEmailAddresses({to:e,cc:o,bcc:a,replyTo:l});if(f)return f;m(`Creating draft - to: ${e}, subject: ${t}`);let y=await this.getGmailClient(),g,_;if(p)try{let v=(await y.users.threads.get({userId:"me",id:p,format:"metadata",metadataHeaders:["Message-ID","References"]})).data.messages||[];if(v.length>0){let C=v[v.length-1].payload?.headers||[],x=C.find($=>$.name?.toLowerCase()==="message-id"),k=C.find($=>$.name?.toLowerCase()==="references");if(x?.value){g=x.value;let $=k?.value||"";_=$?`${$} ${x.value}`:x.value}}}catch(R){m(`Warning: Could not fetch thread ${p} for reply headers: ${R}`)}let S;if(u&&u.length>0){let v=(await Promise.all(u.map(async C=>{if(!Ge.isAbsolute(C.filePath))throw new Error(`Attachment filePath must be an absolute path: ${C.filePath}`);let x;try{x=await ut.stat(C.filePath)}catch(k){throw new Error(`Could not access attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}if(!x.isFile())throw new Error(`Attachment path is not a file: ${C.filePath}`);return x.size}))).reduce((C,x)=>C+x,0);vc(v);let A=await Promise.all(u.map(async C=>{let x;try{x=await ut.readFile(C.filePath)}catch(k){throw new Error(`Could not read attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}return{filename:C.filename||Ge.basename(C.filePath),content:x,contentType:C.mimeType||Wp(C.filePath)}}));vc(A.reduce((C,x)=>C+x.content.length,0)),S=Yt.createMimeMessageWithAttachments({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,inReplyTo:g,references:_,isHtml:d,attachments:A})}else S=Yt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d,inReplyTo:g,references:_});let E=await y.users.drafts.create({userId:"me",requestBody:{message:{raw:S,...p&&{threadId:p}}}});return m(`Draft created successfully: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify({id:E.data.id,message:{id:E.data.message?.id,threadId:E.data.message?.threadId,labelIds:E.data.message?.labelIds},status:"draft_created"},null,2)}]}}catch(f){return this.handleError(f,"gmail.createDraft")}};this.sendDraft=async({draftId:e})=>{try{m(`Sending draft: ${e}`);let s=await(await this.getGmailClient()).users.drafts.send({userId:"me",requestBody:{id:e}});return m(`Draft sent successfully: ${s.data.id}`),{content:[{type:"text",text:JSON.stringify({id:s.data.id,threadId:s.data.threadId,labelIds:s.data.labelIds,status:"sent"},null,2)}]}}catch(t){return this.handleError(t,"gmail.sendDraft")}};this.listLabels=async()=>{try{m("Listing Gmail labels");let s=(await(await this.getGmailClient()).users.labels.list({userId:"me"})).data.labels||[];return m(`Found ${s.length} labels`),{content:[{type:"text",text:JSON.stringify({labels:s.map(o=>({id:o.id,name:o.name,type:o.type,messageListVisibility:o.messageListVisibility,labelListVisibility:o.labelListVisibility}))},null,2)}]}}catch(e){return this.handleError(e,"gmail.listLabels")}};this.createLabel=async({name:e,labelListVisibility:t="labelShow",messageListVisibility:s="show"})=>{try{m(`Creating Gmail label: ${e}`);let l=(await(await this.getGmailClient()).users.labels.create({userId:"me",requestBody:{name:e,labelListVisibility:t,messageListVisibility:s}})).data;return m(`Created label: ${l.name} with id: ${l.id}`),{content:[{type:"text",text:JSON.stringify({id:l.id,name:l.name,type:l.type,messageListVisibility:l.messageListVisibility,labelListVisibility:l.labelListVisibility,status:"created"},null,2)}]}}catch(o){return this.handleError(o,"gmail.createLabel")}}}async getGmailClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Up.gmail({version:"v1",...t})}handleError(e,t){let s=e instanceof Error?e.message:String(e);return m(`Error during ${t}: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}validateEmailAddresses({to:e,cc:t,bcc:s,replyTo:o}){try{return at.parse(e),t&&at.parse(t),s&&at.parse(s),o&&at.parse(o),null}catch(a){if(!(a instanceof qp))throw a;return m(`Rejected invalid email address input: ${a.message}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid email address format",details:a.message})}]}}}extractAttachmentsAndBody(e,t={body:"",attachments:[]}){if(!e)return t;if(e.body?.data&&(!e.filename||!e.body.attachmentId)&&e.mimeType?.startsWith("text/")&&(!t.body||e.mimeType==="text/plain")&&(t.body=Buffer.from(e.body.data,"base64").toString("utf-8")),e.filename&&e.body?.attachmentId&&t.attachments.push({filename:e.filename,mimeType:e.mimeType,attachmentId:e.body.attachmentId,size:e.body.size}),e.parts)for(let s of e.parts)this.extractAttachmentsAndBody(s,t);return t}};var Mn=["search","get","downloadAttachment","modify","batchModify","modifyThread","send","createDraft","sendDraft","listLabels","createLabel"],xc=z(Nn,Mn,{pagination:{search:"maxResults"},bounds:Qa});import{google as zp}from"googleapis";var Fn=class{constructor(e){this.authManager=e;this.getUserProfile=async({userId:e,email:t,name:s})=>{m(`[PeopleService] Starting getUserProfile with: userId=${e}, email=${t}, name=${s}`);try{if(!e&&!t&&!s)throw new Error("Either userId, email, or name must be provided.");let o=await this.getPeopleClient();if(e){let a=e.startsWith("people/")?e:`people/${e}`,l=await o.people.get({resourceName:a,personFields:"names,emailAddresses"});return m(`[PeopleService] Finished getUserProfile for user: ${e}`),{content:[{type:"text",text:JSON.stringify({results:[{person:l.data}]})}]}}else if(t||s){let a=t||s,l=await o.people.searchDirectoryPeople({query:a,readMask:"names,emailAddresses",sources:["DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT","DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"]});return m(`[PeopleService] Finished getUserProfile search for: ${a}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}else throw new Error("Either userId, email, or name must be provided.")}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[PeopleService] Error during people.getUserProfile: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getMe=async()=>{m("[PeopleService] Starting getMe");try{let t=await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"names,emailAddresses"});return m("[PeopleService] Finished getMe"),{content:[{type:"text",text:JSON.stringify(t.data)}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`[PeopleService] Error during people.getMe: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.getUserRelations=async({userId:e,relationType:t})=>{let s=e?e.startsWith("people/")?e:`people/${e}`:"people/me";m(`[PeopleService] Starting getUserRelations for ${s} with relationType=${t}`);try{let a=await(await this.getPeopleClient()).people.get({resourceName:s,personFields:"relations"});m("[PeopleService] Finished getUserRelations API call");let l=a.data?.relations||[],d=t?l.filter(u=>u.type?.toLowerCase()===t.toLowerCase()):l;t?m(`[PeopleService] Filtered to ${d.length} relations of type: ${t}`):m(`[PeopleService] Returning all ${d.length} relations`);let p={resourceName:s,...t&&{relationType:t},relations:d};return{content:[{type:"text",text:JSON.stringify(p)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[PeopleService] Error during people.getUserRelations: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return zp.people({version:"v1",...t})}};var Bn=["getUserProfile","getMe","getUserRelations"],Cc=z(Fn,Bn,{bounds:nc});import{google as Hp}from"googleapis";var Un=class n{constructor(e){this.authManager=e;this.getText=async({spreadsheetId:e,format:t="text",max_chars:s,full:o})=>{m(`[SheetsService] Starting getText for spreadsheet: ${e} with format: ${t}`);try{let a=F(e)||e,l=mo(s,o),d=await this.getSheetsClient(),p=await d.spreadsheets.get({spreadsheetId:a,includeGridData:!1}),u="",f={};p.data.properties?.title&&t!=="json"&&(u+=`Spreadsheet Title: ${p.data.properties.title}
49
+ `:"";return g.documentTab?.body?.content?.forEach(S=>{_+=this._readStructuralElement(S)}),{content:[{type:"text",text:yo(_,a).text}]}}let y=f.map((g,_)=>{let S="";g.documentTab?.body?.content?.forEach(R=>{S+=this._readStructuralElement(R)});let E=yo(S,a);return{tabId:g.tabProperties?.tabId,title:g.tabProperties?.title,content:E.text,truncated:E.truncated,totalCharacters:E.totalCharacters,index:_}});return{content:[{type:"text",text:JSON.stringify({title:u,tabs:y},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.replaceText=async({documentId:e,findText:t,replaceText:s,tabId:o})=>{m(`[DocsService] Starting replaceText for document: ${e}, tabId: ${o}`);try{let a=F(e)||e,l=await this.getDocsClient(),d=await l.documents.get({documentId:a,fields:go,includeTabsContent:!0}),p=this._flattenTabs(d.data.tabs||[]),u=[];if(o){let f=p.find(_=>_.tabProperties?.tabId===o);if(!f)throw new Error(`Tab with ID ${o} not found.`);let y=f.documentTab?.body?.content,g=this._generateReplacementRequests(y,o,t,s);for(let _ of g)u.push(_)}else for(let f of p){let y=f.tabProperties?.tabId,g=f.documentTab?.body?.content,_=this._generateReplacementRequests(g,y,t,s);for(let S of _)u.push(S)}return u.length>0&&await l.documents.batchUpdate({documentId:a,requestBody:{requests:u}}),m(`[DocsService] Finished replaceText for document: ${a}`),{content:[{type:"text",text:`Successfully replaced text in document ${a}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.replaceText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}}}_flattenTabs(e){return e.flatMap(t=>{let s=t.childTabs?this._flattenTabs(t.childTabs):[];return[t,...s]})}async getDocsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return xp.docs({version:"v1",...t})}_extractSuggestions(e){let t=[];if(!e?.content)return t;let s=o=>{o?.forEach(a=>{if(a.paragraph){if(a.paragraph.suggestedParagraphStyleChanges)for(let[l,d]of Object.entries(a.paragraph.suggestedParagraphStyleChanges))t.push({type:"paragraphStyleChange",text:this._getParagraphText(a.paragraph),suggestionIds:[l],namedStyleType:d?.paragraphStyle?.namedStyleType??void 0,startIndex:a.startIndex??void 0,endIndex:a.endIndex??void 0});a.paragraph.elements?.forEach(l=>{if(l.textRun){let d={text:l.textRun.content||"",startIndex:l.startIndex??void 0,endIndex:l.endIndex??void 0};l.textRun.suggestedInsertionIds&&t.push({...d,type:"insertion",suggestionIds:l.textRun.suggestedInsertionIds}),l.textRun.suggestedDeletionIds&&t.push({...d,type:"deletion",suggestionIds:l.textRun.suggestedDeletionIds}),l.textRun.suggestedTextStyleChanges&&t.push({...d,type:"styleChange",suggestionIds:Object.keys(l.textRun.suggestedTextStyleChanges),textStyle:l.textRun.textStyle})}})}else a.table&&a.table.tableRows?.forEach(l=>{l.tableCells?.forEach(d=>{s(d.content)})})})};return s(e.content),t}_getParagraphText(e){return e?.elements?e.elements.map(t=>t.textRun?.content||"").join(""):""}static{this.HEADING_STYLES={heading1:"HEADING_1",heading2:"HEADING_2",heading3:"HEADING_3",heading4:"HEADING_4",heading5:"HEADING_5",heading6:"HEADING_6",normalText:"NORMAL_TEXT"}}static{this.TEXT_STYLES={bold:{bold:!0},italic:{italic:!0},underline:{underline:!0},strikethrough:{strikethrough:!0}}}_readStructuralElement(e){let t="";return e.paragraph?e.paragraph.elements?.forEach(s=>{s.textRun&&s.textRun.content?t+=s.textRun.content:s.person?.personProperties?t+=this._renderPersonChip(s.person.personProperties):s.richLink?.richLinkProperties?t+=this._renderRichLinkChip(s.richLink.richLinkProperties):s.dateElement?.dateElementProperties&&(t+=this._renderDateChip(s.dateElement.dateElementProperties))}):e.table&&e.table.tableRows?.forEach(s=>{s.tableCells?.forEach(o=>{o.content?.forEach(a=>{t+=this._readStructuralElement(a)})})}),t}_renderPersonChip(e){let{name:t,email:s}=e;return s?`[${t||s}](mailto:${s})`:t||""}_renderRichLinkChip(e){let{title:t,uri:s}=e;return s?`[${t||s}](${s})`:t||""}_renderDateChip(e){let{displayText:t,timestamp:s}=e;return t||s||""}_generateReplacementRequests(e,t,s,o){let a=[],l=this._getFullDocumentText(e),d=[],p=0;for(;(p=l.indexOf(s,p))!==-1;)d.push(p+1),p+=s.length;let u=o.length-s.length,f=0;for(let y=0;y<d.length;y++){let _=d[y]+f;a.push({deleteContentRange:{range:{tabId:t,startIndex:_,endIndex:_+s.length}}}),a.push({insertText:{location:{tabId:t,index:_},text:o}}),f+=u}return a}_getFullDocumentText(e){let t="";return e&&e.forEach(s=>{t+=this._readStructuralElement(s)}),t}};var So=["getText","create","writeText","getSuggestions","replaceText","formatText"],_c=z(In,So,{bounds:Xa});import{google as Op}from"googleapis";function On(n){return n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import*as wo from"node:fs";import*as lt from"node:path";import kn from"node:path";import Ap from"node:fs";import{fileURLToPath as Pp}from"node:url";function Ip(){let n=kn.dirname(Pp(import.meta.url));for(;n!==kn.dirname(n);){if(Ap.existsSync(kn.join(n,"package.json")))return n;n=kn.dirname(n)}return process.cwd()}var $n=Ip();var kp=25,$p=new Set(["drive.google.com","docs.google.com"]);function Dp(n){try{return $p.has(new URL(n).hostname)}catch{return!1}}var Lp=[{pattern:/\/folders\/([a-zA-Z0-9-_]+)/,type:"folder"},{pattern:/\/file\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/document\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/presentation\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/forms\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/[?&]id=([a-zA-Z0-9-_]+)/,type:"unknown"}],Dn=class{constructor(e){this.authManager=e;this.findFolder=async({folderName:e})=>{m(`Searching for folder with name: ${e}`);try{let t=await this.getDriveClient(),s=`mimeType='application/vnd.google-apps.folder' and name = '${On(e)}'`;m(`Executing Drive API query: ${s}`);let a=(await t.files.list({q:s,fields:"files(id, name)",spaces:"drive",supportsAllDrives:!0,includeItemsFromAllDrives:!0})).data.files||[];return m(`Found ${a.length} folders.`),m(`API Response: ${JSON.stringify(a,null,2)}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){return this.handleError("drive.findFolder",t)}};this.createFolder=async({name:e,parentId:t})=>{m(`Creating folder with name: ${e} ${t?`in parent: ${t}`:""}`);try{let s=await this.getDriveClient(),o={name:e,mimeType:"application/vnd.google-apps.folder"};t&&(o.parents=[t]);let a=await s.files.create({requestBody:o,fields:"id, name",supportsAllDrives:!0});return m(`Created folder: ${a.data.name} (${a.data.id})`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during drive.createFolder: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.search=async({query:e,pageSize:t=10,pageToken:s,corpus:o,unreadOnly:a,sharedWithMe:l})=>{let d=await this.getDriveClient(),p=e,u=!1;if(e&&Dp(e)){u=!0,m(`Detected Google Drive URL in query: ${e}`);let f=null,y="unknown";for(let g of Lp){let _=e.match(g.pattern);if(_){f=_[1],y=g.type;break}}if(f){let g=y==="folder";if(y==="unknown")try{(await d.files.get({fileId:f,fields:"mimeType",supportsAllDrives:!0})).data.mimeType==="application/vnd.google-apps.folder"&&(g=!0)}catch{m(`Could not determine type of ID from URL, treating as file: ${f}`)}if(g)p=`'${f}' in parents`,m(`Extracted Folder ID from URL: ${f}, using query: ${p}`);else{m(`Extracted File ID from URL: ${f}, using files.get`);try{let _=await d.files.get({fileId:f,fields:"id, name, modifiedTime, viewedByMeTime, mimeType, parents",supportsAllDrives:!0});return{content:[{type:"text",text:JSON.stringify({files:[_.data],nextPageToken:null})}]}}catch(_){let S=_ instanceof Error?_.message:String(_);return m(`Error during drive.files.get: ${S}`),{content:[{type:"text",text:JSON.stringify({error:S})}]}}}}else return m(`Could not extract file/folder ID from URL: ${e}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid Drive URL. Please provide a valid Google Drive URL or a search query.",details:"Could not extract file or folder ID from the provided URL."})}]}}if(e&&!u){let f="title:",y=e.trim();if(y.startsWith(f)){let g=y.substring(f.length).trim();(g.startsWith("'")&&g.endsWith("'")||g.startsWith('"')&&g.endsWith('"'))&&(g=g.substring(1,g.length-1)),p=`name contains '${On(g)}'`}else new RegExp(`^[a-zA-Z0-9-_]{${kp},}$`).test(y)&&!y.includes(" ")?(p=`'${y}' in parents`,m(`Detected Drive ID: ${y}, listing contents`)):/( and | or | not | contains | in |=)/.test(y)||(p=`fullText contains '${On(y)}'`)}l&&(m("Searching for files shared with the user."),p?p+=" and sharedWithMe":p="sharedWithMe"),m(`Executing Drive search with query: ${p}`),o&&m(`Using corpus: ${o}`),a&&m("Filtering for unread files only.");try{let f=await d.files.list({q:p,pageSize:t,pageToken:s,corpus:o,fields:"nextPageToken, files(id, name, modifiedTime, viewedByMeTime, mimeType, parents)",supportsAllDrives:!0,includeItemsFromAllDrives:!0}),y=f.data.files||[],g=f.data.nextPageToken;return a&&(y=y.filter(_=>!_.viewedByMeTime)),m(`Found ${y.length} files.`),g&&m(`Next page token: ${g}`),{content:[{type:"text",text:JSON.stringify({files:y,nextPageToken:g})}]}}catch(f){let y=f instanceof Error?f.message:String(f);return m(`Error during drive.search: ${y}`),{content:[{type:"text",text:JSON.stringify({error:y})}]}}};this.trashFile=async({fileId:e})=>{m(`Trashing Drive file: ${e}`);try{let t=await this.getDriveClient(),s=ct(e),o=await t.files.update({fileId:s,requestBody:{trashed:!0},fields:"id, name",supportsAllDrives:!0});return m(`Successfully trashed file: ${s}`),{content:[{type:"text",text:JSON.stringify({id:o.data.id,name:o.data.name,trashed:!0})}]}}catch(t){return this.handleError("drive.trashFile",t)}};this.renameFile=async({fileId:e,newName:t})=>{m(`Renaming Drive file: ${e} to "${t}"`);try{let s=await this.getDriveClient(),o=ct(e),a=await s.files.update({fileId:o,requestBody:{name:t},fields:"id, name",supportsAllDrives:!0});return m(`Successfully renamed file: ${o} to "${a.data.name}"`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(s){return this.handleError("drive.renameFile",s)}};this.getComments=async({fileId:e,pageSize:t,pageToken:s})=>{m(`[DriveService] Starting getComments for file: ${e}`);try{let o=await this.getDriveClient(),a=ct(e),l=await o.comments.list({fileId:a,...t!==void 0&&{pageSize:t},...s!==void 0&&{pageToken:s},fields:"nextPageToken, comments(id, content, author(displayName, emailAddress), createdTime, resolved, quotedFileContent(value), replies(id, content, author(displayName, emailAddress), createdTime, action))"}),d=l.data.comments||[];return m(`[DriveService] Found ${d.length} comments for file: ${e}`),{content:[{type:"text",text:JSON.stringify({comments:d,nextPageToken:l.data.nextPageToken??null},null,2)}]}}catch(o){return this.handleError("drive.getComments",o)}};this.moveFile=async({fileId:e,folderId:t,folderName:s})=>{m(`Moving Drive file: ${e} to ${t?`folder ID: ${t}`:`folder name: ${s}`}`);try{let o=await this.getDriveClient(),a=ct(e),l=t;if(!l&&s){let f=await this.findFolder({folderName:s}),y=JSON.parse(f.content[0].text);if(y.error)throw new Error(y.error);let g=y;if(g.length===0)throw new Error(`Folder not found: ${s}`);g.length>1&&m(`Warning: Found multiple folders with name "${s}". Using the first one found.`),l=g[0].id}if(!l)throw new Error("Either folderId or folderName must be provided.");let p=(await o.files.get({fileId:a,fields:"parents",supportsAllDrives:!0})).data.parents?.join(","),u=await o.files.update({fileId:a,addParents:l,removeParents:p,fields:"id, name, parents",supportsAllDrives:!0});return m(`Successfully moved file ${a} to folder ${l}`),{content:[{type:"text",text:JSON.stringify({id:u.data.id,name:u.data.name,parents:u.data.parents})}]}}catch(o){return this.handleError("drive.moveFile",o)}};this.downloadFile=async({fileId:e,localPath:t})=>{m(`Downloading Drive file ${e} to ${t}`);try{let s=await this.getDriveClient(),o=ct(e),a=await s.files.get({fileId:o,fields:"id, name, mimeType",supportsAllDrives:!0}),l=a.data.mimeType||"",d={"application/vnd.google-apps.document":{tool:"docs.getText",idName:"documentId",type:"Google Doc"},"application/vnd.google-apps.spreadsheet":{tool:"sheets.getText",idName:"spreadsheetId",type:"Google Sheet"},"application/vnd.google-apps.presentation":{tool:"slides.getText",idName:"presentationId",type:"Google Slide"}};if(l in d){let g=d[l];return{content:[{type:"text",text:`This is a ${g.type}. Direct download is not supported. Please use the '${g.tool}' tool with ${g.idName}: ${o}`}]}}if(l.includes("vnd.google-apps."))return{content:[{type:"text",text:`This is a Google Workspace file type (${l}). Direct media download is not supported. Please use specific tools (docs.getText, slides.getText, etc.) or export it if supported.`}]};let p=await s.files.get({fileId:o,alt:"media",supportsAllDrives:!0},{responseType:"arraybuffer"}),u=Buffer.from(p.data),f=lt.isAbsolute(t)?t:lt.resolve($n,t);if(!f.startsWith($n+lt.sep)&&f!==$n)throw new Error("localPath must be within the project root.");let y=lt.dirname(f);return await wo.promises.mkdir(y,{recursive:!0}),await wo.promises.writeFile(f,u),{content:[{type:"text",text:`Successfully downloaded file ${a.data.name} to ${f}`}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during drive.downloadFile: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}}}async getDriveClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Op.drive({version:"v3",...t})}handleError(e,t){let s=t instanceof Error?t.message:String(t);return m(`Error during ${e}: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}};var _o=["findFolder","createFolder","search","trashFile","renameFile","getComments","moveFile","downloadFile"],Tc=z(Dn,_o,{pagination:{search:"pageSize",getComments:"pageSize"},bounds:ec});import{google as Np}from"googleapis";var Mp=/\/forms\/d\/e\/[\w-]+/,Fp=/\/forms\/d\/([\w-]+)/;function Ln(n){let e=n?.trim()??"";if(!e)throw new Error("formId is required.");if(!e.includes("/"))return e;if(Mp.test(e))throw new Error(`"${e}" is a form's public responder link, which carries a different ID than the API uses. Open the form for editing and pass the ID from https://docs.google.com/forms/d/<formId>/edit instead.`);let t=e.match(Fp);if(t)return t[1];throw new Error(`Could not extract a form ID from "${e}". Pass the ID itself, or the editor URL https://docs.google.com/forms/d/<formId>/edit.`)}function Er(n){return{content:[{type:"text",text:JSON.stringify(n)}]}}var Nn=class{constructor(e){this.authManager=e;this.create=async({title:e,documentTitle:t})=>{if(m(`[FormsService] create title=${e}`),!e?.trim())throw new Error("title is required to create a form.");let o=await(await this.getFormsClient()).forms.create({requestBody:{info:{title:e,...t?{documentTitle:t}:{}}}});return Er({formId:o.data.formId,title:o.data.info?.title,responderUri:o.data.responderUri})};this.get=async({formId:e})=>{let t=Ln(e);m(`[FormsService] get formId=${t}`);let o=await(await this.getFormsClient()).forms.get({formId:t});return Er(o.data)};this.batchUpdate=async({formId:e,requests:t})=>{let s=Ln(e);if(!Array.isArray(t)||t.length===0)throw new Error("batchUpdate needs at least one request in `requests`.");m(`[FormsService] batchUpdate formId=${s}, ${t.length} request(s)`);let a=await(await this.getFormsClient()).forms.batchUpdate({formId:s,requestBody:{requests:t}});return Er(a.data)};this.listResponses=async({formId:e,pageSize:t,pageToken:s,filter:o})=>{let a=Ln(e);m(`[FormsService] listResponses formId=${a}`);let d=await(await this.getFormsClient()).forms.responses.list({formId:a,...t===void 0?{}:{pageSize:t},...s===void 0?{}:{pageToken:s},...o===void 0?{}:{filter:o}});return Er({responses:d.data.responses??[],...d.data.nextPageToken?{nextPageToken:d.data.nextPageToken}:{}})};this.getResponse=async({formId:e,responseId:t})=>{let s=Ln(e);if(!t?.trim())throw new Error("responseId is required.");m(`[FormsService] getResponse formId=${s}, responseId=${t}`);let a=await(await this.getFormsClient()).forms.responses.get({formId:s,responseId:t});return Er(a.data)}}async getFormsClient(){let e=await this.authManager.getAuthenticatedClient();return Np.forms({version:"v1",...W,auth:e})}};var To=["create","get","batchUpdate","listResponses","getResponse"],Rc=z(Nn,To,{pagination:{listResponses:"pageSize"},bounds:oc});import{google as qp}from"googleapis";import*as ut from"node:fs/promises";import*as Ge from"node:path";import{randomUUID as Bp}from"node:crypto";var Zt=class n{static createMimeMessage({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:f=!1}){let y=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,g=[];o&&g.push(`From: ${o}`),g.push(`To: ${e}`),a&&g.push(`Cc: ${a}`),l&&g.push(`Bcc: ${l}`),d&&g.push(`Reply-To: ${d}`),p&&g.push(`In-Reply-To: ${n.sanitizeHeaderValue(p)}`),u&&g.push(`References: ${n.sanitizeHeaderValue(u)}`),g.push(`Subject: ${y}`),f?g.push("Content-Type: text/html; charset=utf-8"):g.push("Content-Type: text/plain; charset=utf-8"),g.push(""),g.push(s);let _=g.join(`\r
50
+ `);return Buffer.from(_).toString("base64url")}static sanitizeHeaderValue(e){return e.replace(/[\r\n\x00-\x1f\x7f]/g,"")}static sanitizeHeaderFilename(e){return n.sanitizeHeaderValue(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}static createMimeMessageWithAttachments({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,attachments:f,isHtml:y=!1}){let g=`boundary_${Date.now()}_${Bp().replace(/-/g,"")}`,_=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,S=[];if(o&&S.push(`From: ${o}`),S.push(`To: ${e}`),a&&S.push(`Cc: ${a}`),l&&S.push(`Bcc: ${l}`),d&&S.push(`Reply-To: ${d}`),S.push(`Subject: ${_}`),S.push("MIME-Version: 1.0"),!f||f.length===0)return this.createMimeMessage({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:y});p&&S.push(`In-Reply-To: ${n.sanitizeHeaderValue(p)}`),u&&S.push(`References: ${n.sanitizeHeaderValue(u)}`),S.push(`Content-Type: multipart/mixed; boundary="${g}"`),S.push(""),S.push(`--${g}`),y?S.push("Content-Type: text/html; charset=utf-8"):S.push("Content-Type: text/plain; charset=utf-8"),S.push(""),S.push(s);for(let R of f){let x=n.sanitizeHeaderValue(R.contentType||"application/octet-stream"),A=n.sanitizeHeaderFilename(R.filename);S.push(`--${g}`),S.push(`Content-Type: ${x}`),S.push("Content-Transfer-Encoding: base64"),S.push(`Content-Disposition: attachment; filename="${A}"`),S.push("");let C=typeof R.content=="string"?R.content:R.content.toString("base64");for(let v=0;v<C.length;v+=76)S.push(C.slice(v,v+76))}S.push(`--${g}--`);let E=S.join(`\r
51
+ `);return Buffer.from(E).toString("base64url")}static decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf-8")}};var Ro="No labels to add or remove were provided. No action taken.";import{ZodError as jp}from"zod";var Wp={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".html":"text/html",".htm":"text/html",".json":"application/json",".xml":"application/xml",".zip":"application/zip",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".mp4":"video/mp4",".mp3":"audio/mpeg"},xc=18*1024*1024;function vc(n){if(n>xc)throw new Error(`Total attachment size (${(n/1024/1024).toFixed(2)}MB) exceeds the maximum allowed limit of ${xc/1024/1024}MB.`)}function zp(n){let e=Ge.extname(n).toLowerCase();return Wp[e]??"application/octet-stream"}var Mn=class{constructor(e){this.authManager=e;this.search=async({query:e,maxResults:t=100,pageToken:s,labelIds:o,includeSpamTrash:a=!1})=>{try{m(`Gmail search - query: ${e}, maxResults: ${t}`);let d=await(await this.getGmailClient()).users.messages.list({userId:"me",q:e,maxResults:t,pageToken:s,labelIds:o,includeSpamTrash:a}),p=d.data.messages||[],u=d.data.nextPageToken,f=d.data.resultSizeEstimate;return m(`Found ${p.length} messages, estimated total: ${f}`),{content:[{type:"text",text:JSON.stringify({messages:p.map(y=>({id:y.id,threadId:y.threadId})),nextPageToken:u,resultSizeEstimate:f},null,2)}]}}catch(l){return this.handleError(l,"gmail.search")}};this.get=async({messageId:e,format:t="full"})=>{try{m(`Getting message ${e} with format: ${t}`);let a=(await(await this.getGmailClient()).users.messages.get({userId:"me",id:e,format:t})).data;if(t==="metadata"||t==="full"){let l=a.payload?.headers||[],d=S=>l.find(E=>E.name===S)?.value,p=d("Subject"),u=d("From"),f=d("To"),y=d("Date"),g="",_=[];if(t==="full"&&a.payload){let S=this.extractAttachmentsAndBody(a.payload);g=S.body,_=S.attachments}return{content:[{type:"text",text:JSON.stringify({id:a.id,threadId:a.threadId,labelIds:a.labelIds,snippet:a.snippet,subject:p,from:u,to:f,date:y,body:g||a.snippet,attachments:_},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(s){return this.handleError(s,"gmail.get")}};this.downloadAttachment=async({messageId:e,attachmentId:t,localPath:s})=>{try{if(m(`Downloading attachment ${t} from message ${e} to ${s}`),!Ge.isAbsolute(s))throw new Error("localPath must be an absolute path.");let l=(await(await this.getGmailClient()).users.messages.attachments.get({userId:"me",messageId:e,id:t})).data.data;if(!l)throw new Error("Attachment data is empty");await ut.mkdir(Ge.dirname(s),{recursive:!0});let d=Buffer.from(l,"base64url");return await ut.writeFile(s,d),m(`Attachment downloaded successfully to ${s}`),{content:[{type:"text",text:JSON.stringify({message:`Attachment downloaded successfully to ${s}`,path:s})}]}}catch(o){return this.handleError(o,"gmail.downloadAttachment")}};this.modify=async({messageId:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{m(`Modifying message ${e} with addLabelIds: ${t}, removeLabelIds: ${s}`);let l=(await(await this.getGmailClient()).users.messages.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:s}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(o){return this.handleError(o,"gmail.modify")}};this.batchModify=async({messageIds:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{if(t.length===0&&s.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:Ro})}]};if(e.length>1e3)throw new Error(`Too many message IDs. Maximum is ${1e3}, got ${e.length}.`);return m(`Batch modifying ${e.length} messages with addLabelIds: ${t}, removeLabelIds: ${s}`),await(await this.getGmailClient()).users.messages.batchModify({userId:"me",requestBody:{ids:e,addLabelIds:t,removeLabelIds:s}}),{content:[{type:"text",text:JSON.stringify({modifiedCount:e.length,addLabelIds:t,removeLabelIds:s,status:"success"},null,2)}]}}catch(o){return this.handleError(o,"gmail.batchModify")}};this.modifyThread=async({threadId:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{if(t.length===0&&s.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:Ro})}]};m(`Modifying thread ${e} with addLabelIds: ${t}, removeLabelIds: ${s}`);let l=(await(await this.getGmailClient()).users.threads.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:s}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(o){return this.handleError(o,"gmail.modifyThread")}};this.send=async({to:e,subject:t,body:s,cc:o,bcc:a,replyTo:l,isHtml:d=!1})=>{try{let p=this.validateEmailAddresses({to:e,cc:o,bcc:a,replyTo:l});if(p)return p;m(`Sending email to: ${e}, subject: ${t}`);let u=Zt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d}),y=await(await this.getGmailClient()).users.messages.send({userId:"me",requestBody:{raw:u}});return m(`Email sent successfully: ${y.data.id}`),{content:[{type:"text",text:JSON.stringify({id:y.data.id,threadId:y.data.threadId,labelIds:y.data.labelIds,status:"sent"},null,2)}]}}catch(p){return this.handleError(p,"gmail.send")}};this.createDraft=async({to:e,subject:t,body:s,cc:o,bcc:a,replyTo:l,isHtml:d=!1,threadId:p,attachments:u})=>{try{let f=this.validateEmailAddresses({to:e,cc:o,bcc:a,replyTo:l});if(f)return f;m(`Creating draft - to: ${e}, subject: ${t}`);let y=await this.getGmailClient(),g,_;if(p)try{let x=(await y.users.threads.get({userId:"me",id:p,format:"metadata",metadataHeaders:["Message-ID","References"]})).data.messages||[];if(x.length>0){let C=x[x.length-1].payload?.headers||[],v=C.find($=>$.name?.toLowerCase()==="message-id"),k=C.find($=>$.name?.toLowerCase()==="references");if(v?.value){g=v.value;let $=k?.value||"";_=$?`${$} ${v.value}`:v.value}}}catch(R){m(`Warning: Could not fetch thread ${p} for reply headers: ${R}`)}let S;if(u&&u.length>0){let x=(await Promise.all(u.map(async C=>{if(!Ge.isAbsolute(C.filePath))throw new Error(`Attachment filePath must be an absolute path: ${C.filePath}`);let v;try{v=await ut.stat(C.filePath)}catch(k){throw new Error(`Could not access attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}if(!v.isFile())throw new Error(`Attachment path is not a file: ${C.filePath}`);return v.size}))).reduce((C,v)=>C+v,0);vc(x);let A=await Promise.all(u.map(async C=>{let v;try{v=await ut.readFile(C.filePath)}catch(k){throw new Error(`Could not read attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}return{filename:C.filename||Ge.basename(C.filePath),content:v,contentType:C.mimeType||zp(C.filePath)}}));vc(A.reduce((C,v)=>C+v.content.length,0)),S=Zt.createMimeMessageWithAttachments({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,inReplyTo:g,references:_,isHtml:d,attachments:A})}else S=Zt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d,inReplyTo:g,references:_});let E=await y.users.drafts.create({userId:"me",requestBody:{message:{raw:S,...p&&{threadId:p}}}});return m(`Draft created successfully: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify({id:E.data.id,message:{id:E.data.message?.id,threadId:E.data.message?.threadId,labelIds:E.data.message?.labelIds},status:"draft_created"},null,2)}]}}catch(f){return this.handleError(f,"gmail.createDraft")}};this.sendDraft=async({draftId:e})=>{try{m(`Sending draft: ${e}`);let s=await(await this.getGmailClient()).users.drafts.send({userId:"me",requestBody:{id:e}});return m(`Draft sent successfully: ${s.data.id}`),{content:[{type:"text",text:JSON.stringify({id:s.data.id,threadId:s.data.threadId,labelIds:s.data.labelIds,status:"sent"},null,2)}]}}catch(t){return this.handleError(t,"gmail.sendDraft")}};this.listLabels=async()=>{try{m("Listing Gmail labels");let s=(await(await this.getGmailClient()).users.labels.list({userId:"me"})).data.labels||[];return m(`Found ${s.length} labels`),{content:[{type:"text",text:JSON.stringify({labels:s.map(o=>({id:o.id,name:o.name,type:o.type,messageListVisibility:o.messageListVisibility,labelListVisibility:o.labelListVisibility}))},null,2)}]}}catch(e){return this.handleError(e,"gmail.listLabels")}};this.createLabel=async({name:e,labelListVisibility:t="labelShow",messageListVisibility:s="show"})=>{try{m(`Creating Gmail label: ${e}`);let l=(await(await this.getGmailClient()).users.labels.create({userId:"me",requestBody:{name:e,labelListVisibility:t,messageListVisibility:s}})).data;return m(`Created label: ${l.name} with id: ${l.id}`),{content:[{type:"text",text:JSON.stringify({id:l.id,name:l.name,type:l.type,messageListVisibility:l.messageListVisibility,labelListVisibility:l.labelListVisibility,status:"created"},null,2)}]}}catch(o){return this.handleError(o,"gmail.createLabel")}}}async getGmailClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return qp.gmail({version:"v1",...t})}handleError(e,t){let s=e instanceof Error?e.message:String(e);return m(`Error during ${t}: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}validateEmailAddresses({to:e,cc:t,bcc:s,replyTo:o}){try{return at.parse(e),t&&at.parse(t),s&&at.parse(s),o&&at.parse(o),null}catch(a){if(!(a instanceof jp))throw a;return m(`Rejected invalid email address input: ${a.message}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid email address format",details:a.message})}]}}}extractAttachmentsAndBody(e,t={body:"",attachments:[]}){if(!e)return t;if(e.body?.data&&(!e.filename||!e.body.attachmentId)&&e.mimeType?.startsWith("text/")&&(!t.body||e.mimeType==="text/plain")&&(t.body=Buffer.from(e.body.data,"base64").toString("utf-8")),e.filename&&e.body?.attachmentId&&t.attachments.push({filename:e.filename,mimeType:e.mimeType,attachmentId:e.body.attachmentId,size:e.body.size}),e.parts)for(let s of e.parts)this.extractAttachmentsAndBody(s,t);return t}};var Fn=["search","get","downloadAttachment","modify","batchModify","modifyThread","send","createDraft","sendDraft","listLabels","createLabel"],Cc=z(Mn,Fn,{pagination:{search:"maxResults"},bounds:Ka});import{google as Hp}from"googleapis";var Bn=class{constructor(e){this.authManager=e;this.getUserProfile=async({userId:e,email:t,name:s})=>{m(`[PeopleService] Starting getUserProfile with: userId=${e}, email=${t}, name=${s}`);try{if(!e&&!t&&!s)throw new Error("Either userId, email, or name must be provided.");let o=await this.getPeopleClient();if(e){let a=e.startsWith("people/")?e:`people/${e}`,l=await o.people.get({resourceName:a,personFields:"names,emailAddresses"});return m(`[PeopleService] Finished getUserProfile for user: ${e}`),{content:[{type:"text",text:JSON.stringify({results:[{person:l.data}]})}]}}else if(t||s){let a=t||s,l=await o.people.searchDirectoryPeople({query:a,readMask:"names,emailAddresses",sources:["DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT","DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"]});return m(`[PeopleService] Finished getUserProfile search for: ${a}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}else throw new Error("Either userId, email, or name must be provided.")}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[PeopleService] Error during people.getUserProfile: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getMe=async()=>{m("[PeopleService] Starting getMe");try{let t=await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"names,emailAddresses"});return m("[PeopleService] Finished getMe"),{content:[{type:"text",text:JSON.stringify(t.data)}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`[PeopleService] Error during people.getMe: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.getUserRelations=async({userId:e,relationType:t})=>{let s=e?e.startsWith("people/")?e:`people/${e}`:"people/me";m(`[PeopleService] Starting getUserRelations for ${s} with relationType=${t}`);try{let a=await(await this.getPeopleClient()).people.get({resourceName:s,personFields:"relations"});m("[PeopleService] Finished getUserRelations API call");let l=a.data?.relations||[],d=t?l.filter(u=>u.type?.toLowerCase()===t.toLowerCase()):l;t?m(`[PeopleService] Filtered to ${d.length} relations of type: ${t}`):m(`[PeopleService] Returning all ${d.length} relations`);let p={resourceName:s,...t&&{relationType:t},relations:d};return{content:[{type:"text",text:JSON.stringify(p)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[PeopleService] Error during people.getUserRelations: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Hp.people({version:"v1",...t})}};var Un=["getUserProfile","getMe","getUserRelations"],Ac=z(Bn,Un,{bounds:sc});import{google as Gp}from"googleapis";var qn=class n{constructor(e){this.authManager=e;this.getText=async({spreadsheetId:e,format:t="text",max_chars:s,full:o})=>{m(`[SheetsService] Starting getText for spreadsheet: ${e} with format: ${t}`);try{let a=F(e)||e,l=ho(s,o),d=await this.getSheetsClient(),p=await d.spreadsheets.get({spreadsheetId:a,includeGridData:!1}),u="",f={};p.data.properties?.title&&t!=="json"&&(u+=`Spreadsheet Title: ${p.data.properties.title}
52
52
 
53
53
  `);let y=p.data.sheets?.map(E=>E.properties?.title).filter(E=>!!E)||[],g=await this.readAllSheets(d,a,y);for(let{sheetName:E,values:R}of g){if(R===null){t==="json"?m(`[SheetsService] Skipping sheet ${E} in JSON output due to error`):u+=`Sheet Name: ${E}
54
54
  (Error reading sheet)
55
55
 
56
56
  `;continue}if(t==="json")f[E]=R;else{if(u+=`Sheet Name: ${E}
57
57
  `,R.length===0)u+=`(Empty sheet)
58
- `;else if(t==="csv")for(let v=0;v<R.length;v++){let A=R[v];for(let C=0;C<A.length;C++){C>0&&(u+=",");let x=String(A[C]||"");(x.includes(",")||x.includes('"')||x.includes(`
59
- `))&&(x=`"${x.replace(/"/g,'""')}"`),u+=x}u+=`
60
- `}else for(let v=0;v<R.length;v++){let A=R[v];for(let C=0;C<A.length;C++)C>0&&(u+=" | "),u+=A[C]||"";u+=`
58
+ `;else if(t==="csv")for(let x=0;x<R.length;x++){let A=R[x];for(let C=0;C<A.length;C++){C>0&&(u+=",");let v=String(A[C]||"");(v.includes(",")||v.includes('"')||v.includes(`
59
+ `))&&(v=`"${v.replace(/"/g,'""')}"`),u+=v}u+=`
60
+ `}else for(let x=0;x<R.length;x++){let A=R[x];for(let C=0;C<A.length;C++)C>0&&(u+=" | "),u+=A[C]||"";u+=`
61
61
  `}u+=`
62
- `}}t==="json"&&(u=JSON.stringify(f,null,2));let _="Pass a larger max_chars (up to "+1e5+"), full:true, a narrower format, or getRange for one tab.";if(t==="json"){let E=Sc(f,l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a} (${E.returnedRows}/${E.totalRows} rows, ${E.returnedCharacters}/${E.totalCharacters} chars)`),{content:[{type:"text",text:E.text}]}}let S=bc(u.trim(),l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a}`),{content:[{type:"text",text:S.text}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getRange=async({spreadsheetId:e,range:t,max_chars:s,full:o})=>{m(`[SheetsService] Starting getRange for spreadsheet: ${e}, range: ${t}`);try{let a=F(e)||e,l=mo(s,o),p=await(await this.getSheetsClient()).spreadsheets.values.get({spreadsheetId:a,range:t}),u=p.data.values||[],f=JSON.stringify({range:p.data.range,values:u});if(f.length<=l)return m(`[SheetsService] Finished getRange for spreadsheet: ${a}`),{content:[{type:"text",text:f}]};let y=0,g=u.length;for(;y<g;){let E=Math.ceil((y+g)/2);JSON.stringify({range:p.data.range,values:u.slice(0,E)}).length<=l?y=E:g=E-1}let _=JSON.stringify({range:p.data.range,values:u.slice(0,y)}),S="Pass a larger max_chars (up to "+1e5+"), full:true, or narrow the range.";return m(`[SheetsService] Finished getRange for spreadsheet: ${a} (${y}/${u.length} rows)`),{content:[{type:"text",text:JSON.stringify({range:p.data.range,values:u.slice(0,y),truncated:!0,total_characters:f.length,returned_characters:_.length,returned_rows:y,total_rows:u.length,truncation_note:Vt(f.length,_.length,S)},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getRange: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getMetadata=async({spreadsheetId:e})=>{m(`[SheetsService] Starting getMetadata for spreadsheet: ${e}`);try{let t=F(e)||e,o=await(await this.getSheetsClient()).spreadsheets.get({spreadsheetId:t,includeGridData:!1}),a={spreadsheetId:o.data.spreadsheetId,title:o.data.properties?.title,sheets:o.data.sheets?.map(l=>({sheetId:l.properties?.sheetId,title:l.properties?.title,index:l.properties?.index,rowCount:l.properties?.gridProperties?.rowCount,columnCount:l.properties?.gridProperties?.columnCount})),locale:o.data.properties?.locale,timeZone:o.data.properties?.timeZone};return m(`[SheetsService] Finished getMetadata for spreadsheet: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SheetsService] Error during sheets.getMetadata: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getSheetsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Hp.sheets({version:"v4",...t})}static sheetRange(e){return`'${e.replace(/'/g,"''")}'`}async readAllSheets(e,t,s){if(s.length===0)return[];let o=s.map(l=>n.sheetRange(l));try{let d=(await e.spreadsheets.values.batchGet({spreadsheetId:t,ranges:o})).data.valueRanges;if(!d||d.length!==o.length)throw new Error(`batchGet returned ${d?.length??0} value ranges for ${o.length} sheets`);return s.map((p,u)=>({sheetName:p,values:d[u].values||[]}))}catch(l){m(`[SheetsService] batchGet failed, falling back to per-sheet reads: ${l}`)}return await Promise.all(s.map(async l=>{try{let d=await e.spreadsheets.values.get({spreadsheetId:t,range:n.sheetRange(l)});return{sheetName:l,values:d.data.values||[]}}catch(d){return m(`[SheetsService] Error reading sheet ${l}: ${d}`),{sheetName:l,values:null}}}))}};var qn=["getText","getRange","getMetadata"],Pc=z(Un,qn);import{google as wh}from"googleapis";import*as ds from"node:fs/promises";import*as or from"node:path";var uu=Ht(Ro(),1);import{Agent as gh}from"https";var vo=Ht(Ro(),1),qc=Ht(Uc(),1),xo=qc.default.pkg,Eo=Symbol.for(`${xo.name}-gaxios-error`),Oe=class n extends Error{config;response;code;status;error;[Eo]=xo.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Eo in e&&e[Eo]===xo.version?!0:Function.prototype[Symbol.hasInstance].call(n,e)}constructor(e,t,s,o){if(super(e,{cause:o}),this.config=t,this.response=s,this.error=o instanceof Error?o:void 0,this.config=(0,vo.default)(!0,{},t),this.response&&(this.response.config=(0,vo.default)(!0,{},this.response.config)),this.response){try{this.response.data=Vp(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,t="The request failed"){let s=t;if(typeof e.data=="string"&&(s=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"){s="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:s;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="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 l=[];for(let d of e.data.error.errors)typeof d=="object"&&"message"in d&&typeof d.message=="string"&&l.push(d.message);return Object.assign({message:l.join(`
63
- `)||s,code:a,status:o},e.data.error)}return Object.assign({message:s,code:a,status:o},e.data.error)}}return{message:s,code:e.status,status:e.statusText}}};function Vp(n,e){switch(n){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 Co(n){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((l,d)=>{(/^authentication$/i.test(d)||/^authorization$/i.test(d)||/secret/i.test(d))&&a.set(d,e)})}function s(a,l){if(typeof a=="object"&&a!==null&&typeof a[l]=="string"){let d=a[l];(/grant_type=/i.test(d)||/assertion=/i.test(d)||/secret/i.test(d))&&(a[l]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((l,d)=>{(["grant_type","assertion"].includes(d)||/secret/.test(d))&&a.set(d,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return n.config&&(t(n.config.headers),s(n.config,"data"),o(n.config.data),s(n.config,"body"),o(n.config.body),n.config.url.searchParams.has("token")&&n.config.url.searchParams.set("token",e),n.config.url.searchParams.has("client_secret")&&n.config.url.searchParams.set("client_secret",e)),n.response&&(Co({config:n.response.config}),t(n.response.headers),n.response.bodyUsed&&(s(n.response,"data"),o(n.response.data))),n}async function jc(n){let e=Wc(n);if(!n||!n.config||!e&&!n.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 t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,n.config.retryConfig=e,!await(e.shouldRetry||Yp)(n))return{shouldRetry:!1,config:n.config};let o=Zp(e);n.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(n,o):new Promise(l=>{setTimeout(l,o)});return e.onRetryAttempt&&await e.onRetryAttempt(n),await a,{shouldRetry:!0,config:n.config}}function Yp(n){let e=Wc(n);if(n.config.signal?.aborted&&n.code!=="TimeoutError"||n.code==="AbortError"||!e||e.retry===0||!n.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(n.config.method?.toUpperCase()||"GET"))return!1;if(n.response&&n.response.status){let t=!1;for(let[s,o]of e.statusCodesToRetry){let a=n.response.status;if(a>=s&&a<=o){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Wc(n){if(n&&n.config&&n.config.retryConfig)return n.config.retryConfig}function Zp(n){let t=(n.currentRetryAttempt?0:n.retryDelay??100)+(Math.pow(n.retryDelayMultiplier,n.currentRetryAttempt)-1)/2*1e3,s=n.totalTimeout-(Date.now()-n.timeOfFirstRequest);return Math.min(t,s,n.maxRetryDelay)}import{Readable as lu}from"stream";var Rr=class extends Set{};var sr,yh=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),bh=204,kr=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Rr,response:new Rr}}fetch(...e){let t=e[0],s=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&sr.mergeHeaders(a,t.headers),s&&sr.mergeHeaders(a,new Headers(s.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...s,...t,headers:a,url:o}):this.request({...s,headers:a,url:o})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await sr.#c(),s={...e};delete s.data;let o=await t(e.url,s),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let a of t.data)o.push(a);t.data=Buffer.concat(o.map(a=>typeof a=="string"?Buffer.from(a):a)).toString("utf8")}let s=Oe.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Oe(s?.message,e,t,s)}return t}catch(t){let s;t instanceof Oe?s=t:t instanceof Error?s=new Oe(t.message,e,void 0,t):s=new Oe("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:a}=await jc(s);if(o&&a)return s.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=s.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(s),s}}async getResponseData(e,t){if(t.status===bh)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Oe("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let s=await t.text();try{return JSON.parse(s)}catch{return s}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let s=new URL(e),o=[...t],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let l of a)o.push(l.trim());for(let l of o)if(l instanceof RegExp){if(l.test(s.toString()))return!1}else if(l instanceof URL){if(l.origin===s.origin)return!1}else if(l.startsWith("*.")||l.startsWith(".")){let d=l.replace(/^\*\./,".");if(s.hostname.endsWith(d))return!1}else if(l===s.origin||l===s.hostname||l===s.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let s of this.interceptors.request.values())s&&(t=t.then(s.resolved,s.rejected));return t}async#r(e){let t=Promise.resolve(e);for(let s of this.interceptors.response.values())s&&(t=t.then(s.resolved,s.rejected));return t}async#n(e){let t=new Headers(this.defaults.headers);sr.mergeHeaders(t,e.headers);let s=(0,uu.default)(!0,{},this.defaults,e);if(!s.url)throw new Error("URL is required.");if(s.baseURL&&(s.url=new URL(s.url,s.baseURL)),s.url=new URL(s.url),s.params)if(s.paramsSerializer){let l=s.paramsSerializer(s.params);l.startsWith("?")&&(l=l.slice(1));let d=s.url.toString().includes("?")?"&":"?";s.url=s.url+d+l}else{let l=s.url instanceof URL?s.url:new URL(s.url);for(let[d,p]of new URLSearchParams(s.params))l.searchParams.append(d,p);s.url=l}typeof e.maxContentLength=="number"&&(s.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(s.follow=e.maxRedirects);let o=typeof s.data=="string"||s.data instanceof ArrayBuffer||s.data instanceof Blob||globalThis.File&&s.data instanceof File||s.data instanceof FormData||s.data instanceof lu||s.data instanceof ReadableStream||s.data instanceof String||s.data instanceof URLSearchParams||ArrayBuffer.isView(s.data)||["Blob","File","FormData"].includes(s.data?.constructor?.name||"");if(s.multipart?.length){let l=await yh();t.set("content-type",`multipart/related; boundary=${l}`),s.body=lu.from(this.getMultipartRequest(s.multipart,l))}else o?s.body=s.data:typeof s.data=="object"?t.get("Content-Type")==="application/x-www-form-urlencoded"?s.body=s.paramsSerializer?s.paramsSerializer(s.data):new URLSearchParams(s.data):(t.has("content-type")||t.set("content-type","application/json"),s.body=JSON.stringify(s.data)):s.data&&(s.body=s.data);s.validateStatus=s.validateStatus||this.validateStatus,s.responseType=s.responseType||"unknown",!t.has("accept")&&s.responseType==="json"&&t.set("accept","application/json");let a=s.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!s.agent)if(a&&this.#e(s.url,s.noProxy)){let l=await sr.#a();this.agentCache.has(a)?s.agent=this.agentCache.get(a):(s.agent=new l(a,{cert:s.cert,key:s.key}),this.agentCache.set(a,s.agent))}else s.cert&&s.key&&(this.agentCache.has(s.key)?s.agent=this.agentCache.get(s.key):(s.agent=new gh({cert:s.cert,key:s.key}),this.agentCache.set(s.key,s.agent)));return typeof s.errorRedactor!="function"&&s.errorRedactor!==!1&&(s.errorRedactor=Co),s.body&&!("duplex"in s)&&(s.duplex="half"),this.#s(s),Object.assign(s,{headers:t,url:s.url instanceof URL?s.url:new URL(s.url)})}#s(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let s=await e.text();try{s=JSON.parse(s)}catch{}return s}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let s=`--${t}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r
62
+ `}}t==="json"&&(u=JSON.stringify(f,null,2));let _="Pass a larger max_chars (up to "+1e5+"), full:true, a narrower format, or getRange for one tab.";if(t==="json"){let E=wc(f,l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a} (${E.returnedRows}/${E.totalRows} rows, ${E.returnedCharacters}/${E.totalCharacters} chars)`),{content:[{type:"text",text:E.text}]}}let S=Sc(u.trim(),l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a}`),{content:[{type:"text",text:S.text}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getRange=async({spreadsheetId:e,range:t,max_chars:s,full:o})=>{m(`[SheetsService] Starting getRange for spreadsheet: ${e}, range: ${t}`);try{let a=F(e)||e,l=ho(s,o),p=await(await this.getSheetsClient()).spreadsheets.values.get({spreadsheetId:a,range:t}),u=p.data.values||[],f=JSON.stringify({range:p.data.range,values:u});if(f.length<=l)return m(`[SheetsService] Finished getRange for spreadsheet: ${a}`),{content:[{type:"text",text:f}]};let y=0,g=u.length;for(;y<g;){let E=Math.ceil((y+g)/2);JSON.stringify({range:p.data.range,values:u.slice(0,E)}).length<=l?y=E:g=E-1}let _=JSON.stringify({range:p.data.range,values:u.slice(0,y)}),S="Pass a larger max_chars (up to "+1e5+"), full:true, or narrow the range.";return m(`[SheetsService] Finished getRange for spreadsheet: ${a} (${y}/${u.length} rows)`),{content:[{type:"text",text:JSON.stringify({range:p.data.range,values:u.slice(0,y),truncated:!0,total_characters:f.length,returned_characters:_.length,returned_rows:y,total_rows:u.length,truncation_note:Yt(f.length,_.length,S)},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getRange: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getMetadata=async({spreadsheetId:e})=>{m(`[SheetsService] Starting getMetadata for spreadsheet: ${e}`);try{let t=F(e)||e,o=await(await this.getSheetsClient()).spreadsheets.get({spreadsheetId:t,includeGridData:!1}),a={spreadsheetId:o.data.spreadsheetId,title:o.data.properties?.title,sheets:o.data.sheets?.map(l=>({sheetId:l.properties?.sheetId,title:l.properties?.title,index:l.properties?.index,rowCount:l.properties?.gridProperties?.rowCount,columnCount:l.properties?.gridProperties?.columnCount})),locale:o.data.properties?.locale,timeZone:o.data.properties?.timeZone};return m(`[SheetsService] Finished getMetadata for spreadsheet: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SheetsService] Error during sheets.getMetadata: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getSheetsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Gp.sheets({version:"v4",...t})}static sheetRange(e){return`'${e.replace(/'/g,"''")}'`}async readAllSheets(e,t,s){if(s.length===0)return[];let o=s.map(l=>n.sheetRange(l));try{let d=(await e.spreadsheets.values.batchGet({spreadsheetId:t,ranges:o})).data.valueRanges;if(!d||d.length!==o.length)throw new Error(`batchGet returned ${d?.length??0} value ranges for ${o.length} sheets`);return s.map((p,u)=>({sheetName:p,values:d[u].values||[]}))}catch(l){m(`[SheetsService] batchGet failed, falling back to per-sheet reads: ${l}`)}return await Promise.all(s.map(async l=>{try{let d=await e.spreadsheets.values.get({spreadsheetId:t,range:n.sheetRange(l)});return{sheetName:l,values:d.data.values||[]}}catch(d){return m(`[SheetsService] Error reading sheet ${l}: ${d}`),{sheetName:l,values:null}}}))}};var jn=["getText","getRange","getMetadata"],Ic=z(qn,jn);import{google as _h}from"googleapis";import*as fs from"node:fs/promises";import*as ir from"node:path";var du=Ht(Eo(),1);import{Agent as yh}from"https";var vo=Ht(Eo(),1),jc=Ht(qc(),1),Co=jc.default.pkg,xo=Symbol.for(`${Co.name}-gaxios-error`),Oe=class n extends Error{config;response;code;status;error;[xo]=Co.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&xo in e&&e[xo]===Co.version?!0:Function.prototype[Symbol.hasInstance].call(n,e)}constructor(e,t,s,o){if(super(e,{cause:o}),this.config=t,this.response=s,this.error=o instanceof Error?o:void 0,this.config=(0,vo.default)(!0,{},t),this.response&&(this.response.config=(0,vo.default)(!0,{},this.response.config)),this.response){try{this.response.data=Yp(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,t="The request failed"){let s=t;if(typeof e.data=="string"&&(s=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"){s="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:s;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="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 l=[];for(let d of e.data.error.errors)typeof d=="object"&&"message"in d&&typeof d.message=="string"&&l.push(d.message);return Object.assign({message:l.join(`
63
+ `)||s,code:a,status:o},e.data.error)}return Object.assign({message:s,code:a,status:o},e.data.error)}}return{message:s,code:e.status,status:e.statusText}}};function Yp(n,e){switch(n){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 Ao(n){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((l,d)=>{(/^authentication$/i.test(d)||/^authorization$/i.test(d)||/secret/i.test(d))&&a.set(d,e)})}function s(a,l){if(typeof a=="object"&&a!==null&&typeof a[l]=="string"){let d=a[l];(/grant_type=/i.test(d)||/assertion=/i.test(d)||/secret/i.test(d))&&(a[l]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((l,d)=>{(["grant_type","assertion"].includes(d)||/secret/.test(d))&&a.set(d,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return n.config&&(t(n.config.headers),s(n.config,"data"),o(n.config.data),s(n.config,"body"),o(n.config.body),n.config.url.searchParams.has("token")&&n.config.url.searchParams.set("token",e),n.config.url.searchParams.has("client_secret")&&n.config.url.searchParams.set("client_secret",e)),n.response&&(Ao({config:n.response.config}),t(n.response.headers),n.response.bodyUsed&&(s(n.response,"data"),o(n.response.data))),n}async function Wc(n){let e=zc(n);if(!n||!n.config||!e&&!n.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 t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,n.config.retryConfig=e,!await(e.shouldRetry||Zp)(n))return{shouldRetry:!1,config:n.config};let o=Xp(e);n.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(n,o):new Promise(l=>{setTimeout(l,o)});return e.onRetryAttempt&&await e.onRetryAttempt(n),await a,{shouldRetry:!0,config:n.config}}function Zp(n){let e=zc(n);if(n.config.signal?.aborted&&n.code!=="TimeoutError"||n.code==="AbortError"||!e||e.retry===0||!n.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(n.config.method?.toUpperCase()||"GET"))return!1;if(n.response&&n.response.status){let t=!1;for(let[s,o]of e.statusCodesToRetry){let a=n.response.status;if(a>=s&&a<=o){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function zc(n){if(n&&n.config&&n.config.retryConfig)return n.config.retryConfig}function Xp(n){let t=(n.currentRetryAttempt?0:n.retryDelay??100)+(Math.pow(n.retryDelayMultiplier,n.currentRetryAttempt)-1)/2*1e3,s=n.totalTimeout-(Date.now()-n.timeOfFirstRequest);return Math.min(t,s,n.maxRetryDelay)}import{Readable as uu}from"stream";var xr=class extends Set{};var or,bh=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Sh=204,Dr=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new xr,response:new xr}}fetch(...e){let t=e[0],s=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&or.mergeHeaders(a,t.headers),s&&or.mergeHeaders(a,new Headers(s.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...s,...t,headers:a,url:o}):this.request({...s,headers:a,url:o})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await or.#c(),s={...e};delete s.data;let o=await t(e.url,s),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let a of t.data)o.push(a);t.data=Buffer.concat(o.map(a=>typeof a=="string"?Buffer.from(a):a)).toString("utf8")}let s=Oe.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Oe(s?.message,e,t,s)}return t}catch(t){let s;t instanceof Oe?s=t:t instanceof Error?s=new Oe(t.message,e,void 0,t):s=new Oe("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:a}=await Wc(s);if(o&&a)return s.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=s.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(s),s}}async getResponseData(e,t){if(t.status===Sh)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Oe("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let s=await t.text();try{return JSON.parse(s)}catch{return s}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let s=new URL(e),o=[...t],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let l of a)o.push(l.trim());for(let l of o)if(l instanceof RegExp){if(l.test(s.toString()))return!1}else if(l instanceof URL){if(l.origin===s.origin)return!1}else if(l.startsWith("*.")||l.startsWith(".")){let d=l.replace(/^\*\./,".");if(s.hostname.endsWith(d))return!1}else if(l===s.origin||l===s.hostname||l===s.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let s of this.interceptors.request.values())s&&(t=t.then(s.resolved,s.rejected));return t}async#r(e){let t=Promise.resolve(e);for(let s of this.interceptors.response.values())s&&(t=t.then(s.resolved,s.rejected));return t}async#n(e){let t=new Headers(this.defaults.headers);or.mergeHeaders(t,e.headers);let s=(0,du.default)(!0,{},this.defaults,e);if(!s.url)throw new Error("URL is required.");if(s.baseURL&&(s.url=new URL(s.url,s.baseURL)),s.url=new URL(s.url),s.params)if(s.paramsSerializer){let l=s.paramsSerializer(s.params);l.startsWith("?")&&(l=l.slice(1));let d=s.url.toString().includes("?")?"&":"?";s.url=s.url+d+l}else{let l=s.url instanceof URL?s.url:new URL(s.url);for(let[d,p]of new URLSearchParams(s.params))l.searchParams.append(d,p);s.url=l}typeof e.maxContentLength=="number"&&(s.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(s.follow=e.maxRedirects);let o=typeof s.data=="string"||s.data instanceof ArrayBuffer||s.data instanceof Blob||globalThis.File&&s.data instanceof File||s.data instanceof FormData||s.data instanceof uu||s.data instanceof ReadableStream||s.data instanceof String||s.data instanceof URLSearchParams||ArrayBuffer.isView(s.data)||["Blob","File","FormData"].includes(s.data?.constructor?.name||"");if(s.multipart?.length){let l=await bh();t.set("content-type",`multipart/related; boundary=${l}`),s.body=uu.from(this.getMultipartRequest(s.multipart,l))}else o?s.body=s.data:typeof s.data=="object"?t.get("Content-Type")==="application/x-www-form-urlencoded"?s.body=s.paramsSerializer?s.paramsSerializer(s.data):new URLSearchParams(s.data):(t.has("content-type")||t.set("content-type","application/json"),s.body=JSON.stringify(s.data)):s.data&&(s.body=s.data);s.validateStatus=s.validateStatus||this.validateStatus,s.responseType=s.responseType||"unknown",!t.has("accept")&&s.responseType==="json"&&t.set("accept","application/json");let a=s.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!s.agent)if(a&&this.#e(s.url,s.noProxy)){let l=await or.#a();this.agentCache.has(a)?s.agent=this.agentCache.get(a):(s.agent=new l(a,{cert:s.cert,key:s.key}),this.agentCache.set(a,s.agent))}else s.cert&&s.key&&(this.agentCache.has(s.key)?s.agent=this.agentCache.get(s.key):(s.agent=new yh({cert:s.cert,key:s.key}),this.agentCache.set(s.key,s.agent)));return typeof s.errorRedactor!="function"&&s.errorRedactor!==!1&&(s.errorRedactor=Ao),s.body&&!("duplex"in s)&&(s.duplex="half"),this.#s(s),Object.assign(s,{headers:t,url:s.url instanceof URL?s.url:new URL(s.url)})}#s(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let s=await e.text();try{s=JSON.parse(s)}catch{}return s}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let s=`--${t}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r
64
64
  Content-Type: ${a}\r
65
65
  \r
66
66
  `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
67
- `}yield s}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Ht(ml(),1))).HttpsProxyAgent,this.#o}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(cu(),au))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let s of t)(s instanceof Headers?s:new Headers(s)).forEach((a,l)=>{l==="set-cookie"?e.append(l,a):e.set(l,a)});return e}};sr=kr;var Sh=new kr;async function du(n){return Sh.request(n)}var fu=["BLANK","TITLE","TITLE_AND_BODY","TITLE_AND_TWO_COLUMNS","TITLE_ONLY","SECTION_HEADER","SECTION_TITLE_AND_DESCRIPTION","ONE_COLUMN_TEXT","MAIN_POINT","BIG_NUMBER"],pu=["ALL","FIXED_RANGE","FROM_START_INDEX"],us=class{constructor(e){this.authManager=e;this.getText=async({presentationId:e})=>{m(`[SlidesService] Starting getText for presentation: ${e}`);try{let t=F(e)||e,o=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"title,slides(pageElements(shape(text,shapeProperties),table(tableRows(tableCells(text)))))"}),a="";return o.data.title&&(a+=`Presentation Title: ${o.data.title}
67
+ `}yield s}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Ht(hl(),1))).HttpsProxyAgent,this.#o}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(lu(),cu))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let s of t)(s instanceof Headers?s:new Headers(s)).forEach((a,l)=>{l==="set-cookie"?e.append(l,a):e.set(l,a)});return e}};or=Dr;var wh=new Dr;async function fu(n){return wh.request(n)}var pu=["BLANK","TITLE","TITLE_AND_BODY","TITLE_AND_TWO_COLUMNS","TITLE_ONLY","SECTION_HEADER","SECTION_TITLE_AND_DESCRIPTION","ONE_COLUMN_TEXT","MAIN_POINT","BIG_NUMBER"],mu=["ALL","FIXED_RANGE","FROM_START_INDEX"],ds=class{constructor(e){this.authManager=e;this.getText=async({presentationId:e})=>{m(`[SlidesService] Starting getText for presentation: ${e}`);try{let t=F(e)||e,o=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"title,slides(pageElements(shape(text,shapeProperties),table(tableRows(tableCells(text)))))"}),a="";return o.data.title&&(a+=`Presentation Title: ${o.data.title}
68
68
 
69
69
  `),o.data.slides&&o.data.slides.forEach((l,d)=>{a+=`
70
70
  --- Slide ${d+1} ---
@@ -74,8 +74,8 @@ Content-Type: ${a}\r
74
74
  `,p.table.tableRows.forEach(u=>{let f=[];u.tableCells&&u.tableCells.forEach(y=>{let g=y.text?this.extractTextFromTextContent(y.text):"";f.push(g.trim())}),a+=f.join(" | ")+`
75
75
  `}),a+=`--- End Table Data ---
76
76
  `)}),a+=`
77
- `}),m(`[SlidesService] Finished getText for presentation: ${t}`),{content:[{type:"text",text:a.trim()}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getText: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.getMetadata=async({presentationId:e})=>{m(`[SlidesService] Starting getMetadata for presentation: ${e}`);try{let t=F(e)||e,o=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"presentationId,title,slides(objectId),pageSize,notesMaster,masters,layouts"}),a={presentationId:o.data.presentationId,title:o.data.title,slideCount:o.data.slides?.length||0,slides:o.data.slides?.map(({objectId:l})=>({objectId:l}))??[],pageSize:o.data.pageSize,hasMasters:!!o.data.masters?.length,hasLayouts:!!o.data.layouts?.length,hasNotesMaster:!!o.data.notesMaster};return m(`[SlidesService] Finished getMetadata for presentation: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getMetadata: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.getImages=async({presentationId:e,localPath:t})=>{m(`[SlidesService] Starting getImages for presentation: ${e} (localPath: ${t})`);try{let s=F(e)||e,a=await(await this.getSlidesClient()).presentations.get({presentationId:s,fields:"slides(objectId,pageElements(objectId,title,description,image(contentUrl,sourceUrl)))"}),l=await Promise.all((a.data.slides??[]).flatMap((d,p)=>(d.pageElements??[]).filter(u=>u.image).map(async u=>{let f={slideIndex:p+1,slideObjectId:d.objectId,elementObjectId:u.objectId,title:u.title,description:u.description,contentUrl:u.image?.contentUrl,sourceUrl:u.image?.sourceUrl};if(f.contentUrl){let y=`slide_${f.slideIndex}_${u.objectId}.png`,g=or.join(t,y);try{await this.downloadToLocal(f.contentUrl,g),f.localPath=g}catch(_){m(`[SlidesService] Failed to download image ${u.objectId}: ${_}`),f.downloadError=String(_)}}return f})));return m(`[SlidesService] Finished getImages for presentation: ${s}`),{content:[{type:"text",text:JSON.stringify({images:l})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`[SlidesService] Error during slides.getImages: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.create=async({title:e})=>{m(`[SlidesService] Creating presentation: ${e}`);try{let s=await(await this.getSlidesClient()).presentations.create({requestBody:{title:e}}),o={presentationId:s.data.presentationId,title:s.data.title,url:`https://docs.google.com/presentation/d/${s.data.presentationId}/edit`};return m(`[SlidesService] Created presentation: ${o.presentationId}`),this.formatResult(o)}catch(t){return this.formatError("slides.create",t)}};this.addSlide=async({presentationId:e,insertionIndex:t,layoutId:s,predefinedLayout:o,objectId:a})=>{m(`[SlidesService] Adding slide to presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p={};if(t!==void 0&&(p.insertionIndex=t),a&&(p.objectId=a),s)p.slideLayoutReference={layoutId:s};else if(o){if(!fu.includes(o))throw new Error(`Invalid predefinedLayout "${o}". Expected one of: ${fu.join(", ")}.`);p.slideLayoutReference={predefinedLayout:o}}let f=(await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{createSlide:p}]}})).data.replies?.[0]?.createSlide?.objectId;if(!f)throw new Error("createSlide returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added slide: ${f}`),this.formatResult({presentationId:l,slideObjectId:f})}catch(l){return this.formatError("slides.addSlide",l)}};this.deleteSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Deleting slide ${t} from presentation: ${e}`);try{let s=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{deleteObject:{objectId:t}}]}}),m(`[SlidesService] Deleted slide: ${t}`),this.formatResult({presentationId:s,deletedSlideObjectId:t})}catch(s){return this.formatError("slides.deleteSlide",s)}};this.duplicateSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Duplicating slide ${t} in presentation: ${e}`);try{let s=F(e)||e,l=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{duplicateObject:{objectId:t}}]}})).data.replies?.[0]?.duplicateObject?.objectId;if(!l)throw new Error("duplicateObject returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Duplicated slide to: ${l}`),this.formatResult({presentationId:s,sourceSlideObjectId:t,newSlideObjectId:l})}catch(s){return this.formatError("slides.duplicateSlide",s)}};this.reorderSlides=async({presentationId:e,slideObjectIds:t,insertionIndex:s})=>{m(`[SlidesService] Reordering slides in presentation: ${e}`);try{let o=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:o,requestBody:{requests:[{updateSlidesPosition:{slideObjectIds:t,insertionIndex:s}}]}}),m(`[SlidesService] Reordered slides in presentation: ${o}`),this.formatResult({presentationId:o,slideObjectIds:t,insertionIndex:s})}catch(o){return this.formatError("slides.reorderSlides",o)}};this.getSpeakerNotes=async({presentationId:e})=>{m(`[SlidesService] Getting speaker notes for presentation: ${e}`);try{let t=F(e)||e,a=((await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides??[]).map((l,d)=>{let p=l.slideProperties?.notesPage,u=p?.notesProperties?.speakerNotesObjectId,f="";if(u&&p?.pageElements){let y=p.pageElements.find(g=>g.objectId===u);y?.shape?.text&&(f=this.extractTextFromTextContent(y.shape.text).trim())}return{slideIndex:d,slideObjectId:l.objectId,speakerNotesObjectId:u,notes:f}});return m(`[SlidesService] Retrieved speaker notes for presentation: ${t}`),this.formatResult({presentationId:t,slides:a})}catch(t){return this.formatError("slides.getSpeakerNotes",t)}};this.updateSpeakerNotes=async({presentationId:e,slideObjectId:t,notes:s})=>{m(`[SlidesService] Updating speaker notes for slide ${t} in presentation: ${e}`);try{let o=F(e)||e,a=await this.getSlidesClient(),d=(await a.presentations.get({presentationId:o,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides?.find(g=>g.objectId===t);if(!d)throw new Error(`Slide not found: ${t}`);let p=d.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;if(!p)throw new Error(`Speaker notes object not found for slide: ${t}`);let u=[];d.slideProperties?.notesPage?.pageElements?.find(g=>g.objectId===p)?.shape?.text?.textElements?.length&&u.push({deleteText:{objectId:p,textRange:{type:"ALL"}}}),s.length>0&&u.push({insertText:{objectId:p,insertionIndex:0,text:s}});let y=u.length===0;return y?m(`[SlidesService] updateSpeakerNotes is a no-op for slide ${t} (existing notes already match input).`):await a.presentations.batchUpdate({presentationId:o,requestBody:{requests:u}}),m(`[SlidesService] Updated speaker notes for slide: ${t}`),this.formatResult({presentationId:o,slideObjectId:t,speakerNotesObjectId:p,notes:s,noOp:y})}catch(o){return this.formatError("slides.updateSpeakerNotes",o)}};this.replaceAllText=async({presentationId:e,findText:t,replaceText:s,matchCase:o=!0})=>{m(`[SlidesService] Replacing all text in presentation: ${e}`);try{let a=F(e)||e,p=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{replaceAllText:{containsText:{text:t,matchCase:o},replaceText:s}}]}})).data.replies?.[0]?.replaceAllText;if(!p)throw new Error("replaceAllText returned no reply; batchUpdate reply was empty or malformed.");let u=p.occurrencesChanged??0;return m(`[SlidesService] Replaced ${u} occurrences in presentation: ${a}`),this.formatResult({presentationId:a,findText:t,replaceText:s,occurrencesChanged:u})}catch(a){return this.formatError("slides.replaceAllText",a)}};this.insertText=async({presentationId:e,objectId:t,text:s,insertionIndex:o=0})=>{m(`[SlidesService] Inserting text into object ${t} in presentation: ${e}`);try{let a=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{insertText:{objectId:t,insertionIndex:o,text:s}}]}}),m(`[SlidesService] Inserted text into object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,insertionIndex:o,textLength:s.length})}catch(a){return this.formatError("slides.insertText",a)}};this.deleteText=async({presentationId:e,objectId:t,range:s={type:"ALL"}})=>{m(`[SlidesService] Deleting text from object ${t} in presentation: ${e}`);try{let o=F(e)||e,a=await this.getSlidesClient(),l=this.buildRange(s);return await a.presentations.batchUpdate({presentationId:o,requestBody:{requests:[{deleteText:{objectId:t,textRange:l}}]}}),m(`[SlidesService] Deleted text from object ${t} in presentation: ${o}`),this.formatResult({presentationId:o,objectId:t,textRange:l})}catch(o){return this.formatError("slides.deleteText",o)}};this.addShape=async({presentationId:e,slideObjectId:t,shapeType:s,x:o,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding shape to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={shapeType:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:o,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createShape:y}]}})).data.replies?.[0]?.createShape?.objectId;if(!_)throw new Error("createShape returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added shape: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,shapeObjectId:_,shapeType:s})}catch(u){return this.formatError("slides.addShape",u)}};this.addImage=async({presentationId:e,slideObjectId:t,imageUrl:s,x:o,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding image to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={url:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:o,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createImage:y}]}})).data.replies?.[0]?.createImage?.objectId;if(!_)throw new Error("createImage returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added image: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,imageObjectId:_,imageUrl:s})}catch(u){return this.formatError("slides.addImage",u)}};this.addTable=async({presentationId:e,slideObjectId:t,rows:s,columns:o,x:a,y:l,width:d,height:p,objectId:u})=>{m(`[SlidesService] Adding table to slide ${t} in presentation: ${e}`);try{let f=F(e)||e,y=await this.getSlidesClient(),g={rows:s,columns:o,elementProperties:{pageObjectId:t,size:{width:{magnitude:d,unit:"PT"},height:{magnitude:p,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:a,translateY:l,unit:"PT"}}};u&&(g.objectId=u);let S=(await y.presentations.batchUpdate({presentationId:f,requestBody:{requests:[{createTable:g}]}})).data.replies?.[0]?.createTable?.objectId;if(!S)throw new Error("createTable returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added table: ${S}`),this.formatResult({presentationId:f,slideObjectId:t,tableObjectId:S,rows:s,columns:o})}catch(f){return this.formatError("slides.addTable",f)}};this.updateTextStyle=async({presentationId:e,objectId:t,style:s,range:o={type:"ALL"},fields:a})=>{m(`[SlidesService] Updating text style for object ${t} in presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p=this.parseJsonObject(s,"style",'{"bold": true}'),u=this.buildRange(o);return await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{updateTextStyle:{objectId:t,textRange:u,style:p,fields:a}}]}}),m(`[SlidesService] Updated text style for object ${t} in presentation: ${l}`),this.formatResult({presentationId:l,objectId:t,textRange:u,fields:a})}catch(l){return this.formatError("slides.updateTextStyle",l)}};this.updateShapeProperties=async({presentationId:e,objectId:t,shapeProperties:s,fields:o})=>{m(`[SlidesService] Updating shape properties for object ${t} in presentation: ${e}`);try{let a=F(e)||e,l=await this.getSlidesClient(),d=this.parseJsonObject(s,"shapeProperties",'{"shapeBackgroundFill": {...}}');return await l.presentations.batchUpdate({presentationId:a,requestBody:{requests:[{updateShapeProperties:{objectId:t,shapeProperties:d,fields:o}}]}}),m(`[SlidesService] Updated shape properties for object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,fields:o})}catch(a){return this.formatError("slides.updateShapeProperties",a)}};this.getSlideThumbnail=async({presentationId:e,slideObjectId:t,localPath:s})=>{m(`[SlidesService] Starting getSlideThumbnail for presentation: ${e}, slide: ${t} (localPath: ${s})`);try{let o=F(e)||e,d={...(await(await this.getSlidesClient()).presentations.pages.getThumbnail({presentationId:o,pageObjectId:t})).data};if(d.contentUrl)try{await this.downloadToLocal(d.contentUrl,s),d.localPath=s}catch(p){m(`[SlidesService] Failed to download thumbnail for slide ${t}: ${p}`),d.downloadError=String(p)}return m(`[SlidesService] Finished getSlideThumbnail for slide: ${t}`),{content:[{type:"text",text:JSON.stringify(d)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[SlidesService] Error during slides.getSlideThumbnail: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getSlidesClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return wh.slides({version:"v1",...t})}extractTextFromTextContent(e){let t="";return e.textElements&&e.textElements.forEach(s=>{s.textRun&&s.textRun.content?t+=s.textRun.content:s.paragraphMarker&&(t+=`
78
- `)}),t}async downloadToLocal(e,t){if(m(`[SlidesService] Downloading from ${e} to ${t}`),!or.isAbsolute(t))throw new Error("localPath must be an absolute path.");await ds.mkdir(or.dirname(t),{recursive:!0});let s=await du({url:e,responseType:"arraybuffer",...W});return await ds.writeFile(t,Buffer.from(s.data)),m(`[SlidesService] Downloaded successfully to ${t}`),t}parseJsonObject(e,t,s){let o;try{o=JSON.parse(e)}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`Invalid JSON for ${t} parameter: ${l}. Expected a JSON string like '${s}'.`)}if(typeof o!="object"||o===null||Array.isArray(o)){let a=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid ${t} parameter: expected a JSON object, got ${a}.`)}return o}buildRange(e){if(!pu.includes(e.type))throw new Error(`Invalid range type "${e.type}". Expected one of: ${pu.join(", ")}.`);if(e.type==="FIXED_RANGE"){if(e.startIndex===void 0||e.endIndex===void 0)throw new Error("FIXED_RANGE requires both startIndex and endIndex.");return{type:e.type,startIndex:e.startIndex,endIndex:e.endIndex}}if(e.type==="FROM_START_INDEX"){if(e.startIndex===void 0)throw new Error("FROM_START_INDEX requires startIndex.");return{type:e.type,startIndex:e.startIndex}}return{type:e.type}}formatError(e,t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during ${e}: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}formatResult(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}};var fs=["getText","getMetadata","getImages","create","addSlide","deleteSlide","duplicateSlide","reorderSlides","getSpeakerNotes","updateSpeakerNotes","replaceAllText","insertText","deleteText","addShape","addImage","addTable","updateTextStyle","updateShapeProperties","getSlideThumbnail"],mu=z(us,fs,{bounds:Xa});import{google as _h}from"googleapis";var ps=class{constructor(e){this.authManager=e;this.listTaskLists=async(e={})=>{m("Listing task lists");try{let s=await(await this.getTasksClient()).tasklists.list({...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken}});return{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.listLists: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.listTasks=async e=>{m(`Listing tasks in list: ${e.taskListId}`);try{let s=await(await this.getTasksClient()).tasks.list({tasklist:e.taskListId,...e.showCompleted!==void 0&&{showCompleted:e.showCompleted},...e.showDeleted!==void 0&&{showDeleted:e.showDeleted},...e.showHidden!==void 0&&{showHidden:e.showHidden},...e.showAssigned!==void 0&&{showAssigned:e.showAssigned},...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken},...e.dueMin!==void 0&&{dueMin:e.dueMin},...e.dueMax!==void 0&&{dueMax:e.dueMax}});return{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.list: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.createTask=async e=>{m(`Creating task in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),s={title:e.title,...e.notes!==void 0&&{notes:e.notes},...e.due!==void 0&&{due:e.due}},o=await t.tasks.insert({tasklist:e.taskListId,requestBody:s});return m(`Successfully created task: ${o.data.id}`),{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.create: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.updateTask=async e=>{m(`Updating task ${e.taskId} in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),s={...e.title!==void 0&&{title:e.title},...e.notes!==void 0&&{notes:e.notes},...e.status!==void 0&&{status:e.status},...e.due!==void 0&&{due:e.due}},o=await t.tasks.patch({tasklist:e.taskListId,task:e.taskId,requestBody:s});return m(`Successfully updated task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.update: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.completeTask=async e=>this.updateTask({taskListId:e.taskListId,taskId:e.taskId,status:"completed"});this.deleteTask=async e=>{m(`Deleting task ${e.taskId} from list: ${e.taskListId}`);try{return await(await this.getTasksClient()).tasks.delete({tasklist:e.taskListId,task:e.taskId}),m(`Successfully deleted task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify({message:`Task ${e.taskId} deleted successfully from list ${e.taskListId}.`})}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.delete: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getTasksClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return _h.tasks({version:"v1",...t})}};var ms=["listTaskLists","listTasks","createTask","updateTask","completeTask","deleteTask"],hu=z(ps,ms,{pagination:{listTaskLists:"maxResults",listTasks:"maxResults"},bounds:rc});var hs=class{constructor(){this.getCurrentDate=async()=>(m("getCurrentDate called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(0,10),local:e.toLocaleDateString("en-CA",{timeZone:t}),timeZone:t}}));this.getCurrentTime=async()=>(m("getCurrentTime called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(11,19),local:e.toLocaleTimeString("en-GB",{hour12:!1,timeZone:t}),timeZone:t}}));this.getTimeZone=async()=>(m("getTimeZone called"),this.handleErrors(async()=>({timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone})));m("TimeService initialized.")}async handleErrors(e){try{let t=await e();return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error in TimeService: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}getTimeContext(){return{now:new Date,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}}};var Yo=["getCurrentDate","getCurrentTime","getTimeZone"],gu=z(hs,Yo,{noAuth:!0});var xe=[{name:"docs",description:`Google Docs operations.
77
+ `}),m(`[SlidesService] Finished getText for presentation: ${t}`),{content:[{type:"text",text:a.trim()}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getText: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.getMetadata=async({presentationId:e})=>{m(`[SlidesService] Starting getMetadata for presentation: ${e}`);try{let t=F(e)||e,o=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"presentationId,title,slides(objectId),pageSize,notesMaster,masters,layouts"}),a={presentationId:o.data.presentationId,title:o.data.title,slideCount:o.data.slides?.length||0,slides:o.data.slides?.map(({objectId:l})=>({objectId:l}))??[],pageSize:o.data.pageSize,hasMasters:!!o.data.masters?.length,hasLayouts:!!o.data.layouts?.length,hasNotesMaster:!!o.data.notesMaster};return m(`[SlidesService] Finished getMetadata for presentation: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getMetadata: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.getImages=async({presentationId:e,localPath:t})=>{m(`[SlidesService] Starting getImages for presentation: ${e} (localPath: ${t})`);try{let s=F(e)||e,a=await(await this.getSlidesClient()).presentations.get({presentationId:s,fields:"slides(objectId,pageElements(objectId,title,description,image(contentUrl,sourceUrl)))"}),l=await Promise.all((a.data.slides??[]).flatMap((d,p)=>(d.pageElements??[]).filter(u=>u.image).map(async u=>{let f={slideIndex:p+1,slideObjectId:d.objectId,elementObjectId:u.objectId,title:u.title,description:u.description,contentUrl:u.image?.contentUrl,sourceUrl:u.image?.sourceUrl};if(f.contentUrl){let y=`slide_${f.slideIndex}_${u.objectId}.png`,g=ir.join(t,y);try{await this.downloadToLocal(f.contentUrl,g),f.localPath=g}catch(_){m(`[SlidesService] Failed to download image ${u.objectId}: ${_}`),f.downloadError=String(_)}}return f})));return m(`[SlidesService] Finished getImages for presentation: ${s}`),{content:[{type:"text",text:JSON.stringify({images:l})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`[SlidesService] Error during slides.getImages: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.create=async({title:e})=>{m(`[SlidesService] Creating presentation: ${e}`);try{let s=await(await this.getSlidesClient()).presentations.create({requestBody:{title:e}}),o={presentationId:s.data.presentationId,title:s.data.title,url:`https://docs.google.com/presentation/d/${s.data.presentationId}/edit`};return m(`[SlidesService] Created presentation: ${o.presentationId}`),this.formatResult(o)}catch(t){return this.formatError("slides.create",t)}};this.addSlide=async({presentationId:e,insertionIndex:t,layoutId:s,predefinedLayout:o,objectId:a})=>{m(`[SlidesService] Adding slide to presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p={};if(t!==void 0&&(p.insertionIndex=t),a&&(p.objectId=a),s)p.slideLayoutReference={layoutId:s};else if(o){if(!pu.includes(o))throw new Error(`Invalid predefinedLayout "${o}". Expected one of: ${pu.join(", ")}.`);p.slideLayoutReference={predefinedLayout:o}}let f=(await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{createSlide:p}]}})).data.replies?.[0]?.createSlide?.objectId;if(!f)throw new Error("createSlide returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added slide: ${f}`),this.formatResult({presentationId:l,slideObjectId:f})}catch(l){return this.formatError("slides.addSlide",l)}};this.deleteSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Deleting slide ${t} from presentation: ${e}`);try{let s=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{deleteObject:{objectId:t}}]}}),m(`[SlidesService] Deleted slide: ${t}`),this.formatResult({presentationId:s,deletedSlideObjectId:t})}catch(s){return this.formatError("slides.deleteSlide",s)}};this.duplicateSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Duplicating slide ${t} in presentation: ${e}`);try{let s=F(e)||e,l=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{duplicateObject:{objectId:t}}]}})).data.replies?.[0]?.duplicateObject?.objectId;if(!l)throw new Error("duplicateObject returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Duplicated slide to: ${l}`),this.formatResult({presentationId:s,sourceSlideObjectId:t,newSlideObjectId:l})}catch(s){return this.formatError("slides.duplicateSlide",s)}};this.reorderSlides=async({presentationId:e,slideObjectIds:t,insertionIndex:s})=>{m(`[SlidesService] Reordering slides in presentation: ${e}`);try{let o=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:o,requestBody:{requests:[{updateSlidesPosition:{slideObjectIds:t,insertionIndex:s}}]}}),m(`[SlidesService] Reordered slides in presentation: ${o}`),this.formatResult({presentationId:o,slideObjectIds:t,insertionIndex:s})}catch(o){return this.formatError("slides.reorderSlides",o)}};this.getSpeakerNotes=async({presentationId:e})=>{m(`[SlidesService] Getting speaker notes for presentation: ${e}`);try{let t=F(e)||e,a=((await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides??[]).map((l,d)=>{let p=l.slideProperties?.notesPage,u=p?.notesProperties?.speakerNotesObjectId,f="";if(u&&p?.pageElements){let y=p.pageElements.find(g=>g.objectId===u);y?.shape?.text&&(f=this.extractTextFromTextContent(y.shape.text).trim())}return{slideIndex:d,slideObjectId:l.objectId,speakerNotesObjectId:u,notes:f}});return m(`[SlidesService] Retrieved speaker notes for presentation: ${t}`),this.formatResult({presentationId:t,slides:a})}catch(t){return this.formatError("slides.getSpeakerNotes",t)}};this.updateSpeakerNotes=async({presentationId:e,slideObjectId:t,notes:s})=>{m(`[SlidesService] Updating speaker notes for slide ${t} in presentation: ${e}`);try{let o=F(e)||e,a=await this.getSlidesClient(),d=(await a.presentations.get({presentationId:o,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides?.find(g=>g.objectId===t);if(!d)throw new Error(`Slide not found: ${t}`);let p=d.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;if(!p)throw new Error(`Speaker notes object not found for slide: ${t}`);let u=[];d.slideProperties?.notesPage?.pageElements?.find(g=>g.objectId===p)?.shape?.text?.textElements?.length&&u.push({deleteText:{objectId:p,textRange:{type:"ALL"}}}),s.length>0&&u.push({insertText:{objectId:p,insertionIndex:0,text:s}});let y=u.length===0;return y?m(`[SlidesService] updateSpeakerNotes is a no-op for slide ${t} (existing notes already match input).`):await a.presentations.batchUpdate({presentationId:o,requestBody:{requests:u}}),m(`[SlidesService] Updated speaker notes for slide: ${t}`),this.formatResult({presentationId:o,slideObjectId:t,speakerNotesObjectId:p,notes:s,noOp:y})}catch(o){return this.formatError("slides.updateSpeakerNotes",o)}};this.replaceAllText=async({presentationId:e,findText:t,replaceText:s,matchCase:o=!0})=>{m(`[SlidesService] Replacing all text in presentation: ${e}`);try{let a=F(e)||e,p=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{replaceAllText:{containsText:{text:t,matchCase:o},replaceText:s}}]}})).data.replies?.[0]?.replaceAllText;if(!p)throw new Error("replaceAllText returned no reply; batchUpdate reply was empty or malformed.");let u=p.occurrencesChanged??0;return m(`[SlidesService] Replaced ${u} occurrences in presentation: ${a}`),this.formatResult({presentationId:a,findText:t,replaceText:s,occurrencesChanged:u})}catch(a){return this.formatError("slides.replaceAllText",a)}};this.insertText=async({presentationId:e,objectId:t,text:s,insertionIndex:o=0})=>{m(`[SlidesService] Inserting text into object ${t} in presentation: ${e}`);try{let a=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{insertText:{objectId:t,insertionIndex:o,text:s}}]}}),m(`[SlidesService] Inserted text into object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,insertionIndex:o,textLength:s.length})}catch(a){return this.formatError("slides.insertText",a)}};this.deleteText=async({presentationId:e,objectId:t,range:s={type:"ALL"}})=>{m(`[SlidesService] Deleting text from object ${t} in presentation: ${e}`);try{let o=F(e)||e,a=await this.getSlidesClient(),l=this.buildRange(s);return await a.presentations.batchUpdate({presentationId:o,requestBody:{requests:[{deleteText:{objectId:t,textRange:l}}]}}),m(`[SlidesService] Deleted text from object ${t} in presentation: ${o}`),this.formatResult({presentationId:o,objectId:t,textRange:l})}catch(o){return this.formatError("slides.deleteText",o)}};this.addShape=async({presentationId:e,slideObjectId:t,shapeType:s,x:o,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding shape to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={shapeType:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:o,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createShape:y}]}})).data.replies?.[0]?.createShape?.objectId;if(!_)throw new Error("createShape returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added shape: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,shapeObjectId:_,shapeType:s})}catch(u){return this.formatError("slides.addShape",u)}};this.addImage=async({presentationId:e,slideObjectId:t,imageUrl:s,x:o,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding image to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={url:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:o,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createImage:y}]}})).data.replies?.[0]?.createImage?.objectId;if(!_)throw new Error("createImage returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added image: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,imageObjectId:_,imageUrl:s})}catch(u){return this.formatError("slides.addImage",u)}};this.addTable=async({presentationId:e,slideObjectId:t,rows:s,columns:o,x:a,y:l,width:d,height:p,objectId:u})=>{m(`[SlidesService] Adding table to slide ${t} in presentation: ${e}`);try{let f=F(e)||e,y=await this.getSlidesClient(),g={rows:s,columns:o,elementProperties:{pageObjectId:t,size:{width:{magnitude:d,unit:"PT"},height:{magnitude:p,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:a,translateY:l,unit:"PT"}}};u&&(g.objectId=u);let S=(await y.presentations.batchUpdate({presentationId:f,requestBody:{requests:[{createTable:g}]}})).data.replies?.[0]?.createTable?.objectId;if(!S)throw new Error("createTable returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added table: ${S}`),this.formatResult({presentationId:f,slideObjectId:t,tableObjectId:S,rows:s,columns:o})}catch(f){return this.formatError("slides.addTable",f)}};this.updateTextStyle=async({presentationId:e,objectId:t,style:s,range:o={type:"ALL"},fields:a})=>{m(`[SlidesService] Updating text style for object ${t} in presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p=this.parseJsonObject(s,"style",'{"bold": true}'),u=this.buildRange(o);return await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{updateTextStyle:{objectId:t,textRange:u,style:p,fields:a}}]}}),m(`[SlidesService] Updated text style for object ${t} in presentation: ${l}`),this.formatResult({presentationId:l,objectId:t,textRange:u,fields:a})}catch(l){return this.formatError("slides.updateTextStyle",l)}};this.updateShapeProperties=async({presentationId:e,objectId:t,shapeProperties:s,fields:o})=>{m(`[SlidesService] Updating shape properties for object ${t} in presentation: ${e}`);try{let a=F(e)||e,l=await this.getSlidesClient(),d=this.parseJsonObject(s,"shapeProperties",'{"shapeBackgroundFill": {...}}');return await l.presentations.batchUpdate({presentationId:a,requestBody:{requests:[{updateShapeProperties:{objectId:t,shapeProperties:d,fields:o}}]}}),m(`[SlidesService] Updated shape properties for object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,fields:o})}catch(a){return this.formatError("slides.updateShapeProperties",a)}};this.getSlideThumbnail=async({presentationId:e,slideObjectId:t,localPath:s})=>{m(`[SlidesService] Starting getSlideThumbnail for presentation: ${e}, slide: ${t} (localPath: ${s})`);try{let o=F(e)||e,d={...(await(await this.getSlidesClient()).presentations.pages.getThumbnail({presentationId:o,pageObjectId:t})).data};if(d.contentUrl)try{await this.downloadToLocal(d.contentUrl,s),d.localPath=s}catch(p){m(`[SlidesService] Failed to download thumbnail for slide ${t}: ${p}`),d.downloadError=String(p)}return m(`[SlidesService] Finished getSlideThumbnail for slide: ${t}`),{content:[{type:"text",text:JSON.stringify(d)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[SlidesService] Error during slides.getSlideThumbnail: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getSlidesClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return _h.slides({version:"v1",...t})}extractTextFromTextContent(e){let t="";return e.textElements&&e.textElements.forEach(s=>{s.textRun&&s.textRun.content?t+=s.textRun.content:s.paragraphMarker&&(t+=`
78
+ `)}),t}async downloadToLocal(e,t){if(m(`[SlidesService] Downloading from ${e} to ${t}`),!ir.isAbsolute(t))throw new Error("localPath must be an absolute path.");await fs.mkdir(ir.dirname(t),{recursive:!0});let s=await fu({url:e,responseType:"arraybuffer",...W});return await fs.writeFile(t,Buffer.from(s.data)),m(`[SlidesService] Downloaded successfully to ${t}`),t}parseJsonObject(e,t,s){let o;try{o=JSON.parse(e)}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`Invalid JSON for ${t} parameter: ${l}. Expected a JSON string like '${s}'.`)}if(typeof o!="object"||o===null||Array.isArray(o)){let a=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid ${t} parameter: expected a JSON object, got ${a}.`)}return o}buildRange(e){if(!mu.includes(e.type))throw new Error(`Invalid range type "${e.type}". Expected one of: ${mu.join(", ")}.`);if(e.type==="FIXED_RANGE"){if(e.startIndex===void 0||e.endIndex===void 0)throw new Error("FIXED_RANGE requires both startIndex and endIndex.");return{type:e.type,startIndex:e.startIndex,endIndex:e.endIndex}}if(e.type==="FROM_START_INDEX"){if(e.startIndex===void 0)throw new Error("FROM_START_INDEX requires startIndex.");return{type:e.type,startIndex:e.startIndex}}return{type:e.type}}formatError(e,t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during ${e}: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}formatResult(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}};var ps=["getText","getMetadata","getImages","create","addSlide","deleteSlide","duplicateSlide","reorderSlides","getSpeakerNotes","updateSpeakerNotes","replaceAllText","insertText","deleteText","addShape","addImage","addTable","updateTextStyle","updateShapeProperties","getSlideThumbnail"],hu=z(ds,ps,{bounds:Qa});import{google as Th}from"googleapis";var ms=class{constructor(e){this.authManager=e;this.listTaskLists=async(e={})=>{m("Listing task lists");try{let s=await(await this.getTasksClient()).tasklists.list({...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken}});return{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.listLists: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.listTasks=async e=>{m(`Listing tasks in list: ${e.taskListId}`);try{let s=await(await this.getTasksClient()).tasks.list({tasklist:e.taskListId,...e.showCompleted!==void 0&&{showCompleted:e.showCompleted},...e.showDeleted!==void 0&&{showDeleted:e.showDeleted},...e.showHidden!==void 0&&{showHidden:e.showHidden},...e.showAssigned!==void 0&&{showAssigned:e.showAssigned},...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken},...e.dueMin!==void 0&&{dueMin:e.dueMin},...e.dueMax!==void 0&&{dueMax:e.dueMax}});return{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.list: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.createTask=async e=>{m(`Creating task in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),s={title:e.title,...e.notes!==void 0&&{notes:e.notes},...e.due!==void 0&&{due:e.due}},o=await t.tasks.insert({tasklist:e.taskListId,requestBody:s});return m(`Successfully created task: ${o.data.id}`),{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.create: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.updateTask=async e=>{m(`Updating task ${e.taskId} in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),s={...e.title!==void 0&&{title:e.title},...e.notes!==void 0&&{notes:e.notes},...e.status!==void 0&&{status:e.status},...e.due!==void 0&&{due:e.due}},o=await t.tasks.patch({tasklist:e.taskListId,task:e.taskId,requestBody:s});return m(`Successfully updated task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.update: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.completeTask=async e=>this.updateTask({taskListId:e.taskListId,taskId:e.taskId,status:"completed"});this.deleteTask=async e=>{m(`Deleting task ${e.taskId} from list: ${e.taskListId}`);try{return await(await this.getTasksClient()).tasks.delete({tasklist:e.taskListId,task:e.taskId}),m(`Successfully deleted task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify({message:`Task ${e.taskId} deleted successfully from list ${e.taskListId}.`})}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.delete: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getTasksClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Th.tasks({version:"v1",...t})}};var hs=["listTaskLists","listTasks","createTask","updateTask","completeTask","deleteTask"],gu=z(ms,hs,{pagination:{listTaskLists:"maxResults",listTasks:"maxResults"},bounds:nc});var gs=class{constructor(){this.getCurrentDate=async()=>(m("getCurrentDate called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(0,10),local:e.toLocaleDateString("en-CA",{timeZone:t}),timeZone:t}}));this.getCurrentTime=async()=>(m("getCurrentTime called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(11,19),local:e.toLocaleTimeString("en-GB",{hour12:!1,timeZone:t}),timeZone:t}}));this.getTimeZone=async()=>(m("getTimeZone called"),this.handleErrors(async()=>({timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone})));m("TimeService initialized.")}async handleErrors(e){try{let t=await e();return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error in TimeService: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}getTimeContext(){return{now:new Date,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}}};var Zo=["getCurrentDate","getCurrentTime","getTimeZone"],yu=z(gs,Zo,{noAuth:!0});var ve=[{name:"docs",description:`Google Docs operations.
79
79
 
80
80
  Actions (required params -> optional):
81
81
  - getText (documentId -> tabId, limit, preview)
@@ -87,28 +87,28 @@ Actions (required params -> optional):
87
87
 
88
88
  getText defaults to 20,000 characters, accepts limit 1-100,000, and marks truncated output explicitly. preview defaults to 2,000 characters unless limit is provided. getSuggestions is bounded separately: 20,000 characters and 100 suggestions by default (max_chars 1-100,000, full:true for every entry). These bounds limit response size without changing document authorization.
89
89
 
90
- account = email of the Google account to use (default: primary).`,actions:bo,inputProps:{documentId:{type:"string",description:"Google Doc ID or URL"},title:{type:"string",description:"Document title (for create)"},content:{type:"string",description:"Initial document content (for create)"},text:{type:"string",description:"Text to insert (for writeText)"},position:{type:"string",description:'Insert position for writeText: "beginning", "end" (default), or a positive integer index'},tabId:{type:"string",description:"Tab ID to target (optional, for multi-tab documents)"},limit:{type:"number",description:"Maximum Docs text characters for getText (1-100000; default 20000)"},preview:{type:"boolean",description:"Use a 2000-character getText preview unless limit is provided"},max_chars:{type:"number",description:"Maximum characters returned by getSuggestions (1-100000; default 20000)"},full:{type:"boolean",description:"Return every getSuggestions entry, bypassing the default 20000-character and 100-item bounds"},replaceText:{type:"string",description:"Replacement text (for replaceText)"},formats:{type:"array",items:{type:"object",properties:{startIndex:{type:"number"},endIndex:{type:"number"},style:{type:"string"},url:{type:"string"}},required:["startIndex","endIndex","style"]},description:"Formatting operations to apply (for formatText)"}},run:wc},{name:"time",description:`Local date/time/timezone helpers (no Google account needed).
90
+ account = email of the Google account to use (default: primary).`,actions:So,inputProps:{documentId:{type:"string",description:"Google Doc ID or URL"},title:{type:"string",description:"Document title (for create)"},content:{type:"string",description:"Initial document content (for create)"},text:{type:"string",description:"Text to insert (for writeText)"},position:{type:"string",description:'Insert position for writeText: "beginning", "end" (default), or a positive integer index'},tabId:{type:"string",description:"Tab ID to target (optional, for multi-tab documents)"},limit:{type:"number",description:"Maximum Docs text characters for getText (1-100000; default 20000)"},preview:{type:"boolean",description:"Use a 2000-character getText preview unless limit is provided"},max_chars:{type:"number",description:"Maximum characters returned by getSuggestions (1-100000; default 20000)"},full:{type:"boolean",description:"Return every getSuggestions entry, bypassing the default 20000-character and 100-item bounds"},replaceText:{type:"string",description:"Replacement text (for replaceText)"},formats:{type:"array",items:{type:"object",properties:{startIndex:{type:"number"},endIndex:{type:"number"},style:{type:"string"},url:{type:"string"}},required:["startIndex","endIndex","style"]},description:"Formatting operations to apply (for formatText)"}},run:_c},{name:"time",description:`Local date/time/timezone helpers (no Google account needed).
91
91
 
92
92
  Actions:
93
93
  - getCurrentDate
94
94
  - getCurrentTime
95
- - getTimeZone`,actions:Yo,inputProps:{},run:gu},{name:"drive",description:`Drive operations. See the action enum for operations available in this transport.
95
+ - getTimeZone`,actions:Zo,inputProps:{},run:yu},{name:"drive",description:`Drive operations. See the action enum for operations available in this transport.
96
96
 
97
- search, getComments and findFolder are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). search and getComments page with pageSize and pageToken; findFolder caps at 50 name matches. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:wo,localOnlyActions:["downloadFile"],localOnlyInputProps:["localPath"],inputProps:{fileId:{type:"string"},folderId:{type:"string"},folderName:{type:"string"},query:{type:"string"},name:{type:"string"},newName:{type:"string"},parentId:{type:"string"},destinationFolderId:{type:"string"},pageSize:{type:"number",description:"Maximum search results per page (default 10)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},corpus:{type:"string",enum:["user","domain"],description:"Drive search corpus"},unreadOnly:{type:"boolean",description:"Restrict search to unread files where supported"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},localPath:{type:"string",description:"Local destination path for downloadFile. This action is available only over local stdio transport."}},run:_c},{name:"calendar",description:"Calendar operations. Actions: "+xn.join(", ")+`.
97
+ search, getComments and findFolder are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). search and getComments page with pageSize and pageToken; findFolder caps at 50 name matches. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:_o,localOnlyActions:["downloadFile"],localOnlyInputProps:["localPath"],inputProps:{fileId:{type:"string"},folderId:{type:"string"},folderName:{type:"string"},query:{type:"string"},name:{type:"string"},newName:{type:"string"},parentId:{type:"string"},destinationFolderId:{type:"string"},pageSize:{type:"number",description:"Maximum search results per page (default 10)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},corpus:{type:"string",enum:["user","domain"],description:"Drive search corpus"},unreadOnly:{type:"boolean",description:"Restrict search to unread files where supported"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},localPath:{type:"string",description:"Local destination path for downloadFile. This action is available only over local stdio transport."}},run:Tc},{name:"calendar",description:"Calendar operations. Actions: "+Cn.join(", ")+`.
98
98
 
99
- listEvents, getEvent, listCalendars and findFreeTime are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload); listEvents pages with maxResults and pageToken and always returns its nextPageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:xn,inputProps:{calendarId:{type:"string"},eventId:{type:"string"},summary:{type:"string"},description:{type:"string"},start:{type:"string"},end:{type:"string"},attendees:{type:"array"},maxResults:{type:"number",description:"Maximum events per page (for listEvents; default 20)"},pageToken:{type:"string",description:"Continuation token from a previous listEvents page"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"}},run:hc},{name:"chat",description:"Chat operations. Actions: "+An.join(", ")+`.
99
+ listEvents, getEvent, listCalendars and findFreeTime are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload); listEvents pages with maxResults and pageToken and always returns its nextPageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:Cn,inputProps:{calendarId:{type:"string"},eventId:{type:"string"},summary:{type:"string"},description:{type:"string"},start:{type:"string"},end:{type:"string"},attendees:{type:"array"},maxResults:{type:"number",description:"Maximum events per page (for listEvents; default 20)"},pageToken:{type:"string",description:"Continuation token from a previous listEvents page"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"}},run:gc},{name:"chat",description:"Chat operations. Actions: "+Pn.join(", ")+`.
100
100
 
101
- listSpaces, getMessages, listThreads and findSpaceByName are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). All three listings page with pageSize and pageToken and always return their nextPageToken; findSpaceByName caps at 50 matches. account = email of the Google account to use (default: primary).`,actions:An,inputProps:{spaceId:{type:"string"},displayName:{type:"string"},email:{type:"string"},text:{type:"string"},threadId:{type:"string"},pageSize:{type:"number",description:"Maximum spaces, messages, or threads per page"},pageToken:{type:"string",description:"Continuation token from a previous page"},unreadOnly:{type:"boolean",description:"Return only unread messages"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},orderBy:{type:"string",description:"Message ordering expression"},filter:{type:"string",description:"Chat message filter"}},run:yc},{name:"gmail",description:"Gmail operations. Actions: "+Mn.join(", ")+`.
101
+ listSpaces, getMessages, listThreads and findSpaceByName are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). All three listings page with pageSize and pageToken and always return their nextPageToken; findSpaceByName caps at 50 matches. account = email of the Google account to use (default: primary).`,actions:Pn,inputProps:{spaceId:{type:"string"},displayName:{type:"string"},email:{type:"string"},text:{type:"string"},threadId:{type:"string"},pageSize:{type:"number",description:"Maximum spaces, messages, or threads per page"},pageToken:{type:"string",description:"Continuation token from a previous page"},unreadOnly:{type:"boolean",description:"Return only unread messages"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},orderBy:{type:"string",description:"Message ordering expression"},filter:{type:"string",description:"Chat message filter"}},run:bc},{name:"gmail",description:"Gmail operations. Actions: "+Fn.join(", ")+`.
102
102
 
103
- get, modify, modifyThread, search and listLabels are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), so a long message body is cut with an explicit marker instead of flooding the response. search pages with maxResults and pageToken. account = email of the Google account to use (default: primary).`,actions:Mn,inputProps:{query:{type:"string"},messageId:{type:"string"},threadId:{type:"string"},to:{type:"string"},subject:{type:"string"},body:{type:"string"},draftId:{type:"string"},labelIds:{type:"array"},maxResults:{type:"number",description:"Maximum messages returned per page (bounded by Gmail)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},includeSpamTrash:{type:"boolean",description:"Include spam and trash in search results"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},format:{type:"string",enum:["minimal","full","raw","metadata"],description:"Message payload detail"}},run:xc},{name:"slides",description:"Slides operations. Actions: "+fs.join(", ")+`.
103
+ get, modify, modifyThread, search and listLabels are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), so a long message body is cut with an explicit marker instead of flooding the response. search pages with maxResults and pageToken. account = email of the Google account to use (default: primary).`,actions:Fn,inputProps:{query:{type:"string"},messageId:{type:"string"},threadId:{type:"string"},to:{type:"string"},subject:{type:"string"},body:{type:"string"},draftId:{type:"string"},labelIds:{type:"array"},maxResults:{type:"number",description:"Maximum messages returned per page (bounded by Gmail)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},includeSpamTrash:{type:"boolean",description:"Include spam and trash in search results"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},format:{type:"string",enum:["minimal","full","raw","metadata"],description:"Message payload detail"}},run:Cc},{name:"slides",description:"Slides operations. Actions: "+ps.join(", ")+`.
104
104
 
105
- getText, getMetadata, getImages and getSpeakerNotes are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and at most 100 slide or image entries. getSlideThumbnail returns one base64 image and is never cut. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:fs,inputProps:{presentationId:{type:"string"},title:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},slideId:{type:"string"},text:{type:"string"}},run:mu},{name:"sheets",description:"Sheets operations. Actions: "+qn.join(", ")+`.
105
+ getText, getMetadata, getImages and getSpeakerNotes are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and at most 100 slide or image entries. getSlideThumbnail returns one base64 image and is never cut. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:ps,inputProps:{presentationId:{type:"string"},title:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},slideId:{type:"string"},text:{type:"string"}},run:hu},{name:"sheets",description:"Sheets operations. Actions: "+jn.join(", ")+`.
106
106
 
107
- getText and getRange return at most 20,000 characters by default (max_chars 1-100,000) and mark truncated output explicitly with the true size and omitted count; pass full:true for the complete payload. account = email of the Google account to use (default: primary).`,actions:qn,inputProps:{spreadsheetId:{type:"string"},range:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by getText/getRange (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete getText/getRange payload, bypassing the default 20000-character bound"}},run:Pc},{name:"tasks",description:"Tasks operations. Actions: "+ms.join(", ")+`.
107
+ getText and getRange return at most 20,000 characters by default (max_chars 1-100,000) and mark truncated output explicitly with the true size and omitted count; pass full:true for the complete payload. account = email of the Google account to use (default: primary).`,actions:jn,inputProps:{spreadsheetId:{type:"string"},range:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by getText/getRange (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete getText/getRange payload, bypassing the default 20000-character bound"}},run:Ic},{name:"tasks",description:"Tasks operations. Actions: "+hs.join(", ")+`.
108
108
 
109
- listTasks and listTaskLists are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and page with maxResults and pageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:ms,inputProps:{taskListId:{type:"string"},taskId:{type:"string"},title:{type:"string"},notes:{type:"string"},due:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},maxResults:{type:"number",description:"Maximum task lists or tasks per page"},pageToken:{type:"string",description:"Continuation token from a previous page"}},run:hu},{name:"people",description:"People operations. Actions: "+Bn.join(", ")+`.
109
+ listTasks and listTaskLists are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and page with maxResults and pageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:hs,inputProps:{taskListId:{type:"string"},taskId:{type:"string"},title:{type:"string"},notes:{type:"string"},due:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},maxResults:{type:"number",description:"Maximum task lists or tasks per page"},pageToken:{type:"string",description:"Continuation token from a previous page"}},run:gu},{name:"people",description:"People operations. Actions: "+Un.join(", ")+`.
110
110
 
111
- All three actions are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), and getUserRelations keeps at most 50 relations. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:Bn,inputProps:{max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},resourceName:{type:"string"}},run:Cc},{name:"forms",description:`Google Forms operations.
111
+ All three actions are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), and getUserRelations keeps at most 50 relations. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:Un,inputProps:{max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},resourceName:{type:"string"}},run:Ac},{name:"forms",description:`Google Forms operations.
112
112
 
113
113
  Actions (required params -> optional):
114
114
  - create (title -> documentTitle)
@@ -121,7 +121,7 @@ Questions are added with batchUpdate, not create. Responses are read-only (the F
121
121
 
122
122
  get, getResponse and listResponses are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload); listResponses pages with pageSize and pageToken.
123
123
 
124
- account = email of the Google account to use (default: primary).`,actions:_o,inputProps:{formId:{type:"string",description:"Form ID, or the editor URL https://docs.google.com/forms/d/<formId>/edit"},title:{type:"string",description:"Form title shown to respondents (for create)"},documentTitle:{type:"string",description:"Drive file name, when it should differ from the title (for create)"},requests:{type:"array",items:{type:"object"},description:'Forms API batchUpdate requests, e.g. [{"createItem": {...}}] (for batchUpdate)'},responseId:{type:"string",description:"Response ID (for getResponse)"},pageSize:{type:"number",description:"Maximum responses to return (for listResponses)"},pageToken:{type:"string",description:"Page token from a previous listResponses call"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},filter:{type:"string",description:"Response filter, e.g. timestamp > 2026-01-01T00:00:00Z (for listResponses)"}},run:Tc}];var yu={config:!0,help:!0,time:!0},Ph=Ah(import.meta.url),Zo=Eh(Ph),$r=Zo.endsWith("bin")?Qo(Zo,"..","build","src","docs"):Qo(Zo,"..","docs"),Ot=[...xe.map(n=>n.name),"config","overview"],Ih=Object.fromEntries(Ot.map(n=>[n,!0])),Su=Ot.join(", "),Oh=new Map(xe.map(n=>[n.name,n])),bu=[...xe.map(n=>n.name),"config","help"];function Xo(n){return{content:[{type:"text",text:n}],isError:!0}}async function kh(n){if(Ih[n]!==!0)throw new U(`Invalid topic: ${n}`,"VALIDATION_ERROR",`Valid topics: ${Su}`);let e=`${Rh(n)}.md`,t=Qo($r,e),s=xh($r,t);if(s===".."||s.startsWith(`..${Ch}`)||vh(s))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid topic");try{return{content:[{type:"text",text:await Th(t,"utf-8")}]}}catch{throw new U(`Documentation not found for: ${n}`,"DOC_NOT_FOUND","Check topic")}}async function gs(n,e,{allowLocalFilesystem:t=!0}={}){if(!e)return Xo("Error: No arguments provided");if(yu[n]!==!0&&Ct()!=="configured"&&await ot(),yu[n]!==!0&&Ct()!=="configured")return Xo('Google account not configured. Run `workspace auth` on the host to complete the Google consent, or call config(action="setup_start") for instructions.');try{let s=Oh.get(n);if(s){let o=e.action;if(!t&&typeof o=="string"&&s.localOnlyActions?.includes(o)===!0)throw n==="drive"&&o==="downloadFile"?new U("downloadFile is only available in local stdio mode.","VALIDATION_ERROR","Use a local stdio server to download a Drive file to the local filesystem."):new U(`Action not available in this transport: ${o}`,"VALIDATION_ERROR","Use an action listed in the tool schema.");return await s.run(e)}switch(n){case"config":return await qa(e);case"help":{let o=e.topic;if(typeof o!="string")throw new U("help requires a topic","VALIDATION_ERROR",`Valid topics: ${Su}`);return await kh(o)}default:{let o=Fa(n,bu),a=o?` Did you mean '${o}'?`:"";throw new U(`Unknown tool: ${n}.${a}`,"UNKNOWN_TOOL",`Available tools: ${bu.join(", ")}`)}}}catch(s){let o=s instanceof U?s:new U(s.message,"TOOL_ERROR","Check the error details and try again");return Xo(Ba(o))}}import{readFile as $h}from"node:fs/promises";import{basename as Dh,isAbsolute as Lh,join as Nh,relative as Mh,sep as Fh}from"node:path";import{CallToolRequestSchema as Bh,ListResourcesRequestSchema as Uh,ListToolsRequestSchema as qh,ReadResourceRequestSchema as jh}from"@modelcontextprotocol/sdk/types.js";var wu=n=>n.charAt(0).toUpperCase()+n.slice(1),Ko=[...xe.map(n=>({uri:`workspace://docs/${n.name}`,name:`${wu(n.name)} Tool Docs`,file:`${n.name}.md`})),{uri:"workspace://docs/config",name:"Config Tool Docs",file:"config.md"},{uri:"workspace://docs/overview",name:"Overview Docs",file:"overview.md"}],Wh=Ko.map(n=>({uri:n.uri,name:n.name,mimeType:"text/markdown"})),zh=new Map(Ko.map(n=>[n.uri,n])),Hh=Ko.map(n=>n.uri).join(", ");function Gh(n,e){return e||!n.localOnlyActions?n.actions:n.actions.filter(t=>!n.localOnlyActions.includes(t))}function Jh(n,e){return e||!n.localOnlyInputProps?n.inputProps:Object.fromEntries(Object.entries(n.inputProps).filter(([t])=>!n.localOnlyInputProps.includes(t)))}function Vh(n,e){let t=Gh(n,e);return{name:n.name,description:n.description,annotations:{title:wu(n.name),readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...t],description:"Action to perform"},account:{type:"string",description:'Google account email to act as. Defaults to the primary account (config action="account_list").'},...Jh(n,e)},required:["action"]}}}var ei=[{name:"config",description:`Manage server configuration, credential state, and the Google accounts this server can act as.
124
+ account = email of the Google account to use (default: primary).`,actions:To,inputProps:{formId:{type:"string",description:"Form ID, or the editor URL https://docs.google.com/forms/d/<formId>/edit"},title:{type:"string",description:"Form title shown to respondents (for create)"},documentTitle:{type:"string",description:"Drive file name, when it should differ from the title (for create)"},requests:{type:"array",items:{type:"object"},description:'Forms API batchUpdate requests, e.g. [{"createItem": {...}}] (for batchUpdate)'},responseId:{type:"string",description:"Response ID (for getResponse)"},pageSize:{type:"number",description:"Maximum responses to return (for listResponses)"},pageToken:{type:"string",description:"Page token from a previous listResponses call"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},filter:{type:"string",description:"Response filter, e.g. timestamp > 2026-01-01T00:00:00Z (for listResponses)"}},run:Rc}];var bu={config:!0,help:!0,time:!0},Ih=Ph(import.meta.url),Xo=xh(Ih),Lr=Xo.endsWith("bin")?Ko(Xo,"..","build","src","docs"):Ko(Xo,"..","docs"),Ot=[...ve.map(n=>n.name),"config","overview"],Oh=Object.fromEntries(Ot.map(n=>[n,!0])),wu=Ot.join(", "),kh=new Map(ve.map(n=>[n.name,n])),Su=[...ve.map(n=>n.name),"config","help"];function Qo(n){return{content:[{type:"text",text:n}],isError:!0}}async function $h(n){if(Oh[n]!==!0)throw new U(`Invalid topic: ${n}`,"VALIDATION_ERROR",`Valid topics: ${wu}`);let e=`${Eh(n)}.md`,t=Ko(Lr,e),s=Ch(Lr,t);if(s===".."||s.startsWith(`..${Ah}`)||vh(s))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid topic");try{return{content:[{type:"text",text:await Rh(t,"utf-8")}]}}catch{throw new U(`Documentation not found for: ${n}`,"DOC_NOT_FOUND","Check topic")}}async function ys(n,e,{allowLocalFilesystem:t=!0}={}){if(!e)return Qo("Error: No arguments provided");if(bu[n]!==!0&&Ct()!=="configured"&&await ot(),bu[n]!==!0&&Ct()!=="configured")return Qo(`Google account not configured. Run \`${Gt()}\` on the host to complete the Google consent, or call config(action="setup_start") for instructions.`);try{let s=kh.get(n);if(s){let o=e.action;if(!t&&typeof o=="string"&&s.localOnlyActions?.includes(o)===!0)throw n==="drive"&&o==="downloadFile"?new U("downloadFile is only available in local stdio mode.","VALIDATION_ERROR","Use a local stdio server to download a Drive file to the local filesystem."):new U(`Action not available in this transport: ${o}`,"VALIDATION_ERROR","Use an action listed in the tool schema.");return await s.run(e)}switch(n){case"config":return await ja(e);case"help":{let o=e.topic;if(typeof o!="string")throw new U("help requires a topic","VALIDATION_ERROR",`Valid topics: ${wu}`);return await $h(o)}default:{let o=Ba(n,Su),a=o?` Did you mean '${o}'?`:"";throw new U(`Unknown tool: ${n}.${a}`,"UNKNOWN_TOOL",`Available tools: ${Su.join(", ")}`)}}}catch(s){let o=s instanceof U?s:new U(s.message,"TOOL_ERROR","Check the error details and try again");return Qo(Ua(o))}}import{readFile as Dh}from"node:fs/promises";import{basename as Lh,isAbsolute as Nh,join as Mh,relative as Fh,sep as Bh}from"node:path";import{CallToolRequestSchema as Uh,ListResourcesRequestSchema as qh,ListToolsRequestSchema as jh,ReadResourceRequestSchema as Wh}from"@modelcontextprotocol/sdk/types.js";var _u=n=>n.charAt(0).toUpperCase()+n.slice(1),ei=[...ve.map(n=>({uri:`workspace://docs/${n.name}`,name:`${_u(n.name)} Tool Docs`,file:`${n.name}.md`})),{uri:"workspace://docs/config",name:"Config Tool Docs",file:"config.md"},{uri:"workspace://docs/overview",name:"Overview Docs",file:"overview.md"}],zh=ei.map(n=>({uri:n.uri,name:n.name,mimeType:"text/markdown"})),Hh=new Map(ei.map(n=>[n.uri,n])),Gh=ei.map(n=>n.uri).join(", ");function Jh(n,e){return e||!n.localOnlyActions?n.actions:n.actions.filter(t=>!n.localOnlyActions.includes(t))}function Vh(n,e){return e||!n.localOnlyInputProps?n.inputProps:Object.fromEntries(Object.entries(n.inputProps).filter(([t])=>!n.localOnlyInputProps.includes(t)))}function Yh(n,e){let t=Jh(n,e);return{name:n.name,description:n.description,annotations:{title:_u(n.name),readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...t],description:"Action to perform"},account:{type:"string",description:'Google account email to act as. Defaults to the primary account (config action="account_list").'},...Vh(n,e)},required:["action"]}}}var ti=[{name:"config",description:`Manage server configuration, credential state, and the Google accounts this server can act as.
125
125
 
126
126
  Actions:
127
127
  - status: current credential state plus the configured accounts and which is primary
@@ -133,12 +133,12 @@ Actions:
133
133
  - account_add: start the browser consent flow for one more account (stdio: returns a URL to open; HTTP: returns the \`workspace auth --user <namespace>\` command to run on the host)
134
134
  - account_list: list configured accounts and the primary one
135
135
  - account_remove (account): forget one account; a remaining account is promoted if it was primary
136
- - account_set_default (account): make one account the primary (used when a call omits account)`,annotations:{title:"Config",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...uo],description:"Action to perform"},key:{type:"string",description:"Setting key (for set action)"},value:{type:"string",description:"Setting value (for set action)"},account:{type:"string",description:"Account email (for account_remove / account_set_default / account_add)"}},required:["action"]}},{name:"help",description:"Get full documentation for a topic. Use when compressed tool descriptions are insufficient.",annotations:{title:"Help",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:{type:"object",properties:{topic:{type:"string",enum:[...Ot],description:"Topic to get documentation for"}},required:["topic"]}}];function Yh(n){return[...xe.map(e=>Vh(e,n)),...ei]}function ys(n,{allowLocalFilesystem:e=!0}={}){let t=Yh(e);n.setRequestHandler(qh,async()=>({tools:t})),n.setRequestHandler(Uh,async()=>({resources:Wh})),n.setRequestHandler(jh,async s=>{let{uri:o}=s.params,a=zh.get(o);if(!a)throw new U(`Resource not found: ${o}`,"RESOURCE_NOT_FOUND",`Available: ${Hh}`);let l=Nh($r,Dh(a.file)),d=Mh($r,l);if(d===".."||d.startsWith(`..${Fh}`)||Lh(d))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid resource URI");try{let p=await $h(l,"utf-8");return{contents:[{uri:o,mimeType:"text/markdown",text:p}]}}catch{throw new U(`Documentation not found for: ${a.name}`,"DOC_NOT_FOUND","Check resource URI")}}),n.setRequestHandler(Bh,async s=>{let{name:o,arguments:a}=s.params;return gs(o,a,{allowLocalFilesystem:e})})}import{readFileSync as Zh}from"node:fs";import{dirname as Xh,join as Qh}from"node:path";import{fileURLToPath as Kh}from"node:url";function yt(){try{let n=Xh(Kh(import.meta.url)),e=Qh(n,"..","package.json");return JSON.parse(Zh(e,"utf-8")).version??"0.0.0"}catch{return"0.0.0"}}var eg={out:n=>console.log(n),err:n=>console.error(n)},_u=2,tg="--json",rg={"-h":!0,"--help":!0},ng={type:"string",description:"Google account email to act as. Defaults to the primary account."};function ti(n){if(typeof n!="object"||n===null)return{type:"string"};let e="type"in n&&typeof n.type=="string"?n.type:"string",t="description"in n&&typeof n.description=="string"?n.description:void 0,s="enum"in n&&Array.isArray(n.enum)?n.enum.filter(o=>typeof o=="string"):void 0;return{type:e,description:t,values:s}}function sg(n){let e=xe.find(t=>t.name===n);if(e)return{tool:e.name,subcommand:e.name,description:e.description,actions:e.actions,props:{account:ng,...e.inputProps}}}var ir={tool:"help",subcommand:"help",description:"Full documentation for one tool (the MCP `help` tool).",actions:[],props:{topic:{type:"string",description:`Topic to read: ${Ot.join(", ")}`}}},ri={"config-tool":"config"};function Eu(n,e){let t=ei.find(a=>a.name===e);if(!t)throw new Error(`subcommand '${n}' aliases the unknown MCP tool '${e}'`);let{action:s,...o}=t.inputSchema.properties;return{tool:e,subcommand:n,description:t.description,actions:ti(s).values??[],props:o}}var Tu=[{name:"auth",description:"add a Google account on the host (`--user <namespace>` for HTTP mode)"},{name:"config",description:"stored credential state: `config status` | `config delete --yes` (MCP `config` tool: `config-tool`)"},{name:"status",description:"alias of `config status`"},{name:"logout",description:"alias of `config delete`"},{name:"doctor",description:"environment and credential-backend checks"},{name:"token",description:"bearer-token helpers for HTTP mode"},{name:"relay",description:"removed; prints a pointer to `auth`"}],vu=[...xe.map(n=>n.name),ir.subcommand,...Object.keys(ri)];function og(n){if(n===ir.subcommand)return ir;let e=ri[n];return e!==void 0?Eu(n,e):sg(n)}var Se=class extends Error{};function ig(n){let e=n.split(`
137
- `)[0]??n;return(e.split(". ")[0]??e).replace(/\.$/,"")}function ag(n,e=6){return n.length<=e?n.join(", "):`${n.slice(0,e).join(", ")}, \u2026 (+${n.length-e})`}function cg(n){if(n.subcommand===ir.subcommand)return["usage: workspace help [topic] [--json]","","Print full documentation for one topic, or the whole subcommand surface","when no topic is given.","","topics:",` ${Ot.join(", ")}`,"","options:"," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
138
- `);let e=Object.entries(n.props).map(([t,s])=>{let o=ti(s),a=o.description?` ${o.description}`:"";return` --${t} <${o.type}>${a}`});return[`usage: workspace ${n.subcommand} <action> [--param <value>]... [--json]`,"",n.description,"","actions:",` ${n.actions.join(", ")}`,"","options:",...e," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
139
- `)}function ni(){let n=[...xe.map(a=>({label:a.name,description:a.description,actions:a.actions})),...Object.entries(ri).map(([a,l])=>{let d=Eu(a,l);return{label:a,description:d.description,actions:d.actions}}),{label:ir.subcommand,description:"Full documentation for any tool",actions:[]}],e=[...n.map(a=>a.label),...Tu.map(a=>a.name)],t=Math.max(...e.map(a=>a.length))+2,s=n.map(a=>{let l=a.actions.length>0?` \u2014 ${ag(a.actions)}`:"";return` ${a.label.padEnd(t)}${ig(a.description)}${l}`}),o=Tu.map(a=>` ${a.name.padEnd(t)}${a.description}`);return[`workspace ${yt()} \u2014 Google Workspace MCP server`,"","usage:"," workspace start the MCP server (stdio)"," workspace --http start the MCP server (HTTP)"," workspace <tool> <action> [--param] call one tool from the terminal"," workspace help [topic] tool documentation","","tools (each is an MCP tool; the CLI runs the same handler):",...s,"","operator commands (not tools):",...o,"","examples:"," workspace time getCurrentTime --json",' workspace gmail search --query "is:unread" --maxResults 5'," workspace docs getText --documentId <document-id> --limit 2000"," workspace config-tool status --json"," workspace help tasks"].join(`
140
- `)}function lg(n,e){try{return JSON.parse(e)}catch{throw new Se(`--${n} expects JSON, got '${e}'`)}}function ug(n,e,t){switch(t.type){case"number":{let s=Number(e);if(!Number.isFinite(s))throw new Se(`--${n} expects a number, got '${e}'`);return s}case"boolean":{if(e==="true"||e==="")return!0;if(e==="false")return!1;throw new Se(`--${n} expects 'true' or 'false', got '${e}'`)}case"array":return e.startsWith("[")?lg(n,e):e.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return e}}function dg(n,e){let t=[],s={},o=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(l===tg){o=!0;continue}if(!l.startsWith("--")){t.push(l);continue}let[d,p]=l.slice(2).split(/=(.*)/s),u=d.startsWith("no-"),f=u?d.slice(3):d,y=n.props[f];if(y===void 0){let R=Object.keys(n.props).map(v=>`--${v}`).join(", ");throw new Se(`unknown option --${f} (valid: ${R})`)}let g=ti(y);if(u){if(g.type!=="boolean")throw new Se(`--no-${f} only applies to boolean options`);s[f]=!1;continue}let _=e[a+1],S=p!==void 0,E=!S&&_!==void 0&&!_.startsWith("--");if(!S&&!E){if(g.type==="boolean"){s[f]=!0;continue}throw new Se(`--${f} expects a value`)}E&&(a+=1),s[f]=ug(f,S?p:_,g)}return{positionals:t,params:s,json:o}}function Ru(n){return n.content.map(e=>e.type==="text"?e.text:"").filter(e=>e.length>0).join(`
141
- `)}function fg(n){try{return JSON.parse(n)}catch{return n}}async function pg(n,e,t=eg){let s=og(n);if(!s)return t.err(`workspace: unknown tool '${n}' (expected one of: ${vu.join(", ")})`),_u;let o=s.tool===ir.tool;if(e.some(u=>rg[u]===!0))return t.out(cg(s)),0;if(o&&!e.some(u=>!u.startsWith("-")))return t.out(ni()),0;let a,l;try{if(a=dg(s,e),o){if(a.positionals.length>1)throw new Se(`help takes one topic, got ${a.positionals.length}`);l="help",a.positionals[0]!==void 0&&(a.params.topic=a.positionals[0])}else{let[u,...f]=a.positionals;if(u===void 0)throw new Se(`missing action (one of: ${s.actions.join(", ")})`);if(f.length>0)throw new Se(`unexpected argument '${f[0]}' (pass options as --name value)`);l=u,a.params.action=u}}catch(u){if(!(u instanceof Se))throw u;return t.err(`workspace ${n}: ${u.message}`),t.err(`run \`workspace ${n} --help\` for usage`),_u}let d=await gs(s.tool,a.params);if(d.isError===!0){let u=Ru(d);return t.err(a.json?JSON.stringify({tool:s.tool,action:l,error:u}):u),1}let p=Ru(d);return a.json?(t.out(JSON.stringify({tool:s.tool,action:l,result:fg(p)},null,2)),0):(t.out(p),0)}function xu(){return Object.fromEntries(vu.map(n=>[n,e=>pg(n,e)]))}import{homedir as wg}from"node:os";import{isAbsolute as _g,join as KT,resolve as oi,sep as Tg}from"node:path";import{setHomeDirForTesting as Rg}from"@n24q02m/hull/storage";import{existsSync as Ou,readdirSync as ku}from"node:fs";import{join as si}from"node:path";import{isDeepStrictEqual as mg}from"node:util";import{credPath as hg,dataDirCandidates as $u,PerPluginStore as Cu}from"@n24q02m/hull/storage";var kt=class extends Error{constructor(t,s){super(s);this.path=t;this.name="StoreMigrationError"}},gg=/^[A-Za-z0-9._-]+$/;function bs(n){return n?.code??"unknown error"}function yg(n){try{return ku(n),!0}catch(e){let t=bs(e);if(t==="ENOENT")return!1;throw new kt(n,`Cannot read the previous credential directory ${n} (${t}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}}function bg(n){let e=si(n,"subs"),t;try{t=ku(e,{withFileTypes:!0})}catch(s){let o=bs(s);if(o==="ENOENT")return[];throw new kt(e,`Cannot read the previous credential directory ${e} (${o}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}return t.filter(s=>s.isDirectory()&&s.name!=="."&&s.name!==".."&&gg.test(s.name)).map(s=>s.name)}function Au(n){for(let{dir:e}of $u(dn)){let t=n===null?si(e,"config.json"):si(e,"subs",n,"config.json");if(Ou(t))return e}return null}async function Pu(n,e,t){let s=hg(We,n);if(Ou(s)){t.kept.push(s);return}if(n!==null&&!process.env.CREDENTIAL_SECRET){t.deferred.push(n);return}let o;try{o=await new Cu(dn,n).load()}catch(d){throw new kt(e,`Cannot read the saved credential in ${e} (${bs(d)}). Nothing was migrated and the previous store was left untouched.`)}if(o===null)return;let a=new Cu(We,n);try{await a.save(o)}catch(d){throw new kt(s,`Cannot write the migrated credential to ${s} (${bs(d)}). The previous store in ${e} was left untouched.`)}let l=null;try{l=await a.load()}catch{l=null}if(!mg(l,o))throw new kt(s,`Wrote ${s} but reading it back did not return the migrated credential. The previous store in ${e} was left untouched.`);t.migrated.push({source:e,sub:n})}async function Sg(){let n={migrated:[],kept:[],deferred:[]},e=$u(dn).map(o=>o.dir).filter(o=>yg(o));if(e.length===0)return n;let t=new Set;for(let o of e)for(let a of bg(o))t.add(a);let s=Au(null);s!==null&&await Pu(null,s,n);for(let o of[...t].sort()){let a=Au(o);a!==null&&await Pu(o,a,n)}return n}var Iu=null;function Du(){return Iu??=Sg(),Iu}var Ss="WORKSPACE_DATA_DIR",nR=`.${We}`,ws=class extends Error{constructor(e){super(e),this.name="DataDirEscapeError"}};function Eg(n=process.env,e=wg()){let t=oi(e),s=n[Ss]?.trim();if(!s)return t;if(s.includes("\0"))throw new ws(`${Ss} must not contain a NUL byte`);if(_g(s))return oi(s);let o=oi(t,s);if(o!==t&&!o.startsWith(t+Tg))throw new ws(`${Ss}="${s}" escapes the base directory ${t}; use an absolute path to choose another directory`);return o}function vg(n=process.env){if(!n[Ss]?.trim())return null;let e=Eg(n);return Rg(e),e}async function ii(n=process.env){return vg(n),Du()}import{Server as xg}from"@modelcontextprotocol/sdk/server/index.js";import{runHttpServer as Cg}from"@n24q02m/hull/transport";var Ag="WORKSPACE_USERS_FILE";async function Lu(){if(!process.env.CREDENTIAL_SECRET)throw new Error("CREDENTIAL_SECRET is required for http mode: per-user credential stores derive their encryption key from it.");let n=process.env.PORT?Number.parseInt(process.env.PORT,10):0,e=process.env.HOST,t=await Cg(()=>{let s=new xg({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});return ys(s,{allowLocalFilesystem:!1}),s},{serverName:ce,port:n,host:e,auth:{mode:"multi",usersFile:process.env[Ag]||void 0}});console.error(`[${ce}] http mode on http://${t.host}:${t.port}/mcp`),await new Promise(s=>{let o=async()=>{await t.close(),s()};process.once("SIGINT",o),process.once("SIGTERM",o)})}function $g(n){let e=process.argv[1];if(!e)return!1;try{let t=Nu(Pg(n)),s=Nu(e);if(process.platform==="win32"){let o=a=>a.replace(/\\/g,"/").toLowerCase();return o(t)===o(s)}return t===s}catch{return!1}}function Dg(n=process.env,e=process.argv){return e.includes("--http")||n.MCP_TRANSPORT==="http"||n.TRANSPORT_MODE==="http"?"http":"stdio"}async function Lg(n){if(await ii(),process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED){console.error(`[${ce}] Startup aborted: server already running in this process tree.`);return}if(process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED="true",n==="http"){await Lu();return}await ot(),Ct()!=="configured"&&(await $a(),await ot());let e=new Ig({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});ys(e);let t=new Og;await e.connect(t),console.error(`[${ce}] stdio mode ready (v${yt()})`)}var Ng=Dg();async function Mg(n=Ng){try{await Lg(n)}catch(e){console.error("Failed to start server:",e instanceof Error?e.message:String(e)),process.exit(1)}}async function Fg(n){if(await ii(),n[0]==="-h"||n[0]==="--help"){console.log(ni()),process.exitCode=0;return}let e=kg(ce,{serve:()=>Mg(),extra:{auth:La,relay:async()=>(console.error("relay was removed; run `workspace auth` (see README)"),2),...xu()},version:yt(),pluginName:We});process.exitCode=await e(n)}$g(import.meta.url)&&process.env.NODE_ENV!=="test"&&Fg(process.argv.slice(2));export{Mg as bootstrap,Dg as getTransportMode,$g as isMain,Ng as mode,Fg as runCli,Lg as startServer};
136
+ - account_set_default (account): make one account the primary (used when a call omits account)`,annotations:{title:"Config",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...fo],description:"Action to perform"},key:{type:"string",description:"Setting key (for set action)"},value:{type:"string",description:"Setting value (for set action)"},account:{type:"string",description:"Account email (for account_remove / account_set_default / account_add)"}},required:["action"]}},{name:"help",description:"Get full documentation for a topic. Use when compressed tool descriptions are insufficient.",annotations:{title:"Help",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:{type:"object",properties:{topic:{type:"string",enum:[...Ot],description:"Topic to get documentation for"}},required:["topic"]}}];function Zh(n){return[...ve.map(e=>Yh(e,n)),...ti]}function bs(n,{allowLocalFilesystem:e=!0}={}){let t=Zh(e);n.setRequestHandler(jh,async()=>({tools:t})),n.setRequestHandler(qh,async()=>({resources:zh})),n.setRequestHandler(Wh,async s=>{let{uri:o}=s.params,a=Hh.get(o);if(!a)throw new U(`Resource not found: ${o}`,"RESOURCE_NOT_FOUND",`Available: ${Gh}`);let l=Mh(Lr,Lh(a.file)),d=Fh(Lr,l);if(d===".."||d.startsWith(`..${Bh}`)||Nh(d))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid resource URI");try{let p=await Dh(l,"utf-8");return{contents:[{uri:o,mimeType:"text/markdown",text:p}]}}catch{throw new U(`Documentation not found for: ${a.name}`,"DOC_NOT_FOUND","Check resource URI")}}),n.setRequestHandler(Uh,async s=>{let{name:o,arguments:a}=s.params;return ys(o,a,{allowLocalFilesystem:e})})}import{readFileSync as Xh}from"node:fs";import{dirname as Qh,join as Kh}from"node:path";import{fileURLToPath as eg}from"node:url";function yt(){try{let n=Qh(eg(import.meta.url)),e=Kh(n,"..","package.json");return JSON.parse(Xh(e,"utf-8")).version??"0.0.0"}catch{return"0.0.0"}}var tg={out:n=>console.log(n),err:n=>console.error(n)},Tu=2,rg="--json",ng={"-h":!0,"--help":!0},sg={type:"string",description:"Google account email to act as. Defaults to the primary account."};function ri(n){if(typeof n!="object"||n===null)return{type:"string"};let e="type"in n&&typeof n.type=="string"?n.type:"string",t="description"in n&&typeof n.description=="string"?n.description:void 0,s="enum"in n&&Array.isArray(n.enum)?n.enum.filter(o=>typeof o=="string"):void 0;return{type:e,description:t,values:s}}function og(n){let e=ve.find(t=>t.name===n);if(e)return{tool:e.name,subcommand:e.name,description:e.description,actions:e.actions,props:{account:sg,...e.inputProps}}}var ar={tool:"help",subcommand:"help",description:"Full documentation for one tool (the MCP `help` tool).",actions:[],props:{topic:{type:"string",description:`Topic to read: ${Ot.join(", ")}`}}},ni={"config-tool":"config"};function xu(n,e){let t=ti.find(a=>a.name===e);if(!t)throw new Error(`subcommand '${n}' aliases the unknown MCP tool '${e}'`);let{action:s,...o}=t.inputSchema.properties;return{tool:e,subcommand:n,description:t.description,actions:ri(s).values??[],props:o}}var Ru=[{name:"auth",description:"add a Google account on the host (`--user <namespace>` for HTTP mode)"},{name:"config",description:"stored credential state: `config status` | `config delete --yes` (MCP `config` tool: `config-tool`)"},{name:"status",description:"alias of `config status`"},{name:"logout",description:"alias of `config delete`"},{name:"doctor",description:"environment and credential-backend checks"},{name:"token",description:"bearer-token helpers for HTTP mode"},{name:"relay",description:"removed; prints a pointer to `auth`"}],vu=[...ve.map(n=>n.name),ar.subcommand,...Object.keys(ni)];function ig(n){if(n===ar.subcommand)return ar;let e=ni[n];return e!==void 0?xu(n,e):og(n)}var Se=class extends Error{};function ag(n){let e=n.split(`
137
+ `)[0]??n;return(e.split(". ")[0]??e).replace(/\.$/,"")}function cg(n,e=6){return n.length<=e?n.join(", "):`${n.slice(0,e).join(", ")}, \u2026 (+${n.length-e})`}function lg(n){if(n.subcommand===ar.subcommand)return["usage: workspace help [topic] [--json]","","Print full documentation for one topic, or the whole subcommand surface","when no topic is given.","","topics:",` ${Ot.join(", ")}`,"","options:"," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
138
+ `);let e=Object.entries(n.props).map(([t,s])=>{let o=ri(s),a=o.description?` ${o.description}`:"";return` --${t} <${o.type}>${a}`});return[`usage: workspace ${n.subcommand} <action> [--param <value>]... [--json]`,"",n.description,"","actions:",` ${n.actions.join(", ")}`,"","options:",...e," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
139
+ `)}function si(){let n=[...ve.map(a=>({label:a.name,description:a.description,actions:a.actions})),...Object.entries(ni).map(([a,l])=>{let d=xu(a,l);return{label:a,description:d.description,actions:d.actions}}),{label:ar.subcommand,description:"Full documentation for any tool",actions:[]}],e=[...n.map(a=>a.label),...Ru.map(a=>a.name)],t=Math.max(...e.map(a=>a.length))+2,s=n.map(a=>{let l=a.actions.length>0?` \u2014 ${cg(a.actions)}`:"";return` ${a.label.padEnd(t)}${ag(a.description)}${l}`}),o=Ru.map(a=>` ${a.name.padEnd(t)}${a.description}`);return[`workspace ${yt()} \u2014 Google Workspace MCP server`,"","usage:"," workspace start the MCP server (stdio)"," workspace --http start the MCP server (HTTP)"," workspace <tool> <action> [--param] call one tool from the terminal"," workspace help [topic] tool documentation","","tools (each is an MCP tool; the CLI runs the same handler):",...s,"","operator commands (not tools):",...o,"","examples:"," workspace time getCurrentTime --json",' workspace gmail search --query "is:unread" --maxResults 5'," workspace docs getText --documentId <document-id> --limit 2000"," workspace config-tool status --json"," workspace help tasks"].join(`
140
+ `)}function ug(n,e){try{return JSON.parse(e)}catch{throw new Se(`--${n} expects JSON, got '${e}'`)}}function dg(n,e,t){switch(t.type){case"number":{let s=Number(e);if(!Number.isFinite(s))throw new Se(`--${n} expects a number, got '${e}'`);return s}case"boolean":{if(e==="true"||e==="")return!0;if(e==="false")return!1;throw new Se(`--${n} expects 'true' or 'false', got '${e}'`)}case"array":return e.startsWith("[")?ug(n,e):e.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return e}}function fg(n,e){let t=[],s={},o=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(l===rg){o=!0;continue}if(!l.startsWith("--")){t.push(l);continue}let[d,p]=l.slice(2).split(/=(.*)/s),u=d.startsWith("no-"),f=u?d.slice(3):d,y=n.props[f];if(y===void 0){let R=Object.keys(n.props).map(x=>`--${x}`).join(", ");throw new Se(`unknown option --${f} (valid: ${R})`)}let g=ri(y);if(u){if(g.type!=="boolean")throw new Se(`--no-${f} only applies to boolean options`);s[f]=!1;continue}let _=e[a+1],S=p!==void 0,E=!S&&_!==void 0&&!_.startsWith("--");if(!S&&!E){if(g.type==="boolean"){s[f]=!0;continue}throw new Se(`--${f} expects a value`)}E&&(a+=1),s[f]=dg(f,S?p:_,g)}return{positionals:t,params:s,json:o}}function Eu(n){return n.content.map(e=>e.type==="text"?e.text:"").filter(e=>e.length>0).join(`
141
+ `)}function pg(n){try{return JSON.parse(n)}catch{return n}}async function mg(n,e,t=tg){let s=ig(n);if(!s)return t.err(`workspace: unknown tool '${n}' (expected one of: ${vu.join(", ")})`),Tu;let o=s.tool===ar.tool;if(e.some(u=>ng[u]===!0))return t.out(lg(s)),0;if(o&&!e.some(u=>!u.startsWith("-")))return t.out(si()),0;let a,l;try{if(a=fg(s,e),o){if(a.positionals.length>1)throw new Se(`help takes one topic, got ${a.positionals.length}`);l="help",a.positionals[0]!==void 0&&(a.params.topic=a.positionals[0])}else{let[u,...f]=a.positionals;if(u===void 0)throw new Se(`missing action (one of: ${s.actions.join(", ")})`);if(f.length>0)throw new Se(`unexpected argument '${f[0]}' (pass options as --name value)`);l=u,a.params.action=u}}catch(u){if(!(u instanceof Se))throw u;return t.err(`workspace ${n}: ${u.message}`),t.err(`run \`workspace ${n} --help\` for usage`),Tu}let d=await ys(s.tool,a.params);if(d.isError===!0){let u=Eu(d);return t.err(a.json?JSON.stringify({tool:s.tool,action:l,error:u}):u),1}let p=Eu(d);return a.json?(t.out(JSON.stringify({tool:s.tool,action:l,result:pg(p)},null,2)),0):(t.out(p),0)}function Cu(){return Object.fromEntries(vu.map(n=>[n,e=>mg(n,e)]))}import{homedir as _g}from"node:os";import{isAbsolute as Tg,join as rR,resolve as ii,sep as Rg}from"node:path";import{setHomeDirForTesting as Eg}from"@n24q02m/hull/storage";import{existsSync as ku,readdirSync as $u}from"node:fs";import{join as oi}from"node:path";import{isDeepStrictEqual as hg}from"node:util";import{credPath as gg,dataDirCandidates as Du,PerPluginStore as Au}from"@n24q02m/hull/storage";var kt=class extends Error{constructor(t,s){super(s);this.path=t;this.name="StoreMigrationError"}},yg=/^[A-Za-z0-9._-]+$/;function Ss(n){return n?.code??"unknown error"}function bg(n){try{return $u(n),!0}catch(e){let t=Ss(e);if(t==="ENOENT")return!1;throw new kt(n,`Cannot read the previous credential directory ${n} (${t}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}}function Sg(n){let e=oi(n,"subs"),t;try{t=$u(e,{withFileTypes:!0})}catch(s){let o=Ss(s);if(o==="ENOENT")return[];throw new kt(e,`Cannot read the previous credential directory ${e} (${o}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}return t.filter(s=>s.isDirectory()&&s.name!=="."&&s.name!==".."&&yg.test(s.name)).map(s=>s.name)}function Pu(n){for(let{dir:e}of Du(pn)){let t=n===null?oi(e,"config.json"):oi(e,"subs",n,"config.json");if(ku(t))return e}return null}async function Iu(n,e,t){let s=gg(We,n);if(ku(s)){t.kept.push(s);return}if(n!==null&&!process.env.CREDENTIAL_SECRET){t.deferred.push(n);return}let o;try{o=await new Au(pn,n).load()}catch(d){throw new kt(e,`Cannot read the saved credential in ${e} (${Ss(d)}). Nothing was migrated and the previous store was left untouched.`)}if(o===null)return;let a=new Au(We,n);try{await a.save(o)}catch(d){throw new kt(s,`Cannot write the migrated credential to ${s} (${Ss(d)}). The previous store in ${e} was left untouched.`)}let l=null;try{l=await a.load()}catch{l=null}if(!hg(l,o))throw new kt(s,`Wrote ${s} but reading it back did not return the migrated credential. The previous store in ${e} was left untouched.`);t.migrated.push({source:e,sub:n})}async function wg(){let n={migrated:[],kept:[],deferred:[]},e=Du(pn).map(o=>o.dir).filter(o=>bg(o));if(e.length===0)return n;let t=new Set;for(let o of e)for(let a of Sg(o))t.add(a);let s=Pu(null);s!==null&&await Iu(null,s,n);for(let o of[...t].sort()){let a=Pu(o);a!==null&&await Iu(o,a,n)}return n}var Ou=null;function Lu(){return Ou??=wg(),Ou}var ws="WORKSPACE_DATA_DIR",iR=`.${We}`,_s=class extends Error{constructor(e){super(e),this.name="DataDirEscapeError"}};function xg(n=process.env,e=_g()){let t=ii(e),s=n[ws]?.trim();if(!s)return t;if(s.includes("\0"))throw new _s(`${ws} must not contain a NUL byte`);if(Tg(s))return ii(s);let o=ii(t,s);if(o!==t&&!o.startsWith(t+Rg))throw new _s(`${ws}="${s}" escapes the base directory ${t}; use an absolute path to choose another directory`);return o}function vg(n=process.env){if(!n[ws]?.trim())return null;let e=xg(n);return Eg(e),e}async function ai(n=process.env){return vg(n),Lu()}import{Server as Cg}from"@modelcontextprotocol/sdk/server/index.js";import{runHttpServer as Ag}from"@n24q02m/hull/transport";var Pg="WORKSPACE_USERS_FILE";async function Nu(){if(!process.env.CREDENTIAL_SECRET)throw new Error("CREDENTIAL_SECRET is required for http mode: per-user credential stores derive their encryption key from it.");let n=process.env.PORT?Number.parseInt(process.env.PORT,10):0,e=process.env.HOST,t=await Ag(()=>{let s=new Cg({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});return bs(s,{allowLocalFilesystem:!1}),s},{serverName:ce,port:n,host:e,auth:{mode:"multi",usersFile:process.env[Pg]||void 0}});console.error(`[${ce}] http mode on http://${t.host}:${t.port}/mcp`),await new Promise(s=>{let o=async()=>{await t.close(),s()};process.once("SIGINT",o),process.once("SIGTERM",o)})}function Dg(n){let e=process.argv[1];if(!e)return!1;try{let t=Mu(Ig(n)),s=Mu(e);if(process.platform==="win32"){let o=a=>a.replace(/\\/g,"/").toLowerCase();return o(t)===o(s)}return t===s}catch{return!1}}function Lg(n=process.env,e=process.argv){return e.includes("--http")||n.MCP_TRANSPORT==="http"||n.TRANSPORT_MODE==="http"?"http":"stdio"}async function Ng(n){if(await ai(),process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED){console.error(`[${ce}] Startup aborted: server already running in this process tree.`);return}if(process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED="true",n==="http"){await Nu();return}await ot(),Ct()!=="configured"&&(await Da(),await ot());let e=new Og({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});bs(e);let t=new kg;await e.connect(t),console.error(`[${ce}] stdio mode ready (v${yt()})`)}var Mg=Lg();async function Fg(n=Mg){try{await Ng(n)}catch(e){console.error("Failed to start server:",e instanceof Error?e.message:String(e)),process.exit(1)}}async function Bg(n){if(await ai(),n[0]==="-h"||n[0]==="--help"){console.log(si()),process.exitCode=0;return}let e=$g(ce,{serve:()=>Fg(),extra:{auth:Na,relay:async()=>(console.error("relay was removed; run `workspace auth` (see README)"),2),...Cu()},version:yt(),pluginName:We});process.exitCode=await e(n)}Dg(import.meta.url)&&process.env.NODE_ENV!=="test"&&Bg(process.argv.slice(2));export{Fg as bootstrap,Lg as getTransportMode,Dg as isMain,Mg as mode,Bg as runCli,Ng as startServer};
142
142
  /**
143
143
  * @license
144
144
  * Copyright 2025 Google LLC