@clinebot/core 0.0.4 → 0.0.5
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/dist/agents/agent-config-parser.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.node.js +63 -63
- package/dist/runtime/session-runtime.d.ts +1 -1
- package/dist/session/default-session-manager.d.ts +1 -1
- package/dist/session/session-host.d.ts +1 -1
- package/dist/session/session-manager.d.ts +1 -1
- package/dist/session/unified-session-persistence-service.d.ts +4 -0
- package/dist/types/config.d.ts +1 -1
- package/package.json +4 -3
- package/src/agents/agent-config-parser.ts +1 -1
- package/src/index.ts +19 -19
- package/src/providers/local-provider-service.ts +25 -7
- package/src/runtime/runtime-builder.ts +2 -2
- package/src/runtime/runtime-parity.test.ts +1 -1
- package/src/runtime/session-runtime.ts +1 -1
- package/src/session/default-session-manager.ts +4 -5
- package/src/session/session-host.ts +1 -1
- package/src/session/session-manager.ts +1 -1
- package/src/session/unified-session-persistence-service.ts +213 -23
- package/src/types/config.ts +1 -1
- /package/dist/{default-tools → tools}/constants.d.ts +0 -0
- /package/dist/{default-tools → tools}/definitions.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/apply-patch-parser.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/apply-patch.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/bash.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/editor.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/file-read.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/index.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/search.d.ts +0 -0
- /package/dist/{default-tools → tools}/executors/web-fetch.d.ts +0 -0
- /package/dist/{default-tools → tools}/index.d.ts +0 -0
- /package/dist/{default-tools → tools}/model-tool-routing.d.ts +0 -0
- /package/dist/{default-tools → tools}/presets.d.ts +0 -0
- /package/dist/{default-tools → tools}/schemas.d.ts +0 -0
- /package/dist/{default-tools → tools}/types.d.ts +0 -0
- /package/src/{default-tools → tools}/constants.ts +0 -0
- /package/src/{default-tools → tools}/definitions.test.ts +0 -0
- /package/src/{default-tools → tools}/definitions.ts +0 -0
- /package/src/{default-tools → tools}/executors/apply-patch-parser.ts +0 -0
- /package/src/{default-tools → tools}/executors/apply-patch.ts +0 -0
- /package/src/{default-tools → tools}/executors/bash.ts +0 -0
- /package/src/{default-tools → tools}/executors/editor.ts +0 -0
- /package/src/{default-tools → tools}/executors/file-read.test.ts +0 -0
- /package/src/{default-tools → tools}/executors/file-read.ts +0 -0
- /package/src/{default-tools → tools}/executors/index.ts +0 -0
- /package/src/{default-tools → tools}/executors/search.ts +0 -0
- /package/src/{default-tools → tools}/executors/web-fetch.ts +0 -0
- /package/src/{default-tools → tools}/index.ts +0 -0
- /package/src/{default-tools → tools}/model-tool-routing.test.ts +0 -0
- /package/src/{default-tools → tools}/model-tool-routing.ts +0 -0
- /package/src/{default-tools → tools}/presets.test.ts +0 -0
- /package/src/{default-tools → tools}/presets.ts +0 -0
- /package/src/{default-tools → tools}/schemas.ts +0 -0
- /package/src/{default-tools → tools}/types.ts +0 -0
package/dist/index.node.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{createRequire as AD}from"node:module";var qD=Object.create;var{getPrototypeOf:XD,defineProperty:bJ,getOwnPropertyNames:JD}=Object;var QD=Object.prototype.hasOwnProperty;function UD($){return this[$]}var ZD,KD,ZY=($,Y,T)=>{var q=$!=null&&typeof $==="object";if(q){var X=Y?ZD??=new WeakMap:KD??=new WeakMap,J=X.get($);if(J)return J}T=$!=null?qD(XD($)):{};let Q=Y||!$||!$.__esModule?bJ(T,"default",{value:$,enumerable:!0}):T;for(let U of JD($))if(!QD.call(Q,U))bJ(Q,U,{get:UD.bind($,U),enumerable:!0});if(q)X.set($,Q);return Q};var M=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var s=AD(import.meta.url);var i=M((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});q7.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=q7.DEFAULT_MAX_SEND_MESSAGE_LENGTH=q7.Propagate=q7.LogVerbosity=q7.Status=void 0;var $7;(function($){$[$.OK=0]="OK",$[$.CANCELLED=1]="CANCELLED",$[$.UNKNOWN=2]="UNKNOWN",$[$.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",$[$.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",$[$.NOT_FOUND=5]="NOT_FOUND",$[$.ALREADY_EXISTS=6]="ALREADY_EXISTS",$[$.PERMISSION_DENIED=7]="PERMISSION_DENIED",$[$.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",$[$.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",$[$.ABORTED=10]="ABORTED",$[$.OUT_OF_RANGE=11]="OUT_OF_RANGE",$[$.UNIMPLEMENTED=12]="UNIMPLEMENTED",$[$.INTERNAL=13]="INTERNAL",$[$.UNAVAILABLE=14]="UNAVAILABLE",$[$.DATA_LOSS=15]="DATA_LOSS",$[$.UNAUTHENTICATED=16]="UNAUTHENTICATED"})($7||(q7.Status=$7={}));var Y7;(function($){$[$.DEBUG=0]="DEBUG",$[$.INFO=1]="INFO",$[$.ERROR=2]="ERROR",$[$.NONE=3]="NONE"})(Y7||(q7.LogVerbosity=Y7={}));var T7;(function($){$[$.DEADLINE=1]="DEADLINE",$[$.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",$[$.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",$[$.CANCELLATION=8]="CANCELLATION",$[$.DEFAULTS=65535]="DEFAULTS"})(T7||(q7.Propagate=T7={}));q7.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;q7.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4194304});var m4=M((v_,jz)=>{jz.exports={name:"@grpc/grpc-js",version:"1.14.3",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var U0=M((U7)=>{var f4,b4,u4,d4;Object.defineProperty(U7,"__esModule",{value:!0});U7.log=U7.setLoggerVerbosity=U7.setLogger=U7.getLogger=void 0;U7.trace=dz;U7.isTracerEnabled=Q7;var z$=i(),vz=s("process"),xz=m4().version,kz={error:($,...Y)=>{console.error("E "+$,...Y)},info:($,...Y)=>{console.error("I "+$,...Y)},debug:($,...Y)=>{console.error("D "+$,...Y)}},c$=kz,MY=z$.LogVerbosity.ERROR,hz=(b4=(f4=process.env.GRPC_NODE_VERBOSITY)!==null&&f4!==void 0?f4:process.env.GRPC_VERBOSITY)!==null&&b4!==void 0?b4:"";switch(hz.toUpperCase()){case"DEBUG":MY=z$.LogVerbosity.DEBUG;break;case"INFO":MY=z$.LogVerbosity.INFO;break;case"ERROR":MY=z$.LogVerbosity.ERROR;break;case"NONE":MY=z$.LogVerbosity.NONE;break;default:}var _z=()=>{return c$};U7.getLogger=_z;var gz=($)=>{c$=$};U7.setLogger=gz;var mz=($)=>{MY=$};U7.setLoggerVerbosity=mz;var fz=($,...Y)=>{let T;if($>=MY){switch($){case z$.LogVerbosity.DEBUG:T=c$.debug;break;case z$.LogVerbosity.INFO:T=c$.info;break;case z$.LogVerbosity.ERROR:T=c$.error;break}if(!T)T=c$.error;if(T)T.bind(c$)(...Y)}};U7.log=fz;var bz=(d4=(u4=process.env.GRPC_NODE_TRACE)!==null&&u4!==void 0?u4:process.env.GRPC_TRACE)!==null&&d4!==void 0?d4:"",c4=new Set,J7=new Set;for(let $ of bz.split(","))if($.startsWith("-"))J7.add($.substring(1));else c4.add($);var uz=c4.has("all");function dz($,Y,T){if(Q7(Y))U7.log($,new Date().toISOString()+" | v"+xz+" "+vz.pid+" | "+Y+" | "+T)}function Q7($){return!J7.has($)&&(uz||c4.has($))}});var x8=M((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});Z7.getErrorMessage=rz;Z7.getErrorCode=az;function rz($){if($ instanceof Error)return $.message;else return String($)}function az($){if(typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="number")return $.code;else return null}});var P0=M((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});W7.Metadata=void 0;var tz=U0(),ez=i(),$I=x8(),YI=/^[:0-9a-z_.-]+$/,TI=/^[ -~]*$/;function qI($){return YI.test($)}function XI($){return TI.test($)}function A7($){return $.endsWith("-bin")}function JI($){return!$.startsWith("grpc-")}function k8($){return $.toLowerCase()}function K7($,Y){if(!qI($))throw Error('Metadata key "'+$+'" contains illegal characters');if(Y!==null&&Y!==void 0)if(A7($)){if(!Buffer.isBuffer(Y))throw Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(Y))throw Error("keys that don't end with '-bin' must have String values");if(!XI(Y))throw Error('Metadata string value "'+Y+'" contains illegal characters')}}class h8{constructor($={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=$}set($,Y){$=k8($),K7($,Y),this.internalRepr.set($,[Y])}add($,Y){$=k8($),K7($,Y);let T=this.internalRepr.get($);if(T===void 0)this.internalRepr.set($,[Y]);else T.push(Y)}remove($){$=k8($),this.internalRepr.delete($)}get($){return $=k8($),this.internalRepr.get($)||[]}getMap(){let $={};for(let[Y,T]of this.internalRepr)if(T.length>0){let q=T[0];$[Y]=Buffer.isBuffer(q)?Buffer.from(q):q}return $}clone(){let $=new h8(this.options),Y=$.internalRepr;for(let[T,q]of this.internalRepr){let X=q.map((J)=>{if(Buffer.isBuffer(J))return Buffer.from(J);else return J});Y.set(T,X)}return $}merge($){for(let[Y,T]of $.internalRepr){let q=(this.internalRepr.get(Y)||[]).concat(T);this.internalRepr.set(Y,q)}}setOptions($){this.options=$}getOptions(){return this.options}toHttp2Headers(){let $={};for(let[Y,T]of this.internalRepr){if(Y.startsWith(":"))continue;$[Y]=T.map(QI)}return $}toJSON(){let $={};for(let[Y,T]of this.internalRepr)$[Y]=T;return $}setOpaque($,Y){this.opaqueData.set($,Y)}getOpaque($){return this.opaqueData.get($)}static fromHttp2Headers($){let Y=new h8;for(let T of Object.keys($)){if(T.charAt(0)===":")continue;let q=$[T];try{if(A7(T)){if(Array.isArray(q))q.forEach((X)=>{Y.add(T,Buffer.from(X,"base64"))});else if(q!==void 0)if(JI(T))q.split(",").forEach((X)=>{Y.add(T,Buffer.from(X.trim(),"base64"))});else Y.add(T,Buffer.from(q,"base64"))}else if(Array.isArray(q))q.forEach((X)=>{Y.add(T,X)});else if(q!==void 0)Y.add(T,q)}catch(X){let J=`Failed to add metadata entry ${T}: ${q}. ${(0,$I.getErrorMessage)(X)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,tz.log)(ez.LogVerbosity.ERROR,J)}}return Y}}W7.Metadata=h8;var QI=($)=>{return Buffer.isBuffer($)?$.toString("base64"):$}});var g8=M((E7)=>{Object.defineProperty(E7,"__esModule",{value:!0});E7.CallCredentials=void 0;var l4=P0();function UI($){return"getRequestHeaders"in $&&typeof $.getRequestHeaders==="function"}class BY{static createFromMetadataGenerator($){return new n4($)}static createFromGoogleCredential($){return BY.createFromMetadataGenerator((Y,T)=>{let q;if(UI($))q=$.getRequestHeaders(Y.service_url);else q=new Promise((X,J)=>{$.getRequestMetadata(Y.service_url,(Q,U)=>{if(Q){J(Q);return}if(!U){J(Error("Headers not set by metadata plugin"));return}X(U)})});q.then((X)=>{let J=new l4.Metadata;for(let Q of Object.keys(X))J.add(Q,X[Q]);T(null,J)},(X)=>{T(X)})})}static createEmpty(){return new i4}}E7.CallCredentials=BY;class _8 extends BY{constructor($){super();this.creds=$}async generateMetadata($){let Y=new l4.Metadata,T=await Promise.all(this.creds.map((q)=>q.generateMetadata($)));for(let q of T)Y.merge(q);return Y}compose($){return new _8(this.creds.concat([$]))}_equals($){if(this===$)return!0;if($ instanceof _8)return this.creds.every((Y,T)=>Y._equals($.creds[T]));else return!1}}class n4 extends BY{constructor($){super();this.metadataGenerator=$}generateMetadata($){return new Promise((Y,T)=>{this.metadataGenerator($,(q,X)=>{if(X!==void 0)Y(X);else T(q)})})}compose($){return new _8([this,$])}_equals($){if(this===$)return!0;if($ instanceof n4)return this.metadataGenerator===$.metadataGenerator;else return!1}}class i4 extends BY{generateMetadata($){return Promise.resolve(new l4.Metadata)}compose($){return $}_equals($){return $ instanceof i4}}});var a4=M((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.CIPHER_SUITES=void 0;F7.getDefaultRootsData=KI;var ZI=s("fs");F7.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var D7=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,r4=null;function KI(){if(D7){if(r4===null)r4=ZI.readFileSync(D7);return r4}return null}});var p0=M((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});z7.parseUri=GI;z7.splitHostPort=EI;z7.combineHostPort=VI;z7.uriToString=DI;var WI=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function GI($){let Y=WI.exec($);if(Y===null)return null;return{scheme:Y[1],authority:Y[2],path:Y[3]}}var H7=/^\d+$/;function EI($){if($.startsWith("[")){let Y=$.indexOf("]");if(Y===-1)return null;let T=$.substring(1,Y);if(T.indexOf(":")===-1)return null;if($.length>Y+1)if($[Y+1]===":"){let q=$.substring(Y+2);if(H7.test(q))return{host:T,port:+q};else return null}else return null;else return{host:T}}else{let Y=$.split(":");if(Y.length===2)if(H7.test(Y[1]))return{host:Y[0],port:+Y[1]};else return null;else return{host:$}}}function VI($){if($.port===void 0)return $.host;else if($.host.includes(":"))return`[${$.host}]:${$.port}`;else return`${$.host}:${$.port}`}function DI($){let Y="";if($.scheme!==void 0)Y+=$.scheme+":";if($.authority!==void 0)Y+="//"+$.authority+"/";return Y+=$.path,Y}});var B1=M((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;I7.registerResolver=II;I7.registerDefaultScheme=MI;I7.createResolver=BI;I7.getDefaultAuthority=RI;I7.mapUriDefaultScheme=OI;var s4=p0();I7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var RY={},o4=null;function II($,Y){RY[$]=Y}function MI($){o4=$}function BI($,Y,T){if($.scheme!==void 0&&$.scheme in RY)return new RY[$.scheme]($,Y,T);else throw Error(`No resolver could be created for target ${(0,s4.uriToString)($)}`)}function RI($){if($.scheme!==void 0&&$.scheme in RY)return RY[$.scheme].getDefaultAuthority($);else throw Error(`Invalid target ${(0,s4.uriToString)($)}`)}function OI($){if($.scheme===void 0||!($.scheme in RY))if(o4!==null)return{scheme:o4,authority:void 0,path:(0,s4.uriToString)($)};else return null;return $}});var PY=M((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.ChannelCredentials=void 0;P7.createCertificateProviderChannelCredentials=xI;var wT=s("tls"),b8=g8(),e4=a4(),B7=p0(),yI=B1(),jI=U0(),vI=i();function t4($,Y){if($&&!($ instanceof Buffer))throw TypeError(`${Y}, if provided, must be a Buffer.`)}class OY{compose($){return new f8(this,$)}static createSsl($,Y,T,q){var X;if(t4($,"Root certificate"),t4(Y,"Private key"),t4(T,"Certificate chain"),Y&&!T)throw Error("Private key must be given with accompanying certificate chain");if(!Y&&T)throw Error("Certificate chain must be given with accompanying private key");let J=(0,wT.createSecureContext)({ca:(X=$!==null&&$!==void 0?$:(0,e4.getDefaultRootsData)())!==null&&X!==void 0?X:void 0,key:Y!==null&&Y!==void 0?Y:void 0,cert:T!==null&&T!==void 0?T:void 0,ciphers:e4.CIPHER_SUITES});return new m8(J,q!==null&&q!==void 0?q:{})}static createFromSecureContext($,Y){return new m8($,Y!==null&&Y!==void 0?Y:{})}static createInsecure(){return new $X}}P7.ChannelCredentials=OY;class $X extends OY{constructor(){super()}compose($){throw Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals($){return $ instanceof $X}_createSecureConnector($,Y,T){return{connect(q){return Promise.resolve({socket:q,secure:!1})},waitForReady:()=>{return Promise.resolve()},getCallCredentials:()=>{return T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty()},destroy(){}}}}function R7($,Y,T,q){var X,J;let Q={secureContext:$},U=T;if("grpc.http_connect_target"in q){let W=(0,B7.parseUri)(q["grpc.http_connect_target"]);if(W)U=W}let Z=(0,yI.getDefaultAuthority)(U),K=(0,B7.splitHostPort)(Z),A=(X=K===null||K===void 0?void 0:K.host)!==null&&X!==void 0?X:Z;if(Q.host=A,Y.checkServerIdentity)Q.checkServerIdentity=Y.checkServerIdentity;if(Y.rejectUnauthorized!==void 0)Q.rejectUnauthorized=Y.rejectUnauthorized;if(Q.ALPNProtocols=["h2"],q["grpc.ssl_target_name_override"]){let W=q["grpc.ssl_target_name_override"],E=(J=Q.checkServerIdentity)!==null&&J!==void 0?J:wT.checkServerIdentity;Q.checkServerIdentity=(D,F)=>{return E(W,F)},Q.servername=W}else Q.servername=A;if(q["grpc-node.tls_enable_trace"])Q.enableTrace=!0;return Q}class O7{constructor($,Y){this.connectionOptions=$,this.callCredentials=Y}connect($){let Y=Object.assign({socket:$},this.connectionOptions);return new Promise((T,q)=>{let X=(0,wT.connect)(Y,()=>{var J;if(((J=this.connectionOptions.rejectUnauthorized)!==null&&J!==void 0?J:!0)&&!X.authorized){q(X.authorizationError);return}T({socket:X,secure:!0})});X.on("error",(J)=>{q(J)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}}class m8 extends OY{constructor($,Y){super();this.secureContext=$,this.verifyOptions=Y}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof m8)return this.secureContext===$.secureContext&&this.verifyOptions.checkServerIdentity===$.verifyOptions.checkServerIdentity;else return!1}_createSecureConnector($,Y,T){let q=R7(this.secureContext,this.verifyOptions,$,Y);return new O7(q,T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty())}}class LT extends OY{constructor($,Y,T){super();this.caCertificateProvider=$,this.identityCertificateProvider=Y,this.verifyOptions=T,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals($){var Y,T;if(this===$)return!0;if($ instanceof LT)return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&((Y=this.verifyOptions)===null||Y===void 0?void 0:Y.checkServerIdentity)===((T=$.verifyOptions)===null||T===void 0?void 0:T.checkServerIdentity);else return!1}ref(){var $;if(this.refcount===0)this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),($=this.identityCertificateProvider)===null||$===void 0||$.addIdentityCertificateListener(this.identityCertificateUpdateListener);this.refcount+=1}unref(){var $;if(this.refcount-=1,this.refcount===0)this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),($=this.identityCertificateProvider)===null||$===void 0||$.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_createSecureConnector($,Y,T){return this.ref(),new LT.SecureConnectorImpl(this,$,Y,T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let $ of this.secureContextWatchers)$(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate($){this.latestCaUpdate=$,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate($){this.latestIdentityUpdate=$,this.maybeUpdateWatchers()}hasReceivedUpdates(){if(this.latestCaUpdate===void 0)return!1;if(this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)return!1;return!0}getSecureContext(){if(this.hasReceivedUpdates())return Promise.resolve(this.getLatestSecureContext());else return new Promise(($)=>{this.secureContextWatchers.push($)})}getLatestSecureContext(){var $,Y;if(!this.latestCaUpdate)return null;if(this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,wT.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:($=this.latestIdentityUpdate)===null||$===void 0?void 0:$.privateKey,cert:(Y=this.latestIdentityUpdate)===null||Y===void 0?void 0:Y.certificate,ciphers:e4.CIPHER_SUITES})}catch(T){return(0,jI.log)(vI.LogVerbosity.ERROR,"Failed to createSecureContext with error "+T.message),null}}}LT.SecureConnectorImpl=class{constructor($,Y,T,q){this.parent=$,this.channelTarget=Y,this.options=T,this.callCredentials=q}connect($){return new Promise((Y,T)=>{let q=this.parent.getLatestSecureContext();if(!q){T(Error("Failed to load credentials"));return}if($.closed)T(Error("Socket closed while loading credentials"));let X=R7(q,this.parent.verifyOptions,this.channelTarget,this.options),J=Object.assign({socket:$},X),Q=()=>{T(Error("Socket closed"))},U=(K)=>{T(K)},Z=(0,wT.connect)(J,()=>{var K;if(Z.removeListener("close",Q),Z.removeListener("error",U),((K=this.parent.verifyOptions.rejectUnauthorized)!==null&&K!==void 0?K:!0)&&!Z.authorized){T(Z.authorizationError);return}Y({socket:Z,secure:!0})});Z.once("close",Q),Z.once("error",U)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function xI($,Y,T){return new LT($,Y,T!==null&&T!==void 0?T:{})}class f8 extends OY{constructor($,Y){super();if(this.channelCredentials=$,this.callCredentials=Y,!$._isSecure())throw Error("Cannot compose insecure credentials")}compose($){let Y=this.callCredentials.compose($);return new f8(this.channelCredentials,Y)}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof f8)return this.channelCredentials._equals($.channelCredentials)&&this.callCredentials._equals($.callCredentials);else return!1}_createSecureConnector($,Y,T){let q=this.callCredentials.compose(T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector($,Y,q)}}});var M$=M((S7)=>{Object.defineProperty(S7,"__esModule",{value:!0});S7.createChildChannelControlHelper=gI;S7.registerLoadBalancerType=mI;S7.registerDefaultLoadBalancerType=fI;S7.createLoadBalancer=bI;S7.isLoadBalancerNameRegistered=uI;S7.parseLoadBalancingConfig=w7;S7.getDefaultConfig=dI;S7.selectLbConfigFromList=cI;var hI=U0(),_I=i();function gI($,Y){var T,q,X,J,Q,U,Z,K,A,W;return{createSubchannel:(q=(T=Y.createSubchannel)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:$.createSubchannel.bind($),updateState:(J=(X=Y.updateState)===null||X===void 0?void 0:X.bind(Y))!==null&&J!==void 0?J:$.updateState.bind($),requestReresolution:(U=(Q=Y.requestReresolution)===null||Q===void 0?void 0:Q.bind(Y))!==null&&U!==void 0?U:$.requestReresolution.bind($),addChannelzChild:(K=(Z=Y.addChannelzChild)===null||Z===void 0?void 0:Z.bind(Y))!==null&&K!==void 0?K:$.addChannelzChild.bind($),removeChannelzChild:(W=(A=Y.removeChannelzChild)===null||A===void 0?void 0:A.bind(Y))!==null&&W!==void 0?W:$.removeChannelzChild.bind($)}}var I$={},ST=null;function mI($,Y,T){I$[$]={LoadBalancer:Y,LoadBalancingConfig:T}}function fI($){ST=$}function bI($,Y){let T=$.getLoadBalancerName();if(T in I$)return new I$[T].LoadBalancer(Y);else return null}function uI($){return $ in I$}function w7($){let Y=Object.keys($);if(Y.length!==1)throw Error("Provided load balancing config has multiple conflicting entries");let T=Y[0];if(T in I$)try{return I$[T].LoadBalancingConfig.createFromJson($[T])}catch(q){throw Error(`${T}: ${q.message}`)}else throw Error(`Unrecognized load balancing config name ${T}`)}function dI(){if(!ST)throw Error("No default load balancer type registered");return new I$[ST].LoadBalancingConfig}function cI($,Y=!1){for(let T of $)try{return w7(T)}catch(q){(0,hI.log)(_I.LogVerbosity.DEBUG,"Config parsing failed with error",q.message);continue}if(Y)if(ST)return new I$[ST].LoadBalancingConfig;else return null;else return null}});var YX=M((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});j7.validateRetryThrottling=C7;j7.validateServiceConfig=y7;j7.extractAndSelectServiceConfig=UM;var tI=s("os"),u8=i(),d8=/^\d+(\.\d{1,9})?s$/,eI="node";function $M($){if("service"in $&&$.service!==""){if(typeof $.service!=="string")throw Error(`Invalid method config name: invalid service: expected type string, got ${typeof $.service}`);if("method"in $&&$.method!==""){if(typeof $.method!=="string")throw Error(`Invalid method config name: invalid method: expected type string, got ${typeof $.service}`);return{service:$.service,method:$.method}}else return{service:$.service}}else{if("method"in $&&$.method!==void 0)throw Error("Invalid method config name: method set with empty or unset service");return{}}}function YM($){if(!("maxAttempts"in $)||!Number.isInteger($.maxAttempts)||$.maxAttempts<2)throw Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in $)||typeof $.initialBackoff!=="string"||!d8.test($.initialBackoff))throw Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in $)||typeof $.maxBackoff!=="string"||!d8.test($.maxBackoff))throw Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in $)||typeof $.backoffMultiplier!=="number"||$.backoffMultiplier<=0)throw Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!(("retryableStatusCodes"in $)&&Array.isArray($.retryableStatusCodes)))throw Error("Invalid method config retry policy: retryableStatusCodes is required");if($.retryableStatusCodes.length===0)throw Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let Y of $.retryableStatusCodes)if(typeof Y==="number"){if(!Object.values(u8.Status).includes(Y))throw Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof Y==="string"){if(!Object.values(u8.Status).includes(Y.toUpperCase()))throw Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:$.maxAttempts,initialBackoff:$.initialBackoff,maxBackoff:$.maxBackoff,backoffMultiplier:$.backoffMultiplier,retryableStatusCodes:$.retryableStatusCodes}}function TM($){if(!("maxAttempts"in $)||!Number.isInteger($.maxAttempts)||$.maxAttempts<2)throw Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in $&&(typeof $.hedgingDelay!=="string"||!d8.test($.hedgingDelay)))throw Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in $&&Array.isArray($.nonFatalStatusCodes))for(let T of $.nonFatalStatusCodes)if(typeof T==="number"){if(!Object.values(u8.Status).includes(T))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof T==="string"){if(!Object.values(u8.Status).includes(T.toUpperCase()))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let Y={maxAttempts:$.maxAttempts};if($.hedgingDelay)Y.hedgingDelay=$.hedgingDelay;if($.nonFatalStatusCodes)Y.nonFatalStatusCodes=$.nonFatalStatusCodes;return Y}function qM($){var Y;let T={name:[]};if(!("name"in $)||!Array.isArray($.name))throw Error("Invalid method config: invalid name array");for(let q of $.name)T.name.push($M(q));if("waitForReady"in $){if(typeof $.waitForReady!=="boolean")throw Error("Invalid method config: invalid waitForReady");T.waitForReady=$.waitForReady}if("timeout"in $)if(typeof $.timeout==="object"){if(!("seconds"in $.timeout)||typeof $.timeout.seconds!=="number")throw Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in $.timeout)||typeof $.timeout.nanos!=="number")throw Error("Invalid method config: invalid timeout.nanos");T.timeout=$.timeout}else if(typeof $.timeout==="string"&&d8.test($.timeout)){let q=$.timeout.substring(0,$.timeout.length-1).split(".");T.timeout={seconds:q[0]|0,nanos:((Y=q[1])!==null&&Y!==void 0?Y:0)|0}}else throw Error("Invalid method config: invalid timeout");if("maxRequestBytes"in $){if(typeof $.maxRequestBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");T.maxRequestBytes=$.maxRequestBytes}if("maxResponseBytes"in $){if(typeof $.maxResponseBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");T.maxResponseBytes=$.maxResponseBytes}if("retryPolicy"in $)if("hedgingPolicy"in $)throw Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");else T.retryPolicy=YM($.retryPolicy);else if("hedgingPolicy"in $)T.hedgingPolicy=TM($.hedgingPolicy);return T}function C7($){if(!("maxTokens"in $)||typeof $.maxTokens!=="number"||$.maxTokens<=0||$.maxTokens>1000)throw Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in $)||typeof $.tokenRatio!=="number"||$.tokenRatio<=0)throw Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+$.maxTokens.toFixed(3),tokenRatio:+$.tokenRatio.toFixed(3)}}function XM($){if(!(typeof $==="object"&&$!==null))throw Error(`Invalid loadBalancingConfig: unexpected type ${typeof $}`);let Y=Object.keys($);if(Y.length>1)throw Error(`Invalid loadBalancingConfig: unexpected multiple keys ${Y}`);if(Y.length===0)throw Error("Invalid loadBalancingConfig: load balancing policy name required");return{[Y[0]]:$[Y[0]]}}function y7($){let Y={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in $)if(typeof $.loadBalancingPolicy==="string")Y.loadBalancingPolicy=$.loadBalancingPolicy;else throw Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in $)if(Array.isArray($.loadBalancingConfig))for(let q of $.loadBalancingConfig)Y.loadBalancingConfig.push(XM(q));else throw Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in $){if(Array.isArray($.methodConfig))for(let q of $.methodConfig)Y.methodConfig.push(qM(q))}if("retryThrottling"in $)Y.retryThrottling=C7($.retryThrottling);let T=[];for(let q of Y.methodConfig)for(let X of q.name){for(let J of T)if(X.service===J.service&&X.method===J.method)throw Error(`Invalid service config: duplicate name ${X.service}/${X.method}`);T.push(X)}return Y}function JM($){if(!("serviceConfig"in $))throw Error("Invalid service config choice: missing service config");let Y={serviceConfig:y7($.serviceConfig)};if("clientLanguage"in $)if(Array.isArray($.clientLanguage)){Y.clientLanguage=[];for(let q of $.clientLanguage)if(typeof q==="string")Y.clientLanguage.push(q);else throw Error("Invalid service config choice: invalid clientLanguage")}else throw Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in $)if(Array.isArray($.clientHostname)){Y.clientHostname=[];for(let q of $.clientHostname)if(typeof q==="string")Y.clientHostname.push(q);else throw Error("Invalid service config choice: invalid clientHostname")}else throw Error("Invalid service config choice: invalid clientHostname");if("percentage"in $)if(typeof $.percentage==="number"&&0<=$.percentage&&$.percentage<=100)Y.percentage=$.percentage;else throw Error("Invalid service config choice: invalid percentage");let T=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let q in $)if(!T.includes(q))throw Error(`Invalid service config choice: unexpected field ${q}`);return Y}function QM($,Y){if(!Array.isArray($))throw Error("Invalid service config list");for(let T of $){let q=JM(T);if(typeof q.percentage==="number"&&Y>q.percentage)continue;if(Array.isArray(q.clientHostname)){let X=!1;for(let J of q.clientHostname)if(J===tI.hostname())X=!0;if(!X)continue}if(Array.isArray(q.clientLanguage)){let X=!1;for(let J of q.clientLanguage)if(J===eI)X=!0;if(!X)continue}return q.serviceConfig}throw Error("No matching service config found")}function UM($,Y){for(let T of $)if(T.length>0&&T[0].startsWith("grpc_config=")){let q=T.join("").substring(12),X=JSON.parse(q);return QM(X,Y)}return null}});var l0=M((x7)=>{Object.defineProperty(x7,"__esModule",{value:!0});x7.ConnectivityState=void 0;var v7;(function($){$[$.IDLE=0]="IDLE",$[$.CONNECTING=1]="CONNECTING",$[$.READY=2]="READY",$[$.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",$[$.SHUTDOWN=4]="SHUTDOWN"})(v7||(x7.ConnectivityState=v7={}))});var Y$=M((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});g7.QueuePicker=g7.UnavailablePicker=g7.PickResultType=void 0;var WM=P0(),GM=i(),c8;(function($){$[$.COMPLETE=0]="COMPLETE",$[$.QUEUE=1]="QUEUE",$[$.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",$[$.DROP=3]="DROP"})(c8||(g7.PickResultType=c8={}));class h7{constructor($){this.status=Object.assign({code:GM.Status.UNAVAILABLE,details:"No connection established",metadata:new WM.Metadata},$)}pick($){return{pickResultType:c8.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}}g7.UnavailablePicker=h7;class _7{constructor($,Y){this.loadBalancer=$,this.childPicker=Y,this.calledExitIdle=!1}pick($){if(!this.calledExitIdle)process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0;if(this.childPicker)return this.childPicker.pick($);else return{pickResultType:c8.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}}g7.QueuePicker=_7});var LY=M((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});f7.BackoffTimeout=void 0;var DM=i(),FM=U0(),NM="backoff",HM=1000,zM=1.6,IM=120000,MM=0.2;function BM($,Y){return Math.random()*(Y-$)+$}class p8{constructor($,Y){if(this.callback=$,this.initialDelay=HM,this.multiplier=zM,this.maxDelay=IM,this.jitter=MM,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=p8.getNextId(),Y){if(Y.initialDelay)this.initialDelay=Y.initialDelay;if(Y.multiplier)this.multiplier=Y.multiplier;if(Y.jitter)this.jitter=Y.jitter;if(Y.maxDelay)this.maxDelay=Y.maxDelay}this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace($){FM.trace(DM.LogVerbosity.DEBUG,NM,"{"+this.id+"} "+$)}runTimer($){var Y,T;if(this.trace("runTimer(delay="+$+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+$),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},$),!this.hasRef)(T=(Y=this.timerId).unref)===null||T===void 0||T.call(Y)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let $=Math.min(this.nextDelay*this.multiplier,this.maxDelay),Y=$*this.jitter;this.nextDelay=$+BM(-Y,Y)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let $=new Date,Y=this.startTime;if(Y.setMilliseconds(Y.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),$<Y)this.runTimer(Y.getTime()-$.getTime());else this.running=!1}}isRunning(){return this.running}ref(){var $,Y;this.hasRef=!0,(Y=($=this.timerId).ref)===null||Y===void 0||Y.call($)}unref(){var $,Y;this.hasRef=!1,(Y=($=this.timerId).unref)===null||Y===void 0||Y.call($)}getEndTime(){return this.endTime}}f7.BackoffTimeout=p8;p8.nextId=0});var l8=M((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});d7.ChildLoadBalancerHandler=void 0;var RM=M$(),OM=l0(),PM="child_load_balancer_helper";class u7{constructor($){this.channelControlHelper=$,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(Y){this.parent=Y,this.child=null}createSubchannel(Y,T){return this.parent.channelControlHelper.createSubchannel(Y,T)}updateState(Y,T,q){var X;if(this.calledByPendingChild()){if(Y===OM.ConnectivityState.CONNECTING)return;(X=this.parent.currentChild)===null||X===void 0||X.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(Y,T,q)}requestReresolution(){var Y;let T=(Y=this.parent.pendingChild)!==null&&Y!==void 0?Y:this.parent.currentChild;if(this.child===T)this.parent.channelControlHelper.requestReresolution()}setChild(Y){this.child=Y}addChannelzChild(Y){this.parent.channelControlHelper.addChannelzChild(Y)}removeChannelzChild(Y){this.parent.channelControlHelper.removeChannelzChild(Y)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance($,Y){return $.getLoadBalancerName()!==Y.getLoadBalancerName()}updateAddressList($,Y,T,q){let X;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,Y)){let J=new this.ChildPolicyHelper(this),Q=(0,RM.createLoadBalancer)(Y,J);if(J.setChild(Q),this.currentChild===null)this.currentChild=Q,X=this.currentChild;else{if(this.pendingChild)this.pendingChild.destroy();this.pendingChild=Q,X=this.pendingChild}}else if(this.pendingChild===null)X=this.currentChild;else X=this.pendingChild;return this.latestConfig=Y,X.updateAddressList($,Y,T,q)}exitIdle(){if(this.currentChild){if(this.currentChild.exitIdle(),this.pendingChild)this.pendingChild.exitIdle()}}resetBackoff(){if(this.currentChild){if(this.currentChild.resetBackoff(),this.pendingChild)this.pendingChild.resetBackoff()}}destroy(){if(this.currentChild)this.currentChild.destroy(),this.currentChild=null;if(this.pendingChild)this.pendingChild.destroy(),this.pendingChild=null}getTypeName(){return PM}}d7.ChildLoadBalancerHandler=u7});var a7=M((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});i7.ResolvingLoadBalancer=void 0;var LM=M$(),wM=YX(),i0=l0(),p7=B1(),CT=Y$(),SM=LY(),TX=i(),CM=P0(),yM=U0(),jM=i(),vM=p0(),xM=l8(),kM="resolving_load_balancer";function l7($){yM.trace(jM.LogVerbosity.DEBUG,kM,$)}var hM=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function _M($,Y,T,q){for(let X of T.name)switch(q){case"EMPTY":if(!X.service&&!X.method)return!0;break;case"SERVICE":if(X.service===$&&!X.method)return!0;break;case"SERVICE_AND_METHOD":if(X.service===$&&X.method===Y)return!0}return!1}function gM($,Y,T,q){for(let X of T)if(_M($,Y,X,q))return X;return null}function mM($){return{invoke(Y,T){var q,X;let J=Y.split("/").filter((Z)=>Z.length>0),Q=(q=J[0])!==null&&q!==void 0?q:"",U=(X=J[1])!==null&&X!==void 0?X:"";if($&&$.methodConfig)for(let Z of hM){let K=gM(Q,U,$.methodConfig,Z);if(K)return{methodConfig:K,pickInformation:{},status:TX.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:TX.Status.OK,dynamicFilterFactories:[]}},unref(){}}}class n7{constructor($,Y,T,q,X){if(this.target=$,this.channelControlHelper=Y,this.channelOptions=T,this.onSuccessfulResolution=q,this.onFailedResolution=X,this.latestChildState=i0.ConnectivityState.IDLE,this.latestChildPicker=new CT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,T["grpc.service_config"])this.defaultServiceConfig=(0,wM.validateServiceConfig)(JSON.parse(T["grpc.service_config"]));else this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]};this.updateState(i0.ConnectivityState.IDLE,new CT.QueuePicker(this),null),this.childLoadBalancer=new xM.ChildLoadBalancerHandler({createSubchannel:Y.createSubchannel.bind(Y),requestReresolution:()=>{if(this.backoffTimeout.isRunning())l7("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0;else this.updateResolution()},updateState:(Q,U,Z)=>{this.latestChildState=Q,this.latestChildPicker=U,this.latestChildErrorMessage=Z,this.updateState(Q,U,Z)},addChannelzChild:Y.addChannelzChild.bind(Y),removeChannelzChild:Y.removeChannelzChild.bind(Y)}),this.innerResolver=(0,p7.createResolver)($,this.handleResolverResult.bind(this),T);let J={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new SM.BackoffTimeout(()=>{if(this.continueResolving)this.updateResolution(),this.continueResolving=!1;else this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},J),this.backoffTimeout.unref()}handleResolverResult($,Y,T,q){var X,J;this.backoffTimeout.stop(),this.backoffTimeout.reset();let Q=!0,U=null;if(T===null)U=this.defaultServiceConfig;else if(T.ok)U=T.value;else if(this.previousServiceConfig!==null)U=this.previousServiceConfig;else Q=!1,this.handleResolutionFailure(T.error);if(U!==null){let Z=(X=U===null||U===void 0?void 0:U.loadBalancingConfig)!==null&&X!==void 0?X:[],K=(0,LM.selectLbConfigFromList)(Z,!0);if(K===null)Q=!1,this.handleResolutionFailure({code:TX.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new CM.Metadata});else Q=this.childLoadBalancer.updateAddressList($,K,Object.assign(Object.assign({},this.channelOptions),Y),q)}if(Q)this.onSuccessfulResolution(U,(J=Y[p7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&J!==void 0?J:mM(U));return Q}updateResolution(){if(this.innerResolver.updateResolution(),this.currentState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage);this.backoffTimeout.runOnce()}updateState($,Y,T){if(l7((0,vM.uriToString)(this.target)+" "+i0.ConnectivityState[this.currentState]+" -> "+i0.ConnectivityState[$]),$===i0.ConnectivityState.IDLE)Y=new CT.QueuePicker(this,Y);this.currentState=$,this.channelControlHelper.updateState($,Y,T)}handleResolutionFailure($){if(this.latestChildState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.TRANSIENT_FAILURE,new CT.UnavailablePicker($),$.details),this.onFailedResolution($)}exitIdle(){if(this.currentState===i0.ConnectivityState.IDLE||this.currentState===i0.ConnectivityState.TRANSIENT_FAILURE)if(this.backoffTimeout.isRunning())this.continueResolving=!0;else this.updateResolution();this.childLoadBalancer.exitIdle()}updateAddressList($,Y){throw Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=i0.ConnectivityState.IDLE,this.latestChildPicker=new CT.QueuePicker(this),this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}}i7.ResolvingLoadBalancer=n7});var t7=M((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});o7.recognizedOptions=void 0;o7.channelOptionsEqual=fM;o7.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function fM($,Y){let T=Object.keys($).sort(),q=Object.keys(Y).sort();if(T.length!==q.length)return!1;for(let X=0;X<T.length;X+=1){if(T[X]!==q[X])return!1;if($[T[X]]!==Y[q[X]])return!1}return!0}});var r0=M((qZ)=>{Object.defineProperty(qZ,"__esModule",{value:!0});qZ.EndpointMap=void 0;qZ.isTcpSubchannelAddress=jT;qZ.subchannelAddressEqual=n8;qZ.subchannelAddressToString=$Z;qZ.stringToSubchannelAddress=dM;qZ.endpointEqual=cM;qZ.endpointToString=pM;qZ.endpointHasAddress=YZ;var e7=s("net");function jT($){return"port"in $}function n8($,Y){if(!$&&!Y)return!0;if(!$||!Y)return!1;if(jT($))return jT(Y)&&$.host===Y.host&&$.port===Y.port;else return!jT(Y)&&$.path===Y.path}function $Z($){if(jT($))if((0,e7.isIPv6)($.host))return"["+$.host+"]:"+$.port;else return $.host+":"+$.port;else return $.path}var uM=443;function dM($,Y){if((0,e7.isIP)($))return{host:$,port:Y!==null&&Y!==void 0?Y:uM};else return{path:$}}function cM($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let T=0;T<$.addresses.length;T++)if(!n8($.addresses[T],Y.addresses[T]))return!1;return!0}function pM($){return"["+$.addresses.map($Z).join(", ")+"]"}function YZ($,Y){for(let T of $.addresses)if(n8(T,Y))return!0;return!1}function yT($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let T of $.addresses){let q=!1;for(let X of Y.addresses)if(n8(T,X)){q=!0;break}if(!q)return!1}return!0}class TZ{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress($){for(let Y of this.map)if(YZ(Y.key,$))return Y.value;return}deleteMissing($){let Y=[];for(let T of this.map){let q=!1;for(let X of $)if(yT(X,T.key))q=!0;if(!q)Y.push(T.value),this.map.delete(T)}return Y}get($){for(let Y of this.map)if(yT($,Y.key))return Y.value;return}set($,Y){for(let T of this.map)if(yT($,T.key)){T.value=Y;return}this.map.add({key:$,value:Y})}delete($){for(let Y of this.map)if(yT($,Y.key)){this.map.delete(Y);return}}has($){for(let Y of this.map)if(yT($,Y.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let $ of this.map)yield $.key}*values(){for(let $ of this.map)yield $.value}*entries(){for(let $ of this.map)yield[$.key,$.value]}}qZ.EndpointMap=TZ});var EZ=M((GZ)=>{Object.defineProperty(GZ,"t",{value:!0});class qX{constructor($,Y,T=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=$,this.l=Y,this.p=T}I(){let $=this,Y=$.o.o===$;if(Y&&$.p===1)$=$.h;else if($.i){$=$.i;while($.h)$=$.h}else{if(Y)return $.o;let T=$.o;while(T.i===$)$=T,T=$.o;$=T}return $}B(){let $=this;if($.h){$=$.h;while($.i)$=$.i;return $}else{let Y=$.o;while(Y.h===$)$=Y,Y=$.o;if($.h!==Y)return Y;else return $}}_(){let $=this.o,Y=this.h,T=Y.i;if($.o===this)$.o=Y;else if($.i===this)$.i=Y;else $.h=Y;if(Y.o=$,Y.i=this,this.o=Y,this.h=T,T)T.o=this;return Y}g(){let $=this.o,Y=this.i,T=Y.h;if($.o===this)$.o=Y;else if($.i===this)$.i=Y;else $.h=Y;if(Y.o=$,Y.h=this,this.o=Y,this.i=T,T)T.o=this;return Y}}class JZ extends qX{constructor(){super(...arguments);this.M=1}_(){let $=super._();return this.O(),$.O(),$}g(){let $=super.g();return this.O(),$.O(),$}O(){if(this.M=1,this.i)this.M+=this.i.M;if(this.h)this.M+=this.h.M}}class QZ{constructor($=0){this.iteratorType=$}equals($){return this.T===$.T}}class UZ{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}}class ZZ extends UZ{}function p$(){throw RangeError("Iterator access denied!")}class KZ extends ZZ{constructor($=function(T,q){if(T<q)return-1;if(T>q)return 1;return 0},Y=!1){super();this.v=void 0,this.A=$,this.enableIndex=Y,this.N=Y?JZ:qX,this.C=new this.N}R($,Y){let T=this.C;while($){let q=this.A($.u,Y);if(q<0)$=$.h;else if(q>0)T=$,$=$.i;else return $}return T}K($,Y){let T=this.C;while($)if(this.A($.u,Y)<=0)$=$.h;else T=$,$=$.i;return T}L($,Y){let T=this.C;while($){let q=this.A($.u,Y);if(q<0)T=$,$=$.h;else if(q>0)$=$.i;else return $}return T}k($,Y){let T=this.C;while($)if(this.A($.u,Y)<0)T=$,$=$.h;else $=$.i;return T}P($){while(!0){let Y=$.o;if(Y===this.C)return;if($.p===1){$.p=0;return}if($===Y.i){let T=Y.h;if(T.p===1)if(T.p=0,Y.p=1,Y===this.v)this.v=Y._();else Y._();else if(T.h&&T.h.p===1){if(T.p=Y.p,Y.p=0,T.h.p=0,Y===this.v)this.v=Y._();else Y._();return}else if(T.i&&T.i.p===1)T.p=1,T.i.p=0,T.g();else T.p=1,$=Y}else{let T=Y.i;if(T.p===1)if(T.p=0,Y.p=1,Y===this.v)this.v=Y.g();else Y.g();else if(T.i&&T.i.p===1){if(T.p=Y.p,Y.p=0,T.i.p=0,Y===this.v)this.v=Y.g();else Y.g();return}else if(T.h&&T.h.p===1)T.p=1,T.h.p=0,T._();else T.p=1,$=Y}}}S($){if(this.m===1){this.clear();return}let Y=$;while(Y.i||Y.h){if(Y.h){Y=Y.h;while(Y.i)Y=Y.i}else Y=Y.i;let q=$.u;$.u=Y.u,Y.u=q;let X=$.l;$.l=Y.l,Y.l=X,$=Y}if(this.C.i===Y)this.C.i=Y.o;else if(this.C.h===Y)this.C.h=Y.o;this.P(Y);let T=Y.o;if(Y===T.i)T.i=void 0;else T.h=void 0;if(this.m-=1,this.v.p=0,this.enableIndex)while(T!==this.C)T.M-=1,T=T.o}U($){let Y=typeof $==="number"?$:void 0,T=typeof $==="function"?$:void 0,q=typeof $>"u"?[]:void 0,X=0,J=this.v,Q=[];while(Q.length||J)if(J)Q.push(J),J=J.i;else{if(J=Q.pop(),X===Y)return J;q&&q.push(J),T&&T(J,X,this),X+=1,J=J.h}return q}j($){while(!0){let Y=$.o;if(Y.p===0)return;let T=Y.o;if(Y===T.i){let q=T.h;if(q&&q.p===1){if(q.p=Y.p=0,T===this.v)return;T.p=1,$=T;continue}else if($===Y.h){if($.p=0,$.i)$.i.o=Y;if($.h)$.h.o=T;if(Y.h=$.i,T.i=$.h,$.i=Y,$.h=T,T===this.v)this.v=$,this.C.o=$;else{let X=T.o;if(X.i===T)X.i=$;else X.h=$}$.o=T.o,Y.o=$,T.o=$,T.p=1}else{if(Y.p=0,T===this.v)this.v=T.g();else T.g();T.p=1;return}}else{let q=T.i;if(q&&q.p===1){if(q.p=Y.p=0,T===this.v)return;T.p=1,$=T;continue}else if($===Y.i){if($.p=0,$.i)$.i.o=T;if($.h)$.h.o=Y;if(T.h=$.i,Y.i=$.h,$.i=T,$.h=Y,T===this.v)this.v=$,this.C.o=$;else{let X=T.o;if(X.i===T)X.i=$;else X.h=$}$.o=T.o,Y.o=$,T.o=$,T.p=1}else{if(Y.p=0,T===this.v)this.v=T._();else T._();T.p=1;return}}if(this.enableIndex)Y.O(),T.O(),$.O();return}}q($,Y,T){if(this.v===void 0)return this.m+=1,this.v=new this.N($,Y,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let q,X=this.C.i,J=this.A(X.u,$);if(J===0)return X.l=Y,this.m;else if(J>0)X.i=new this.N($,Y),X.i.o=X,q=X.i,this.C.i=q;else{let Q=this.C.h,U=this.A(Q.u,$);if(U===0)return Q.l=Y,this.m;else if(U<0)Q.h=new this.N($,Y),Q.h.o=Q,q=Q.h,this.C.h=q;else{if(T!==void 0){let Z=T.T;if(Z!==this.C){let K=this.A(Z.u,$);if(K===0)return Z.l=Y,this.m;else if(K>0){let A=Z.I(),W=this.A(A.u,$);if(W===0)return A.l=Y,this.m;else if(W<0)if(q=new this.N($,Y),A.h===void 0)A.h=q,q.o=A;else Z.i=q,q.o=Z}}}if(q===void 0){q=this.v;while(!0){let Z=this.A(q.u,$);if(Z>0){if(q.i===void 0){q.i=new this.N($,Y),q.i.o=q,q=q.i;break}q=q.i}else if(Z<0){if(q.h===void 0){q.h=new this.N($,Y),q.h.o=q,q=q.h;break}q=q.h}else return q.l=Y,this.m}}}}if(this.enableIndex){let Q=q.o;while(Q!==this.C)Q.M+=1,Q=Q.o}return this.j(q),this.m+=1,this.m}H($,Y){while($){let T=this.A($.u,Y);if(T<0)$=$.h;else if(T>0)$=$.i;else return $}return $||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator($,Y){let T=$.T;if(T===this.C)p$();if(this.m===1)return T.u=Y,!0;let q=T.B().u;if(T===this.C.i){if(this.A(q,Y)>0)return T.u=Y,!0;return!1}let X=T.I().u;if(T===this.C.h){if(this.A(X,Y)<0)return T.u=Y,!0;return!1}if(this.A(X,Y)>=0||this.A(q,Y)<=0)return!1;return T.u=Y,!0}eraseElementByPos($){if($<0||$>this.m-1)throw RangeError();let Y=this.U($);return this.S(Y),this.m}eraseElementByKey($){if(this.m===0)return!1;let Y=this.H(this.v,$);if(Y===this.C)return!1;return this.S(Y),!0}eraseElementByIterator($){let Y=$.T;if(Y===this.C)p$();let T=Y.h===void 0;if($.iteratorType===0){if(T)$.next()}else if(!T||Y.i===void 0)$.next();return this.S(Y),$}getHeight(){if(this.m===0)return 0;function $(Y){if(!Y)return 0;return Math.max($(Y.i),$(Y.h))+1}return $(this.v)}}class AZ extends QZ{constructor($,Y,T){super(T);if(this.T=$,this.C=Y,this.iteratorType===0)this.pre=function(){if(this.T===this.C.i)p$();return this.T=this.T.I(),this},this.next=function(){if(this.T===this.C)p$();return this.T=this.T.B(),this};else this.pre=function(){if(this.T===this.C.h)p$();return this.T=this.T.B(),this},this.next=function(){if(this.T===this.C)p$();return this.T=this.T.I(),this}}get index(){let $=this.T,Y=this.C.o;if($===this.C){if(Y)return Y.M-1;return 0}let T=0;if($.i)T+=$.i.M;while($!==Y){let q=$.o;if($===q.h){if(T+=1,q.i)T+=q.i.M}$=q}return T}isAccessible(){return this.T!==this.C}}class R1 extends AZ{constructor($,Y,T,q){super($,Y,q);this.container=T}get pointer(){if(this.T===this.C)p$();let $=this;return new Proxy([],{get(Y,T){if(T==="0")return $.T.u;else if(T==="1")return $.T.l;return Y[0]=$.T.u,Y[1]=$.T.l,Y[T]},set(Y,T,q){if(T!=="1")throw TypeError("prop must be 1");return $.T.l=q,!0}})}copy(){return new R1(this.T,this.C,this.container,this.iteratorType)}}class WZ extends KZ{constructor($=[],Y,T){super(Y,T);let q=this;$.forEach(function(X){q.setElement(X[0],X[1])})}begin(){return new R1(this.C.i||this.C,this.C,this)}end(){return new R1(this.C,this.C,this)}rBegin(){return new R1(this.C.h||this.C,this.C,this,1)}rEnd(){return new R1(this.C,this.C,this,1)}front(){if(this.m===0)return;let $=this.C.i;return[$.u,$.l]}back(){if(this.m===0)return;let $=this.C.h;return[$.u,$.l]}lowerBound($){let Y=this.R(this.v,$);return new R1(Y,this.C,this)}upperBound($){let Y=this.K(this.v,$);return new R1(Y,this.C,this)}reverseLowerBound($){let Y=this.L(this.v,$);return new R1(Y,this.C,this)}reverseUpperBound($){let Y=this.k(this.v,$);return new R1(Y,this.C,this)}forEach($){this.U(function(Y,T,q){$([Y.u,Y.l],T,q)})}setElement($,Y,T){return this.q($,Y,T)}getElementByPos($){if($<0||$>this.m-1)throw RangeError();let Y=this.U($);return[Y.u,Y.l]}find($){let Y=this.H(this.v,$);return new R1(Y,this.C,this)}getElementByKey($){return this.H(this.v,$).l}union($){let Y=this;return $.forEach(function(T){Y.setElement(T[0],T[1])}),this.m}*[Symbol.iterator](){let $=this.m,Y=this.U();for(let T=0;T<$;++T){let q=Y[T];yield[q.u,q.l]}}}GZ.OrderedMap=WZ});var i8=M((DZ)=>{Object.defineProperty(DZ,"__esModule",{value:!0});DZ.registerAdminService=eM;DZ.addAdminServicesToServer=$B;var VZ=[];function eM($,Y){VZ.push({getServiceDefinition:$,getHandlers:Y})}function $B($){for(let{getServiceDefinition:Y,getHandlers:T}of VZ)$.addService(Y(),T())}});var BZ=M((IZ)=>{Object.defineProperty(IZ,"__esModule",{value:!0});IZ.ClientDuplexStreamImpl=IZ.ClientWritableStreamImpl=IZ.ClientReadableStreamImpl=IZ.ClientUnaryCallImpl=void 0;IZ.callErrorFromStatus=XB;var qB=s("events"),XX=s("stream"),vT=i();function XB($,Y){let T=`${$.code} ${vT.Status[$.code]}: ${$.details}`,X=`${Error(T).stack}
|
|
1
|
+
import{createRequire as ED}from"node:module";var QD=Object.create;var{getPrototypeOf:UD,defineProperty:cJ,getOwnPropertyNames:ZD}=Object;var KD=Object.prototype.hasOwnProperty;function AD($){return this[$]}var WD,GD,ZY=($,Y,T)=>{var q=$!=null&&typeof $==="object";if(q){var X=Y?WD??=new WeakMap:GD??=new WeakMap,J=X.get($);if(J)return J}T=$!=null?QD(UD($)):{};let Q=Y||!$||!$.__esModule?cJ(T,"default",{value:$,enumerable:!0}):T;for(let U of ZD($))if(!KD.call(Q,U))cJ(Q,U,{get:AD.bind($,U),enumerable:!0});if(q)X.set($,Q);return Q};var B=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var s=ED(import.meta.url);var i=B((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});U7.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=U7.DEFAULT_MAX_SEND_MESSAGE_LENGTH=U7.Propagate=U7.LogVerbosity=U7.Status=void 0;var X7;(function($){$[$.OK=0]="OK",$[$.CANCELLED=1]="CANCELLED",$[$.UNKNOWN=2]="UNKNOWN",$[$.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",$[$.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",$[$.NOT_FOUND=5]="NOT_FOUND",$[$.ALREADY_EXISTS=6]="ALREADY_EXISTS",$[$.PERMISSION_DENIED=7]="PERMISSION_DENIED",$[$.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",$[$.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",$[$.ABORTED=10]="ABORTED",$[$.OUT_OF_RANGE=11]="OUT_OF_RANGE",$[$.UNIMPLEMENTED=12]="UNIMPLEMENTED",$[$.INTERNAL=13]="INTERNAL",$[$.UNAVAILABLE=14]="UNAVAILABLE",$[$.DATA_LOSS=15]="DATA_LOSS",$[$.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(X7||(U7.Status=X7={}));var J7;(function($){$[$.DEBUG=0]="DEBUG",$[$.INFO=1]="INFO",$[$.ERROR=2]="ERROR",$[$.NONE=3]="NONE"})(J7||(U7.LogVerbosity=J7={}));var Q7;(function($){$[$.DEADLINE=1]="DEADLINE",$[$.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",$[$.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",$[$.CANCELLATION=8]="CANCELLATION",$[$.DEFAULTS=65535]="DEFAULTS"})(Q7||(U7.Propagate=Q7={}));U7.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;U7.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4194304});var f4=B((m_,kz)=>{kz.exports={name:"@grpc/grpc-js",version:"1.14.3",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var U0=B((W7)=>{var b4,u4,d4,c4;Object.defineProperty(W7,"__esModule",{value:!0});W7.log=W7.setLoggerVerbosity=W7.setLogger=W7.getLogger=void 0;W7.trace=lz;W7.isTracerEnabled=A7;var z$=i(),hz=s("process"),_z=f4().version,gz={error:($,...Y)=>{console.error("E "+$,...Y)},info:($,...Y)=>{console.error("I "+$,...Y)},debug:($,...Y)=>{console.error("D "+$,...Y)}},c$=gz,MY=z$.LogVerbosity.ERROR,mz=(u4=(b4=process.env.GRPC_NODE_VERBOSITY)!==null&&b4!==void 0?b4:process.env.GRPC_VERBOSITY)!==null&&u4!==void 0?u4:"";switch(mz.toUpperCase()){case"DEBUG":MY=z$.LogVerbosity.DEBUG;break;case"INFO":MY=z$.LogVerbosity.INFO;break;case"ERROR":MY=z$.LogVerbosity.ERROR;break;case"NONE":MY=z$.LogVerbosity.NONE;break;default:}var fz=()=>{return c$};W7.getLogger=fz;var bz=($)=>{c$=$};W7.setLogger=bz;var uz=($)=>{MY=$};W7.setLoggerVerbosity=uz;var dz=($,...Y)=>{let T;if($>=MY){switch($){case z$.LogVerbosity.DEBUG:T=c$.debug;break;case z$.LogVerbosity.INFO:T=c$.info;break;case z$.LogVerbosity.ERROR:T=c$.error;break}if(!T)T=c$.error;if(T)T.bind(c$)(...Y)}};W7.log=dz;var cz=(c4=(d4=process.env.GRPC_NODE_TRACE)!==null&&d4!==void 0?d4:process.env.GRPC_TRACE)!==null&&c4!==void 0?c4:"",p4=new Set,K7=new Set;for(let $ of cz.split(","))if($.startsWith("-"))K7.add($.substring(1));else p4.add($);var pz=p4.has("all");function lz($,Y,T){if(A7(Y))W7.log($,new Date().toISOString()+" | v"+_z+" "+hz.pid+" | "+Y+" | "+T)}function A7($){return!K7.has($)&&(pz||p4.has($))}});var k8=B((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});G7.getErrorMessage=sz;G7.getErrorCode=tz;function sz($){if($ instanceof Error)return $.message;else return String($)}function tz($){if(typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="number")return $.code;else return null}});var P0=B((D7)=>{Object.defineProperty(D7,"__esModule",{value:!0});D7.Metadata=void 0;var YI=U0(),TI=i(),qI=k8(),XI=/^[:0-9a-z_.-]+$/,JI=/^[ -~]*$/;function QI($){return XI.test($)}function UI($){return JI.test($)}function V7($){return $.endsWith("-bin")}function ZI($){return!$.startsWith("grpc-")}function h8($){return $.toLowerCase()}function E7($,Y){if(!QI($))throw Error('Metadata key "'+$+'" contains illegal characters');if(Y!==null&&Y!==void 0)if(V7($)){if(!Buffer.isBuffer(Y))throw Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(Y))throw Error("keys that don't end with '-bin' must have String values");if(!UI(Y))throw Error('Metadata string value "'+Y+'" contains illegal characters')}}class _8{constructor($={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=$}set($,Y){$=h8($),E7($,Y),this.internalRepr.set($,[Y])}add($,Y){$=h8($),E7($,Y);let T=this.internalRepr.get($);if(T===void 0)this.internalRepr.set($,[Y]);else T.push(Y)}remove($){$=h8($),this.internalRepr.delete($)}get($){return $=h8($),this.internalRepr.get($)||[]}getMap(){let $={};for(let[Y,T]of this.internalRepr)if(T.length>0){let q=T[0];$[Y]=Buffer.isBuffer(q)?Buffer.from(q):q}return $}clone(){let $=new _8(this.options),Y=$.internalRepr;for(let[T,q]of this.internalRepr){let X=q.map((J)=>{if(Buffer.isBuffer(J))return Buffer.from(J);else return J});Y.set(T,X)}return $}merge($){for(let[Y,T]of $.internalRepr){let q=(this.internalRepr.get(Y)||[]).concat(T);this.internalRepr.set(Y,q)}}setOptions($){this.options=$}getOptions(){return this.options}toHttp2Headers(){let $={};for(let[Y,T]of this.internalRepr){if(Y.startsWith(":"))continue;$[Y]=T.map(KI)}return $}toJSON(){let $={};for(let[Y,T]of this.internalRepr)$[Y]=T;return $}setOpaque($,Y){this.opaqueData.set($,Y)}getOpaque($){return this.opaqueData.get($)}static fromHttp2Headers($){let Y=new _8;for(let T of Object.keys($)){if(T.charAt(0)===":")continue;let q=$[T];try{if(V7(T)){if(Array.isArray(q))q.forEach((X)=>{Y.add(T,Buffer.from(X,"base64"))});else if(q!==void 0)if(ZI(T))q.split(",").forEach((X)=>{Y.add(T,Buffer.from(X.trim(),"base64"))});else Y.add(T,Buffer.from(q,"base64"))}else if(Array.isArray(q))q.forEach((X)=>{Y.add(T,X)});else if(q!==void 0)Y.add(T,q)}catch(X){let J=`Failed to add metadata entry ${T}: ${q}. ${(0,qI.getErrorMessage)(X)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,YI.log)(TI.LogVerbosity.ERROR,J)}}return Y}}D7.Metadata=_8;var KI=($)=>{return Buffer.isBuffer($)?$.toString("base64"):$}});var m8=B((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});N7.CallCredentials=void 0;var n4=P0();function AI($){return"getRequestHeaders"in $&&typeof $.getRequestHeaders==="function"}class BY{static createFromMetadataGenerator($){return new i4($)}static createFromGoogleCredential($){return BY.createFromMetadataGenerator((Y,T)=>{let q;if(AI($))q=$.getRequestHeaders(Y.service_url);else q=new Promise((X,J)=>{$.getRequestMetadata(Y.service_url,(Q,U)=>{if(Q){J(Q);return}if(!U){J(Error("Headers not set by metadata plugin"));return}X(U)})});q.then((X)=>{let J=new n4.Metadata;for(let Q of Object.keys(X))J.add(Q,X[Q]);T(null,J)},(X)=>{T(X)})})}static createEmpty(){return new r4}}N7.CallCredentials=BY;class g8 extends BY{constructor($){super();this.creds=$}async generateMetadata($){let Y=new n4.Metadata,T=await Promise.all(this.creds.map((q)=>q.generateMetadata($)));for(let q of T)Y.merge(q);return Y}compose($){return new g8(this.creds.concat([$]))}_equals($){if(this===$)return!0;if($ instanceof g8)return this.creds.every((Y,T)=>Y._equals($.creds[T]));else return!1}}class i4 extends BY{constructor($){super();this.metadataGenerator=$}generateMetadata($){return new Promise((Y,T)=>{this.metadataGenerator($,(q,X)=>{if(X!==void 0)Y(X);else T(q)})})}compose($){return new g8([this,$])}_equals($){if(this===$)return!0;if($ instanceof i4)return this.metadataGenerator===$.metadataGenerator;else return!1}}class r4 extends BY{generateMetadata($){return Promise.resolve(new n4.Metadata)}compose($){return $}_equals($){return $ instanceof r4}}});var o4=B((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.CIPHER_SUITES=void 0;I7.getDefaultRootsData=GI;var WI=s("fs");I7.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var z7=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,a4=null;function GI(){if(z7){if(a4===null)a4=WI.readFileSync(z7);return a4}return null}});var p0=B((R7)=>{Object.defineProperty(R7,"__esModule",{value:!0});R7.parseUri=DI;R7.splitHostPort=FI;R7.combineHostPort=NI;R7.uriToString=HI;var VI=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function DI($){let Y=VI.exec($);if(Y===null)return null;return{scheme:Y[1],authority:Y[2],path:Y[3]}}var B7=/^\d+$/;function FI($){if($.startsWith("[")){let Y=$.indexOf("]");if(Y===-1)return null;let T=$.substring(1,Y);if(T.indexOf(":")===-1)return null;if($.length>Y+1)if($[Y+1]===":"){let q=$.substring(Y+2);if(B7.test(q))return{host:T,port:+q};else return null}else return null;else return{host:T}}else{let Y=$.split(":");if(Y.length===2)if(B7.test(Y[1]))return{host:Y[0],port:+Y[1]};else return null;else return{host:$}}}function NI($){if($.port===void 0)return $.host;else if($.host.includes(":"))return`[${$.host}]:${$.port}`;else return`${$.host}:${$.port}`}function HI($){let Y="";if($.scheme!==void 0)Y+=$.scheme+":";if($.authority!==void 0)Y+="//"+$.authority+"/";return Y+=$.path,Y}});var B1=B((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});O7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;O7.registerResolver=RI;O7.registerDefaultScheme=OI;O7.createResolver=PI;O7.getDefaultAuthority=LI;O7.mapUriDefaultScheme=wI;var t4=p0();O7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var RY={},s4=null;function RI($,Y){RY[$]=Y}function OI($){s4=$}function PI($,Y,T){if($.scheme!==void 0&&$.scheme in RY)return new RY[$.scheme]($,Y,T);else throw Error(`No resolver could be created for target ${(0,t4.uriToString)($)}`)}function LI($){if($.scheme!==void 0&&$.scheme in RY)return RY[$.scheme].getDefaultAuthority($);else throw Error(`Invalid target ${(0,t4.uriToString)($)}`)}function wI($){if($.scheme===void 0||!($.scheme in RY))if(s4!==null)return{scheme:s4,authority:void 0,path:(0,t4.uriToString)($)};else return null;return $}});var PY=B((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});C7.ChannelCredentials=void 0;C7.createCertificateProviderChannelCredentials=_I;var w6=s("tls"),u8=m8(),$X=o4(),L7=p0(),xI=B1(),kI=U0(),hI=i();function e4($,Y){if($&&!($ instanceof Buffer))throw TypeError(`${Y}, if provided, must be a Buffer.`)}class OY{compose($){return new b8(this,$)}static createSsl($,Y,T,q){var X;if(e4($,"Root certificate"),e4(Y,"Private key"),e4(T,"Certificate chain"),Y&&!T)throw Error("Private key must be given with accompanying certificate chain");if(!Y&&T)throw Error("Certificate chain must be given with accompanying private key");let J=(0,w6.createSecureContext)({ca:(X=$!==null&&$!==void 0?$:(0,$X.getDefaultRootsData)())!==null&&X!==void 0?X:void 0,key:Y!==null&&Y!==void 0?Y:void 0,cert:T!==null&&T!==void 0?T:void 0,ciphers:$X.CIPHER_SUITES});return new f8(J,q!==null&&q!==void 0?q:{})}static createFromSecureContext($,Y){return new f8($,Y!==null&&Y!==void 0?Y:{})}static createInsecure(){return new YX}}C7.ChannelCredentials=OY;class YX extends OY{constructor(){super()}compose($){throw Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals($){return $ instanceof YX}_createSecureConnector($,Y,T){return{connect(q){return Promise.resolve({socket:q,secure:!1})},waitForReady:()=>{return Promise.resolve()},getCallCredentials:()=>{return T!==null&&T!==void 0?T:u8.CallCredentials.createEmpty()},destroy(){}}}}function w7($,Y,T,q){var X,J;let Q={secureContext:$},U=T;if("grpc.http_connect_target"in q){let W=(0,L7.parseUri)(q["grpc.http_connect_target"]);if(W)U=W}let Z=(0,xI.getDefaultAuthority)(U),K=(0,L7.splitHostPort)(Z),A=(X=K===null||K===void 0?void 0:K.host)!==null&&X!==void 0?X:Z;if(Q.host=A,Y.checkServerIdentity)Q.checkServerIdentity=Y.checkServerIdentity;if(Y.rejectUnauthorized!==void 0)Q.rejectUnauthorized=Y.rejectUnauthorized;if(Q.ALPNProtocols=["h2"],q["grpc.ssl_target_name_override"]){let W=q["grpc.ssl_target_name_override"],E=(J=Q.checkServerIdentity)!==null&&J!==void 0?J:w6.checkServerIdentity;Q.checkServerIdentity=(V,F)=>{return E(W,F)},Q.servername=W}else Q.servername=A;if(q["grpc-node.tls_enable_trace"])Q.enableTrace=!0;return Q}class S7{constructor($,Y){this.connectionOptions=$,this.callCredentials=Y}connect($){let Y=Object.assign({socket:$},this.connectionOptions);return new Promise((T,q)=>{let X=(0,w6.connect)(Y,()=>{var J;if(((J=this.connectionOptions.rejectUnauthorized)!==null&&J!==void 0?J:!0)&&!X.authorized){q(X.authorizationError);return}T({socket:X,secure:!0})});X.on("error",(J)=>{q(J)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}}class f8 extends OY{constructor($,Y){super();this.secureContext=$,this.verifyOptions=Y}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof f8)return this.secureContext===$.secureContext&&this.verifyOptions.checkServerIdentity===$.verifyOptions.checkServerIdentity;else return!1}_createSecureConnector($,Y,T){let q=w7(this.secureContext,this.verifyOptions,$,Y);return new S7(q,T!==null&&T!==void 0?T:u8.CallCredentials.createEmpty())}}class L6 extends OY{constructor($,Y,T){super();this.caCertificateProvider=$,this.identityCertificateProvider=Y,this.verifyOptions=T,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals($){var Y,T;if(this===$)return!0;if($ instanceof L6)return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&((Y=this.verifyOptions)===null||Y===void 0?void 0:Y.checkServerIdentity)===((T=$.verifyOptions)===null||T===void 0?void 0:T.checkServerIdentity);else return!1}ref(){var $;if(this.refcount===0)this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),($=this.identityCertificateProvider)===null||$===void 0||$.addIdentityCertificateListener(this.identityCertificateUpdateListener);this.refcount+=1}unref(){var $;if(this.refcount-=1,this.refcount===0)this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),($=this.identityCertificateProvider)===null||$===void 0||$.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_createSecureConnector($,Y,T){return this.ref(),new L6.SecureConnectorImpl(this,$,Y,T!==null&&T!==void 0?T:u8.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let $ of this.secureContextWatchers)$(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate($){this.latestCaUpdate=$,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate($){this.latestIdentityUpdate=$,this.maybeUpdateWatchers()}hasReceivedUpdates(){if(this.latestCaUpdate===void 0)return!1;if(this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)return!1;return!0}getSecureContext(){if(this.hasReceivedUpdates())return Promise.resolve(this.getLatestSecureContext());else return new Promise(($)=>{this.secureContextWatchers.push($)})}getLatestSecureContext(){var $,Y;if(!this.latestCaUpdate)return null;if(this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,w6.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:($=this.latestIdentityUpdate)===null||$===void 0?void 0:$.privateKey,cert:(Y=this.latestIdentityUpdate)===null||Y===void 0?void 0:Y.certificate,ciphers:$X.CIPHER_SUITES})}catch(T){return(0,kI.log)(hI.LogVerbosity.ERROR,"Failed to createSecureContext with error "+T.message),null}}}L6.SecureConnectorImpl=class{constructor($,Y,T,q){this.parent=$,this.channelTarget=Y,this.options=T,this.callCredentials=q}connect($){return new Promise((Y,T)=>{let q=this.parent.getLatestSecureContext();if(!q){T(Error("Failed to load credentials"));return}if($.closed)T(Error("Socket closed while loading credentials"));let X=w7(q,this.parent.verifyOptions,this.channelTarget,this.options),J=Object.assign({socket:$},X),Q=()=>{T(Error("Socket closed"))},U=(K)=>{T(K)},Z=(0,w6.connect)(J,()=>{var K;if(Z.removeListener("close",Q),Z.removeListener("error",U),((K=this.parent.verifyOptions.rejectUnauthorized)!==null&&K!==void 0?K:!0)&&!Z.authorized){T(Z.authorizationError);return}Y({socket:Z,secure:!0})});Z.once("close",Q),Z.once("error",U)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function _I($,Y,T){return new L6($,Y,T!==null&&T!==void 0?T:{})}class b8 extends OY{constructor($,Y){super();if(this.channelCredentials=$,this.callCredentials=Y,!$._isSecure())throw Error("Cannot compose insecure credentials")}compose($){let Y=this.callCredentials.compose($);return new b8(this.channelCredentials,Y)}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof b8)return this.channelCredentials._equals($.channelCredentials)&&this.callCredentials._equals($.callCredentials);else return!1}_createSecureConnector($,Y,T){let q=this.callCredentials.compose(T!==null&&T!==void 0?T:u8.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector($,Y,q)}}});var M$=B((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});v7.createChildChannelControlHelper=bI;v7.registerLoadBalancerType=uI;v7.registerDefaultLoadBalancerType=dI;v7.createLoadBalancer=cI;v7.isLoadBalancerNameRegistered=pI;v7.parseLoadBalancingConfig=j7;v7.getDefaultConfig=lI;v7.selectLbConfigFromList=nI;var mI=U0(),fI=i();function bI($,Y){var T,q,X,J,Q,U,Z,K,A,W;return{createSubchannel:(q=(T=Y.createSubchannel)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:$.createSubchannel.bind($),updateState:(J=(X=Y.updateState)===null||X===void 0?void 0:X.bind(Y))!==null&&J!==void 0?J:$.updateState.bind($),requestReresolution:(U=(Q=Y.requestReresolution)===null||Q===void 0?void 0:Q.bind(Y))!==null&&U!==void 0?U:$.requestReresolution.bind($),addChannelzChild:(K=(Z=Y.addChannelzChild)===null||Z===void 0?void 0:Z.bind(Y))!==null&&K!==void 0?K:$.addChannelzChild.bind($),removeChannelzChild:(W=(A=Y.removeChannelzChild)===null||A===void 0?void 0:A.bind(Y))!==null&&W!==void 0?W:$.removeChannelzChild.bind($)}}var I$={},S6=null;function uI($,Y,T){I$[$]={LoadBalancer:Y,LoadBalancingConfig:T}}function dI($){S6=$}function cI($,Y){let T=$.getLoadBalancerName();if(T in I$)return new I$[T].LoadBalancer(Y);else return null}function pI($){return $ in I$}function j7($){let Y=Object.keys($);if(Y.length!==1)throw Error("Provided load balancing config has multiple conflicting entries");let T=Y[0];if(T in I$)try{return I$[T].LoadBalancingConfig.createFromJson($[T])}catch(q){throw Error(`${T}: ${q.message}`)}else throw Error(`Unrecognized load balancing config name ${T}`)}function lI(){if(!S6)throw Error("No default load balancer type registered");return new I$[S6].LoadBalancingConfig}function nI($,Y=!1){for(let T of $)try{return j7(T)}catch(q){(0,mI.log)(fI.LogVerbosity.DEBUG,"Config parsing failed with error",q.message);continue}if(Y)if(S6)return new I$[S6].LoadBalancingConfig;else return null;else return null}});var TX=B((h7)=>{Object.defineProperty(h7,"__esModule",{value:!0});h7.validateRetryThrottling=x7;h7.validateServiceConfig=k7;h7.extractAndSelectServiceConfig=AM;var YM=s("os"),d8=i(),c8=/^\d+(\.\d{1,9})?s$/,TM="node";function qM($){if("service"in $&&$.service!==""){if(typeof $.service!=="string")throw Error(`Invalid method config name: invalid service: expected type string, got ${typeof $.service}`);if("method"in $&&$.method!==""){if(typeof $.method!=="string")throw Error(`Invalid method config name: invalid method: expected type string, got ${typeof $.service}`);return{service:$.service,method:$.method}}else return{service:$.service}}else{if("method"in $&&$.method!==void 0)throw Error("Invalid method config name: method set with empty or unset service");return{}}}function XM($){if(!("maxAttempts"in $)||!Number.isInteger($.maxAttempts)||$.maxAttempts<2)throw Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in $)||typeof $.initialBackoff!=="string"||!c8.test($.initialBackoff))throw Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in $)||typeof $.maxBackoff!=="string"||!c8.test($.maxBackoff))throw Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in $)||typeof $.backoffMultiplier!=="number"||$.backoffMultiplier<=0)throw Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!(("retryableStatusCodes"in $)&&Array.isArray($.retryableStatusCodes)))throw Error("Invalid method config retry policy: retryableStatusCodes is required");if($.retryableStatusCodes.length===0)throw Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let Y of $.retryableStatusCodes)if(typeof Y==="number"){if(!Object.values(d8.Status).includes(Y))throw Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof Y==="string"){if(!Object.values(d8.Status).includes(Y.toUpperCase()))throw Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:$.maxAttempts,initialBackoff:$.initialBackoff,maxBackoff:$.maxBackoff,backoffMultiplier:$.backoffMultiplier,retryableStatusCodes:$.retryableStatusCodes}}function JM($){if(!("maxAttempts"in $)||!Number.isInteger($.maxAttempts)||$.maxAttempts<2)throw Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in $&&(typeof $.hedgingDelay!=="string"||!c8.test($.hedgingDelay)))throw Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in $&&Array.isArray($.nonFatalStatusCodes))for(let T of $.nonFatalStatusCodes)if(typeof T==="number"){if(!Object.values(d8.Status).includes(T))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof T==="string"){if(!Object.values(d8.Status).includes(T.toUpperCase()))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let Y={maxAttempts:$.maxAttempts};if($.hedgingDelay)Y.hedgingDelay=$.hedgingDelay;if($.nonFatalStatusCodes)Y.nonFatalStatusCodes=$.nonFatalStatusCodes;return Y}function QM($){var Y;let T={name:[]};if(!("name"in $)||!Array.isArray($.name))throw Error("Invalid method config: invalid name array");for(let q of $.name)T.name.push(qM(q));if("waitForReady"in $){if(typeof $.waitForReady!=="boolean")throw Error("Invalid method config: invalid waitForReady");T.waitForReady=$.waitForReady}if("timeout"in $)if(typeof $.timeout==="object"){if(!("seconds"in $.timeout)||typeof $.timeout.seconds!=="number")throw Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in $.timeout)||typeof $.timeout.nanos!=="number")throw Error("Invalid method config: invalid timeout.nanos");T.timeout=$.timeout}else if(typeof $.timeout==="string"&&c8.test($.timeout)){let q=$.timeout.substring(0,$.timeout.length-1).split(".");T.timeout={seconds:q[0]|0,nanos:((Y=q[1])!==null&&Y!==void 0?Y:0)|0}}else throw Error("Invalid method config: invalid timeout");if("maxRequestBytes"in $){if(typeof $.maxRequestBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");T.maxRequestBytes=$.maxRequestBytes}if("maxResponseBytes"in $){if(typeof $.maxResponseBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");T.maxResponseBytes=$.maxResponseBytes}if("retryPolicy"in $)if("hedgingPolicy"in $)throw Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");else T.retryPolicy=XM($.retryPolicy);else if("hedgingPolicy"in $)T.hedgingPolicy=JM($.hedgingPolicy);return T}function x7($){if(!("maxTokens"in $)||typeof $.maxTokens!=="number"||$.maxTokens<=0||$.maxTokens>1000)throw Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in $)||typeof $.tokenRatio!=="number"||$.tokenRatio<=0)throw Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+$.maxTokens.toFixed(3),tokenRatio:+$.tokenRatio.toFixed(3)}}function UM($){if(!(typeof $==="object"&&$!==null))throw Error(`Invalid loadBalancingConfig: unexpected type ${typeof $}`);let Y=Object.keys($);if(Y.length>1)throw Error(`Invalid loadBalancingConfig: unexpected multiple keys ${Y}`);if(Y.length===0)throw Error("Invalid loadBalancingConfig: load balancing policy name required");return{[Y[0]]:$[Y[0]]}}function k7($){let Y={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in $)if(typeof $.loadBalancingPolicy==="string")Y.loadBalancingPolicy=$.loadBalancingPolicy;else throw Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in $)if(Array.isArray($.loadBalancingConfig))for(let q of $.loadBalancingConfig)Y.loadBalancingConfig.push(UM(q));else throw Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in $){if(Array.isArray($.methodConfig))for(let q of $.methodConfig)Y.methodConfig.push(QM(q))}if("retryThrottling"in $)Y.retryThrottling=x7($.retryThrottling);let T=[];for(let q of Y.methodConfig)for(let X of q.name){for(let J of T)if(X.service===J.service&&X.method===J.method)throw Error(`Invalid service config: duplicate name ${X.service}/${X.method}`);T.push(X)}return Y}function ZM($){if(!("serviceConfig"in $))throw Error("Invalid service config choice: missing service config");let Y={serviceConfig:k7($.serviceConfig)};if("clientLanguage"in $)if(Array.isArray($.clientLanguage)){Y.clientLanguage=[];for(let q of $.clientLanguage)if(typeof q==="string")Y.clientLanguage.push(q);else throw Error("Invalid service config choice: invalid clientLanguage")}else throw Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in $)if(Array.isArray($.clientHostname)){Y.clientHostname=[];for(let q of $.clientHostname)if(typeof q==="string")Y.clientHostname.push(q);else throw Error("Invalid service config choice: invalid clientHostname")}else throw Error("Invalid service config choice: invalid clientHostname");if("percentage"in $)if(typeof $.percentage==="number"&&0<=$.percentage&&$.percentage<=100)Y.percentage=$.percentage;else throw Error("Invalid service config choice: invalid percentage");let T=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let q in $)if(!T.includes(q))throw Error(`Invalid service config choice: unexpected field ${q}`);return Y}function KM($,Y){if(!Array.isArray($))throw Error("Invalid service config list");for(let T of $){let q=ZM(T);if(typeof q.percentage==="number"&&Y>q.percentage)continue;if(Array.isArray(q.clientHostname)){let X=!1;for(let J of q.clientHostname)if(J===YM.hostname())X=!0;if(!X)continue}if(Array.isArray(q.clientLanguage)){let X=!1;for(let J of q.clientLanguage)if(J===TM)X=!0;if(!X)continue}return q.serviceConfig}throw Error("No matching service config found")}function AM($,Y){for(let T of $)if(T.length>0&&T[0].startsWith("grpc_config=")){let q=T.join("").substring(12),X=JSON.parse(q);return KM(X,Y)}return null}});var l0=B((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});g7.ConnectivityState=void 0;var _7;(function($){$[$.IDLE=0]="IDLE",$[$.CONNECTING=1]="CONNECTING",$[$.READY=2]="READY",$[$.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",$[$.SHUTDOWN=4]="SHUTDOWN"})(_7||(g7.ConnectivityState=_7={}))});var Y$=B((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});u7.QueuePicker=u7.UnavailablePicker=u7.PickResultType=void 0;var VM=P0(),DM=i(),p8;(function($){$[$.COMPLETE=0]="COMPLETE",$[$.QUEUE=1]="QUEUE",$[$.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",$[$.DROP=3]="DROP"})(p8||(u7.PickResultType=p8={}));class f7{constructor($){this.status=Object.assign({code:DM.Status.UNAVAILABLE,details:"No connection established",metadata:new VM.Metadata},$)}pick($){return{pickResultType:p8.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}}u7.UnavailablePicker=f7;class b7{constructor($,Y){this.loadBalancer=$,this.childPicker=Y,this.calledExitIdle=!1}pick($){if(!this.calledExitIdle)process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0;if(this.childPicker)return this.childPicker.pick($);else return{pickResultType:p8.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}}u7.QueuePicker=b7});var LY=B((c7)=>{Object.defineProperty(c7,"__esModule",{value:!0});c7.BackoffTimeout=void 0;var HM=i(),zM=U0(),IM="backoff",MM=1000,BM=1.6,RM=120000,OM=0.2;function PM($,Y){return Math.random()*(Y-$)+$}class l8{constructor($,Y){if(this.callback=$,this.initialDelay=MM,this.multiplier=BM,this.maxDelay=RM,this.jitter=OM,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=l8.getNextId(),Y){if(Y.initialDelay)this.initialDelay=Y.initialDelay;if(Y.multiplier)this.multiplier=Y.multiplier;if(Y.jitter)this.jitter=Y.jitter;if(Y.maxDelay)this.maxDelay=Y.maxDelay}this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace($){zM.trace(HM.LogVerbosity.DEBUG,IM,"{"+this.id+"} "+$)}runTimer($){var Y,T;if(this.trace("runTimer(delay="+$+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+$),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},$),!this.hasRef)(T=(Y=this.timerId).unref)===null||T===void 0||T.call(Y)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let $=Math.min(this.nextDelay*this.multiplier,this.maxDelay),Y=$*this.jitter;this.nextDelay=$+PM(-Y,Y)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let $=new Date,Y=this.startTime;if(Y.setMilliseconds(Y.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),$<Y)this.runTimer(Y.getTime()-$.getTime());else this.running=!1}}isRunning(){return this.running}ref(){var $,Y;this.hasRef=!0,(Y=($=this.timerId).ref)===null||Y===void 0||Y.call($)}unref(){var $,Y;this.hasRef=!1,(Y=($=this.timerId).unref)===null||Y===void 0||Y.call($)}getEndTime(){return this.endTime}}c7.BackoffTimeout=l8;l8.nextId=0});var n8=B((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});n7.ChildLoadBalancerHandler=void 0;var LM=M$(),wM=l0(),SM="child_load_balancer_helper";class l7{constructor($){this.channelControlHelper=$,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(Y){this.parent=Y,this.child=null}createSubchannel(Y,T){return this.parent.channelControlHelper.createSubchannel(Y,T)}updateState(Y,T,q){var X;if(this.calledByPendingChild()){if(Y===wM.ConnectivityState.CONNECTING)return;(X=this.parent.currentChild)===null||X===void 0||X.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(Y,T,q)}requestReresolution(){var Y;let T=(Y=this.parent.pendingChild)!==null&&Y!==void 0?Y:this.parent.currentChild;if(this.child===T)this.parent.channelControlHelper.requestReresolution()}setChild(Y){this.child=Y}addChannelzChild(Y){this.parent.channelControlHelper.addChannelzChild(Y)}removeChannelzChild(Y){this.parent.channelControlHelper.removeChannelzChild(Y)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance($,Y){return $.getLoadBalancerName()!==Y.getLoadBalancerName()}updateAddressList($,Y,T,q){let X;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,Y)){let J=new this.ChildPolicyHelper(this),Q=(0,LM.createLoadBalancer)(Y,J);if(J.setChild(Q),this.currentChild===null)this.currentChild=Q,X=this.currentChild;else{if(this.pendingChild)this.pendingChild.destroy();this.pendingChild=Q,X=this.pendingChild}}else if(this.pendingChild===null)X=this.currentChild;else X=this.pendingChild;return this.latestConfig=Y,X.updateAddressList($,Y,T,q)}exitIdle(){if(this.currentChild){if(this.currentChild.exitIdle(),this.pendingChild)this.pendingChild.exitIdle()}}resetBackoff(){if(this.currentChild){if(this.currentChild.resetBackoff(),this.pendingChild)this.pendingChild.resetBackoff()}}destroy(){if(this.currentChild)this.currentChild.destroy(),this.currentChild=null;if(this.pendingChild)this.pendingChild.destroy(),this.pendingChild=null}getTypeName(){return SM}}n7.ChildLoadBalancerHandler=l7});var e7=B((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});s7.ResolvingLoadBalancer=void 0;var CM=M$(),yM=TX(),i0=l0(),r7=B1(),C6=Y$(),jM=LY(),qX=i(),vM=P0(),xM=U0(),kM=i(),hM=p0(),_M=n8(),gM="resolving_load_balancer";function a7($){xM.trace(kM.LogVerbosity.DEBUG,gM,$)}var mM=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function fM($,Y,T,q){for(let X of T.name)switch(q){case"EMPTY":if(!X.service&&!X.method)return!0;break;case"SERVICE":if(X.service===$&&!X.method)return!0;break;case"SERVICE_AND_METHOD":if(X.service===$&&X.method===Y)return!0}return!1}function bM($,Y,T,q){for(let X of T)if(fM($,Y,X,q))return X;return null}function uM($){return{invoke(Y,T){var q,X;let J=Y.split("/").filter((Z)=>Z.length>0),Q=(q=J[0])!==null&&q!==void 0?q:"",U=(X=J[1])!==null&&X!==void 0?X:"";if($&&$.methodConfig)for(let Z of mM){let K=bM(Q,U,$.methodConfig,Z);if(K)return{methodConfig:K,pickInformation:{},status:qX.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:qX.Status.OK,dynamicFilterFactories:[]}},unref(){}}}class o7{constructor($,Y,T,q,X){if(this.target=$,this.channelControlHelper=Y,this.channelOptions=T,this.onSuccessfulResolution=q,this.onFailedResolution=X,this.latestChildState=i0.ConnectivityState.IDLE,this.latestChildPicker=new C6.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,T["grpc.service_config"])this.defaultServiceConfig=(0,yM.validateServiceConfig)(JSON.parse(T["grpc.service_config"]));else this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]};this.updateState(i0.ConnectivityState.IDLE,new C6.QueuePicker(this),null),this.childLoadBalancer=new _M.ChildLoadBalancerHandler({createSubchannel:Y.createSubchannel.bind(Y),requestReresolution:()=>{if(this.backoffTimeout.isRunning())a7("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0;else this.updateResolution()},updateState:(Q,U,Z)=>{this.latestChildState=Q,this.latestChildPicker=U,this.latestChildErrorMessage=Z,this.updateState(Q,U,Z)},addChannelzChild:Y.addChannelzChild.bind(Y),removeChannelzChild:Y.removeChannelzChild.bind(Y)}),this.innerResolver=(0,r7.createResolver)($,this.handleResolverResult.bind(this),T);let J={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new jM.BackoffTimeout(()=>{if(this.continueResolving)this.updateResolution(),this.continueResolving=!1;else this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},J),this.backoffTimeout.unref()}handleResolverResult($,Y,T,q){var X,J;this.backoffTimeout.stop(),this.backoffTimeout.reset();let Q=!0,U=null;if(T===null)U=this.defaultServiceConfig;else if(T.ok)U=T.value;else if(this.previousServiceConfig!==null)U=this.previousServiceConfig;else Q=!1,this.handleResolutionFailure(T.error);if(U!==null){let Z=(X=U===null||U===void 0?void 0:U.loadBalancingConfig)!==null&&X!==void 0?X:[],K=(0,CM.selectLbConfigFromList)(Z,!0);if(K===null)Q=!1,this.handleResolutionFailure({code:qX.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new vM.Metadata});else Q=this.childLoadBalancer.updateAddressList($,K,Object.assign(Object.assign({},this.channelOptions),Y),q)}if(Q)this.onSuccessfulResolution(U,(J=Y[r7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&J!==void 0?J:uM(U));return Q}updateResolution(){if(this.innerResolver.updateResolution(),this.currentState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage);this.backoffTimeout.runOnce()}updateState($,Y,T){if(a7((0,hM.uriToString)(this.target)+" "+i0.ConnectivityState[this.currentState]+" -> "+i0.ConnectivityState[$]),$===i0.ConnectivityState.IDLE)Y=new C6.QueuePicker(this,Y);this.currentState=$,this.channelControlHelper.updateState($,Y,T)}handleResolutionFailure($){if(this.latestChildState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.TRANSIENT_FAILURE,new C6.UnavailablePicker($),$.details),this.onFailedResolution($)}exitIdle(){if(this.currentState===i0.ConnectivityState.IDLE||this.currentState===i0.ConnectivityState.TRANSIENT_FAILURE)if(this.backoffTimeout.isRunning())this.continueResolving=!0;else this.updateResolution();this.childLoadBalancer.exitIdle()}updateAddressList($,Y){throw Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=i0.ConnectivityState.IDLE,this.latestChildPicker=new C6.QueuePicker(this),this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}}s7.ResolvingLoadBalancer=o7});var TZ=B(($Z)=>{Object.defineProperty($Z,"__esModule",{value:!0});$Z.recognizedOptions=void 0;$Z.channelOptionsEqual=dM;$Z.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function dM($,Y){let T=Object.keys($).sort(),q=Object.keys(Y).sort();if(T.length!==q.length)return!1;for(let X=0;X<T.length;X+=1){if(T[X]!==q[X])return!1;if($[T[X]]!==Y[q[X]])return!1}return!0}});var r0=B((UZ)=>{Object.defineProperty(UZ,"__esModule",{value:!0});UZ.EndpointMap=void 0;UZ.isTcpSubchannelAddress=j6;UZ.subchannelAddressEqual=i8;UZ.subchannelAddressToString=XZ;UZ.stringToSubchannelAddress=lM;UZ.endpointEqual=nM;UZ.endpointToString=iM;UZ.endpointHasAddress=JZ;var qZ=s("net");function j6($){return"port"in $}function i8($,Y){if(!$&&!Y)return!0;if(!$||!Y)return!1;if(j6($))return j6(Y)&&$.host===Y.host&&$.port===Y.port;else return!j6(Y)&&$.path===Y.path}function XZ($){if(j6($))if((0,qZ.isIPv6)($.host))return"["+$.host+"]:"+$.port;else return $.host+":"+$.port;else return $.path}var pM=443;function lM($,Y){if((0,qZ.isIP)($))return{host:$,port:Y!==null&&Y!==void 0?Y:pM};else return{path:$}}function nM($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let T=0;T<$.addresses.length;T++)if(!i8($.addresses[T],Y.addresses[T]))return!1;return!0}function iM($){return"["+$.addresses.map(XZ).join(", ")+"]"}function JZ($,Y){for(let T of $.addresses)if(i8(T,Y))return!0;return!1}function y6($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let T of $.addresses){let q=!1;for(let X of Y.addresses)if(i8(T,X)){q=!0;break}if(!q)return!1}return!0}class QZ{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress($){for(let Y of this.map)if(JZ(Y.key,$))return Y.value;return}deleteMissing($){let Y=[];for(let T of this.map){let q=!1;for(let X of $)if(y6(X,T.key))q=!0;if(!q)Y.push(T.value),this.map.delete(T)}return Y}get($){for(let Y of this.map)if(y6($,Y.key))return Y.value;return}set($,Y){for(let T of this.map)if(y6($,T.key)){T.value=Y;return}this.map.add({key:$,value:Y})}delete($){for(let Y of this.map)if(y6($,Y.key)){this.map.delete(Y);return}}has($){for(let Y of this.map)if(y6($,Y.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let $ of this.map)yield $.key}*values(){for(let $ of this.map)yield $.value}*entries(){for(let $ of this.map)yield[$.key,$.value]}}UZ.EndpointMap=QZ});var NZ=B((FZ)=>{Object.defineProperty(FZ,"t",{value:!0});class XX{constructor($,Y,T=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=$,this.l=Y,this.p=T}I(){let $=this,Y=$.o.o===$;if(Y&&$.p===1)$=$.h;else if($.i){$=$.i;while($.h)$=$.h}else{if(Y)return $.o;let T=$.o;while(T.i===$)$=T,T=$.o;$=T}return $}B(){let $=this;if($.h){$=$.h;while($.i)$=$.i;return $}else{let Y=$.o;while(Y.h===$)$=Y,Y=$.o;if($.h!==Y)return Y;else return $}}_(){let $=this.o,Y=this.h,T=Y.i;if($.o===this)$.o=Y;else if($.i===this)$.i=Y;else $.h=Y;if(Y.o=$,Y.i=this,this.o=Y,this.h=T,T)T.o=this;return Y}g(){let $=this.o,Y=this.i,T=Y.h;if($.o===this)$.o=Y;else if($.i===this)$.i=Y;else $.h=Y;if(Y.o=$,Y.h=this,this.o=Y,this.i=T,T)T.o=this;return Y}}class KZ extends XX{constructor(){super(...arguments);this.M=1}_(){let $=super._();return this.O(),$.O(),$}g(){let $=super.g();return this.O(),$.O(),$}O(){if(this.M=1,this.i)this.M+=this.i.M;if(this.h)this.M+=this.h.M}}class AZ{constructor($=0){this.iteratorType=$}equals($){return this.T===$.T}}class WZ{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}}class GZ extends WZ{}function p$(){throw RangeError("Iterator access denied!")}class EZ extends GZ{constructor($=function(T,q){if(T<q)return-1;if(T>q)return 1;return 0},Y=!1){super();this.v=void 0,this.A=$,this.enableIndex=Y,this.N=Y?KZ:XX,this.C=new this.N}R($,Y){let T=this.C;while($){let q=this.A($.u,Y);if(q<0)$=$.h;else if(q>0)T=$,$=$.i;else return $}return T}K($,Y){let T=this.C;while($)if(this.A($.u,Y)<=0)$=$.h;else T=$,$=$.i;return T}L($,Y){let T=this.C;while($){let q=this.A($.u,Y);if(q<0)T=$,$=$.h;else if(q>0)$=$.i;else return $}return T}k($,Y){let T=this.C;while($)if(this.A($.u,Y)<0)T=$,$=$.h;else $=$.i;return T}P($){while(!0){let Y=$.o;if(Y===this.C)return;if($.p===1){$.p=0;return}if($===Y.i){let T=Y.h;if(T.p===1)if(T.p=0,Y.p=1,Y===this.v)this.v=Y._();else Y._();else if(T.h&&T.h.p===1){if(T.p=Y.p,Y.p=0,T.h.p=0,Y===this.v)this.v=Y._();else Y._();return}else if(T.i&&T.i.p===1)T.p=1,T.i.p=0,T.g();else T.p=1,$=Y}else{let T=Y.i;if(T.p===1)if(T.p=0,Y.p=1,Y===this.v)this.v=Y.g();else Y.g();else if(T.i&&T.i.p===1){if(T.p=Y.p,Y.p=0,T.i.p=0,Y===this.v)this.v=Y.g();else Y.g();return}else if(T.h&&T.h.p===1)T.p=1,T.h.p=0,T._();else T.p=1,$=Y}}}S($){if(this.m===1){this.clear();return}let Y=$;while(Y.i||Y.h){if(Y.h){Y=Y.h;while(Y.i)Y=Y.i}else Y=Y.i;let q=$.u;$.u=Y.u,Y.u=q;let X=$.l;$.l=Y.l,Y.l=X,$=Y}if(this.C.i===Y)this.C.i=Y.o;else if(this.C.h===Y)this.C.h=Y.o;this.P(Y);let T=Y.o;if(Y===T.i)T.i=void 0;else T.h=void 0;if(this.m-=1,this.v.p=0,this.enableIndex)while(T!==this.C)T.M-=1,T=T.o}U($){let Y=typeof $==="number"?$:void 0,T=typeof $==="function"?$:void 0,q=typeof $>"u"?[]:void 0,X=0,J=this.v,Q=[];while(Q.length||J)if(J)Q.push(J),J=J.i;else{if(J=Q.pop(),X===Y)return J;q&&q.push(J),T&&T(J,X,this),X+=1,J=J.h}return q}j($){while(!0){let Y=$.o;if(Y.p===0)return;let T=Y.o;if(Y===T.i){let q=T.h;if(q&&q.p===1){if(q.p=Y.p=0,T===this.v)return;T.p=1,$=T;continue}else if($===Y.h){if($.p=0,$.i)$.i.o=Y;if($.h)$.h.o=T;if(Y.h=$.i,T.i=$.h,$.i=Y,$.h=T,T===this.v)this.v=$,this.C.o=$;else{let X=T.o;if(X.i===T)X.i=$;else X.h=$}$.o=T.o,Y.o=$,T.o=$,T.p=1}else{if(Y.p=0,T===this.v)this.v=T.g();else T.g();T.p=1;return}}else{let q=T.i;if(q&&q.p===1){if(q.p=Y.p=0,T===this.v)return;T.p=1,$=T;continue}else if($===Y.i){if($.p=0,$.i)$.i.o=T;if($.h)$.h.o=Y;if(T.h=$.i,Y.i=$.h,$.i=T,$.h=Y,T===this.v)this.v=$,this.C.o=$;else{let X=T.o;if(X.i===T)X.i=$;else X.h=$}$.o=T.o,Y.o=$,T.o=$,T.p=1}else{if(Y.p=0,T===this.v)this.v=T._();else T._();T.p=1;return}}if(this.enableIndex)Y.O(),T.O(),$.O();return}}q($,Y,T){if(this.v===void 0)return this.m+=1,this.v=new this.N($,Y,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let q,X=this.C.i,J=this.A(X.u,$);if(J===0)return X.l=Y,this.m;else if(J>0)X.i=new this.N($,Y),X.i.o=X,q=X.i,this.C.i=q;else{let Q=this.C.h,U=this.A(Q.u,$);if(U===0)return Q.l=Y,this.m;else if(U<0)Q.h=new this.N($,Y),Q.h.o=Q,q=Q.h,this.C.h=q;else{if(T!==void 0){let Z=T.T;if(Z!==this.C){let K=this.A(Z.u,$);if(K===0)return Z.l=Y,this.m;else if(K>0){let A=Z.I(),W=this.A(A.u,$);if(W===0)return A.l=Y,this.m;else if(W<0)if(q=new this.N($,Y),A.h===void 0)A.h=q,q.o=A;else Z.i=q,q.o=Z}}}if(q===void 0){q=this.v;while(!0){let Z=this.A(q.u,$);if(Z>0){if(q.i===void 0){q.i=new this.N($,Y),q.i.o=q,q=q.i;break}q=q.i}else if(Z<0){if(q.h===void 0){q.h=new this.N($,Y),q.h.o=q,q=q.h;break}q=q.h}else return q.l=Y,this.m}}}}if(this.enableIndex){let Q=q.o;while(Q!==this.C)Q.M+=1,Q=Q.o}return this.j(q),this.m+=1,this.m}H($,Y){while($){let T=this.A($.u,Y);if(T<0)$=$.h;else if(T>0)$=$.i;else return $}return $||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator($,Y){let T=$.T;if(T===this.C)p$();if(this.m===1)return T.u=Y,!0;let q=T.B().u;if(T===this.C.i){if(this.A(q,Y)>0)return T.u=Y,!0;return!1}let X=T.I().u;if(T===this.C.h){if(this.A(X,Y)<0)return T.u=Y,!0;return!1}if(this.A(X,Y)>=0||this.A(q,Y)<=0)return!1;return T.u=Y,!0}eraseElementByPos($){if($<0||$>this.m-1)throw RangeError();let Y=this.U($);return this.S(Y),this.m}eraseElementByKey($){if(this.m===0)return!1;let Y=this.H(this.v,$);if(Y===this.C)return!1;return this.S(Y),!0}eraseElementByIterator($){let Y=$.T;if(Y===this.C)p$();let T=Y.h===void 0;if($.iteratorType===0){if(T)$.next()}else if(!T||Y.i===void 0)$.next();return this.S(Y),$}getHeight(){if(this.m===0)return 0;function $(Y){if(!Y)return 0;return Math.max($(Y.i),$(Y.h))+1}return $(this.v)}}class VZ extends AZ{constructor($,Y,T){super(T);if(this.T=$,this.C=Y,this.iteratorType===0)this.pre=function(){if(this.T===this.C.i)p$();return this.T=this.T.I(),this},this.next=function(){if(this.T===this.C)p$();return this.T=this.T.B(),this};else this.pre=function(){if(this.T===this.C.h)p$();return this.T=this.T.B(),this},this.next=function(){if(this.T===this.C)p$();return this.T=this.T.I(),this}}get index(){let $=this.T,Y=this.C.o;if($===this.C){if(Y)return Y.M-1;return 0}let T=0;if($.i)T+=$.i.M;while($!==Y){let q=$.o;if($===q.h){if(T+=1,q.i)T+=q.i.M}$=q}return T}isAccessible(){return this.T!==this.C}}class R1 extends VZ{constructor($,Y,T,q){super($,Y,q);this.container=T}get pointer(){if(this.T===this.C)p$();let $=this;return new Proxy([],{get(Y,T){if(T==="0")return $.T.u;else if(T==="1")return $.T.l;return Y[0]=$.T.u,Y[1]=$.T.l,Y[T]},set(Y,T,q){if(T!=="1")throw TypeError("prop must be 1");return $.T.l=q,!0}})}copy(){return new R1(this.T,this.C,this.container,this.iteratorType)}}class DZ extends EZ{constructor($=[],Y,T){super(Y,T);let q=this;$.forEach(function(X){q.setElement(X[0],X[1])})}begin(){return new R1(this.C.i||this.C,this.C,this)}end(){return new R1(this.C,this.C,this)}rBegin(){return new R1(this.C.h||this.C,this.C,this,1)}rEnd(){return new R1(this.C,this.C,this,1)}front(){if(this.m===0)return;let $=this.C.i;return[$.u,$.l]}back(){if(this.m===0)return;let $=this.C.h;return[$.u,$.l]}lowerBound($){let Y=this.R(this.v,$);return new R1(Y,this.C,this)}upperBound($){let Y=this.K(this.v,$);return new R1(Y,this.C,this)}reverseLowerBound($){let Y=this.L(this.v,$);return new R1(Y,this.C,this)}reverseUpperBound($){let Y=this.k(this.v,$);return new R1(Y,this.C,this)}forEach($){this.U(function(Y,T,q){$([Y.u,Y.l],T,q)})}setElement($,Y,T){return this.q($,Y,T)}getElementByPos($){if($<0||$>this.m-1)throw RangeError();let Y=this.U($);return[Y.u,Y.l]}find($){let Y=this.H(this.v,$);return new R1(Y,this.C,this)}getElementByKey($){return this.H(this.v,$).l}union($){let Y=this;return $.forEach(function(T){Y.setElement(T[0],T[1])}),this.m}*[Symbol.iterator](){let $=this.m,Y=this.U();for(let T=0;T<$;++T){let q=Y[T];yield[q.u,q.l]}}}FZ.OrderedMap=DZ});var r8=B((zZ)=>{Object.defineProperty(zZ,"__esModule",{value:!0});zZ.registerAdminService=TB;zZ.addAdminServicesToServer=qB;var HZ=[];function TB($,Y){HZ.push({getServiceDefinition:$,getHandlers:Y})}function qB($){for(let{getServiceDefinition:Y,getHandlers:T}of HZ)$.addService(Y(),T())}});var LZ=B((OZ)=>{Object.defineProperty(OZ,"__esModule",{value:!0});OZ.ClientDuplexStreamImpl=OZ.ClientWritableStreamImpl=OZ.ClientReadableStreamImpl=OZ.ClientUnaryCallImpl=void 0;OZ.callErrorFromStatus=UB;var QB=s("events"),JX=s("stream"),v6=i();function UB($,Y){let T=`${$.code} ${v6.Status[$.code]}: ${$.details}`,X=`${Error(T).stack}
|
|
2
2
|
for call at
|
|
3
|
-
${Y}`;return Object.assign(Error(T),$,{stack:X})}class FZ extends qB.EventEmitter{constructor(){super()}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}}IZ.ClientUnaryCallImpl=FZ;class NZ extends XX.Readable{constructor($){super({objectMode:!0});this.deserialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_read($){var Y;(Y=this.call)===null||Y===void 0||Y.startRead()}}IZ.ClientReadableStreamImpl=NZ;class HZ extends XX.Writable{constructor($){super({objectMode:!0});this.serialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_write($,Y,T){var q;let X={callback:T},J=Number(Y);if(!Number.isNaN(J))X.flags=J;(q=this.call)===null||q===void 0||q.sendMessageWithContext(X,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}IZ.ClientWritableStreamImpl=HZ;class zZ extends XX.Duplex{constructor($,Y){super({objectMode:!0});this.serialize=$,this.deserialize=Y}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_read($){var Y;(Y=this.call)===null||Y===void 0||Y.startRead()}_write($,Y,T){var q;let X={callback:T},J=Number(Y);if(!Number.isNaN(J))X.flags=J;(q=this.call)===null||q===void 0||q.sendMessageWithContext(X,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}IZ.ClientDuplexStreamImpl=zZ});var l$=M((OZ)=>{Object.defineProperty(OZ,"__esModule",{value:!0});OZ.InterceptingListenerImpl=void 0;OZ.statusOrFromValue=AB;OZ.statusOrFromError=WB;OZ.isInterceptingListener=GB;var KB=P0();function AB($){return{ok:!0,value:$}}function WB($){var Y;return{ok:!1,error:Object.assign(Object.assign({},$),{metadata:(Y=$.metadata)!==null&&Y!==void 0?Y:new KB.Metadata})}}function GB($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class RZ{constructor($,Y){this.listener=$,this.nextListener=Y,this.processingMetadata=!1,this.hasPendingMessage=!1,this.processingMessage=!1,this.pendingStatus=null}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingStatus(){if(this.pendingStatus)this.nextListener.onReceiveStatus(this.pendingStatus)}onReceiveMetadata($){this.processingMetadata=!0,this.listener.onReceiveMetadata($,(Y)=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(Y),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage($){this.processingMessage=!0,this.listener.onReceiveMessage($,(Y)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=Y,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(Y),this.processPendingStatus()})}onReceiveStatus($){this.listener.onReceiveStatus($,(Y)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=Y;else this.nextListener.onReceiveStatus(Y)})}}OZ.InterceptingListenerImpl=RZ});var UX=M((kZ)=>{Object.defineProperty(kZ,"__esModule",{value:!0});kZ.InterceptingCall=kZ.RequesterBuilder=kZ.ListenerBuilder=kZ.InterceptorConfigurationError=void 0;kZ.getInterceptingCall=zB;var FB=P0(),LZ=l$(),wZ=i(),SZ=x8();class kT extends Error{constructor($){super($);this.name="InterceptorConfigurationError",Error.captureStackTrace(this,kT)}}kZ.InterceptorConfigurationError=kT;class CZ{constructor(){this.metadata=void 0,this.message=void 0,this.status=void 0}withOnReceiveMetadata($){return this.metadata=$,this}withOnReceiveMessage($){return this.message=$,this}withOnReceiveStatus($){return this.status=$,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveStatus:this.status}}}kZ.ListenerBuilder=CZ;class yZ{constructor(){this.start=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withStart($){return this.start=$,this}withSendMessage($){return this.message=$,this}withHalfClose($){return this.halfClose=$,this}withCancel($){return this.cancel=$,this}build(){return{start:this.start,sendMessage:this.message,halfClose:this.halfClose,cancel:this.cancel}}}kZ.RequesterBuilder=yZ;var JX={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveStatus:($,Y)=>{Y($)}},xT={start:($,Y,T)=>{T($,Y)},sendMessage:($,Y)=>{Y($)},halfClose:($)=>{$()},cancel:($)=>{$()}};class jZ{constructor($,Y){var T,q,X,J;if(this.nextCall=$,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,Y)this.requester={start:(T=Y.start)!==null&&T!==void 0?T:xT.start,sendMessage:(q=Y.sendMessage)!==null&&q!==void 0?q:xT.sendMessage,halfClose:(X=Y.halfClose)!==null&&X!==void 0?X:xT.halfClose,cancel:(J=Y.cancel)!==null&&J!==void 0?J:xT.cancel};else this.requester=xT}cancelWithStatus($,Y){this.requester.cancel(()=>{this.nextCall.cancelWithStatus($,Y)})}getPeer(){return this.nextCall.getPeer()}processPendingMessage(){if(this.pendingMessageContext)this.nextCall.sendMessageWithContext(this.pendingMessageContext,this.pendingMessage),this.pendingMessageContext=null,this.pendingMessage=null}processPendingHalfClose(){if(this.pendingHalfClose)this.nextCall.halfClose()}start($,Y){var T,q,X,J,Q,U;let Z={onReceiveMetadata:(q=(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:(K)=>{},onReceiveMessage:(J=(X=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||X===void 0?void 0:X.bind(Y))!==null&&J!==void 0?J:(K)=>{},onReceiveStatus:(U=(Q=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Q===void 0?void 0:Q.bind(Y))!==null&&U!==void 0?U:(K)=>{}};this.processingMetadata=!0,this.requester.start($,Z,(K,A)=>{var W,E,D;this.processingMetadata=!1;let F;if((0,LZ.isInterceptingListener)(A))F=A;else{let H={onReceiveMetadata:(W=A.onReceiveMetadata)!==null&&W!==void 0?W:JX.onReceiveMetadata,onReceiveMessage:(E=A.onReceiveMessage)!==null&&E!==void 0?E:JX.onReceiveMessage,onReceiveStatus:(D=A.onReceiveStatus)!==null&&D!==void 0?D:JX.onReceiveStatus};F=new LZ.InterceptingListenerImpl(H,Z)}this.nextCall.start(K,F),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext($,Y){this.processingMessage=!0,this.requester.sendMessage(Y,(T)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessageContext=$,this.pendingMessage=Y;else this.nextCall.sendMessageWithContext($,T),this.processPendingHalfClose()})}sendMessage($){this.sendMessageWithContext({},$)}startRead(){this.nextCall.startRead()}halfClose(){this.requester.halfClose(()=>{if(this.processingMetadata||this.processingMessage)this.pendingHalfClose=!0;else this.nextCall.halfClose()})}getAuthContext(){return this.nextCall.getAuthContext()}}kZ.InterceptingCall=jZ;function NB($,Y,T){var q,X;let J=(q=T.deadline)!==null&&q!==void 0?q:1/0,Q=T.host,U=(X=T.parent)!==null&&X!==void 0?X:null,Z=T.propagate_flags,K=T.credentials,A=$.createCall(Y,J,Q,U,Z);if(K)A.setCredentials(K);return A}class QX{constructor($,Y){this.call=$,this.methodDefinition=Y}cancelWithStatus($,Y){this.call.cancelWithStatus($,Y)}getPeer(){return this.call.getPeer()}sendMessageWithContext($,Y){let T;try{T=this.methodDefinition.requestSerialize(Y)}catch(q){this.call.cancelWithStatus(wZ.Status.INTERNAL,`Request message serialization failure: ${(0,SZ.getErrorMessage)(q)}`);return}this.call.sendMessageWithContext($,T)}sendMessage($){this.sendMessageWithContext({},$)}start($,Y){let T=null;this.call.start($,{onReceiveMetadata:(q)=>{var X;(X=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||X===void 0||X.call(Y,q)},onReceiveMessage:(q)=>{var X;let J;try{J=this.methodDefinition.responseDeserialize(q)}catch(Q){T={code:wZ.Status.INTERNAL,details:`Response message parsing error: ${(0,SZ.getErrorMessage)(Q)}`,metadata:new FB.Metadata},this.call.cancelWithStatus(T.code,T.details);return}(X=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||X===void 0||X.call(Y,J)},onReceiveStatus:(q)=>{var X,J;if(T)(X=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||X===void 0||X.call(Y,T);else(J=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||J===void 0||J.call(Y,q)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}}class vZ extends QX{constructor($,Y){super($,Y)}start($,Y){var T,q;let X=!1,J={onReceiveMetadata:(q=(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:(Q)=>{},onReceiveMessage:(Q)=>{var U;X=!0,(U=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||U===void 0||U.call(Y,Q)},onReceiveStatus:(Q)=>{var U,Z;if(!X)(U=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||U===void 0||U.call(Y,null);(Z=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Z===void 0||Z.call(Y,Q)}};super.start($,J),this.call.startRead()}}class xZ extends QX{}function HB($,Y,T){let q=NB($,T.path,Y);if(T.responseStream)return new xZ(q,T);else return new vZ(q,T)}function zB($,Y,T,q){if($.clientInterceptors.length>0&&$.clientInterceptorProviders.length>0)throw new kT("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if($.callInterceptors.length>0&&$.callInterceptorProviders.length>0)throw new kT("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let X=[];if($.callInterceptors.length>0||$.callInterceptorProviders.length>0)X=[].concat($.callInterceptors,$.callInterceptorProviders.map((U)=>U(Y))).filter((U)=>U);else X=[].concat($.clientInterceptors,$.clientInterceptorProviders.map((U)=>U(Y))).filter((U)=>U);let J=Object.assign({},T,{method_definition:Y});return X.reduceRight((U,Z)=>{return(K)=>Z(K,U)},(U)=>HB(q,U,Y))(J)}});var KX=M((gZ)=>{Object.defineProperty(gZ,"__esModule",{value:!0});gZ.Client=void 0;var h1=BZ(),OB=AX(),PB=l0(),B$=i(),wY=P0(),r8=UX(),O1=Symbol(),SY=Symbol(),CY=Symbol(),T$=Symbol();function ZX($){return typeof $==="function"}function yY($){var Y;return((Y=$.stack)===null||Y===void 0?void 0:Y.split(`
|
|
3
|
+
${Y}`;return Object.assign(Error(T),$,{stack:X})}class IZ extends QB.EventEmitter{constructor(){super()}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(v6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}}OZ.ClientUnaryCallImpl=IZ;class MZ extends JX.Readable{constructor($){super({objectMode:!0});this.deserialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(v6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_read($){var Y;(Y=this.call)===null||Y===void 0||Y.startRead()}}OZ.ClientReadableStreamImpl=MZ;class BZ extends JX.Writable{constructor($){super({objectMode:!0});this.serialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(v6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_write($,Y,T){var q;let X={callback:T},J=Number(Y);if(!Number.isNaN(J))X.flags=J;(q=this.call)===null||q===void 0||q.sendMessageWithContext(X,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}OZ.ClientWritableStreamImpl=BZ;class RZ extends JX.Duplex{constructor($,Y){super({objectMode:!0});this.serialize=$,this.deserialize=Y}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(v6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_read($){var Y;(Y=this.call)===null||Y===void 0||Y.startRead()}_write($,Y,T){var q;let X={callback:T},J=Number(Y);if(!Number.isNaN(J))X.flags=J;(q=this.call)===null||q===void 0||q.sendMessageWithContext(X,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}OZ.ClientDuplexStreamImpl=RZ});var l$=B((SZ)=>{Object.defineProperty(SZ,"__esModule",{value:!0});SZ.InterceptingListenerImpl=void 0;SZ.statusOrFromValue=EB;SZ.statusOrFromError=VB;SZ.isInterceptingListener=DB;var GB=P0();function EB($){return{ok:!0,value:$}}function VB($){var Y;return{ok:!1,error:Object.assign(Object.assign({},$),{metadata:(Y=$.metadata)!==null&&Y!==void 0?Y:new GB.Metadata})}}function DB($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class wZ{constructor($,Y){this.listener=$,this.nextListener=Y,this.processingMetadata=!1,this.hasPendingMessage=!1,this.processingMessage=!1,this.pendingStatus=null}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingStatus(){if(this.pendingStatus)this.nextListener.onReceiveStatus(this.pendingStatus)}onReceiveMetadata($){this.processingMetadata=!0,this.listener.onReceiveMetadata($,(Y)=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(Y),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage($){this.processingMessage=!0,this.listener.onReceiveMessage($,(Y)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=Y,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(Y),this.processPendingStatus()})}onReceiveStatus($){this.listener.onReceiveStatus($,(Y)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=Y;else this.nextListener.onReceiveStatus(Y)})}}SZ.InterceptingListenerImpl=wZ});var ZX=B((mZ)=>{Object.defineProperty(mZ,"__esModule",{value:!0});mZ.InterceptingCall=mZ.RequesterBuilder=mZ.ListenerBuilder=mZ.InterceptorConfigurationError=void 0;mZ.getInterceptingCall=BB;var zB=P0(),yZ=l$(),jZ=i(),vZ=k8();class k6 extends Error{constructor($){super($);this.name="InterceptorConfigurationError",Error.captureStackTrace(this,k6)}}mZ.InterceptorConfigurationError=k6;class xZ{constructor(){this.metadata=void 0,this.message=void 0,this.status=void 0}withOnReceiveMetadata($){return this.metadata=$,this}withOnReceiveMessage($){return this.message=$,this}withOnReceiveStatus($){return this.status=$,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveStatus:this.status}}}mZ.ListenerBuilder=xZ;class kZ{constructor(){this.start=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withStart($){return this.start=$,this}withSendMessage($){return this.message=$,this}withHalfClose($){return this.halfClose=$,this}withCancel($){return this.cancel=$,this}build(){return{start:this.start,sendMessage:this.message,halfClose:this.halfClose,cancel:this.cancel}}}mZ.RequesterBuilder=kZ;var QX={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveStatus:($,Y)=>{Y($)}},x6={start:($,Y,T)=>{T($,Y)},sendMessage:($,Y)=>{Y($)},halfClose:($)=>{$()},cancel:($)=>{$()}};class hZ{constructor($,Y){var T,q,X,J;if(this.nextCall=$,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,Y)this.requester={start:(T=Y.start)!==null&&T!==void 0?T:x6.start,sendMessage:(q=Y.sendMessage)!==null&&q!==void 0?q:x6.sendMessage,halfClose:(X=Y.halfClose)!==null&&X!==void 0?X:x6.halfClose,cancel:(J=Y.cancel)!==null&&J!==void 0?J:x6.cancel};else this.requester=x6}cancelWithStatus($,Y){this.requester.cancel(()=>{this.nextCall.cancelWithStatus($,Y)})}getPeer(){return this.nextCall.getPeer()}processPendingMessage(){if(this.pendingMessageContext)this.nextCall.sendMessageWithContext(this.pendingMessageContext,this.pendingMessage),this.pendingMessageContext=null,this.pendingMessage=null}processPendingHalfClose(){if(this.pendingHalfClose)this.nextCall.halfClose()}start($,Y){var T,q,X,J,Q,U;let Z={onReceiveMetadata:(q=(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:(K)=>{},onReceiveMessage:(J=(X=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||X===void 0?void 0:X.bind(Y))!==null&&J!==void 0?J:(K)=>{},onReceiveStatus:(U=(Q=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Q===void 0?void 0:Q.bind(Y))!==null&&U!==void 0?U:(K)=>{}};this.processingMetadata=!0,this.requester.start($,Z,(K,A)=>{var W,E,V;this.processingMetadata=!1;let F;if((0,yZ.isInterceptingListener)(A))F=A;else{let H={onReceiveMetadata:(W=A.onReceiveMetadata)!==null&&W!==void 0?W:QX.onReceiveMetadata,onReceiveMessage:(E=A.onReceiveMessage)!==null&&E!==void 0?E:QX.onReceiveMessage,onReceiveStatus:(V=A.onReceiveStatus)!==null&&V!==void 0?V:QX.onReceiveStatus};F=new yZ.InterceptingListenerImpl(H,Z)}this.nextCall.start(K,F),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext($,Y){this.processingMessage=!0,this.requester.sendMessage(Y,(T)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessageContext=$,this.pendingMessage=Y;else this.nextCall.sendMessageWithContext($,T),this.processPendingHalfClose()})}sendMessage($){this.sendMessageWithContext({},$)}startRead(){this.nextCall.startRead()}halfClose(){this.requester.halfClose(()=>{if(this.processingMetadata||this.processingMessage)this.pendingHalfClose=!0;else this.nextCall.halfClose()})}getAuthContext(){return this.nextCall.getAuthContext()}}mZ.InterceptingCall=hZ;function IB($,Y,T){var q,X;let J=(q=T.deadline)!==null&&q!==void 0?q:1/0,Q=T.host,U=(X=T.parent)!==null&&X!==void 0?X:null,Z=T.propagate_flags,K=T.credentials,A=$.createCall(Y,J,Q,U,Z);if(K)A.setCredentials(K);return A}class UX{constructor($,Y){this.call=$,this.methodDefinition=Y}cancelWithStatus($,Y){this.call.cancelWithStatus($,Y)}getPeer(){return this.call.getPeer()}sendMessageWithContext($,Y){let T;try{T=this.methodDefinition.requestSerialize(Y)}catch(q){this.call.cancelWithStatus(jZ.Status.INTERNAL,`Request message serialization failure: ${(0,vZ.getErrorMessage)(q)}`);return}this.call.sendMessageWithContext($,T)}sendMessage($){this.sendMessageWithContext({},$)}start($,Y){let T=null;this.call.start($,{onReceiveMetadata:(q)=>{var X;(X=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||X===void 0||X.call(Y,q)},onReceiveMessage:(q)=>{var X;let J;try{J=this.methodDefinition.responseDeserialize(q)}catch(Q){T={code:jZ.Status.INTERNAL,details:`Response message parsing error: ${(0,vZ.getErrorMessage)(Q)}`,metadata:new zB.Metadata},this.call.cancelWithStatus(T.code,T.details);return}(X=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||X===void 0||X.call(Y,J)},onReceiveStatus:(q)=>{var X,J;if(T)(X=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||X===void 0||X.call(Y,T);else(J=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||J===void 0||J.call(Y,q)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}}class _Z extends UX{constructor($,Y){super($,Y)}start($,Y){var T,q;let X=!1,J={onReceiveMetadata:(q=(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:(Q)=>{},onReceiveMessage:(Q)=>{var U;X=!0,(U=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||U===void 0||U.call(Y,Q)},onReceiveStatus:(Q)=>{var U,Z;if(!X)(U=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||U===void 0||U.call(Y,null);(Z=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Z===void 0||Z.call(Y,Q)}};super.start($,J),this.call.startRead()}}class gZ extends UX{}function MB($,Y,T){let q=IB($,T.path,Y);if(T.responseStream)return new gZ(q,T);else return new _Z(q,T)}function BB($,Y,T,q){if($.clientInterceptors.length>0&&$.clientInterceptorProviders.length>0)throw new k6("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if($.callInterceptors.length>0&&$.callInterceptorProviders.length>0)throw new k6("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let X=[];if($.callInterceptors.length>0||$.callInterceptorProviders.length>0)X=[].concat($.callInterceptors,$.callInterceptorProviders.map((U)=>U(Y))).filter((U)=>U);else X=[].concat($.clientInterceptors,$.clientInterceptorProviders.map((U)=>U(Y))).filter((U)=>U);let J=Object.assign({},T,{method_definition:Y});return X.reduceRight((U,Z)=>{return(K)=>Z(K,U)},(U)=>MB(q,U,Y))(J)}});var AX=B((uZ)=>{Object.defineProperty(uZ,"__esModule",{value:!0});uZ.Client=void 0;var h1=LZ(),wB=WX(),SB=l0(),B$=i(),wY=P0(),a8=ZX(),O1=Symbol(),SY=Symbol(),CY=Symbol(),T$=Symbol();function KX($){return typeof $==="function"}function yY($){var Y;return((Y=$.stack)===null||Y===void 0?void 0:Y.split(`
|
|
4
4
|
`).slice(1).join(`
|
|
5
|
-
`))||"no stack trace available"}class _Z{constructor($,Y,T={}){var q,X;if(T=Object.assign({},T),this[SY]=(q=T.interceptors)!==null&&q!==void 0?q:[],delete T.interceptors,this[CY]=(X=T.interceptor_providers)!==null&&X!==void 0?X:[],delete T.interceptor_providers,this[SY].length>0&&this[CY].length>0)throw Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if(this[T$]=T.callInvocationTransformer,delete T.callInvocationTransformer,T.channelOverride)this[O1]=T.channelOverride;else if(T.channelFactoryOverride){let J=T.channelFactoryOverride;delete T.channelFactoryOverride,this[O1]=J($,Y,T)}else this[O1]=new OB.ChannelImplementation($,Y,T)}close(){this[O1].close()}getChannel(){return this[O1]}waitForReady($,Y){let T=(q)=>{if(q){Y(Error("Failed to connect before the deadline"));return}let X;try{X=this[O1].getConnectivityState(!0)}catch(J){Y(Error("The channel has been closed"));return}if(X===PB.ConnectivityState.READY)Y();else try{this[O1].watchConnectivityState(X,$,T)}catch(J){Y(Error("The channel has been closed"))}};setImmediate(T)}checkOptionalUnaryResponseArguments($,Y,T){if(ZX($))return{metadata:new wY.Metadata,options:{},callback:$};else if(ZX(Y))if($ instanceof wY.Metadata)return{metadata:$,options:{},callback:Y};else return{metadata:new wY.Metadata,options:$,callback:Y};else{if(!($ instanceof wY.Metadata&&Y instanceof Object&&ZX(T)))throw Error("Incorrect arguments passed");return{metadata:$,options:Y,callback:T}}}makeUnaryRequest($,Y,T,q,X,J,Q){var U,Z;let K=this.checkOptionalUnaryResponseArguments(X,J,Q),A={path:$,requestStream:!1,responseStream:!1,requestSerialize:Y,responseDeserialize:T},W={argument:q,metadata:K.metadata,call:new h1.ClientUnaryCallImpl,channel:this[O1],methodDefinition:A,callOptions:K.options,callback:K.callback};if(this[T$])W=this[T$](W);let E=W.call,D={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(U=W.callOptions.interceptors)!==null&&U!==void 0?U:[],callInterceptorProviders:(Z=W.callOptions.interceptor_providers)!==null&&Z!==void 0?Z:[]},F=(0,r8.getInterceptingCall)(D,W.methodDefinition,W.callOptions,W.channel);E.call=F;let H=null,V=!1,B=Error();return F.start(W.metadata,{onReceiveMetadata:(S)=>{E.emit("metadata",S)},onReceiveMessage(S){if(H!==null)F.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");H=S},onReceiveStatus(S){if(V)return;if(V=!0,S.code===B$.Status.OK)if(H===null){let v=yY(B);W.callback((0,h1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:S.metadata},v))}else W.callback(null,H);else{let v=yY(B);W.callback((0,h1.callErrorFromStatus)(S,v))}B=null,E.emit("status",S)}}),F.sendMessage(q),F.halfClose(),E}makeClientStreamRequest($,Y,T,q,X,J){var Q,U;let Z=this.checkOptionalUnaryResponseArguments(q,X,J),K={path:$,requestStream:!0,responseStream:!1,requestSerialize:Y,responseDeserialize:T},A={metadata:Z.metadata,call:new h1.ClientWritableStreamImpl(Y),channel:this[O1],methodDefinition:K,callOptions:Z.options,callback:Z.callback};if(this[T$])A=this[T$](A);let W=A.call,E={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},D=(0,r8.getInterceptingCall)(E,A.methodDefinition,A.callOptions,A.channel);W.call=D;let F=null,H=!1,V=Error();return D.start(A.metadata,{onReceiveMetadata:(B)=>{W.emit("metadata",B)},onReceiveMessage(B){if(F!==null)D.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");F=B,D.startRead()},onReceiveStatus(B){if(H)return;if(H=!0,B.code===B$.Status.OK)if(F===null){let S=yY(V);A.callback((0,h1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:B.metadata},S))}else A.callback(null,F);else{let S=yY(V);A.callback((0,h1.callErrorFromStatus)(B,S))}V=null,W.emit("status",B)}}),W}checkMetadataAndOptions($,Y){let T,q;if($ instanceof wY.Metadata)if(T=$,Y)q=Y;else q={};else{if($)q=$;else q={};T=new wY.Metadata}return{metadata:T,options:q}}makeServerStreamRequest($,Y,T,q,X,J){var Q,U;let Z=this.checkMetadataAndOptions(X,J),K={path:$,requestStream:!1,responseStream:!0,requestSerialize:Y,responseDeserialize:T},A={argument:q,metadata:Z.metadata,call:new h1.ClientReadableStreamImpl(T),channel:this[O1],methodDefinition:K,callOptions:Z.options};if(this[T$])A=this[T$](A);let W=A.call,E={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},D=(0,r8.getInterceptingCall)(E,A.methodDefinition,A.callOptions,A.channel);W.call=D;let F=!1,H=Error();return D.start(A.metadata,{onReceiveMetadata(V){W.emit("metadata",V)},onReceiveMessage(V){W.push(V)},onReceiveStatus(V){if(F)return;if(F=!0,W.push(null),V.code!==B$.Status.OK){let B=yY(H);W.emit("error",(0,h1.callErrorFromStatus)(V,B))}H=null,W.emit("status",V)}}),D.sendMessage(q),D.halfClose(),W}makeBidiStreamRequest($,Y,T,q,X){var J,Q;let U=this.checkMetadataAndOptions(q,X),Z={path:$,requestStream:!0,responseStream:!0,requestSerialize:Y,responseDeserialize:T},K={metadata:U.metadata,call:new h1.ClientDuplexStreamImpl(Y,T),channel:this[O1],methodDefinition:Z,callOptions:U.options};if(this[T$])K=this[T$](K);let A=K.call,W={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(J=K.callOptions.interceptors)!==null&&J!==void 0?J:[],callInterceptorProviders:(Q=K.callOptions.interceptor_providers)!==null&&Q!==void 0?Q:[]},E=(0,r8.getInterceptingCall)(W,K.methodDefinition,K.callOptions,K.channel);A.call=E;let D=!1,F=Error();return E.start(K.metadata,{onReceiveMetadata(H){A.emit("metadata",H)},onReceiveMessage(H){A.push(H)},onReceiveStatus(H){if(D)return;if(D=!0,A.push(null),H.code!==B$.Status.OK){let V=yY(F);A.emit("error",(0,h1.callErrorFromStatus)(H,V))}F=null,A.emit("status",H)}}),A}}gZ.Client=_Z});var a8=M((bZ)=>{Object.defineProperty(bZ,"__esModule",{value:!0});bZ.makeClientConstructor=fZ;bZ.loadPackageDefinition=CB;var hT=KX(),LB={unary:hT.Client.prototype.makeUnaryRequest,server_stream:hT.Client.prototype.makeServerStreamRequest,client_stream:hT.Client.prototype.makeClientStreamRequest,bidi:hT.Client.prototype.makeBidiStreamRequest};function WX($){return["__proto__","prototype","constructor"].includes($)}function fZ($,Y,T){if(!T)T={};class q extends hT.Client{}return Object.keys($).forEach((X)=>{if(WX(X))return;let J=$[X],Q;if(typeof X==="string"&&X.charAt(0)==="$")throw Error("Method names cannot start with $");if(J.requestStream)if(J.responseStream)Q="bidi";else Q="client_stream";else if(J.responseStream)Q="server_stream";else Q="unary";let{requestSerialize:U,responseDeserialize:Z}=J,K=wB(LB[Q],J.path,U,Z);if(q.prototype[X]=K,Object.assign(q.prototype[X],J),J.originalName&&!WX(J.originalName))q.prototype[J.originalName]=q.prototype[X]}),q.service=$,q.serviceName=Y,q}function wB($,Y,T,q){return function(...X){return $.call(this,Y,T,q,...X)}}function SB($){return"format"in $}function CB($){let Y={};for(let T in $)if(Object.prototype.hasOwnProperty.call($,T)){let q=$[T],X=T.split(".");if(X.some((U)=>WX(U)))continue;let J=X[X.length-1],Q=Y;for(let U of X.slice(0,-1)){if(!Q[U])Q[U]={};Q=Q[U]}if(SB(q))Q[J]=q;else Q[J]=fZ(q,J,{})}return Y}});var WK=M((Jg,AK)=>{var vB=1/0,xB="[object Symbol]",kB=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,hB=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,s8="\\ud800-\\udfff",rZ="\\u0300-\\u036f\\ufe20-\\ufe23",aZ="\\u20d0-\\u20f0",oZ="\\u2700-\\u27bf",sZ="a-z\\xdf-\\xf6\\xf8-\\xff",_B="\\xac\\xb1\\xd7\\xf7",gB="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",mB="\\u2000-\\u206f",fB=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",tZ="A-Z\\xc0-\\xd6\\xd8-\\xde",eZ="\\ufe0e\\ufe0f",$K=_B+gB+mB+fB,EX="['’]",bB="["+s8+"]",uZ="["+$K+"]",o8="["+rZ+aZ+"]",YK="\\d+",uB="["+oZ+"]",TK="["+sZ+"]",qK="[^"+s8+$K+YK+oZ+sZ+tZ+"]",GX="\\ud83c[\\udffb-\\udfff]",dB="(?:"+o8+"|"+GX+")",XK="[^"+s8+"]",VX="(?:\\ud83c[\\udde6-\\uddff]){2}",DX="[\\ud800-\\udbff][\\udc00-\\udfff]",jY="["+tZ+"]",JK="\\u200d",dZ="(?:"+TK+"|"+qK+")",cB="(?:"+jY+"|"+qK+")",cZ="(?:"+EX+"(?:d|ll|m|re|s|t|ve))?",pZ="(?:"+EX+"(?:D|LL|M|RE|S|T|VE))?",QK=dB+"?",UK="["+eZ+"]?",pB="(?:"+JK+"(?:"+[XK,VX,DX].join("|")+")"+UK+QK+")*",ZK=UK+QK+pB,lB="(?:"+[uB,VX,DX].join("|")+")"+ZK,nB="(?:"+[XK+o8+"?",o8,VX,DX,bB].join("|")+")",iB=RegExp(EX,"g"),rB=RegExp(o8,"g"),aB=RegExp(GX+"(?="+GX+")|"+nB+ZK,"g"),oB=RegExp([jY+"?"+TK+"+"+cZ+"(?="+[uZ,jY,"$"].join("|")+")",cB+"+"+pZ+"(?="+[uZ,jY+dZ,"$"].join("|")+")",jY+"?"+dZ+"+"+cZ,jY+"+"+pZ,YK,lB].join("|"),"g"),sB=RegExp("["+JK+s8+rZ+aZ+eZ+"]"),tB=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,eB={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"ss"},$R=typeof global=="object"&&global&&global.Object===Object&&global,YR=typeof self=="object"&&self&&self.Object===Object&&self,TR=$R||YR||Function("return this")();function qR($,Y,T,q){var X=-1,J=$?$.length:0;if(q&&J)T=$[++X];while(++X<J)T=Y(T,$[X],X,$);return T}function XR($){return $.split("")}function JR($){return $.match(kB)||[]}function QR($){return function(Y){return $==null?void 0:$[Y]}}var UR=QR(eB);function KK($){return sB.test($)}function ZR($){return tB.test($)}function KR($){return KK($)?AR($):XR($)}function AR($){return $.match(aB)||[]}function WR($){return $.match(oB)||[]}var GR=Object.prototype,ER=GR.toString,lZ=TR.Symbol,nZ=lZ?lZ.prototype:void 0,iZ=nZ?nZ.toString:void 0;function VR($,Y,T){var q=-1,X=$.length;if(Y<0)Y=-Y>X?0:X+Y;if(T=T>X?X:T,T<0)T+=X;X=Y>T?0:T-Y>>>0,Y>>>=0;var J=Array(X);while(++q<X)J[q]=$[q+Y];return J}function DR($){if(typeof $=="string")return $;if(IR($))return iZ?iZ.call($):"";var Y=$+"";return Y=="0"&&1/$==-vB?"-0":Y}function FR($,Y,T){var q=$.length;return T=T===void 0?q:T,!Y&&T>=q?$:VR($,Y,T)}function NR($){return function(Y){Y=t8(Y);var T=KK(Y)?KR(Y):void 0,q=T?T[0]:Y.charAt(0),X=T?FR(T,1).join(""):Y.slice(1);return q[$]()+X}}function HR($){return function(Y){return qR(PR(RR(Y).replace(iB,"")),$,"")}}function zR($){return!!$&&typeof $=="object"}function IR($){return typeof $=="symbol"||zR($)&&ER.call($)==xB}function t8($){return $==null?"":DR($)}var MR=HR(function($,Y,T){return Y=Y.toLowerCase(),$+(T?BR(Y):Y)});function BR($){return OR(t8($).toLowerCase())}function RR($){return $=t8($),$&&$.replace(hB,UR).replace(rB,"")}var OR=NR("toUpperCase");function PR($,Y,T){if($=t8($),Y=T?void 0:Y,Y===void 0)return ZR($)?WR($):JR($);return $.match(Y)||[]}AK.exports=MR});var FX=M((Qg,GK)=>{GK.exports=LR;function LR($,Y){var T=Array(arguments.length-1),q=0,X=2,J=!0;while(X<arguments.length)T[q++]=arguments[X++];return new Promise(function(U,Z){T[q]=function(A){if(J)if(J=!1,A)Z(A);else{var W=Array(arguments.length-1),E=0;while(E<W.length)W[E++]=arguments[E];U.apply(null,W)}};try{$.apply(Y||null,T)}catch(K){if(J)J=!1,Z(K)}})}});var FK=M((DK)=>{var e8=DK;e8.length=function(Y){var T=Y.length;if(!T)return 0;var q=0;while(--T%4>1&&Y.charAt(T)==="=")++q;return Math.ceil(Y.length*3)/4-q};var vY=Array(64),VK=Array(123);for(E1=0;E1<64;)VK[vY[E1]=E1<26?E1+65:E1<52?E1+71:E1<62?E1-4:E1-59|43]=E1++;var E1;e8.encode=function(Y,T,q){var X=null,J=[],Q=0,U=0,Z;while(T<q){var K=Y[T++];switch(U){case 0:J[Q++]=vY[K>>2],Z=(K&3)<<4,U=1;break;case 1:J[Q++]=vY[Z|K>>4],Z=(K&15)<<2,U=2;break;case 2:J[Q++]=vY[Z|K>>6],J[Q++]=vY[K&63],U=0;break}if(Q>8191)(X||(X=[])).push(String.fromCharCode.apply(String,J)),Q=0}if(U){if(J[Q++]=vY[Z],J[Q++]=61,U===1)J[Q++]=61}if(X){if(Q)X.push(String.fromCharCode.apply(String,J.slice(0,Q)));return X.join("")}return String.fromCharCode.apply(String,J.slice(0,Q))};var EK="invalid encoding";e8.decode=function(Y,T,q){var X=q,J=0,Q;for(var U=0;U<Y.length;){var Z=Y.charCodeAt(U++);if(Z===61&&J>1)break;if((Z=VK[Z])===void 0)throw Error(EK);switch(J){case 0:Q=Z,J=1;break;case 1:T[q++]=Q<<2|(Z&48)>>4,Q=Z,J=2;break;case 2:T[q++]=(Q&15)<<4|(Z&60)>>2,Q=Z,J=3;break;case 3:T[q++]=(Q&3)<<6|Z,J=0;break}}if(J===1)throw Error(EK);return q-X};e8.test=function(Y){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Y)}});var HK=M((Zg,NK)=>{NK.exports=$q;function $q(){this._listeners={}}$q.prototype.on=function(Y,T,q){return(this._listeners[Y]||(this._listeners[Y]=[])).push({fn:T,ctx:q||this}),this};$q.prototype.off=function(Y,T){if(Y===void 0)this._listeners={};else if(T===void 0)this._listeners[Y]=[];else{var q=this._listeners[Y];for(var X=0;X<q.length;)if(q[X].fn===T)q.splice(X,1);else++X}return this};$q.prototype.emit=function(Y){var T=this._listeners[Y];if(T){var q=[],X=1;for(;X<arguments.length;)q.push(arguments[X++]);for(X=0;X<T.length;)T[X].fn.apply(T[X++].ctx,q)}return this}});var PK=M((Kg,OK)=>{OK.exports=zK(zK);function zK($){if(typeof Float32Array<"u")(function(){var Y=new Float32Array([-0]),T=new Uint8Array(Y.buffer),q=T[3]===128;function X(Z,K,A){Y[0]=Z,K[A]=T[0],K[A+1]=T[1],K[A+2]=T[2],K[A+3]=T[3]}function J(Z,K,A){Y[0]=Z,K[A]=T[3],K[A+1]=T[2],K[A+2]=T[1],K[A+3]=T[0]}$.writeFloatLE=q?X:J,$.writeFloatBE=q?J:X;function Q(Z,K){return T[0]=Z[K],T[1]=Z[K+1],T[2]=Z[K+2],T[3]=Z[K+3],Y[0]}function U(Z,K){return T[3]=Z[K],T[2]=Z[K+1],T[1]=Z[K+2],T[0]=Z[K+3],Y[0]}$.readFloatLE=q?Q:U,$.readFloatBE=q?U:Q})();else(function(){function Y(q,X,J,Q){var U=X<0?1:0;if(U)X=-X;if(X===0)q(1/X>0?0:2147483648,J,Q);else if(isNaN(X))q(2143289344,J,Q);else if(X>340282346638528860000000000000000000000)q((U<<31|2139095040)>>>0,J,Q);else if(X<0.000000000000000000000000000000000000011754943508222875)q((U<<31|Math.round(X/0.000000000000000000000000000000000000000000001401298464324817))>>>0,J,Q);else{var Z=Math.floor(Math.log(X)/Math.LN2),K=Math.round(X*Math.pow(2,-Z)*8388608)&8388607;q((U<<31|Z+127<<23|K)>>>0,J,Q)}}$.writeFloatLE=Y.bind(null,IK),$.writeFloatBE=Y.bind(null,MK);function T(q,X,J){var Q=q(X,J),U=(Q>>31)*2+1,Z=Q>>>23&255,K=Q&8388607;return Z===255?K?NaN:U*(1/0):Z===0?U*0.000000000000000000000000000000000000000000001401298464324817*K:U*Math.pow(2,Z-150)*(K+8388608)}$.readFloatLE=T.bind(null,BK),$.readFloatBE=T.bind(null,RK)})();if(typeof Float64Array<"u")(function(){var Y=new Float64Array([-0]),T=new Uint8Array(Y.buffer),q=T[7]===128;function X(Z,K,A){Y[0]=Z,K[A]=T[0],K[A+1]=T[1],K[A+2]=T[2],K[A+3]=T[3],K[A+4]=T[4],K[A+5]=T[5],K[A+6]=T[6],K[A+7]=T[7]}function J(Z,K,A){Y[0]=Z,K[A]=T[7],K[A+1]=T[6],K[A+2]=T[5],K[A+3]=T[4],K[A+4]=T[3],K[A+5]=T[2],K[A+6]=T[1],K[A+7]=T[0]}$.writeDoubleLE=q?X:J,$.writeDoubleBE=q?J:X;function Q(Z,K){return T[0]=Z[K],T[1]=Z[K+1],T[2]=Z[K+2],T[3]=Z[K+3],T[4]=Z[K+4],T[5]=Z[K+5],T[6]=Z[K+6],T[7]=Z[K+7],Y[0]}function U(Z,K){return T[7]=Z[K],T[6]=Z[K+1],T[5]=Z[K+2],T[4]=Z[K+3],T[3]=Z[K+4],T[2]=Z[K+5],T[1]=Z[K+6],T[0]=Z[K+7],Y[0]}$.readDoubleLE=q?Q:U,$.readDoubleBE=q?U:Q})();else(function(){function Y(q,X,J,Q,U,Z){var K=Q<0?1:0;if(K)Q=-Q;if(Q===0)q(0,U,Z+X),q(1/Q>0?0:2147483648,U,Z+J);else if(isNaN(Q))q(0,U,Z+X),q(2146959360,U,Z+J);else if(Q>179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)q(0,U,Z+X),q((K<<31|2146435072)>>>0,U,Z+J);else{var A;if(Q<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014)A=Q/0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005,q(A>>>0,U,Z+X),q((K<<31|A/4294967296)>>>0,U,Z+J);else{var W=Math.floor(Math.log(Q)/Math.LN2);if(W===1024)W=1023;A=Q*Math.pow(2,-W),q(A*4503599627370496>>>0,U,Z+X),q((K<<31|W+1023<<20|A*1048576&1048575)>>>0,U,Z+J)}}}$.writeDoubleLE=Y.bind(null,IK,0,4),$.writeDoubleBE=Y.bind(null,MK,4,0);function T(q,X,J,Q,U){var Z=q(Q,U+X),K=q(Q,U+J),A=(K>>31)*2+1,W=K>>>20&2047,E=4294967296*(K&1048575)+Z;return W===2047?E?NaN:A*(1/0):W===0?A*0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005*E:A*Math.pow(2,W-1075)*(E+4503599627370496)}$.readDoubleLE=T.bind(null,BK,0,4),$.readDoubleBE=T.bind(null,RK,4,0)})();return $}function IK($,Y,T){Y[T]=$&255,Y[T+1]=$>>>8&255,Y[T+2]=$>>>16&255,Y[T+3]=$>>>24}function MK($,Y,T){Y[T]=$>>>24,Y[T+1]=$>>>16&255,Y[T+2]=$>>>8&255,Y[T+3]=$&255}function BK($,Y){return($[Y]|$[Y+1]<<8|$[Y+2]<<16|$[Y+3]<<24)>>>0}function RK($,Y){return($[Y]<<24|$[Y+1]<<16|$[Y+2]<<8|$[Y+3])>>>0}});var HX=M((LK,NX)=>{NX.exports=wR;function wR(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch($){}return null}});var SK=M((wK)=>{var zX=wK;zX.length=function(Y){var T=0,q=0;for(var X=0;X<Y.length;++X)if(q=Y.charCodeAt(X),q<128)T+=1;else if(q<2048)T+=2;else if((q&64512)===55296&&(Y.charCodeAt(X+1)&64512)===56320)++X,T+=4;else T+=3;return T};zX.read=function(Y,T,q){var X=q-T;if(X<1)return"";var J=null,Q=[],U=0,Z;while(T<q){if(Z=Y[T++],Z<128)Q[U++]=Z;else if(Z>191&&Z<224)Q[U++]=(Z&31)<<6|Y[T++]&63;else if(Z>239&&Z<365)Z=((Z&7)<<18|(Y[T++]&63)<<12|(Y[T++]&63)<<6|Y[T++]&63)-65536,Q[U++]=55296+(Z>>10),Q[U++]=56320+(Z&1023);else Q[U++]=(Z&15)<<12|(Y[T++]&63)<<6|Y[T++]&63;if(U>8191)(J||(J=[])).push(String.fromCharCode.apply(String,Q)),U=0}if(J){if(U)J.push(String.fromCharCode.apply(String,Q.slice(0,U)));return J.join("")}return String.fromCharCode.apply(String,Q.slice(0,U))};zX.write=function(Y,T,q){var X=q,J,Q;for(var U=0;U<Y.length;++U)if(J=Y.charCodeAt(U),J<128)T[q++]=J;else if(J<2048)T[q++]=J>>6|192,T[q++]=J&63|128;else if((J&64512)===55296&&((Q=Y.charCodeAt(U+1))&64512)===56320)J=65536+((J&1023)<<10)+(Q&1023),++U,T[q++]=J>>18|240,T[q++]=J>>12&63|128,T[q++]=J>>6&63|128,T[q++]=J&63|128;else T[q++]=J>>12|224,T[q++]=J>>6&63|128,T[q++]=J&63|128;return q-X}});var yK=M((Wg,CK)=>{CK.exports=SR;function SR($,Y,T){var q=T||8192,X=q>>>1,J=null,Q=q;return function(Z){if(Z<1||Z>X)return $(Z);if(Q+Z>q)J=$(q),Q=0;var K=Y.call(J,Q,Q+=Z);if(Q&7)Q=(Q|7)+1;return K}}});var vK=M((Gg,jK)=>{jK.exports=L0;var _T=_1();function L0($,Y){this.lo=$>>>0,this.hi=Y>>>0}var n$=L0.zero=new L0(0,0);n$.toNumber=function(){return 0};n$.zzEncode=n$.zzDecode=function(){return this};n$.length=function(){return 1};var CR=L0.zeroHash="\x00\x00\x00\x00\x00\x00\x00\x00";L0.fromNumber=function(Y){if(Y===0)return n$;var T=Y<0;if(T)Y=-Y;var q=Y>>>0,X=(Y-q)/4294967296>>>0;if(T){if(X=~X>>>0,q=~q>>>0,++q>4294967295){if(q=0,++X>4294967295)X=0}}return new L0(q,X)};L0.from=function(Y){if(typeof Y==="number")return L0.fromNumber(Y);if(_T.isString(Y))if(_T.Long)Y=_T.Long.fromString(Y);else return L0.fromNumber(parseInt(Y,10));return Y.low||Y.high?new L0(Y.low>>>0,Y.high>>>0):n$};L0.prototype.toNumber=function(Y){if(!Y&&this.hi>>>31){var T=~this.lo+1>>>0,q=~this.hi>>>0;if(!T)q=q+1>>>0;return-(T+q*4294967296)}return this.lo+this.hi*4294967296};L0.prototype.toLong=function(Y){return _T.Long?new _T.Long(this.lo|0,this.hi|0,Boolean(Y)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(Y)}};var R$=String.prototype.charCodeAt;L0.fromHash=function(Y){if(Y===CR)return n$;return new L0((R$.call(Y,0)|R$.call(Y,1)<<8|R$.call(Y,2)<<16|R$.call(Y,3)<<24)>>>0,(R$.call(Y,4)|R$.call(Y,5)<<8|R$.call(Y,6)<<16|R$.call(Y,7)<<24)>>>0)};L0.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};L0.prototype.zzEncode=function(){var Y=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^Y)>>>0,this.lo=(this.lo<<1^Y)>>>0,this};L0.prototype.zzDecode=function(){var Y=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^Y)>>>0,this.hi=(this.hi>>>1^Y)>>>0,this};L0.prototype.length=function(){var Y=this.lo,T=(this.lo>>>28|this.hi<<4)>>>0,q=this.hi>>>24;return q===0?T===0?Y<16384?Y<128?1:2:Y<2097152?3:4:T<16384?T<128?5:6:T<2097152?7:8:q<128?9:10}});var _1=M((IX)=>{var g=IX;g.asPromise=FX();g.base64=FK();g.EventEmitter=HK();g.float=PK();g.inquire=HX();g.utf8=SK();g.pool=yK();g.LongBits=vK();g.isNode=Boolean(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);g.global=g.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||IX;g.emptyArray=Object.freeze?Object.freeze([]):[];g.emptyObject=Object.freeze?Object.freeze({}):{};g.isInteger=Number.isInteger||function(Y){return typeof Y==="number"&&isFinite(Y)&&Math.floor(Y)===Y};g.isString=function(Y){return typeof Y==="string"||Y instanceof String};g.isObject=function(Y){return Y&&typeof Y==="object"};g.isset=g.isSet=function(Y,T){var q=Y[T];if(q!=null&&Y.hasOwnProperty(T))return typeof q!=="object"||(Array.isArray(q)?q.length:Object.keys(q).length)>0;return!1};g.Buffer=function(){try{var $=g.inquire("buffer").Buffer;return $.prototype.utf8Write?$:null}catch(Y){return null}}();g._Buffer_from=null;g._Buffer_allocUnsafe=null;g.newBuffer=function(Y){return typeof Y==="number"?g.Buffer?g._Buffer_allocUnsafe(Y):new g.Array(Y):g.Buffer?g._Buffer_from(Y):typeof Uint8Array>"u"?Y:new Uint8Array(Y)};g.Array=typeof Uint8Array<"u"?Uint8Array:Array;g.Long=g.global.dcodeIO&&g.global.dcodeIO.Long||g.global.Long||g.inquire("long");g.key2Re=/^true|false|0|1$/;g.key32Re=/^-?(?:0|[1-9][0-9]*)$/;g.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;g.longToHash=function(Y){return Y?g.LongBits.from(Y).toHash():g.LongBits.zeroHash};g.longFromHash=function(Y,T){var q=g.LongBits.fromHash(Y);if(g.Long)return g.Long.fromBits(q.lo,q.hi,T);return q.toNumber(Boolean(T))};function xK($,Y,T){for(var q=Object.keys(Y),X=0;X<q.length;++X)if($[q[X]]===void 0||!T)$[q[X]]=Y[q[X]];return $}g.merge=xK;g.lcFirst=function(Y){return Y.charAt(0).toLowerCase()+Y.substring(1)};function kK($){function Y(T,q){if(!(this instanceof Y))return new Y(T,q);if(Object.defineProperty(this,"message",{get:function(){return T}}),Error.captureStackTrace)Error.captureStackTrace(this,Y);else Object.defineProperty(this,"stack",{value:Error().stack||""});if(q)xK(this,q)}return Y.prototype=Object.create(Error.prototype,{constructor:{value:Y,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return $},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),Y}g.newError=kK;g.ProtocolError=kK("ProtocolError");g.oneOfGetter=function(Y){var T={};for(var q=0;q<Y.length;++q)T[Y[q]]=1;return function(){for(var X=Object.keys(this),J=X.length-1;J>-1;--J)if(T[X[J]]===1&&this[X[J]]!==void 0&&this[X[J]]!==null)return X[J]}};g.oneOfSetter=function(Y){return function(T){for(var q=0;q<Y.length;++q)if(Y[q]!==T)delete this[Y[q]]}};g.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};g._configure=function(){var $=g.Buffer;if(!$){g._Buffer_from=g._Buffer_allocUnsafe=null;return}g._Buffer_from=$.from!==Uint8Array.from&&$.from||function(T,q){return new $(T,q)},g._Buffer_allocUnsafe=$.allocUnsafe||function(T){return new $(T)}}});var Tq=M((Vg,mK)=>{mK.exports=$0;var V1=_1(),MX,Yq=V1.LongBits,hK=V1.base64,_K=V1.utf8;function gT($,Y,T){this.fn=$,this.len=Y,this.next=void 0,this.val=T}function RX(){}function yR($){this.head=$.head,this.tail=$.tail,this.len=$.len,this.next=$.states}function $0(){this.len=0,this.head=new gT(RX,0,0),this.tail=this.head,this.states=null}var gK=function(){return V1.Buffer?function(){return($0.create=function(){return new MX})()}:function(){return new $0}};$0.create=gK();$0.alloc=function(Y){return new V1.Array(Y)};if(V1.Array!==Array)$0.alloc=V1.pool($0.alloc,V1.Array.prototype.subarray);$0.prototype._push=function(Y,T,q){return this.tail=this.tail.next=new gT(Y,T,q),this.len+=T,this};function OX($,Y,T){Y[T]=$&255}function jR($,Y,T){while($>127)Y[T++]=$&127|128,$>>>=7;Y[T]=$}function PX($,Y){this.len=$,this.next=void 0,this.val=Y}PX.prototype=Object.create(gT.prototype);PX.prototype.fn=jR;$0.prototype.uint32=function(Y){return this.len+=(this.tail=this.tail.next=new PX((Y=Y>>>0)<128?1:Y<16384?2:Y<2097152?3:Y<268435456?4:5,Y)).len,this};$0.prototype.int32=function(Y){return Y<0?this._push(LX,10,Yq.fromNumber(Y)):this.uint32(Y)};$0.prototype.sint32=function(Y){return this.uint32((Y<<1^Y>>31)>>>0)};function LX($,Y,T){while($.hi)Y[T++]=$.lo&127|128,$.lo=($.lo>>>7|$.hi<<25)>>>0,$.hi>>>=7;while($.lo>127)Y[T++]=$.lo&127|128,$.lo=$.lo>>>7;Y[T++]=$.lo}$0.prototype.uint64=function(Y){var T=Yq.from(Y);return this._push(LX,T.length(),T)};$0.prototype.int64=$0.prototype.uint64;$0.prototype.sint64=function(Y){var T=Yq.from(Y).zzEncode();return this._push(LX,T.length(),T)};$0.prototype.bool=function(Y){return this._push(OX,1,Y?1:0)};function BX($,Y,T){Y[T]=$&255,Y[T+1]=$>>>8&255,Y[T+2]=$>>>16&255,Y[T+3]=$>>>24}$0.prototype.fixed32=function(Y){return this._push(BX,4,Y>>>0)};$0.prototype.sfixed32=$0.prototype.fixed32;$0.prototype.fixed64=function(Y){var T=Yq.from(Y);return this._push(BX,4,T.lo)._push(BX,4,T.hi)};$0.prototype.sfixed64=$0.prototype.fixed64;$0.prototype.float=function(Y){return this._push(V1.float.writeFloatLE,4,Y)};$0.prototype.double=function(Y){return this._push(V1.float.writeDoubleLE,8,Y)};var vR=V1.Array.prototype.set?function(Y,T,q){T.set(Y,q)}:function(Y,T,q){for(var X=0;X<Y.length;++X)T[q+X]=Y[X]};$0.prototype.bytes=function(Y){var T=Y.length>>>0;if(!T)return this._push(OX,1,0);if(V1.isString(Y)){var q=$0.alloc(T=hK.length(Y));hK.decode(Y,q,0),Y=q}return this.uint32(T)._push(vR,T,Y)};$0.prototype.string=function(Y){var T=_K.length(Y);return T?this.uint32(T)._push(_K.write,T,Y):this._push(OX,1,0)};$0.prototype.fork=function(){return this.states=new yR(this),this.head=this.tail=new gT(RX,0,0),this.len=0,this};$0.prototype.reset=function(){if(this.states)this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next;else this.head=this.tail=new gT(RX,0,0),this.len=0;return this};$0.prototype.ldelim=function(){var Y=this.head,T=this.tail,q=this.len;if(this.reset().uint32(q),q)this.tail.next=Y.next,this.tail=T,this.len+=q;return this};$0.prototype.finish=function(){var Y=this.head.next,T=this.constructor.alloc(this.len),q=0;while(Y)Y.fn(Y.val,T,q),q+=Y.len,Y=Y.next;return T};$0._configure=function($){MX=$,$0.create=gK(),MX._configure()}});var uK=M((Dg,bK)=>{bK.exports=g1;var fK=Tq();(g1.prototype=Object.create(fK.prototype)).constructor=g1;var O$=_1();function g1(){fK.call(this)}g1._configure=function(){g1.alloc=O$._Buffer_allocUnsafe,g1.writeBytesBuffer=O$.Buffer&&O$.Buffer.prototype instanceof Uint8Array&&O$.Buffer.prototype.set.name==="set"?function(Y,T,q){T.set(Y,q)}:function(Y,T,q){if(Y.copy)Y.copy(T,q,0,Y.length);else for(var X=0;X<Y.length;)T[q++]=Y[X++]}};g1.prototype.bytes=function(Y){if(O$.isString(Y))Y=O$._Buffer_from(Y,"base64");var T=Y.length>>>0;if(this.uint32(T),T)this._push(g1.writeBytesBuffer,T,Y);return this};function xR($,Y,T){if($.length<40)O$.utf8.write($,Y,T);else if(Y.utf8Write)Y.utf8Write($,T);else Y.write($,T)}g1.prototype.string=function(Y){var T=O$.Buffer.byteLength(Y);if(this.uint32(T),T)this._push(xR,T,Y);return this};g1._configure()});var Xq=M((Fg,nK)=>{nK.exports=D0;var P1=_1(),SX,pK=P1.LongBits,kR=P1.utf8;function L1($,Y){return RangeError("index out of range: "+$.pos+" + "+(Y||1)+" > "+$.len)}function D0($){this.buf=$,this.pos=0,this.len=$.length}var dK=typeof Uint8Array<"u"?function(Y){if(Y instanceof Uint8Array||Array.isArray(Y))return new D0(Y);throw Error("illegal buffer")}:function(Y){if(Array.isArray(Y))return new D0(Y);throw Error("illegal buffer")},lK=function(){return P1.Buffer?function(T){return(D0.create=function(X){return P1.Buffer.isBuffer(X)?new SX(X):dK(X)})(T)}:dK};D0.create=lK();D0.prototype._slice=P1.Array.prototype.subarray||P1.Array.prototype.slice;D0.prototype.uint32=function(){var Y=4294967295;return function(){if(Y=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128)return Y;if((this.pos+=5)>this.len)throw this.pos=this.len,L1(this,10);return Y}}();D0.prototype.int32=function(){return this.uint32()|0};D0.prototype.sint32=function(){var Y=this.uint32();return Y>>>1^-(Y&1)|0};function wX(){var $=new pK(0,0),Y=0;if(this.len-this.pos>4){for(;Y<4;++Y)if($.lo=($.lo|(this.buf[this.pos]&127)<<Y*7)>>>0,this.buf[this.pos++]<128)return $;if($.lo=($.lo|(this.buf[this.pos]&127)<<28)>>>0,$.hi=($.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return $;Y=0}else{for(;Y<3;++Y){if(this.pos>=this.len)throw L1(this);if($.lo=($.lo|(this.buf[this.pos]&127)<<Y*7)>>>0,this.buf[this.pos++]<128)return $}return $.lo=($.lo|(this.buf[this.pos++]&127)<<Y*7)>>>0,$}if(this.len-this.pos>4){for(;Y<5;++Y)if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}else for(;Y<5;++Y){if(this.pos>=this.len)throw L1(this);if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}throw Error("invalid varint encoding")}D0.prototype.bool=function(){return this.uint32()!==0};function qq($,Y){return($[Y-4]|$[Y-3]<<8|$[Y-2]<<16|$[Y-1]<<24)>>>0}D0.prototype.fixed32=function(){if(this.pos+4>this.len)throw L1(this,4);return qq(this.buf,this.pos+=4)};D0.prototype.sfixed32=function(){if(this.pos+4>this.len)throw L1(this,4);return qq(this.buf,this.pos+=4)|0};function cK(){if(this.pos+8>this.len)throw L1(this,8);return new pK(qq(this.buf,this.pos+=4),qq(this.buf,this.pos+=4))}D0.prototype.float=function(){if(this.pos+4>this.len)throw L1(this,4);var Y=P1.float.readFloatLE(this.buf,this.pos);return this.pos+=4,Y};D0.prototype.double=function(){if(this.pos+8>this.len)throw L1(this,4);var Y=P1.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,Y};D0.prototype.bytes=function(){var Y=this.uint32(),T=this.pos,q=this.pos+Y;if(q>this.len)throw L1(this,Y);if(this.pos+=Y,Array.isArray(this.buf))return this.buf.slice(T,q);if(T===q){var X=P1.Buffer;return X?X.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,T,q)};D0.prototype.string=function(){var Y=this.bytes();return kR.read(Y,0,Y.length)};D0.prototype.skip=function(Y){if(typeof Y==="number"){if(this.pos+Y>this.len)throw L1(this,Y);this.pos+=Y}else do if(this.pos>=this.len)throw L1(this);while(this.buf[this.pos++]&128);return this};D0.prototype.skipType=function($){switch($){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:while(($=this.uint32()&7)!==4)this.skipType($);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+$+" at offset "+this.pos)}return this};D0._configure=function($){SX=$,D0.create=lK(),SX._configure();var Y=P1.Long?"toLong":"toNumber";P1.merge(D0.prototype,{int64:function(){return wX.call(this)[Y](!1)},uint64:function(){return wX.call(this)[Y](!0)},sint64:function(){return wX.call(this).zzDecode()[Y](!1)},fixed64:function(){return cK.call(this)[Y](!0)},sfixed64:function(){return cK.call(this)[Y](!1)}})}});var oK=M((Ng,aK)=>{aK.exports=i$;var rK=Xq();(i$.prototype=Object.create(rK.prototype)).constructor=i$;var iK=_1();function i$($){rK.call(this,$)}i$._configure=function(){if(iK.Buffer)i$.prototype._slice=iK.Buffer.prototype.slice};i$.prototype.string=function(){var Y=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+Y,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+Y,this.len))};i$._configure()});var tK=M((Hg,sK)=>{sK.exports=mT;var CX=_1();(mT.prototype=Object.create(CX.EventEmitter.prototype)).constructor=mT;function mT($,Y,T){if(typeof $!=="function")throw TypeError("rpcImpl must be a function");CX.EventEmitter.call(this),this.rpcImpl=$,this.requestDelimited=Boolean(Y),this.responseDelimited=Boolean(T)}mT.prototype.rpcCall=function $(Y,T,q,X,J){if(!X)throw TypeError("request must be specified");var Q=this;if(!J)return CX.asPromise($,Q,Y,T,q,X);if(!Q.rpcImpl){setTimeout(function(){J(Error("already ended"))},0);return}try{return Q.rpcImpl(Y,T[Q.requestDelimited?"encodeDelimited":"encode"](X).finish(),function(Z,K){if(Z)return Q.emit("error",Z,Y),J(Z);if(K===null){Q.end(!0);return}if(!(K instanceof q))try{K=q[Q.responseDelimited?"decodeDelimited":"decode"](K)}catch(A){return Q.emit("error",A,Y),J(A)}return Q.emit("data",K,Y),J(null,K)})}catch(U){Q.emit("error",U,Y),setTimeout(function(){J(U)},0);return}};mT.prototype.end=function(Y){if(this.rpcImpl){if(!Y)this.rpcImpl(null,null,null);this.rpcImpl=null,this.emit("end").off()}return this}});var yX=M((eK)=>{var hR=eK;hR.Service=tK()});var jX=M((Ig,$A)=>{$A.exports={}});var qA=M((TA)=>{var a0=TA;a0.build="minimal";a0.Writer=Tq();a0.BufferWriter=uK();a0.Reader=Xq();a0.BufferReader=oK();a0.util=_1();a0.rpc=yX();a0.roots=jX();a0.configure=YA;function YA(){a0.util._configure(),a0.Writer._configure(a0.BufferWriter),a0.Reader._configure(a0.BufferReader)}YA()});var JA=M((Bg,XA)=>{XA.exports=vX;function vX($,Y){if(typeof $==="string")Y=$,$=void 0;var T=[];function q(J){if(typeof J!=="string"){var Q=X();if(vX.verbose)console.log("codegen: "+Q);if(Q="return "+Q,J){var U=Object.keys(J),Z=Array(U.length+1),K=Array(U.length),A=0;while(A<U.length)Z[A]=U[A],K[A]=J[U[A++]];return Z[A]=Q,Function.apply(null,Z).apply(null,K)}return Function(Q)()}var W=Array(arguments.length-1),E=0;while(E<W.length)W[E]=arguments[++E];if(E=0,J=J.replace(/%([%dfijs])/g,function(F,H){var V=W[E++];switch(H){case"d":case"f":return String(Number(V));case"i":return String(Math.floor(V));case"j":return JSON.stringify(V);case"s":return String(V)}return"%"}),E!==W.length)throw Error("parameter count mismatch");return T.push(J),q}function X(J){return"function "+(J||Y||"")+"("+($&&$.join(",")||"")+`){
|
|
5
|
+
`))||"no stack trace available"}class bZ{constructor($,Y,T={}){var q,X;if(T=Object.assign({},T),this[SY]=(q=T.interceptors)!==null&&q!==void 0?q:[],delete T.interceptors,this[CY]=(X=T.interceptor_providers)!==null&&X!==void 0?X:[],delete T.interceptor_providers,this[SY].length>0&&this[CY].length>0)throw Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if(this[T$]=T.callInvocationTransformer,delete T.callInvocationTransformer,T.channelOverride)this[O1]=T.channelOverride;else if(T.channelFactoryOverride){let J=T.channelFactoryOverride;delete T.channelFactoryOverride,this[O1]=J($,Y,T)}else this[O1]=new wB.ChannelImplementation($,Y,T)}close(){this[O1].close()}getChannel(){return this[O1]}waitForReady($,Y){let T=(q)=>{if(q){Y(Error("Failed to connect before the deadline"));return}let X;try{X=this[O1].getConnectivityState(!0)}catch(J){Y(Error("The channel has been closed"));return}if(X===SB.ConnectivityState.READY)Y();else try{this[O1].watchConnectivityState(X,$,T)}catch(J){Y(Error("The channel has been closed"))}};setImmediate(T)}checkOptionalUnaryResponseArguments($,Y,T){if(KX($))return{metadata:new wY.Metadata,options:{},callback:$};else if(KX(Y))if($ instanceof wY.Metadata)return{metadata:$,options:{},callback:Y};else return{metadata:new wY.Metadata,options:$,callback:Y};else{if(!($ instanceof wY.Metadata&&Y instanceof Object&&KX(T)))throw Error("Incorrect arguments passed");return{metadata:$,options:Y,callback:T}}}makeUnaryRequest($,Y,T,q,X,J,Q){var U,Z;let K=this.checkOptionalUnaryResponseArguments(X,J,Q),A={path:$,requestStream:!1,responseStream:!1,requestSerialize:Y,responseDeserialize:T},W={argument:q,metadata:K.metadata,call:new h1.ClientUnaryCallImpl,channel:this[O1],methodDefinition:A,callOptions:K.options,callback:K.callback};if(this[T$])W=this[T$](W);let E=W.call,V={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(U=W.callOptions.interceptors)!==null&&U!==void 0?U:[],callInterceptorProviders:(Z=W.callOptions.interceptor_providers)!==null&&Z!==void 0?Z:[]},F=(0,a8.getInterceptingCall)(V,W.methodDefinition,W.callOptions,W.channel);E.call=F;let H=null,D=!1,I=Error();return F.start(W.metadata,{onReceiveMetadata:(S)=>{E.emit("metadata",S)},onReceiveMessage(S){if(H!==null)F.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");H=S},onReceiveStatus(S){if(D)return;if(D=!0,S.code===B$.Status.OK)if(H===null){let v=yY(I);W.callback((0,h1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:S.metadata},v))}else W.callback(null,H);else{let v=yY(I);W.callback((0,h1.callErrorFromStatus)(S,v))}I=null,E.emit("status",S)}}),F.sendMessage(q),F.halfClose(),E}makeClientStreamRequest($,Y,T,q,X,J){var Q,U;let Z=this.checkOptionalUnaryResponseArguments(q,X,J),K={path:$,requestStream:!0,responseStream:!1,requestSerialize:Y,responseDeserialize:T},A={metadata:Z.metadata,call:new h1.ClientWritableStreamImpl(Y),channel:this[O1],methodDefinition:K,callOptions:Z.options,callback:Z.callback};if(this[T$])A=this[T$](A);let W=A.call,E={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},V=(0,a8.getInterceptingCall)(E,A.methodDefinition,A.callOptions,A.channel);W.call=V;let F=null,H=!1,D=Error();return V.start(A.metadata,{onReceiveMetadata:(I)=>{W.emit("metadata",I)},onReceiveMessage(I){if(F!==null)V.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");F=I,V.startRead()},onReceiveStatus(I){if(H)return;if(H=!0,I.code===B$.Status.OK)if(F===null){let S=yY(D);A.callback((0,h1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:I.metadata},S))}else A.callback(null,F);else{let S=yY(D);A.callback((0,h1.callErrorFromStatus)(I,S))}D=null,W.emit("status",I)}}),W}checkMetadataAndOptions($,Y){let T,q;if($ instanceof wY.Metadata)if(T=$,Y)q=Y;else q={};else{if($)q=$;else q={};T=new wY.Metadata}return{metadata:T,options:q}}makeServerStreamRequest($,Y,T,q,X,J){var Q,U;let Z=this.checkMetadataAndOptions(X,J),K={path:$,requestStream:!1,responseStream:!0,requestSerialize:Y,responseDeserialize:T},A={argument:q,metadata:Z.metadata,call:new h1.ClientReadableStreamImpl(T),channel:this[O1],methodDefinition:K,callOptions:Z.options};if(this[T$])A=this[T$](A);let W=A.call,E={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},V=(0,a8.getInterceptingCall)(E,A.methodDefinition,A.callOptions,A.channel);W.call=V;let F=!1,H=Error();return V.start(A.metadata,{onReceiveMetadata(D){W.emit("metadata",D)},onReceiveMessage(D){W.push(D)},onReceiveStatus(D){if(F)return;if(F=!0,W.push(null),D.code!==B$.Status.OK){let I=yY(H);W.emit("error",(0,h1.callErrorFromStatus)(D,I))}H=null,W.emit("status",D)}}),V.sendMessage(q),V.halfClose(),W}makeBidiStreamRequest($,Y,T,q,X){var J,Q;let U=this.checkMetadataAndOptions(q,X),Z={path:$,requestStream:!0,responseStream:!0,requestSerialize:Y,responseDeserialize:T},K={metadata:U.metadata,call:new h1.ClientDuplexStreamImpl(Y,T),channel:this[O1],methodDefinition:Z,callOptions:U.options};if(this[T$])K=this[T$](K);let A=K.call,W={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(J=K.callOptions.interceptors)!==null&&J!==void 0?J:[],callInterceptorProviders:(Q=K.callOptions.interceptor_providers)!==null&&Q!==void 0?Q:[]},E=(0,a8.getInterceptingCall)(W,K.methodDefinition,K.callOptions,K.channel);A.call=E;let V=!1,F=Error();return E.start(K.metadata,{onReceiveMetadata(H){A.emit("metadata",H)},onReceiveMessage(H){A.push(H)},onReceiveStatus(H){if(V)return;if(V=!0,A.push(null),H.code!==B$.Status.OK){let D=yY(F);A.emit("error",(0,h1.callErrorFromStatus)(H,D))}F=null,A.emit("status",H)}}),A}}uZ.Client=bZ});var o8=B((pZ)=>{Object.defineProperty(pZ,"__esModule",{value:!0});pZ.makeClientConstructor=cZ;pZ.loadPackageDefinition=vB;var h6=AX(),CB={unary:h6.Client.prototype.makeUnaryRequest,server_stream:h6.Client.prototype.makeServerStreamRequest,client_stream:h6.Client.prototype.makeClientStreamRequest,bidi:h6.Client.prototype.makeBidiStreamRequest};function GX($){return["__proto__","prototype","constructor"].includes($)}function cZ($,Y,T){if(!T)T={};class q extends h6.Client{}return Object.keys($).forEach((X)=>{if(GX(X))return;let J=$[X],Q;if(typeof X==="string"&&X.charAt(0)==="$")throw Error("Method names cannot start with $");if(J.requestStream)if(J.responseStream)Q="bidi";else Q="client_stream";else if(J.responseStream)Q="server_stream";else Q="unary";let{requestSerialize:U,responseDeserialize:Z}=J,K=yB(CB[Q],J.path,U,Z);if(q.prototype[X]=K,Object.assign(q.prototype[X],J),J.originalName&&!GX(J.originalName))q.prototype[J.originalName]=q.prototype[X]}),q.service=$,q.serviceName=Y,q}function yB($,Y,T,q){return function(...X){return $.call(this,Y,T,q,...X)}}function jB($){return"format"in $}function vB($){let Y={};for(let T in $)if(Object.prototype.hasOwnProperty.call($,T)){let q=$[T],X=T.split(".");if(X.some((U)=>GX(U)))continue;let J=X[X.length-1],Q=Y;for(let U of X.slice(0,-1)){if(!Q[U])Q[U]={};Q=Q[U]}if(jB(q))Q[J]=q;else Q[J]=cZ(q,J,{})}return Y}});var DK=B((Wg,VK)=>{var hB=1/0,_B="[object Symbol]",gB=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,mB=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,t8="\\ud800-\\udfff",tZ="\\u0300-\\u036f\\ufe20-\\ufe23",eZ="\\u20d0-\\u20f0",$K="\\u2700-\\u27bf",YK="a-z\\xdf-\\xf6\\xf8-\\xff",fB="\\xac\\xb1\\xd7\\xf7",bB="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",uB="\\u2000-\\u206f",dB=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",TK="A-Z\\xc0-\\xd6\\xd8-\\xde",qK="\\ufe0e\\ufe0f",XK=fB+bB+uB+dB,VX="['’]",cB="["+t8+"]",lZ="["+XK+"]",s8="["+tZ+eZ+"]",JK="\\d+",pB="["+$K+"]",QK="["+YK+"]",UK="[^"+t8+XK+JK+$K+YK+TK+"]",EX="\\ud83c[\\udffb-\\udfff]",lB="(?:"+s8+"|"+EX+")",ZK="[^"+t8+"]",DX="(?:\\ud83c[\\udde6-\\uddff]){2}",FX="[\\ud800-\\udbff][\\udc00-\\udfff]",jY="["+TK+"]",KK="\\u200d",nZ="(?:"+QK+"|"+UK+")",nB="(?:"+jY+"|"+UK+")",iZ="(?:"+VX+"(?:d|ll|m|re|s|t|ve))?",rZ="(?:"+VX+"(?:D|LL|M|RE|S|T|VE))?",AK=lB+"?",WK="["+qK+"]?",iB="(?:"+KK+"(?:"+[ZK,DX,FX].join("|")+")"+WK+AK+")*",GK=WK+AK+iB,rB="(?:"+[pB,DX,FX].join("|")+")"+GK,aB="(?:"+[ZK+s8+"?",s8,DX,FX,cB].join("|")+")",oB=RegExp(VX,"g"),sB=RegExp(s8,"g"),tB=RegExp(EX+"(?="+EX+")|"+aB+GK,"g"),eB=RegExp([jY+"?"+QK+"+"+iZ+"(?="+[lZ,jY,"$"].join("|")+")",nB+"+"+rZ+"(?="+[lZ,jY+nZ,"$"].join("|")+")",jY+"?"+nZ+"+"+iZ,jY+"+"+rZ,JK,rB].join("|"),"g"),$R=RegExp("["+KK+t8+tZ+eZ+qK+"]"),YR=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,TR={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"ss"},qR=typeof global=="object"&&global&&global.Object===Object&&global,XR=typeof self=="object"&&self&&self.Object===Object&&self,JR=qR||XR||Function("return this")();function QR($,Y,T,q){var X=-1,J=$?$.length:0;if(q&&J)T=$[++X];while(++X<J)T=Y(T,$[X],X,$);return T}function UR($){return $.split("")}function ZR($){return $.match(gB)||[]}function KR($){return function(Y){return $==null?void 0:$[Y]}}var AR=KR(TR);function EK($){return $R.test($)}function WR($){return YR.test($)}function GR($){return EK($)?ER($):UR($)}function ER($){return $.match(tB)||[]}function VR($){return $.match(eB)||[]}var DR=Object.prototype,FR=DR.toString,aZ=JR.Symbol,oZ=aZ?aZ.prototype:void 0,sZ=oZ?oZ.toString:void 0;function NR($,Y,T){var q=-1,X=$.length;if(Y<0)Y=-Y>X?0:X+Y;if(T=T>X?X:T,T<0)T+=X;X=Y>T?0:T-Y>>>0,Y>>>=0;var J=Array(X);while(++q<X)J[q]=$[q+Y];return J}function HR($){if(typeof $=="string")return $;if(RR($))return sZ?sZ.call($):"";var Y=$+"";return Y=="0"&&1/$==-hB?"-0":Y}function zR($,Y,T){var q=$.length;return T=T===void 0?q:T,!Y&&T>=q?$:NR($,Y,T)}function IR($){return function(Y){Y=e8(Y);var T=EK(Y)?GR(Y):void 0,q=T?T[0]:Y.charAt(0),X=T?zR(T,1).join(""):Y.slice(1);return q[$]()+X}}function MR($){return function(Y){return QR(SR(LR(Y).replace(oB,"")),$,"")}}function BR($){return!!$&&typeof $=="object"}function RR($){return typeof $=="symbol"||BR($)&&FR.call($)==_B}function e8($){return $==null?"":HR($)}var OR=MR(function($,Y,T){return Y=Y.toLowerCase(),$+(T?PR(Y):Y)});function PR($){return wR(e8($).toLowerCase())}function LR($){return $=e8($),$&&$.replace(mB,AR).replace(sB,"")}var wR=IR("toUpperCase");function SR($,Y,T){if($=e8($),Y=T?void 0:Y,Y===void 0)return WR($)?VR($):ZR($);return $.match(Y)||[]}VK.exports=OR});var NX=B((Gg,FK)=>{FK.exports=CR;function CR($,Y){var T=Array(arguments.length-1),q=0,X=2,J=!0;while(X<arguments.length)T[q++]=arguments[X++];return new Promise(function(U,Z){T[q]=function(A){if(J)if(J=!1,A)Z(A);else{var W=Array(arguments.length-1),E=0;while(E<W.length)W[E++]=arguments[E];U.apply(null,W)}};try{$.apply(Y||null,T)}catch(K){if(J)J=!1,Z(K)}})}});var IK=B((zK)=>{var $q=zK;$q.length=function(Y){var T=Y.length;if(!T)return 0;var q=0;while(--T%4>1&&Y.charAt(T)==="=")++q;return Math.ceil(Y.length*3)/4-q};var vY=Array(64),HK=Array(123);for(E1=0;E1<64;)HK[vY[E1]=E1<26?E1+65:E1<52?E1+71:E1<62?E1-4:E1-59|43]=E1++;var E1;$q.encode=function(Y,T,q){var X=null,J=[],Q=0,U=0,Z;while(T<q){var K=Y[T++];switch(U){case 0:J[Q++]=vY[K>>2],Z=(K&3)<<4,U=1;break;case 1:J[Q++]=vY[Z|K>>4],Z=(K&15)<<2,U=2;break;case 2:J[Q++]=vY[Z|K>>6],J[Q++]=vY[K&63],U=0;break}if(Q>8191)(X||(X=[])).push(String.fromCharCode.apply(String,J)),Q=0}if(U){if(J[Q++]=vY[Z],J[Q++]=61,U===1)J[Q++]=61}if(X){if(Q)X.push(String.fromCharCode.apply(String,J.slice(0,Q)));return X.join("")}return String.fromCharCode.apply(String,J.slice(0,Q))};var NK="invalid encoding";$q.decode=function(Y,T,q){var X=q,J=0,Q;for(var U=0;U<Y.length;){var Z=Y.charCodeAt(U++);if(Z===61&&J>1)break;if((Z=HK[Z])===void 0)throw Error(NK);switch(J){case 0:Q=Z,J=1;break;case 1:T[q++]=Q<<2|(Z&48)>>4,Q=Z,J=2;break;case 2:T[q++]=(Q&15)<<4|(Z&60)>>2,Q=Z,J=3;break;case 3:T[q++]=(Q&3)<<6|Z,J=0;break}}if(J===1)throw Error(NK);return q-X};$q.test=function(Y){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Y)}});var BK=B((Vg,MK)=>{MK.exports=Yq;function Yq(){this._listeners={}}Yq.prototype.on=function(Y,T,q){return(this._listeners[Y]||(this._listeners[Y]=[])).push({fn:T,ctx:q||this}),this};Yq.prototype.off=function(Y,T){if(Y===void 0)this._listeners={};else if(T===void 0)this._listeners[Y]=[];else{var q=this._listeners[Y];for(var X=0;X<q.length;)if(q[X].fn===T)q.splice(X,1);else++X}return this};Yq.prototype.emit=function(Y){var T=this._listeners[Y];if(T){var q=[],X=1;for(;X<arguments.length;)q.push(arguments[X++]);for(X=0;X<T.length;)T[X].fn.apply(T[X++].ctx,q)}return this}});var CK=B((Dg,SK)=>{SK.exports=RK(RK);function RK($){if(typeof Float32Array<"u")(function(){var Y=new Float32Array([-0]),T=new Uint8Array(Y.buffer),q=T[3]===128;function X(Z,K,A){Y[0]=Z,K[A]=T[0],K[A+1]=T[1],K[A+2]=T[2],K[A+3]=T[3]}function J(Z,K,A){Y[0]=Z,K[A]=T[3],K[A+1]=T[2],K[A+2]=T[1],K[A+3]=T[0]}$.writeFloatLE=q?X:J,$.writeFloatBE=q?J:X;function Q(Z,K){return T[0]=Z[K],T[1]=Z[K+1],T[2]=Z[K+2],T[3]=Z[K+3],Y[0]}function U(Z,K){return T[3]=Z[K],T[2]=Z[K+1],T[1]=Z[K+2],T[0]=Z[K+3],Y[0]}$.readFloatLE=q?Q:U,$.readFloatBE=q?U:Q})();else(function(){function Y(q,X,J,Q){var U=X<0?1:0;if(U)X=-X;if(X===0)q(1/X>0?0:2147483648,J,Q);else if(isNaN(X))q(2143289344,J,Q);else if(X>340282346638528860000000000000000000000)q((U<<31|2139095040)>>>0,J,Q);else if(X<0.000000000000000000000000000000000000011754943508222875)q((U<<31|Math.round(X/0.000000000000000000000000000000000000000000001401298464324817))>>>0,J,Q);else{var Z=Math.floor(Math.log(X)/Math.LN2),K=Math.round(X*Math.pow(2,-Z)*8388608)&8388607;q((U<<31|Z+127<<23|K)>>>0,J,Q)}}$.writeFloatLE=Y.bind(null,OK),$.writeFloatBE=Y.bind(null,PK);function T(q,X,J){var Q=q(X,J),U=(Q>>31)*2+1,Z=Q>>>23&255,K=Q&8388607;return Z===255?K?NaN:U*(1/0):Z===0?U*0.000000000000000000000000000000000000000000001401298464324817*K:U*Math.pow(2,Z-150)*(K+8388608)}$.readFloatLE=T.bind(null,LK),$.readFloatBE=T.bind(null,wK)})();if(typeof Float64Array<"u")(function(){var Y=new Float64Array([-0]),T=new Uint8Array(Y.buffer),q=T[7]===128;function X(Z,K,A){Y[0]=Z,K[A]=T[0],K[A+1]=T[1],K[A+2]=T[2],K[A+3]=T[3],K[A+4]=T[4],K[A+5]=T[5],K[A+6]=T[6],K[A+7]=T[7]}function J(Z,K,A){Y[0]=Z,K[A]=T[7],K[A+1]=T[6],K[A+2]=T[5],K[A+3]=T[4],K[A+4]=T[3],K[A+5]=T[2],K[A+6]=T[1],K[A+7]=T[0]}$.writeDoubleLE=q?X:J,$.writeDoubleBE=q?J:X;function Q(Z,K){return T[0]=Z[K],T[1]=Z[K+1],T[2]=Z[K+2],T[3]=Z[K+3],T[4]=Z[K+4],T[5]=Z[K+5],T[6]=Z[K+6],T[7]=Z[K+7],Y[0]}function U(Z,K){return T[7]=Z[K],T[6]=Z[K+1],T[5]=Z[K+2],T[4]=Z[K+3],T[3]=Z[K+4],T[2]=Z[K+5],T[1]=Z[K+6],T[0]=Z[K+7],Y[0]}$.readDoubleLE=q?Q:U,$.readDoubleBE=q?U:Q})();else(function(){function Y(q,X,J,Q,U,Z){var K=Q<0?1:0;if(K)Q=-Q;if(Q===0)q(0,U,Z+X),q(1/Q>0?0:2147483648,U,Z+J);else if(isNaN(Q))q(0,U,Z+X),q(2146959360,U,Z+J);else if(Q>179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)q(0,U,Z+X),q((K<<31|2146435072)>>>0,U,Z+J);else{var A;if(Q<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014)A=Q/0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005,q(A>>>0,U,Z+X),q((K<<31|A/4294967296)>>>0,U,Z+J);else{var W=Math.floor(Math.log(Q)/Math.LN2);if(W===1024)W=1023;A=Q*Math.pow(2,-W),q(A*4503599627370496>>>0,U,Z+X),q((K<<31|W+1023<<20|A*1048576&1048575)>>>0,U,Z+J)}}}$.writeDoubleLE=Y.bind(null,OK,0,4),$.writeDoubleBE=Y.bind(null,PK,4,0);function T(q,X,J,Q,U){var Z=q(Q,U+X),K=q(Q,U+J),A=(K>>31)*2+1,W=K>>>20&2047,E=4294967296*(K&1048575)+Z;return W===2047?E?NaN:A*(1/0):W===0?A*0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005*E:A*Math.pow(2,W-1075)*(E+4503599627370496)}$.readDoubleLE=T.bind(null,LK,0,4),$.readDoubleBE=T.bind(null,wK,4,0)})();return $}function OK($,Y,T){Y[T]=$&255,Y[T+1]=$>>>8&255,Y[T+2]=$>>>16&255,Y[T+3]=$>>>24}function PK($,Y,T){Y[T]=$>>>24,Y[T+1]=$>>>16&255,Y[T+2]=$>>>8&255,Y[T+3]=$&255}function LK($,Y){return($[Y]|$[Y+1]<<8|$[Y+2]<<16|$[Y+3]<<24)>>>0}function wK($,Y){return($[Y]<<24|$[Y+1]<<16|$[Y+2]<<8|$[Y+3])>>>0}});var zX=B((yK,HX)=>{HX.exports=yR;function yR(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch($){}return null}});var vK=B((jK)=>{var IX=jK;IX.length=function(Y){var T=0,q=0;for(var X=0;X<Y.length;++X)if(q=Y.charCodeAt(X),q<128)T+=1;else if(q<2048)T+=2;else if((q&64512)===55296&&(Y.charCodeAt(X+1)&64512)===56320)++X,T+=4;else T+=3;return T};IX.read=function(Y,T,q){var X=q-T;if(X<1)return"";var J=null,Q=[],U=0,Z;while(T<q){if(Z=Y[T++],Z<128)Q[U++]=Z;else if(Z>191&&Z<224)Q[U++]=(Z&31)<<6|Y[T++]&63;else if(Z>239&&Z<365)Z=((Z&7)<<18|(Y[T++]&63)<<12|(Y[T++]&63)<<6|Y[T++]&63)-65536,Q[U++]=55296+(Z>>10),Q[U++]=56320+(Z&1023);else Q[U++]=(Z&15)<<12|(Y[T++]&63)<<6|Y[T++]&63;if(U>8191)(J||(J=[])).push(String.fromCharCode.apply(String,Q)),U=0}if(J){if(U)J.push(String.fromCharCode.apply(String,Q.slice(0,U)));return J.join("")}return String.fromCharCode.apply(String,Q.slice(0,U))};IX.write=function(Y,T,q){var X=q,J,Q;for(var U=0;U<Y.length;++U)if(J=Y.charCodeAt(U),J<128)T[q++]=J;else if(J<2048)T[q++]=J>>6|192,T[q++]=J&63|128;else if((J&64512)===55296&&((Q=Y.charCodeAt(U+1))&64512)===56320)J=65536+((J&1023)<<10)+(Q&1023),++U,T[q++]=J>>18|240,T[q++]=J>>12&63|128,T[q++]=J>>6&63|128,T[q++]=J&63|128;else T[q++]=J>>12|224,T[q++]=J>>6&63|128,T[q++]=J&63|128;return q-X}});var kK=B((Ng,xK)=>{xK.exports=jR;function jR($,Y,T){var q=T||8192,X=q>>>1,J=null,Q=q;return function(Z){if(Z<1||Z>X)return $(Z);if(Q+Z>q)J=$(q),Q=0;var K=Y.call(J,Q,Q+=Z);if(Q&7)Q=(Q|7)+1;return K}}});var _K=B((Hg,hK)=>{hK.exports=L0;var _6=_1();function L0($,Y){this.lo=$>>>0,this.hi=Y>>>0}var n$=L0.zero=new L0(0,0);n$.toNumber=function(){return 0};n$.zzEncode=n$.zzDecode=function(){return this};n$.length=function(){return 1};var vR=L0.zeroHash="\x00\x00\x00\x00\x00\x00\x00\x00";L0.fromNumber=function(Y){if(Y===0)return n$;var T=Y<0;if(T)Y=-Y;var q=Y>>>0,X=(Y-q)/4294967296>>>0;if(T){if(X=~X>>>0,q=~q>>>0,++q>4294967295){if(q=0,++X>4294967295)X=0}}return new L0(q,X)};L0.from=function(Y){if(typeof Y==="number")return L0.fromNumber(Y);if(_6.isString(Y))if(_6.Long)Y=_6.Long.fromString(Y);else return L0.fromNumber(parseInt(Y,10));return Y.low||Y.high?new L0(Y.low>>>0,Y.high>>>0):n$};L0.prototype.toNumber=function(Y){if(!Y&&this.hi>>>31){var T=~this.lo+1>>>0,q=~this.hi>>>0;if(!T)q=q+1>>>0;return-(T+q*4294967296)}return this.lo+this.hi*4294967296};L0.prototype.toLong=function(Y){return _6.Long?new _6.Long(this.lo|0,this.hi|0,Boolean(Y)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(Y)}};var R$=String.prototype.charCodeAt;L0.fromHash=function(Y){if(Y===vR)return n$;return new L0((R$.call(Y,0)|R$.call(Y,1)<<8|R$.call(Y,2)<<16|R$.call(Y,3)<<24)>>>0,(R$.call(Y,4)|R$.call(Y,5)<<8|R$.call(Y,6)<<16|R$.call(Y,7)<<24)>>>0)};L0.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};L0.prototype.zzEncode=function(){var Y=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^Y)>>>0,this.lo=(this.lo<<1^Y)>>>0,this};L0.prototype.zzDecode=function(){var Y=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^Y)>>>0,this.hi=(this.hi>>>1^Y)>>>0,this};L0.prototype.length=function(){var Y=this.lo,T=(this.lo>>>28|this.hi<<4)>>>0,q=this.hi>>>24;return q===0?T===0?Y<16384?Y<128?1:2:Y<2097152?3:4:T<16384?T<128?5:6:T<2097152?7:8:q<128?9:10}});var _1=B((MX)=>{var g=MX;g.asPromise=NX();g.base64=IK();g.EventEmitter=BK();g.float=CK();g.inquire=zX();g.utf8=vK();g.pool=kK();g.LongBits=_K();g.isNode=Boolean(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);g.global=g.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||MX;g.emptyArray=Object.freeze?Object.freeze([]):[];g.emptyObject=Object.freeze?Object.freeze({}):{};g.isInteger=Number.isInteger||function(Y){return typeof Y==="number"&&isFinite(Y)&&Math.floor(Y)===Y};g.isString=function(Y){return typeof Y==="string"||Y instanceof String};g.isObject=function(Y){return Y&&typeof Y==="object"};g.isset=g.isSet=function(Y,T){var q=Y[T];if(q!=null&&Y.hasOwnProperty(T))return typeof q!=="object"||(Array.isArray(q)?q.length:Object.keys(q).length)>0;return!1};g.Buffer=function(){try{var $=g.inquire("buffer").Buffer;return $.prototype.utf8Write?$:null}catch(Y){return null}}();g._Buffer_from=null;g._Buffer_allocUnsafe=null;g.newBuffer=function(Y){return typeof Y==="number"?g.Buffer?g._Buffer_allocUnsafe(Y):new g.Array(Y):g.Buffer?g._Buffer_from(Y):typeof Uint8Array>"u"?Y:new Uint8Array(Y)};g.Array=typeof Uint8Array<"u"?Uint8Array:Array;g.Long=g.global.dcodeIO&&g.global.dcodeIO.Long||g.global.Long||g.inquire("long");g.key2Re=/^true|false|0|1$/;g.key32Re=/^-?(?:0|[1-9][0-9]*)$/;g.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;g.longToHash=function(Y){return Y?g.LongBits.from(Y).toHash():g.LongBits.zeroHash};g.longFromHash=function(Y,T){var q=g.LongBits.fromHash(Y);if(g.Long)return g.Long.fromBits(q.lo,q.hi,T);return q.toNumber(Boolean(T))};function gK($,Y,T){for(var q=Object.keys(Y),X=0;X<q.length;++X)if($[q[X]]===void 0||!T)$[q[X]]=Y[q[X]];return $}g.merge=gK;g.lcFirst=function(Y){return Y.charAt(0).toLowerCase()+Y.substring(1)};function mK($){function Y(T,q){if(!(this instanceof Y))return new Y(T,q);if(Object.defineProperty(this,"message",{get:function(){return T}}),Error.captureStackTrace)Error.captureStackTrace(this,Y);else Object.defineProperty(this,"stack",{value:Error().stack||""});if(q)gK(this,q)}return Y.prototype=Object.create(Error.prototype,{constructor:{value:Y,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return $},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),Y}g.newError=mK;g.ProtocolError=mK("ProtocolError");g.oneOfGetter=function(Y){var T={};for(var q=0;q<Y.length;++q)T[Y[q]]=1;return function(){for(var X=Object.keys(this),J=X.length-1;J>-1;--J)if(T[X[J]]===1&&this[X[J]]!==void 0&&this[X[J]]!==null)return X[J]}};g.oneOfSetter=function(Y){return function(T){for(var q=0;q<Y.length;++q)if(Y[q]!==T)delete this[Y[q]]}};g.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};g._configure=function(){var $=g.Buffer;if(!$){g._Buffer_from=g._Buffer_allocUnsafe=null;return}g._Buffer_from=$.from!==Uint8Array.from&&$.from||function(T,q){return new $(T,q)},g._Buffer_allocUnsafe=$.allocUnsafe||function(T){return new $(T)}}});var qq=B((Ig,dK)=>{dK.exports=$0;var V1=_1(),BX,Tq=V1.LongBits,fK=V1.base64,bK=V1.utf8;function g6($,Y,T){this.fn=$,this.len=Y,this.next=void 0,this.val=T}function OX(){}function xR($){this.head=$.head,this.tail=$.tail,this.len=$.len,this.next=$.states}function $0(){this.len=0,this.head=new g6(OX,0,0),this.tail=this.head,this.states=null}var uK=function(){return V1.Buffer?function(){return($0.create=function(){return new BX})()}:function(){return new $0}};$0.create=uK();$0.alloc=function(Y){return new V1.Array(Y)};if(V1.Array!==Array)$0.alloc=V1.pool($0.alloc,V1.Array.prototype.subarray);$0.prototype._push=function(Y,T,q){return this.tail=this.tail.next=new g6(Y,T,q),this.len+=T,this};function PX($,Y,T){Y[T]=$&255}function kR($,Y,T){while($>127)Y[T++]=$&127|128,$>>>=7;Y[T]=$}function LX($,Y){this.len=$,this.next=void 0,this.val=Y}LX.prototype=Object.create(g6.prototype);LX.prototype.fn=kR;$0.prototype.uint32=function(Y){return this.len+=(this.tail=this.tail.next=new LX((Y=Y>>>0)<128?1:Y<16384?2:Y<2097152?3:Y<268435456?4:5,Y)).len,this};$0.prototype.int32=function(Y){return Y<0?this._push(wX,10,Tq.fromNumber(Y)):this.uint32(Y)};$0.prototype.sint32=function(Y){return this.uint32((Y<<1^Y>>31)>>>0)};function wX($,Y,T){while($.hi)Y[T++]=$.lo&127|128,$.lo=($.lo>>>7|$.hi<<25)>>>0,$.hi>>>=7;while($.lo>127)Y[T++]=$.lo&127|128,$.lo=$.lo>>>7;Y[T++]=$.lo}$0.prototype.uint64=function(Y){var T=Tq.from(Y);return this._push(wX,T.length(),T)};$0.prototype.int64=$0.prototype.uint64;$0.prototype.sint64=function(Y){var T=Tq.from(Y).zzEncode();return this._push(wX,T.length(),T)};$0.prototype.bool=function(Y){return this._push(PX,1,Y?1:0)};function RX($,Y,T){Y[T]=$&255,Y[T+1]=$>>>8&255,Y[T+2]=$>>>16&255,Y[T+3]=$>>>24}$0.prototype.fixed32=function(Y){return this._push(RX,4,Y>>>0)};$0.prototype.sfixed32=$0.prototype.fixed32;$0.prototype.fixed64=function(Y){var T=Tq.from(Y);return this._push(RX,4,T.lo)._push(RX,4,T.hi)};$0.prototype.sfixed64=$0.prototype.fixed64;$0.prototype.float=function(Y){return this._push(V1.float.writeFloatLE,4,Y)};$0.prototype.double=function(Y){return this._push(V1.float.writeDoubleLE,8,Y)};var hR=V1.Array.prototype.set?function(Y,T,q){T.set(Y,q)}:function(Y,T,q){for(var X=0;X<Y.length;++X)T[q+X]=Y[X]};$0.prototype.bytes=function(Y){var T=Y.length>>>0;if(!T)return this._push(PX,1,0);if(V1.isString(Y)){var q=$0.alloc(T=fK.length(Y));fK.decode(Y,q,0),Y=q}return this.uint32(T)._push(hR,T,Y)};$0.prototype.string=function(Y){var T=bK.length(Y);return T?this.uint32(T)._push(bK.write,T,Y):this._push(PX,1,0)};$0.prototype.fork=function(){return this.states=new xR(this),this.head=this.tail=new g6(OX,0,0),this.len=0,this};$0.prototype.reset=function(){if(this.states)this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next;else this.head=this.tail=new g6(OX,0,0),this.len=0;return this};$0.prototype.ldelim=function(){var Y=this.head,T=this.tail,q=this.len;if(this.reset().uint32(q),q)this.tail.next=Y.next,this.tail=T,this.len+=q;return this};$0.prototype.finish=function(){var Y=this.head.next,T=this.constructor.alloc(this.len),q=0;while(Y)Y.fn(Y.val,T,q),q+=Y.len,Y=Y.next;return T};$0._configure=function($){BX=$,$0.create=uK(),BX._configure()}});var lK=B((Mg,pK)=>{pK.exports=g1;var cK=qq();(g1.prototype=Object.create(cK.prototype)).constructor=g1;var O$=_1();function g1(){cK.call(this)}g1._configure=function(){g1.alloc=O$._Buffer_allocUnsafe,g1.writeBytesBuffer=O$.Buffer&&O$.Buffer.prototype instanceof Uint8Array&&O$.Buffer.prototype.set.name==="set"?function(Y,T,q){T.set(Y,q)}:function(Y,T,q){if(Y.copy)Y.copy(T,q,0,Y.length);else for(var X=0;X<Y.length;)T[q++]=Y[X++]}};g1.prototype.bytes=function(Y){if(O$.isString(Y))Y=O$._Buffer_from(Y,"base64");var T=Y.length>>>0;if(this.uint32(T),T)this._push(g1.writeBytesBuffer,T,Y);return this};function _R($,Y,T){if($.length<40)O$.utf8.write($,Y,T);else if(Y.utf8Write)Y.utf8Write($,T);else Y.write($,T)}g1.prototype.string=function(Y){var T=O$.Buffer.byteLength(Y);if(this.uint32(T),T)this._push(_R,T,Y);return this};g1._configure()});var Jq=B((Bg,oK)=>{oK.exports=D0;var P1=_1(),CX,rK=P1.LongBits,gR=P1.utf8;function L1($,Y){return RangeError("index out of range: "+$.pos+" + "+(Y||1)+" > "+$.len)}function D0($){this.buf=$,this.pos=0,this.len=$.length}var nK=typeof Uint8Array<"u"?function(Y){if(Y instanceof Uint8Array||Array.isArray(Y))return new D0(Y);throw Error("illegal buffer")}:function(Y){if(Array.isArray(Y))return new D0(Y);throw Error("illegal buffer")},aK=function(){return P1.Buffer?function(T){return(D0.create=function(X){return P1.Buffer.isBuffer(X)?new CX(X):nK(X)})(T)}:nK};D0.create=aK();D0.prototype._slice=P1.Array.prototype.subarray||P1.Array.prototype.slice;D0.prototype.uint32=function(){var Y=4294967295;return function(){if(Y=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128)return Y;if((this.pos+=5)>this.len)throw this.pos=this.len,L1(this,10);return Y}}();D0.prototype.int32=function(){return this.uint32()|0};D0.prototype.sint32=function(){var Y=this.uint32();return Y>>>1^-(Y&1)|0};function SX(){var $=new rK(0,0),Y=0;if(this.len-this.pos>4){for(;Y<4;++Y)if($.lo=($.lo|(this.buf[this.pos]&127)<<Y*7)>>>0,this.buf[this.pos++]<128)return $;if($.lo=($.lo|(this.buf[this.pos]&127)<<28)>>>0,$.hi=($.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return $;Y=0}else{for(;Y<3;++Y){if(this.pos>=this.len)throw L1(this);if($.lo=($.lo|(this.buf[this.pos]&127)<<Y*7)>>>0,this.buf[this.pos++]<128)return $}return $.lo=($.lo|(this.buf[this.pos++]&127)<<Y*7)>>>0,$}if(this.len-this.pos>4){for(;Y<5;++Y)if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}else for(;Y<5;++Y){if(this.pos>=this.len)throw L1(this);if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}throw Error("invalid varint encoding")}D0.prototype.bool=function(){return this.uint32()!==0};function Xq($,Y){return($[Y-4]|$[Y-3]<<8|$[Y-2]<<16|$[Y-1]<<24)>>>0}D0.prototype.fixed32=function(){if(this.pos+4>this.len)throw L1(this,4);return Xq(this.buf,this.pos+=4)};D0.prototype.sfixed32=function(){if(this.pos+4>this.len)throw L1(this,4);return Xq(this.buf,this.pos+=4)|0};function iK(){if(this.pos+8>this.len)throw L1(this,8);return new rK(Xq(this.buf,this.pos+=4),Xq(this.buf,this.pos+=4))}D0.prototype.float=function(){if(this.pos+4>this.len)throw L1(this,4);var Y=P1.float.readFloatLE(this.buf,this.pos);return this.pos+=4,Y};D0.prototype.double=function(){if(this.pos+8>this.len)throw L1(this,4);var Y=P1.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,Y};D0.prototype.bytes=function(){var Y=this.uint32(),T=this.pos,q=this.pos+Y;if(q>this.len)throw L1(this,Y);if(this.pos+=Y,Array.isArray(this.buf))return this.buf.slice(T,q);if(T===q){var X=P1.Buffer;return X?X.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,T,q)};D0.prototype.string=function(){var Y=this.bytes();return gR.read(Y,0,Y.length)};D0.prototype.skip=function(Y){if(typeof Y==="number"){if(this.pos+Y>this.len)throw L1(this,Y);this.pos+=Y}else do if(this.pos>=this.len)throw L1(this);while(this.buf[this.pos++]&128);return this};D0.prototype.skipType=function($){switch($){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:while(($=this.uint32()&7)!==4)this.skipType($);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+$+" at offset "+this.pos)}return this};D0._configure=function($){CX=$,D0.create=aK(),CX._configure();var Y=P1.Long?"toLong":"toNumber";P1.merge(D0.prototype,{int64:function(){return SX.call(this)[Y](!1)},uint64:function(){return SX.call(this)[Y](!0)},sint64:function(){return SX.call(this).zzDecode()[Y](!1)},fixed64:function(){return iK.call(this)[Y](!0)},sfixed64:function(){return iK.call(this)[Y](!1)}})}});var $A=B((Rg,eK)=>{eK.exports=i$;var tK=Jq();(i$.prototype=Object.create(tK.prototype)).constructor=i$;var sK=_1();function i$($){tK.call(this,$)}i$._configure=function(){if(sK.Buffer)i$.prototype._slice=sK.Buffer.prototype.slice};i$.prototype.string=function(){var Y=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+Y,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+Y,this.len))};i$._configure()});var TA=B((Og,YA)=>{YA.exports=m6;var yX=_1();(m6.prototype=Object.create(yX.EventEmitter.prototype)).constructor=m6;function m6($,Y,T){if(typeof $!=="function")throw TypeError("rpcImpl must be a function");yX.EventEmitter.call(this),this.rpcImpl=$,this.requestDelimited=Boolean(Y),this.responseDelimited=Boolean(T)}m6.prototype.rpcCall=function $(Y,T,q,X,J){if(!X)throw TypeError("request must be specified");var Q=this;if(!J)return yX.asPromise($,Q,Y,T,q,X);if(!Q.rpcImpl){setTimeout(function(){J(Error("already ended"))},0);return}try{return Q.rpcImpl(Y,T[Q.requestDelimited?"encodeDelimited":"encode"](X).finish(),function(Z,K){if(Z)return Q.emit("error",Z,Y),J(Z);if(K===null){Q.end(!0);return}if(!(K instanceof q))try{K=q[Q.responseDelimited?"decodeDelimited":"decode"](K)}catch(A){return Q.emit("error",A,Y),J(A)}return Q.emit("data",K,Y),J(null,K)})}catch(U){Q.emit("error",U,Y),setTimeout(function(){J(U)},0);return}};m6.prototype.end=function(Y){if(this.rpcImpl){if(!Y)this.rpcImpl(null,null,null);this.rpcImpl=null,this.emit("end").off()}return this}});var jX=B((qA)=>{var mR=qA;mR.Service=TA()});var vX=B((Lg,XA)=>{XA.exports={}});var UA=B((QA)=>{var a0=QA;a0.build="minimal";a0.Writer=qq();a0.BufferWriter=lK();a0.Reader=Jq();a0.BufferReader=$A();a0.util=_1();a0.rpc=jX();a0.roots=vX();a0.configure=JA;function JA(){a0.util._configure(),a0.Writer._configure(a0.BufferWriter),a0.Reader._configure(a0.BufferReader)}JA()});var KA=B((Sg,ZA)=>{ZA.exports=xX;function xX($,Y){if(typeof $==="string")Y=$,$=void 0;var T=[];function q(J){if(typeof J!=="string"){var Q=X();if(xX.verbose)console.log("codegen: "+Q);if(Q="return "+Q,J){var U=Object.keys(J),Z=Array(U.length+1),K=Array(U.length),A=0;while(A<U.length)Z[A]=U[A],K[A]=J[U[A++]];return Z[A]=Q,Function.apply(null,Z).apply(null,K)}return Function(Q)()}var W=Array(arguments.length-1),E=0;while(E<W.length)W[E]=arguments[++E];if(E=0,J=J.replace(/%([%dfijs])/g,function(F,H){var D=W[E++];switch(H){case"d":case"f":return String(Number(D));case"i":return String(Math.floor(D));case"j":return JSON.stringify(D);case"s":return String(D)}return"%"}),E!==W.length)throw Error("parameter count mismatch");return T.push(J),q}function X(J){return"function "+(J||Y||"")+"("+($&&$.join(",")||"")+`){
|
|
6
6
|
`+T.join(`
|
|
7
7
|
`)+`
|
|
8
|
-
}`}return q.toString=X,q}vX.verbose=!1});var UA=M((Rg,QA)=>{QA.exports=fT;var _R=FX(),gR=HX(),xX=gR("fs");function fT($,Y,T){if(typeof Y==="function")T=Y,Y={};else if(!Y)Y={};if(!T)return _R(fT,this,$,Y);if(!Y.xhr&&xX&&xX.readFile)return xX.readFile($,function(X,J){return X&&typeof XMLHttpRequest<"u"?fT.xhr($,Y,T):X?T(X):T(null,Y.binary?J:J.toString("utf8"))});return fT.xhr($,Y,T)}fT.xhr=function(Y,T,q){var X=new XMLHttpRequest;if(X.onreadystatechange=function(){if(X.readyState!==4)return;if(X.status!==0&&X.status!==200)return q(Error("status "+X.status));if(T.binary){var Q=X.response;if(!Q){Q=[];for(var U=0;U<X.responseText.length;++U)Q.push(X.responseText.charCodeAt(U)&255)}return q(null,typeof Uint8Array<"u"?new Uint8Array(Q):Q)}return q(null,X.responseText)},T.binary){if("overrideMimeType"in X)X.overrideMimeType("text/plain; charset=x-user-defined");X.responseType="arraybuffer"}X.open("GET",Y),X.send()}});var AA=M((KA)=>{var hX=KA,ZA=hX.isAbsolute=function(Y){return/^(?:\/|\w+:)/.test(Y)},kX=hX.normalize=function(Y){Y=Y.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var T=Y.split("/"),q=ZA(Y),X="";if(q)X=T.shift()+"/";for(var J=0;J<T.length;)if(T[J]==="..")if(J>0&&T[J-1]!=="..")T.splice(--J,2);else if(q)T.splice(J,1);else++J;else if(T[J]===".")T.splice(J,1);else++J;return X+T.join("/")};hX.resolve=function(Y,T,q){if(!q)T=kX(T);if(ZA(T))return T;if(!q)Y=kX(Y);return(Y=Y.replace(/(?:\/|^)[^/]+$/,"")).length?kX(Y+"/"+T):T}});var kY=M((Pg,EA)=>{EA.exports=t;var Jq=L$();((t.prototype=Object.create(Jq.prototype)).constructor=t).className="Namespace";var _X=P$(),Qq=w0(),mR=o$(),r$,xY,a$;t.fromJSON=function(Y,T){return new t(Y,T.options).addJSON(T.nested)};function WA($,Y){if(!($&&$.length))return;var T={};for(var q=0;q<$.length;++q)T[$[q].name]=$[q].toJSON(Y);return T}t.arrayToJSON=WA;t.isReservedId=function(Y,T){if(Y){for(var q=0;q<Y.length;++q)if(typeof Y[q]!=="string"&&Y[q][0]<=T&&Y[q][1]>T)return!0}return!1};t.isReservedName=function(Y,T){if(Y){for(var q=0;q<Y.length;++q)if(Y[q]===T)return!0}return!1};function t($,Y){Jq.call(this,$,Y),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function GA($){$._nestedArray=null,$._lookupCache={};var Y=$;while(Y=Y.parent)Y._lookupCache={};return $}Object.defineProperty(t.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=Qq.toArray(this.nested))}});t.prototype.toJSON=function(Y){return Qq.toObject(["options",this.options,"nested",WA(this.nestedArray,Y)])};t.prototype.addJSON=function(Y){var T=this;if(Y)for(var q=Object.keys(Y),X=0,J;X<q.length;++X)J=Y[q[X]],T.add((J.fields!==void 0?r$.fromJSON:J.values!==void 0?a$.fromJSON:J.methods!==void 0?xY.fromJSON:J.id!==void 0?_X.fromJSON:t.fromJSON)(q[X],J));return this};t.prototype.get=function(Y){return this.nested&&this.nested[Y]||null};t.prototype.getEnum=function(Y){if(this.nested&&this.nested[Y]instanceof a$)return this.nested[Y].values;throw Error("no such enum: "+Y)};t.prototype.add=function(Y){if(!(Y instanceof _X&&Y.extend!==void 0||Y instanceof r$||Y instanceof mR||Y instanceof a$||Y instanceof xY||Y instanceof t))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var T=this.get(Y.name);if(T)if(T instanceof t&&Y instanceof t&&!(T instanceof r$||T instanceof xY)){var q=T.nestedArray;for(var X=0;X<q.length;++X)Y.add(q[X]);if(this.remove(T),!this.nested)this.nested={};Y.setOptions(T.options,!0)}else throw Error("duplicate name '"+Y.name+"' in "+this)}if(this.nested[Y.name]=Y,!(this instanceof r$||this instanceof xY||this instanceof a$||this instanceof _X)){if(!Y._edition)Y._edition=Y._defaultEdition}this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;var J=this;while(J=J.parent)J._needsRecursiveFeatureResolution=!0,J._needsRecursiveResolve=!0;return Y.onAdd(this),GA(this)};t.prototype.remove=function(Y){if(!(Y instanceof Jq))throw TypeError("object must be a ReflectionObject");if(Y.parent!==this)throw Error(Y+" is not a member of "+this);if(delete this.nested[Y.name],!Object.keys(this.nested).length)this.nested=void 0;return Y.onRemove(this),GA(this)};t.prototype.define=function(Y,T){if(Qq.isString(Y))Y=Y.split(".");else if(!Array.isArray(Y))throw TypeError("illegal path");if(Y&&Y.length&&Y[0]==="")throw Error("path must be relative");var q=this;while(Y.length>0){var X=Y.shift();if(q.nested&&q.nested[X]){if(q=q.nested[X],!(q instanceof t))throw Error("path conflicts with non-namespace objects")}else q.add(q=new t(X))}if(T)q.addJSON(T);return q};t.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var Y=this.nestedArray,T=0;this.resolve();while(T<Y.length)if(Y[T]instanceof t)Y[T++].resolveAll();else Y[T++].resolve();return this._needsRecursiveResolve=!1,this};t.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return this._needsRecursiveFeatureResolution=!1,Y=this._edition||Y,Jq.prototype._resolveFeaturesRecursive.call(this,Y),this.nestedArray.forEach((T)=>{T._resolveFeaturesRecursive(Y)}),this};t.prototype.lookup=function(Y,T,q){if(typeof T==="boolean")q=T,T=void 0;else if(T&&!Array.isArray(T))T=[T];if(Qq.isString(Y)&&Y.length){if(Y===".")return this.root;Y=Y.split(".")}else if(!Y.length)return this;var X=Y.join(".");if(Y[0]==="")return this.root.lookup(Y.slice(1),T);var J=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+X];if(J&&(!T||T.indexOf(J.constructor)>-1))return J;if(J=this._lookupImpl(Y,X),J&&(!T||T.indexOf(J.constructor)>-1))return J;if(q)return null;var Q=this;while(Q.parent){if(J=Q.parent._lookupImpl(Y,X),J&&(!T||T.indexOf(J.constructor)>-1))return J;Q=Q.parent}return null};t.prototype._lookupImpl=function(Y,T){if(Object.prototype.hasOwnProperty.call(this._lookupCache,T))return this._lookupCache[T];var q=this.get(Y[0]),X=null;if(q){if(Y.length===1)X=q;else if(q instanceof t)Y=Y.slice(1),X=q._lookupImpl(Y,Y.join("."))}else for(var J=0;J<this.nestedArray.length;++J)if(this._nestedArray[J]instanceof t&&(q=this._nestedArray[J]._lookupImpl(Y,T)))X=q;return this._lookupCache[T]=X,X};t.prototype.lookupType=function(Y){var T=this.lookup(Y,[r$]);if(!T)throw Error("no such type: "+Y);return T};t.prototype.lookupEnum=function(Y){var T=this.lookup(Y,[a$]);if(!T)throw Error("no such Enum '"+Y+"' in "+this);return T};t.prototype.lookupTypeOrEnum=function(Y){var T=this.lookup(Y,[r$,a$]);if(!T)throw Error("no such Type or Enum '"+Y+"' in "+this);return T};t.prototype.lookupService=function(Y){var T=this.lookup(Y,[xY]);if(!T)throw Error("no such Service '"+Y+"' in "+this);return T};t._configure=function($,Y,T){r$=$,xY=Y,a$=T}});var Uq=M((Lg,VA)=>{VA.exports=q$;var gX=P$();((q$.prototype=Object.create(gX.prototype)).constructor=q$).className="MapField";var fR=s$(),bT=w0();function q$($,Y,T,q,X,J){if(gX.call(this,$,Y,q,void 0,void 0,X,J),!bT.isString(T))throw TypeError("keyType must be a string");this.keyType=T,this.resolvedKeyType=null,this.map=!0}q$.fromJSON=function(Y,T){return new q$(Y,T.id,T.keyType,T.type,T.options,T.comment)};q$.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return bT.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",T?this.comment:void 0])};q$.prototype.resolve=function(){if(this.resolved)return this;if(fR.mapKey[this.keyType]===void 0)throw Error("invalid key type: "+this.keyType);return gX.prototype.resolve.call(this)};q$.d=function(Y,T,q){if(typeof q==="function")q=bT.decorateType(q).name;else if(q&&typeof q==="object")q=bT.decorateEnum(q).name;return function(J,Q){bT.decorateType(J.constructor).add(new q$(Q,Y,T,q))}}});var Zq=M((wg,DA)=>{DA.exports=t$;var mX=L$();((t$.prototype=Object.create(mX.prototype)).constructor=t$).className="Method";var hY=w0();function t$($,Y,T,q,X,J,Q,U,Z){if(hY.isObject(X))Q=X,X=J=void 0;else if(hY.isObject(J))Q=J,J=void 0;if(!(Y===void 0||hY.isString(Y)))throw TypeError("type must be a string");if(!hY.isString(T))throw TypeError("requestType must be a string");if(!hY.isString(q))throw TypeError("responseType must be a string");mX.call(this,$,Q),this.type=Y||"rpc",this.requestType=T,this.requestStream=X?!0:void 0,this.responseType=q,this.responseStream=J?!0:void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=U,this.parsedOptions=Z}t$.fromJSON=function(Y,T){return new t$(Y,T.type,T.requestType,T.responseType,T.requestStream,T.responseStream,T.options,T.comment,T.parsedOptions)};t$.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return hY.toObject(["type",this.type!=="rpc"&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",T?this.comment:void 0,"parsedOptions",this.parsedOptions])};t$.prototype.resolve=function(){if(this.resolved)return this;return this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),mX.prototype.resolve.call(this)}});var Kq=M((Sg,NA)=>{NA.exports=Y1;var X$=kY();((Y1.prototype=Object.create(X$.prototype)).constructor=Y1).className="Service";var fX=Zq(),uT=w0(),bR=yX();function Y1($,Y){X$.call(this,$,Y),this.methods={},this._methodsArray=null}Y1.fromJSON=function(Y,T){var q=new Y1(Y,T.options);if(T.methods)for(var X=Object.keys(T.methods),J=0;J<X.length;++J)q.add(fX.fromJSON(X[J],T.methods[X[J]]));if(T.nested)q.addJSON(T.nested);if(T.edition)q._edition=T.edition;return q.comment=T.comment,q._defaultEdition="proto3",q};Y1.prototype.toJSON=function(Y){var T=X$.prototype.toJSON.call(this,Y),q=Y?Boolean(Y.keepComments):!1;return uT.toObject(["edition",this._editionToJSON(),"options",T&&T.options||void 0,"methods",X$.arrayToJSON(this.methodsArray,Y)||{},"nested",T&&T.nested||void 0,"comment",q?this.comment:void 0])};Object.defineProperty(Y1.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=uT.toArray(this.methods))}});function FA($){return $._methodsArray=null,$}Y1.prototype.get=function(Y){return this.methods[Y]||X$.prototype.get.call(this,Y)};Y1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;X$.prototype.resolve.call(this);var Y=this.methodsArray;for(var T=0;T<Y.length;++T)Y[T].resolve();return this};Y1.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,X$.prototype._resolveFeaturesRecursive.call(this,Y),this.methodsArray.forEach((T)=>{T._resolveFeaturesRecursive(Y)}),this};Y1.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof fX)return this.methods[Y.name]=Y,Y.parent=this,FA(this);return X$.prototype.add.call(this,Y)};Y1.prototype.remove=function(Y){if(Y instanceof fX){if(this.methods[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.methods[Y.name],Y.parent=null,FA(this)}return X$.prototype.remove.call(this,Y)};Y1.prototype.create=function(Y,T,q){var X=new bR.Service(Y,T,q);for(var J=0,Q;J<this.methodsArray.length;++J){var U=uT.lcFirst((Q=this._methodsArray[J]).resolve().name).replace(/[^$\w_]/g,"");X[U]=uT.codegen(["r","c"],uT.isReserved(U)?U+"_":U)("return this.rpcCall(m,q,s,r,c)")({m:Q,q:Q.resolvedRequestType.ctor,s:Q.resolvedResponseType.ctor})}return X}});var Aq=M((Cg,HA)=>{HA.exports=m1;var uR=_1();function m1($){if($)for(var Y=Object.keys($),T=0;T<Y.length;++T)this[Y[T]]=$[Y[T]]}m1.create=function(Y){return this.$type.create(Y)};m1.encode=function(Y,T){return this.$type.encode(Y,T)};m1.encodeDelimited=function(Y,T){return this.$type.encodeDelimited(Y,T)};m1.decode=function(Y){return this.$type.decode(Y)};m1.decodeDelimited=function(Y){return this.$type.decodeDelimited(Y)};m1.verify=function(Y){return this.$type.verify(Y)};m1.fromObject=function(Y){return this.$type.fromObject(Y)};m1.toObject=function(Y,T){return this.$type.toObject(Y,T)};m1.prototype.toJSON=function(){return this.$type.toObject(this,uR.toJSONOptions)}});var bX=M((yg,IA)=>{IA.exports=pR;var dR=w1(),J$=s$(),zA=w0();function cR($){return"missing required '"+$.name+"'"}function pR($){var Y=zA.codegen(["r","l","e"],$.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+($.fieldsArray.filter(function(U){return U.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),T=0;for(;T<$.fieldsArray.length;++T){var q=$._fieldsArray[T].resolve(),X=q.resolvedType instanceof dR?"int32":q.type,J="m"+zA.safeProp(q.name);if(Y("case %i: {",q.id),q.map){if(Y("if(%s===util.emptyObject)",J)("%s={}",J)("var c2 = r.uint32()+r.pos"),J$.defaults[q.keyType]!==void 0)Y("k=%j",J$.defaults[q.keyType]);else Y("k=null");if(J$.defaults[X]!==void 0)Y("value=%j",J$.defaults[X]);else Y("value=null");if(Y("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",q.keyType)("case 2:"),J$.basic[X]===void 0)Y("value=types[%i].decode(r,r.uint32())",T);else Y("value=r.%s()",X);if(Y("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),J$.long[q.keyType]!==void 0)Y('%s[typeof k==="object"?util.longToHash(k):k]=value',J);else Y("%s[k]=value",J)}else if(q.repeated){if(Y("if(!(%s&&%s.length))",J,J)("%s=[]",J),J$.packed[X]!==void 0)Y("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",J,X)("}else");if(J$.basic[X]===void 0)Y(q.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",J,T);else Y("%s.push(r.%s())",J,X)}else if(J$.basic[X]===void 0)Y(q.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",J,T);else Y("%s=r.%s()",J,X);Y("break")("}")}Y("default:")("r.skipType(t&7)")("break")("}")("}");for(T=0;T<$._fieldsArray.length;++T){var Q=$._fieldsArray[T];if(Q.required)Y("if(!m.hasOwnProperty(%j))",Q.name)("throw util.ProtocolError(%j,{instance:m})",cR(Q))}return Y("return m")}});var cX=M((jg,MA)=>{MA.exports=iR;var lR=w1(),uX=w0();function D1($,Y){return $.name+": "+Y+($.repeated&&Y!=="array"?"[]":$.map&&Y!=="object"?"{k:"+$.keyType+"}":"")+" expected"}function dX($,Y,T,q){if(Y.resolvedType)if(Y.resolvedType instanceof lR){$("switch(%s){",q)("default:")("return%j",D1(Y,"enum value"));for(var X=Object.keys(Y.resolvedType.values),J=0;J<X.length;++J)$("case %i:",Y.resolvedType.values[X[J]]);$("break")("}")}else $("{")("var e=types[%i].verify(%s);",T,q)("if(e)")("return%j+e",Y.name+".")("}");else switch(Y.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.isInteger(%s))",q)("return%j",D1(Y,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",q,q,q,q)("return%j",D1(Y,"integer|Long"));break;case"float":case"double":$('if(typeof %s!=="number")',q)("return%j",D1(Y,"number"));break;case"bool":$('if(typeof %s!=="boolean")',q)("return%j",D1(Y,"boolean"));break;case"string":$("if(!util.isString(%s))",q)("return%j",D1(Y,"string"));break;case"bytes":$('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',q,q,q)("return%j",D1(Y,"buffer"));break}return $}function nR($,Y,T){switch(Y.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.key32Re.test(%s))",T)("return%j",D1(Y,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.key64Re.test(%s))",T)("return%j",D1(Y,"integer|Long key"));break;case"bool":$("if(!util.key2Re.test(%s))",T)("return%j",D1(Y,"boolean key"));break}return $}function iR($){var Y=uX.codegen(["m"],$.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),T=$.oneofsArray,q={};if(T.length)Y("var p={}");for(var X=0;X<$.fieldsArray.length;++X){var J=$._fieldsArray[X].resolve(),Q="m"+uX.safeProp(J.name);if(J.optional)Y("if(%s!=null&&m.hasOwnProperty(%j)){",Q,J.name);if(J.map)Y("if(!util.isObject(%s))",Q)("return%j",D1(J,"object"))("var k=Object.keys(%s)",Q)("for(var i=0;i<k.length;++i){"),nR(Y,J,"k[i]"),dX(Y,J,X,Q+"[k[i]]")("}");else if(J.repeated)Y("if(!Array.isArray(%s))",Q)("return%j",D1(J,"array"))("for(var i=0;i<%s.length;++i){",Q),dX(Y,J,X,Q+"[i]")("}");else{if(J.partOf){var U=uX.safeProp(J.partOf.name);if(q[J.partOf.name]===1)Y("if(p%s===1)",U)("return%j",J.partOf.name+": multiple values");q[J.partOf.name]=1,Y("p%s=1",U)}dX(Y,J,X,Q)}if(J.optional)Y("}")}return Y("return null")}});var nX=M((RA)=>{var BA=RA,dT=w1(),f1=w0();function pX($,Y,T,q){var X=!1;if(Y.resolvedType)if(Y.resolvedType instanceof dT){$("switch(d%s){",q);for(var J=Y.resolvedType.values,Q=Object.keys(J),U=0;U<Q.length;++U){if(J[Q[U]]===Y.typeDefault&&!X){if($("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',q,q,q),!Y.repeated)$("break");X=!0}$("case%j:",Q[U])("case %i:",J[Q[U]])("m%s=%j",q,J[Q[U]])("break")}$("}")}else $('if(typeof d%s!=="object")',q)("throw TypeError(%j)",Y.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",q,T,q);else{var Z=!1;switch(Y.type){case"double":case"float":$("m%s=Number(d%s)",q,q);break;case"uint32":case"fixed32":$("m%s=d%s>>>0",q,q);break;case"int32":case"sint32":case"sfixed32":$("m%s=d%s|0",q,q);break;case"uint64":Z=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",q,q,Z)('else if(typeof d%s==="string")',q)("m%s=parseInt(d%s,10)",q,q)('else if(typeof d%s==="number")',q)("m%s=d%s",q,q)('else if(typeof d%s==="object")',q)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",q,q,q,Z?"true":"");break;case"bytes":$('if(typeof d%s==="string")',q)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",q,q,q)("else if(d%s.length >= 0)",q)("m%s=d%s",q,q);break;case"string":$("m%s=String(d%s)",q,q);break;case"bool":$("m%s=Boolean(d%s)",q,q);break}}return $}BA.fromObject=function(Y){var T=Y.fieldsArray,q=f1.codegen(["d"],Y.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!T.length)return q("return new this.ctor");q("var m=new this.ctor");for(var X=0;X<T.length;++X){var J=T[X].resolve(),Q=f1.safeProp(J.name);if(J.map)q("if(d%s){",Q)('if(typeof d%s!=="object")',Q)("throw TypeError(%j)",J.fullName+": object expected")("m%s={}",Q)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",Q),pX(q,J,X,Q+"[ks[i]]")("}")("}");else if(J.repeated)q("if(d%s){",Q)("if(!Array.isArray(d%s))",Q)("throw TypeError(%j)",J.fullName+": array expected")("m%s=[]",Q)("for(var i=0;i<d%s.length;++i){",Q),pX(q,J,X,Q+"[i]")("}")("}");else{if(!(J.resolvedType instanceof dT))q("if(d%s!=null){",Q);if(pX(q,J,X,Q),!(J.resolvedType instanceof dT))q("}")}}return q("return m")};function lX($,Y,T,q){if(Y.resolvedType)if(Y.resolvedType instanceof dT)$("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",q,T,q,q,T,q,q);else $("d%s=types[%i].toObject(m%s,o)",q,T,q);else{var X=!1;switch(Y.type){case"double":case"float":$("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",q,q,q,q);break;case"uint64":X=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$('if(typeof m%s==="number")',q)("d%s=o.longs===String?String(m%s):m%s",q,q,q)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",q,q,q,q,X?"true":"",q);break;case"bytes":$("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",q,q,q,q,q);break;default:$("d%s=m%s",q,q);break}}return $}BA.toObject=function(Y){var T=Y.fieldsArray.slice().sort(f1.compareFieldsById);if(!T.length)return f1.codegen()("return {}");var q=f1.codegen(["m","o"],Y.name+"$toObject")("if(!o)")("o={}")("var d={}"),X=[],J=[],Q=[],U=0;for(;U<T.length;++U)if(!T[U].partOf)(T[U].resolve().repeated?X:T[U].map?J:Q).push(T[U]);if(X.length){q("if(o.arrays||o.defaults){");for(U=0;U<X.length;++U)q("d%s=[]",f1.safeProp(X[U].name));q("}")}if(J.length){q("if(o.objects||o.defaults){");for(U=0;U<J.length;++U)q("d%s={}",f1.safeProp(J[U].name));q("}")}if(Q.length){q("if(o.defaults){");for(U=0;U<Q.length;++U){var Z=Q[U],K=f1.safeProp(Z.name);if(Z.resolvedType instanceof dT)q("d%s=o.enums===String?%j:%j",K,Z.resolvedType.valuesById[Z.typeDefault],Z.typeDefault);else if(Z.long)q("if(util.Long){")("var n=new util.Long(%i,%i,%j)",Z.typeDefault.low,Z.typeDefault.high,Z.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",K)("}else")("d%s=o.longs===String?%j:%i",K,Z.typeDefault.toString(),Z.typeDefault.toNumber());else if(Z.bytes){var A="["+Array.prototype.slice.call(Z.typeDefault).join(",")+"]";q("if(o.bytes===String)d%s=%j",K,String.fromCharCode.apply(String,Z.typeDefault))("else{")("d%s=%s",K,A)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",K,K)("}")}else q("d%s=%j",K,Z.typeDefault)}q("}")}var W=!1;for(U=0;U<T.length;++U){var Z=T[U],E=Y._fieldsArray.indexOf(Z),K=f1.safeProp(Z.name);if(Z.map){if(!W)W=!0,q("var ks2");q("if(m%s&&(ks2=Object.keys(m%s)).length){",K,K)("d%s={}",K)("for(var j=0;j<ks2.length;++j){"),lX(q,Z,E,K+"[ks2[j]]")("}")}else if(Z.repeated)q("if(m%s&&m%s.length){",K,K)("d%s=[]",K)("for(var j=0;j<m%s.length;++j){",K),lX(q,Z,E,K+"[j]")("}");else if(q("if(m%s!=null&&m.hasOwnProperty(%j)){",K,Z.name),lX(q,Z,E,K),Z.partOf)q("if(o.oneofs)")("d%s=%j",f1.safeProp(Z.partOf.name),Z.name);q("}")}return q("return d")}});var iX=M((OA)=>{var rR=OA,aR=Aq();rR[".google.protobuf.Any"]={fromObject:function($){if($&&$["@type"]){var Y=$["@type"].substring($["@type"].lastIndexOf("/")+1),T=this.lookup(Y);if(T){var q=$["@type"].charAt(0)==="."?$["@type"].slice(1):$["@type"];if(q.indexOf("/")===-1)q="/"+q;return this.create({type_url:q,value:T.encode(T.fromObject($)).finish()})}}return this.fromObject($)},toObject:function($,Y){var T="type.googleapis.com/",q="",X="";if(Y&&Y.json&&$.type_url&&$.value){X=$.type_url.substring($.type_url.lastIndexOf("/")+1),q=$.type_url.substring(0,$.type_url.lastIndexOf("/")+1);var J=this.lookup(X);if(J)$=J.decode($.value)}if(!($ instanceof this.ctor)&&$ instanceof aR){var Q=$.$type.toObject($,Y),U=$.$type.fullName[0]==="."?$.$type.fullName.slice(1):$.$type.fullName;if(q==="")q=T;return X=q+U,Q["@type"]=X,Q}return this.toObject($,Y)}}});var Eq=M((kg,LA)=>{LA.exports=Z0;var F1=kY();((Z0.prototype=Object.create(F1.prototype)).constructor=Z0).className="Type";var oR=w1(),oX=o$(),Wq=P$(),sR=Uq(),tR=Kq(),rX=Aq(),aX=Xq(),eR=Tq(),m0=w0(),$2=sX(),Y2=bX(),T2=cX(),PA=nX(),q2=iX();function Z0($,Y){F1.call(this,$,Y),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}Object.defineProperties(Z0.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var $=Object.keys(this.fields),Y=0;Y<$.length;++Y){var T=this.fields[$[Y]],q=T.id;if(this._fieldsById[q])throw Error("duplicate id "+q+" in "+this);this._fieldsById[q]=T}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=m0.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=m0.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=Z0.generateConstructor(this)())},set:function($){var Y=$.prototype;if(!(Y instanceof rX))($.prototype=new rX).constructor=$,m0.merge($.prototype,Y);$.$type=$.prototype.$type=this,m0.merge($,rX,!0),this._ctor=$;var T=0;for(;T<this.fieldsArray.length;++T)this._fieldsArray[T].resolve();var q={};for(T=0;T<this.oneofsArray.length;++T)q[this._oneofsArray[T].resolve().name]={get:m0.oneOfGetter(this._oneofsArray[T].oneof),set:m0.oneOfSetter(this._oneofsArray[T].oneof)};if(T)Object.defineProperties($.prototype,q)}}});Z0.generateConstructor=function(Y){var T=m0.codegen(["p"],Y.name);for(var q=0,X;q<Y.fieldsArray.length;++q)if((X=Y._fieldsArray[q]).map)T("this%s={}",m0.safeProp(X.name));else if(X.repeated)T("this%s=[]",m0.safeProp(X.name));return T("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")};function Gq($){return $._fieldsById=$._fieldsArray=$._oneofsArray=null,delete $.encode,delete $.decode,delete $.verify,$}Z0.fromJSON=function(Y,T){var q=new Z0(Y,T.options);q.extensions=T.extensions,q.reserved=T.reserved;var X=Object.keys(T.fields),J=0;for(;J<X.length;++J)q.add((typeof T.fields[X[J]].keyType<"u"?sR.fromJSON:Wq.fromJSON)(X[J],T.fields[X[J]]));if(T.oneofs)for(X=Object.keys(T.oneofs),J=0;J<X.length;++J)q.add(oX.fromJSON(X[J],T.oneofs[X[J]]));if(T.nested)for(X=Object.keys(T.nested),J=0;J<X.length;++J){var Q=T.nested[X[J]];q.add((Q.id!==void 0?Wq.fromJSON:Q.fields!==void 0?Z0.fromJSON:Q.values!==void 0?oR.fromJSON:Q.methods!==void 0?tR.fromJSON:F1.fromJSON)(X[J],Q))}if(T.extensions&&T.extensions.length)q.extensions=T.extensions;if(T.reserved&&T.reserved.length)q.reserved=T.reserved;if(T.group)q.group=!0;if(T.comment)q.comment=T.comment;if(T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};Z0.prototype.toJSON=function(Y){var T=F1.prototype.toJSON.call(this,Y),q=Y?Boolean(Y.keepComments):!1;return m0.toObject(["edition",this._editionToJSON(),"options",T&&T.options||void 0,"oneofs",F1.arrayToJSON(this.oneofsArray,Y),"fields",F1.arrayToJSON(this.fieldsArray.filter(function(X){return!X.declaringField}),Y)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",T&&T.nested||void 0,"comment",q?this.comment:void 0])};Z0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;F1.prototype.resolveAll.call(this);var Y=this.oneofsArray;q=0;while(q<Y.length)Y[q++].resolve();var T=this.fieldsArray,q=0;while(q<T.length)T[q++].resolve();return this};Z0.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,F1.prototype._resolveFeaturesRecursive.call(this,Y),this.oneofsArray.forEach((T)=>{T._resolveFeatures(Y)}),this.fieldsArray.forEach((T)=>{T._resolveFeatures(Y)}),this};Z0.prototype.get=function(Y){return this.fields[Y]||this.oneofs&&this.oneofs[Y]||this.nested&&this.nested[Y]||null};Z0.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof Wq&&Y.extend===void 0){if(this._fieldsById?this._fieldsById[Y.id]:this.fieldsById[Y.id])throw Error("duplicate id "+Y.id+" in "+this);if(this.isReservedId(Y.id))throw Error("id "+Y.id+" is reserved in "+this);if(this.isReservedName(Y.name))throw Error("name '"+Y.name+"' is reserved in "+this);if(Y.parent)Y.parent.remove(Y);return this.fields[Y.name]=Y,Y.message=this,Y.onAdd(this),Gq(this)}if(Y instanceof oX){if(!this.oneofs)this.oneofs={};return this.oneofs[Y.name]=Y,Y.onAdd(this),Gq(this)}return F1.prototype.add.call(this,Y)};Z0.prototype.remove=function(Y){if(Y instanceof Wq&&Y.extend===void 0){if(!this.fields||this.fields[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.fields[Y.name],Y.parent=null,Y.onRemove(this),Gq(this)}if(Y instanceof oX){if(!this.oneofs||this.oneofs[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.oneofs[Y.name],Y.parent=null,Y.onRemove(this),Gq(this)}return F1.prototype.remove.call(this,Y)};Z0.prototype.isReservedId=function(Y){return F1.isReservedId(this.reserved,Y)};Z0.prototype.isReservedName=function(Y){return F1.isReservedName(this.reserved,Y)};Z0.prototype.create=function(Y){return new this.ctor(Y)};Z0.prototype.setup=function(){var Y=this.fullName,T=[];for(var q=0;q<this.fieldsArray.length;++q)T.push(this._fieldsArray[q].resolve().resolvedType);this.encode=$2(this)({Writer:eR,types:T,util:m0}),this.decode=Y2(this)({Reader:aX,types:T,util:m0}),this.verify=T2(this)({types:T,util:m0}),this.fromObject=PA.fromObject(this)({types:T,util:m0}),this.toObject=PA.toObject(this)({types:T,util:m0});var X=q2[Y];if(X){var J=Object.create(this);J.fromObject=this.fromObject,this.fromObject=X.fromObject.bind(J),J.toObject=this.toObject,this.toObject=X.toObject.bind(J)}return this};Z0.prototype.encode=function(Y,T){return this.setup().encode(Y,T)};Z0.prototype.encodeDelimited=function(Y,T){return this.encode(Y,T&&T.len?T.fork():T).ldelim()};Z0.prototype.decode=function(Y,T){return this.setup().decode(Y,T)};Z0.prototype.decodeDelimited=function(Y){if(!(Y instanceof aX))Y=aX.create(Y);return this.decode(Y,Y.uint32())};Z0.prototype.verify=function(Y){return this.setup().verify(Y)};Z0.prototype.fromObject=function(Y){return this.setup().fromObject(Y)};Z0.prototype.toObject=function(Y,T){return this.setup().toObject(Y,T)};Z0.d=function(Y){return function(q){m0.decorateType(q,Y)}}});var Nq=M((hg,CA)=>{CA.exports=T1;var Fq=kY();((T1.prototype=Object.create(Fq.prototype)).constructor=T1).className="Root";var Vq=P$(),tX=w1(),X2=o$(),w$=w0(),eX,$5,cT;function T1($){Fq.call(this,"",$),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}T1.fromJSON=function(Y,T){if(!T)T=new T1;if(Y.options)T.setOptions(Y.options);return T.addJSON(Y.nested).resolveAll()};T1.prototype.resolvePath=w$.path.resolve;T1.prototype.fetch=w$.fetch;function SA(){}T1.prototype.load=function $(Y,T,q){if(typeof T==="function")q=T,T=void 0;var X=this;if(!q)return w$.asPromise($,X,Y,T);var J=q===SA;function Q(D,F){if(!q)return;if(J)throw D;if(F)F.resolveAll();var H=q;q=null,H(D,F)}function U(D){var F=D.lastIndexOf("google/protobuf/");if(F>-1){var H=D.substring(F);if(H in cT)return H}return null}function Z(D,F){try{if(w$.isString(F)&&F.charAt(0)==="{")F=JSON.parse(F);if(!w$.isString(F))X.setOptions(F.options).addJSON(F.nested);else{$5.filename=D;var H=$5(F,X,T),V,B=0;if(H.imports){for(;B<H.imports.length;++B)if(V=U(H.imports[B])||X.resolvePath(D,H.imports[B]))K(V)}if(H.weakImports){for(B=0;B<H.weakImports.length;++B)if(V=U(H.weakImports[B])||X.resolvePath(D,H.weakImports[B]))K(V,!0)}}}catch(S){Q(S)}if(!J&&!A)Q(null,X)}function K(D,F){if(D=U(D)||D,X.files.indexOf(D)>-1)return;if(X.files.push(D),D in cT){if(J)Z(D,cT[D]);else++A,setTimeout(function(){--A,Z(D,cT[D])});return}if(J){var H;try{H=w$.fs.readFileSync(D).toString("utf8")}catch(V){if(!F)Q(V);return}Z(D,H)}else++A,X.fetch(D,function(V,B){if(--A,!q)return;if(V){if(!F)Q(V);else if(!A)Q(null,X);return}Z(D,B)})}var A=0;if(w$.isString(Y))Y=[Y];for(var W=0,E;W<Y.length;++W)if(E=X.resolvePath("",Y[W]))K(E);if(J)return X.resolveAll(),X;if(!A)Q(null,X);return X};T1.prototype.loadSync=function(Y,T){if(!w$.isNode)throw Error("not supported");return this.load(Y,T,SA)};T1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(Y){return"'extend "+Y.extend+"' in "+Y.parent.fullName}).join(", "));return Fq.prototype.resolveAll.call(this)};var Dq=/^[A-Z]/;function wA($,Y){var T=Y.parent.lookup(Y.extend);if(T){var q=new Vq(Y.fullName,Y.id,Y.type,Y.rule,void 0,Y.options);if(T.get(q.name))return!0;return q.declaringField=Y,Y.extensionField=q,T.add(q),!0}return!1}T1.prototype._handleAdd=function(Y){if(Y instanceof Vq){if(Y.extend!==void 0&&!Y.extensionField){if(!wA(this,Y))this.deferred.push(Y)}}else if(Y instanceof tX){if(Dq.test(Y.name))Y.parent[Y.name]=Y.values}else if(!(Y instanceof X2)){if(Y instanceof eX)for(var T=0;T<this.deferred.length;)if(wA(this,this.deferred[T]))this.deferred.splice(T,1);else++T;for(var q=0;q<Y.nestedArray.length;++q)this._handleAdd(Y._nestedArray[q]);if(Dq.test(Y.name))Y.parent[Y.name]=Y}if(Y instanceof eX||Y instanceof tX||Y instanceof Vq)this._fullyQualifiedObjects[Y.fullName]=Y};T1.prototype._handleRemove=function(Y){if(Y instanceof Vq){if(Y.extend!==void 0)if(Y.extensionField)Y.extensionField.parent.remove(Y.extensionField),Y.extensionField=null;else{var T=this.deferred.indexOf(Y);if(T>-1)this.deferred.splice(T,1)}}else if(Y instanceof tX){if(Dq.test(Y.name))delete Y.parent[Y.name]}else if(Y instanceof Fq){for(var q=0;q<Y.nestedArray.length;++q)this._handleRemove(Y._nestedArray[q]);if(Dq.test(Y.name))delete Y.parent[Y.name]}delete this._fullyQualifiedObjects[Y.fullName]};T1._configure=function($,Y,T){eX=$,$5=Y,cT=T}});var w0=M((_g,jA)=>{var F0=jA.exports=_1(),yA=jX(),Y5,T5;F0.codegen=JA();F0.fetch=UA();F0.path=AA();F0.fs=F0.inquire("fs");F0.toArray=function(Y){if(Y){var T=Object.keys(Y),q=Array(T.length),X=0;while(X<T.length)q[X]=Y[T[X++]];return q}return[]};F0.toObject=function(Y){var T={},q=0;while(q<Y.length){var X=Y[q++],J=Y[q++];if(J!==void 0)T[X]=J}return T};var J2=/\\/g,Q2=/"/g;F0.isReserved=function(Y){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(Y)};F0.safeProp=function(Y){if(!/^[$\w_]+$/.test(Y)||F0.isReserved(Y))return'["'+Y.replace(J2,"\\\\").replace(Q2,"\\\"")+'"]';return"."+Y};F0.ucFirst=function(Y){return Y.charAt(0).toUpperCase()+Y.substring(1)};var U2=/_([a-z])/g;F0.camelCase=function(Y){return Y.substring(0,1)+Y.substring(1).replace(U2,function(T,q){return q.toUpperCase()})};F0.compareFieldsById=function(Y,T){return Y.id-T.id};F0.decorateType=function(Y,T){if(Y.$type){if(T&&Y.$type.name!==T)F0.decorateRoot.remove(Y.$type),Y.$type.name=T,F0.decorateRoot.add(Y.$type);return Y.$type}if(!Y5)Y5=Eq();var q=new Y5(T||Y.name);return F0.decorateRoot.add(q),q.ctor=Y,Object.defineProperty(Y,"$type",{value:q,enumerable:!1}),Object.defineProperty(Y.prototype,"$type",{value:q,enumerable:!1}),q};var Z2=0;F0.decorateEnum=function(Y){if(Y.$type)return Y.$type;if(!T5)T5=w1();var T=new T5("Enum"+Z2++,Y);return F0.decorateRoot.add(T),Object.defineProperty(Y,"$type",{value:T,enumerable:!1}),T};F0.setProperty=function(Y,T,q,X){function J(Q,U,Z){var K=U.shift();if(K==="__proto__"||K==="prototype")return Q;if(U.length>0)Q[K]=J(Q[K]||{},U,Z);else{var A=Q[K];if(A&&X)return Q;if(A)Z=[].concat(A).concat(Z);Q[K]=Z}return Q}if(typeof Y!=="object")throw TypeError("dst must be an object");if(!T)throw TypeError("path must be specified");return T=T.split("."),J(Y,T,q)};Object.defineProperty(F0,"decorateRoot",{get:function(){return yA.decorated||(yA.decorated=new(Nq()))}})});var s$=M((vA)=>{var pT=vA,K2=w0(),A2=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function lT($,Y){var T=0,q={};Y|=0;while(T<$.length)q[A2[T+Y]]=$[T++];return q}pT.basic=lT([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);pT.defaults=lT([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",K2.emptyArray,null]);pT.long=lT([0,0,0,1,1],7);pT.mapKey=lT([0,0,0,5,5,0,0,0,1,1,0,2],2);pT.packed=lT([1,5,0,0,0,5,5,0,0,0,1,1,0])});var P$=M((mg,kA)=>{kA.exports=S0;var iT=L$();((S0.prototype=Object.create(iT.prototype)).constructor=S0).className="Field";var xA=w1(),q5=s$(),I0=w0(),nT,W2=/^required|optional|repeated$/;S0.fromJSON=function(Y,T){var q=new S0(Y,T.id,T.type,T.rule,T.extend,T.options,T.comment);if(T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};function S0($,Y,T,q,X,J,Q){if(I0.isObject(q))Q=X,J=q,q=X=void 0;else if(I0.isObject(X))Q=J,J=X,X=void 0;if(iT.call(this,$,J),!I0.isInteger(Y)||Y<0)throw TypeError("id must be a non-negative integer");if(!I0.isString(T))throw TypeError("type must be a string");if(q!==void 0&&!W2.test(q=q.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(X!==void 0&&!I0.isString(X))throw TypeError("extend must be a string");if(q==="proto3_optional")q="optional";this.rule=q&&q!=="optional"?q:void 0,this.type=T,this.id=Y,this.extend=X||void 0,this.repeated=q==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=I0.Long?q5.long[T]!==void 0:!1,this.bytes=T==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=Q}Object.defineProperty(S0.prototype,"required",{get:function(){return this._features.field_presence==="LEGACY_REQUIRED"}});Object.defineProperty(S0.prototype,"optional",{get:function(){return!this.required}});Object.defineProperty(S0.prototype,"delimited",{get:function(){return this.resolvedType instanceof nT&&this._features.message_encoding==="DELIMITED"}});Object.defineProperty(S0.prototype,"packed",{get:function(){return this._features.repeated_field_encoding==="PACKED"}});Object.defineProperty(S0.prototype,"hasPresence",{get:function(){if(this.repeated||this.map)return!1;return this.partOf||this.declaringField||this.extensionField||this._features.field_presence!=="IMPLICIT"}});S0.prototype.setOption=function(Y,T,q){return iT.prototype.setOption.call(this,Y,T,q)};S0.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return I0.toObject(["edition",this._editionToJSON(),"rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",T?this.comment:void 0])};S0.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=q5.defaults[this.type])===void 0)if(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof nT)this.typeDefault=null;else this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]];else if(this.options&&this.options.proto3_optional)this.typeDefault=null;if(this.options&&this.options.default!=null){if(this.typeDefault=this.options.default,this.resolvedType instanceof xA&&typeof this.typeDefault==="string")this.typeDefault=this.resolvedType.values[this.typeDefault]}if(this.options){if(this.options.packed!==void 0&&this.resolvedType&&!(this.resolvedType instanceof xA))delete this.options.packed;if(!Object.keys(this.options).length)this.options=void 0}if(this.long){if(this.typeDefault=I0.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze)Object.freeze(this.typeDefault)}else if(this.bytes&&typeof this.typeDefault==="string"){var Y;if(I0.base64.test(this.typeDefault))I0.base64.decode(this.typeDefault,Y=I0.newBuffer(I0.base64.length(this.typeDefault)),0);else I0.utf8.write(this.typeDefault,Y=I0.newBuffer(I0.utf8.length(this.typeDefault)),0);this.typeDefault=Y}if(this.map)this.defaultValue=I0.emptyObject;else if(this.repeated)this.defaultValue=I0.emptyArray;else this.defaultValue=this.typeDefault;if(this.parent instanceof nT)this.parent.ctor.prototype[this.name]=this.defaultValue;return iT.prototype.resolve.call(this)};S0.prototype._inferLegacyProtoFeatures=function(Y){if(Y!=="proto2"&&Y!=="proto3")return{};var T={};if(this.rule==="required")T.field_presence="LEGACY_REQUIRED";if(this.parent&&q5.defaults[this.type]===void 0){var q=this.parent.get(this.type.split(".").pop());if(q&&q instanceof nT&&q.group)T.message_encoding="DELIMITED"}if(this.getOption("packed")===!0)T.repeated_field_encoding="PACKED";else if(this.getOption("packed")===!1)T.repeated_field_encoding="EXPANDED";return T};S0.prototype._resolveFeatures=function(Y){return iT.prototype._resolveFeatures.call(this,this._edition||Y)};S0.d=function(Y,T,q,X){if(typeof T==="function")T=I0.decorateType(T).name;else if(T&&typeof T==="object")T=I0.decorateEnum(T).name;return function(Q,U){I0.decorateType(Q.constructor).add(new S0(U,Y,T,q,{default:X}))}};S0._configure=function(Y){nT=Y}});var o$=M((fg,gA)=>{gA.exports=q1;var zq=L$();((q1.prototype=Object.create(zq.prototype)).constructor=q1).className="OneOf";var hA=P$(),Hq=w0();function q1($,Y,T,q){if(!Array.isArray(Y))T=Y,Y=void 0;if(zq.call(this,$,T),!(Y===void 0||Array.isArray(Y)))throw TypeError("fieldNames must be an Array");this.oneof=Y||[],this.fieldsArray=[],this.comment=q}q1.fromJSON=function(Y,T){return new q1(Y,T.oneof,T.options,T.comment)};q1.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return Hq.toObject(["options",this.options,"oneof",this.oneof,"comment",T?this.comment:void 0])};function _A($){if($.parent){for(var Y=0;Y<$.fieldsArray.length;++Y)if(!$.fieldsArray[Y].parent)$.parent.add($.fieldsArray[Y])}}q1.prototype.add=function(Y){if(!(Y instanceof hA))throw TypeError("field must be a Field");if(Y.parent&&Y.parent!==this.parent)Y.parent.remove(Y);return this.oneof.push(Y.name),this.fieldsArray.push(Y),Y.partOf=this,_A(this),this};q1.prototype.remove=function(Y){if(!(Y instanceof hA))throw TypeError("field must be a Field");var T=this.fieldsArray.indexOf(Y);if(T<0)throw Error(Y+" is not a member of "+this);if(this.fieldsArray.splice(T,1),T=this.oneof.indexOf(Y.name),T>-1)this.oneof.splice(T,1);return Y.partOf=null,this};q1.prototype.onAdd=function(Y){zq.prototype.onAdd.call(this,Y);var T=this;for(var q=0;q<this.oneof.length;++q){var X=Y.get(this.oneof[q]);if(X&&!X.partOf)X.partOf=T,T.fieldsArray.push(X)}_A(this)};q1.prototype.onRemove=function(Y){for(var T=0,q;T<this.fieldsArray.length;++T)if((q=this.fieldsArray[T]).parent)q.parent.remove(q);zq.prototype.onRemove.call(this,Y)};Object.defineProperty(q1.prototype,"isProto3Optional",{get:function(){if(this.fieldsArray==null||this.fieldsArray.length!==1)return!1;var $=this.fieldsArray[0];return $.options!=null&&$.options.proto3_optional===!0}});q1.d=function(){var Y=Array(arguments.length),T=0;while(T<arguments.length)Y[T]=arguments[T++];return function(X,J){Hq.decorateType(X.constructor).add(new q1(J,Y)),Object.defineProperty(X,J,{get:Hq.oneOfGetter(Y),set:Hq.oneOfSetter(Y)})}}});var L$=M((bg,mA)=>{mA.exports=x0;x0.className="ReflectionObject";var G2=o$(),rT=w0(),Iq,E2={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},V2={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},D2={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function x0($,Y){if(!rT.isString($))throw TypeError("name must be a string");if(Y&&!rT.isObject(Y))throw TypeError("options must be an object");this.options=Y,this.parsedOptions=null,this.name=$,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(x0.prototype,{root:{get:function(){var $=this;while($.parent!==null)$=$.parent;return $}},fullName:{get:function(){var $=[this.name],Y=this.parent;while(Y)$.unshift(Y.name),Y=Y.parent;return $.join(".")}}});x0.prototype.toJSON=function(){throw Error()};x0.prototype.onAdd=function(Y){if(this.parent&&this.parent!==Y)this.parent.remove(this);this.parent=Y,this.resolved=!1;var T=Y.root;if(T instanceof Iq)T._handleAdd(this)};x0.prototype.onRemove=function(Y){var T=Y.root;if(T instanceof Iq)T._handleRemove(this);this.parent=null,this.resolved=!1};x0.prototype.resolve=function(){if(this.resolved)return this;if(this.root instanceof Iq)this.resolved=!0;return this};x0.prototype._resolveFeaturesRecursive=function(Y){return this._resolveFeatures(this._edition||Y)};x0.prototype._resolveFeatures=function(Y){if(this._featuresResolved)return;var T={};if(!Y)throw Error("Unknown edition for "+this.fullName);var q=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(Y));if(this._edition){if(Y==="proto2")T=Object.assign({},V2);else if(Y==="proto3")T=Object.assign({},D2);else if(Y==="2023")T=Object.assign({},E2);else throw Error("Unknown edition: "+Y);this._features=Object.assign(T,q||{}),this._featuresResolved=!0;return}if(this.partOf instanceof G2){var X=Object.assign({},this.partOf._features);this._features=Object.assign(X,q||{})}else if(this.declaringField);else if(this.parent){var J=Object.assign({},this.parent._features);this._features=Object.assign(J,q||{})}else throw Error("Unable to find a parent for "+this.fullName);if(this.extensionField)this.extensionField._features=this._features;this._featuresResolved=!0};x0.prototype._inferLegacyProtoFeatures=function(){return{}};x0.prototype.getOption=function(Y){if(this.options)return this.options[Y];return};x0.prototype.setOption=function(Y,T,q){if(!this.options)this.options={};if(/^features\./.test(Y))rT.setProperty(this.options,Y,T,q);else if(!q||this.options[Y]===void 0){if(this.getOption(Y)!==T)this.resolved=!1;this.options[Y]=T}return this};x0.prototype.setParsedOption=function(Y,T,q){if(!this.parsedOptions)this.parsedOptions=[];var X=this.parsedOptions;if(q){var J=X.find(function(Z){return Object.prototype.hasOwnProperty.call(Z,Y)});if(J){var Q=J[Y];rT.setProperty(Q,q,T)}else J={},J[Y]=rT.setProperty({},q,T),X.push(J)}else{var U={};U[Y]=T,X.push(U)}return this};x0.prototype.setOptions=function(Y,T){if(Y)for(var q=Object.keys(Y),X=0;X<q.length;++X)this.setOption(q[X],Y[q[X]],T);return this};x0.prototype.toString=function(){var Y=this.constructor.className,T=this.fullName;if(T.length)return Y+" "+T;return Y};x0.prototype._editionToJSON=function(){if(!this._edition||this._edition==="proto3")return;return this._edition};x0._configure=function($){Iq=$}});var w1=M((ug,bA)=>{bA.exports=S1;var X5=L$();((S1.prototype=Object.create(X5.prototype)).constructor=S1).className="Enum";var fA=kY(),Mq=w0();function S1($,Y,T,q,X,J){if(X5.call(this,$,T),Y&&typeof Y!=="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=q,this.comments=X||{},this.valuesOptions=J,this._valuesFeatures={},this.reserved=void 0,Y){for(var Q=Object.keys(Y),U=0;U<Q.length;++U)if(typeof Y[Q[U]]==="number")this.valuesById[this.values[Q[U]]=Y[Q[U]]]=Q[U]}}S1.prototype._resolveFeatures=function(Y){return Y=this._edition||Y,X5.prototype._resolveFeatures.call(this,Y),Object.keys(this.values).forEach((T)=>{var q=Object.assign({},this._features);this._valuesFeatures[T]=Object.assign(q,this.valuesOptions&&this.valuesOptions[T]&&this.valuesOptions[T].features)}),this};S1.fromJSON=function(Y,T){var q=new S1(Y,T.values,T.options,T.comment,T.comments);if(q.reserved=T.reserved,T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};S1.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return Mq.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",T?this.comment:void 0,"comments",T?this.comments:void 0])};S1.prototype.add=function(Y,T,q,X){if(!Mq.isString(Y))throw TypeError("name must be a string");if(!Mq.isInteger(T))throw TypeError("id must be an integer");if(this.values[Y]!==void 0)throw Error("duplicate name '"+Y+"' in "+this);if(this.isReservedId(T))throw Error("id "+T+" is reserved in "+this);if(this.isReservedName(Y))throw Error("name '"+Y+"' is reserved in "+this);if(this.valuesById[T]!==void 0){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+T+" in "+this);this.values[Y]=T}else this.valuesById[this.values[Y]=T]=Y;if(X){if(this.valuesOptions===void 0)this.valuesOptions={};this.valuesOptions[Y]=X||null}return this.comments[Y]=q||null,this};S1.prototype.remove=function(Y){if(!Mq.isString(Y))throw TypeError("name must be a string");var T=this.values[Y];if(T==null)throw Error("name '"+Y+"' does not exist in "+this);if(delete this.valuesById[T],delete this.values[Y],delete this.comments[Y],this.valuesOptions)delete this.valuesOptions[Y];return this};S1.prototype.isReservedId=function(Y){return fA.isReservedId(this.reserved,Y)};S1.prototype.isReservedName=function(Y){return fA.isReservedName(this.reserved,Y)}});var sX=M((dg,dA)=>{dA.exports=N2;var F2=w1(),J5=s$(),Q5=w0();function uA($,Y,T,q){return Y.delimited?$("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",T,q,(Y.id<<3|3)>>>0,(Y.id<<3|4)>>>0):$("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",T,q,(Y.id<<3|2)>>>0)}function N2($){var Y=Q5.codegen(["m","w"],$.name+"$encode")("if(!w)")("w=Writer.create()"),T,q,X=$.fieldsArray.slice().sort(Q5.compareFieldsById);for(var T=0;T<X.length;++T){var J=X[T].resolve(),Q=$._fieldsArray.indexOf(J),U=J.resolvedType instanceof F2?"int32":J.type,Z=J5.basic[U];if(q="m"+Q5.safeProp(J.name),J.map){if(Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",q,J.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",q)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(J.id<<3|2)>>>0,8|J5.mapKey[J.keyType],J.keyType),Z===void 0)Y("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",Q,q);else Y(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|Z,U,q);Y("}")("}")}else if(J.repeated){if(Y("if(%s!=null&&%s.length){",q,q),J.packed&&J5.packed[U]!==void 0)Y("w.uint32(%i).fork()",(J.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",q)("w.%s(%s[i])",U,q)("w.ldelim()");else if(Y("for(var i=0;i<%s.length;++i)",q),Z===void 0)uA(Y,J,Q,q+"[i]");else Y("w.uint32(%i).%s(%s[i])",(J.id<<3|Z)>>>0,U,q);Y("}")}else{if(J.optional)Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",q,J.name);if(Z===void 0)uA(Y,J,Q,q);else Y("w.uint32(%i).%s(%s)",(J.id<<3|Z)>>>0,U,q)}}return Y("return w")}});var pA=M((cg,cA)=>{var e=cA.exports=qA();e.build="light";function H2($,Y,T){if(typeof Y==="function")T=Y,Y=new e.Root;else if(!Y)Y=new e.Root;return Y.load($,T)}e.load=H2;function z2($,Y){if(!Y)Y=new e.Root;return Y.loadSync($)}e.loadSync=z2;e.encoder=sX();e.decoder=bX();e.verifier=cX();e.converter=nX();e.ReflectionObject=L$();e.Namespace=kY();e.Root=Nq();e.Enum=w1();e.Type=Eq();e.Field=P$();e.OneOf=o$();e.MapField=Uq();e.Service=Kq();e.Method=Zq();e.Message=Aq();e.wrappers=iX();e.types=s$();e.util=w0();e.ReflectionObject._configure(e.Root);e.Namespace._configure(e.Type,e.Service,e.Enum);e.Root._configure(e.Type);e.Field._configure(e.Type)});var Z5=M((pg,iA)=>{iA.exports=nA;var U5=/[\s{}=;:[\],'"()<>]/g,I2=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,M2=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,B2=/^ *[*/]+ */,R2=/^\s*\*?\/*/,O2=/\n/g,P2=/\s/,L2=/\\(.?)/g,w2={"0":"\x00",r:"\r",n:`
|
|
9
|
-
`,t:"\t"};function
|
|
10
|
-
`){k.lineEmpty=!0;break}while(j===" "||j==="\t");var
|
|
11
|
-
`).trim(),Q[X]=k,J=X}function
|
|
12
|
-
`)_++;return _}function H(){if(U.length>0)return U.shift();if(Z)return A();var z,_,y,k,m,C=T===0;do{if(T===q)return null;z=!1;while(
|
|
8
|
+
}`}return q.toString=X,q}xX.verbose=!1});var WA=B((Cg,AA)=>{AA.exports=f6;var fR=NX(),bR=zX(),kX=bR("fs");function f6($,Y,T){if(typeof Y==="function")T=Y,Y={};else if(!Y)Y={};if(!T)return fR(f6,this,$,Y);if(!Y.xhr&&kX&&kX.readFile)return kX.readFile($,function(X,J){return X&&typeof XMLHttpRequest<"u"?f6.xhr($,Y,T):X?T(X):T(null,Y.binary?J:J.toString("utf8"))});return f6.xhr($,Y,T)}f6.xhr=function(Y,T,q){var X=new XMLHttpRequest;if(X.onreadystatechange=function(){if(X.readyState!==4)return;if(X.status!==0&&X.status!==200)return q(Error("status "+X.status));if(T.binary){var Q=X.response;if(!Q){Q=[];for(var U=0;U<X.responseText.length;++U)Q.push(X.responseText.charCodeAt(U)&255)}return q(null,typeof Uint8Array<"u"?new Uint8Array(Q):Q)}return q(null,X.responseText)},T.binary){if("overrideMimeType"in X)X.overrideMimeType("text/plain; charset=x-user-defined");X.responseType="arraybuffer"}X.open("GET",Y),X.send()}});var VA=B((EA)=>{var _X=EA,GA=_X.isAbsolute=function(Y){return/^(?:\/|\w+:)/.test(Y)},hX=_X.normalize=function(Y){Y=Y.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var T=Y.split("/"),q=GA(Y),X="";if(q)X=T.shift()+"/";for(var J=0;J<T.length;)if(T[J]==="..")if(J>0&&T[J-1]!=="..")T.splice(--J,2);else if(q)T.splice(J,1);else++J;else if(T[J]===".")T.splice(J,1);else++J;return X+T.join("/")};_X.resolve=function(Y,T,q){if(!q)T=hX(T);if(GA(T))return T;if(!q)Y=hX(Y);return(Y=Y.replace(/(?:\/|^)[^/]+$/,"")).length?hX(Y+"/"+T):T}});var kY=B((jg,NA)=>{NA.exports=t;var Qq=L$();((t.prototype=Object.create(Qq.prototype)).constructor=t).className="Namespace";var gX=P$(),Uq=w0(),uR=o$(),r$,xY,a$;t.fromJSON=function(Y,T){return new t(Y,T.options).addJSON(T.nested)};function DA($,Y){if(!($&&$.length))return;var T={};for(var q=0;q<$.length;++q)T[$[q].name]=$[q].toJSON(Y);return T}t.arrayToJSON=DA;t.isReservedId=function(Y,T){if(Y){for(var q=0;q<Y.length;++q)if(typeof Y[q]!=="string"&&Y[q][0]<=T&&Y[q][1]>T)return!0}return!1};t.isReservedName=function(Y,T){if(Y){for(var q=0;q<Y.length;++q)if(Y[q]===T)return!0}return!1};function t($,Y){Qq.call(this,$,Y),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function FA($){$._nestedArray=null,$._lookupCache={};var Y=$;while(Y=Y.parent)Y._lookupCache={};return $}Object.defineProperty(t.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=Uq.toArray(this.nested))}});t.prototype.toJSON=function(Y){return Uq.toObject(["options",this.options,"nested",DA(this.nestedArray,Y)])};t.prototype.addJSON=function(Y){var T=this;if(Y)for(var q=Object.keys(Y),X=0,J;X<q.length;++X)J=Y[q[X]],T.add((J.fields!==void 0?r$.fromJSON:J.values!==void 0?a$.fromJSON:J.methods!==void 0?xY.fromJSON:J.id!==void 0?gX.fromJSON:t.fromJSON)(q[X],J));return this};t.prototype.get=function(Y){return this.nested&&this.nested[Y]||null};t.prototype.getEnum=function(Y){if(this.nested&&this.nested[Y]instanceof a$)return this.nested[Y].values;throw Error("no such enum: "+Y)};t.prototype.add=function(Y){if(!(Y instanceof gX&&Y.extend!==void 0||Y instanceof r$||Y instanceof uR||Y instanceof a$||Y instanceof xY||Y instanceof t))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var T=this.get(Y.name);if(T)if(T instanceof t&&Y instanceof t&&!(T instanceof r$||T instanceof xY)){var q=T.nestedArray;for(var X=0;X<q.length;++X)Y.add(q[X]);if(this.remove(T),!this.nested)this.nested={};Y.setOptions(T.options,!0)}else throw Error("duplicate name '"+Y.name+"' in "+this)}if(this.nested[Y.name]=Y,!(this instanceof r$||this instanceof xY||this instanceof a$||this instanceof gX)){if(!Y._edition)Y._edition=Y._defaultEdition}this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;var J=this;while(J=J.parent)J._needsRecursiveFeatureResolution=!0,J._needsRecursiveResolve=!0;return Y.onAdd(this),FA(this)};t.prototype.remove=function(Y){if(!(Y instanceof Qq))throw TypeError("object must be a ReflectionObject");if(Y.parent!==this)throw Error(Y+" is not a member of "+this);if(delete this.nested[Y.name],!Object.keys(this.nested).length)this.nested=void 0;return Y.onRemove(this),FA(this)};t.prototype.define=function(Y,T){if(Uq.isString(Y))Y=Y.split(".");else if(!Array.isArray(Y))throw TypeError("illegal path");if(Y&&Y.length&&Y[0]==="")throw Error("path must be relative");var q=this;while(Y.length>0){var X=Y.shift();if(q.nested&&q.nested[X]){if(q=q.nested[X],!(q instanceof t))throw Error("path conflicts with non-namespace objects")}else q.add(q=new t(X))}if(T)q.addJSON(T);return q};t.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var Y=this.nestedArray,T=0;this.resolve();while(T<Y.length)if(Y[T]instanceof t)Y[T++].resolveAll();else Y[T++].resolve();return this._needsRecursiveResolve=!1,this};t.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return this._needsRecursiveFeatureResolution=!1,Y=this._edition||Y,Qq.prototype._resolveFeaturesRecursive.call(this,Y),this.nestedArray.forEach((T)=>{T._resolveFeaturesRecursive(Y)}),this};t.prototype.lookup=function(Y,T,q){if(typeof T==="boolean")q=T,T=void 0;else if(T&&!Array.isArray(T))T=[T];if(Uq.isString(Y)&&Y.length){if(Y===".")return this.root;Y=Y.split(".")}else if(!Y.length)return this;var X=Y.join(".");if(Y[0]==="")return this.root.lookup(Y.slice(1),T);var J=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+X];if(J&&(!T||T.indexOf(J.constructor)>-1))return J;if(J=this._lookupImpl(Y,X),J&&(!T||T.indexOf(J.constructor)>-1))return J;if(q)return null;var Q=this;while(Q.parent){if(J=Q.parent._lookupImpl(Y,X),J&&(!T||T.indexOf(J.constructor)>-1))return J;Q=Q.parent}return null};t.prototype._lookupImpl=function(Y,T){if(Object.prototype.hasOwnProperty.call(this._lookupCache,T))return this._lookupCache[T];var q=this.get(Y[0]),X=null;if(q){if(Y.length===1)X=q;else if(q instanceof t)Y=Y.slice(1),X=q._lookupImpl(Y,Y.join("."))}else for(var J=0;J<this.nestedArray.length;++J)if(this._nestedArray[J]instanceof t&&(q=this._nestedArray[J]._lookupImpl(Y,T)))X=q;return this._lookupCache[T]=X,X};t.prototype.lookupType=function(Y){var T=this.lookup(Y,[r$]);if(!T)throw Error("no such type: "+Y);return T};t.prototype.lookupEnum=function(Y){var T=this.lookup(Y,[a$]);if(!T)throw Error("no such Enum '"+Y+"' in "+this);return T};t.prototype.lookupTypeOrEnum=function(Y){var T=this.lookup(Y,[r$,a$]);if(!T)throw Error("no such Type or Enum '"+Y+"' in "+this);return T};t.prototype.lookupService=function(Y){var T=this.lookup(Y,[xY]);if(!T)throw Error("no such Service '"+Y+"' in "+this);return T};t._configure=function($,Y,T){r$=$,xY=Y,a$=T}});var Zq=B((vg,HA)=>{HA.exports=q$;var mX=P$();((q$.prototype=Object.create(mX.prototype)).constructor=q$).className="MapField";var dR=s$(),b6=w0();function q$($,Y,T,q,X,J){if(mX.call(this,$,Y,q,void 0,void 0,X,J),!b6.isString(T))throw TypeError("keyType must be a string");this.keyType=T,this.resolvedKeyType=null,this.map=!0}q$.fromJSON=function(Y,T){return new q$(Y,T.id,T.keyType,T.type,T.options,T.comment)};q$.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return b6.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",T?this.comment:void 0])};q$.prototype.resolve=function(){if(this.resolved)return this;if(dR.mapKey[this.keyType]===void 0)throw Error("invalid key type: "+this.keyType);return mX.prototype.resolve.call(this)};q$.d=function(Y,T,q){if(typeof q==="function")q=b6.decorateType(q).name;else if(q&&typeof q==="object")q=b6.decorateEnum(q).name;return function(J,Q){b6.decorateType(J.constructor).add(new q$(Q,Y,T,q))}}});var Kq=B((xg,zA)=>{zA.exports=t$;var fX=L$();((t$.prototype=Object.create(fX.prototype)).constructor=t$).className="Method";var hY=w0();function t$($,Y,T,q,X,J,Q,U,Z){if(hY.isObject(X))Q=X,X=J=void 0;else if(hY.isObject(J))Q=J,J=void 0;if(!(Y===void 0||hY.isString(Y)))throw TypeError("type must be a string");if(!hY.isString(T))throw TypeError("requestType must be a string");if(!hY.isString(q))throw TypeError("responseType must be a string");fX.call(this,$,Q),this.type=Y||"rpc",this.requestType=T,this.requestStream=X?!0:void 0,this.responseType=q,this.responseStream=J?!0:void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=U,this.parsedOptions=Z}t$.fromJSON=function(Y,T){return new t$(Y,T.type,T.requestType,T.responseType,T.requestStream,T.responseStream,T.options,T.comment,T.parsedOptions)};t$.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return hY.toObject(["type",this.type!=="rpc"&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",T?this.comment:void 0,"parsedOptions",this.parsedOptions])};t$.prototype.resolve=function(){if(this.resolved)return this;return this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),fX.prototype.resolve.call(this)}});var Aq=B((kg,MA)=>{MA.exports=Y1;var X$=kY();((Y1.prototype=Object.create(X$.prototype)).constructor=Y1).className="Service";var bX=Kq(),u6=w0(),cR=jX();function Y1($,Y){X$.call(this,$,Y),this.methods={},this._methodsArray=null}Y1.fromJSON=function(Y,T){var q=new Y1(Y,T.options);if(T.methods)for(var X=Object.keys(T.methods),J=0;J<X.length;++J)q.add(bX.fromJSON(X[J],T.methods[X[J]]));if(T.nested)q.addJSON(T.nested);if(T.edition)q._edition=T.edition;return q.comment=T.comment,q._defaultEdition="proto3",q};Y1.prototype.toJSON=function(Y){var T=X$.prototype.toJSON.call(this,Y),q=Y?Boolean(Y.keepComments):!1;return u6.toObject(["edition",this._editionToJSON(),"options",T&&T.options||void 0,"methods",X$.arrayToJSON(this.methodsArray,Y)||{},"nested",T&&T.nested||void 0,"comment",q?this.comment:void 0])};Object.defineProperty(Y1.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=u6.toArray(this.methods))}});function IA($){return $._methodsArray=null,$}Y1.prototype.get=function(Y){return this.methods[Y]||X$.prototype.get.call(this,Y)};Y1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;X$.prototype.resolve.call(this);var Y=this.methodsArray;for(var T=0;T<Y.length;++T)Y[T].resolve();return this};Y1.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,X$.prototype._resolveFeaturesRecursive.call(this,Y),this.methodsArray.forEach((T)=>{T._resolveFeaturesRecursive(Y)}),this};Y1.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof bX)return this.methods[Y.name]=Y,Y.parent=this,IA(this);return X$.prototype.add.call(this,Y)};Y1.prototype.remove=function(Y){if(Y instanceof bX){if(this.methods[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.methods[Y.name],Y.parent=null,IA(this)}return X$.prototype.remove.call(this,Y)};Y1.prototype.create=function(Y,T,q){var X=new cR.Service(Y,T,q);for(var J=0,Q;J<this.methodsArray.length;++J){var U=u6.lcFirst((Q=this._methodsArray[J]).resolve().name).replace(/[^$\w_]/g,"");X[U]=u6.codegen(["r","c"],u6.isReserved(U)?U+"_":U)("return this.rpcCall(m,q,s,r,c)")({m:Q,q:Q.resolvedRequestType.ctor,s:Q.resolvedResponseType.ctor})}return X}});var Wq=B((hg,BA)=>{BA.exports=m1;var pR=_1();function m1($){if($)for(var Y=Object.keys($),T=0;T<Y.length;++T)this[Y[T]]=$[Y[T]]}m1.create=function(Y){return this.$type.create(Y)};m1.encode=function(Y,T){return this.$type.encode(Y,T)};m1.encodeDelimited=function(Y,T){return this.$type.encodeDelimited(Y,T)};m1.decode=function(Y){return this.$type.decode(Y)};m1.decodeDelimited=function(Y){return this.$type.decodeDelimited(Y)};m1.verify=function(Y){return this.$type.verify(Y)};m1.fromObject=function(Y){return this.$type.fromObject(Y)};m1.toObject=function(Y,T){return this.$type.toObject(Y,T)};m1.prototype.toJSON=function(){return this.$type.toObject(this,pR.toJSONOptions)}});var uX=B((_g,OA)=>{OA.exports=iR;var lR=w1(),J$=s$(),RA=w0();function nR($){return"missing required '"+$.name+"'"}function iR($){var Y=RA.codegen(["r","l","e"],$.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+($.fieldsArray.filter(function(U){return U.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),T=0;for(;T<$.fieldsArray.length;++T){var q=$._fieldsArray[T].resolve(),X=q.resolvedType instanceof lR?"int32":q.type,J="m"+RA.safeProp(q.name);if(Y("case %i: {",q.id),q.map){if(Y("if(%s===util.emptyObject)",J)("%s={}",J)("var c2 = r.uint32()+r.pos"),J$.defaults[q.keyType]!==void 0)Y("k=%j",J$.defaults[q.keyType]);else Y("k=null");if(J$.defaults[X]!==void 0)Y("value=%j",J$.defaults[X]);else Y("value=null");if(Y("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",q.keyType)("case 2:"),J$.basic[X]===void 0)Y("value=types[%i].decode(r,r.uint32())",T);else Y("value=r.%s()",X);if(Y("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),J$.long[q.keyType]!==void 0)Y('%s[typeof k==="object"?util.longToHash(k):k]=value',J);else Y("%s[k]=value",J)}else if(q.repeated){if(Y("if(!(%s&&%s.length))",J,J)("%s=[]",J),J$.packed[X]!==void 0)Y("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",J,X)("}else");if(J$.basic[X]===void 0)Y(q.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",J,T);else Y("%s.push(r.%s())",J,X)}else if(J$.basic[X]===void 0)Y(q.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",J,T);else Y("%s=r.%s()",J,X);Y("break")("}")}Y("default:")("r.skipType(t&7)")("break")("}")("}");for(T=0;T<$._fieldsArray.length;++T){var Q=$._fieldsArray[T];if(Q.required)Y("if(!m.hasOwnProperty(%j))",Q.name)("throw util.ProtocolError(%j,{instance:m})",nR(Q))}return Y("return m")}});var pX=B((gg,PA)=>{PA.exports=oR;var rR=w1(),dX=w0();function D1($,Y){return $.name+": "+Y+($.repeated&&Y!=="array"?"[]":$.map&&Y!=="object"?"{k:"+$.keyType+"}":"")+" expected"}function cX($,Y,T,q){if(Y.resolvedType)if(Y.resolvedType instanceof rR){$("switch(%s){",q)("default:")("return%j",D1(Y,"enum value"));for(var X=Object.keys(Y.resolvedType.values),J=0;J<X.length;++J)$("case %i:",Y.resolvedType.values[X[J]]);$("break")("}")}else $("{")("var e=types[%i].verify(%s);",T,q)("if(e)")("return%j+e",Y.name+".")("}");else switch(Y.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.isInteger(%s))",q)("return%j",D1(Y,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",q,q,q,q)("return%j",D1(Y,"integer|Long"));break;case"float":case"double":$('if(typeof %s!=="number")',q)("return%j",D1(Y,"number"));break;case"bool":$('if(typeof %s!=="boolean")',q)("return%j",D1(Y,"boolean"));break;case"string":$("if(!util.isString(%s))",q)("return%j",D1(Y,"string"));break;case"bytes":$('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',q,q,q)("return%j",D1(Y,"buffer"));break}return $}function aR($,Y,T){switch(Y.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.key32Re.test(%s))",T)("return%j",D1(Y,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.key64Re.test(%s))",T)("return%j",D1(Y,"integer|Long key"));break;case"bool":$("if(!util.key2Re.test(%s))",T)("return%j",D1(Y,"boolean key"));break}return $}function oR($){var Y=dX.codegen(["m"],$.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),T=$.oneofsArray,q={};if(T.length)Y("var p={}");for(var X=0;X<$.fieldsArray.length;++X){var J=$._fieldsArray[X].resolve(),Q="m"+dX.safeProp(J.name);if(J.optional)Y("if(%s!=null&&m.hasOwnProperty(%j)){",Q,J.name);if(J.map)Y("if(!util.isObject(%s))",Q)("return%j",D1(J,"object"))("var k=Object.keys(%s)",Q)("for(var i=0;i<k.length;++i){"),aR(Y,J,"k[i]"),cX(Y,J,X,Q+"[k[i]]")("}");else if(J.repeated)Y("if(!Array.isArray(%s))",Q)("return%j",D1(J,"array"))("for(var i=0;i<%s.length;++i){",Q),cX(Y,J,X,Q+"[i]")("}");else{if(J.partOf){var U=dX.safeProp(J.partOf.name);if(q[J.partOf.name]===1)Y("if(p%s===1)",U)("return%j",J.partOf.name+": multiple values");q[J.partOf.name]=1,Y("p%s=1",U)}cX(Y,J,X,Q)}if(J.optional)Y("}")}return Y("return null")}});var iX=B((wA)=>{var LA=wA,d6=w1(),f1=w0();function lX($,Y,T,q){var X=!1;if(Y.resolvedType)if(Y.resolvedType instanceof d6){$("switch(d%s){",q);for(var J=Y.resolvedType.values,Q=Object.keys(J),U=0;U<Q.length;++U){if(J[Q[U]]===Y.typeDefault&&!X){if($("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',q,q,q),!Y.repeated)$("break");X=!0}$("case%j:",Q[U])("case %i:",J[Q[U]])("m%s=%j",q,J[Q[U]])("break")}$("}")}else $('if(typeof d%s!=="object")',q)("throw TypeError(%j)",Y.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",q,T,q);else{var Z=!1;switch(Y.type){case"double":case"float":$("m%s=Number(d%s)",q,q);break;case"uint32":case"fixed32":$("m%s=d%s>>>0",q,q);break;case"int32":case"sint32":case"sfixed32":$("m%s=d%s|0",q,q);break;case"uint64":Z=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",q,q,Z)('else if(typeof d%s==="string")',q)("m%s=parseInt(d%s,10)",q,q)('else if(typeof d%s==="number")',q)("m%s=d%s",q,q)('else if(typeof d%s==="object")',q)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",q,q,q,Z?"true":"");break;case"bytes":$('if(typeof d%s==="string")',q)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",q,q,q)("else if(d%s.length >= 0)",q)("m%s=d%s",q,q);break;case"string":$("m%s=String(d%s)",q,q);break;case"bool":$("m%s=Boolean(d%s)",q,q);break}}return $}LA.fromObject=function(Y){var T=Y.fieldsArray,q=f1.codegen(["d"],Y.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!T.length)return q("return new this.ctor");q("var m=new this.ctor");for(var X=0;X<T.length;++X){var J=T[X].resolve(),Q=f1.safeProp(J.name);if(J.map)q("if(d%s){",Q)('if(typeof d%s!=="object")',Q)("throw TypeError(%j)",J.fullName+": object expected")("m%s={}",Q)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",Q),lX(q,J,X,Q+"[ks[i]]")("}")("}");else if(J.repeated)q("if(d%s){",Q)("if(!Array.isArray(d%s))",Q)("throw TypeError(%j)",J.fullName+": array expected")("m%s=[]",Q)("for(var i=0;i<d%s.length;++i){",Q),lX(q,J,X,Q+"[i]")("}")("}");else{if(!(J.resolvedType instanceof d6))q("if(d%s!=null){",Q);if(lX(q,J,X,Q),!(J.resolvedType instanceof d6))q("}")}}return q("return m")};function nX($,Y,T,q){if(Y.resolvedType)if(Y.resolvedType instanceof d6)$("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",q,T,q,q,T,q,q);else $("d%s=types[%i].toObject(m%s,o)",q,T,q);else{var X=!1;switch(Y.type){case"double":case"float":$("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",q,q,q,q);break;case"uint64":X=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$('if(typeof m%s==="number")',q)("d%s=o.longs===String?String(m%s):m%s",q,q,q)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",q,q,q,q,X?"true":"",q);break;case"bytes":$("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",q,q,q,q,q);break;default:$("d%s=m%s",q,q);break}}return $}LA.toObject=function(Y){var T=Y.fieldsArray.slice().sort(f1.compareFieldsById);if(!T.length)return f1.codegen()("return {}");var q=f1.codegen(["m","o"],Y.name+"$toObject")("if(!o)")("o={}")("var d={}"),X=[],J=[],Q=[],U=0;for(;U<T.length;++U)if(!T[U].partOf)(T[U].resolve().repeated?X:T[U].map?J:Q).push(T[U]);if(X.length){q("if(o.arrays||o.defaults){");for(U=0;U<X.length;++U)q("d%s=[]",f1.safeProp(X[U].name));q("}")}if(J.length){q("if(o.objects||o.defaults){");for(U=0;U<J.length;++U)q("d%s={}",f1.safeProp(J[U].name));q("}")}if(Q.length){q("if(o.defaults){");for(U=0;U<Q.length;++U){var Z=Q[U],K=f1.safeProp(Z.name);if(Z.resolvedType instanceof d6)q("d%s=o.enums===String?%j:%j",K,Z.resolvedType.valuesById[Z.typeDefault],Z.typeDefault);else if(Z.long)q("if(util.Long){")("var n=new util.Long(%i,%i,%j)",Z.typeDefault.low,Z.typeDefault.high,Z.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",K)("}else")("d%s=o.longs===String?%j:%i",K,Z.typeDefault.toString(),Z.typeDefault.toNumber());else if(Z.bytes){var A="["+Array.prototype.slice.call(Z.typeDefault).join(",")+"]";q("if(o.bytes===String)d%s=%j",K,String.fromCharCode.apply(String,Z.typeDefault))("else{")("d%s=%s",K,A)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",K,K)("}")}else q("d%s=%j",K,Z.typeDefault)}q("}")}var W=!1;for(U=0;U<T.length;++U){var Z=T[U],E=Y._fieldsArray.indexOf(Z),K=f1.safeProp(Z.name);if(Z.map){if(!W)W=!0,q("var ks2");q("if(m%s&&(ks2=Object.keys(m%s)).length){",K,K)("d%s={}",K)("for(var j=0;j<ks2.length;++j){"),nX(q,Z,E,K+"[ks2[j]]")("}")}else if(Z.repeated)q("if(m%s&&m%s.length){",K,K)("d%s=[]",K)("for(var j=0;j<m%s.length;++j){",K),nX(q,Z,E,K+"[j]")("}");else if(q("if(m%s!=null&&m.hasOwnProperty(%j)){",K,Z.name),nX(q,Z,E,K),Z.partOf)q("if(o.oneofs)")("d%s=%j",f1.safeProp(Z.partOf.name),Z.name);q("}")}return q("return d")}});var rX=B((SA)=>{var sR=SA,tR=Wq();sR[".google.protobuf.Any"]={fromObject:function($){if($&&$["@type"]){var Y=$["@type"].substring($["@type"].lastIndexOf("/")+1),T=this.lookup(Y);if(T){var q=$["@type"].charAt(0)==="."?$["@type"].slice(1):$["@type"];if(q.indexOf("/")===-1)q="/"+q;return this.create({type_url:q,value:T.encode(T.fromObject($)).finish()})}}return this.fromObject($)},toObject:function($,Y){var T="type.googleapis.com/",q="",X="";if(Y&&Y.json&&$.type_url&&$.value){X=$.type_url.substring($.type_url.lastIndexOf("/")+1),q=$.type_url.substring(0,$.type_url.lastIndexOf("/")+1);var J=this.lookup(X);if(J)$=J.decode($.value)}if(!($ instanceof this.ctor)&&$ instanceof tR){var Q=$.$type.toObject($,Y),U=$.$type.fullName[0]==="."?$.$type.fullName.slice(1):$.$type.fullName;if(q==="")q=T;return X=q+U,Q["@type"]=X,Q}return this.toObject($,Y)}}});var Vq=B((bg,yA)=>{yA.exports=Z0;var F1=kY();((Z0.prototype=Object.create(F1.prototype)).constructor=Z0).className="Type";var eR=w1(),sX=o$(),Gq=P$(),$2=Zq(),Y2=Aq(),aX=Wq(),oX=Jq(),T2=qq(),m0=w0(),q2=tX(),X2=uX(),J2=pX(),CA=iX(),Q2=rX();function Z0($,Y){F1.call(this,$,Y),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}Object.defineProperties(Z0.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var $=Object.keys(this.fields),Y=0;Y<$.length;++Y){var T=this.fields[$[Y]],q=T.id;if(this._fieldsById[q])throw Error("duplicate id "+q+" in "+this);this._fieldsById[q]=T}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=m0.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=m0.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=Z0.generateConstructor(this)())},set:function($){var Y=$.prototype;if(!(Y instanceof aX))($.prototype=new aX).constructor=$,m0.merge($.prototype,Y);$.$type=$.prototype.$type=this,m0.merge($,aX,!0),this._ctor=$;var T=0;for(;T<this.fieldsArray.length;++T)this._fieldsArray[T].resolve();var q={};for(T=0;T<this.oneofsArray.length;++T)q[this._oneofsArray[T].resolve().name]={get:m0.oneOfGetter(this._oneofsArray[T].oneof),set:m0.oneOfSetter(this._oneofsArray[T].oneof)};if(T)Object.defineProperties($.prototype,q)}}});Z0.generateConstructor=function(Y){var T=m0.codegen(["p"],Y.name);for(var q=0,X;q<Y.fieldsArray.length;++q)if((X=Y._fieldsArray[q]).map)T("this%s={}",m0.safeProp(X.name));else if(X.repeated)T("this%s=[]",m0.safeProp(X.name));return T("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")};function Eq($){return $._fieldsById=$._fieldsArray=$._oneofsArray=null,delete $.encode,delete $.decode,delete $.verify,$}Z0.fromJSON=function(Y,T){var q=new Z0(Y,T.options);q.extensions=T.extensions,q.reserved=T.reserved;var X=Object.keys(T.fields),J=0;for(;J<X.length;++J)q.add((typeof T.fields[X[J]].keyType<"u"?$2.fromJSON:Gq.fromJSON)(X[J],T.fields[X[J]]));if(T.oneofs)for(X=Object.keys(T.oneofs),J=0;J<X.length;++J)q.add(sX.fromJSON(X[J],T.oneofs[X[J]]));if(T.nested)for(X=Object.keys(T.nested),J=0;J<X.length;++J){var Q=T.nested[X[J]];q.add((Q.id!==void 0?Gq.fromJSON:Q.fields!==void 0?Z0.fromJSON:Q.values!==void 0?eR.fromJSON:Q.methods!==void 0?Y2.fromJSON:F1.fromJSON)(X[J],Q))}if(T.extensions&&T.extensions.length)q.extensions=T.extensions;if(T.reserved&&T.reserved.length)q.reserved=T.reserved;if(T.group)q.group=!0;if(T.comment)q.comment=T.comment;if(T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};Z0.prototype.toJSON=function(Y){var T=F1.prototype.toJSON.call(this,Y),q=Y?Boolean(Y.keepComments):!1;return m0.toObject(["edition",this._editionToJSON(),"options",T&&T.options||void 0,"oneofs",F1.arrayToJSON(this.oneofsArray,Y),"fields",F1.arrayToJSON(this.fieldsArray.filter(function(X){return!X.declaringField}),Y)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",T&&T.nested||void 0,"comment",q?this.comment:void 0])};Z0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;F1.prototype.resolveAll.call(this);var Y=this.oneofsArray;q=0;while(q<Y.length)Y[q++].resolve();var T=this.fieldsArray,q=0;while(q<T.length)T[q++].resolve();return this};Z0.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,F1.prototype._resolveFeaturesRecursive.call(this,Y),this.oneofsArray.forEach((T)=>{T._resolveFeatures(Y)}),this.fieldsArray.forEach((T)=>{T._resolveFeatures(Y)}),this};Z0.prototype.get=function(Y){return this.fields[Y]||this.oneofs&&this.oneofs[Y]||this.nested&&this.nested[Y]||null};Z0.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof Gq&&Y.extend===void 0){if(this._fieldsById?this._fieldsById[Y.id]:this.fieldsById[Y.id])throw Error("duplicate id "+Y.id+" in "+this);if(this.isReservedId(Y.id))throw Error("id "+Y.id+" is reserved in "+this);if(this.isReservedName(Y.name))throw Error("name '"+Y.name+"' is reserved in "+this);if(Y.parent)Y.parent.remove(Y);return this.fields[Y.name]=Y,Y.message=this,Y.onAdd(this),Eq(this)}if(Y instanceof sX){if(!this.oneofs)this.oneofs={};return this.oneofs[Y.name]=Y,Y.onAdd(this),Eq(this)}return F1.prototype.add.call(this,Y)};Z0.prototype.remove=function(Y){if(Y instanceof Gq&&Y.extend===void 0){if(!this.fields||this.fields[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.fields[Y.name],Y.parent=null,Y.onRemove(this),Eq(this)}if(Y instanceof sX){if(!this.oneofs||this.oneofs[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.oneofs[Y.name],Y.parent=null,Y.onRemove(this),Eq(this)}return F1.prototype.remove.call(this,Y)};Z0.prototype.isReservedId=function(Y){return F1.isReservedId(this.reserved,Y)};Z0.prototype.isReservedName=function(Y){return F1.isReservedName(this.reserved,Y)};Z0.prototype.create=function(Y){return new this.ctor(Y)};Z0.prototype.setup=function(){var Y=this.fullName,T=[];for(var q=0;q<this.fieldsArray.length;++q)T.push(this._fieldsArray[q].resolve().resolvedType);this.encode=q2(this)({Writer:T2,types:T,util:m0}),this.decode=X2(this)({Reader:oX,types:T,util:m0}),this.verify=J2(this)({types:T,util:m0}),this.fromObject=CA.fromObject(this)({types:T,util:m0}),this.toObject=CA.toObject(this)({types:T,util:m0});var X=Q2[Y];if(X){var J=Object.create(this);J.fromObject=this.fromObject,this.fromObject=X.fromObject.bind(J),J.toObject=this.toObject,this.toObject=X.toObject.bind(J)}return this};Z0.prototype.encode=function(Y,T){return this.setup().encode(Y,T)};Z0.prototype.encodeDelimited=function(Y,T){return this.encode(Y,T&&T.len?T.fork():T).ldelim()};Z0.prototype.decode=function(Y,T){return this.setup().decode(Y,T)};Z0.prototype.decodeDelimited=function(Y){if(!(Y instanceof oX))Y=oX.create(Y);return this.decode(Y,Y.uint32())};Z0.prototype.verify=function(Y){return this.setup().verify(Y)};Z0.prototype.fromObject=function(Y){return this.setup().fromObject(Y)};Z0.prototype.toObject=function(Y,T){return this.setup().toObject(Y,T)};Z0.d=function(Y){return function(q){m0.decorateType(q,Y)}}});var Hq=B((ug,xA)=>{xA.exports=T1;var Nq=kY();((T1.prototype=Object.create(Nq.prototype)).constructor=T1).className="Root";var Dq=P$(),eX=w1(),U2=o$(),w$=w0(),$5,Y5,c6;function T1($){Nq.call(this,"",$),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}T1.fromJSON=function(Y,T){if(!T)T=new T1;if(Y.options)T.setOptions(Y.options);return T.addJSON(Y.nested).resolveAll()};T1.prototype.resolvePath=w$.path.resolve;T1.prototype.fetch=w$.fetch;function vA(){}T1.prototype.load=function $(Y,T,q){if(typeof T==="function")q=T,T=void 0;var X=this;if(!q)return w$.asPromise($,X,Y,T);var J=q===vA;function Q(V,F){if(!q)return;if(J)throw V;if(F)F.resolveAll();var H=q;q=null,H(V,F)}function U(V){var F=V.lastIndexOf("google/protobuf/");if(F>-1){var H=V.substring(F);if(H in c6)return H}return null}function Z(V,F){try{if(w$.isString(F)&&F.charAt(0)==="{")F=JSON.parse(F);if(!w$.isString(F))X.setOptions(F.options).addJSON(F.nested);else{Y5.filename=V;var H=Y5(F,X,T),D,I=0;if(H.imports){for(;I<H.imports.length;++I)if(D=U(H.imports[I])||X.resolvePath(V,H.imports[I]))K(D)}if(H.weakImports){for(I=0;I<H.weakImports.length;++I)if(D=U(H.weakImports[I])||X.resolvePath(V,H.weakImports[I]))K(D,!0)}}}catch(S){Q(S)}if(!J&&!A)Q(null,X)}function K(V,F){if(V=U(V)||V,X.files.indexOf(V)>-1)return;if(X.files.push(V),V in c6){if(J)Z(V,c6[V]);else++A,setTimeout(function(){--A,Z(V,c6[V])});return}if(J){var H;try{H=w$.fs.readFileSync(V).toString("utf8")}catch(D){if(!F)Q(D);return}Z(V,H)}else++A,X.fetch(V,function(D,I){if(--A,!q)return;if(D){if(!F)Q(D);else if(!A)Q(null,X);return}Z(V,I)})}var A=0;if(w$.isString(Y))Y=[Y];for(var W=0,E;W<Y.length;++W)if(E=X.resolvePath("",Y[W]))K(E);if(J)return X.resolveAll(),X;if(!A)Q(null,X);return X};T1.prototype.loadSync=function(Y,T){if(!w$.isNode)throw Error("not supported");return this.load(Y,T,vA)};T1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(Y){return"'extend "+Y.extend+"' in "+Y.parent.fullName}).join(", "));return Nq.prototype.resolveAll.call(this)};var Fq=/^[A-Z]/;function jA($,Y){var T=Y.parent.lookup(Y.extend);if(T){var q=new Dq(Y.fullName,Y.id,Y.type,Y.rule,void 0,Y.options);if(T.get(q.name))return!0;return q.declaringField=Y,Y.extensionField=q,T.add(q),!0}return!1}T1.prototype._handleAdd=function(Y){if(Y instanceof Dq){if(Y.extend!==void 0&&!Y.extensionField){if(!jA(this,Y))this.deferred.push(Y)}}else if(Y instanceof eX){if(Fq.test(Y.name))Y.parent[Y.name]=Y.values}else if(!(Y instanceof U2)){if(Y instanceof $5)for(var T=0;T<this.deferred.length;)if(jA(this,this.deferred[T]))this.deferred.splice(T,1);else++T;for(var q=0;q<Y.nestedArray.length;++q)this._handleAdd(Y._nestedArray[q]);if(Fq.test(Y.name))Y.parent[Y.name]=Y}if(Y instanceof $5||Y instanceof eX||Y instanceof Dq)this._fullyQualifiedObjects[Y.fullName]=Y};T1.prototype._handleRemove=function(Y){if(Y instanceof Dq){if(Y.extend!==void 0)if(Y.extensionField)Y.extensionField.parent.remove(Y.extensionField),Y.extensionField=null;else{var T=this.deferred.indexOf(Y);if(T>-1)this.deferred.splice(T,1)}}else if(Y instanceof eX){if(Fq.test(Y.name))delete Y.parent[Y.name]}else if(Y instanceof Nq){for(var q=0;q<Y.nestedArray.length;++q)this._handleRemove(Y._nestedArray[q]);if(Fq.test(Y.name))delete Y.parent[Y.name]}delete this._fullyQualifiedObjects[Y.fullName]};T1._configure=function($,Y,T){$5=$,Y5=Y,c6=T}});var w0=B((dg,hA)=>{var F0=hA.exports=_1(),kA=vX(),T5,q5;F0.codegen=KA();F0.fetch=WA();F0.path=VA();F0.fs=F0.inquire("fs");F0.toArray=function(Y){if(Y){var T=Object.keys(Y),q=Array(T.length),X=0;while(X<T.length)q[X]=Y[T[X++]];return q}return[]};F0.toObject=function(Y){var T={},q=0;while(q<Y.length){var X=Y[q++],J=Y[q++];if(J!==void 0)T[X]=J}return T};var Z2=/\\/g,K2=/"/g;F0.isReserved=function(Y){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(Y)};F0.safeProp=function(Y){if(!/^[$\w_]+$/.test(Y)||F0.isReserved(Y))return'["'+Y.replace(Z2,"\\\\").replace(K2,"\\\"")+'"]';return"."+Y};F0.ucFirst=function(Y){return Y.charAt(0).toUpperCase()+Y.substring(1)};var A2=/_([a-z])/g;F0.camelCase=function(Y){return Y.substring(0,1)+Y.substring(1).replace(A2,function(T,q){return q.toUpperCase()})};F0.compareFieldsById=function(Y,T){return Y.id-T.id};F0.decorateType=function(Y,T){if(Y.$type){if(T&&Y.$type.name!==T)F0.decorateRoot.remove(Y.$type),Y.$type.name=T,F0.decorateRoot.add(Y.$type);return Y.$type}if(!T5)T5=Vq();var q=new T5(T||Y.name);return F0.decorateRoot.add(q),q.ctor=Y,Object.defineProperty(Y,"$type",{value:q,enumerable:!1}),Object.defineProperty(Y.prototype,"$type",{value:q,enumerable:!1}),q};var W2=0;F0.decorateEnum=function(Y){if(Y.$type)return Y.$type;if(!q5)q5=w1();var T=new q5("Enum"+W2++,Y);return F0.decorateRoot.add(T),Object.defineProperty(Y,"$type",{value:T,enumerable:!1}),T};F0.setProperty=function(Y,T,q,X){function J(Q,U,Z){var K=U.shift();if(K==="__proto__"||K==="prototype")return Q;if(U.length>0)Q[K]=J(Q[K]||{},U,Z);else{var A=Q[K];if(A&&X)return Q;if(A)Z=[].concat(A).concat(Z);Q[K]=Z}return Q}if(typeof Y!=="object")throw TypeError("dst must be an object");if(!T)throw TypeError("path must be specified");return T=T.split("."),J(Y,T,q)};Object.defineProperty(F0,"decorateRoot",{get:function(){return kA.decorated||(kA.decorated=new(Hq()))}})});var s$=B((_A)=>{var p6=_A,G2=w0(),E2=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function l6($,Y){var T=0,q={};Y|=0;while(T<$.length)q[E2[T+Y]]=$[T++];return q}p6.basic=l6([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);p6.defaults=l6([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",G2.emptyArray,null]);p6.long=l6([0,0,0,1,1],7);p6.mapKey=l6([0,0,0,5,5,0,0,0,1,1,0,2],2);p6.packed=l6([1,5,0,0,0,5,5,0,0,0,1,1,0])});var P$=B((pg,mA)=>{mA.exports=S0;var i6=L$();((S0.prototype=Object.create(i6.prototype)).constructor=S0).className="Field";var gA=w1(),X5=s$(),I0=w0(),n6,V2=/^required|optional|repeated$/;S0.fromJSON=function(Y,T){var q=new S0(Y,T.id,T.type,T.rule,T.extend,T.options,T.comment);if(T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};function S0($,Y,T,q,X,J,Q){if(I0.isObject(q))Q=X,J=q,q=X=void 0;else if(I0.isObject(X))Q=J,J=X,X=void 0;if(i6.call(this,$,J),!I0.isInteger(Y)||Y<0)throw TypeError("id must be a non-negative integer");if(!I0.isString(T))throw TypeError("type must be a string");if(q!==void 0&&!V2.test(q=q.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(X!==void 0&&!I0.isString(X))throw TypeError("extend must be a string");if(q==="proto3_optional")q="optional";this.rule=q&&q!=="optional"?q:void 0,this.type=T,this.id=Y,this.extend=X||void 0,this.repeated=q==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=I0.Long?X5.long[T]!==void 0:!1,this.bytes=T==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=Q}Object.defineProperty(S0.prototype,"required",{get:function(){return this._features.field_presence==="LEGACY_REQUIRED"}});Object.defineProperty(S0.prototype,"optional",{get:function(){return!this.required}});Object.defineProperty(S0.prototype,"delimited",{get:function(){return this.resolvedType instanceof n6&&this._features.message_encoding==="DELIMITED"}});Object.defineProperty(S0.prototype,"packed",{get:function(){return this._features.repeated_field_encoding==="PACKED"}});Object.defineProperty(S0.prototype,"hasPresence",{get:function(){if(this.repeated||this.map)return!1;return this.partOf||this.declaringField||this.extensionField||this._features.field_presence!=="IMPLICIT"}});S0.prototype.setOption=function(Y,T,q){return i6.prototype.setOption.call(this,Y,T,q)};S0.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return I0.toObject(["edition",this._editionToJSON(),"rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",T?this.comment:void 0])};S0.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=X5.defaults[this.type])===void 0)if(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof n6)this.typeDefault=null;else this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]];else if(this.options&&this.options.proto3_optional)this.typeDefault=null;if(this.options&&this.options.default!=null){if(this.typeDefault=this.options.default,this.resolvedType instanceof gA&&typeof this.typeDefault==="string")this.typeDefault=this.resolvedType.values[this.typeDefault]}if(this.options){if(this.options.packed!==void 0&&this.resolvedType&&!(this.resolvedType instanceof gA))delete this.options.packed;if(!Object.keys(this.options).length)this.options=void 0}if(this.long){if(this.typeDefault=I0.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze)Object.freeze(this.typeDefault)}else if(this.bytes&&typeof this.typeDefault==="string"){var Y;if(I0.base64.test(this.typeDefault))I0.base64.decode(this.typeDefault,Y=I0.newBuffer(I0.base64.length(this.typeDefault)),0);else I0.utf8.write(this.typeDefault,Y=I0.newBuffer(I0.utf8.length(this.typeDefault)),0);this.typeDefault=Y}if(this.map)this.defaultValue=I0.emptyObject;else if(this.repeated)this.defaultValue=I0.emptyArray;else this.defaultValue=this.typeDefault;if(this.parent instanceof n6)this.parent.ctor.prototype[this.name]=this.defaultValue;return i6.prototype.resolve.call(this)};S0.prototype._inferLegacyProtoFeatures=function(Y){if(Y!=="proto2"&&Y!=="proto3")return{};var T={};if(this.rule==="required")T.field_presence="LEGACY_REQUIRED";if(this.parent&&X5.defaults[this.type]===void 0){var q=this.parent.get(this.type.split(".").pop());if(q&&q instanceof n6&&q.group)T.message_encoding="DELIMITED"}if(this.getOption("packed")===!0)T.repeated_field_encoding="PACKED";else if(this.getOption("packed")===!1)T.repeated_field_encoding="EXPANDED";return T};S0.prototype._resolveFeatures=function(Y){return i6.prototype._resolveFeatures.call(this,this._edition||Y)};S0.d=function(Y,T,q,X){if(typeof T==="function")T=I0.decorateType(T).name;else if(T&&typeof T==="object")T=I0.decorateEnum(T).name;return function(Q,U){I0.decorateType(Q.constructor).add(new S0(U,Y,T,q,{default:X}))}};S0._configure=function(Y){n6=Y}});var o$=B((lg,uA)=>{uA.exports=q1;var Iq=L$();((q1.prototype=Object.create(Iq.prototype)).constructor=q1).className="OneOf";var fA=P$(),zq=w0();function q1($,Y,T,q){if(!Array.isArray(Y))T=Y,Y=void 0;if(Iq.call(this,$,T),!(Y===void 0||Array.isArray(Y)))throw TypeError("fieldNames must be an Array");this.oneof=Y||[],this.fieldsArray=[],this.comment=q}q1.fromJSON=function(Y,T){return new q1(Y,T.oneof,T.options,T.comment)};q1.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return zq.toObject(["options",this.options,"oneof",this.oneof,"comment",T?this.comment:void 0])};function bA($){if($.parent){for(var Y=0;Y<$.fieldsArray.length;++Y)if(!$.fieldsArray[Y].parent)$.parent.add($.fieldsArray[Y])}}q1.prototype.add=function(Y){if(!(Y instanceof fA))throw TypeError("field must be a Field");if(Y.parent&&Y.parent!==this.parent)Y.parent.remove(Y);return this.oneof.push(Y.name),this.fieldsArray.push(Y),Y.partOf=this,bA(this),this};q1.prototype.remove=function(Y){if(!(Y instanceof fA))throw TypeError("field must be a Field");var T=this.fieldsArray.indexOf(Y);if(T<0)throw Error(Y+" is not a member of "+this);if(this.fieldsArray.splice(T,1),T=this.oneof.indexOf(Y.name),T>-1)this.oneof.splice(T,1);return Y.partOf=null,this};q1.prototype.onAdd=function(Y){Iq.prototype.onAdd.call(this,Y);var T=this;for(var q=0;q<this.oneof.length;++q){var X=Y.get(this.oneof[q]);if(X&&!X.partOf)X.partOf=T,T.fieldsArray.push(X)}bA(this)};q1.prototype.onRemove=function(Y){for(var T=0,q;T<this.fieldsArray.length;++T)if((q=this.fieldsArray[T]).parent)q.parent.remove(q);Iq.prototype.onRemove.call(this,Y)};Object.defineProperty(q1.prototype,"isProto3Optional",{get:function(){if(this.fieldsArray==null||this.fieldsArray.length!==1)return!1;var $=this.fieldsArray[0];return $.options!=null&&$.options.proto3_optional===!0}});q1.d=function(){var Y=Array(arguments.length),T=0;while(T<arguments.length)Y[T]=arguments[T++];return function(X,J){zq.decorateType(X.constructor).add(new q1(J,Y)),Object.defineProperty(X,J,{get:zq.oneOfGetter(Y),set:zq.oneOfSetter(Y)})}}});var L$=B((ng,dA)=>{dA.exports=x0;x0.className="ReflectionObject";var D2=o$(),r6=w0(),Mq,F2={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},N2={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},H2={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function x0($,Y){if(!r6.isString($))throw TypeError("name must be a string");if(Y&&!r6.isObject(Y))throw TypeError("options must be an object");this.options=Y,this.parsedOptions=null,this.name=$,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(x0.prototype,{root:{get:function(){var $=this;while($.parent!==null)$=$.parent;return $}},fullName:{get:function(){var $=[this.name],Y=this.parent;while(Y)$.unshift(Y.name),Y=Y.parent;return $.join(".")}}});x0.prototype.toJSON=function(){throw Error()};x0.prototype.onAdd=function(Y){if(this.parent&&this.parent!==Y)this.parent.remove(this);this.parent=Y,this.resolved=!1;var T=Y.root;if(T instanceof Mq)T._handleAdd(this)};x0.prototype.onRemove=function(Y){var T=Y.root;if(T instanceof Mq)T._handleRemove(this);this.parent=null,this.resolved=!1};x0.prototype.resolve=function(){if(this.resolved)return this;if(this.root instanceof Mq)this.resolved=!0;return this};x0.prototype._resolveFeaturesRecursive=function(Y){return this._resolveFeatures(this._edition||Y)};x0.prototype._resolveFeatures=function(Y){if(this._featuresResolved)return;var T={};if(!Y)throw Error("Unknown edition for "+this.fullName);var q=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(Y));if(this._edition){if(Y==="proto2")T=Object.assign({},N2);else if(Y==="proto3")T=Object.assign({},H2);else if(Y==="2023")T=Object.assign({},F2);else throw Error("Unknown edition: "+Y);this._features=Object.assign(T,q||{}),this._featuresResolved=!0;return}if(this.partOf instanceof D2){var X=Object.assign({},this.partOf._features);this._features=Object.assign(X,q||{})}else if(this.declaringField);else if(this.parent){var J=Object.assign({},this.parent._features);this._features=Object.assign(J,q||{})}else throw Error("Unable to find a parent for "+this.fullName);if(this.extensionField)this.extensionField._features=this._features;this._featuresResolved=!0};x0.prototype._inferLegacyProtoFeatures=function(){return{}};x0.prototype.getOption=function(Y){if(this.options)return this.options[Y];return};x0.prototype.setOption=function(Y,T,q){if(!this.options)this.options={};if(/^features\./.test(Y))r6.setProperty(this.options,Y,T,q);else if(!q||this.options[Y]===void 0){if(this.getOption(Y)!==T)this.resolved=!1;this.options[Y]=T}return this};x0.prototype.setParsedOption=function(Y,T,q){if(!this.parsedOptions)this.parsedOptions=[];var X=this.parsedOptions;if(q){var J=X.find(function(Z){return Object.prototype.hasOwnProperty.call(Z,Y)});if(J){var Q=J[Y];r6.setProperty(Q,q,T)}else J={},J[Y]=r6.setProperty({},q,T),X.push(J)}else{var U={};U[Y]=T,X.push(U)}return this};x0.prototype.setOptions=function(Y,T){if(Y)for(var q=Object.keys(Y),X=0;X<q.length;++X)this.setOption(q[X],Y[q[X]],T);return this};x0.prototype.toString=function(){var Y=this.constructor.className,T=this.fullName;if(T.length)return Y+" "+T;return Y};x0.prototype._editionToJSON=function(){if(!this._edition||this._edition==="proto3")return;return this._edition};x0._configure=function($){Mq=$}});var w1=B((ig,pA)=>{pA.exports=S1;var J5=L$();((S1.prototype=Object.create(J5.prototype)).constructor=S1).className="Enum";var cA=kY(),Bq=w0();function S1($,Y,T,q,X,J){if(J5.call(this,$,T),Y&&typeof Y!=="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=q,this.comments=X||{},this.valuesOptions=J,this._valuesFeatures={},this.reserved=void 0,Y){for(var Q=Object.keys(Y),U=0;U<Q.length;++U)if(typeof Y[Q[U]]==="number")this.valuesById[this.values[Q[U]]=Y[Q[U]]]=Q[U]}}S1.prototype._resolveFeatures=function(Y){return Y=this._edition||Y,J5.prototype._resolveFeatures.call(this,Y),Object.keys(this.values).forEach((T)=>{var q=Object.assign({},this._features);this._valuesFeatures[T]=Object.assign(q,this.valuesOptions&&this.valuesOptions[T]&&this.valuesOptions[T].features)}),this};S1.fromJSON=function(Y,T){var q=new S1(Y,T.values,T.options,T.comment,T.comments);if(q.reserved=T.reserved,T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};S1.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return Bq.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",T?this.comment:void 0,"comments",T?this.comments:void 0])};S1.prototype.add=function(Y,T,q,X){if(!Bq.isString(Y))throw TypeError("name must be a string");if(!Bq.isInteger(T))throw TypeError("id must be an integer");if(this.values[Y]!==void 0)throw Error("duplicate name '"+Y+"' in "+this);if(this.isReservedId(T))throw Error("id "+T+" is reserved in "+this);if(this.isReservedName(Y))throw Error("name '"+Y+"' is reserved in "+this);if(this.valuesById[T]!==void 0){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+T+" in "+this);this.values[Y]=T}else this.valuesById[this.values[Y]=T]=Y;if(X){if(this.valuesOptions===void 0)this.valuesOptions={};this.valuesOptions[Y]=X||null}return this.comments[Y]=q||null,this};S1.prototype.remove=function(Y){if(!Bq.isString(Y))throw TypeError("name must be a string");var T=this.values[Y];if(T==null)throw Error("name '"+Y+"' does not exist in "+this);if(delete this.valuesById[T],delete this.values[Y],delete this.comments[Y],this.valuesOptions)delete this.valuesOptions[Y];return this};S1.prototype.isReservedId=function(Y){return cA.isReservedId(this.reserved,Y)};S1.prototype.isReservedName=function(Y){return cA.isReservedName(this.reserved,Y)}});var tX=B((rg,nA)=>{nA.exports=I2;var z2=w1(),Q5=s$(),U5=w0();function lA($,Y,T,q){return Y.delimited?$("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",T,q,(Y.id<<3|3)>>>0,(Y.id<<3|4)>>>0):$("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",T,q,(Y.id<<3|2)>>>0)}function I2($){var Y=U5.codegen(["m","w"],$.name+"$encode")("if(!w)")("w=Writer.create()"),T,q,X=$.fieldsArray.slice().sort(U5.compareFieldsById);for(var T=0;T<X.length;++T){var J=X[T].resolve(),Q=$._fieldsArray.indexOf(J),U=J.resolvedType instanceof z2?"int32":J.type,Z=Q5.basic[U];if(q="m"+U5.safeProp(J.name),J.map){if(Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",q,J.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",q)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(J.id<<3|2)>>>0,8|Q5.mapKey[J.keyType],J.keyType),Z===void 0)Y("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",Q,q);else Y(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|Z,U,q);Y("}")("}")}else if(J.repeated){if(Y("if(%s!=null&&%s.length){",q,q),J.packed&&Q5.packed[U]!==void 0)Y("w.uint32(%i).fork()",(J.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",q)("w.%s(%s[i])",U,q)("w.ldelim()");else if(Y("for(var i=0;i<%s.length;++i)",q),Z===void 0)lA(Y,J,Q,q+"[i]");else Y("w.uint32(%i).%s(%s[i])",(J.id<<3|Z)>>>0,U,q);Y("}")}else{if(J.optional)Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",q,J.name);if(Z===void 0)lA(Y,J,Q,q);else Y("w.uint32(%i).%s(%s)",(J.id<<3|Z)>>>0,U,q)}}return Y("return w")}});var rA=B((ag,iA)=>{var e=iA.exports=UA();e.build="light";function M2($,Y,T){if(typeof Y==="function")T=Y,Y=new e.Root;else if(!Y)Y=new e.Root;return Y.load($,T)}e.load=M2;function B2($,Y){if(!Y)Y=new e.Root;return Y.loadSync($)}e.loadSync=B2;e.encoder=tX();e.decoder=uX();e.verifier=pX();e.converter=iX();e.ReflectionObject=L$();e.Namespace=kY();e.Root=Hq();e.Enum=w1();e.Type=Vq();e.Field=P$();e.OneOf=o$();e.MapField=Zq();e.Service=Aq();e.Method=Kq();e.Message=Wq();e.wrappers=rX();e.types=s$();e.util=w0();e.ReflectionObject._configure(e.Root);e.Namespace._configure(e.Type,e.Service,e.Enum);e.Root._configure(e.Type);e.Field._configure(e.Type)});var K5=B((og,sA)=>{sA.exports=oA;var Z5=/[\s{}=;:[\],'"()<>]/g,R2=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,O2=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,P2=/^ *[*/]+ */,L2=/^\s*\*?\/*/,w2=/\n/g,S2=/\s/,C2=/\\(.?)/g,y2={"0":"\x00",r:"\r",n:`
|
|
9
|
+
`,t:"\t"};function aA($){return $.replace(C2,function(Y,T){switch(T){case"\\":case"":return T;default:return y2[T]||""}})}oA.unescape=aA;function oA($,Y){$=$.toString();var T=0,q=$.length,X=1,J=0,Q={},U=[],Z=null;function K(z){return Error("illegal "+z+" (line "+X+")")}function A(){var z=Z==="'"?O2:R2;z.lastIndex=T-1;var _=z.exec($);if(!_)throw K("string");return T=z.lastIndex,D(Z),Z=null,aA(_[1])}function W(z){return $.charAt(z)}function E(z,_,y){var k={type:$.charAt(z++),lineEmpty:!1,leading:y},m;if(Y)m=2;else m=3;var C=z-m,j;do if(--C<0||(j=$.charAt(C))===`
|
|
10
|
+
`){k.lineEmpty=!0;break}while(j===" "||j==="\t");var M=$.substring(z,_).split(w2);for(var h0=0;h0<M.length;++h0)M[h0]=M[h0].replace(Y?L2:P2,"").trim();k.text=M.join(`
|
|
11
|
+
`).trim(),Q[X]=k,J=X}function V(z){var _=F(z),y=$.substring(z,_),k=/^\s*\/\//.test(y);return k}function F(z){var _=z;while(_<q&&W(_)!==`
|
|
12
|
+
`)_++;return _}function H(){if(U.length>0)return U.shift();if(Z)return A();var z,_,y,k,m,C=T===0;do{if(T===q)return null;z=!1;while(S2.test(y=W(T))){if(y===`
|
|
13
13
|
`)C=!0,++X;if(++T===q)return null}if(W(T)==="/"){if(++T===q)throw K("comment");if(W(T)==="/")if(!Y){m=W(k=T+1)==="/";while(W(++T)!==`
|
|
14
|
-
`)if(T===q)return null;if(++T,m)E(k,T-1,C),C=!0;++X,z=!0}else{if(k=T,m=!1,
|
|
15
|
-
`)++X;if(++T===q)throw K("comment");_=y,y=W(T)}while(_!=="*"||y!=="/");if(++T,m)E(k,T-2,C),C=!0;z=!0}else return"/"}}while(z);var j=T;U5.lastIndex=0;var I=U5.test(W(j++));if(!I)while(j<q&&!U5.test(W(j)))++j;var h0=$.substring(T,T=j);if(h0==='"'||h0==="'")Z=h0;return h0}function V(z){U.push(z)}function B(){if(!U.length){var z=H();if(z===null)return null;V(z)}return U[0]}function S(z,_){var y=B(),k=y===z;if(k)return H(),!0;if(!_)throw K("token '"+y+"', '"+z+"' expected");return!1}function v(z){var _=null,y;if(z===void 0){if(y=Q[X-1],delete Q[X-1],y&&(Y||y.type==="*"||y.lineEmpty))_=y.leading?y.text:null}else{if(J<z)B();if(y=Q[z],delete Q[z],y&&!y.lineEmpty&&(Y||y.type==="/"))_=y.leading?null:y.text}return _}return Object.defineProperty({next:H,peek:B,push:V,skip:S,cmnt:v},"line",{get:function(){return X}})}});var eA=M((lg,tA)=>{tA.exports=Q$;Q$.filename=null;Q$.defaults={keepCase:!1};var S2=Z5(),rA=Nq(),aA=Eq(),oA=P$(),C2=Uq(),sA=o$(),y2=w1(),j2=Kq(),v2=Zq(),x2=L$(),k2=s$(),K5=w0(),h2=/^[1-9][0-9]*$/,_2=/^-?[1-9][0-9]*$/,g2=/^0[x][0-9a-fA-F]+$/,m2=/^-?0[x][0-9a-fA-F]+$/,f2=/^0[0-7]+$/,b2=/^-?0[0-7]+$/,u2=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,b1=/^[a-zA-Z_][a-zA-Z_0-9]*$/,u1=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function Q$($,Y,T){if(!(Y instanceof rA))T=Y,Y=new rA;if(!T)T=Q$.defaults;var q=T.preferTrailingComment||!1,X=S2($,T.alternateCommentMode||!1),J=X.next,Q=X.push,U=X.peek,Z=X.skip,K=X.cmnt,A=!0,W,E,D,F="proto2",H=Y,V=[],B={},S=T.keepCase?function(O){return O}:K5.camelCase;function v(){V.forEach((O)=>{O._edition=F,Object.keys(B).forEach((R)=>{if(O.getOption(R)!==void 0)return;O.setOption(R,B[R],!0)})})}function z(O,R,w){var h=Q$.filename;if(!w)Q$.filename=null;return Error("illegal "+(R||"token")+" '"+O+"' ("+(h?h+", ":"")+"line "+X.line+")")}function _(){var O=[],R;do{if((R=J())!=='"'&&R!=="'")throw z(R);O.push(J()),Z(R),R=U()}while(R==='"'||R==="'");return O.join("")}function y(O){var R=J();switch(R){case"'":case'"':return Q(R),_();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return m(R,!0)}catch(w){if(O&&u1.test(R))return R;throw z(R,"value")}}function k(O,R){var w,h;do if(R&&((w=U())==='"'||w==="'")){var x=_();if(O.push(x),F>=2023)throw z(x,"id")}else try{O.push([h=C(J()),Z("to",!0)?C(J()):h])}catch(A0){if(R&&u1.test(w)&&F>=2023)O.push(w);else throw A0}while(Z(",",!0));var f={options:void 0};f.setOption=function(A0,g0){if(this.options===void 0)this.options={};this.options[A0]=g0},L(f,function(g0){if(g0==="option")Y0(f,g0),Z(";");else throw z(g0)},function(){o1(f)})}function m(O,R){var w=1;if(O.charAt(0)==="-")w=-1,O=O.substring(1);switch(O){case"inf":case"INF":case"Inf":return w*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(h2.test(O))return w*parseInt(O,10);if(g2.test(O))return w*parseInt(O,16);if(f2.test(O))return w*parseInt(O,8);if(u2.test(O))return w*parseFloat(O);throw z(O,"number",R)}function C(O,R){switch(O){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!R&&O.charAt(0)==="-")throw z(O,"id");if(_2.test(O))return parseInt(O,10);if(m2.test(O))return parseInt(O,16);if(b2.test(O))return parseInt(O,8);throw z(O,"id")}function j(){if(W!==void 0)throw z("package");if(W=J(),!u1.test(W))throw z(W,"name");H=H.define(W),Z(";")}function I(){var O=U(),R;switch(O){case"weak":R=D||(D=[]),J();break;case"public":J();default:R=E||(E=[]);break}O=_(),Z(";"),R.push(O)}function h0(){if(Z("="),F=_(),F<2023)throw z(F,"syntax");Z(";")}function P(){if(Z("="),F=_(),!["2023"].includes(F))throw z(F,"edition");Z(";")}function G(O,R){switch(R){case"option":return Y0(O,R),Z(";"),!0;case"message":return l(O,R),!0;case"enum":return b0(O,R),!0;case"service":return $D(O,R),!0;case"extend":return TD(O,R),!0}return!1}function L(O,R,w){var h=X.line;if(O){if(typeof O.comment!=="string")O.comment=K();O.filename=Q$.filename}if(Z("{",!0)){var x;while((x=J())!=="}")R(x);Z(";",!0)}else{if(w)w();if(Z(";"),O&&(typeof O.comment!=="string"||q))O.comment=K(h)||O.comment}}function l(O,R){if(!b1.test(R=J()))throw z(R,"type name");var w=new aA(R);if(L(w,function(x){if(G(w,x))return;switch(x){case"map":V0(w,x);break;case"required":if(F!=="proto2")throw z(x);case"repeated":u(w,x);break;case"optional":if(F==="proto3")u(w,"proto3_optional");else if(F!=="proto2")throw z(x);else u(w,"optional");break;case"oneof":_0(w,x);break;case"extensions":k(w.extensions||(w.extensions=[]));break;case"reserved":k(w.reserved||(w.reserved=[]),!0);break;default:if(F==="proto2"||!u1.test(x))throw z(x);Q(x),u(w,"optional");break}}),O.add(w),O===H)V.push(w)}function u(O,R,w){var h=J();if(h==="group"){d(O,R);return}while(h.endsWith(".")||U().startsWith("."))h+=J();if(!u1.test(h))throw z(h,"type");var x=J();if(!b1.test(x))throw z(x,"name");x=S(x),Z("=");var f=new oA(x,C(J()),h,R,w);if(L(f,function(c0){if(c0==="option")Y0(f,c0),Z(";");else throw z(c0)},function(){o1(f)}),R==="proto3_optional"){var A0=new sA("_"+x);f.setOption("proto3_optional",!0),A0.add(f),O.add(A0)}else O.add(f);if(O===H)V.push(f)}function d(O,R){if(F>=2023)throw z("group");var w=J();if(!b1.test(w))throw z(w,"name");var h=K5.lcFirst(w);if(w===h)w=K5.ucFirst(w);Z("=");var x=C(J()),f=new aA(w);f.group=!0;var A0=new oA(h,x,w,R);A0.filename=Q$.filename,L(f,function(c0){switch(c0){case"option":Y0(f,c0),Z(";");break;case"required":case"repeated":u(f,c0);break;case"optional":if(F==="proto3")u(f,"proto3_optional");else u(f,"optional");break;case"message":l(f,c0);break;case"enum":b0(f,c0);break;case"reserved":k(f.reserved||(f.reserved=[]),!0);break;default:throw z(c0)}}),O.add(f).add(A0)}function V0(O){Z("<");var R=J();if(k2.mapKey[R]===void 0)throw z(R,"type");Z(",");var w=J();if(!u1.test(w))throw z(w,"type");Z(">");var h=J();if(!b1.test(h))throw z(h,"name");Z("=");var x=new C2(S(h),C(J()),R,w);L(x,function(A0){if(A0==="option")Y0(x,A0),Z(";");else throw z(A0)},function(){o1(x)}),O.add(x)}function _0(O,R){if(!b1.test(R=J()))throw z(R,"name");var w=new sA(S(R));L(w,function(x){if(x==="option")Y0(w,x),Z(";");else Q(x),u(w,"optional")}),O.add(w)}function b0(O,R){if(!b1.test(R=J()))throw z(R,"name");var w=new y2(R);if(L(w,function(x){switch(x){case"option":Y0(w,x),Z(";");break;case"reserved":if(k(w.reserved||(w.reserved=[]),!0),w.reserved===void 0)w.reserved=[];break;default:B0(w,x)}}),O.add(w),O===H)V.push(w)}function B0(O,R){if(!b1.test(R))throw z(R,"name");Z("=");var w=C(J(),!0),h={options:void 0};h.getOption=function(x){return this.options[x]},h.setOption=function(x,f){x2.prototype.setOption.call(h,x,f)},h.setParsedOption=function(){return},L(h,function(f){if(f==="option")Y0(h,f),Z(";");else throw z(f)},function(){o1(h)}),O.add(R,w,h.comment,h.parsedOptions||h.options)}function Y0(O,R){var w,h,x=!0;if(R==="option")R=J();while(R!=="="){if(R==="("){var f=J();Z(")"),R="("+f+")"}if(x){if(x=!1,R.includes(".")&&!R.includes("(")){var A0=R.split(".");w=A0[0]+".",R=A0[1];continue}w=R}else h=h?h+=R:R;R=J()}var g0=h?w.concat(h):w,c0=u0(O,g0);h=h&&h[0]==="."?h.slice(1):h,w=w&&w[w.length-1]==="."?w.slice(0,-1):w,d0(O,w,c0,h)}function u0(O,R){if(Z("{",!0)){var w={};while(!Z("}",!0)){if(!b1.test(j0=J()))throw z(j0,"name");if(j0===null)throw z(j0,"end of input");var h,x=j0;if(Z(":",!0),U()==="{")h=u0(O,R+"."+j0);else if(U()==="["){h=[];var f;if(Z("[",!0)){do f=y(!0),h.push(f);while(Z(",",!0));if(Z("]"),typeof f<"u")E0(O,R+"."+j0,f)}}else h=y(!0),E0(O,R+"."+j0,h);var A0=w[x];if(A0)h=[].concat(A0).concat(h);w[x]=h,Z(",",!0),Z(";",!0)}return w}var g0=y(!0);return E0(O,R,g0),g0}function E0(O,R,w){if(H===O&&/^features\./.test(R)){B[R]=w;return}if(O.setOption)O.setOption(R,w)}function d0(O,R,w,h){if(O.setParsedOption)O.setParsedOption(R,w,h)}function o1(O){if(Z("[",!0)){do Y0(O,"option");while(Z(",",!0));Z("]")}return O}function $D(O,R){if(!b1.test(R=J()))throw z(R,"service name");var w=new j2(R);if(L(w,function(x){if(G(w,x))return;if(x==="rpc")YD(w,x);else throw z(x)}),O.add(w),O===H)V.push(w)}function YD(O,R){var w=K(),h=R;if(!b1.test(R=J()))throw z(R,"name");var x=R,f,A0,g0,c0;if(Z("("),Z("stream",!0))A0=!0;if(!u1.test(R=J()))throw z(R);if(f=R,Z(")"),Z("returns"),Z("("),Z("stream",!0))c0=!0;if(!u1.test(R=J()))throw z(R);g0=R,Z(")");var L6=new v2(x,h,f,g0,A0,c0);L6.comment=w,L(L6,function(F9){if(F9==="option")Y0(L6,F9),Z(";");else throw z(F9)}),O.add(L6)}function TD(O,R){if(!u1.test(R=J()))throw z(R,"reference");var w=R;L(null,function(x){switch(x){case"required":case"repeated":u(O,x,w);break;case"optional":if(F==="proto3")u(O,"proto3_optional",w);else u(O,"optional",w);break;default:if(F==="proto2"||!u1.test(x))throw z(x);Q(x),u(O,"optional",w);break}})}var j0;while((j0=J())!==null)switch(j0){case"package":if(!A)throw z(j0);j();break;case"import":if(!A)throw z(j0);I();break;case"syntax":if(!A)throw z(j0);h0();break;case"edition":if(!A)throw z(j0);P();break;case"option":Y0(H,j0),Z(";",!0);break;default:if(G(H,j0)){A=!1;continue}throw z(j0)}return v(),Q$.filename=null,{package:W,imports:E,weakImports:D,root:Y}}});var TW=M((ng,YW)=>{YW.exports=C1;var d2=/\/|\./;function C1($,Y){if(!d2.test($))$="google/protobuf/"+$+".proto",Y={nested:{google:{nested:{protobuf:{nested:Y}}}}};C1[$]=Y}C1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var $W;C1("duration",{Duration:$W={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});C1("timestamp",{Timestamp:$W});C1("empty",{Empty:{fields:{}}});C1("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});C1("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});C1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});C1.get=function(Y){return C1[Y]||null}});var Bq=M((ig,qW)=>{var S$=qW.exports=pA();S$.build="full";S$.tokenize=Z5();S$.parse=eA();S$.common=TW();S$.Root._configure(S$.Type,S$.parse,S$.common)});var A5=M((rg,c2)=>{c2.exports={nested:{google:{nested:{protobuf:{options:{go_package:"google.golang.org/protobuf/types/descriptorpb",java_package:"com.google.protobuf",java_outer_classname:"DescriptorProtos",csharp_namespace:"Google.Protobuf.Reflection",objc_class_prefix:"GPB",cc_enable_arenas:!0,optimize_for:"SPEED"},nested:{FileDescriptorSet:{edition:"proto2",fields:{file:{rule:"repeated",type:"FileDescriptorProto",id:1}},extensions:[[536000000,536000000]]},Edition:{edition:"proto2",values:{EDITION_UNKNOWN:0,EDITION_LEGACY:900,EDITION_PROTO2:998,EDITION_PROTO3:999,EDITION_2023:1000,EDITION_2024:1001,EDITION_1_TEST_ONLY:1,EDITION_2_TEST_ONLY:2,EDITION_99997_TEST_ONLY:99997,EDITION_99998_TEST_ONLY:99998,EDITION_99999_TEST_ONLY:99999,EDITION_MAX:2147483647}},FileDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},package:{type:"string",id:2},dependency:{rule:"repeated",type:"string",id:3},publicDependency:{rule:"repeated",type:"int32",id:10},weakDependency:{rule:"repeated",type:"int32",id:11},optionDependency:{rule:"repeated",type:"string",id:15},messageType:{rule:"repeated",type:"DescriptorProto",id:4},enumType:{rule:"repeated",type:"EnumDescriptorProto",id:5},service:{rule:"repeated",type:"ServiceDescriptorProto",id:6},extension:{rule:"repeated",type:"FieldDescriptorProto",id:7},options:{type:"FileOptions",id:8},sourceCodeInfo:{type:"SourceCodeInfo",id:9},syntax:{type:"string",id:12},edition:{type:"Edition",id:14}}},DescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},field:{rule:"repeated",type:"FieldDescriptorProto",id:2},extension:{rule:"repeated",type:"FieldDescriptorProto",id:6},nestedType:{rule:"repeated",type:"DescriptorProto",id:3},enumType:{rule:"repeated",type:"EnumDescriptorProto",id:4},extensionRange:{rule:"repeated",type:"ExtensionRange",id:5},oneofDecl:{rule:"repeated",type:"OneofDescriptorProto",id:8},options:{type:"MessageOptions",id:7},reservedRange:{rule:"repeated",type:"ReservedRange",id:9},reservedName:{rule:"repeated",type:"string",id:10},visibility:{type:"SymbolVisibility",id:11}},nested:{ExtensionRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2},options:{type:"ExtensionRangeOptions",id:3}}},ReservedRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2}}}}},ExtensionRangeOptions:{edition:"proto2",fields:{uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999},declaration:{rule:"repeated",type:"Declaration",id:2,options:{retention:"RETENTION_SOURCE"}},features:{type:"FeatureSet",id:50},verification:{type:"VerificationState",id:3,options:{default:"UNVERIFIED",retention:"RETENTION_SOURCE"}}},extensions:[[1000,536870911]],nested:{Declaration:{fields:{number:{type:"int32",id:1},fullName:{type:"string",id:2},type:{type:"string",id:3},reserved:{type:"bool",id:5},repeated:{type:"bool",id:6}},reserved:[[4,4]]},VerificationState:{values:{DECLARATION:0,UNVERIFIED:1}}}},FieldDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},number:{type:"int32",id:3},label:{type:"Label",id:4},type:{type:"Type",id:5},typeName:{type:"string",id:6},extendee:{type:"string",id:2},defaultValue:{type:"string",id:7},oneofIndex:{type:"int32",id:9},jsonName:{type:"string",id:10},options:{type:"FieldOptions",id:8},proto3Optional:{type:"bool",id:17}},nested:{Type:{values:{TYPE_DOUBLE:1,TYPE_FLOAT:2,TYPE_INT64:3,TYPE_UINT64:4,TYPE_INT32:5,TYPE_FIXED64:6,TYPE_FIXED32:7,TYPE_BOOL:8,TYPE_STRING:9,TYPE_GROUP:10,TYPE_MESSAGE:11,TYPE_BYTES:12,TYPE_UINT32:13,TYPE_ENUM:14,TYPE_SFIXED32:15,TYPE_SFIXED64:16,TYPE_SINT32:17,TYPE_SINT64:18}},Label:{values:{LABEL_OPTIONAL:1,LABEL_REPEATED:3,LABEL_REQUIRED:2}}}},OneofDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},options:{type:"OneofOptions",id:2}}},EnumDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},value:{rule:"repeated",type:"EnumValueDescriptorProto",id:2},options:{type:"EnumOptions",id:3},reservedRange:{rule:"repeated",type:"EnumReservedRange",id:4},reservedName:{rule:"repeated",type:"string",id:5},visibility:{type:"SymbolVisibility",id:6}},nested:{EnumReservedRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2}}}}},EnumValueDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},number:{type:"int32",id:2},options:{type:"EnumValueOptions",id:3}}},ServiceDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},method:{rule:"repeated",type:"MethodDescriptorProto",id:2},options:{type:"ServiceOptions",id:3}}},MethodDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},inputType:{type:"string",id:2},outputType:{type:"string",id:3},options:{type:"MethodOptions",id:4},clientStreaming:{type:"bool",id:5},serverStreaming:{type:"bool",id:6}}},FileOptions:{edition:"proto2",fields:{javaPackage:{type:"string",id:1},javaOuterClassname:{type:"string",id:8},javaMultipleFiles:{type:"bool",id:10},javaGenerateEqualsAndHash:{type:"bool",id:20,options:{deprecated:!0}},javaStringCheckUtf8:{type:"bool",id:27},optimizeFor:{type:"OptimizeMode",id:9,options:{default:"SPEED"}},goPackage:{type:"string",id:11},ccGenericServices:{type:"bool",id:16},javaGenericServices:{type:"bool",id:17},pyGenericServices:{type:"bool",id:18},deprecated:{type:"bool",id:23},ccEnableArenas:{type:"bool",id:31,options:{default:!0}},objcClassPrefix:{type:"string",id:36},csharpNamespace:{type:"string",id:37},swiftPrefix:{type:"string",id:39},phpClassPrefix:{type:"string",id:40},phpNamespace:{type:"string",id:41},phpMetadataNamespace:{type:"string",id:44},rubyPackage:{type:"string",id:45},features:{type:"FeatureSet",id:50},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[42,42],[38,38],"php_generic_services"],nested:{OptimizeMode:{values:{SPEED:1,CODE_SIZE:2,LITE_RUNTIME:3}}}},MessageOptions:{edition:"proto2",fields:{messageSetWireFormat:{type:"bool",id:1},noStandardDescriptorAccessor:{type:"bool",id:2},deprecated:{type:"bool",id:3},mapEntry:{type:"bool",id:7},deprecatedLegacyJsonFieldConflicts:{type:"bool",id:11,options:{deprecated:!0}},features:{type:"FeatureSet",id:12},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[4,4],[5,5],[6,6],[8,8],[9,9]]},FieldOptions:{edition:"proto2",fields:{ctype:{type:"CType",id:1,options:{default:"STRING"}},packed:{type:"bool",id:2},jstype:{type:"JSType",id:6,options:{default:"JS_NORMAL"}},lazy:{type:"bool",id:5},unverifiedLazy:{type:"bool",id:15},deprecated:{type:"bool",id:3},weak:{type:"bool",id:10,options:{deprecated:!0}},debugRedact:{type:"bool",id:16},retention:{type:"OptionRetention",id:17},targets:{rule:"repeated",type:"OptionTargetType",id:19},editionDefaults:{rule:"repeated",type:"EditionDefault",id:20},features:{type:"FeatureSet",id:21},featureSupport:{type:"FeatureSupport",id:22},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[4,4],[18,18]],nested:{CType:{values:{STRING:0,CORD:1,STRING_PIECE:2}},JSType:{values:{JS_NORMAL:0,JS_STRING:1,JS_NUMBER:2}},OptionRetention:{values:{RETENTION_UNKNOWN:0,RETENTION_RUNTIME:1,RETENTION_SOURCE:2}},OptionTargetType:{values:{TARGET_TYPE_UNKNOWN:0,TARGET_TYPE_FILE:1,TARGET_TYPE_EXTENSION_RANGE:2,TARGET_TYPE_MESSAGE:3,TARGET_TYPE_FIELD:4,TARGET_TYPE_ONEOF:5,TARGET_TYPE_ENUM:6,TARGET_TYPE_ENUM_ENTRY:7,TARGET_TYPE_SERVICE:8,TARGET_TYPE_METHOD:9}},EditionDefault:{fields:{edition:{type:"Edition",id:3},value:{type:"string",id:2}}},FeatureSupport:{fields:{editionIntroduced:{type:"Edition",id:1},editionDeprecated:{type:"Edition",id:2},deprecationWarning:{type:"string",id:3},editionRemoved:{type:"Edition",id:4}}}}},OneofOptions:{edition:"proto2",fields:{features:{type:"FeatureSet",id:1},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},EnumOptions:{edition:"proto2",fields:{allowAlias:{type:"bool",id:2},deprecated:{type:"bool",id:3},deprecatedLegacyJsonFieldConflicts:{type:"bool",id:6,options:{deprecated:!0}},features:{type:"FeatureSet",id:7},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[5,5]]},EnumValueOptions:{edition:"proto2",fields:{deprecated:{type:"bool",id:1},features:{type:"FeatureSet",id:2},debugRedact:{type:"bool",id:3},featureSupport:{type:"FieldOptions.FeatureSupport",id:4},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},ServiceOptions:{edition:"proto2",fields:{features:{type:"FeatureSet",id:34},deprecated:{type:"bool",id:33},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},MethodOptions:{edition:"proto2",fields:{deprecated:{type:"bool",id:33},idempotencyLevel:{type:"IdempotencyLevel",id:34,options:{default:"IDEMPOTENCY_UNKNOWN"}},features:{type:"FeatureSet",id:35},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],nested:{IdempotencyLevel:{values:{IDEMPOTENCY_UNKNOWN:0,NO_SIDE_EFFECTS:1,IDEMPOTENT:2}}}},UninterpretedOption:{edition:"proto2",fields:{name:{rule:"repeated",type:"NamePart",id:2},identifierValue:{type:"string",id:3},positiveIntValue:{type:"uint64",id:4},negativeIntValue:{type:"int64",id:5},doubleValue:{type:"double",id:6},stringValue:{type:"bytes",id:7},aggregateValue:{type:"string",id:8}},nested:{NamePart:{fields:{namePart:{rule:"required",type:"string",id:1},isExtension:{rule:"required",type:"bool",id:2}}}}},FeatureSet:{edition:"proto2",fields:{fieldPresence:{type:"FieldPresence",id:1,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},enumType:{type:"EnumType",id:2,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},repeatedFieldEncoding:{type:"RepeatedFieldEncoding",id:3,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},utf8Validation:{type:"Utf8Validation",id:4,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},messageEncoding:{type:"MessageEncoding",id:5,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_LEGACY","edition_defaults.value":"LENGTH_PREFIXED"}},jsonFormat:{type:"JsonFormat",id:6,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}},enforceNamingStyle:{type:"EnforceNamingStyle",id:7,options:{retention:"RETENTION_SOURCE",targets:"TARGET_TYPE_METHOD","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"STYLE2024"}},defaultSymbolVisibility:{type:"VisibilityFeature.DefaultSymbolVisibility",id:8,options:{retention:"RETENTION_SOURCE",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"EXPORT_TOP_LEVEL"}}},extensions:[[1000,9994],[9995,9999],[1e4,1e4]],reserved:[[999,999]],nested:{FieldPresence:{values:{FIELD_PRESENCE_UNKNOWN:0,EXPLICIT:1,IMPLICIT:2,LEGACY_REQUIRED:3}},EnumType:{values:{ENUM_TYPE_UNKNOWN:0,OPEN:1,CLOSED:2}},RepeatedFieldEncoding:{values:{REPEATED_FIELD_ENCODING_UNKNOWN:0,PACKED:1,EXPANDED:2}},Utf8Validation:{values:{UTF8_VALIDATION_UNKNOWN:0,VERIFY:2,NONE:3}},MessageEncoding:{values:{MESSAGE_ENCODING_UNKNOWN:0,LENGTH_PREFIXED:1,DELIMITED:2}},JsonFormat:{values:{JSON_FORMAT_UNKNOWN:0,ALLOW:1,LEGACY_BEST_EFFORT:2}},EnforceNamingStyle:{values:{ENFORCE_NAMING_STYLE_UNKNOWN:0,STYLE2024:1,STYLE_LEGACY:2}},VisibilityFeature:{fields:{},reserved:[[1,536870911]],nested:{DefaultSymbolVisibility:{values:{DEFAULT_SYMBOL_VISIBILITY_UNKNOWN:0,EXPORT_ALL:1,EXPORT_TOP_LEVEL:2,LOCAL_ALL:3,STRICT:4}}}}}},FeatureSetDefaults:{edition:"proto2",fields:{defaults:{rule:"repeated",type:"FeatureSetEditionDefault",id:1},minimumEdition:{type:"Edition",id:4},maximumEdition:{type:"Edition",id:5}},nested:{FeatureSetEditionDefault:{fields:{edition:{type:"Edition",id:3},overridableFeatures:{type:"FeatureSet",id:4},fixedFeatures:{type:"FeatureSet",id:5}},reserved:[[1,1],[2,2],"features"]}}},SourceCodeInfo:{edition:"proto2",fields:{location:{rule:"repeated",type:"Location",id:1}},extensions:[[536000000,536000000]],nested:{Location:{fields:{path:{rule:"repeated",type:"int32",id:1,options:{packed:!0}},span:{rule:"repeated",type:"int32",id:2,options:{packed:!0}},leadingComments:{type:"string",id:3},trailingComments:{type:"string",id:4},leadingDetachedComments:{rule:"repeated",type:"string",id:6}}}}},GeneratedCodeInfo:{edition:"proto2",fields:{annotation:{rule:"repeated",type:"Annotation",id:1}},nested:{Annotation:{fields:{path:{rule:"repeated",type:"int32",id:1,options:{packed:!0}},sourceFile:{type:"string",id:2},begin:{type:"int32",id:3},end:{type:"int32",id:4},semantic:{type:"Semantic",id:5}},nested:{Semantic:{values:{NONE:0,SET:1,ALIAS:2}}}}}},SymbolVisibility:{edition:"proto2",values:{VISIBILITY_UNSET:0,VISIBILITY_LOCAL:1,VISIBILITY_EXPORT:2}}}}}}}}});var AW=M((p,KW)=>{var X1=Bq();KW.exports=p=X1.descriptor=X1.Root.fromJSON(A5()).lookup(".google.protobuf");var{Namespace:XW,Root:aT,Enum:U$,Type:d1,Field:C$,MapField:p2,OneOf:Rq,Service:oT,Method:Oq}=X1;aT.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.FileDescriptorSet.decode(Y);var T=new aT;if(Y.file){var q,X;for(var J=0,Q;J<Y.file.length;++J){if(X=T,(q=Y.file[J]).package&&q.package.length)X=T.define(q.package);var U=$O(q);if(q.name&&q.name.length)T.files.push(X.filename=q.name);if(q.messageType)for(Q=0;Q<q.messageType.length;++Q)X.add(d1.fromDescriptor(q.messageType[Q],U));if(q.enumType)for(Q=0;Q<q.enumType.length;++Q)X.add(U$.fromDescriptor(q.enumType[Q],U));if(q.extension)for(Q=0;Q<q.extension.length;++Q)X.add(C$.fromDescriptor(q.extension[Q],U));if(q.service)for(Q=0;Q<q.service.length;++Q)X.add(oT.fromDescriptor(q.service[Q],U));var Z=_Y(q.options,p.FileOptions);if(Z){var K=Object.keys(Z);for(Q=0;Q<K.length;++Q)X.setOption(K[Q],Z[K[Q]])}}}return T.resolveAll()};aT.prototype.toDescriptor=function(Y){var T=p.FileDescriptorSet.create();return JW(this,T.file,Y),T};function JW($,Y,T){var q=p.FileDescriptorProto.create({name:$.filename||($.fullName.substring(1).replace(/\./g,"_")||"root")+".proto"});if(YO(T,q),!($ instanceof aT))q.package=$.fullName.substring(1);for(var X=0,J;X<$.nestedArray.length;++X)if((J=$._nestedArray[X])instanceof d1)q.messageType.push(J.toDescriptor(T));else if(J instanceof U$)q.enumType.push(J.toDescriptor());else if(J instanceof C$)q.extension.push(J.toDescriptor(T));else if(J instanceof oT)q.service.push(J.toDescriptor());else if(J instanceof XW)JW(J,Y,T);if(q.options=gY($.options,p.FileOptions),q.messageType.length+q.enumType.length+q.extension.length+q.service.length)Y.push(q)}var l2=0;d1.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);var X=new d1(Y.name.length?Y.name:"Type"+l2++,_Y(Y.options,p.MessageOptions)),J;if(!q)X._edition=T;if(Y.oneofDecl)for(J=0;J<Y.oneofDecl.length;++J)X.add(Rq.fromDescriptor(Y.oneofDecl[J]));if(Y.field)for(J=0;J<Y.field.length;++J){var Q=C$.fromDescriptor(Y.field[J],T,!0);if(X.add(Q),Y.field[J].hasOwnProperty("oneofIndex"))X.oneofsArray[Y.field[J].oneofIndex].add(Q)}if(Y.extension)for(J=0;J<Y.extension.length;++J)X.add(C$.fromDescriptor(Y.extension[J],T,!0));if(Y.nestedType){for(J=0;J<Y.nestedType.length;++J)if(X.add(d1.fromDescriptor(Y.nestedType[J],T,!0)),Y.nestedType[J].options&&Y.nestedType[J].options.mapEntry)X.setOption("map_entry",!0)}if(Y.enumType)for(J=0;J<Y.enumType.length;++J)X.add(U$.fromDescriptor(Y.enumType[J],T,!0));if(Y.extensionRange&&Y.extensionRange.length){X.extensions=[];for(J=0;J<Y.extensionRange.length;++J)X.extensions.push([Y.extensionRange[J].start,Y.extensionRange[J].end])}if(Y.reservedRange&&Y.reservedRange.length||Y.reservedName&&Y.reservedName.length){if(X.reserved=[],Y.reservedRange)for(J=0;J<Y.reservedRange.length;++J)X.reserved.push([Y.reservedRange[J].start,Y.reservedRange[J].end]);if(Y.reservedName)for(J=0;J<Y.reservedName.length;++J)X.reserved.push(Y.reservedName[J])}return X};d1.prototype.toDescriptor=function(Y){var T=p.DescriptorProto.create({name:this.name}),q;for(q=0;q<this.fieldsArray.length;++q){var X;if(T.field.push(X=this._fieldsArray[q].toDescriptor(Y)),this._fieldsArray[q]instanceof p2){var J=W5(this._fieldsArray[q].keyType,this._fieldsArray[q].resolvedKeyType,!1),Q=W5(this._fieldsArray[q].type,this._fieldsArray[q].resolvedType,!1),U=Q===11||Q===14?this._fieldsArray[q].resolvedType&&ZW(this.parent,this._fieldsArray[q].resolvedType)||this._fieldsArray[q].type:void 0;T.nestedType.push(p.DescriptorProto.create({name:X.typeName,field:[p.FieldDescriptorProto.create({name:"key",number:1,label:1,type:J}),p.FieldDescriptorProto.create({name:"value",number:2,label:1,type:Q,typeName:U})],options:p.MessageOptions.create({mapEntry:!0})}))}}for(q=0;q<this.oneofsArray.length;++q)T.oneofDecl.push(this._oneofsArray[q].toDescriptor());for(q=0;q<this.nestedArray.length;++q)if(this._nestedArray[q]instanceof C$)T.field.push(this._nestedArray[q].toDescriptor(Y));else if(this._nestedArray[q]instanceof d1)T.nestedType.push(this._nestedArray[q].toDescriptor(Y));else if(this._nestedArray[q]instanceof U$)T.enumType.push(this._nestedArray[q].toDescriptor());if(this.extensions)for(q=0;q<this.extensions.length;++q)T.extensionRange.push(p.DescriptorProto.ExtensionRange.create({start:this.extensions[q][0],end:this.extensions[q][1]}));if(this.reserved)for(q=0;q<this.reserved.length;++q)if(typeof this.reserved[q]==="string")T.reservedName.push(this.reserved[q]);else T.reservedRange.push(p.DescriptorProto.ReservedRange.create({start:this.reserved[q][0],end:this.reserved[q][1]}));return T.options=gY(this.options,p.MessageOptions),T};var n2=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;C$.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);if(typeof Y.number!=="number")throw Error("missing field id");var X;if(Y.typeName&&Y.typeName.length)X=Y.typeName;else X=s2(Y.type);var J;switch(Y.label){case 1:J=void 0;break;case 2:J="required";break;case 3:J="repeated";break;default:throw Error("illegal label: "+Y.label)}var Q=Y.extendee;if(Y.extendee!==void 0)Q=Q.length?Q:void 0;var U=new C$(Y.name.length?Y.name:"field"+Y.number,Y.number,X,J,Q);if(!q)U._edition=T;if(U.options=_Y(Y.options,p.FieldOptions),Y.proto3_optional)U.options.proto3_optional=!0;if(Y.defaultValue&&Y.defaultValue.length){var Z=Y.defaultValue;switch(Z){case"true":case"TRUE":Z=!0;break;case"false":case"FALSE":Z=!1;break;default:var K=n2.exec(Z);if(K)Z=parseInt(Z);break}U.setOption("default",Z)}if(t2(Y.type)){if(T==="proto3"){if(Y.options&&!Y.options.packed)U.setOption("packed",!1)}else if((!T||T==="proto2")&&Y.options&&Y.options.packed)U.setOption("packed",!0)}return U};C$.prototype.toDescriptor=function(Y){var T=p.FieldDescriptorProto.create({name:this.name,number:this.id});if(this.map)T.type=11,T.typeName=X1.util.ucFirst(this.name),T.label=3;else{switch(T.type=W5(this.type,this.resolve().resolvedType,this.delimited)){case 10:case 11:case 14:T.typeName=this.resolvedType?ZW(this.parent,this.resolvedType):this.type;break}if(this.rule==="repeated")T.label=3;else if(this.required&&Y==="proto2")T.label=2;else T.label=1}if(T.extendee=this.extensionField?this.extensionField.parent.fullName:this.extend,this.partOf){if((T.oneofIndex=this.parent.oneofsArray.indexOf(this.partOf))<0)throw Error("missing oneof")}if(this.options){if(T.options=gY(this.options,p.FieldOptions),this.options.default!=null)T.defaultValue=String(this.options.default);if(this.options.proto3_optional)T.proto3_optional=!0}if(Y==="proto3"){if(!this.packed)(T.options||(T.options=p.FieldOptions.create())).packed=!1}else if((!Y||Y==="proto2")&&this.packed)(T.options||(T.options=p.FieldOptions.create())).packed=!0;return T};var i2=0;U$.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.EnumDescriptorProto.decode(Y);var X={};if(Y.value)for(var J=0;J<Y.value.length;++J){var Q=Y.value[J].name,U=Y.value[J].number||0;X[Q&&Q.length?Q:"NAME"+U]=U}var Z=new U$(Y.name&&Y.name.length?Y.name:"Enum"+i2++,X,_Y(Y.options,p.EnumOptions));if(!q)Z._edition=T;return Z};U$.prototype.toDescriptor=function(){var Y=[];for(var T=0,q=Object.keys(this.values);T<q.length;++T)Y.push(p.EnumValueDescriptorProto.create({name:q[T],number:this.values[q[T]]}));return p.EnumDescriptorProto.create({name:this.name,value:Y,options:gY(this.options,p.EnumOptions)})};var r2=0;Rq.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.OneofDescriptorProto.decode(Y);return new Rq(Y.name&&Y.name.length?Y.name:"oneof"+r2++)};Rq.prototype.toDescriptor=function(){return p.OneofDescriptorProto.create({name:this.name})};var a2=0;oT.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.ServiceDescriptorProto.decode(Y);var X=new oT(Y.name&&Y.name.length?Y.name:"Service"+a2++,_Y(Y.options,p.ServiceOptions));if(!q)X._edition=T;if(Y.method)for(var J=0;J<Y.method.length;++J)X.add(Oq.fromDescriptor(Y.method[J]));return X};oT.prototype.toDescriptor=function(){var Y=[];for(var T=0;T<this.methodsArray.length;++T)Y.push(this._methodsArray[T].toDescriptor());return p.ServiceDescriptorProto.create({name:this.name,method:Y,options:gY(this.options,p.ServiceOptions)})};var o2=0;Oq.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.MethodDescriptorProto.decode(Y);return new Oq(Y.name&&Y.name.length?Y.name:"Method"+o2++,"rpc",Y.inputType,Y.outputType,Boolean(Y.clientStreaming),Boolean(Y.serverStreaming),_Y(Y.options,p.MethodOptions))};Oq.prototype.toDescriptor=function(){return p.MethodDescriptorProto.create({name:this.name,inputType:this.resolvedRequestType?this.resolvedRequestType.fullName:this.requestType,outputType:this.resolvedResponseType?this.resolvedResponseType.fullName:this.responseType,clientStreaming:this.requestStream,serverStreaming:this.responseStream,options:gY(this.options,p.MethodOptions)})};function s2($){switch($){case 1:return"double";case 2:return"float";case 3:return"int64";case 4:return"uint64";case 5:return"int32";case 6:return"fixed64";case 7:return"fixed32";case 8:return"bool";case 9:return"string";case 12:return"bytes";case 13:return"uint32";case 15:return"sfixed32";case 16:return"sfixed64";case 17:return"sint32";case 18:return"sint64"}throw Error("illegal type: "+$)}function t2($){switch($){case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 13:case 14:case 15:case 16:case 17:case 18:return!0}return!1}function W5($,Y,T){switch($){case"double":return 1;case"float":return 2;case"int64":return 3;case"uint64":return 4;case"int32":return 5;case"fixed64":return 6;case"fixed32":return 7;case"bool":return 8;case"string":return 9;case"bytes":return 12;case"uint32":return 13;case"sfixed32":return 15;case"sfixed64":return 16;case"sint32":return 17;case"sint64":return 18}if(Y instanceof U$)return 14;if(Y instanceof d1)return T?10:11;throw Error("illegal type: "+$)}function QW($,Y){var T={};for(var q=0,X,J;q<Y.fieldsArray.length;++q){if((J=(X=Y._fieldsArray[q]).name)==="uninterpretedOption")continue;if(!Object.prototype.hasOwnProperty.call($,J))continue;var Q=e2(J);if(X.resolvedType instanceof d1)T[Q]=QW($[J],X.resolvedType);else if(X.resolvedType instanceof U$)T[Q]=X.resolvedType.valuesById[$[J]];else T[Q]=$[J]}return T}function _Y($,Y){if(!$)return;return QW(Y.toObject($),Y)}function UW($,Y){var T={},q=Object.keys($);for(var X=0;X<q.length;++X){var J=q[X],Q=X1.util.camelCase(J);if(!Object.prototype.hasOwnProperty.call(Y.fields,Q))continue;var U=Y.fields[Q];if(U.resolvedType instanceof d1)T[Q]=UW($[J],U.resolvedType);else T[Q]=$[J];if(U.repeated&&!Array.isArray(T[Q]))T[Q]=[T[Q]]}return T}function gY($,Y){if(!$)return;return Y.fromObject(UW($,Y))}function ZW($,Y){var T=$.fullName.split("."),q=Y.fullName.split("."),X=0,J=0,Q=q.length-1;if(!($ instanceof aT)&&Y instanceof XW)while(X<T.length&&J<Q&&T[X]===q[J]){var U=Y.lookup(T[X++],!0);if(U!==null&&U!==Y)break;++J}else for(;X<T.length&&J<Q&&T[X]===q[J];++X,++J);return q.slice(J).join(".")}function e2($){return $.substring(0,1)+$.substring(1).replace(/([A-Z])(?=[a-z]|$)/g,function(Y,T){return"_"+T.toLowerCase()})}function $O($){if($.syntax==="editions")switch($.edition){case p.Edition.EDITION_2023:return"2023";default:throw Error("Unsupported edition "+$.edition)}if($.syntax==="proto3")return"proto3";return"proto2"}function YO($,Y){if(!$)return;if($==="proto2"||$==="proto3")Y.syntax=$;else switch(Y.syntax="editions",$){case"2023":Y.edition=p.Edition.EDITION_2023;break;default:throw Error("Unsupported edition "+$)}}});var WW=M((ag,TO)=>{TO.exports={nested:{google:{nested:{protobuf:{nested:{Api:{fields:{name:{type:"string",id:1},methods:{rule:"repeated",type:"Method",id:2},options:{rule:"repeated",type:"Option",id:3},version:{type:"string",id:4},sourceContext:{type:"SourceContext",id:5},mixins:{rule:"repeated",type:"Mixin",id:6},syntax:{type:"Syntax",id:7}}},Method:{fields:{name:{type:"string",id:1},requestTypeUrl:{type:"string",id:2},requestStreaming:{type:"bool",id:3},responseTypeUrl:{type:"string",id:4},responseStreaming:{type:"bool",id:5},options:{rule:"repeated",type:"Option",id:6},syntax:{type:"Syntax",id:7}}},Mixin:{fields:{name:{type:"string",id:1},root:{type:"string",id:2}}},SourceContext:{fields:{fileName:{type:"string",id:1}}},Option:{fields:{name:{type:"string",id:1},value:{type:"Any",id:2}}},Syntax:{values:{SYNTAX_PROTO2:0,SYNTAX_PROTO3:1}}}}}}}}});var GW=M((og,qO)=>{qO.exports={nested:{google:{nested:{protobuf:{nested:{SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var EW=M((sg,XO)=>{XO.exports={nested:{google:{nested:{protobuf:{nested:{Type:{fields:{name:{type:"string",id:1},fields:{rule:"repeated",type:"Field",id:2},oneofs:{rule:"repeated",type:"string",id:3},options:{rule:"repeated",type:"Option",id:4},sourceContext:{type:"SourceContext",id:5},syntax:{type:"Syntax",id:6}}},Field:{fields:{kind:{type:"Kind",id:1},cardinality:{type:"Cardinality",id:2},number:{type:"int32",id:3},name:{type:"string",id:4},typeUrl:{type:"string",id:6},oneofIndex:{type:"int32",id:7},packed:{type:"bool",id:8},options:{rule:"repeated",type:"Option",id:9},jsonName:{type:"string",id:10},defaultValue:{type:"string",id:11}},nested:{Kind:{values:{TYPE_UNKNOWN:0,TYPE_DOUBLE:1,TYPE_FLOAT:2,TYPE_INT64:3,TYPE_UINT64:4,TYPE_INT32:5,TYPE_FIXED64:6,TYPE_FIXED32:7,TYPE_BOOL:8,TYPE_STRING:9,TYPE_GROUP:10,TYPE_MESSAGE:11,TYPE_BYTES:12,TYPE_UINT32:13,TYPE_ENUM:14,TYPE_SFIXED32:15,TYPE_SFIXED64:16,TYPE_SINT32:17,TYPE_SINT64:18}},Cardinality:{values:{CARDINALITY_UNKNOWN:0,CARDINALITY_OPTIONAL:1,CARDINALITY_REQUIRED:2,CARDINALITY_REPEATED:3}}}},Enum:{fields:{name:{type:"string",id:1},enumvalue:{rule:"repeated",type:"EnumValue",id:2},options:{rule:"repeated",type:"Option",id:3},sourceContext:{type:"SourceContext",id:4},syntax:{type:"Syntax",id:5}}},EnumValue:{fields:{name:{type:"string",id:1},number:{type:"int32",id:2},options:{rule:"repeated",type:"Option",id:3}}},Option:{fields:{name:{type:"string",id:1},value:{type:"Any",id:2}}},Syntax:{values:{SYNTAX_PROTO2:0,SYNTAX_PROTO3:1}},Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}},SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var zW=M((NW)=>{Object.defineProperty(NW,"__esModule",{value:!0});NW.addCommonProtos=NW.loadProtosWithOptionsSync=NW.loadProtosWithOptions=void 0;var VW=s("fs"),DW=s("path"),mY=Bq();function FW($,Y){let T=$.resolvePath;$.resolvePath=(q,X)=>{if(DW.isAbsolute(X))return X;for(let J of Y){let Q=DW.join(J,X);try{return VW.accessSync(Q,VW.constants.R_OK),Q}catch(U){continue}}return process.emitWarning(`${X} not found in any of the include paths ${Y}`),T(q,X)}}async function JO($,Y){let T=new mY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))return Promise.reject(Error("The includeDirs option must be an array"));FW(T,Y.includeDirs)}let q=await T.load($,Y);return q.resolveAll(),q}NW.loadProtosWithOptions=JO;function QO($,Y){let T=new mY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))throw Error("The includeDirs option must be an array");FW(T,Y.includeDirs)}let q=T.loadSync($,Y);return q.resolveAll(),q}NW.loadProtosWithOptionsSync=QO;function UO(){let $=WW(),Y=A5(),T=GW(),q=EW();mY.common("api",$.nested.google.nested.protobuf.nested),mY.common("descriptor",Y.nested.google.nested.protobuf.nested),mY.common("source_context",T.nested.google.nested.protobuf.nested),mY.common("type",q.nested.google.nested.protobuf.nested)}NW.addCommonProtos=UO});var IW=M((sT,G5)=>{(function($,Y){function T(q){return q.default||q}if(typeof define==="function"&&define.amd)define([],function(){var q={};return Y(q),T(q)});else if(typeof sT==="object"){if(Y(sT),typeof G5==="object")G5.exports=T(sT)}else(function(){var q={};Y(q),$.Long=T(q)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:sT,function($){Object.defineProperty($,"__esModule",{value:!0}),$.default=void 0;var Y=null;try{Y=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function T(P,G,L){this.low=P|0,this.high=G|0,this.unsigned=!!L}T.prototype.__isLong__,Object.defineProperty(T.prototype,"__isLong__",{value:!0});function q(P){return(P&&P.__isLong__)===!0}function X(P){var G=Math.clz32(P&-P);return P?31-G:G}T.isLong=q;var J={},Q={};function U(P,G){var L,l,u;if(G){if(P>>>=0,u=0<=P&&P<256){if(l=Q[P],l)return l}if(L=K(P,0,!0),u)Q[P]=L;return L}else{if(P|=0,u=-128<=P&&P<128){if(l=J[P],l)return l}if(L=K(P,P<0?-1:0,!1),u)J[P]=L;return L}}T.fromInt=U;function Z(P,G){if(isNaN(P))return G?z:v;if(G){if(P<0)return z;if(P>=V)return C}else{if(P<=-B)return j;if(P+1>=B)return m}if(P<0)return Z(-P,G).neg();return K(P%H|0,P/H|0,G)}T.fromNumber=Z;function K(P,G,L){return new T(P,G,L)}T.fromBits=K;var A=Math.pow;function W(P,G,L){if(P.length===0)throw Error("empty string");if(typeof G==="number")L=G,G=!1;else G=!!G;if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return G?z:v;if(L=L||10,L<2||36<L)throw RangeError("radix");var l;if((l=P.indexOf("-"))>0)throw Error("interior hyphen");else if(l===0)return W(P.substring(1),G,L).neg();var u=Z(A(L,8)),d=v;for(var V0=0;V0<P.length;V0+=8){var _0=Math.min(8,P.length-V0),b0=parseInt(P.substring(V0,V0+_0),L);if(_0<8){var B0=Z(A(L,_0));d=d.mul(B0).add(Z(b0))}else d=d.mul(u),d=d.add(Z(b0))}return d.unsigned=G,d}T.fromString=W;function E(P,G){if(typeof P==="number")return Z(P,G);if(typeof P==="string")return W(P,G);return K(P.low,P.high,typeof G==="boolean"?G:P.unsigned)}T.fromValue=E;var D=65536,F=16777216,H=D*D,V=H*H,B=V/2,S=U(F),v=U(0);T.ZERO=v;var z=U(0,!0);T.UZERO=z;var _=U(1);T.ONE=_;var y=U(1,!0);T.UONE=y;var k=U(-1);T.NEG_ONE=k;var m=K(-1,2147483647,!1);T.MAX_VALUE=m;var C=K(-1,-1,!0);T.MAX_UNSIGNED_VALUE=C;var j=K(0,-2147483648,!1);T.MIN_VALUE=j;var I=T.prototype;if(I.toInt=function(){return this.unsigned?this.low>>>0:this.low},I.toNumber=function(){if(this.unsigned)return(this.high>>>0)*H+(this.low>>>0);return this.high*H+(this.low>>>0)},I.toString=function(G){if(G=G||10,G<2||36<G)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(j)){var L=Z(G),l=this.div(L),u=l.mul(L).sub(this);return l.toString(G)+u.toInt().toString(G)}else return"-"+this.neg().toString(G);var d=Z(A(G,6),this.unsigned),V0=this,_0="";while(!0){var b0=V0.div(d),B0=V0.sub(b0.mul(d)).toInt()>>>0,Y0=B0.toString(G);if(V0=b0,V0.isZero())return Y0+_0;else{while(Y0.length<6)Y0="0"+Y0;_0=""+Y0+_0}}},I.getHighBits=function(){return this.high},I.getHighBitsUnsigned=function(){return this.high>>>0},I.getLowBits=function(){return this.low},I.getLowBitsUnsigned=function(){return this.low>>>0},I.getNumBitsAbs=function(){if(this.isNegative())return this.eq(j)?64:this.neg().getNumBitsAbs();var G=this.high!=0?this.high:this.low;for(var L=31;L>0;L--)if((G&1<<L)!=0)break;return this.high!=0?L+33:L+1},I.isSafeInteger=function(){var G=this.high>>21;if(!G)return!0;if(this.unsigned)return!1;return G===-1&&!(this.low===0&&this.high===-2097152)},I.isZero=function(){return this.high===0&&this.low===0},I.eqz=I.isZero,I.isNegative=function(){return!this.unsigned&&this.high<0},I.isPositive=function(){return this.unsigned||this.high>=0},I.isOdd=function(){return(this.low&1)===1},I.isEven=function(){return(this.low&1)===0},I.equals=function(G){if(!q(G))G=E(G);if(this.unsigned!==G.unsigned&&this.high>>>31===1&&G.high>>>31===1)return!1;return this.high===G.high&&this.low===G.low},I.eq=I.equals,I.notEquals=function(G){return!this.eq(G)},I.neq=I.notEquals,I.ne=I.notEquals,I.lessThan=function(G){return this.comp(G)<0},I.lt=I.lessThan,I.lessThanOrEqual=function(G){return this.comp(G)<=0},I.lte=I.lessThanOrEqual,I.le=I.lessThanOrEqual,I.greaterThan=function(G){return this.comp(G)>0},I.gt=I.greaterThan,I.greaterThanOrEqual=function(G){return this.comp(G)>=0},I.gte=I.greaterThanOrEqual,I.ge=I.greaterThanOrEqual,I.compare=function(G){if(!q(G))G=E(G);if(this.eq(G))return 0;var L=this.isNegative(),l=G.isNegative();if(L&&!l)return-1;if(!L&&l)return 1;if(!this.unsigned)return this.sub(G).isNegative()?-1:1;return G.high>>>0>this.high>>>0||G.high===this.high&&G.low>>>0>this.low>>>0?-1:1},I.comp=I.compare,I.negate=function(){if(!this.unsigned&&this.eq(j))return j;return this.not().add(_)},I.neg=I.negate,I.add=function(G){if(!q(G))G=E(G);var L=this.high>>>16,l=this.high&65535,u=this.low>>>16,d=this.low&65535,V0=G.high>>>16,_0=G.high&65535,b0=G.low>>>16,B0=G.low&65535,Y0=0,u0=0,E0=0,d0=0;return d0+=d+B0,E0+=d0>>>16,d0&=65535,E0+=u+b0,u0+=E0>>>16,E0&=65535,u0+=l+_0,Y0+=u0>>>16,u0&=65535,Y0+=L+V0,Y0&=65535,K(E0<<16|d0,Y0<<16|u0,this.unsigned)},I.subtract=function(G){if(!q(G))G=E(G);return this.add(G.neg())},I.sub=I.subtract,I.multiply=function(G){if(this.isZero())return this;if(!q(G))G=E(G);if(Y){var L=Y.mul(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}if(G.isZero())return this.unsigned?z:v;if(this.eq(j))return G.isOdd()?j:v;if(G.eq(j))return this.isOdd()?j:v;if(this.isNegative())if(G.isNegative())return this.neg().mul(G.neg());else return this.neg().mul(G).neg();else if(G.isNegative())return this.mul(G.neg()).neg();if(this.lt(S)&&G.lt(S))return Z(this.toNumber()*G.toNumber(),this.unsigned);var l=this.high>>>16,u=this.high&65535,d=this.low>>>16,V0=this.low&65535,_0=G.high>>>16,b0=G.high&65535,B0=G.low>>>16,Y0=G.low&65535,u0=0,E0=0,d0=0,o1=0;return o1+=V0*Y0,d0+=o1>>>16,o1&=65535,d0+=d*Y0,E0+=d0>>>16,d0&=65535,d0+=V0*B0,E0+=d0>>>16,d0&=65535,E0+=u*Y0,u0+=E0>>>16,E0&=65535,E0+=d*B0,u0+=E0>>>16,E0&=65535,E0+=V0*b0,u0+=E0>>>16,E0&=65535,u0+=l*Y0+u*B0+d*b0+V0*_0,u0&=65535,K(d0<<16|o1,u0<<16|E0,this.unsigned)},I.mul=I.multiply,I.divide=function(G){if(!q(G))G=E(G);if(G.isZero())throw Error("division by zero");if(Y){if(!this.unsigned&&this.high===-2147483648&&G.low===-1&&G.high===-1)return this;var L=(this.unsigned?Y.div_u:Y.div_s)(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?z:v;var l,u,d;if(!this.unsigned){if(this.eq(j))if(G.eq(_)||G.eq(k))return j;else if(G.eq(j))return _;else{var V0=this.shr(1);if(l=V0.div(G).shl(1),l.eq(v))return G.isNegative()?_:k;else return u=this.sub(G.mul(l)),d=l.add(u.div(G)),d}else if(G.eq(j))return this.unsigned?z:v;if(this.isNegative()){if(G.isNegative())return this.neg().div(G.neg());return this.neg().div(G).neg()}else if(G.isNegative())return this.div(G.neg()).neg();d=v}else{if(!G.unsigned)G=G.toUnsigned();if(G.gt(this))return z;if(G.gt(this.shru(1)))return y;d=z}u=this;while(u.gte(G)){l=Math.max(1,Math.floor(u.toNumber()/G.toNumber()));var _0=Math.ceil(Math.log(l)/Math.LN2),b0=_0<=48?1:A(2,_0-48),B0=Z(l),Y0=B0.mul(G);while(Y0.isNegative()||Y0.gt(u))l-=b0,B0=Z(l,this.unsigned),Y0=B0.mul(G);if(B0.isZero())B0=_;d=d.add(B0),u=u.sub(Y0)}return d},I.div=I.divide,I.modulo=function(G){if(!q(G))G=E(G);if(Y){var L=(this.unsigned?Y.rem_u:Y.rem_s)(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}return this.sub(this.div(G).mul(G))},I.mod=I.modulo,I.rem=I.modulo,I.not=function(){return K(~this.low,~this.high,this.unsigned)},I.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},I.clz=I.countLeadingZeros,I.countTrailingZeros=function(){return this.low?X(this.low):X(this.high)+32},I.ctz=I.countTrailingZeros,I.and=function(G){if(!q(G))G=E(G);return K(this.low&G.low,this.high&G.high,this.unsigned)},I.or=function(G){if(!q(G))G=E(G);return K(this.low|G.low,this.high|G.high,this.unsigned)},I.xor=function(G){if(!q(G))G=E(G);return K(this.low^G.low,this.high^G.high,this.unsigned)},I.shiftLeft=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;else if(G<32)return K(this.low<<G,this.high<<G|this.low>>>32-G,this.unsigned);else return K(0,this.low<<G-32,this.unsigned)},I.shl=I.shiftLeft,I.shiftRight=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;else if(G<32)return K(this.low>>>G|this.high<<32-G,this.high>>G,this.unsigned);else return K(this.high>>G-32,this.high>=0?0:-1,this.unsigned)},I.shr=I.shiftRight,I.shiftRightUnsigned=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G<32)return K(this.low>>>G|this.high<<32-G,this.high>>>G,this.unsigned);if(G===32)return K(this.high,0,this.unsigned);return K(this.high>>>G-32,0,this.unsigned)},I.shru=I.shiftRightUnsigned,I.shr_u=I.shiftRightUnsigned,I.rotateLeft=function(G){var L;if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G===32)return K(this.high,this.low,this.unsigned);if(G<32)return L=32-G,K(this.low<<G|this.high>>>L,this.high<<G|this.low>>>L,this.unsigned);return G-=32,L=32-G,K(this.high<<G|this.low>>>L,this.low<<G|this.high>>>L,this.unsigned)},I.rotl=I.rotateLeft,I.rotateRight=function(G){var L;if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G===32)return K(this.high,this.low,this.unsigned);if(G<32)return L=32-G,K(this.high<<L|this.low>>>G,this.low<<L|this.high>>>G,this.unsigned);return G-=32,L=32-G,K(this.low<<L|this.high>>>G,this.high<<L|this.low>>>G,this.unsigned)},I.rotr=I.rotateRight,I.toSigned=function(){if(!this.unsigned)return this;return K(this.low,this.high,!1)},I.toUnsigned=function(){if(this.unsigned)return this;return K(this.low,this.high,!0)},I.toBytes=function(G){return G?this.toBytesLE():this.toBytesBE()},I.toBytesLE=function(){var G=this.high,L=this.low;return[L&255,L>>>8&255,L>>>16&255,L>>>24,G&255,G>>>8&255,G>>>16&255,G>>>24]},I.toBytesBE=function(){var G=this.high,L=this.low;return[G>>>24,G>>>16&255,G>>>8&255,G&255,L>>>24,L>>>16&255,L>>>8&255,L&255]},T.fromBytes=function(G,L,l){return l?T.fromBytesLE(G,L):T.fromBytesBE(G,L)},T.fromBytesLE=function(G,L){return new T(G[0]|G[1]<<8|G[2]<<16|G[3]<<24,G[4]|G[5]<<8|G[6]<<16|G[7]<<24,L)},T.fromBytesBE=function(G,L){return new T(G[4]<<24|G[5]<<16|G[6]<<8|G[7],G[0]<<24|G[1]<<16|G[2]<<8|G[3],L)},typeof BigInt==="function")T.fromBigInt=function(G,L){var l=Number(BigInt.asIntN(32,G)),u=Number(BigInt.asIntN(32,G>>BigInt(32)));return K(l,u,L)},T.fromValue=function(G,L){if(typeof G==="bigint")return T.fromBigInt(G,L);return E(G,L)},I.toBigInt=function(){var G=BigInt(this.low>>>0),L=BigInt(this.unsigned?this.high>>>0:this.high);return L<<BigInt(32)|G};var h0=$.default=T})});var tT=M((LW)=>{Object.defineProperty(LW,"__esModule",{value:!0});LW.loadFileDescriptorSetFromObject=LW.loadFileDescriptorSetFromBuffer=LW.fromJSON=LW.loadSync=LW.load=LW.IdempotencyLevel=LW.isAnyExtension=LW.Long=void 0;var AO=WK(),c1=Bq(),F5=AW(),N5=zW(),WO=IW();LW.Long=WO;function GO($){return"@type"in $&&typeof $["@type"]==="string"}LW.isAnyExtension=GO;var BW;(function($){$.IDEMPOTENCY_UNKNOWN="IDEMPOTENCY_UNKNOWN",$.NO_SIDE_EFFECTS="NO_SIDE_EFFECTS",$.IDEMPOTENT="IDEMPOTENT"})(BW=LW.IdempotencyLevel||(LW.IdempotencyLevel={}));var RW={longs:String,enums:String,bytes:String,defaults:!0,oneofs:!0,json:!0};function EO($,Y){if($==="")return Y;else return $+"."+Y}function VO($){return $ instanceof c1.Service||$ instanceof c1.Type||$ instanceof c1.Enum}function DO($){return $ instanceof c1.Namespace||$ instanceof c1.Root}function OW($,Y){let T=EO(Y,$.name);if(VO($))return[[T,$]];else if(DO($)&&typeof $.nested<"u")return Object.keys($.nested).map((q)=>{return OW($.nested[q],T)}).reduce((q,X)=>q.concat(X),[]);return[]}function E5($,Y){return function(q){return $.toObject($.decode(q),Y)}}function V5($){return function(T){if(Array.isArray(T))throw Error(`Failed to serialize message: expected object with ${$.name} structure, got array instead`);let q=$.fromObject(T);return $.encode(q).finish()}}function FO($){return($||[]).reduce((Y,T)=>{for(let[q,X]of Object.entries(T))switch(q){case"uninterpreted_option":Y.uninterpreted_option.push(T.uninterpreted_option);break;default:Y[q]=X}return Y},{deprecated:!1,idempotency_level:BW.IDEMPOTENCY_UNKNOWN,uninterpreted_option:[]})}function NO($,Y,T,q){let{resolvedRequestType:X,resolvedResponseType:J}=$;return{path:"/"+Y+"/"+$.name,requestStream:!!$.requestStream,responseStream:!!$.responseStream,requestSerialize:V5(X),requestDeserialize:E5(X,T),responseSerialize:V5(J),responseDeserialize:E5(J,T),originalName:AO($.name),requestType:D5(X,T,q),responseType:D5(J,T,q),options:FO($.parsedOptions)}}function HO($,Y,T,q){let X={};for(let J of $.methodsArray)X[J.name]=NO(J,Y,T,q);return X}function D5($,Y,T){let q=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 DescriptorProto",type:q.$type.toObject(q,RW),fileDescriptorProtos:T,serialize:V5($),deserialize:E5($,Y)}}function zO($,Y){let T=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 EnumDescriptorProto",type:T.$type.toObject(T,RW),fileDescriptorProtos:Y}}function IO($,Y,T,q){if($ instanceof c1.Service)return HO($,Y,T,q);else if($ instanceof c1.Type)return D5($,T,q);else if($ instanceof c1.Enum)return zO($,q);else throw Error("Type mismatch in reflection object handling")}function Pq($,Y){let T={};$.resolveAll();let X=$.toDescriptor("proto3").file.map((J)=>Buffer.from(F5.FileDescriptorProto.encode(J).finish()));for(let[J,Q]of OW($,""))T[J]=IO(Q,J,Y,X);return T}function PW($,Y){Y=Y||{};let T=c1.Root.fromDescriptor($);return T.resolveAll(),Pq(T,Y)}function MO($,Y){return(0,N5.loadProtosWithOptions)($,Y).then((T)=>{return Pq(T,Y)})}LW.load=MO;function BO($,Y){let T=(0,N5.loadProtosWithOptionsSync)($,Y);return Pq(T,Y)}LW.loadSync=BO;function RO($,Y){Y=Y||{};let T=c1.Root.fromJSON($);return T.resolveAll(),Pq(T,Y)}LW.fromJSON=RO;function OO($,Y){let T=F5.FileDescriptorSet.decode($);return PW(T,Y)}LW.loadFileDescriptorSetFromBuffer=OO;function PO($,Y){let T=F5.FileDescriptorSet.fromObject($);return PW(T,Y)}LW.loadFileDescriptorSetFromObject=PO;(0,N5.addCommonProtos)()});var y$=M((uW)=>{var __dirname="/Users/beatrix/dev/clinee/sdk-wip/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(uW,"__esModule",{value:!0});uW.registerChannelzSocket=uW.registerChannelzServer=uW.registerChannelzSubchannel=uW.registerChannelzChannel=uW.ChannelzCallTrackerStub=uW.ChannelzCallTracker=uW.ChannelzChildrenTrackerStub=uW.ChannelzChildrenTracker=uW.ChannelzTrace=uW.ChannelzTraceStub=void 0;uW.unregisterChannelzRef=_O;uW.getChannelzHandlers=fW;uW.getChannelzServiceDefinition=bW;uW.setup=iO;var wq=s("net"),e$=EZ(),eT=l0(),$6=i(),vO=r0(),xO=i8(),kO=a8();function H5($){return{channel_id:$.id,name:$.name}}function z5($){return{subchannel_id:$.id,name:$.name}}function hO($){return{server_id:$.id}}function Sq($){return{socket_id:$.id,name:$.name}}var SW=32,I5=100;class vW{constructor(){this.events=[],this.creationTimestamp=new Date,this.eventsLogged=0}addTrace(){}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:[]}}}uW.ChannelzTraceStub=vW;class xW{constructor(){this.events=[],this.eventsLogged=0,this.creationTimestamp=new Date}addTrace($,Y,T){let q=new Date;if(this.events.push({description:Y,severity:$,timestamp:q,childChannel:(T===null||T===void 0?void 0:T.kind)==="channel"?T:void 0,childSubchannel:(T===null||T===void 0?void 0:T.kind)==="subchannel"?T:void 0}),this.events.length>=SW*2)this.events=this.events.slice(SW);this.eventsLogged+=1}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:this.events.map(($)=>{return{description:$.description,severity:$.severity,timestamp:p1($.timestamp),channel_ref:$.childChannel?H5($.childChannel):null,subchannel_ref:$.childSubchannel?z5($.childSubchannel):null}})}}}uW.ChannelzTrace=xW;class M5{constructor(){this.channelChildren=new e$.OrderedMap,this.subchannelChildren=new e$.OrderedMap,this.socketChildren=new e$.OrderedMap,this.trackerMap={["channel"]:this.channelChildren,["subchannel"]:this.subchannelChildren,["socket"]:this.socketChildren}}refChild($){let Y=this.trackerMap[$.kind],T=Y.find($.id);if(T.equals(Y.end()))Y.setElement($.id,{ref:$,count:1},T);else T.pointer[1].count+=1}unrefChild($){let Y=this.trackerMap[$.kind],T=Y.getElementByKey($.id);if(T!==void 0){if(T.count-=1,T.count===0)Y.eraseElementByKey($.id)}}getChildLists(){return{channels:this.channelChildren,subchannels:this.subchannelChildren,sockets:this.socketChildren}}}uW.ChannelzChildrenTracker=M5;class kW extends M5{refChild(){}unrefChild(){}}uW.ChannelzChildrenTrackerStub=kW;class B5{constructor(){this.callsStarted=0,this.callsSucceeded=0,this.callsFailed=0,this.lastCallStartedTimestamp=null}addCallStarted(){this.callsStarted+=1,this.lastCallStartedTimestamp=new Date}addCallSucceeded(){this.callsSucceeded+=1}addCallFailed(){this.callsFailed+=1}}uW.ChannelzCallTracker=B5;class hW extends B5{addCallStarted(){}addCallSucceeded(){}addCallFailed(){}}uW.ChannelzCallTrackerStub=hW;var Z$={["channel"]:new e$.OrderedMap,["subchannel"]:new e$.OrderedMap,["server"]:new e$.OrderedMap,["socket"]:new e$.OrderedMap},Cq=($)=>{let Y=1;function T(){return Y++}let q=Z$[$];return(X,J,Q)=>{let U=T(),Z={id:U,name:X,kind:$};if(Q)q.setElement(U,{ref:Z,getInfo:J});return Z}};uW.registerChannelzChannel=Cq("channel");uW.registerChannelzSubchannel=Cq("subchannel");uW.registerChannelzServer=Cq("server");uW.registerChannelzSocket=Cq("socket");function _O($){Z$[$.kind].eraseElementByKey($.id)}function gO($){let Y=Number.parseInt($,16);return[Y/256|0,Y%256]}function CW($){if($==="")return[];let Y=$.split(":").map((q)=>gO(q));return[].concat(...Y)}function mO($){return(0,wq.isIPv6)($)&&$.toLowerCase().startsWith("::ffff:")&&(0,wq.isIPv4)($.substring(7))}function yW($){return Buffer.from(Uint8Array.from($.split(".").map((Y)=>Number.parseInt(Y))))}function fO($){if((0,wq.isIPv4)($))return yW($);else if(mO($))return yW($.substring(7));else if((0,wq.isIPv6)($)){let Y,T,q=$.indexOf("::");if(q===-1)Y=$,T="";else Y=$.substring(0,q),T=$.substring(q+2);let X=Buffer.from(CW(Y)),J=Buffer.from(CW(T)),Q=Buffer.alloc(16-X.length-J.length,0);return Buffer.concat([X,Q,J])}else return null}function _W($){switch($){case eT.ConnectivityState.CONNECTING:return{state:"CONNECTING"};case eT.ConnectivityState.IDLE:return{state:"IDLE"};case eT.ConnectivityState.READY:return{state:"READY"};case eT.ConnectivityState.SHUTDOWN:return{state:"SHUTDOWN"};case eT.ConnectivityState.TRANSIENT_FAILURE:return{state:"TRANSIENT_FAILURE"};default:return{state:"UNKNOWN"}}}function p1($){if(!$)return null;let Y=$.getTime();return{seconds:Y/1000|0,nanos:Y%1000*1e6}}function gW($){let Y=$.getInfo(),T=[],q=[];return Y.children.channels.forEach((X)=>{T.push(H5(X[1].ref))}),Y.children.subchannels.forEach((X)=>{q.push(z5(X[1].ref))}),{ref:H5($.ref),data:{target:Y.target,state:_W(Y.state),calls_started:Y.callTracker.callsStarted,calls_succeeded:Y.callTracker.callsSucceeded,calls_failed:Y.callTracker.callsFailed,last_call_started_timestamp:p1(Y.callTracker.lastCallStartedTimestamp),trace:Y.trace.getTraceMessage()},channel_ref:T,subchannel_ref:q}}function bO($,Y){let T=parseInt($.request.channel_id,10),q=Z$.channel.getElementByKey(T);if(q===void 0){Y({code:$6.Status.NOT_FOUND,details:"No channel data found for id "+T});return}Y(null,{channel:gW(q)})}function uO($,Y){let T=parseInt($.request.max_results,10)||I5,q=[],X=parseInt($.request.start_channel_id,10),J=Z$.channel,Q;for(Q=J.lowerBound(X);!Q.equals(J.end())&&q.length<T;Q=Q.next())q.push(gW(Q.pointer[1]));Y(null,{channel:q,end:Q.equals(J.end())})}function mW($){let Y=$.getInfo(),T=[];return Y.listenerChildren.sockets.forEach((q)=>{T.push(Sq(q[1].ref))}),{ref:hO($.ref),data:{calls_started:Y.callTracker.callsStarted,calls_succeeded:Y.callTracker.callsSucceeded,calls_failed:Y.callTracker.callsFailed,last_call_started_timestamp:p1(Y.callTracker.lastCallStartedTimestamp),trace:Y.trace.getTraceMessage()},listen_socket:T}}function dO($,Y){let T=parseInt($.request.server_id,10),X=Z$.server.getElementByKey(T);if(X===void 0){Y({code:$6.Status.NOT_FOUND,details:"No server data found for id "+T});return}Y(null,{server:mW(X)})}function cO($,Y){let T=parseInt($.request.max_results,10)||I5,q=parseInt($.request.start_server_id,10),X=Z$.server,J=[],Q;for(Q=X.lowerBound(q);!Q.equals(X.end())&&J.length<T;Q=Q.next())J.push(mW(Q.pointer[1]));Y(null,{server:J,end:Q.equals(X.end())})}function pO($,Y){let T=parseInt($.request.subchannel_id,10),q=Z$.subchannel.getElementByKey(T);if(q===void 0){Y({code:$6.Status.NOT_FOUND,details:"No subchannel data found for id "+T});return}let X=q.getInfo(),J=[];X.children.sockets.forEach((U)=>{J.push(Sq(U[1].ref))});let Q={ref:z5(q.ref),data:{target:X.target,state:_W(X.state),calls_started:X.callTracker.callsStarted,calls_succeeded:X.callTracker.callsSucceeded,calls_failed:X.callTracker.callsFailed,last_call_started_timestamp:p1(X.callTracker.lastCallStartedTimestamp),trace:X.trace.getTraceMessage()},socket_ref:J};Y(null,{subchannel:Q})}function jW($){var Y;if((0,vO.isTcpSubchannelAddress)($))return{address:"tcpip_address",tcpip_address:{ip_address:(Y=fO($.host))!==null&&Y!==void 0?Y:void 0,port:$.port}};else return{address:"uds_address",uds_address:{filename:$.path}}}function lO($,Y){var T,q,X,J,Q;let U=parseInt($.request.socket_id,10),Z=Z$.socket.getElementByKey(U);if(Z===void 0){Y({code:$6.Status.NOT_FOUND,details:"No socket data found for id "+U});return}let K=Z.getInfo(),A=K.security?{model:"tls",tls:{cipher_suite:K.security.cipherSuiteStandardName?"standard_name":"other_name",standard_name:(T=K.security.cipherSuiteStandardName)!==null&&T!==void 0?T:void 0,other_name:(q=K.security.cipherSuiteOtherName)!==null&&q!==void 0?q:void 0,local_certificate:(X=K.security.localCertificate)!==null&&X!==void 0?X:void 0,remote_certificate:(J=K.security.remoteCertificate)!==null&&J!==void 0?J:void 0}}:null,W={ref:Sq(Z.ref),local:K.localAddress?jW(K.localAddress):null,remote:K.remoteAddress?jW(K.remoteAddress):null,remote_name:(Q=K.remoteName)!==null&&Q!==void 0?Q:void 0,security:A,data:{keep_alives_sent:K.keepAlivesSent,streams_started:K.streamsStarted,streams_succeeded:K.streamsSucceeded,streams_failed:K.streamsFailed,last_local_stream_created_timestamp:p1(K.lastLocalStreamCreatedTimestamp),last_remote_stream_created_timestamp:p1(K.lastRemoteStreamCreatedTimestamp),messages_received:K.messagesReceived,messages_sent:K.messagesSent,last_message_received_timestamp:p1(K.lastMessageReceivedTimestamp),last_message_sent_timestamp:p1(K.lastMessageSentTimestamp),local_flow_control_window:K.localFlowControlWindow?{value:K.localFlowControlWindow}:null,remote_flow_control_window:K.remoteFlowControlWindow?{value:K.remoteFlowControlWindow}:null}};Y(null,{socket:W})}function nO($,Y){let T=parseInt($.request.server_id,10),q=Z$.server.getElementByKey(T);if(q===void 0){Y({code:$6.Status.NOT_FOUND,details:"No server data found for id "+T});return}let X=parseInt($.request.start_socket_id,10),J=parseInt($.request.max_results,10)||I5,U=q.getInfo().sessionChildren.sockets,Z=[],K;for(K=U.lowerBound(X);!K.equals(U.end())&&Z.length<J;K=K.next())Z.push(Sq(K.pointer[1].ref));Y(null,{socket_ref:Z,end:K.equals(U.end())})}function fW(){return{GetChannel:bO,GetTopChannels:uO,GetServer:dO,GetServers:cO,GetSubchannel:pO,GetSocket:lO,GetServerSockets:nO}}var Lq=null;function bW(){if(Lq)return Lq;let $=tT().loadSync,Y=$("channelz.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto`]});return Lq=(0,kO.loadPackageDefinition)(Y).grpc.channelz.v1.Channelz.service,Lq}function iO(){(0,xO.registerAdminService)(bW,fW)}});var yq=M((cW)=>{Object.defineProperty(cW,"__esModule",{value:!0});cW.getNextCallNumber=ZP;var UP=0;function ZP(){return UP++}});var R5=M((lW)=>{Object.defineProperty(lW,"__esModule",{value:!0});lW.CompressionAlgorithms=void 0;var pW;(function($){$[$.identity=0]="identity",$[$.deflate=1]="deflate",$[$.gzip=2]="gzip"})(pW||(lW.CompressionAlgorithms=pW={}))});var O5=M((rW)=>{Object.defineProperty(rW,"__esModule",{value:!0});rW.BaseFilter=void 0;class iW{async sendMetadata($){return $}receiveMetadata($){return $}async sendMessage($){return $}async receiveMessage($){return $}receiveTrailers($){return $}}rW.BaseFilter=iW});var L5=M((TG)=>{Object.defineProperty(TG,"__esModule",{value:!0});TG.CompressionFilterFactory=TG.CompressionFilter=void 0;var jq=s("zlib"),sW=R5(),fY=i(),AP=O5(),WP=U0(),GP=($)=>{return typeof $==="number"&&typeof sW.CompressionAlgorithms[$]==="string"};class Y6{async writeMessage($,Y){let T=$;if(Y)T=await this.compressMessage(T);let q=Buffer.allocUnsafe(T.length+5);return q.writeUInt8(Y?1:0,0),q.writeUInt32BE(T.length,1),T.copy(q,5),q}async readMessage($){let Y=$.readUInt8(0)===1,T=$.slice(5);if(Y)T=await this.decompressMessage(T);return T}}class bY extends Y6{async compressMessage($){return $}async writeMessage($,Y){let T=Buffer.allocUnsafe($.length+5);return T.writeUInt8(0,0),T.writeUInt32BE($.length,1),$.copy(T,5),T}decompressMessage($){return Promise.reject(Error('Received compressed message but "grpc-encoding" header was identity'))}}class tW extends Y6{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,T)=>{jq.deflate($,(q,X)=>{if(q)T(q);else Y(X)})})}decompressMessage($){return new Promise((Y,T)=>{let q=0,X=[],J=jq.createInflate();J.on("data",(Q)=>{if(X.push(Q),q+=Q.byteLength,this.maxRecvMessageLength!==-1&&q>this.maxRecvMessageLength)J.destroy(),T({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{Y(Buffer.concat(X))}),J.write($),J.end()})}}class eW extends Y6{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,T)=>{jq.gzip($,(q,X)=>{if(q)T(q);else Y(X)})})}decompressMessage($){return new Promise((Y,T)=>{let q=0,X=[],J=jq.createGunzip();J.on("data",(Q)=>{if(X.push(Q),q+=Q.byteLength,this.maxRecvMessageLength!==-1&&q>this.maxRecvMessageLength)J.destroy(),T({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{Y(Buffer.concat(X))}),J.write($),J.end()})}}class $G extends Y6{constructor($){super();this.compressionName=$}compressMessage($){return Promise.reject(Error(`Received message compressed with unsupported compression method ${this.compressionName}`))}decompressMessage($){return Promise.reject(Error(`Compression method not supported: ${this.compressionName}`))}}function oW($,Y){switch($){case"identity":return new bY;case"deflate":return new tW(Y);case"gzip":return new eW(Y);default:return new $G($)}}class P5 extends AP.BaseFilter{constructor($,Y){var T,q,X;super();this.sharedFilterConfig=Y,this.sendCompression=new bY,this.receiveCompression=new bY,this.currentCompressionAlgorithm="identity";let J=$["grpc.default_compression_algorithm"];if(this.maxReceiveMessageLength=(T=$["grpc.max_receive_message_length"])!==null&&T!==void 0?T:fY.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.maxSendMessageLength=(q=$["grpc.max_send_message_length"])!==null&&q!==void 0?q:fY.DEFAULT_MAX_SEND_MESSAGE_LENGTH,J!==void 0)if(GP(J)){let Q=sW.CompressionAlgorithms[J],U=(X=Y.serverSupportedEncodingHeader)===null||X===void 0?void 0:X.split(",");if(!U||U.includes(Q))this.currentCompressionAlgorithm=Q,this.sendCompression=oW(this.currentCompressionAlgorithm,-1)}else WP.log(fY.LogVerbosity.ERROR,`Invalid value provided for grpc.default_compression_algorithm option: ${J}`)}async sendMetadata($){let Y=await $;if(Y.set("grpc-accept-encoding","identity,deflate,gzip"),Y.set("accept-encoding","identity"),this.currentCompressionAlgorithm==="identity")Y.remove("grpc-encoding");else Y.set("grpc-encoding",this.currentCompressionAlgorithm);return Y}receiveMetadata($){let Y=$.get("grpc-encoding");if(Y.length>0){let q=Y[0];if(typeof q==="string")this.receiveCompression=oW(q,this.maxReceiveMessageLength)}$.remove("grpc-encoding");let T=$.get("grpc-accept-encoding")[0];if(T){if(this.sharedFilterConfig.serverSupportedEncodingHeader=T,!T.split(",").includes(this.currentCompressionAlgorithm))this.sendCompression=new bY,this.currentCompressionAlgorithm="identity"}return $.remove("grpc-accept-encoding"),$}async sendMessage($){var Y;let T=await $;if(this.maxSendMessageLength!==-1&&T.message.length>this.maxSendMessageLength)throw{code:fY.Status.RESOURCE_EXHAUSTED,details:`Attempted to send message with a size larger than ${this.maxSendMessageLength}`};let q;if(this.sendCompression instanceof bY)q=!1;else q=(((Y=T.flags)!==null&&Y!==void 0?Y:0)&2)===0;return{message:await this.sendCompression.writeMessage(T.message,q),flags:T.flags}}async receiveMessage($){return this.receiveCompression.readMessage(await $)}}TG.CompressionFilter=P5;class YG{constructor($,Y){this.options=Y,this.sharedFilterConfig={}}createFilter(){return new P5(this.options,this.sharedFilterConfig)}}TG.CompressionFilterFactory=YG});var T6=M((XG)=>{Object.defineProperty(XG,"__esModule",{value:!0});XG.restrictControlPlaneStatusCode=DP;var l1=i(),VP=[l1.Status.OK,l1.Status.INVALID_ARGUMENT,l1.Status.NOT_FOUND,l1.Status.ALREADY_EXISTS,l1.Status.FAILED_PRECONDITION,l1.Status.ABORTED,l1.Status.OUT_OF_RANGE,l1.Status.DATA_LOSS];function DP($,Y){if(VP.includes($))return{code:l1.Status.INTERNAL,details:`Invalid status from control plane: ${$} ${l1.Status[$]} ${Y}`};else return{code:$,details:Y}}});var uY=M((JG)=>{Object.defineProperty(JG,"__esModule",{value:!0});JG.minDeadline=NP;JG.getDeadlineTimeoutString=zP;JG.getRelativeTimeout=MP;JG.deadlineToString=BP;JG.formatDateDifference=RP;function NP(...$){let Y=1/0;for(let T of $){let q=T instanceof Date?T.getTime():T;if(q<Y)Y=q}return Y}var HP=[["m",1],["S",1000],["M",60000],["H",3600000]];function zP($){let Y=new Date().getTime();if($ instanceof Date)$=$.getTime();let T=Math.max($-Y,0);for(let[q,X]of HP){let J=T/X;if(J<1e8)return String(Math.ceil(J))+q}throw Error("Deadline is too far in the future")}var IP=2147483647;function MP($){let Y=$ instanceof Date?$.getTime():$,T=new Date().getTime(),q=Y-T;if(q<0)return 0;else if(q>IP)return 1/0;else return q}function BP($){if($ instanceof Date)return $.toISOString();else{let Y=new Date($);if(Number.isNaN(Y.getTime()))return""+$;else return Y.toISOString()}}function RP($,Y){return((Y.getTime()-$.getTime())/1000).toFixed(3)+"s"}});var vq=M((QG)=>{Object.defineProperty(QG,"__esModule",{value:!0});QG.FilterStackFactory=QG.FilterStack=void 0;class w5{constructor($){this.filters=$}sendMetadata($){let Y=$;for(let T=0;T<this.filters.length;T++)Y=this.filters[T].sendMetadata(Y);return Y}receiveMetadata($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveMetadata(Y);return Y}sendMessage($){let Y=$;for(let T=0;T<this.filters.length;T++)Y=this.filters[T].sendMessage(Y);return Y}receiveMessage($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveMessage(Y);return Y}receiveTrailers($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveTrailers(Y);return Y}push($){this.filters.unshift(...$)}getFilters(){return this.filters}}QG.FilterStack=w5;class S5{constructor($){this.factories=$}push($){this.factories.unshift(...$)}clone(){return new S5([...this.factories])}createFilter(){return new w5(this.factories.map(($)=>$.createFilter()))}}QG.FilterStackFactory=S5});var GG=M((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});AG.SingleSubchannelChannel=void 0;var yP=yq(),q6=y$(),jP=L5(),vP=l0(),X6=i(),xP=T6(),kP=uY(),hP=vq(),C5=P0(),_P=B1(),xq=p0();class ZG{constructor($,Y,T,q,X){var J,Q;this.subchannel=$,this.method=Y,this.options=q,this.callNumber=X,this.childCall=null,this.pendingMessage=null,this.readPending=!1,this.halfClosePending=!1,this.pendingStatus=null,this.readFilterPending=!1,this.writeFilterPending=!1;let U=this.method.split("/"),Z="";if(U.length>=2)Z=U[1];let K=(Q=(J=(0,xq.splitHostPort)(this.options.host))===null||J===void 0?void 0:J.host)!==null&&Q!==void 0?Q:"localhost";this.serviceUrl=`https://${K}/${Z}`;let A=(0,kP.getRelativeTimeout)(q.deadline);if(A!==1/0)if(A<=0)this.cancelWithStatus(X6.Status.DEADLINE_EXCEEDED,"Deadline exceeded");else setTimeout(()=>{this.cancelWithStatus(X6.Status.DEADLINE_EXCEEDED,"Deadline exceeded")},A);this.filterStack=T.createFilter()}cancelWithStatus($,Y){if(this.childCall)this.childCall.cancelWithStatus($,Y);else this.pendingStatus={code:$,details:Y,metadata:new C5.Metadata}}getPeer(){var $,Y;return(Y=($=this.childCall)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.subchannel.getAddress()}async start($,Y){if(this.pendingStatus){Y.onReceiveStatus(this.pendingStatus);return}if(this.subchannel.getConnectivityState()!==vP.ConnectivityState.READY){Y.onReceiveStatus({code:X6.Status.UNAVAILABLE,details:"Subchannel not ready",metadata:new C5.Metadata});return}let T=await this.filterStack.sendMetadata(Promise.resolve($)),q;try{q=await this.subchannel.getCallCredentials().generateMetadata({method_name:this.method,service_url:this.serviceUrl})}catch(J){let Q=J,{code:U,details:Z}=(0,xP.restrictControlPlaneStatusCode)(typeof Q.code==="number"?Q.code:X6.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Q.message}`);Y.onReceiveStatus({code:U,details:Z,metadata:new C5.Metadata});return}q.merge(T);let X={onReceiveMetadata:async(J)=>{Y.onReceiveMetadata(await this.filterStack.receiveMetadata(J))},onReceiveMessage:async(J)=>{this.readFilterPending=!0;let Q=await this.filterStack.receiveMessage(J);if(this.readFilterPending=!1,Y.onReceiveMessage(Q),this.pendingStatus)Y.onReceiveStatus(this.pendingStatus)},onReceiveStatus:async(J)=>{let Q=await this.filterStack.receiveTrailers(J);if(this.readFilterPending)this.pendingStatus=Q;else Y.onReceiveStatus(Q)}};if(this.childCall=this.subchannel.createCall(q,this.options.host,this.method,X),this.readPending)this.childCall.startRead();if(this.pendingMessage)this.childCall.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.halfClosePending&&!this.writeFilterPending)this.childCall.halfClose()}async sendMessageWithContext($,Y){this.writeFilterPending=!0;let T=await this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags}));if(this.writeFilterPending=!1,this.childCall){if(this.childCall.sendMessageWithContext($,T.message),this.halfClosePending)this.childCall.halfClose()}else this.pendingMessage={context:$,message:T.message}}startRead(){if(this.childCall)this.childCall.startRead();else this.readPending=!0}halfClose(){if(this.childCall&&!this.writeFilterPending)this.childCall.halfClose();else this.halfClosePending=!0}getCallNumber(){return this.callNumber}setCredentials($){throw Error("Method not implemented.")}getAuthContext(){if(this.childCall)return this.childCall.getAuthContext();else return null}}class KG{constructor($,Y,T){if(this.subchannel=$,this.target=Y,this.channelzEnabled=!1,this.channelzTrace=new q6.ChannelzTrace,this.callTracker=new q6.ChannelzCallTracker,this.childrenTracker=new q6.ChannelzChildrenTracker,this.channelzEnabled=T["grpc.enable_channelz"]!==0,this.channelzRef=(0,q6.registerChannelzChannel)((0,xq.uriToString)(Y),()=>({target:`${(0,xq.uriToString)(Y)} (${$.getAddress()})`,state:this.subchannel.getConnectivityState(),trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}),this.channelzEnabled),this.channelzEnabled)this.childrenTracker.refChild($.getChannelzRef());this.filterStackFactory=new hP.FilterStackFactory([new jP.CompressionFilterFactory(this,T)])}close(){if(this.channelzEnabled)this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());(0,q6.unregisterChannelzRef)(this.channelzRef)}getTarget(){return(0,xq.uriToString)(this.target)}getConnectivityState($){throw Error("Method not implemented.")}watchConnectivityState($,Y,T){throw Error("Method not implemented.")}getChannelzRef(){return this.channelzRef}createCall($,Y){let T={deadline:Y,host:(0,_P.getDefaultAuthority)(this.target),flags:X6.Propagate.DEFAULTS,parentCall:null};return new ZG(this.subchannel,$,this.filterStackFactory,T,(0,yP.getNextCallNumber)())}}AG.SingleSubchannelChannel=KG});var FG=M((VG)=>{Object.defineProperty(VG,"__esModule",{value:!0});VG.Subchannel=void 0;var q0=l0(),gP=LY(),y5=U0(),kq=i(),mP=p0(),fP=r0(),n1=y$(),bP=GG(),uP="subchannel",dP=2147483647;class EG{constructor($,Y,T,q,X){var J;this.channelTarget=$,this.subchannelAddress=Y,this.options=T,this.connector=X,this.connectivityState=q0.ConnectivityState.IDLE,this.transport=null,this.continueConnecting=!1,this.stateListeners=new Set,this.refcount=0,this.channelzEnabled=!0,this.dataProducers=new Map,this.subchannelChannel=null;let Q={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};if(this.backoffTimeout=new gP.BackoffTimeout(()=>{this.handleBackoffTimer()},Q),this.backoffTimeout.unref(),this.subchannelAddressString=(0,fP.subchannelAddressToString)(Y),this.keepaliveTime=(J=T["grpc.keepalive_time_ms"])!==null&&J!==void 0?J:-1,T["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new n1.ChannelzTraceStub,this.callTracker=new n1.ChannelzCallTrackerStub,this.childrenTracker=new n1.ChannelzChildrenTrackerStub,this.streamTracker=new n1.ChannelzCallTrackerStub;else this.channelzTrace=new n1.ChannelzTrace,this.callTracker=new n1.ChannelzCallTracker,this.childrenTracker=new n1.ChannelzChildrenTracker,this.streamTracker=new n1.ChannelzCallTracker;this.channelzRef=(0,n1.registerChannelzSubchannel)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Subchannel created"),this.trace("Subchannel constructed with options "+JSON.stringify(T,void 0,2)),this.secureConnector=q._createSecureConnector($,T)}getChannelzInfo(){return{state:this.connectivityState,trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists(),target:this.subchannelAddressString}}trace($){y5.trace(kq.LogVerbosity.DEBUG,uP,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}refTrace($){y5.trace(kq.LogVerbosity.DEBUG,"subchannel_refcount","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}handleBackoffTimer(){if(this.continueConnecting)this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.CONNECTING);else this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.IDLE)}startBackoff(){this.backoffTimeout.runOnce()}stopBackoff(){this.backoffTimeout.stop(),this.backoffTimeout.reset()}startConnectingInternal(){let $=this.options;if($["grpc.keepalive_time_ms"]){let Y=Math.min(this.keepaliveTime,dP);$=Object.assign(Object.assign({},$),{"grpc.keepalive_time_ms":Y})}this.connector.connect(this.subchannelAddress,this.secureConnector,$).then((Y)=>{if(this.transitionToState([q0.ConnectivityState.CONNECTING],q0.ConnectivityState.READY)){if(this.transport=Y,this.channelzEnabled)this.childrenTracker.refChild(Y.getChannelzRef());Y.addDisconnectListener((T)=>{if(this.transitionToState([q0.ConnectivityState.READY],q0.ConnectivityState.IDLE),T&&this.keepaliveTime>0)this.keepaliveTime*=2,y5.log(kq.LogVerbosity.ERROR,`Connection to ${(0,mP.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`)})}else Y.shutdown()},(Y)=>{this.transitionToState([q0.ConnectivityState.CONNECTING],q0.ConnectivityState.TRANSIENT_FAILURE,`${Y}`)})}transitionToState($,Y,T){var q,X;if($.indexOf(this.connectivityState)===-1)return!1;if(T)this.trace(q0.ConnectivityState[this.connectivityState]+" -> "+q0.ConnectivityState[Y]+' with error "'+T+'"');else this.trace(q0.ConnectivityState[this.connectivityState]+" -> "+q0.ConnectivityState[Y]);if(this.channelzEnabled)this.channelzTrace.addTrace("CT_INFO","Connectivity state change to "+q0.ConnectivityState[Y]);let J=this.connectivityState;switch(this.connectivityState=Y,Y){case q0.ConnectivityState.READY:this.stopBackoff();break;case q0.ConnectivityState.CONNECTING:this.startBackoff(),this.startConnectingInternal(),this.continueConnecting=!1;break;case q0.ConnectivityState.TRANSIENT_FAILURE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());if((q=this.transport)===null||q===void 0||q.shutdown(),this.transport=null,!this.backoffTimeout.isRunning())process.nextTick(()=>{this.handleBackoffTimer()});break;case q0.ConnectivityState.IDLE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());(X=this.transport)===null||X===void 0||X.shutdown(),this.transport=null;break;default:throw Error(`Invalid state: unknown ConnectivityState ${Y}`)}for(let Q of this.stateListeners)Q(this,J,Y,this.keepaliveTime,T);return!0}ref(){this.refTrace("refcount "+this.refcount+" -> "+(this.refcount+1)),this.refcount+=1}unref(){if(this.refTrace("refcount "+this.refcount+" -> "+(this.refcount-1)),this.refcount-=1,this.refcount===0)this.channelzTrace.addTrace("CT_INFO","Shutting down"),(0,n1.unregisterChannelzRef)(this.channelzRef),this.secureConnector.destroy(),process.nextTick(()=>{this.transitionToState([q0.ConnectivityState.CONNECTING,q0.ConnectivityState.READY],q0.ConnectivityState.IDLE)})}unrefIfOneRef(){if(this.refcount===1)return this.unref(),!0;return!1}createCall($,Y,T,q){if(!this.transport)throw Error("Cannot create call, subchannel not READY");let X;if(this.channelzEnabled)this.callTracker.addCallStarted(),this.streamTracker.addCallStarted(),X={onCallEnd:(J)=>{if(J.code===kq.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()}};else X={};return this.transport.createCall($,Y,T,q,X)}startConnecting(){process.nextTick(()=>{if(!this.transitionToState([q0.ConnectivityState.IDLE],q0.ConnectivityState.CONNECTING)){if(this.connectivityState===q0.ConnectivityState.TRANSIENT_FAILURE)this.continueConnecting=!0}})}getConnectivityState(){return this.connectivityState}addConnectivityStateListener($){this.stateListeners.add($)}removeConnectivityStateListener($){this.stateListeners.delete($)}resetBackoff(){process.nextTick(()=>{this.backoffTimeout.reset(),this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.CONNECTING)})}getAddress(){return this.subchannelAddressString}getChannelzRef(){return this.channelzRef}isHealthy(){return!0}addHealthStateWatcher($){}removeHealthStateWatcher($){}getRealSubchannel(){return this}realSubchannelEquals($){return $.getRealSubchannel()===this}throttleKeepalive($){if($>this.keepaliveTime)this.keepaliveTime=$}getCallCredentials(){return this.secureConnector.getCallCredentials()}getChannel(){if(!this.subchannelChannel)this.subchannelChannel=new bP.SingleSubchannelChannel(this,this.channelTarget,this.options);return this.subchannelChannel}addDataWatcher($){throw Error("Not implemented")}getOrCreateDataProducer($,Y){let T=this.dataProducers.get($);if(T)return T;let q=Y(this);return this.dataProducers.set($,q),q}removeDataProducer($){this.dataProducers.delete($)}}VG.Subchannel=EG});var zG=M((NG)=>{var j5;Object.defineProperty(NG,"__esModule",{value:!0});NG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=void 0;NG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=((j5=process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)!==null&&j5!==void 0?j5:"false")==="true"});var k5=M((OG)=>{Object.defineProperty(OG,"__esModule",{value:!0});OG.DEFAULT_PORT=void 0;OG.setup=oP;var IG=B1(),v5=s("dns"),cP=YX(),x5=i(),dY=l$(),pP=P0(),lP=U0(),nP=i(),j$=p0(),MG=s("net"),iP=LY(),BG=zG(),rP="dns_resolver";function i1($){lP.trace(nP.LogVerbosity.DEBUG,rP,$)}OG.DEFAULT_PORT=443;var aP=30000;class RG{constructor($,Y,T){var q,X,J;if(this.target=$,this.listener=Y,this.pendingLookupPromise=null,this.pendingTxtPromise=null,this.latestLookupResult=null,this.latestServiceConfigResult=null,this.continueResolving=!1,this.isNextResolutionTimerRunning=!1,this.isServiceConfigEnabled=!0,this.returnedIpResult=!1,this.alternativeResolver=new v5.promises.Resolver,i1("Resolver constructed for target "+(0,j$.uriToString)($)),$.authority)this.alternativeResolver.setServers([$.authority]);let Q=(0,j$.splitHostPort)($.path);if(Q===null)this.ipResult=null,this.dnsHostname=null,this.port=null;else if((0,MG.isIPv4)(Q.host)||(0,MG.isIPv6)(Q.host))this.ipResult=[{addresses:[{host:Q.host,port:(q=Q.port)!==null&&q!==void 0?q:OG.DEFAULT_PORT}]}],this.dnsHostname=null,this.port=null;else this.ipResult=null,this.dnsHostname=Q.host,this.port=(X=Q.port)!==null&&X!==void 0?X:OG.DEFAULT_PORT;if(this.percentage=Math.random()*100,T["grpc.service_config_disable_resolution"]===1)this.isServiceConfigEnabled=!1;this.defaultResolutionError={code:x5.Status.UNAVAILABLE,details:`Name resolution failed for target ${(0,j$.uriToString)(this.target)}`,metadata:new pP.Metadata};let U={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};this.backoff=new iP.BackoffTimeout(()=>{if(this.continueResolving)this.startResolutionWithBackoff()},U),this.backoff.unref(),this.minTimeBetweenResolutionsMs=(J=T["grpc.dns_min_time_between_resolutions_ms"])!==null&&J!==void 0?J:aP,this.nextResolutionTimer=setTimeout(()=>{},0),clearTimeout(this.nextResolutionTimer)}startResolution(){if(this.ipResult!==null){if(!this.returnedIpResult)i1("Returning IP address for target "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,dY.statusOrFromValue)(this.ipResult),{},null,"")}),this.returnedIpResult=!0;this.backoff.stop(),this.backoff.reset(),this.stopNextResolutionTimer();return}if(this.dnsHostname===null)i1("Failed to parse DNS address "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,dY.statusOrFromError)({code:x5.Status.UNAVAILABLE,details:`Failed to parse DNS address ${(0,j$.uriToString)(this.target)}`}),{},null,"")}),this.stopNextResolutionTimer();else{if(this.pendingLookupPromise!==null)return;i1("Looking up DNS hostname "+this.dnsHostname),this.latestLookupResult=null;let $=this.dnsHostname;if(this.pendingLookupPromise=this.lookup($),this.pendingLookupPromise.then((Y)=>{if(this.pendingLookupPromise===null)return;this.pendingLookupPromise=null,this.latestLookupResult=(0,dY.statusOrFromValue)(Y.map((X)=>({addresses:[X]})));let T="["+Y.map((X)=>X.host+":"+X.port).join(",")+"]";i1("Resolved addresses for target "+(0,j$.uriToString)(this.target)+": "+T);let q=this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"");this.handleHealthStatus(q)},(Y)=>{if(this.pendingLookupPromise===null)return;i1("Resolution error for target "+(0,j$.uriToString)(this.target)+": "+Y.message),this.pendingLookupPromise=null,this.stopNextResolutionTimer(),this.listener((0,dY.statusOrFromError)(this.defaultResolutionError),{},this.latestServiceConfigResult,"")}),this.isServiceConfigEnabled&&this.pendingTxtPromise===null)this.pendingTxtPromise=this.resolveTxt($),this.pendingTxtPromise.then((Y)=>{if(this.pendingTxtPromise===null)return;this.pendingTxtPromise=null;let T;try{if(T=(0,cP.extractAndSelectServiceConfig)(Y,this.percentage),T)this.latestServiceConfigResult=(0,dY.statusOrFromValue)(T);else this.latestServiceConfigResult=null}catch(q){this.latestServiceConfigResult=(0,dY.statusOrFromError)({code:x5.Status.UNAVAILABLE,details:`Parsing service config failed with error ${q.message}`})}if(this.latestLookupResult!==null)this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"")},(Y)=>{})}}handleHealthStatus($){if($)this.backoff.stop(),this.backoff.reset();else this.continueResolving=!0}async lookup($){if(BG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER){i1("Using alternative DNS resolver.");let T=await Promise.allSettled([this.alternativeResolver.resolve4($),this.alternativeResolver.resolve6($)]);if(T.every((q)=>q.status==="rejected"))throw Error(T[0].reason);return T.reduce((q,X)=>{return X.status==="fulfilled"?[...q,...X.value]:q},[]).map((q)=>({host:q,port:+this.port}))}return(await v5.promises.lookup($,{all:!0})).map((T)=>({host:T.address,port:+this.port}))}async resolveTxt($){if(BG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)return i1("Using alternative DNS resolver."),this.alternativeResolver.resolveTxt($);return v5.promises.resolveTxt($)}startNextResolutionTimer(){var $,Y;clearTimeout(this.nextResolutionTimer),this.nextResolutionTimer=setTimeout(()=>{if(this.stopNextResolutionTimer(),this.continueResolving)this.startResolutionWithBackoff()},this.minTimeBetweenResolutionsMs),(Y=($=this.nextResolutionTimer).unref)===null||Y===void 0||Y.call($),this.isNextResolutionTimerRunning=!0}stopNextResolutionTimer(){clearTimeout(this.nextResolutionTimer),this.isNextResolutionTimerRunning=!1}startResolutionWithBackoff(){if(this.pendingLookupPromise===null)this.continueResolving=!1,this.backoff.runOnce(),this.startNextResolutionTimer(),this.startResolution()}updateResolution(){if(this.pendingLookupPromise===null)if(this.isNextResolutionTimerRunning||this.backoff.isRunning()){if(this.isNextResolutionTimerRunning)i1('resolution update delayed by "min time between resolutions" rate limit');else i1("resolution update delayed by backoff timer until "+this.backoff.getEndTime().toISOString());this.continueResolving=!0}else this.startResolutionWithBackoff()}destroy(){this.continueResolving=!1,this.backoff.reset(),this.backoff.stop(),this.stopNextResolutionTimer(),this.pendingLookupPromise=null,this.pendingTxtPromise=null,this.latestLookupResult=null,this.latestServiceConfigResult=null,this.returnedIpResult=!1}static getDefaultAuthority($){return $.path}}function oP(){(0,IG.registerResolver)("dns",RG),(0,IG.registerDefaultScheme)("dns")}});var h5=M((CG)=>{Object.defineProperty(CG,"__esModule",{value:!0});CG.parseCIDR=wG;CG.mapProxyName=UL;CG.getProxiedConnection=ZL;var J6=U0(),cY=i(),LG=s("net"),tP=s("http"),eP=U0(),PG=r0(),Q6=p0(),$L=s("url"),YL=k5(),TL="proxy";function pY($){eP.trace(cY.LogVerbosity.DEBUG,TL,$)}function qL(){let $="",Y="";if(process.env.grpc_proxy)Y="grpc_proxy",$=process.env.grpc_proxy;else if(process.env.https_proxy)Y="https_proxy",$=process.env.https_proxy;else if(process.env.http_proxy)Y="http_proxy",$=process.env.http_proxy;else return{};let T;try{T=new $L.URL($)}catch(U){return(0,J6.log)(cY.LogVerbosity.ERROR,`cannot parse value of "${Y}" env var`),{}}if(T.protocol!=="http:")return(0,J6.log)(cY.LogVerbosity.ERROR,`"${T.protocol}" scheme not supported in proxy URI`),{};let q=null;if(T.username)if(T.password)(0,J6.log)(cY.LogVerbosity.INFO,"userinfo found in proxy URI"),q=decodeURIComponent(`${T.username}:${T.password}`);else q=T.username;let{hostname:X,port:J}=T;if(J==="")J="80";let Q={address:`${X}:${J}`};if(q)Q.creds=q;return pY("Proxy server "+Q.address+" set by environment variable "+Y),Q}function XL(){let $=process.env.no_grpc_proxy,Y="no_grpc_proxy";if(!$)$=process.env.no_proxy,Y="no_proxy";if($)return pY("No proxy server list set by environment variable "+Y),$.split(",");else return[]}function wG($){let Y=$.split("/");if(Y.length!==2)return null;let T=parseInt(Y[1],10);if(!(0,LG.isIPv4)(Y[0])||Number.isNaN(T)||T<0||T>32)return null;return{ip:SG(Y[0]),prefixLength:T}}function SG($){return $.split(".").reduce((Y,T)=>(Y<<8)+parseInt(T,10),0)}function JL($,Y){let T=$.ip,q=-1<<32-$.prefixLength;return(SG(Y)&q)===(T&q)}function QL($){for(let Y of XL()){let T=wG(Y);if((0,LG.isIPv4)($)&&T&&JL(T,$))return!0;else if($.endsWith(Y))return!0}return!1}function UL($,Y){var T;let q={target:$,extraOptions:{}};if(((T=Y["grpc.enable_http_proxy"])!==null&&T!==void 0?T:1)===0)return q;if($.scheme==="unix")return q;let X=qL();if(!X.address)return q;let J=(0,Q6.splitHostPort)($.path);if(!J)return q;let Q=J.host;if(QL(Q))return pY("Not using proxy for target in no_proxy list: "+(0,Q6.uriToString)($)),q;let U={"grpc.http_connect_target":(0,Q6.uriToString)($)};if(X.creds)U["grpc.http_connect_creds"]=X.creds;return{target:{scheme:"dns",path:X.address},extraOptions:U}}function ZL($,Y){var T;if(!("grpc.http_connect_target"in Y))return Promise.resolve(null);let q=Y["grpc.http_connect_target"],X=(0,Q6.parseUri)(q);if(X===null)return Promise.resolve(null);let J=(0,Q6.splitHostPort)(X.path);if(J===null)return Promise.resolve(null);let Q=`${J.host}:${(T=J.port)!==null&&T!==void 0?T:YL.DEFAULT_PORT}`,U={method:"CONNECT",path:Q},Z={Host:Q};if((0,PG.isTcpSubchannelAddress)($))U.host=$.host,U.port=$.port;else U.socketPath=$.path;if("grpc.http_connect_creds"in Y)Z["Proxy-Authorization"]="Basic "+Buffer.from(Y["grpc.http_connect_creds"]).toString("base64");U.headers=Z;let K=(0,PG.subchannelAddressToString)($);return pY("Using proxy "+K+" to connect to "+U.path),new Promise((A,W)=>{let E=tP.request(U);E.once("connect",(D,F,H)=>{if(E.removeAllListeners(),F.removeAllListeners(),D.statusCode===200){if(pY("Successfully connected to "+U.path+" through proxy "+K),H.length>0)F.unshift(H);pY("Successfully established a plaintext connection to "+U.path+" through proxy "+K),A(F)}else(0,J6.log)(cY.LogVerbosity.ERROR,"Failed to connect to "+U.path+" through proxy "+K+" with status "+D.statusCode),W()}),E.once("error",(D)=>{E.removeAllListeners(),(0,J6.log)(cY.LogVerbosity.ERROR,"Failed to connect to proxy "+K+" with error "+D.message),W()}),E.end()})}});var _5=M((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});jG.StreamDecoder=void 0;var r1;(function($){$[$.NO_DATA=0]="NO_DATA",$[$.READING_SIZE=1]="READING_SIZE",$[$.READING_MESSAGE=2]="READING_MESSAGE"})(r1||(r1={}));class yG{constructor($){this.maxReadMessageLength=$,this.readState=r1.NO_DATA,this.readCompressFlag=Buffer.alloc(1),this.readPartialSize=Buffer.alloc(4),this.readSizeRemaining=4,this.readMessageSize=0,this.readPartialMessage=[],this.readMessageRemaining=0}write($){let Y=0,T,q=[];while(Y<$.length)switch(this.readState){case r1.NO_DATA:this.readCompressFlag=$.slice(Y,Y+1),Y+=1,this.readState=r1.READING_SIZE,this.readPartialSize.fill(0),this.readSizeRemaining=4,this.readMessageSize=0,this.readMessageRemaining=0,this.readPartialMessage=[];break;case r1.READING_SIZE:if(T=Math.min($.length-Y,this.readSizeRemaining),$.copy(this.readPartialSize,4-this.readSizeRemaining,Y,Y+T),this.readSizeRemaining-=T,Y+=T,this.readSizeRemaining===0){if(this.readMessageSize=this.readPartialSize.readUInt32BE(0),this.maxReadMessageLength!==-1&&this.readMessageSize>this.maxReadMessageLength)throw Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`);if(this.readMessageRemaining=this.readMessageSize,this.readMessageRemaining>0)this.readState=r1.READING_MESSAGE;else{let X=Buffer.concat([this.readCompressFlag,this.readPartialSize],5);this.readState=r1.NO_DATA,q.push(X)}}break;case r1.READING_MESSAGE:if(T=Math.min($.length-Y,this.readMessageRemaining),this.readPartialMessage.push($.slice(Y,Y+T)),this.readMessageRemaining-=T,Y+=T,this.readMessageRemaining===0){let X=[this.readCompressFlag,this.readPartialSize].concat(this.readPartialMessage),J=Buffer.concat(X,this.readMessageSize+5);this.readState=r1.NO_DATA,q.push(J)}break;default:throw Error("Unexpected read state")}return q}}jG.StreamDecoder=yG});var _G=M((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});kG.Http2SubchannelCall=void 0;var K$=s("http2"),GL=s("os"),X0=i(),A$=P0(),EL=_5(),VL=U0(),DL=i(),FL="subchannel_call";function NL($){for(let[Y,T]of Object.entries(GL.constants.errno))if(T===$)return Y;return"Unknown system error "+$}function g5($){let Y=`Received HTTP status code ${$}`,T;switch($){case 400:T=X0.Status.INTERNAL;break;case 401:T=X0.Status.UNAUTHENTICATED;break;case 403:T=X0.Status.PERMISSION_DENIED;break;case 404:T=X0.Status.UNIMPLEMENTED;break;case 429:case 502:case 503:case 504:T=X0.Status.UNAVAILABLE;break;default:T=X0.Status.UNKNOWN}return{code:T,details:Y,metadata:new A$.Metadata}}class xG{constructor($,Y,T,q,X){var J;this.http2Stream=$,this.callEventTracker=Y,this.listener=T,this.transport=q,this.callId=X,this.isReadFilterPending=!1,this.isPushPending=!1,this.canPush=!1,this.readsClosed=!1,this.statusOutput=!1,this.unpushedReadMessages=[],this.finalStatus=null,this.internalError=null,this.serverEndedCall=!1,this.connectionDropped=!1;let Q=(J=q.getOptions()["grpc.max_receive_message_length"])!==null&&J!==void 0?J:X0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;this.decoder=new EL.StreamDecoder(Q),$.on("response",(U,Z)=>{let K="";for(let A of Object.keys(U))K+="\t\t"+A+": "+U[A]+`
|
|
14
|
+
`)if(T===q)return null;if(++T,m)E(k,T-1,C),C=!0;++X,z=!0}else{if(k=T,m=!1,V(T-1)){m=!0;do{if(T=F(T),T===q)break;if(T++,!C)break}while(V(T))}else T=Math.min(q,F(T)+1);if(m)E(k,T,C),C=!0;X++,z=!0}else if((y=W(T))==="*"){k=T+1,m=Y||W(k)==="*";do{if(y===`
|
|
15
|
+
`)++X;if(++T===q)throw K("comment");_=y,y=W(T)}while(_!=="*"||y!=="/");if(++T,m)E(k,T-2,C),C=!0;z=!0}else return"/"}}while(z);var j=T;Z5.lastIndex=0;var M=Z5.test(W(j++));if(!M)while(j<q&&!Z5.test(W(j)))++j;var h0=$.substring(T,T=j);if(h0==='"'||h0==="'")Z=h0;return h0}function D(z){U.push(z)}function I(){if(!U.length){var z=H();if(z===null)return null;D(z)}return U[0]}function S(z,_){var y=I(),k=y===z;if(k)return H(),!0;if(!_)throw K("token '"+y+"', '"+z+"' expected");return!1}function v(z){var _=null,y;if(z===void 0){if(y=Q[X-1],delete Q[X-1],y&&(Y||y.type==="*"||y.lineEmpty))_=y.leading?y.text:null}else{if(J<z)I();if(y=Q[z],delete Q[z],y&&!y.lineEmpty&&(Y||y.type==="/"))_=y.leading?null:y.text}return _}return Object.defineProperty({next:H,peek:I,push:D,skip:S,cmnt:v},"line",{get:function(){return X}})}});var qW=B((sg,TW)=>{TW.exports=Q$;Q$.filename=null;Q$.defaults={keepCase:!1};var j2=K5(),tA=Hq(),eA=Vq(),$W=P$(),v2=Zq(),YW=o$(),x2=w1(),k2=Aq(),h2=Kq(),_2=L$(),g2=s$(),A5=w0(),m2=/^[1-9][0-9]*$/,f2=/^-?[1-9][0-9]*$/,b2=/^0[x][0-9a-fA-F]+$/,u2=/^-?0[x][0-9a-fA-F]+$/,d2=/^0[0-7]+$/,c2=/^-?0[0-7]+$/,p2=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,b1=/^[a-zA-Z_][a-zA-Z_0-9]*$/,u1=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function Q$($,Y,T){if(!(Y instanceof tA))T=Y,Y=new tA;if(!T)T=Q$.defaults;var q=T.preferTrailingComment||!1,X=j2($,T.alternateCommentMode||!1),J=X.next,Q=X.push,U=X.peek,Z=X.skip,K=X.cmnt,A=!0,W,E,V,F="proto2",H=Y,D=[],I={},S=T.keepCase?function(O){return O}:A5.camelCase;function v(){D.forEach((O)=>{O._edition=F,Object.keys(I).forEach((R)=>{if(O.getOption(R)!==void 0)return;O.setOption(R,I[R],!0)})})}function z(O,R,w){var h=Q$.filename;if(!w)Q$.filename=null;return Error("illegal "+(R||"token")+" '"+O+"' ("+(h?h+", ":"")+"line "+X.line+")")}function _(){var O=[],R;do{if((R=J())!=='"'&&R!=="'")throw z(R);O.push(J()),Z(R),R=U()}while(R==='"'||R==="'");return O.join("")}function y(O){var R=J();switch(R){case"'":case'"':return Q(R),_();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return m(R,!0)}catch(w){if(O&&u1.test(R))return R;throw z(R,"value")}}function k(O,R){var w,h;do if(R&&((w=U())==='"'||w==="'")){var x=_();if(O.push(x),F>=2023)throw z(x,"id")}else try{O.push([h=C(J()),Z("to",!0)?C(J()):h])}catch(A0){if(R&&u1.test(w)&&F>=2023)O.push(w);else throw A0}while(Z(",",!0));var f={options:void 0};f.setOption=function(A0,g0){if(this.options===void 0)this.options={};this.options[A0]=g0},L(f,function(g0){if(g0==="option")Y0(f,g0),Z(";");else throw z(g0)},function(){o1(f)})}function m(O,R){var w=1;if(O.charAt(0)==="-")w=-1,O=O.substring(1);switch(O){case"inf":case"INF":case"Inf":return w*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(m2.test(O))return w*parseInt(O,10);if(b2.test(O))return w*parseInt(O,16);if(d2.test(O))return w*parseInt(O,8);if(p2.test(O))return w*parseFloat(O);throw z(O,"number",R)}function C(O,R){switch(O){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!R&&O.charAt(0)==="-")throw z(O,"id");if(f2.test(O))return parseInt(O,10);if(u2.test(O))return parseInt(O,16);if(c2.test(O))return parseInt(O,8);throw z(O,"id")}function j(){if(W!==void 0)throw z("package");if(W=J(),!u1.test(W))throw z(W,"name");H=H.define(W),Z(";")}function M(){var O=U(),R;switch(O){case"weak":R=V||(V=[]),J();break;case"public":J();default:R=E||(E=[]);break}O=_(),Z(";"),R.push(O)}function h0(){if(Z("="),F=_(),F<2023)throw z(F,"syntax");Z(";")}function P(){if(Z("="),F=_(),!["2023"].includes(F))throw z(F,"edition");Z(";")}function G(O,R){switch(R){case"option":return Y0(O,R),Z(";"),!0;case"message":return l(O,R),!0;case"enum":return b0(O,R),!0;case"service":return qD(O,R),!0;case"extend":return JD(O,R),!0}return!1}function L(O,R,w){var h=X.line;if(O){if(typeof O.comment!=="string")O.comment=K();O.filename=Q$.filename}if(Z("{",!0)){var x;while((x=J())!=="}")R(x);Z(";",!0)}else{if(w)w();if(Z(";"),O&&(typeof O.comment!=="string"||q))O.comment=K(h)||O.comment}}function l(O,R){if(!b1.test(R=J()))throw z(R,"type name");var w=new eA(R);if(L(w,function(x){if(G(w,x))return;switch(x){case"map":V0(w,x);break;case"required":if(F!=="proto2")throw z(x);case"repeated":u(w,x);break;case"optional":if(F==="proto3")u(w,"proto3_optional");else if(F!=="proto2")throw z(x);else u(w,"optional");break;case"oneof":_0(w,x);break;case"extensions":k(w.extensions||(w.extensions=[]));break;case"reserved":k(w.reserved||(w.reserved=[]),!0);break;default:if(F==="proto2"||!u1.test(x))throw z(x);Q(x),u(w,"optional");break}}),O.add(w),O===H)D.push(w)}function u(O,R,w){var h=J();if(h==="group"){d(O,R);return}while(h.endsWith(".")||U().startsWith("."))h+=J();if(!u1.test(h))throw z(h,"type");var x=J();if(!b1.test(x))throw z(x,"name");x=S(x),Z("=");var f=new $W(x,C(J()),h,R,w);if(L(f,function(c0){if(c0==="option")Y0(f,c0),Z(";");else throw z(c0)},function(){o1(f)}),R==="proto3_optional"){var A0=new YW("_"+x);f.setOption("proto3_optional",!0),A0.add(f),O.add(A0)}else O.add(f);if(O===H)D.push(f)}function d(O,R){if(F>=2023)throw z("group");var w=J();if(!b1.test(w))throw z(w,"name");var h=A5.lcFirst(w);if(w===h)w=A5.ucFirst(w);Z("=");var x=C(J()),f=new eA(w);f.group=!0;var A0=new $W(h,x,w,R);A0.filename=Q$.filename,L(f,function(c0){switch(c0){case"option":Y0(f,c0),Z(";");break;case"required":case"repeated":u(f,c0);break;case"optional":if(F==="proto3")u(f,"proto3_optional");else u(f,"optional");break;case"message":l(f,c0);break;case"enum":b0(f,c0);break;case"reserved":k(f.reserved||(f.reserved=[]),!0);break;default:throw z(c0)}}),O.add(f).add(A0)}function V0(O){Z("<");var R=J();if(g2.mapKey[R]===void 0)throw z(R,"type");Z(",");var w=J();if(!u1.test(w))throw z(w,"type");Z(">");var h=J();if(!b1.test(h))throw z(h,"name");Z("=");var x=new v2(S(h),C(J()),R,w);L(x,function(A0){if(A0==="option")Y0(x,A0),Z(";");else throw z(A0)},function(){o1(x)}),O.add(x)}function _0(O,R){if(!b1.test(R=J()))throw z(R,"name");var w=new YW(S(R));L(w,function(x){if(x==="option")Y0(w,x),Z(";");else Q(x),u(w,"optional")}),O.add(w)}function b0(O,R){if(!b1.test(R=J()))throw z(R,"name");var w=new x2(R);if(L(w,function(x){switch(x){case"option":Y0(w,x),Z(";");break;case"reserved":if(k(w.reserved||(w.reserved=[]),!0),w.reserved===void 0)w.reserved=[];break;default:B0(w,x)}}),O.add(w),O===H)D.push(w)}function B0(O,R){if(!b1.test(R))throw z(R,"name");Z("=");var w=C(J(),!0),h={options:void 0};h.getOption=function(x){return this.options[x]},h.setOption=function(x,f){_2.prototype.setOption.call(h,x,f)},h.setParsedOption=function(){return},L(h,function(f){if(f==="option")Y0(h,f),Z(";");else throw z(f)},function(){o1(h)}),O.add(R,w,h.comment,h.parsedOptions||h.options)}function Y0(O,R){var w,h,x=!0;if(R==="option")R=J();while(R!=="="){if(R==="("){var f=J();Z(")"),R="("+f+")"}if(x){if(x=!1,R.includes(".")&&!R.includes("(")){var A0=R.split(".");w=A0[0]+".",R=A0[1];continue}w=R}else h=h?h+=R:R;R=J()}var g0=h?w.concat(h):w,c0=u0(O,g0);h=h&&h[0]==="."?h.slice(1):h,w=w&&w[w.length-1]==="."?w.slice(0,-1):w,d0(O,w,c0,h)}function u0(O,R){if(Z("{",!0)){var w={};while(!Z("}",!0)){if(!b1.test(j0=J()))throw z(j0,"name");if(j0===null)throw z(j0,"end of input");var h,x=j0;if(Z(":",!0),U()==="{")h=u0(O,R+"."+j0);else if(U()==="["){h=[];var f;if(Z("[",!0)){do f=y(!0),h.push(f);while(Z(",",!0));if(Z("]"),typeof f<"u")E0(O,R+"."+j0,f)}}else h=y(!0),E0(O,R+"."+j0,h);var A0=w[x];if(A0)h=[].concat(A0).concat(h);w[x]=h,Z(",",!0),Z(";",!0)}return w}var g0=y(!0);return E0(O,R,g0),g0}function E0(O,R,w){if(H===O&&/^features\./.test(R)){I[R]=w;return}if(O.setOption)O.setOption(R,w)}function d0(O,R,w,h){if(O.setParsedOption)O.setParsedOption(R,w,h)}function o1(O){if(Z("[",!0)){do Y0(O,"option");while(Z(",",!0));Z("]")}return O}function qD(O,R){if(!b1.test(R=J()))throw z(R,"service name");var w=new k2(R);if(L(w,function(x){if(G(w,x))return;if(x==="rpc")XD(w,x);else throw z(x)}),O.add(w),O===H)D.push(w)}function XD(O,R){var w=K(),h=R;if(!b1.test(R=J()))throw z(R,"name");var x=R,f,A0,g0,c0;if(Z("("),Z("stream",!0))A0=!0;if(!u1.test(R=J()))throw z(R);if(f=R,Z(")"),Z("returns"),Z("("),Z("stream",!0))c0=!0;if(!u1.test(R=J()))throw z(R);g0=R,Z(")");var wT=new h2(x,h,f,g0,A0,c0);wT.comment=w,L(wT,function(N9){if(N9==="option")Y0(wT,N9),Z(";");else throw z(N9)}),O.add(wT)}function JD(O,R){if(!u1.test(R=J()))throw z(R,"reference");var w=R;L(null,function(x){switch(x){case"required":case"repeated":u(O,x,w);break;case"optional":if(F==="proto3")u(O,"proto3_optional",w);else u(O,"optional",w);break;default:if(F==="proto2"||!u1.test(x))throw z(x);Q(x),u(O,"optional",w);break}})}var j0;while((j0=J())!==null)switch(j0){case"package":if(!A)throw z(j0);j();break;case"import":if(!A)throw z(j0);M();break;case"syntax":if(!A)throw z(j0);h0();break;case"edition":if(!A)throw z(j0);P();break;case"option":Y0(H,j0),Z(";",!0);break;default:if(G(H,j0)){A=!1;continue}throw z(j0)}return v(),Q$.filename=null,{package:W,imports:E,weakImports:V,root:Y}}});var QW=B((tg,JW)=>{JW.exports=C1;var l2=/\/|\./;function C1($,Y){if(!l2.test($))$="google/protobuf/"+$+".proto",Y={nested:{google:{nested:{protobuf:{nested:Y}}}}};C1[$]=Y}C1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var XW;C1("duration",{Duration:XW={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});C1("timestamp",{Timestamp:XW});C1("empty",{Empty:{fields:{}}});C1("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});C1("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});C1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});C1.get=function(Y){return C1[Y]||null}});var Rq=B((eg,UW)=>{var S$=UW.exports=rA();S$.build="full";S$.tokenize=K5();S$.parse=qW();S$.common=QW();S$.Root._configure(S$.Type,S$.parse,S$.common)});var W5=B(($m,n2)=>{n2.exports={nested:{google:{nested:{protobuf:{options:{go_package:"google.golang.org/protobuf/types/descriptorpb",java_package:"com.google.protobuf",java_outer_classname:"DescriptorProtos",csharp_namespace:"Google.Protobuf.Reflection",objc_class_prefix:"GPB",cc_enable_arenas:!0,optimize_for:"SPEED"},nested:{FileDescriptorSet:{edition:"proto2",fields:{file:{rule:"repeated",type:"FileDescriptorProto",id:1}},extensions:[[536000000,536000000]]},Edition:{edition:"proto2",values:{EDITION_UNKNOWN:0,EDITION_LEGACY:900,EDITION_PROTO2:998,EDITION_PROTO3:999,EDITION_2023:1000,EDITION_2024:1001,EDITION_1_TEST_ONLY:1,EDITION_2_TEST_ONLY:2,EDITION_99997_TEST_ONLY:99997,EDITION_99998_TEST_ONLY:99998,EDITION_99999_TEST_ONLY:99999,EDITION_MAX:2147483647}},FileDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},package:{type:"string",id:2},dependency:{rule:"repeated",type:"string",id:3},publicDependency:{rule:"repeated",type:"int32",id:10},weakDependency:{rule:"repeated",type:"int32",id:11},optionDependency:{rule:"repeated",type:"string",id:15},messageType:{rule:"repeated",type:"DescriptorProto",id:4},enumType:{rule:"repeated",type:"EnumDescriptorProto",id:5},service:{rule:"repeated",type:"ServiceDescriptorProto",id:6},extension:{rule:"repeated",type:"FieldDescriptorProto",id:7},options:{type:"FileOptions",id:8},sourceCodeInfo:{type:"SourceCodeInfo",id:9},syntax:{type:"string",id:12},edition:{type:"Edition",id:14}}},DescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},field:{rule:"repeated",type:"FieldDescriptorProto",id:2},extension:{rule:"repeated",type:"FieldDescriptorProto",id:6},nestedType:{rule:"repeated",type:"DescriptorProto",id:3},enumType:{rule:"repeated",type:"EnumDescriptorProto",id:4},extensionRange:{rule:"repeated",type:"ExtensionRange",id:5},oneofDecl:{rule:"repeated",type:"OneofDescriptorProto",id:8},options:{type:"MessageOptions",id:7},reservedRange:{rule:"repeated",type:"ReservedRange",id:9},reservedName:{rule:"repeated",type:"string",id:10},visibility:{type:"SymbolVisibility",id:11}},nested:{ExtensionRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2},options:{type:"ExtensionRangeOptions",id:3}}},ReservedRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2}}}}},ExtensionRangeOptions:{edition:"proto2",fields:{uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999},declaration:{rule:"repeated",type:"Declaration",id:2,options:{retention:"RETENTION_SOURCE"}},features:{type:"FeatureSet",id:50},verification:{type:"VerificationState",id:3,options:{default:"UNVERIFIED",retention:"RETENTION_SOURCE"}}},extensions:[[1000,536870911]],nested:{Declaration:{fields:{number:{type:"int32",id:1},fullName:{type:"string",id:2},type:{type:"string",id:3},reserved:{type:"bool",id:5},repeated:{type:"bool",id:6}},reserved:[[4,4]]},VerificationState:{values:{DECLARATION:0,UNVERIFIED:1}}}},FieldDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},number:{type:"int32",id:3},label:{type:"Label",id:4},type:{type:"Type",id:5},typeName:{type:"string",id:6},extendee:{type:"string",id:2},defaultValue:{type:"string",id:7},oneofIndex:{type:"int32",id:9},jsonName:{type:"string",id:10},options:{type:"FieldOptions",id:8},proto3Optional:{type:"bool",id:17}},nested:{Type:{values:{TYPE_DOUBLE:1,TYPE_FLOAT:2,TYPE_INT64:3,TYPE_UINT64:4,TYPE_INT32:5,TYPE_FIXED64:6,TYPE_FIXED32:7,TYPE_BOOL:8,TYPE_STRING:9,TYPE_GROUP:10,TYPE_MESSAGE:11,TYPE_BYTES:12,TYPE_UINT32:13,TYPE_ENUM:14,TYPE_SFIXED32:15,TYPE_SFIXED64:16,TYPE_SINT32:17,TYPE_SINT64:18}},Label:{values:{LABEL_OPTIONAL:1,LABEL_REPEATED:3,LABEL_REQUIRED:2}}}},OneofDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},options:{type:"OneofOptions",id:2}}},EnumDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},value:{rule:"repeated",type:"EnumValueDescriptorProto",id:2},options:{type:"EnumOptions",id:3},reservedRange:{rule:"repeated",type:"EnumReservedRange",id:4},reservedName:{rule:"repeated",type:"string",id:5},visibility:{type:"SymbolVisibility",id:6}},nested:{EnumReservedRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2}}}}},EnumValueDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},number:{type:"int32",id:2},options:{type:"EnumValueOptions",id:3}}},ServiceDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},method:{rule:"repeated",type:"MethodDescriptorProto",id:2},options:{type:"ServiceOptions",id:3}}},MethodDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},inputType:{type:"string",id:2},outputType:{type:"string",id:3},options:{type:"MethodOptions",id:4},clientStreaming:{type:"bool",id:5},serverStreaming:{type:"bool",id:6}}},FileOptions:{edition:"proto2",fields:{javaPackage:{type:"string",id:1},javaOuterClassname:{type:"string",id:8},javaMultipleFiles:{type:"bool",id:10},javaGenerateEqualsAndHash:{type:"bool",id:20,options:{deprecated:!0}},javaStringCheckUtf8:{type:"bool",id:27},optimizeFor:{type:"OptimizeMode",id:9,options:{default:"SPEED"}},goPackage:{type:"string",id:11},ccGenericServices:{type:"bool",id:16},javaGenericServices:{type:"bool",id:17},pyGenericServices:{type:"bool",id:18},deprecated:{type:"bool",id:23},ccEnableArenas:{type:"bool",id:31,options:{default:!0}},objcClassPrefix:{type:"string",id:36},csharpNamespace:{type:"string",id:37},swiftPrefix:{type:"string",id:39},phpClassPrefix:{type:"string",id:40},phpNamespace:{type:"string",id:41},phpMetadataNamespace:{type:"string",id:44},rubyPackage:{type:"string",id:45},features:{type:"FeatureSet",id:50},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[42,42],[38,38],"php_generic_services"],nested:{OptimizeMode:{values:{SPEED:1,CODE_SIZE:2,LITE_RUNTIME:3}}}},MessageOptions:{edition:"proto2",fields:{messageSetWireFormat:{type:"bool",id:1},noStandardDescriptorAccessor:{type:"bool",id:2},deprecated:{type:"bool",id:3},mapEntry:{type:"bool",id:7},deprecatedLegacyJsonFieldConflicts:{type:"bool",id:11,options:{deprecated:!0}},features:{type:"FeatureSet",id:12},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[4,4],[5,5],[6,6],[8,8],[9,9]]},FieldOptions:{edition:"proto2",fields:{ctype:{type:"CType",id:1,options:{default:"STRING"}},packed:{type:"bool",id:2},jstype:{type:"JSType",id:6,options:{default:"JS_NORMAL"}},lazy:{type:"bool",id:5},unverifiedLazy:{type:"bool",id:15},deprecated:{type:"bool",id:3},weak:{type:"bool",id:10,options:{deprecated:!0}},debugRedact:{type:"bool",id:16},retention:{type:"OptionRetention",id:17},targets:{rule:"repeated",type:"OptionTargetType",id:19},editionDefaults:{rule:"repeated",type:"EditionDefault",id:20},features:{type:"FeatureSet",id:21},featureSupport:{type:"FeatureSupport",id:22},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[4,4],[18,18]],nested:{CType:{values:{STRING:0,CORD:1,STRING_PIECE:2}},JSType:{values:{JS_NORMAL:0,JS_STRING:1,JS_NUMBER:2}},OptionRetention:{values:{RETENTION_UNKNOWN:0,RETENTION_RUNTIME:1,RETENTION_SOURCE:2}},OptionTargetType:{values:{TARGET_TYPE_UNKNOWN:0,TARGET_TYPE_FILE:1,TARGET_TYPE_EXTENSION_RANGE:2,TARGET_TYPE_MESSAGE:3,TARGET_TYPE_FIELD:4,TARGET_TYPE_ONEOF:5,TARGET_TYPE_ENUM:6,TARGET_TYPE_ENUM_ENTRY:7,TARGET_TYPE_SERVICE:8,TARGET_TYPE_METHOD:9}},EditionDefault:{fields:{edition:{type:"Edition",id:3},value:{type:"string",id:2}}},FeatureSupport:{fields:{editionIntroduced:{type:"Edition",id:1},editionDeprecated:{type:"Edition",id:2},deprecationWarning:{type:"string",id:3},editionRemoved:{type:"Edition",id:4}}}}},OneofOptions:{edition:"proto2",fields:{features:{type:"FeatureSet",id:1},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},EnumOptions:{edition:"proto2",fields:{allowAlias:{type:"bool",id:2},deprecated:{type:"bool",id:3},deprecatedLegacyJsonFieldConflicts:{type:"bool",id:6,options:{deprecated:!0}},features:{type:"FeatureSet",id:7},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[5,5]]},EnumValueOptions:{edition:"proto2",fields:{deprecated:{type:"bool",id:1},features:{type:"FeatureSet",id:2},debugRedact:{type:"bool",id:3},featureSupport:{type:"FieldOptions.FeatureSupport",id:4},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},ServiceOptions:{edition:"proto2",fields:{features:{type:"FeatureSet",id:34},deprecated:{type:"bool",id:33},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},MethodOptions:{edition:"proto2",fields:{deprecated:{type:"bool",id:33},idempotencyLevel:{type:"IdempotencyLevel",id:34,options:{default:"IDEMPOTENCY_UNKNOWN"}},features:{type:"FeatureSet",id:35},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],nested:{IdempotencyLevel:{values:{IDEMPOTENCY_UNKNOWN:0,NO_SIDE_EFFECTS:1,IDEMPOTENT:2}}}},UninterpretedOption:{edition:"proto2",fields:{name:{rule:"repeated",type:"NamePart",id:2},identifierValue:{type:"string",id:3},positiveIntValue:{type:"uint64",id:4},negativeIntValue:{type:"int64",id:5},doubleValue:{type:"double",id:6},stringValue:{type:"bytes",id:7},aggregateValue:{type:"string",id:8}},nested:{NamePart:{fields:{namePart:{rule:"required",type:"string",id:1},isExtension:{rule:"required",type:"bool",id:2}}}}},FeatureSet:{edition:"proto2",fields:{fieldPresence:{type:"FieldPresence",id:1,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},enumType:{type:"EnumType",id:2,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},repeatedFieldEncoding:{type:"RepeatedFieldEncoding",id:3,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},utf8Validation:{type:"Utf8Validation",id:4,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},messageEncoding:{type:"MessageEncoding",id:5,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_LEGACY","edition_defaults.value":"LENGTH_PREFIXED"}},jsonFormat:{type:"JsonFormat",id:6,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}},enforceNamingStyle:{type:"EnforceNamingStyle",id:7,options:{retention:"RETENTION_SOURCE",targets:"TARGET_TYPE_METHOD","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"STYLE2024"}},defaultSymbolVisibility:{type:"VisibilityFeature.DefaultSymbolVisibility",id:8,options:{retention:"RETENTION_SOURCE",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"EXPORT_TOP_LEVEL"}}},extensions:[[1000,9994],[9995,9999],[1e4,1e4]],reserved:[[999,999]],nested:{FieldPresence:{values:{FIELD_PRESENCE_UNKNOWN:0,EXPLICIT:1,IMPLICIT:2,LEGACY_REQUIRED:3}},EnumType:{values:{ENUM_TYPE_UNKNOWN:0,OPEN:1,CLOSED:2}},RepeatedFieldEncoding:{values:{REPEATED_FIELD_ENCODING_UNKNOWN:0,PACKED:1,EXPANDED:2}},Utf8Validation:{values:{UTF8_VALIDATION_UNKNOWN:0,VERIFY:2,NONE:3}},MessageEncoding:{values:{MESSAGE_ENCODING_UNKNOWN:0,LENGTH_PREFIXED:1,DELIMITED:2}},JsonFormat:{values:{JSON_FORMAT_UNKNOWN:0,ALLOW:1,LEGACY_BEST_EFFORT:2}},EnforceNamingStyle:{values:{ENFORCE_NAMING_STYLE_UNKNOWN:0,STYLE2024:1,STYLE_LEGACY:2}},VisibilityFeature:{fields:{},reserved:[[1,536870911]],nested:{DefaultSymbolVisibility:{values:{DEFAULT_SYMBOL_VISIBILITY_UNKNOWN:0,EXPORT_ALL:1,EXPORT_TOP_LEVEL:2,LOCAL_ALL:3,STRICT:4}}}}}},FeatureSetDefaults:{edition:"proto2",fields:{defaults:{rule:"repeated",type:"FeatureSetEditionDefault",id:1},minimumEdition:{type:"Edition",id:4},maximumEdition:{type:"Edition",id:5}},nested:{FeatureSetEditionDefault:{fields:{edition:{type:"Edition",id:3},overridableFeatures:{type:"FeatureSet",id:4},fixedFeatures:{type:"FeatureSet",id:5}},reserved:[[1,1],[2,2],"features"]}}},SourceCodeInfo:{edition:"proto2",fields:{location:{rule:"repeated",type:"Location",id:1}},extensions:[[536000000,536000000]],nested:{Location:{fields:{path:{rule:"repeated",type:"int32",id:1,options:{packed:!0}},span:{rule:"repeated",type:"int32",id:2,options:{packed:!0}},leadingComments:{type:"string",id:3},trailingComments:{type:"string",id:4},leadingDetachedComments:{rule:"repeated",type:"string",id:6}}}}},GeneratedCodeInfo:{edition:"proto2",fields:{annotation:{rule:"repeated",type:"Annotation",id:1}},nested:{Annotation:{fields:{path:{rule:"repeated",type:"int32",id:1,options:{packed:!0}},sourceFile:{type:"string",id:2},begin:{type:"int32",id:3},end:{type:"int32",id:4},semantic:{type:"Semantic",id:5}},nested:{Semantic:{values:{NONE:0,SET:1,ALIAS:2}}}}}},SymbolVisibility:{edition:"proto2",values:{VISIBILITY_UNSET:0,VISIBILITY_LOCAL:1,VISIBILITY_EXPORT:2}}}}}}}}});var VW=B((p,EW)=>{var X1=Rq();EW.exports=p=X1.descriptor=X1.Root.fromJSON(W5()).lookup(".google.protobuf");var{Namespace:ZW,Root:a6,Enum:U$,Type:d1,Field:C$,MapField:i2,OneOf:Oq,Service:o6,Method:Pq}=X1;a6.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.FileDescriptorSet.decode(Y);var T=new a6;if(Y.file){var q,X;for(var J=0,Q;J<Y.file.length;++J){if(X=T,(q=Y.file[J]).package&&q.package.length)X=T.define(q.package);var U=qO(q);if(q.name&&q.name.length)T.files.push(X.filename=q.name);if(q.messageType)for(Q=0;Q<q.messageType.length;++Q)X.add(d1.fromDescriptor(q.messageType[Q],U));if(q.enumType)for(Q=0;Q<q.enumType.length;++Q)X.add(U$.fromDescriptor(q.enumType[Q],U));if(q.extension)for(Q=0;Q<q.extension.length;++Q)X.add(C$.fromDescriptor(q.extension[Q],U));if(q.service)for(Q=0;Q<q.service.length;++Q)X.add(o6.fromDescriptor(q.service[Q],U));var Z=_Y(q.options,p.FileOptions);if(Z){var K=Object.keys(Z);for(Q=0;Q<K.length;++Q)X.setOption(K[Q],Z[K[Q]])}}}return T.resolveAll()};a6.prototype.toDescriptor=function(Y){var T=p.FileDescriptorSet.create();return KW(this,T.file,Y),T};function KW($,Y,T){var q=p.FileDescriptorProto.create({name:$.filename||($.fullName.substring(1).replace(/\./g,"_")||"root")+".proto"});if(XO(T,q),!($ instanceof a6))q.package=$.fullName.substring(1);for(var X=0,J;X<$.nestedArray.length;++X)if((J=$._nestedArray[X])instanceof d1)q.messageType.push(J.toDescriptor(T));else if(J instanceof U$)q.enumType.push(J.toDescriptor());else if(J instanceof C$)q.extension.push(J.toDescriptor(T));else if(J instanceof o6)q.service.push(J.toDescriptor());else if(J instanceof ZW)KW(J,Y,T);if(q.options=gY($.options,p.FileOptions),q.messageType.length+q.enumType.length+q.extension.length+q.service.length)Y.push(q)}var r2=0;d1.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);var X=new d1(Y.name.length?Y.name:"Type"+r2++,_Y(Y.options,p.MessageOptions)),J;if(!q)X._edition=T;if(Y.oneofDecl)for(J=0;J<Y.oneofDecl.length;++J)X.add(Oq.fromDescriptor(Y.oneofDecl[J]));if(Y.field)for(J=0;J<Y.field.length;++J){var Q=C$.fromDescriptor(Y.field[J],T,!0);if(X.add(Q),Y.field[J].hasOwnProperty("oneofIndex"))X.oneofsArray[Y.field[J].oneofIndex].add(Q)}if(Y.extension)for(J=0;J<Y.extension.length;++J)X.add(C$.fromDescriptor(Y.extension[J],T,!0));if(Y.nestedType){for(J=0;J<Y.nestedType.length;++J)if(X.add(d1.fromDescriptor(Y.nestedType[J],T,!0)),Y.nestedType[J].options&&Y.nestedType[J].options.mapEntry)X.setOption("map_entry",!0)}if(Y.enumType)for(J=0;J<Y.enumType.length;++J)X.add(U$.fromDescriptor(Y.enumType[J],T,!0));if(Y.extensionRange&&Y.extensionRange.length){X.extensions=[];for(J=0;J<Y.extensionRange.length;++J)X.extensions.push([Y.extensionRange[J].start,Y.extensionRange[J].end])}if(Y.reservedRange&&Y.reservedRange.length||Y.reservedName&&Y.reservedName.length){if(X.reserved=[],Y.reservedRange)for(J=0;J<Y.reservedRange.length;++J)X.reserved.push([Y.reservedRange[J].start,Y.reservedRange[J].end]);if(Y.reservedName)for(J=0;J<Y.reservedName.length;++J)X.reserved.push(Y.reservedName[J])}return X};d1.prototype.toDescriptor=function(Y){var T=p.DescriptorProto.create({name:this.name}),q;for(q=0;q<this.fieldsArray.length;++q){var X;if(T.field.push(X=this._fieldsArray[q].toDescriptor(Y)),this._fieldsArray[q]instanceof i2){var J=G5(this._fieldsArray[q].keyType,this._fieldsArray[q].resolvedKeyType,!1),Q=G5(this._fieldsArray[q].type,this._fieldsArray[q].resolvedType,!1),U=Q===11||Q===14?this._fieldsArray[q].resolvedType&&GW(this.parent,this._fieldsArray[q].resolvedType)||this._fieldsArray[q].type:void 0;T.nestedType.push(p.DescriptorProto.create({name:X.typeName,field:[p.FieldDescriptorProto.create({name:"key",number:1,label:1,type:J}),p.FieldDescriptorProto.create({name:"value",number:2,label:1,type:Q,typeName:U})],options:p.MessageOptions.create({mapEntry:!0})}))}}for(q=0;q<this.oneofsArray.length;++q)T.oneofDecl.push(this._oneofsArray[q].toDescriptor());for(q=0;q<this.nestedArray.length;++q)if(this._nestedArray[q]instanceof C$)T.field.push(this._nestedArray[q].toDescriptor(Y));else if(this._nestedArray[q]instanceof d1)T.nestedType.push(this._nestedArray[q].toDescriptor(Y));else if(this._nestedArray[q]instanceof U$)T.enumType.push(this._nestedArray[q].toDescriptor());if(this.extensions)for(q=0;q<this.extensions.length;++q)T.extensionRange.push(p.DescriptorProto.ExtensionRange.create({start:this.extensions[q][0],end:this.extensions[q][1]}));if(this.reserved)for(q=0;q<this.reserved.length;++q)if(typeof this.reserved[q]==="string")T.reservedName.push(this.reserved[q]);else T.reservedRange.push(p.DescriptorProto.ReservedRange.create({start:this.reserved[q][0],end:this.reserved[q][1]}));return T.options=gY(this.options,p.MessageOptions),T};var a2=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;C$.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);if(typeof Y.number!=="number")throw Error("missing field id");var X;if(Y.typeName&&Y.typeName.length)X=Y.typeName;else X=$O(Y.type);var J;switch(Y.label){case 1:J=void 0;break;case 2:J="required";break;case 3:J="repeated";break;default:throw Error("illegal label: "+Y.label)}var Q=Y.extendee;if(Y.extendee!==void 0)Q=Q.length?Q:void 0;var U=new C$(Y.name.length?Y.name:"field"+Y.number,Y.number,X,J,Q);if(!q)U._edition=T;if(U.options=_Y(Y.options,p.FieldOptions),Y.proto3_optional)U.options.proto3_optional=!0;if(Y.defaultValue&&Y.defaultValue.length){var Z=Y.defaultValue;switch(Z){case"true":case"TRUE":Z=!0;break;case"false":case"FALSE":Z=!1;break;default:var K=a2.exec(Z);if(K)Z=parseInt(Z);break}U.setOption("default",Z)}if(YO(Y.type)){if(T==="proto3"){if(Y.options&&!Y.options.packed)U.setOption("packed",!1)}else if((!T||T==="proto2")&&Y.options&&Y.options.packed)U.setOption("packed",!0)}return U};C$.prototype.toDescriptor=function(Y){var T=p.FieldDescriptorProto.create({name:this.name,number:this.id});if(this.map)T.type=11,T.typeName=X1.util.ucFirst(this.name),T.label=3;else{switch(T.type=G5(this.type,this.resolve().resolvedType,this.delimited)){case 10:case 11:case 14:T.typeName=this.resolvedType?GW(this.parent,this.resolvedType):this.type;break}if(this.rule==="repeated")T.label=3;else if(this.required&&Y==="proto2")T.label=2;else T.label=1}if(T.extendee=this.extensionField?this.extensionField.parent.fullName:this.extend,this.partOf){if((T.oneofIndex=this.parent.oneofsArray.indexOf(this.partOf))<0)throw Error("missing oneof")}if(this.options){if(T.options=gY(this.options,p.FieldOptions),this.options.default!=null)T.defaultValue=String(this.options.default);if(this.options.proto3_optional)T.proto3_optional=!0}if(Y==="proto3"){if(!this.packed)(T.options||(T.options=p.FieldOptions.create())).packed=!1}else if((!Y||Y==="proto2")&&this.packed)(T.options||(T.options=p.FieldOptions.create())).packed=!0;return T};var o2=0;U$.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.EnumDescriptorProto.decode(Y);var X={};if(Y.value)for(var J=0;J<Y.value.length;++J){var Q=Y.value[J].name,U=Y.value[J].number||0;X[Q&&Q.length?Q:"NAME"+U]=U}var Z=new U$(Y.name&&Y.name.length?Y.name:"Enum"+o2++,X,_Y(Y.options,p.EnumOptions));if(!q)Z._edition=T;return Z};U$.prototype.toDescriptor=function(){var Y=[];for(var T=0,q=Object.keys(this.values);T<q.length;++T)Y.push(p.EnumValueDescriptorProto.create({name:q[T],number:this.values[q[T]]}));return p.EnumDescriptorProto.create({name:this.name,value:Y,options:gY(this.options,p.EnumOptions)})};var s2=0;Oq.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.OneofDescriptorProto.decode(Y);return new Oq(Y.name&&Y.name.length?Y.name:"oneof"+s2++)};Oq.prototype.toDescriptor=function(){return p.OneofDescriptorProto.create({name:this.name})};var t2=0;o6.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.ServiceDescriptorProto.decode(Y);var X=new o6(Y.name&&Y.name.length?Y.name:"Service"+t2++,_Y(Y.options,p.ServiceOptions));if(!q)X._edition=T;if(Y.method)for(var J=0;J<Y.method.length;++J)X.add(Pq.fromDescriptor(Y.method[J]));return X};o6.prototype.toDescriptor=function(){var Y=[];for(var T=0;T<this.methodsArray.length;++T)Y.push(this._methodsArray[T].toDescriptor());return p.ServiceDescriptorProto.create({name:this.name,method:Y,options:gY(this.options,p.ServiceOptions)})};var e2=0;Pq.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.MethodDescriptorProto.decode(Y);return new Pq(Y.name&&Y.name.length?Y.name:"Method"+e2++,"rpc",Y.inputType,Y.outputType,Boolean(Y.clientStreaming),Boolean(Y.serverStreaming),_Y(Y.options,p.MethodOptions))};Pq.prototype.toDescriptor=function(){return p.MethodDescriptorProto.create({name:this.name,inputType:this.resolvedRequestType?this.resolvedRequestType.fullName:this.requestType,outputType:this.resolvedResponseType?this.resolvedResponseType.fullName:this.responseType,clientStreaming:this.requestStream,serverStreaming:this.responseStream,options:gY(this.options,p.MethodOptions)})};function $O($){switch($){case 1:return"double";case 2:return"float";case 3:return"int64";case 4:return"uint64";case 5:return"int32";case 6:return"fixed64";case 7:return"fixed32";case 8:return"bool";case 9:return"string";case 12:return"bytes";case 13:return"uint32";case 15:return"sfixed32";case 16:return"sfixed64";case 17:return"sint32";case 18:return"sint64"}throw Error("illegal type: "+$)}function YO($){switch($){case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 13:case 14:case 15:case 16:case 17:case 18:return!0}return!1}function G5($,Y,T){switch($){case"double":return 1;case"float":return 2;case"int64":return 3;case"uint64":return 4;case"int32":return 5;case"fixed64":return 6;case"fixed32":return 7;case"bool":return 8;case"string":return 9;case"bytes":return 12;case"uint32":return 13;case"sfixed32":return 15;case"sfixed64":return 16;case"sint32":return 17;case"sint64":return 18}if(Y instanceof U$)return 14;if(Y instanceof d1)return T?10:11;throw Error("illegal type: "+$)}function AW($,Y){var T={};for(var q=0,X,J;q<Y.fieldsArray.length;++q){if((J=(X=Y._fieldsArray[q]).name)==="uninterpretedOption")continue;if(!Object.prototype.hasOwnProperty.call($,J))continue;var Q=TO(J);if(X.resolvedType instanceof d1)T[Q]=AW($[J],X.resolvedType);else if(X.resolvedType instanceof U$)T[Q]=X.resolvedType.valuesById[$[J]];else T[Q]=$[J]}return T}function _Y($,Y){if(!$)return;return AW(Y.toObject($),Y)}function WW($,Y){var T={},q=Object.keys($);for(var X=0;X<q.length;++X){var J=q[X],Q=X1.util.camelCase(J);if(!Object.prototype.hasOwnProperty.call(Y.fields,Q))continue;var U=Y.fields[Q];if(U.resolvedType instanceof d1)T[Q]=WW($[J],U.resolvedType);else T[Q]=$[J];if(U.repeated&&!Array.isArray(T[Q]))T[Q]=[T[Q]]}return T}function gY($,Y){if(!$)return;return Y.fromObject(WW($,Y))}function GW($,Y){var T=$.fullName.split("."),q=Y.fullName.split("."),X=0,J=0,Q=q.length-1;if(!($ instanceof a6)&&Y instanceof ZW)while(X<T.length&&J<Q&&T[X]===q[J]){var U=Y.lookup(T[X++],!0);if(U!==null&&U!==Y)break;++J}else for(;X<T.length&&J<Q&&T[X]===q[J];++X,++J);return q.slice(J).join(".")}function TO($){return $.substring(0,1)+$.substring(1).replace(/([A-Z])(?=[a-z]|$)/g,function(Y,T){return"_"+T.toLowerCase()})}function qO($){if($.syntax==="editions")switch($.edition){case p.Edition.EDITION_2023:return"2023";default:throw Error("Unsupported edition "+$.edition)}if($.syntax==="proto3")return"proto3";return"proto2"}function XO($,Y){if(!$)return;if($==="proto2"||$==="proto3")Y.syntax=$;else switch(Y.syntax="editions",$){case"2023":Y.edition=p.Edition.EDITION_2023;break;default:throw Error("Unsupported edition "+$)}}});var DW=B((Ym,JO)=>{JO.exports={nested:{google:{nested:{protobuf:{nested:{Api:{fields:{name:{type:"string",id:1},methods:{rule:"repeated",type:"Method",id:2},options:{rule:"repeated",type:"Option",id:3},version:{type:"string",id:4},sourceContext:{type:"SourceContext",id:5},mixins:{rule:"repeated",type:"Mixin",id:6},syntax:{type:"Syntax",id:7}}},Method:{fields:{name:{type:"string",id:1},requestTypeUrl:{type:"string",id:2},requestStreaming:{type:"bool",id:3},responseTypeUrl:{type:"string",id:4},responseStreaming:{type:"bool",id:5},options:{rule:"repeated",type:"Option",id:6},syntax:{type:"Syntax",id:7}}},Mixin:{fields:{name:{type:"string",id:1},root:{type:"string",id:2}}},SourceContext:{fields:{fileName:{type:"string",id:1}}},Option:{fields:{name:{type:"string",id:1},value:{type:"Any",id:2}}},Syntax:{values:{SYNTAX_PROTO2:0,SYNTAX_PROTO3:1}}}}}}}}});var FW=B((Tm,QO)=>{QO.exports={nested:{google:{nested:{protobuf:{nested:{SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var NW=B((qm,UO)=>{UO.exports={nested:{google:{nested:{protobuf:{nested:{Type:{fields:{name:{type:"string",id:1},fields:{rule:"repeated",type:"Field",id:2},oneofs:{rule:"repeated",type:"string",id:3},options:{rule:"repeated",type:"Option",id:4},sourceContext:{type:"SourceContext",id:5},syntax:{type:"Syntax",id:6}}},Field:{fields:{kind:{type:"Kind",id:1},cardinality:{type:"Cardinality",id:2},number:{type:"int32",id:3},name:{type:"string",id:4},typeUrl:{type:"string",id:6},oneofIndex:{type:"int32",id:7},packed:{type:"bool",id:8},options:{rule:"repeated",type:"Option",id:9},jsonName:{type:"string",id:10},defaultValue:{type:"string",id:11}},nested:{Kind:{values:{TYPE_UNKNOWN:0,TYPE_DOUBLE:1,TYPE_FLOAT:2,TYPE_INT64:3,TYPE_UINT64:4,TYPE_INT32:5,TYPE_FIXED64:6,TYPE_FIXED32:7,TYPE_BOOL:8,TYPE_STRING:9,TYPE_GROUP:10,TYPE_MESSAGE:11,TYPE_BYTES:12,TYPE_UINT32:13,TYPE_ENUM:14,TYPE_SFIXED32:15,TYPE_SFIXED64:16,TYPE_SINT32:17,TYPE_SINT64:18}},Cardinality:{values:{CARDINALITY_UNKNOWN:0,CARDINALITY_OPTIONAL:1,CARDINALITY_REQUIRED:2,CARDINALITY_REPEATED:3}}}},Enum:{fields:{name:{type:"string",id:1},enumvalue:{rule:"repeated",type:"EnumValue",id:2},options:{rule:"repeated",type:"Option",id:3},sourceContext:{type:"SourceContext",id:4},syntax:{type:"Syntax",id:5}}},EnumValue:{fields:{name:{type:"string",id:1},number:{type:"int32",id:2},options:{rule:"repeated",type:"Option",id:3}}},Option:{fields:{name:{type:"string",id:1},value:{type:"Any",id:2}}},Syntax:{values:{SYNTAX_PROTO2:0,SYNTAX_PROTO3:1}},Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}},SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var RW=B((MW)=>{Object.defineProperty(MW,"__esModule",{value:!0});MW.addCommonProtos=MW.loadProtosWithOptionsSync=MW.loadProtosWithOptions=void 0;var HW=s("fs"),zW=s("path"),mY=Rq();function IW($,Y){let T=$.resolvePath;$.resolvePath=(q,X)=>{if(zW.isAbsolute(X))return X;for(let J of Y){let Q=zW.join(J,X);try{return HW.accessSync(Q,HW.constants.R_OK),Q}catch(U){continue}}return process.emitWarning(`${X} not found in any of the include paths ${Y}`),T(q,X)}}async function ZO($,Y){let T=new mY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))return Promise.reject(Error("The includeDirs option must be an array"));IW(T,Y.includeDirs)}let q=await T.load($,Y);return q.resolveAll(),q}MW.loadProtosWithOptions=ZO;function KO($,Y){let T=new mY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))throw Error("The includeDirs option must be an array");IW(T,Y.includeDirs)}let q=T.loadSync($,Y);return q.resolveAll(),q}MW.loadProtosWithOptionsSync=KO;function AO(){let $=DW(),Y=W5(),T=FW(),q=NW();mY.common("api",$.nested.google.nested.protobuf.nested),mY.common("descriptor",Y.nested.google.nested.protobuf.nested),mY.common("source_context",T.nested.google.nested.protobuf.nested),mY.common("type",q.nested.google.nested.protobuf.nested)}MW.addCommonProtos=AO});var OW=B((s6,E5)=>{(function($,Y){function T(q){return q.default||q}if(typeof define==="function"&&define.amd)define([],function(){var q={};return Y(q),T(q)});else if(typeof s6==="object"){if(Y(s6),typeof E5==="object")E5.exports=T(s6)}else(function(){var q={};Y(q),$.Long=T(q)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:s6,function($){Object.defineProperty($,"__esModule",{value:!0}),$.default=void 0;var Y=null;try{Y=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function T(P,G,L){this.low=P|0,this.high=G|0,this.unsigned=!!L}T.prototype.__isLong__,Object.defineProperty(T.prototype,"__isLong__",{value:!0});function q(P){return(P&&P.__isLong__)===!0}function X(P){var G=Math.clz32(P&-P);return P?31-G:G}T.isLong=q;var J={},Q={};function U(P,G){var L,l,u;if(G){if(P>>>=0,u=0<=P&&P<256){if(l=Q[P],l)return l}if(L=K(P,0,!0),u)Q[P]=L;return L}else{if(P|=0,u=-128<=P&&P<128){if(l=J[P],l)return l}if(L=K(P,P<0?-1:0,!1),u)J[P]=L;return L}}T.fromInt=U;function Z(P,G){if(isNaN(P))return G?z:v;if(G){if(P<0)return z;if(P>=D)return C}else{if(P<=-I)return j;if(P+1>=I)return m}if(P<0)return Z(-P,G).neg();return K(P%H|0,P/H|0,G)}T.fromNumber=Z;function K(P,G,L){return new T(P,G,L)}T.fromBits=K;var A=Math.pow;function W(P,G,L){if(P.length===0)throw Error("empty string");if(typeof G==="number")L=G,G=!1;else G=!!G;if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return G?z:v;if(L=L||10,L<2||36<L)throw RangeError("radix");var l;if((l=P.indexOf("-"))>0)throw Error("interior hyphen");else if(l===0)return W(P.substring(1),G,L).neg();var u=Z(A(L,8)),d=v;for(var V0=0;V0<P.length;V0+=8){var _0=Math.min(8,P.length-V0),b0=parseInt(P.substring(V0,V0+_0),L);if(_0<8){var B0=Z(A(L,_0));d=d.mul(B0).add(Z(b0))}else d=d.mul(u),d=d.add(Z(b0))}return d.unsigned=G,d}T.fromString=W;function E(P,G){if(typeof P==="number")return Z(P,G);if(typeof P==="string")return W(P,G);return K(P.low,P.high,typeof G==="boolean"?G:P.unsigned)}T.fromValue=E;var V=65536,F=16777216,H=V*V,D=H*H,I=D/2,S=U(F),v=U(0);T.ZERO=v;var z=U(0,!0);T.UZERO=z;var _=U(1);T.ONE=_;var y=U(1,!0);T.UONE=y;var k=U(-1);T.NEG_ONE=k;var m=K(-1,2147483647,!1);T.MAX_VALUE=m;var C=K(-1,-1,!0);T.MAX_UNSIGNED_VALUE=C;var j=K(0,-2147483648,!1);T.MIN_VALUE=j;var M=T.prototype;if(M.toInt=function(){return this.unsigned?this.low>>>0:this.low},M.toNumber=function(){if(this.unsigned)return(this.high>>>0)*H+(this.low>>>0);return this.high*H+(this.low>>>0)},M.toString=function(G){if(G=G||10,G<2||36<G)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(j)){var L=Z(G),l=this.div(L),u=l.mul(L).sub(this);return l.toString(G)+u.toInt().toString(G)}else return"-"+this.neg().toString(G);var d=Z(A(G,6),this.unsigned),V0=this,_0="";while(!0){var b0=V0.div(d),B0=V0.sub(b0.mul(d)).toInt()>>>0,Y0=B0.toString(G);if(V0=b0,V0.isZero())return Y0+_0;else{while(Y0.length<6)Y0="0"+Y0;_0=""+Y0+_0}}},M.getHighBits=function(){return this.high},M.getHighBitsUnsigned=function(){return this.high>>>0},M.getLowBits=function(){return this.low},M.getLowBitsUnsigned=function(){return this.low>>>0},M.getNumBitsAbs=function(){if(this.isNegative())return this.eq(j)?64:this.neg().getNumBitsAbs();var G=this.high!=0?this.high:this.low;for(var L=31;L>0;L--)if((G&1<<L)!=0)break;return this.high!=0?L+33:L+1},M.isSafeInteger=function(){var G=this.high>>21;if(!G)return!0;if(this.unsigned)return!1;return G===-1&&!(this.low===0&&this.high===-2097152)},M.isZero=function(){return this.high===0&&this.low===0},M.eqz=M.isZero,M.isNegative=function(){return!this.unsigned&&this.high<0},M.isPositive=function(){return this.unsigned||this.high>=0},M.isOdd=function(){return(this.low&1)===1},M.isEven=function(){return(this.low&1)===0},M.equals=function(G){if(!q(G))G=E(G);if(this.unsigned!==G.unsigned&&this.high>>>31===1&&G.high>>>31===1)return!1;return this.high===G.high&&this.low===G.low},M.eq=M.equals,M.notEquals=function(G){return!this.eq(G)},M.neq=M.notEquals,M.ne=M.notEquals,M.lessThan=function(G){return this.comp(G)<0},M.lt=M.lessThan,M.lessThanOrEqual=function(G){return this.comp(G)<=0},M.lte=M.lessThanOrEqual,M.le=M.lessThanOrEqual,M.greaterThan=function(G){return this.comp(G)>0},M.gt=M.greaterThan,M.greaterThanOrEqual=function(G){return this.comp(G)>=0},M.gte=M.greaterThanOrEqual,M.ge=M.greaterThanOrEqual,M.compare=function(G){if(!q(G))G=E(G);if(this.eq(G))return 0;var L=this.isNegative(),l=G.isNegative();if(L&&!l)return-1;if(!L&&l)return 1;if(!this.unsigned)return this.sub(G).isNegative()?-1:1;return G.high>>>0>this.high>>>0||G.high===this.high&&G.low>>>0>this.low>>>0?-1:1},M.comp=M.compare,M.negate=function(){if(!this.unsigned&&this.eq(j))return j;return this.not().add(_)},M.neg=M.negate,M.add=function(G){if(!q(G))G=E(G);var L=this.high>>>16,l=this.high&65535,u=this.low>>>16,d=this.low&65535,V0=G.high>>>16,_0=G.high&65535,b0=G.low>>>16,B0=G.low&65535,Y0=0,u0=0,E0=0,d0=0;return d0+=d+B0,E0+=d0>>>16,d0&=65535,E0+=u+b0,u0+=E0>>>16,E0&=65535,u0+=l+_0,Y0+=u0>>>16,u0&=65535,Y0+=L+V0,Y0&=65535,K(E0<<16|d0,Y0<<16|u0,this.unsigned)},M.subtract=function(G){if(!q(G))G=E(G);return this.add(G.neg())},M.sub=M.subtract,M.multiply=function(G){if(this.isZero())return this;if(!q(G))G=E(G);if(Y){var L=Y.mul(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}if(G.isZero())return this.unsigned?z:v;if(this.eq(j))return G.isOdd()?j:v;if(G.eq(j))return this.isOdd()?j:v;if(this.isNegative())if(G.isNegative())return this.neg().mul(G.neg());else return this.neg().mul(G).neg();else if(G.isNegative())return this.mul(G.neg()).neg();if(this.lt(S)&&G.lt(S))return Z(this.toNumber()*G.toNumber(),this.unsigned);var l=this.high>>>16,u=this.high&65535,d=this.low>>>16,V0=this.low&65535,_0=G.high>>>16,b0=G.high&65535,B0=G.low>>>16,Y0=G.low&65535,u0=0,E0=0,d0=0,o1=0;return o1+=V0*Y0,d0+=o1>>>16,o1&=65535,d0+=d*Y0,E0+=d0>>>16,d0&=65535,d0+=V0*B0,E0+=d0>>>16,d0&=65535,E0+=u*Y0,u0+=E0>>>16,E0&=65535,E0+=d*B0,u0+=E0>>>16,E0&=65535,E0+=V0*b0,u0+=E0>>>16,E0&=65535,u0+=l*Y0+u*B0+d*b0+V0*_0,u0&=65535,K(d0<<16|o1,u0<<16|E0,this.unsigned)},M.mul=M.multiply,M.divide=function(G){if(!q(G))G=E(G);if(G.isZero())throw Error("division by zero");if(Y){if(!this.unsigned&&this.high===-2147483648&&G.low===-1&&G.high===-1)return this;var L=(this.unsigned?Y.div_u:Y.div_s)(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?z:v;var l,u,d;if(!this.unsigned){if(this.eq(j))if(G.eq(_)||G.eq(k))return j;else if(G.eq(j))return _;else{var V0=this.shr(1);if(l=V0.div(G).shl(1),l.eq(v))return G.isNegative()?_:k;else return u=this.sub(G.mul(l)),d=l.add(u.div(G)),d}else if(G.eq(j))return this.unsigned?z:v;if(this.isNegative()){if(G.isNegative())return this.neg().div(G.neg());return this.neg().div(G).neg()}else if(G.isNegative())return this.div(G.neg()).neg();d=v}else{if(!G.unsigned)G=G.toUnsigned();if(G.gt(this))return z;if(G.gt(this.shru(1)))return y;d=z}u=this;while(u.gte(G)){l=Math.max(1,Math.floor(u.toNumber()/G.toNumber()));var _0=Math.ceil(Math.log(l)/Math.LN2),b0=_0<=48?1:A(2,_0-48),B0=Z(l),Y0=B0.mul(G);while(Y0.isNegative()||Y0.gt(u))l-=b0,B0=Z(l,this.unsigned),Y0=B0.mul(G);if(B0.isZero())B0=_;d=d.add(B0),u=u.sub(Y0)}return d},M.div=M.divide,M.modulo=function(G){if(!q(G))G=E(G);if(Y){var L=(this.unsigned?Y.rem_u:Y.rem_s)(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}return this.sub(this.div(G).mul(G))},M.mod=M.modulo,M.rem=M.modulo,M.not=function(){return K(~this.low,~this.high,this.unsigned)},M.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},M.clz=M.countLeadingZeros,M.countTrailingZeros=function(){return this.low?X(this.low):X(this.high)+32},M.ctz=M.countTrailingZeros,M.and=function(G){if(!q(G))G=E(G);return K(this.low&G.low,this.high&G.high,this.unsigned)},M.or=function(G){if(!q(G))G=E(G);return K(this.low|G.low,this.high|G.high,this.unsigned)},M.xor=function(G){if(!q(G))G=E(G);return K(this.low^G.low,this.high^G.high,this.unsigned)},M.shiftLeft=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;else if(G<32)return K(this.low<<G,this.high<<G|this.low>>>32-G,this.unsigned);else return K(0,this.low<<G-32,this.unsigned)},M.shl=M.shiftLeft,M.shiftRight=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;else if(G<32)return K(this.low>>>G|this.high<<32-G,this.high>>G,this.unsigned);else return K(this.high>>G-32,this.high>=0?0:-1,this.unsigned)},M.shr=M.shiftRight,M.shiftRightUnsigned=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G<32)return K(this.low>>>G|this.high<<32-G,this.high>>>G,this.unsigned);if(G===32)return K(this.high,0,this.unsigned);return K(this.high>>>G-32,0,this.unsigned)},M.shru=M.shiftRightUnsigned,M.shr_u=M.shiftRightUnsigned,M.rotateLeft=function(G){var L;if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G===32)return K(this.high,this.low,this.unsigned);if(G<32)return L=32-G,K(this.low<<G|this.high>>>L,this.high<<G|this.low>>>L,this.unsigned);return G-=32,L=32-G,K(this.high<<G|this.low>>>L,this.low<<G|this.high>>>L,this.unsigned)},M.rotl=M.rotateLeft,M.rotateRight=function(G){var L;if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G===32)return K(this.high,this.low,this.unsigned);if(G<32)return L=32-G,K(this.high<<L|this.low>>>G,this.low<<L|this.high>>>G,this.unsigned);return G-=32,L=32-G,K(this.low<<L|this.high>>>G,this.high<<L|this.low>>>G,this.unsigned)},M.rotr=M.rotateRight,M.toSigned=function(){if(!this.unsigned)return this;return K(this.low,this.high,!1)},M.toUnsigned=function(){if(this.unsigned)return this;return K(this.low,this.high,!0)},M.toBytes=function(G){return G?this.toBytesLE():this.toBytesBE()},M.toBytesLE=function(){var G=this.high,L=this.low;return[L&255,L>>>8&255,L>>>16&255,L>>>24,G&255,G>>>8&255,G>>>16&255,G>>>24]},M.toBytesBE=function(){var G=this.high,L=this.low;return[G>>>24,G>>>16&255,G>>>8&255,G&255,L>>>24,L>>>16&255,L>>>8&255,L&255]},T.fromBytes=function(G,L,l){return l?T.fromBytesLE(G,L):T.fromBytesBE(G,L)},T.fromBytesLE=function(G,L){return new T(G[0]|G[1]<<8|G[2]<<16|G[3]<<24,G[4]|G[5]<<8|G[6]<<16|G[7]<<24,L)},T.fromBytesBE=function(G,L){return new T(G[4]<<24|G[5]<<16|G[6]<<8|G[7],G[0]<<24|G[1]<<16|G[2]<<8|G[3],L)},typeof BigInt==="function")T.fromBigInt=function(G,L){var l=Number(BigInt.asIntN(32,G)),u=Number(BigInt.asIntN(32,G>>BigInt(32)));return K(l,u,L)},T.fromValue=function(G,L){if(typeof G==="bigint")return T.fromBigInt(G,L);return E(G,L)},M.toBigInt=function(){var G=BigInt(this.low>>>0),L=BigInt(this.unsigned?this.high>>>0:this.high);return L<<BigInt(32)|G};var h0=$.default=T})});var t6=B((yW)=>{Object.defineProperty(yW,"__esModule",{value:!0});yW.loadFileDescriptorSetFromObject=yW.loadFileDescriptorSetFromBuffer=yW.fromJSON=yW.loadSync=yW.load=yW.IdempotencyLevel=yW.isAnyExtension=yW.Long=void 0;var EO=DK(),c1=Rq(),N5=VW(),H5=RW(),VO=OW();yW.Long=VO;function DO($){return"@type"in $&&typeof $["@type"]==="string"}yW.isAnyExtension=DO;var LW;(function($){$.IDEMPOTENCY_UNKNOWN="IDEMPOTENCY_UNKNOWN",$.NO_SIDE_EFFECTS="NO_SIDE_EFFECTS",$.IDEMPOTENT="IDEMPOTENT"})(LW=yW.IdempotencyLevel||(yW.IdempotencyLevel={}));var wW={longs:String,enums:String,bytes:String,defaults:!0,oneofs:!0,json:!0};function FO($,Y){if($==="")return Y;else return $+"."+Y}function NO($){return $ instanceof c1.Service||$ instanceof c1.Type||$ instanceof c1.Enum}function HO($){return $ instanceof c1.Namespace||$ instanceof c1.Root}function SW($,Y){let T=FO(Y,$.name);if(NO($))return[[T,$]];else if(HO($)&&typeof $.nested<"u")return Object.keys($.nested).map((q)=>{return SW($.nested[q],T)}).reduce((q,X)=>q.concat(X),[]);return[]}function V5($,Y){return function(q){return $.toObject($.decode(q),Y)}}function D5($){return function(T){if(Array.isArray(T))throw Error(`Failed to serialize message: expected object with ${$.name} structure, got array instead`);let q=$.fromObject(T);return $.encode(q).finish()}}function zO($){return($||[]).reduce((Y,T)=>{for(let[q,X]of Object.entries(T))switch(q){case"uninterpreted_option":Y.uninterpreted_option.push(T.uninterpreted_option);break;default:Y[q]=X}return Y},{deprecated:!1,idempotency_level:LW.IDEMPOTENCY_UNKNOWN,uninterpreted_option:[]})}function IO($,Y,T,q){let{resolvedRequestType:X,resolvedResponseType:J}=$;return{path:"/"+Y+"/"+$.name,requestStream:!!$.requestStream,responseStream:!!$.responseStream,requestSerialize:D5(X),requestDeserialize:V5(X,T),responseSerialize:D5(J),responseDeserialize:V5(J,T),originalName:EO($.name),requestType:F5(X,T,q),responseType:F5(J,T,q),options:zO($.parsedOptions)}}function MO($,Y,T,q){let X={};for(let J of $.methodsArray)X[J.name]=IO(J,Y,T,q);return X}function F5($,Y,T){let q=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 DescriptorProto",type:q.$type.toObject(q,wW),fileDescriptorProtos:T,serialize:D5($),deserialize:V5($,Y)}}function BO($,Y){let T=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 EnumDescriptorProto",type:T.$type.toObject(T,wW),fileDescriptorProtos:Y}}function RO($,Y,T,q){if($ instanceof c1.Service)return MO($,Y,T,q);else if($ instanceof c1.Type)return F5($,T,q);else if($ instanceof c1.Enum)return BO($,q);else throw Error("Type mismatch in reflection object handling")}function Lq($,Y){let T={};$.resolveAll();let X=$.toDescriptor("proto3").file.map((J)=>Buffer.from(N5.FileDescriptorProto.encode(J).finish()));for(let[J,Q]of SW($,""))T[J]=RO(Q,J,Y,X);return T}function CW($,Y){Y=Y||{};let T=c1.Root.fromDescriptor($);return T.resolveAll(),Lq(T,Y)}function OO($,Y){return(0,H5.loadProtosWithOptions)($,Y).then((T)=>{return Lq(T,Y)})}yW.load=OO;function PO($,Y){let T=(0,H5.loadProtosWithOptionsSync)($,Y);return Lq(T,Y)}yW.loadSync=PO;function LO($,Y){Y=Y||{};let T=c1.Root.fromJSON($);return T.resolveAll(),Lq(T,Y)}yW.fromJSON=LO;function wO($,Y){let T=N5.FileDescriptorSet.decode($);return CW(T,Y)}yW.loadFileDescriptorSetFromBuffer=wO;function SO($,Y){let T=N5.FileDescriptorSet.fromObject($);return CW(T,Y)}yW.loadFileDescriptorSetFromObject=SO;(0,H5.addCommonProtos)()});var y$=B((lW)=>{var __dirname="/Users/beatrix/dev/clinee/sdk-wip/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(lW,"__esModule",{value:!0});lW.registerChannelzSocket=lW.registerChannelzServer=lW.registerChannelzSubchannel=lW.registerChannelzChannel=lW.ChannelzCallTrackerStub=lW.ChannelzCallTracker=lW.ChannelzChildrenTrackerStub=lW.ChannelzChildrenTracker=lW.ChannelzTrace=lW.ChannelzTraceStub=void 0;lW.unregisterChannelzRef=fO;lW.getChannelzHandlers=cW;lW.getChannelzServiceDefinition=pW;lW.setup=oO;var Sq=s("net"),e$=NZ(),e6=l0(),$T=i(),hO=r0(),_O=r8(),gO=o8();function z5($){return{channel_id:$.id,name:$.name}}function I5($){return{subchannel_id:$.id,name:$.name}}function mO($){return{server_id:$.id}}function Cq($){return{socket_id:$.id,name:$.name}}var vW=32,M5=100;class _W{constructor(){this.events=[],this.creationTimestamp=new Date,this.eventsLogged=0}addTrace(){}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:[]}}}lW.ChannelzTraceStub=_W;class gW{constructor(){this.events=[],this.eventsLogged=0,this.creationTimestamp=new Date}addTrace($,Y,T){let q=new Date;if(this.events.push({description:Y,severity:$,timestamp:q,childChannel:(T===null||T===void 0?void 0:T.kind)==="channel"?T:void 0,childSubchannel:(T===null||T===void 0?void 0:T.kind)==="subchannel"?T:void 0}),this.events.length>=vW*2)this.events=this.events.slice(vW);this.eventsLogged+=1}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:this.events.map(($)=>{return{description:$.description,severity:$.severity,timestamp:p1($.timestamp),channel_ref:$.childChannel?z5($.childChannel):null,subchannel_ref:$.childSubchannel?I5($.childSubchannel):null}})}}}lW.ChannelzTrace=gW;class B5{constructor(){this.channelChildren=new e$.OrderedMap,this.subchannelChildren=new e$.OrderedMap,this.socketChildren=new e$.OrderedMap,this.trackerMap={["channel"]:this.channelChildren,["subchannel"]:this.subchannelChildren,["socket"]:this.socketChildren}}refChild($){let Y=this.trackerMap[$.kind],T=Y.find($.id);if(T.equals(Y.end()))Y.setElement($.id,{ref:$,count:1},T);else T.pointer[1].count+=1}unrefChild($){let Y=this.trackerMap[$.kind],T=Y.getElementByKey($.id);if(T!==void 0){if(T.count-=1,T.count===0)Y.eraseElementByKey($.id)}}getChildLists(){return{channels:this.channelChildren,subchannels:this.subchannelChildren,sockets:this.socketChildren}}}lW.ChannelzChildrenTracker=B5;class mW extends B5{refChild(){}unrefChild(){}}lW.ChannelzChildrenTrackerStub=mW;class R5{constructor(){this.callsStarted=0,this.callsSucceeded=0,this.callsFailed=0,this.lastCallStartedTimestamp=null}addCallStarted(){this.callsStarted+=1,this.lastCallStartedTimestamp=new Date}addCallSucceeded(){this.callsSucceeded+=1}addCallFailed(){this.callsFailed+=1}}lW.ChannelzCallTracker=R5;class fW extends R5{addCallStarted(){}addCallSucceeded(){}addCallFailed(){}}lW.ChannelzCallTrackerStub=fW;var Z$={["channel"]:new e$.OrderedMap,["subchannel"]:new e$.OrderedMap,["server"]:new e$.OrderedMap,["socket"]:new e$.OrderedMap},yq=($)=>{let Y=1;function T(){return Y++}let q=Z$[$];return(X,J,Q)=>{let U=T(),Z={id:U,name:X,kind:$};if(Q)q.setElement(U,{ref:Z,getInfo:J});return Z}};lW.registerChannelzChannel=yq("channel");lW.registerChannelzSubchannel=yq("subchannel");lW.registerChannelzServer=yq("server");lW.registerChannelzSocket=yq("socket");function fO($){Z$[$.kind].eraseElementByKey($.id)}function bO($){let Y=Number.parseInt($,16);return[Y/256|0,Y%256]}function xW($){if($==="")return[];let Y=$.split(":").map((q)=>bO(q));return[].concat(...Y)}function uO($){return(0,Sq.isIPv6)($)&&$.toLowerCase().startsWith("::ffff:")&&(0,Sq.isIPv4)($.substring(7))}function kW($){return Buffer.from(Uint8Array.from($.split(".").map((Y)=>Number.parseInt(Y))))}function dO($){if((0,Sq.isIPv4)($))return kW($);else if(uO($))return kW($.substring(7));else if((0,Sq.isIPv6)($)){let Y,T,q=$.indexOf("::");if(q===-1)Y=$,T="";else Y=$.substring(0,q),T=$.substring(q+2);let X=Buffer.from(xW(Y)),J=Buffer.from(xW(T)),Q=Buffer.alloc(16-X.length-J.length,0);return Buffer.concat([X,Q,J])}else return null}function bW($){switch($){case e6.ConnectivityState.CONNECTING:return{state:"CONNECTING"};case e6.ConnectivityState.IDLE:return{state:"IDLE"};case e6.ConnectivityState.READY:return{state:"READY"};case e6.ConnectivityState.SHUTDOWN:return{state:"SHUTDOWN"};case e6.ConnectivityState.TRANSIENT_FAILURE:return{state:"TRANSIENT_FAILURE"};default:return{state:"UNKNOWN"}}}function p1($){if(!$)return null;let Y=$.getTime();return{seconds:Y/1000|0,nanos:Y%1000*1e6}}function uW($){let Y=$.getInfo(),T=[],q=[];return Y.children.channels.forEach((X)=>{T.push(z5(X[1].ref))}),Y.children.subchannels.forEach((X)=>{q.push(I5(X[1].ref))}),{ref:z5($.ref),data:{target:Y.target,state:bW(Y.state),calls_started:Y.callTracker.callsStarted,calls_succeeded:Y.callTracker.callsSucceeded,calls_failed:Y.callTracker.callsFailed,last_call_started_timestamp:p1(Y.callTracker.lastCallStartedTimestamp),trace:Y.trace.getTraceMessage()},channel_ref:T,subchannel_ref:q}}function cO($,Y){let T=parseInt($.request.channel_id,10),q=Z$.channel.getElementByKey(T);if(q===void 0){Y({code:$T.Status.NOT_FOUND,details:"No channel data found for id "+T});return}Y(null,{channel:uW(q)})}function pO($,Y){let T=parseInt($.request.max_results,10)||M5,q=[],X=parseInt($.request.start_channel_id,10),J=Z$.channel,Q;for(Q=J.lowerBound(X);!Q.equals(J.end())&&q.length<T;Q=Q.next())q.push(uW(Q.pointer[1]));Y(null,{channel:q,end:Q.equals(J.end())})}function dW($){let Y=$.getInfo(),T=[];return Y.listenerChildren.sockets.forEach((q)=>{T.push(Cq(q[1].ref))}),{ref:mO($.ref),data:{calls_started:Y.callTracker.callsStarted,calls_succeeded:Y.callTracker.callsSucceeded,calls_failed:Y.callTracker.callsFailed,last_call_started_timestamp:p1(Y.callTracker.lastCallStartedTimestamp),trace:Y.trace.getTraceMessage()},listen_socket:T}}function lO($,Y){let T=parseInt($.request.server_id,10),X=Z$.server.getElementByKey(T);if(X===void 0){Y({code:$T.Status.NOT_FOUND,details:"No server data found for id "+T});return}Y(null,{server:dW(X)})}function nO($,Y){let T=parseInt($.request.max_results,10)||M5,q=parseInt($.request.start_server_id,10),X=Z$.server,J=[],Q;for(Q=X.lowerBound(q);!Q.equals(X.end())&&J.length<T;Q=Q.next())J.push(dW(Q.pointer[1]));Y(null,{server:J,end:Q.equals(X.end())})}function iO($,Y){let T=parseInt($.request.subchannel_id,10),q=Z$.subchannel.getElementByKey(T);if(q===void 0){Y({code:$T.Status.NOT_FOUND,details:"No subchannel data found for id "+T});return}let X=q.getInfo(),J=[];X.children.sockets.forEach((U)=>{J.push(Cq(U[1].ref))});let Q={ref:I5(q.ref),data:{target:X.target,state:bW(X.state),calls_started:X.callTracker.callsStarted,calls_succeeded:X.callTracker.callsSucceeded,calls_failed:X.callTracker.callsFailed,last_call_started_timestamp:p1(X.callTracker.lastCallStartedTimestamp),trace:X.trace.getTraceMessage()},socket_ref:J};Y(null,{subchannel:Q})}function hW($){var Y;if((0,hO.isTcpSubchannelAddress)($))return{address:"tcpip_address",tcpip_address:{ip_address:(Y=dO($.host))!==null&&Y!==void 0?Y:void 0,port:$.port}};else return{address:"uds_address",uds_address:{filename:$.path}}}function rO($,Y){var T,q,X,J,Q;let U=parseInt($.request.socket_id,10),Z=Z$.socket.getElementByKey(U);if(Z===void 0){Y({code:$T.Status.NOT_FOUND,details:"No socket data found for id "+U});return}let K=Z.getInfo(),A=K.security?{model:"tls",tls:{cipher_suite:K.security.cipherSuiteStandardName?"standard_name":"other_name",standard_name:(T=K.security.cipherSuiteStandardName)!==null&&T!==void 0?T:void 0,other_name:(q=K.security.cipherSuiteOtherName)!==null&&q!==void 0?q:void 0,local_certificate:(X=K.security.localCertificate)!==null&&X!==void 0?X:void 0,remote_certificate:(J=K.security.remoteCertificate)!==null&&J!==void 0?J:void 0}}:null,W={ref:Cq(Z.ref),local:K.localAddress?hW(K.localAddress):null,remote:K.remoteAddress?hW(K.remoteAddress):null,remote_name:(Q=K.remoteName)!==null&&Q!==void 0?Q:void 0,security:A,data:{keep_alives_sent:K.keepAlivesSent,streams_started:K.streamsStarted,streams_succeeded:K.streamsSucceeded,streams_failed:K.streamsFailed,last_local_stream_created_timestamp:p1(K.lastLocalStreamCreatedTimestamp),last_remote_stream_created_timestamp:p1(K.lastRemoteStreamCreatedTimestamp),messages_received:K.messagesReceived,messages_sent:K.messagesSent,last_message_received_timestamp:p1(K.lastMessageReceivedTimestamp),last_message_sent_timestamp:p1(K.lastMessageSentTimestamp),local_flow_control_window:K.localFlowControlWindow?{value:K.localFlowControlWindow}:null,remote_flow_control_window:K.remoteFlowControlWindow?{value:K.remoteFlowControlWindow}:null}};Y(null,{socket:W})}function aO($,Y){let T=parseInt($.request.server_id,10),q=Z$.server.getElementByKey(T);if(q===void 0){Y({code:$T.Status.NOT_FOUND,details:"No server data found for id "+T});return}let X=parseInt($.request.start_socket_id,10),J=parseInt($.request.max_results,10)||M5,U=q.getInfo().sessionChildren.sockets,Z=[],K;for(K=U.lowerBound(X);!K.equals(U.end())&&Z.length<J;K=K.next())Z.push(Cq(K.pointer[1].ref));Y(null,{socket_ref:Z,end:K.equals(U.end())})}function cW(){return{GetChannel:cO,GetTopChannels:pO,GetServer:lO,GetServers:nO,GetSubchannel:iO,GetSocket:rO,GetServerSockets:aO}}var wq=null;function pW(){if(wq)return wq;let $=t6().loadSync,Y=$("channelz.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto`]});return wq=(0,gO.loadPackageDefinition)(Y).grpc.channelz.v1.Channelz.service,wq}function oO(){(0,_O.registerAdminService)(pW,cW)}});var jq=B((iW)=>{Object.defineProperty(iW,"__esModule",{value:!0});iW.getNextCallNumber=WP;var AP=0;function WP(){return AP++}});var O5=B((aW)=>{Object.defineProperty(aW,"__esModule",{value:!0});aW.CompressionAlgorithms=void 0;var rW;(function($){$[$.identity=0]="identity",$[$.deflate=1]="deflate",$[$.gzip=2]="gzip"})(rW||(aW.CompressionAlgorithms=rW={}))});var P5=B((tW)=>{Object.defineProperty(tW,"__esModule",{value:!0});tW.BaseFilter=void 0;class sW{async sendMetadata($){return $}receiveMetadata($){return $}async sendMessage($){return $}async receiveMessage($){return $}receiveTrailers($){return $}}tW.BaseFilter=sW});var w5=B((QG)=>{Object.defineProperty(QG,"__esModule",{value:!0});QG.CompressionFilterFactory=QG.CompressionFilter=void 0;var vq=s("zlib"),YG=O5(),fY=i(),EP=P5(),VP=U0(),DP=($)=>{return typeof $==="number"&&typeof YG.CompressionAlgorithms[$]==="string"};class YT{async writeMessage($,Y){let T=$;if(Y)T=await this.compressMessage(T);let q=Buffer.allocUnsafe(T.length+5);return q.writeUInt8(Y?1:0,0),q.writeUInt32BE(T.length,1),T.copy(q,5),q}async readMessage($){let Y=$.readUInt8(0)===1,T=$.slice(5);if(Y)T=await this.decompressMessage(T);return T}}class bY extends YT{async compressMessage($){return $}async writeMessage($,Y){let T=Buffer.allocUnsafe($.length+5);return T.writeUInt8(0,0),T.writeUInt32BE($.length,1),$.copy(T,5),T}decompressMessage($){return Promise.reject(Error('Received compressed message but "grpc-encoding" header was identity'))}}class TG extends YT{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,T)=>{vq.deflate($,(q,X)=>{if(q)T(q);else Y(X)})})}decompressMessage($){return new Promise((Y,T)=>{let q=0,X=[],J=vq.createInflate();J.on("data",(Q)=>{if(X.push(Q),q+=Q.byteLength,this.maxRecvMessageLength!==-1&&q>this.maxRecvMessageLength)J.destroy(),T({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{Y(Buffer.concat(X))}),J.write($),J.end()})}}class qG extends YT{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,T)=>{vq.gzip($,(q,X)=>{if(q)T(q);else Y(X)})})}decompressMessage($){return new Promise((Y,T)=>{let q=0,X=[],J=vq.createGunzip();J.on("data",(Q)=>{if(X.push(Q),q+=Q.byteLength,this.maxRecvMessageLength!==-1&&q>this.maxRecvMessageLength)J.destroy(),T({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{Y(Buffer.concat(X))}),J.write($),J.end()})}}class XG extends YT{constructor($){super();this.compressionName=$}compressMessage($){return Promise.reject(Error(`Received message compressed with unsupported compression method ${this.compressionName}`))}decompressMessage($){return Promise.reject(Error(`Compression method not supported: ${this.compressionName}`))}}function $G($,Y){switch($){case"identity":return new bY;case"deflate":return new TG(Y);case"gzip":return new qG(Y);default:return new XG($)}}class L5 extends EP.BaseFilter{constructor($,Y){var T,q,X;super();this.sharedFilterConfig=Y,this.sendCompression=new bY,this.receiveCompression=new bY,this.currentCompressionAlgorithm="identity";let J=$["grpc.default_compression_algorithm"];if(this.maxReceiveMessageLength=(T=$["grpc.max_receive_message_length"])!==null&&T!==void 0?T:fY.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.maxSendMessageLength=(q=$["grpc.max_send_message_length"])!==null&&q!==void 0?q:fY.DEFAULT_MAX_SEND_MESSAGE_LENGTH,J!==void 0)if(DP(J)){let Q=YG.CompressionAlgorithms[J],U=(X=Y.serverSupportedEncodingHeader)===null||X===void 0?void 0:X.split(",");if(!U||U.includes(Q))this.currentCompressionAlgorithm=Q,this.sendCompression=$G(this.currentCompressionAlgorithm,-1)}else VP.log(fY.LogVerbosity.ERROR,`Invalid value provided for grpc.default_compression_algorithm option: ${J}`)}async sendMetadata($){let Y=await $;if(Y.set("grpc-accept-encoding","identity,deflate,gzip"),Y.set("accept-encoding","identity"),this.currentCompressionAlgorithm==="identity")Y.remove("grpc-encoding");else Y.set("grpc-encoding",this.currentCompressionAlgorithm);return Y}receiveMetadata($){let Y=$.get("grpc-encoding");if(Y.length>0){let q=Y[0];if(typeof q==="string")this.receiveCompression=$G(q,this.maxReceiveMessageLength)}$.remove("grpc-encoding");let T=$.get("grpc-accept-encoding")[0];if(T){if(this.sharedFilterConfig.serverSupportedEncodingHeader=T,!T.split(",").includes(this.currentCompressionAlgorithm))this.sendCompression=new bY,this.currentCompressionAlgorithm="identity"}return $.remove("grpc-accept-encoding"),$}async sendMessage($){var Y;let T=await $;if(this.maxSendMessageLength!==-1&&T.message.length>this.maxSendMessageLength)throw{code:fY.Status.RESOURCE_EXHAUSTED,details:`Attempted to send message with a size larger than ${this.maxSendMessageLength}`};let q;if(this.sendCompression instanceof bY)q=!1;else q=(((Y=T.flags)!==null&&Y!==void 0?Y:0)&2)===0;return{message:await this.sendCompression.writeMessage(T.message,q),flags:T.flags}}async receiveMessage($){return this.receiveCompression.readMessage(await $)}}QG.CompressionFilter=L5;class JG{constructor($,Y){this.options=Y,this.sharedFilterConfig={}}createFilter(){return new L5(this.options,this.sharedFilterConfig)}}QG.CompressionFilterFactory=JG});var TT=B((ZG)=>{Object.defineProperty(ZG,"__esModule",{value:!0});ZG.restrictControlPlaneStatusCode=HP;var l1=i(),NP=[l1.Status.OK,l1.Status.INVALID_ARGUMENT,l1.Status.NOT_FOUND,l1.Status.ALREADY_EXISTS,l1.Status.FAILED_PRECONDITION,l1.Status.ABORTED,l1.Status.OUT_OF_RANGE,l1.Status.DATA_LOSS];function HP($,Y){if(NP.includes($))return{code:l1.Status.INTERNAL,details:`Invalid status from control plane: ${$} ${l1.Status[$]} ${Y}`};else return{code:$,details:Y}}});var uY=B((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});KG.minDeadline=IP;KG.getDeadlineTimeoutString=BP;KG.getRelativeTimeout=OP;KG.deadlineToString=PP;KG.formatDateDifference=LP;function IP(...$){let Y=1/0;for(let T of $){let q=T instanceof Date?T.getTime():T;if(q<Y)Y=q}return Y}var MP=[["m",1],["S",1000],["M",60000],["H",3600000]];function BP($){let Y=new Date().getTime();if($ instanceof Date)$=$.getTime();let T=Math.max($-Y,0);for(let[q,X]of MP){let J=T/X;if(J<1e8)return String(Math.ceil(J))+q}throw Error("Deadline is too far in the future")}var RP=2147483647;function OP($){let Y=$ instanceof Date?$.getTime():$,T=new Date().getTime(),q=Y-T;if(q<0)return 0;else if(q>RP)return 1/0;else return q}function PP($){if($ instanceof Date)return $.toISOString();else{let Y=new Date($);if(Number.isNaN(Y.getTime()))return""+$;else return Y.toISOString()}}function LP($,Y){return((Y.getTime()-$.getTime())/1000).toFixed(3)+"s"}});var xq=B((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});AG.FilterStackFactory=AG.FilterStack=void 0;class S5{constructor($){this.filters=$}sendMetadata($){let Y=$;for(let T=0;T<this.filters.length;T++)Y=this.filters[T].sendMetadata(Y);return Y}receiveMetadata($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveMetadata(Y);return Y}sendMessage($){let Y=$;for(let T=0;T<this.filters.length;T++)Y=this.filters[T].sendMessage(Y);return Y}receiveMessage($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveMessage(Y);return Y}receiveTrailers($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveTrailers(Y);return Y}push($){this.filters.unshift(...$)}getFilters(){return this.filters}}AG.FilterStack=S5;class C5{constructor($){this.factories=$}push($){this.factories.unshift(...$)}clone(){return new C5([...this.factories])}createFilter(){return new S5(this.factories.map(($)=>$.createFilter()))}}AG.FilterStackFactory=C5});var FG=B((VG)=>{Object.defineProperty(VG,"__esModule",{value:!0});VG.SingleSubchannelChannel=void 0;var xP=jq(),qT=y$(),kP=w5(),hP=l0(),XT=i(),_P=TT(),gP=uY(),mP=xq(),y5=P0(),fP=B1(),kq=p0();class GG{constructor($,Y,T,q,X){var J,Q;this.subchannel=$,this.method=Y,this.options=q,this.callNumber=X,this.childCall=null,this.pendingMessage=null,this.readPending=!1,this.halfClosePending=!1,this.pendingStatus=null,this.readFilterPending=!1,this.writeFilterPending=!1;let U=this.method.split("/"),Z="";if(U.length>=2)Z=U[1];let K=(Q=(J=(0,kq.splitHostPort)(this.options.host))===null||J===void 0?void 0:J.host)!==null&&Q!==void 0?Q:"localhost";this.serviceUrl=`https://${K}/${Z}`;let A=(0,gP.getRelativeTimeout)(q.deadline);if(A!==1/0)if(A<=0)this.cancelWithStatus(XT.Status.DEADLINE_EXCEEDED,"Deadline exceeded");else setTimeout(()=>{this.cancelWithStatus(XT.Status.DEADLINE_EXCEEDED,"Deadline exceeded")},A);this.filterStack=T.createFilter()}cancelWithStatus($,Y){if(this.childCall)this.childCall.cancelWithStatus($,Y);else this.pendingStatus={code:$,details:Y,metadata:new y5.Metadata}}getPeer(){var $,Y;return(Y=($=this.childCall)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.subchannel.getAddress()}async start($,Y){if(this.pendingStatus){Y.onReceiveStatus(this.pendingStatus);return}if(this.subchannel.getConnectivityState()!==hP.ConnectivityState.READY){Y.onReceiveStatus({code:XT.Status.UNAVAILABLE,details:"Subchannel not ready",metadata:new y5.Metadata});return}let T=await this.filterStack.sendMetadata(Promise.resolve($)),q;try{q=await this.subchannel.getCallCredentials().generateMetadata({method_name:this.method,service_url:this.serviceUrl})}catch(J){let Q=J,{code:U,details:Z}=(0,_P.restrictControlPlaneStatusCode)(typeof Q.code==="number"?Q.code:XT.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Q.message}`);Y.onReceiveStatus({code:U,details:Z,metadata:new y5.Metadata});return}q.merge(T);let X={onReceiveMetadata:async(J)=>{Y.onReceiveMetadata(await this.filterStack.receiveMetadata(J))},onReceiveMessage:async(J)=>{this.readFilterPending=!0;let Q=await this.filterStack.receiveMessage(J);if(this.readFilterPending=!1,Y.onReceiveMessage(Q),this.pendingStatus)Y.onReceiveStatus(this.pendingStatus)},onReceiveStatus:async(J)=>{let Q=await this.filterStack.receiveTrailers(J);if(this.readFilterPending)this.pendingStatus=Q;else Y.onReceiveStatus(Q)}};if(this.childCall=this.subchannel.createCall(q,this.options.host,this.method,X),this.readPending)this.childCall.startRead();if(this.pendingMessage)this.childCall.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.halfClosePending&&!this.writeFilterPending)this.childCall.halfClose()}async sendMessageWithContext($,Y){this.writeFilterPending=!0;let T=await this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags}));if(this.writeFilterPending=!1,this.childCall){if(this.childCall.sendMessageWithContext($,T.message),this.halfClosePending)this.childCall.halfClose()}else this.pendingMessage={context:$,message:T.message}}startRead(){if(this.childCall)this.childCall.startRead();else this.readPending=!0}halfClose(){if(this.childCall&&!this.writeFilterPending)this.childCall.halfClose();else this.halfClosePending=!0}getCallNumber(){return this.callNumber}setCredentials($){throw Error("Method not implemented.")}getAuthContext(){if(this.childCall)return this.childCall.getAuthContext();else return null}}class EG{constructor($,Y,T){if(this.subchannel=$,this.target=Y,this.channelzEnabled=!1,this.channelzTrace=new qT.ChannelzTrace,this.callTracker=new qT.ChannelzCallTracker,this.childrenTracker=new qT.ChannelzChildrenTracker,this.channelzEnabled=T["grpc.enable_channelz"]!==0,this.channelzRef=(0,qT.registerChannelzChannel)((0,kq.uriToString)(Y),()=>({target:`${(0,kq.uriToString)(Y)} (${$.getAddress()})`,state:this.subchannel.getConnectivityState(),trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}),this.channelzEnabled),this.channelzEnabled)this.childrenTracker.refChild($.getChannelzRef());this.filterStackFactory=new mP.FilterStackFactory([new kP.CompressionFilterFactory(this,T)])}close(){if(this.channelzEnabled)this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());(0,qT.unregisterChannelzRef)(this.channelzRef)}getTarget(){return(0,kq.uriToString)(this.target)}getConnectivityState($){throw Error("Method not implemented.")}watchConnectivityState($,Y,T){throw Error("Method not implemented.")}getChannelzRef(){return this.channelzRef}createCall($,Y){let T={deadline:Y,host:(0,fP.getDefaultAuthority)(this.target),flags:XT.Propagate.DEFAULTS,parentCall:null};return new GG(this.subchannel,$,this.filterStackFactory,T,(0,xP.getNextCallNumber)())}}VG.SingleSubchannelChannel=EG});var IG=B((HG)=>{Object.defineProperty(HG,"__esModule",{value:!0});HG.Subchannel=void 0;var q0=l0(),bP=LY(),j5=U0(),hq=i(),uP=p0(),dP=r0(),n1=y$(),cP=FG(),pP="subchannel",lP=2147483647;class NG{constructor($,Y,T,q,X){var J;this.channelTarget=$,this.subchannelAddress=Y,this.options=T,this.connector=X,this.connectivityState=q0.ConnectivityState.IDLE,this.transport=null,this.continueConnecting=!1,this.stateListeners=new Set,this.refcount=0,this.channelzEnabled=!0,this.dataProducers=new Map,this.subchannelChannel=null;let Q={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};if(this.backoffTimeout=new bP.BackoffTimeout(()=>{this.handleBackoffTimer()},Q),this.backoffTimeout.unref(),this.subchannelAddressString=(0,dP.subchannelAddressToString)(Y),this.keepaliveTime=(J=T["grpc.keepalive_time_ms"])!==null&&J!==void 0?J:-1,T["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new n1.ChannelzTraceStub,this.callTracker=new n1.ChannelzCallTrackerStub,this.childrenTracker=new n1.ChannelzChildrenTrackerStub,this.streamTracker=new n1.ChannelzCallTrackerStub;else this.channelzTrace=new n1.ChannelzTrace,this.callTracker=new n1.ChannelzCallTracker,this.childrenTracker=new n1.ChannelzChildrenTracker,this.streamTracker=new n1.ChannelzCallTracker;this.channelzRef=(0,n1.registerChannelzSubchannel)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Subchannel created"),this.trace("Subchannel constructed with options "+JSON.stringify(T,void 0,2)),this.secureConnector=q._createSecureConnector($,T)}getChannelzInfo(){return{state:this.connectivityState,trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists(),target:this.subchannelAddressString}}trace($){j5.trace(hq.LogVerbosity.DEBUG,pP,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}refTrace($){j5.trace(hq.LogVerbosity.DEBUG,"subchannel_refcount","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}handleBackoffTimer(){if(this.continueConnecting)this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.CONNECTING);else this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.IDLE)}startBackoff(){this.backoffTimeout.runOnce()}stopBackoff(){this.backoffTimeout.stop(),this.backoffTimeout.reset()}startConnectingInternal(){let $=this.options;if($["grpc.keepalive_time_ms"]){let Y=Math.min(this.keepaliveTime,lP);$=Object.assign(Object.assign({},$),{"grpc.keepalive_time_ms":Y})}this.connector.connect(this.subchannelAddress,this.secureConnector,$).then((Y)=>{if(this.transitionToState([q0.ConnectivityState.CONNECTING],q0.ConnectivityState.READY)){if(this.transport=Y,this.channelzEnabled)this.childrenTracker.refChild(Y.getChannelzRef());Y.addDisconnectListener((T)=>{if(this.transitionToState([q0.ConnectivityState.READY],q0.ConnectivityState.IDLE),T&&this.keepaliveTime>0)this.keepaliveTime*=2,j5.log(hq.LogVerbosity.ERROR,`Connection to ${(0,uP.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`)})}else Y.shutdown()},(Y)=>{this.transitionToState([q0.ConnectivityState.CONNECTING],q0.ConnectivityState.TRANSIENT_FAILURE,`${Y}`)})}transitionToState($,Y,T){var q,X;if($.indexOf(this.connectivityState)===-1)return!1;if(T)this.trace(q0.ConnectivityState[this.connectivityState]+" -> "+q0.ConnectivityState[Y]+' with error "'+T+'"');else this.trace(q0.ConnectivityState[this.connectivityState]+" -> "+q0.ConnectivityState[Y]);if(this.channelzEnabled)this.channelzTrace.addTrace("CT_INFO","Connectivity state change to "+q0.ConnectivityState[Y]);let J=this.connectivityState;switch(this.connectivityState=Y,Y){case q0.ConnectivityState.READY:this.stopBackoff();break;case q0.ConnectivityState.CONNECTING:this.startBackoff(),this.startConnectingInternal(),this.continueConnecting=!1;break;case q0.ConnectivityState.TRANSIENT_FAILURE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());if((q=this.transport)===null||q===void 0||q.shutdown(),this.transport=null,!this.backoffTimeout.isRunning())process.nextTick(()=>{this.handleBackoffTimer()});break;case q0.ConnectivityState.IDLE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());(X=this.transport)===null||X===void 0||X.shutdown(),this.transport=null;break;default:throw Error(`Invalid state: unknown ConnectivityState ${Y}`)}for(let Q of this.stateListeners)Q(this,J,Y,this.keepaliveTime,T);return!0}ref(){this.refTrace("refcount "+this.refcount+" -> "+(this.refcount+1)),this.refcount+=1}unref(){if(this.refTrace("refcount "+this.refcount+" -> "+(this.refcount-1)),this.refcount-=1,this.refcount===0)this.channelzTrace.addTrace("CT_INFO","Shutting down"),(0,n1.unregisterChannelzRef)(this.channelzRef),this.secureConnector.destroy(),process.nextTick(()=>{this.transitionToState([q0.ConnectivityState.CONNECTING,q0.ConnectivityState.READY],q0.ConnectivityState.IDLE)})}unrefIfOneRef(){if(this.refcount===1)return this.unref(),!0;return!1}createCall($,Y,T,q){if(!this.transport)throw Error("Cannot create call, subchannel not READY");let X;if(this.channelzEnabled)this.callTracker.addCallStarted(),this.streamTracker.addCallStarted(),X={onCallEnd:(J)=>{if(J.code===hq.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()}};else X={};return this.transport.createCall($,Y,T,q,X)}startConnecting(){process.nextTick(()=>{if(!this.transitionToState([q0.ConnectivityState.IDLE],q0.ConnectivityState.CONNECTING)){if(this.connectivityState===q0.ConnectivityState.TRANSIENT_FAILURE)this.continueConnecting=!0}})}getConnectivityState(){return this.connectivityState}addConnectivityStateListener($){this.stateListeners.add($)}removeConnectivityStateListener($){this.stateListeners.delete($)}resetBackoff(){process.nextTick(()=>{this.backoffTimeout.reset(),this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.CONNECTING)})}getAddress(){return this.subchannelAddressString}getChannelzRef(){return this.channelzRef}isHealthy(){return!0}addHealthStateWatcher($){}removeHealthStateWatcher($){}getRealSubchannel(){return this}realSubchannelEquals($){return $.getRealSubchannel()===this}throttleKeepalive($){if($>this.keepaliveTime)this.keepaliveTime=$}getCallCredentials(){return this.secureConnector.getCallCredentials()}getChannel(){if(!this.subchannelChannel)this.subchannelChannel=new cP.SingleSubchannelChannel(this,this.channelTarget,this.options);return this.subchannelChannel}addDataWatcher($){throw Error("Not implemented")}getOrCreateDataProducer($,Y){let T=this.dataProducers.get($);if(T)return T;let q=Y(this);return this.dataProducers.set($,q),q}removeDataProducer($){this.dataProducers.delete($)}}HG.Subchannel=NG});var RG=B((MG)=>{var v5;Object.defineProperty(MG,"__esModule",{value:!0});MG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=void 0;MG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=((v5=process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)!==null&&v5!==void 0?v5:"false")==="true"});var h5=B((SG)=>{Object.defineProperty(SG,"__esModule",{value:!0});SG.DEFAULT_PORT=void 0;SG.setup=eP;var OG=B1(),x5=s("dns"),nP=TX(),k5=i(),dY=l$(),iP=P0(),rP=U0(),aP=i(),j$=p0(),PG=s("net"),oP=LY(),LG=RG(),sP="dns_resolver";function i1($){rP.trace(aP.LogVerbosity.DEBUG,sP,$)}SG.DEFAULT_PORT=443;var tP=30000;class wG{constructor($,Y,T){var q,X,J;if(this.target=$,this.listener=Y,this.pendingLookupPromise=null,this.pendingTxtPromise=null,this.latestLookupResult=null,this.latestServiceConfigResult=null,this.continueResolving=!1,this.isNextResolutionTimerRunning=!1,this.isServiceConfigEnabled=!0,this.returnedIpResult=!1,this.alternativeResolver=new x5.promises.Resolver,i1("Resolver constructed for target "+(0,j$.uriToString)($)),$.authority)this.alternativeResolver.setServers([$.authority]);let Q=(0,j$.splitHostPort)($.path);if(Q===null)this.ipResult=null,this.dnsHostname=null,this.port=null;else if((0,PG.isIPv4)(Q.host)||(0,PG.isIPv6)(Q.host))this.ipResult=[{addresses:[{host:Q.host,port:(q=Q.port)!==null&&q!==void 0?q:SG.DEFAULT_PORT}]}],this.dnsHostname=null,this.port=null;else this.ipResult=null,this.dnsHostname=Q.host,this.port=(X=Q.port)!==null&&X!==void 0?X:SG.DEFAULT_PORT;if(this.percentage=Math.random()*100,T["grpc.service_config_disable_resolution"]===1)this.isServiceConfigEnabled=!1;this.defaultResolutionError={code:k5.Status.UNAVAILABLE,details:`Name resolution failed for target ${(0,j$.uriToString)(this.target)}`,metadata:new iP.Metadata};let U={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};this.backoff=new oP.BackoffTimeout(()=>{if(this.continueResolving)this.startResolutionWithBackoff()},U),this.backoff.unref(),this.minTimeBetweenResolutionsMs=(J=T["grpc.dns_min_time_between_resolutions_ms"])!==null&&J!==void 0?J:tP,this.nextResolutionTimer=setTimeout(()=>{},0),clearTimeout(this.nextResolutionTimer)}startResolution(){if(this.ipResult!==null){if(!this.returnedIpResult)i1("Returning IP address for target "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,dY.statusOrFromValue)(this.ipResult),{},null,"")}),this.returnedIpResult=!0;this.backoff.stop(),this.backoff.reset(),this.stopNextResolutionTimer();return}if(this.dnsHostname===null)i1("Failed to parse DNS address "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,dY.statusOrFromError)({code:k5.Status.UNAVAILABLE,details:`Failed to parse DNS address ${(0,j$.uriToString)(this.target)}`}),{},null,"")}),this.stopNextResolutionTimer();else{if(this.pendingLookupPromise!==null)return;i1("Looking up DNS hostname "+this.dnsHostname),this.latestLookupResult=null;let $=this.dnsHostname;if(this.pendingLookupPromise=this.lookup($),this.pendingLookupPromise.then((Y)=>{if(this.pendingLookupPromise===null)return;this.pendingLookupPromise=null,this.latestLookupResult=(0,dY.statusOrFromValue)(Y.map((X)=>({addresses:[X]})));let T="["+Y.map((X)=>X.host+":"+X.port).join(",")+"]";i1("Resolved addresses for target "+(0,j$.uriToString)(this.target)+": "+T);let q=this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"");this.handleHealthStatus(q)},(Y)=>{if(this.pendingLookupPromise===null)return;i1("Resolution error for target "+(0,j$.uriToString)(this.target)+": "+Y.message),this.pendingLookupPromise=null,this.stopNextResolutionTimer(),this.listener((0,dY.statusOrFromError)(this.defaultResolutionError),{},this.latestServiceConfigResult,"")}),this.isServiceConfigEnabled&&this.pendingTxtPromise===null)this.pendingTxtPromise=this.resolveTxt($),this.pendingTxtPromise.then((Y)=>{if(this.pendingTxtPromise===null)return;this.pendingTxtPromise=null;let T;try{if(T=(0,nP.extractAndSelectServiceConfig)(Y,this.percentage),T)this.latestServiceConfigResult=(0,dY.statusOrFromValue)(T);else this.latestServiceConfigResult=null}catch(q){this.latestServiceConfigResult=(0,dY.statusOrFromError)({code:k5.Status.UNAVAILABLE,details:`Parsing service config failed with error ${q.message}`})}if(this.latestLookupResult!==null)this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"")},(Y)=>{})}}handleHealthStatus($){if($)this.backoff.stop(),this.backoff.reset();else this.continueResolving=!0}async lookup($){if(LG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER){i1("Using alternative DNS resolver.");let T=await Promise.allSettled([this.alternativeResolver.resolve4($),this.alternativeResolver.resolve6($)]);if(T.every((q)=>q.status==="rejected"))throw Error(T[0].reason);return T.reduce((q,X)=>{return X.status==="fulfilled"?[...q,...X.value]:q},[]).map((q)=>({host:q,port:+this.port}))}return(await x5.promises.lookup($,{all:!0})).map((T)=>({host:T.address,port:+this.port}))}async resolveTxt($){if(LG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)return i1("Using alternative DNS resolver."),this.alternativeResolver.resolveTxt($);return x5.promises.resolveTxt($)}startNextResolutionTimer(){var $,Y;clearTimeout(this.nextResolutionTimer),this.nextResolutionTimer=setTimeout(()=>{if(this.stopNextResolutionTimer(),this.continueResolving)this.startResolutionWithBackoff()},this.minTimeBetweenResolutionsMs),(Y=($=this.nextResolutionTimer).unref)===null||Y===void 0||Y.call($),this.isNextResolutionTimerRunning=!0}stopNextResolutionTimer(){clearTimeout(this.nextResolutionTimer),this.isNextResolutionTimerRunning=!1}startResolutionWithBackoff(){if(this.pendingLookupPromise===null)this.continueResolving=!1,this.backoff.runOnce(),this.startNextResolutionTimer(),this.startResolution()}updateResolution(){if(this.pendingLookupPromise===null)if(this.isNextResolutionTimerRunning||this.backoff.isRunning()){if(this.isNextResolutionTimerRunning)i1('resolution update delayed by "min time between resolutions" rate limit');else i1("resolution update delayed by backoff timer until "+this.backoff.getEndTime().toISOString());this.continueResolving=!0}else this.startResolutionWithBackoff()}destroy(){this.continueResolving=!1,this.backoff.reset(),this.backoff.stop(),this.stopNextResolutionTimer(),this.pendingLookupPromise=null,this.pendingTxtPromise=null,this.latestLookupResult=null,this.latestServiceConfigResult=null,this.returnedIpResult=!1}static getDefaultAuthority($){return $.path}}function eP(){(0,OG.registerResolver)("dns",wG),(0,OG.registerDefaultScheme)("dns")}});var _5=B((xG)=>{Object.defineProperty(xG,"__esModule",{value:!0});xG.parseCIDR=jG;xG.mapProxyName=AL;xG.getProxiedConnection=WL;var JT=U0(),cY=i(),yG=s("net"),YL=s("http"),TL=U0(),CG=r0(),QT=p0(),qL=s("url"),XL=h5(),JL="proxy";function pY($){TL.trace(cY.LogVerbosity.DEBUG,JL,$)}function QL(){let $="",Y="";if(process.env.grpc_proxy)Y="grpc_proxy",$=process.env.grpc_proxy;else if(process.env.https_proxy)Y="https_proxy",$=process.env.https_proxy;else if(process.env.http_proxy)Y="http_proxy",$=process.env.http_proxy;else return{};let T;try{T=new qL.URL($)}catch(U){return(0,JT.log)(cY.LogVerbosity.ERROR,`cannot parse value of "${Y}" env var`),{}}if(T.protocol!=="http:")return(0,JT.log)(cY.LogVerbosity.ERROR,`"${T.protocol}" scheme not supported in proxy URI`),{};let q=null;if(T.username)if(T.password)(0,JT.log)(cY.LogVerbosity.INFO,"userinfo found in proxy URI"),q=decodeURIComponent(`${T.username}:${T.password}`);else q=T.username;let{hostname:X,port:J}=T;if(J==="")J="80";let Q={address:`${X}:${J}`};if(q)Q.creds=q;return pY("Proxy server "+Q.address+" set by environment variable "+Y),Q}function UL(){let $=process.env.no_grpc_proxy,Y="no_grpc_proxy";if(!$)$=process.env.no_proxy,Y="no_proxy";if($)return pY("No proxy server list set by environment variable "+Y),$.split(",");else return[]}function jG($){let Y=$.split("/");if(Y.length!==2)return null;let T=parseInt(Y[1],10);if(!(0,yG.isIPv4)(Y[0])||Number.isNaN(T)||T<0||T>32)return null;return{ip:vG(Y[0]),prefixLength:T}}function vG($){return $.split(".").reduce((Y,T)=>(Y<<8)+parseInt(T,10),0)}function ZL($,Y){let T=$.ip,q=-1<<32-$.prefixLength;return(vG(Y)&q)===(T&q)}function KL($){for(let Y of UL()){let T=jG(Y);if((0,yG.isIPv4)($)&&T&&ZL(T,$))return!0;else if($.endsWith(Y))return!0}return!1}function AL($,Y){var T;let q={target:$,extraOptions:{}};if(((T=Y["grpc.enable_http_proxy"])!==null&&T!==void 0?T:1)===0)return q;if($.scheme==="unix")return q;let X=QL();if(!X.address)return q;let J=(0,QT.splitHostPort)($.path);if(!J)return q;let Q=J.host;if(KL(Q))return pY("Not using proxy for target in no_proxy list: "+(0,QT.uriToString)($)),q;let U={"grpc.http_connect_target":(0,QT.uriToString)($)};if(X.creds)U["grpc.http_connect_creds"]=X.creds;return{target:{scheme:"dns",path:X.address},extraOptions:U}}function WL($,Y){var T;if(!("grpc.http_connect_target"in Y))return Promise.resolve(null);let q=Y["grpc.http_connect_target"],X=(0,QT.parseUri)(q);if(X===null)return Promise.resolve(null);let J=(0,QT.splitHostPort)(X.path);if(J===null)return Promise.resolve(null);let Q=`${J.host}:${(T=J.port)!==null&&T!==void 0?T:XL.DEFAULT_PORT}`,U={method:"CONNECT",path:Q},Z={Host:Q};if((0,CG.isTcpSubchannelAddress)($))U.host=$.host,U.port=$.port;else U.socketPath=$.path;if("grpc.http_connect_creds"in Y)Z["Proxy-Authorization"]="Basic "+Buffer.from(Y["grpc.http_connect_creds"]).toString("base64");U.headers=Z;let K=(0,CG.subchannelAddressToString)($);return pY("Using proxy "+K+" to connect to "+U.path),new Promise((A,W)=>{let E=YL.request(U);E.once("connect",(V,F,H)=>{if(E.removeAllListeners(),F.removeAllListeners(),V.statusCode===200){if(pY("Successfully connected to "+U.path+" through proxy "+K),H.length>0)F.unshift(H);pY("Successfully established a plaintext connection to "+U.path+" through proxy "+K),A(F)}else(0,JT.log)(cY.LogVerbosity.ERROR,"Failed to connect to "+U.path+" through proxy "+K+" with status "+V.statusCode),W()}),E.once("error",(V)=>{E.removeAllListeners(),(0,JT.log)(cY.LogVerbosity.ERROR,"Failed to connect to proxy "+K+" with error "+V.message),W()}),E.end()})}});var g5=B((hG)=>{Object.defineProperty(hG,"__esModule",{value:!0});hG.StreamDecoder=void 0;var r1;(function($){$[$.NO_DATA=0]="NO_DATA",$[$.READING_SIZE=1]="READING_SIZE",$[$.READING_MESSAGE=2]="READING_MESSAGE"})(r1||(r1={}));class kG{constructor($){this.maxReadMessageLength=$,this.readState=r1.NO_DATA,this.readCompressFlag=Buffer.alloc(1),this.readPartialSize=Buffer.alloc(4),this.readSizeRemaining=4,this.readMessageSize=0,this.readPartialMessage=[],this.readMessageRemaining=0}write($){let Y=0,T,q=[];while(Y<$.length)switch(this.readState){case r1.NO_DATA:this.readCompressFlag=$.slice(Y,Y+1),Y+=1,this.readState=r1.READING_SIZE,this.readPartialSize.fill(0),this.readSizeRemaining=4,this.readMessageSize=0,this.readMessageRemaining=0,this.readPartialMessage=[];break;case r1.READING_SIZE:if(T=Math.min($.length-Y,this.readSizeRemaining),$.copy(this.readPartialSize,4-this.readSizeRemaining,Y,Y+T),this.readSizeRemaining-=T,Y+=T,this.readSizeRemaining===0){if(this.readMessageSize=this.readPartialSize.readUInt32BE(0),this.maxReadMessageLength!==-1&&this.readMessageSize>this.maxReadMessageLength)throw Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`);if(this.readMessageRemaining=this.readMessageSize,this.readMessageRemaining>0)this.readState=r1.READING_MESSAGE;else{let X=Buffer.concat([this.readCompressFlag,this.readPartialSize],5);this.readState=r1.NO_DATA,q.push(X)}}break;case r1.READING_MESSAGE:if(T=Math.min($.length-Y,this.readMessageRemaining),this.readPartialMessage.push($.slice(Y,Y+T)),this.readMessageRemaining-=T,Y+=T,this.readMessageRemaining===0){let X=[this.readCompressFlag,this.readPartialSize].concat(this.readPartialMessage),J=Buffer.concat(X,this.readMessageSize+5);this.readState=r1.NO_DATA,q.push(J)}break;default:throw Error("Unexpected read state")}return q}}hG.StreamDecoder=kG});var bG=B((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});mG.Http2SubchannelCall=void 0;var K$=s("http2"),DL=s("os"),X0=i(),A$=P0(),FL=g5(),NL=U0(),HL=i(),zL="subchannel_call";function IL($){for(let[Y,T]of Object.entries(DL.constants.errno))if(T===$)return Y;return"Unknown system error "+$}function m5($){let Y=`Received HTTP status code ${$}`,T;switch($){case 400:T=X0.Status.INTERNAL;break;case 401:T=X0.Status.UNAUTHENTICATED;break;case 403:T=X0.Status.PERMISSION_DENIED;break;case 404:T=X0.Status.UNIMPLEMENTED;break;case 429:case 502:case 503:case 504:T=X0.Status.UNAVAILABLE;break;default:T=X0.Status.UNKNOWN}return{code:T,details:Y,metadata:new A$.Metadata}}class gG{constructor($,Y,T,q,X){var J;this.http2Stream=$,this.callEventTracker=Y,this.listener=T,this.transport=q,this.callId=X,this.isReadFilterPending=!1,this.isPushPending=!1,this.canPush=!1,this.readsClosed=!1,this.statusOutput=!1,this.unpushedReadMessages=[],this.finalStatus=null,this.internalError=null,this.serverEndedCall=!1,this.connectionDropped=!1;let Q=(J=q.getOptions()["grpc.max_receive_message_length"])!==null&&J!==void 0?J:X0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;this.decoder=new FL.StreamDecoder(Q),$.on("response",(U,Z)=>{let K="";for(let A of Object.keys(U))K+="\t\t"+A+": "+U[A]+`
|
|
16
16
|
`;if(this.trace(`Received server headers:
|
|
17
|
-
`+K),this.httpStatusCode=U[":status"],Z&K$.constants.NGHTTP2_FLAG_END_STREAM)this.handleTrailers(U);else{let A;try{A=A$.Metadata.fromHttp2Headers(U)}catch(W){this.endCall({code:X0.Status.UNKNOWN,details:W.message,metadata:new A$.Metadata});return}this.listener.onReceiveMetadata(A)}}),$.on("trailers",(U)=>{this.handleTrailers(U)}),$.on("data",(U)=>{if(this.statusOutput)return;this.trace("receive HTTP/2 data frame of length "+U.length);let Z;try{Z=this.decoder.write(U)}catch(K){if(this.httpStatusCode!==void 0&&this.httpStatusCode!==200){let A=
|
|
17
|
+
`+K),this.httpStatusCode=U[":status"],Z&K$.constants.NGHTTP2_FLAG_END_STREAM)this.handleTrailers(U);else{let A;try{A=A$.Metadata.fromHttp2Headers(U)}catch(W){this.endCall({code:X0.Status.UNKNOWN,details:W.message,metadata:new A$.Metadata});return}this.listener.onReceiveMetadata(A)}}),$.on("trailers",(U)=>{this.handleTrailers(U)}),$.on("data",(U)=>{if(this.statusOutput)return;this.trace("receive HTTP/2 data frame of length "+U.length);let Z;try{Z=this.decoder.write(U)}catch(K){if(this.httpStatusCode!==void 0&&this.httpStatusCode!==200){let A=m5(this.httpStatusCode);this.cancelWithStatus(A.code,A.details)}else this.cancelWithStatus(X0.Status.RESOURCE_EXHAUSTED,K.message);return}for(let K of Z)this.trace("parsed message of length "+K.length),this.callEventTracker.addMessageReceived(),this.tryPush(K)}),$.on("end",()=>{this.readsClosed=!0,this.maybeOutputStatus()}),$.on("close",()=>{this.serverEndedCall=!0,process.nextTick(()=>{var U;if(this.trace("HTTP/2 stream closed with code "+$.rstCode),((U=this.finalStatus)===null||U===void 0?void 0:U.code)===X0.Status.OK)return;let Z,K="";switch($.rstCode){case K$.constants.NGHTTP2_NO_ERROR:if(this.finalStatus!==null)return;if(this.httpStatusCode&&this.httpStatusCode!==200){let A=m5(this.httpStatusCode);Z=A.code,K=A.details}else Z=X0.Status.INTERNAL,K=`Received RST_STREAM with code ${$.rstCode} (Call ended without gRPC status)`;break;case K$.constants.NGHTTP2_REFUSED_STREAM:Z=X0.Status.UNAVAILABLE,K="Stream refused by server";break;case K$.constants.NGHTTP2_CANCEL:if(this.connectionDropped)Z=X0.Status.UNAVAILABLE,K="Connection dropped";else Z=X0.Status.CANCELLED,K="Call cancelled";break;case K$.constants.NGHTTP2_ENHANCE_YOUR_CALM:Z=X0.Status.RESOURCE_EXHAUSTED,K="Bandwidth exhausted or memory limit exceeded";break;case K$.constants.NGHTTP2_INADEQUATE_SECURITY:Z=X0.Status.PERMISSION_DENIED,K="Protocol not secure enough";break;case K$.constants.NGHTTP2_INTERNAL_ERROR:if(Z=X0.Status.INTERNAL,this.internalError===null)K=`Received RST_STREAM with code ${$.rstCode} (Internal server error)`;else if(this.internalError.code==="ECONNRESET"||this.internalError.code==="ETIMEDOUT")Z=X0.Status.UNAVAILABLE,K=this.internalError.message;else K=`Received RST_STREAM with code ${$.rstCode} triggered by internal client error: ${this.internalError.message}`;break;default:Z=X0.Status.INTERNAL,K=`Received RST_STREAM with code ${$.rstCode}`}this.endCall({code:Z,details:K,metadata:new A$.Metadata,rstCode:$.rstCode})})}),$.on("error",(U)=>{if(U.code!=="ERR_HTTP2_STREAM_ERROR")this.trace("Node error event: message="+U.message+" code="+U.code+" errno="+IL(U.errno)+" syscall="+U.syscall),this.internalError=U;this.callEventTracker.onStreamEnd(!1)})}getDeadlineInfo(){return[`remote_addr=${this.getPeer()}`]}onDisconnect(){this.connectionDropped=!0,setImmediate(()=>{this.endCall({code:X0.Status.UNAVAILABLE,details:"Connection dropped",metadata:new A$.Metadata})})}outputStatus(){if(!this.statusOutput)this.statusOutput=!0,this.trace("ended with status: code="+this.finalStatus.code+' details="'+this.finalStatus.details+'"'),this.callEventTracker.onCallEnd(this.finalStatus),process.nextTick(()=>{this.listener.onReceiveStatus(this.finalStatus)}),this.http2Stream.resume()}trace($){NL.trace(HL.LogVerbosity.DEBUG,zL,"["+this.callId+"] "+$)}endCall($){if(this.finalStatus===null||this.finalStatus.code===X0.Status.OK)this.finalStatus=$,this.maybeOutputStatus();this.destroyHttp2Stream()}maybeOutputStatus(){if(this.finalStatus!==null){if(this.finalStatus.code!==X0.Status.OK||this.readsClosed&&this.unpushedReadMessages.length===0&&!this.isReadFilterPending&&!this.isPushPending)this.outputStatus()}}push($){this.trace("pushing to reader message of length "+($ instanceof Buffer?$.length:null)),this.canPush=!1,this.isPushPending=!0,process.nextTick(()=>{if(this.isPushPending=!1,this.statusOutput)return;this.listener.onReceiveMessage($),this.maybeOutputStatus()})}tryPush($){if(this.canPush)this.http2Stream.pause(),this.push($);else this.trace("unpushedReadMessages.push message of length "+$.length),this.unpushedReadMessages.push($)}handleTrailers($){this.serverEndedCall=!0,this.callEventTracker.onStreamEnd(!0);let Y="";for(let J of Object.keys($))Y+="\t\t"+J+": "+$[J]+`
|
|
18
18
|
`;this.trace(`Received server trailers:
|
|
19
|
-
`+Y);let T;try{T=A$.Metadata.fromHttp2Headers($)}catch(J){T=new A$.Metadata}let q=T.getMap(),X;if(typeof q["grpc-status"]==="string"){let J=Number(q["grpc-status"]);this.trace("received status code "+J+" from server"),T.remove("grpc-status");let Q="";if(typeof q["grpc-message"]==="string"){try{Q=decodeURI(q["grpc-message"])}catch(U){Q=q["grpc-message"]}T.remove("grpc-message"),this.trace('received status details string "'+Q+'" from server')}X={code:J,details:Q,metadata:T}}else if(this.httpStatusCode)X=g5(this.httpStatusCode),X.metadata=T;else X={code:X0.Status.UNKNOWN,details:"No status information received",metadata:T};this.endCall(X)}destroyHttp2Stream(){var $;if(this.http2Stream.destroyed)return;if(this.serverEndedCall)this.http2Stream.end();else{let Y;if((($=this.finalStatus)===null||$===void 0?void 0:$.code)===X0.Status.OK)Y=K$.constants.NGHTTP2_NO_ERROR;else Y=K$.constants.NGHTTP2_CANCEL;this.trace("close http2 stream with code "+Y),this.http2Stream.close(Y)}}cancelWithStatus($,Y){this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),this.endCall({code:$,details:Y,metadata:new A$.Metadata})}getStatus(){return this.finalStatus}getPeer(){return this.transport.getPeerName()}getCallNumber(){return this.callId}getAuthContext(){return this.transport.getAuthContext()}startRead(){if(this.finalStatus!==null&&this.finalStatus.code!==X0.Status.OK){this.readsClosed=!0,this.maybeOutputStatus();return}if(this.canPush=!0,this.unpushedReadMessages.length>0){let $=this.unpushedReadMessages.shift();this.push($);return}this.http2Stream.resume()}sendMessageWithContext($,Y){this.trace("write() called with message of length "+Y.length);let T=(q)=>{process.nextTick(()=>{var X;let J=X0.Status.UNAVAILABLE;if((q===null||q===void 0?void 0:q.code)==="ERR_STREAM_WRITE_AFTER_END")J=X0.Status.INTERNAL;if(q)this.cancelWithStatus(J,`Write error: ${q.message}`);(X=$.callback)===null||X===void 0||X.call($)})};this.trace("sending data chunk of length "+Y.length),this.callEventTracker.addMessageSent();try{this.http2Stream.write(Y,T)}catch(q){this.endCall({code:X0.Status.UNAVAILABLE,details:`Write failed with error ${q.message}`,metadata:new A$.Metadata})}}halfClose(){this.trace("end() called"),this.trace("calling end() on HTTP/2 stream"),this.http2Stream.end()}}kG.Http2SubchannelCall=xG});var uG=M((fG)=>{Object.defineProperty(fG,"__esModule",{value:!0});fG.Http2SubchannelConnector=void 0;var $Y=s("http2"),HL=s("tls"),_q=y$(),U6=i(),zL=h5(),lY=U0(),IL=B1(),gq=r0(),m5=p0(),ML=s("net"),BL=_G(),RL=yq(),f5="transport",OL="transport_flowctrl",PL=m4().version,{HTTP2_HEADER_AUTHORITY:LL,HTTP2_HEADER_CONTENT_TYPE:wL,HTTP2_HEADER_METHOD:SL,HTTP2_HEADER_PATH:CL,HTTP2_HEADER_TE:yL,HTTP2_HEADER_USER_AGENT:jL}=$Y.constants,vL=20000,xL=Buffer.from("too_many_pings","ascii");class gG{constructor($,Y,T,q){if(this.session=$,this.options=T,this.remoteName=q,this.keepaliveTimer=null,this.pendingSendKeepalivePing=!1,this.activeCalls=new Set,this.disconnectListeners=[],this.disconnectHandled=!1,this.channelzEnabled=!0,this.keepalivesSent=0,this.messagesSent=0,this.messagesReceived=0,this.lastMessageSentTimestamp=null,this.lastMessageReceivedTimestamp=null,this.subchannelAddressString=(0,gq.subchannelAddressToString)(Y),T["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.streamTracker=new _q.ChannelzCallTrackerStub;else this.streamTracker=new _q.ChannelzCallTracker;if(this.channelzRef=(0,_q.registerChannelzSocket)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.userAgent=[T["grpc.primary_user_agent"],`grpc-node-js/${PL}`,T["grpc.secondary_user_agent"]].filter((X)=>X).join(" "),"grpc.keepalive_time_ms"in T)this.keepaliveTimeMs=T["grpc.keepalive_time_ms"];else this.keepaliveTimeMs=-1;if("grpc.keepalive_timeout_ms"in T)this.keepaliveTimeoutMs=T["grpc.keepalive_timeout_ms"];else this.keepaliveTimeoutMs=vL;if("grpc.keepalive_permit_without_calls"in T)this.keepaliveWithoutCalls=T["grpc.keepalive_permit_without_calls"]===1;else this.keepaliveWithoutCalls=!1;if($.once("close",()=>{this.trace("session closed"),this.handleDisconnect()}),$.once("goaway",(X,J,Q)=>{let U=!1;if(X===$Y.constants.NGHTTP2_ENHANCE_YOUR_CALM&&Q&&Q.equals(xL))U=!0;this.trace("connection closed by GOAWAY with code "+X+" and data "+(Q===null||Q===void 0?void 0:Q.toString())),this.reportDisconnectToOwner(U)}),$.once("error",(X)=>{this.trace("connection closed with error "+X.message),this.handleDisconnect()}),$.socket.once("close",(X)=>{this.trace("connection closed. hadError="+X),this.handleDisconnect()}),lY.isTracerEnabled(f5))$.on("remoteSettings",(X)=>{this.trace("new settings received"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))}),$.on("localSettings",(X)=>{this.trace("local settings acknowledged by remote"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))});if(this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer();if($.socket instanceof HL.TLSSocket)this.authContext={transportSecurityType:"ssl",sslPeerCertificate:$.socket.getPeerCertificate()};else this.authContext={}}getChannelzInfo(){var $,Y,T;let q=this.session.socket,X=q.remoteAddress?(0,gq.stringToSubchannelAddress)(q.remoteAddress,q.remotePort):null,J=q.localAddress?(0,gq.stringToSubchannelAddress)(q.localAddress,q.localPort):null,Q;if(this.session.encrypted){let Z=q,K=Z.getCipher(),A=Z.getCertificate(),W=Z.getPeerCertificate();Q={cipherSuiteStandardName:($=K.standardName)!==null&&$!==void 0?$:null,cipherSuiteOtherName:K.standardName?null:K.name,localCertificate:A&&"raw"in A?A.raw:null,remoteCertificate:W&&"raw"in W?W.raw:null}}else Q=null;return{remoteAddress:X,localAddress:J,security:Q,remoteName:this.remoteName,streamsStarted:this.streamTracker.callsStarted,streamsSucceeded:this.streamTracker.callsSucceeded,streamsFailed:this.streamTracker.callsFailed,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,keepAlivesSent:this.keepalivesSent,lastLocalStreamCreatedTimestamp:this.streamTracker.lastCallStartedTimestamp,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:this.lastMessageSentTimestamp,lastMessageReceivedTimestamp:this.lastMessageReceivedTimestamp,localFlowControlWindow:(Y=this.session.state.localWindowSize)!==null&&Y!==void 0?Y:null,remoteFlowControlWindow:(T=this.session.state.remoteWindowSize)!==null&&T!==void 0?T:null}}trace($){lY.trace(U6.LogVerbosity.DEBUG,f5,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}keepaliveTrace($){lY.trace(U6.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}flowControlTrace($){lY.trace(U6.LogVerbosity.DEBUG,OL,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}internalsTrace($){lY.trace(U6.LogVerbosity.DEBUG,"transport_internals","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}reportDisconnectToOwner($){if(this.disconnectHandled)return;this.disconnectHandled=!0,this.disconnectListeners.forEach((Y)=>Y($))}handleDisconnect(){this.clearKeepaliveTimeout(),this.reportDisconnectToOwner(!1);for(let $ of this.activeCalls)$.onDisconnect();setImmediate(()=>{this.session.destroy()})}addDisconnectListener($){this.disconnectListeners.push($)}canSendPing(){return!this.session.destroyed&&this.keepaliveTimeMs>0&&(this.keepaliveWithoutCalls||this.activeCalls.size>0)}maybeSendPing(){var $,Y;if(!this.canSendPing()){this.pendingSendKeepalivePing=!0;return}if(this.keepaliveTimer){console.error("keepaliveTimeout is not null");return}if(this.channelzEnabled)this.keepalivesSent+=1;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.keepaliveTrace("Ping timeout passed without response"),this.handleDisconnect()},this.keepaliveTimeoutMs),(Y=($=this.keepaliveTimer).unref)===null||Y===void 0||Y.call($);let T="";try{if(!this.session.ping((X,J,Q)=>{if(this.clearKeepaliveTimeout(),X)this.keepaliveTrace("Ping failed with error "+X.message),this.handleDisconnect();else this.keepaliveTrace("Received ping response"),this.maybeStartKeepalivePingTimer()}))T="Ping returned false"}catch(q){T=(q instanceof Error?q.message:"")||"Unknown error"}if(T)this.keepaliveTrace("Ping send failed: "+T),this.handleDisconnect()}maybeStartKeepalivePingTimer(){var $,Y;if(!this.canSendPing())return;if(this.pendingSendKeepalivePing)this.pendingSendKeepalivePing=!1,this.maybeSendPing();else if(!this.keepaliveTimer)this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.maybeSendPing()},this.keepaliveTimeMs),(Y=($=this.keepaliveTimer).unref)===null||Y===void 0||Y.call($)}clearKeepaliveTimeout(){if(this.keepaliveTimer)clearTimeout(this.keepaliveTimer),this.keepaliveTimer=null}removeActiveCall($){if(this.activeCalls.delete($),this.activeCalls.size===0)this.session.unref()}addActiveCall($){if(this.activeCalls.add($),this.activeCalls.size===1){if(this.session.ref(),!this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer()}}createCall($,Y,T,q,X){let J=$.toHttp2Headers();J[LL]=Y,J[jL]=this.userAgent,J[wL]="application/grpc",J[SL]="POST",J[CL]=T,J[yL]="trailers";let Q;try{Q=this.session.request(J)}catch(K){throw this.handleDisconnect(),K}this.flowControlTrace("local window size: "+this.session.state.localWindowSize+" remote window size: "+this.session.state.remoteWindowSize),this.internalsTrace("session.closed="+this.session.closed+" session.destroyed="+this.session.destroyed+" session.socket.destroyed="+this.session.socket.destroyed);let U,Z;if(this.channelzEnabled)this.streamTracker.addCallStarted(),U={addMessageSent:()=>{var K;this.messagesSent+=1,this.lastMessageSentTimestamp=new Date,(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;this.messagesReceived+=1,this.lastMessageReceivedTimestamp=new Date,(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;if(K)this.streamTracker.addCallSucceeded();else this.streamTracker.addCallFailed();(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};else U={addMessageSent:()=>{var K;(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};return Z=new BL.Http2SubchannelCall(Q,U,q,this,(0,RL.getNextCallNumber)()),this.addActiveCall(Z),Z}getChannelzRef(){return this.channelzRef}getPeerName(){return this.subchannelAddressString}getOptions(){return this.options}getAuthContext(){return this.authContext}shutdown(){this.session.close(),(0,_q.unregisterChannelzRef)(this.channelzRef)}}class mG{constructor($){this.channelTarget=$,this.session=null,this.isShutdown=!1}trace($){lY.trace(U6.LogVerbosity.DEBUG,f5,(0,m5.uriToString)(this.channelTarget)+" "+$)}createSession($,Y,T){if(this.isShutdown)return Promise.reject();if($.socket.closed)return Promise.reject("Connection closed before starting HTTP/2 handshake");return new Promise((q,X)=>{var J,Q,U,Z,K,A,W,E;let D=null,F=this.channelTarget;if("grpc.http_connect_target"in T){let C=(0,m5.parseUri)(T["grpc.http_connect_target"]);if(C)F=C,D=(0,m5.uriToString)(C)}let H=$.secure?"https":"http",V=(0,IL.getDefaultAuthority)(F),B=()=>{var C;(C=this.session)===null||C===void 0||C.destroy(),this.session=null,setImmediate(()=>{if(!m)m=!0,X(`${k.trim()} (${new Date().toISOString()})`)})},S=(C)=>{var j;if((j=this.session)===null||j===void 0||j.destroy(),k=C.message,this.trace("connection failed with error "+k),!m)m=!0,X(`${k} (${new Date().toISOString()})`)},v={createConnection:(C,j)=>{return $.socket},settings:{initialWindowSize:(Z=(J=T["grpc-node.flow_control_window"])!==null&&J!==void 0?J:(U=(Q=$Y.getDefaultSettings)===null||Q===void 0?void 0:Q.call($Y))===null||U===void 0?void 0:U.initialWindowSize)!==null&&Z!==void 0?Z:65535},maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER,maxSessionMemory:(K=T["grpc-node.max_session_memory"])!==null&&K!==void 0?K:Number.MAX_SAFE_INTEGER},z=$Y.connect(`${H}://${V}`,v),_=(E=(W=(A=$Y.getDefaultSettings)===null||A===void 0?void 0:A.call($Y))===null||W===void 0?void 0:W.initialWindowSize)!==null&&E!==void 0?E:65535,y=T["grpc-node.flow_control_window"];this.session=z;let k="Failed to connect",m=!1;z.unref(),z.once("remoteSettings",()=>{var C;if(y&&y>_)try{z.setLocalWindowSize(y)}catch(j){let I=y-((C=z.state.localWindowSize)!==null&&C!==void 0?C:_);if(I>0)z.incrementWindowSize(I)}z.removeAllListeners(),$.socket.removeListener("close",B),$.socket.removeListener("error",S),q(new gG(z,Y,T,D)),this.session=null}),z.once("close",B),z.once("error",S),$.socket.once("close",B),$.socket.once("error",S)})}tcpConnect($,Y){return(0,zL.getProxiedConnection)($,Y).then((T)=>{if(T)return T;else return new Promise((q,X)=>{let J=()=>{X(Error("Socket closed"))},Q=(Z)=>{X(Z)},U=ML.connect($,()=>{U.removeListener("close",J),U.removeListener("error",Q),q(U)});U.once("close",J),U.once("error",Q)})})}async connect($,Y,T){if(this.isShutdown)return Promise.reject();let q=null,X=null,J=(0,gq.subchannelAddressToString)($);try{return this.trace(J+" Waiting for secureConnector to be ready"),await Y.waitForReady(),this.trace(J+" secureConnector is ready"),q=await this.tcpConnect($,T),q.setNoDelay(),this.trace(J+" Established TCP connection"),X=await Y.connect(q),this.trace(J+" Established secure connection"),this.createSession(X,$,T)}catch(Q){throw q===null||q===void 0||q.destroy(),X===null||X===void 0||X.socket.destroy(),Q}}shutdown(){var $;this.isShutdown=!0,($=this.session)===null||$===void 0||$.close(),this.session=null}}fG.Http2SubchannelConnector=mG});var pG=M((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});dG.SubchannelPool=void 0;dG.getSubchannelPool=uL;var kL=t7(),hL=FG(),_L=r0(),gL=p0(),mL=uG(),fL=1e4;class mq{constructor(){this.pool=Object.create(null),this.cleanupTimer=null}unrefUnusedSubchannels(){let $=!0;for(let Y in this.pool){let q=this.pool[Y].filter((X)=>!X.subchannel.unrefIfOneRef());if(q.length>0)$=!1;this.pool[Y]=q}if($&&this.cleanupTimer!==null)clearInterval(this.cleanupTimer),this.cleanupTimer=null}ensureCleanupTask(){var $,Y;if(this.cleanupTimer===null)this.cleanupTimer=setInterval(()=>{this.unrefUnusedSubchannels()},fL),(Y=($=this.cleanupTimer).unref)===null||Y===void 0||Y.call($)}getOrCreateSubchannel($,Y,T,q){this.ensureCleanupTask();let X=(0,gL.uriToString)($);if(X in this.pool){let Q=this.pool[X];for(let U of Q)if((0,_L.subchannelAddressEqual)(Y,U.subchannelAddress)&&(0,kL.channelOptionsEqual)(T,U.channelArguments)&&q._equals(U.channelCredentials))return U.subchannel}let J=new hL.Subchannel($,Y,T,q,new mL.Http2SubchannelConnector($));if(!(X in this.pool))this.pool[X]=[];return this.pool[X].push({subchannelAddress:Y,channelArguments:T,channelCredentials:q,subchannel:J}),J.ref(),J}}dG.SubchannelPool=mq;var bL=new mq;function uL($){if($)return bL;else return new mq}});var oG=M((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});rG.LoadBalancingCall=void 0;var lG=l0(),fq=i(),nG=uY(),bq=P0(),Z6=Y$(),cL=p0(),pL=U0(),b5=T6(),lL=s("http2"),nL="load_balancing_call";class iG{constructor($,Y,T,q,X,J,Q){var U,Z;this.channel=$,this.callConfig=Y,this.methodName=T,this.host=q,this.credentials=X,this.deadline=J,this.callNumber=Q,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.metadata=null,this.listener=null,this.onCallEnded=null,this.childStartTime=null;let K=this.methodName.split("/"),A="";if(K.length>=2)A=K[1];let W=(Z=(U=(0,cL.splitHostPort)(this.host))===null||U===void 0?void 0:U.host)!==null&&Z!==void 0?Z:"localhost";this.serviceUrl=`https://${W}/${A}`,this.startTime=new Date}getDeadlineInfo(){var $,Y;let T=[];if(this.childStartTime){if(this.childStartTime>this.startTime){if(($=this.metadata)===null||$===void 0?void 0:$.getOptions().waitForReady)T.push("wait_for_ready");T.push(`LB pick: ${(0,nG.formatDateDifference)(this.startTime,this.childStartTime)}`)}return T.push(...this.child.getDeadlineInfo()),T}else{if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)T.push("wait_for_ready");T.push("Waiting for LB pick")}return T}trace($){pL.trace(fq.LogVerbosity.DEBUG,nL,"["+this.callNumber+"] "+$)}outputStatus($,Y){var T,q;if(!this.ended){this.ended=!0,this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString());let X=Object.assign(Object.assign({},$),{progress:Y});(T=this.listener)===null||T===void 0||T.onReceiveStatus(X),(q=this.onCallEnded)===null||q===void 0||q.call(this,X.code,X.details,X.metadata)}}doPick(){var $,Y;if(this.ended)return;if(!this.metadata)throw Error("doPick called before start");this.trace("Pick called");let T=this.metadata.clone(),q=this.channel.doPick(T,this.callConfig.pickInformation),X=q.subchannel?"("+q.subchannel.getChannelzRef().id+") "+q.subchannel.getAddress():""+q.subchannel;switch(this.trace("Pick result: "+Z6.PickResultType[q.pickResultType]+" subchannel: "+X+" status: "+(($=q.status)===null||$===void 0?void 0:$.code)+" "+((Y=q.status)===null||Y===void 0?void 0:Y.details)),q.pickResultType){case Z6.PickResultType.COMPLETE:this.credentials.compose(q.subchannel.getCallCredentials()).generateMetadata({method_name:this.methodName,service_url:this.serviceUrl}).then((Z)=>{var K;if(this.ended){this.trace("Credentials metadata generation finished after call ended");return}if(T.merge(Z),T.get("authorization").length>1)this.outputStatus({code:fq.Status.INTERNAL,details:'"authorization" metadata cannot have multiple values',metadata:new bq.Metadata},"PROCESSED");if(q.subchannel.getConnectivityState()!==lG.ConnectivityState.READY){this.trace("Picked subchannel "+X+" has state "+lG.ConnectivityState[q.subchannel.getConnectivityState()]+" after getting credentials metadata. Retrying pick"),this.doPick();return}if(this.deadline!==1/0)T.set("grpc-timeout",(0,nG.getDeadlineTimeoutString)(this.deadline));try{this.child=q.subchannel.getRealSubchannel().createCall(T,this.host,this.methodName,{onReceiveMetadata:(A)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(A)},onReceiveMessage:(A)=>{this.trace("Received message"),this.listener.onReceiveMessage(A)},onReceiveStatus:(A)=>{if(this.trace("Received status"),A.rstCode===lL.constants.NGHTTP2_REFUSED_STREAM)this.outputStatus(A,"REFUSED");else this.outputStatus(A,"PROCESSED")}}),this.childStartTime=new Date}catch(A){this.trace("Failed to start call on picked subchannel "+X+" with error "+A.message),this.outputStatus({code:fq.Status.INTERNAL,details:"Failed to start HTTP/2 stream with error "+A.message,metadata:new bq.Metadata},"NOT_STARTED");return}if((K=q.onCallStarted)===null||K===void 0||K.call(q),this.onCallEnded=q.onCallEnded,this.trace("Created child call ["+this.child.getCallNumber()+"]"),this.readPending)this.child.startRead();if(this.pendingMessage)this.child.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.pendingHalfClose)this.child.halfClose()},(Z)=>{let{code:K,details:A}=(0,b5.restrictControlPlaneStatusCode)(typeof Z.code==="number"?Z.code:fq.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Z.message}`);this.outputStatus({code:K,details:A,metadata:new bq.Metadata},"PROCESSED")});break;case Z6.PickResultType.DROP:let{code:Q,details:U}=(0,b5.restrictControlPlaneStatusCode)(q.status.code,q.status.details);setImmediate(()=>{this.outputStatus({code:Q,details:U,metadata:q.status.metadata},"DROP")});break;case Z6.PickResultType.TRANSIENT_FAILURE:if(this.metadata.getOptions().waitForReady)this.channel.queueCallForPick(this);else{let{code:Z,details:K}=(0,b5.restrictControlPlaneStatusCode)(q.status.code,q.status.details);setImmediate(()=>{this.outputStatus({code:Z,details:K,metadata:q.status.metadata},"PROCESSED")})}break;case Z6.PickResultType.QUEUE:this.channel.queueCallForPick(this)}}cancelWithStatus($,Y){var T;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(T=this.child)===null||T===void 0||T.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new bq.Metadata},"PROCESSED")}getPeer(){var $,Y;return(Y=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.channel.getTarget()}start($,Y){this.trace("start called"),this.listener=Y,this.metadata=$,this.doPick()}sendMessageWithContext($,Y){if(this.trace("write() called with message of length "+Y.length),this.child)this.child.sendMessageWithContext($,Y);else this.pendingMessage={context:$,message:Y}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials($){throw Error("Method not implemented.")}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}rG.LoadBalancingCall=iG});var YE=M((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});eG.ResolvingCall=void 0;var iL=g8(),YY=i(),TY=uY(),sG=P0(),rL=U0(),aL=T6(),oL="resolving_call";class tG{constructor($,Y,T,q,X){if(this.channel=$,this.method=Y,this.filterStackFactory=q,this.callNumber=X,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.readFilterPending=!1,this.writeFilterPending=!1,this.pendingChildStatus=null,this.metadata=null,this.listener=null,this.statusWatchers=[],this.deadlineTimer=setTimeout(()=>{},0),this.filterStack=null,this.deadlineStartTime=null,this.configReceivedTime=null,this.childStartTime=null,this.credentials=iL.CallCredentials.createEmpty(),this.deadline=T.deadline,this.host=T.host,T.parentCall){if(T.flags&YY.Propagate.CANCELLATION)T.parentCall.on("cancelled",()=>{this.cancelWithStatus(YY.Status.CANCELLED,"Cancelled by parent call")});if(T.flags&YY.Propagate.DEADLINE)this.trace("Propagating deadline from parent: "+T.parentCall.getDeadline()),this.deadline=(0,TY.minDeadline)(this.deadline,T.parentCall.getDeadline())}this.trace("Created"),this.runDeadlineTimer()}trace($){rL.trace(YY.LogVerbosity.DEBUG,oL,"["+this.callNumber+"] "+$)}runDeadlineTimer(){clearTimeout(this.deadlineTimer),this.deadlineStartTime=new Date,this.trace("Deadline: "+(0,TY.deadlineToString)(this.deadline));let $=(0,TY.getRelativeTimeout)(this.deadline);if($!==1/0){this.trace("Deadline will be reached in "+$+"ms");let Y=()=>{if(!this.deadlineStartTime){this.cancelWithStatus(YY.Status.DEADLINE_EXCEEDED,"Deadline exceeded");return}let T=[],q=new Date;if(T.push(`Deadline exceeded after ${(0,TY.formatDateDifference)(this.deadlineStartTime,q)}`),this.configReceivedTime){if(this.configReceivedTime>this.deadlineStartTime)T.push(`name resolution: ${(0,TY.formatDateDifference)(this.deadlineStartTime,this.configReceivedTime)}`);if(this.childStartTime){if(this.childStartTime>this.configReceivedTime)T.push(`metadata filters: ${(0,TY.formatDateDifference)(this.configReceivedTime,this.childStartTime)}`)}else T.push("waiting for metadata filters")}else T.push("waiting for name resolution");if(this.child)T.push(...this.child.getDeadlineInfo());this.cancelWithStatus(YY.Status.DEADLINE_EXCEEDED,T.join(","))};if($<=0)process.nextTick(Y);else this.deadlineTimer=setTimeout(Y,$)}}outputStatus($){if(!this.ended){if(this.ended=!0,!this.filterStack)this.filterStack=this.filterStackFactory.createFilter();clearTimeout(this.deadlineTimer);let Y=this.filterStack.receiveTrailers($);this.trace("ended with status: code="+Y.code+' details="'+Y.details+'"'),this.statusWatchers.forEach((T)=>T(Y)),process.nextTick(()=>{var T;(T=this.listener)===null||T===void 0||T.onReceiveStatus(Y)})}}sendMessageOnChild($,Y){if(!this.child)throw Error("sendMessageonChild called with child not populated");let T=this.child;this.writeFilterPending=!0,this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags})).then((q)=>{if(this.writeFilterPending=!1,T.sendMessageWithContext($,q.message),this.pendingHalfClose)T.halfClose()},(q)=>{this.cancelWithStatus(q.code,q.details)})}getConfig(){if(this.ended)return;if(!this.metadata||!this.listener)throw Error("getConfig called before start");let $=this.channel.getConfig(this.method,this.metadata);if($.type==="NONE"){this.channel.queueCallForConfig(this);return}else if($.type==="ERROR"){if(this.metadata.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($.error);return}this.configReceivedTime=new Date;let Y=$.config;if(Y.status!==YY.Status.OK){let{code:T,details:q}=(0,aL.restrictControlPlaneStatusCode)(Y.status,"Failed to route call to method "+this.method);this.outputStatus({code:T,details:q,metadata:new sG.Metadata});return}if(Y.methodConfig.timeout){let T=new Date;T.setSeconds(T.getSeconds()+Y.methodConfig.timeout.seconds),T.setMilliseconds(T.getMilliseconds()+Y.methodConfig.timeout.nanos/1e6),this.deadline=(0,TY.minDeadline)(this.deadline,T),this.runDeadlineTimer()}this.filterStackFactory.push(Y.dynamicFilterFactories),this.filterStack=this.filterStackFactory.createFilter(),this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((T)=>{if(this.child=this.channel.createRetryingCall(Y,this.method,this.host,this.credentials,this.deadline),this.trace("Created child ["+this.child.getCallNumber()+"]"),this.childStartTime=new Date,this.child.start(T,{onReceiveMetadata:(q)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(q))},onReceiveMessage:(q)=>{this.trace("Received message"),this.readFilterPending=!0,this.filterStack.receiveMessage(q).then((X)=>{if(this.trace("Finished filtering received message"),this.readFilterPending=!1,this.listener.onReceiveMessage(X),this.pendingChildStatus)this.outputStatus(this.pendingChildStatus)},(X)=>{this.cancelWithStatus(X.code,X.details)})},onReceiveStatus:(q)=>{if(this.trace("Received status"),this.readFilterPending)this.pendingChildStatus=q;else this.outputStatus(q)}}),this.readPending)this.child.startRead();if(this.pendingMessage)this.sendMessageOnChild(this.pendingMessage.context,this.pendingMessage.message);else if(this.pendingHalfClose)this.child.halfClose()},(T)=>{this.outputStatus(T)})}reportResolverError($){var Y;if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($)}cancelWithStatus($,Y){var T;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(T=this.child)===null||T===void 0||T.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new sG.Metadata})}getPeer(){var $,Y;return(Y=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.channel.getTarget()}start($,Y){this.trace("start called"),this.metadata=$.clone(),this.listener=Y,this.getConfig()}sendMessageWithContext($,Y){if(this.trace("write() called with message of length "+Y.length),this.child)this.sendMessageOnChild($,Y);else this.pendingMessage={context:$,message:Y}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child&&!this.writeFilterPending)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials($){this.credentials=$}addStatusWatcher($){this.statusWatchers.push($)}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}eG.ResolvingCall=tG});var UE=M((JE)=>{Object.defineProperty(JE,"__esModule",{value:!0});JE.RetryingCall=JE.MessageBufferTracker=JE.RetryThrottler=void 0;var uq=i(),sL=uY(),tL=P0(),eL=U0(),$w="retrying_call";class TE{constructor($,Y,T){if(this.maxTokens=$,this.tokenRatio=Y,T)this.tokens=T.tokens*($/T.maxTokens);else this.tokens=$}addCallSucceeded(){this.tokens=Math.min(this.tokens+this.tokenRatio,this.maxTokens)}addCallFailed(){this.tokens=Math.max(this.tokens-1,0)}canRetryCall(){return this.tokens>this.maxTokens/2}}JE.RetryThrottler=TE;class qE{constructor($,Y){this.totalLimit=$,this.limitPerCall=Y,this.totalAllocated=0,this.allocatedPerCall=new Map}allocate($,Y){var T;let q=(T=this.allocatedPerCall.get(Y))!==null&&T!==void 0?T:0;if(this.limitPerCall-q<$||this.totalLimit-this.totalAllocated<$)return!1;return this.allocatedPerCall.set(Y,q+$),this.totalAllocated+=$,!0}free($,Y){var T;if(this.totalAllocated<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > total allocated ${this.totalAllocated}`);this.totalAllocated-=$;let q=(T=this.allocatedPerCall.get(Y))!==null&&T!==void 0?T:0;if(q<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > allocated for call ${q}`);this.allocatedPerCall.set(Y,q-$)}freeAll($){var Y;let T=(Y=this.allocatedPerCall.get($))!==null&&Y!==void 0?Y:0;if(this.totalAllocated<T)throw Error(`Invalid buffer allocation state: call ${$} allocated ${T} > total allocated ${this.totalAllocated}`);this.totalAllocated-=T,this.allocatedPerCall.delete($)}}JE.MessageBufferTracker=qE;var u5="grpc-previous-rpc-attempts",Yw=5;class XE{constructor($,Y,T,q,X,J,Q,U,Z){var K;this.channel=$,this.callConfig=Y,this.methodName=T,this.host=q,this.credentials=X,this.deadline=J,this.callNumber=Q,this.bufferTracker=U,this.retryThrottler=Z,this.listener=null,this.initialMetadata=null,this.underlyingCalls=[],this.writeBuffer=[],this.writeBufferOffset=0,this.readStarted=!1,this.transparentRetryUsed=!1,this.attempts=0,this.hedgingTimer=null,this.committedCallIndex=null,this.initialRetryBackoffSec=0,this.nextRetryBackoffSec=0;let A=(K=$.getOptions()["grpc-node.retry_max_attempts_limit"])!==null&&K!==void 0?K:Yw;if($.getOptions()["grpc.enable_retries"]===0)this.state="NO_RETRY",this.maxAttempts=1;else if(Y.methodConfig.retryPolicy){this.state="RETRY";let W=Y.methodConfig.retryPolicy;this.nextRetryBackoffSec=this.initialRetryBackoffSec=Number(W.initialBackoff.substring(0,W.initialBackoff.length-1)),this.maxAttempts=Math.min(W.maxAttempts,A)}else if(Y.methodConfig.hedgingPolicy)this.state="HEDGING",this.maxAttempts=Math.min(Y.methodConfig.hedgingPolicy.maxAttempts,A);else this.state="TRANSPARENT_ONLY",this.maxAttempts=1;this.startTime=new Date}getDeadlineInfo(){if(this.underlyingCalls.length===0)return[];let $=[],Y=this.underlyingCalls[this.underlyingCalls.length-1];if(this.underlyingCalls.length>1)$.push(`previous attempts: ${this.underlyingCalls.length-1}`);if(Y.startTime>this.startTime)$.push(`time to current attempt start: ${(0,sL.formatDateDifference)(this.startTime,Y.startTime)}`);return $.push(...Y.call.getDeadlineInfo()),$}getCallNumber(){return this.callNumber}trace($){eL.trace(uq.LogVerbosity.DEBUG,$w,"["+this.callNumber+"] "+$)}reportStatus($){this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString()),this.bufferTracker.freeAll(this.callNumber),this.writeBufferOffset=this.writeBufferOffset+this.writeBuffer.length,this.writeBuffer=[],process.nextTick(()=>{var Y;(Y=this.listener)===null||Y===void 0||Y.onReceiveStatus({code:$.code,details:$.details,metadata:$.metadata})})}cancelWithStatus($,Y){this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),this.reportStatus({code:$,details:Y,metadata:new tL.Metadata});for(let{call:T}of this.underlyingCalls)T.cancelWithStatus($,Y)}getPeer(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getPeer();else return"unknown"}getBufferEntry($){var Y;return(Y=this.writeBuffer[$-this.writeBufferOffset])!==null&&Y!==void 0?Y:{entryType:"FREED",allocated:!1}}getNextBufferIndex(){return this.writeBufferOffset+this.writeBuffer.length}clearSentMessages(){if(this.state!=="COMMITTED")return;let $;if(this.underlyingCalls[this.committedCallIndex].state==="COMPLETED")$=this.getNextBufferIndex();else $=this.underlyingCalls[this.committedCallIndex].nextMessageToSend;for(let Y=this.writeBufferOffset;Y<$;Y++){let T=this.getBufferEntry(Y);if(T.allocated)this.bufferTracker.free(T.message.message.length,this.callNumber)}this.writeBuffer=this.writeBuffer.slice($-this.writeBufferOffset),this.writeBufferOffset=$}commitCall($){var Y,T;if(this.state==="COMMITTED")return;this.trace("Committing call ["+this.underlyingCalls[$].call.getCallNumber()+"] at index "+$),this.state="COMMITTED",(T=(Y=this.callConfig).onCommitted)===null||T===void 0||T.call(Y),this.committedCallIndex=$;for(let q=0;q<this.underlyingCalls.length;q++){if(q===$)continue;if(this.underlyingCalls[q].state==="COMPLETED")continue;this.underlyingCalls[q].state="COMPLETED",this.underlyingCalls[q].call.cancelWithStatus(uq.Status.CANCELLED,"Discarded in favor of other hedged attempt")}this.clearSentMessages()}commitCallWithMostMessages(){if(this.state==="COMMITTED")return;let $=-1,Y=-1;for(let[T,q]of this.underlyingCalls.entries())if(q.state==="ACTIVE"&&q.nextMessageToSend>$)$=q.nextMessageToSend,Y=T;if(Y===-1)this.state="TRANSPARENT_ONLY";else this.commitCall(Y)}isStatusCodeInList($,Y){return $.some((T)=>{var q;return T===Y||T.toString().toLowerCase()===((q=uq.Status[Y])===null||q===void 0?void 0:q.toLowerCase())})}getNextRetryJitter(){return Math.random()*0.3999999999999999+0.8}getNextRetryBackoffMs(){var $;let Y=($=this.callConfig)===null||$===void 0?void 0:$.methodConfig.retryPolicy;if(!Y)return 0;let q=this.getNextRetryJitter()*this.nextRetryBackoffSec*1000,X=Number(Y.maxBackoff.substring(0,Y.maxBackoff.length-1));return this.nextRetryBackoffSec=Math.min(this.nextRetryBackoffSec*Y.backoffMultiplier,X),q}maybeRetryCall($,Y){if(this.state!=="RETRY"){Y(!1);return}if(this.attempts>=this.maxAttempts){Y(!1);return}let T;if($===null)T=this.getNextRetryBackoffMs();else if($<0){this.state="TRANSPARENT_ONLY",Y(!1);return}else T=$,this.nextRetryBackoffSec=this.initialRetryBackoffSec;setTimeout(()=>{var q,X;if(this.state!=="RETRY"){Y(!1);return}if((X=(q=this.retryThrottler)===null||q===void 0?void 0:q.canRetryCall())!==null&&X!==void 0?X:!0)Y(!0),this.attempts+=1,this.startNewAttempt();else this.trace("Retry attempt denied by throttling policy"),Y(!1)},T)}countActiveCalls(){let $=0;for(let Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE")$+=1;return $}handleProcessedStatus($,Y,T){var q,X,J;switch(this.state){case"COMMITTED":case"NO_RETRY":case"TRANSPARENT_ONLY":this.commitCall(Y),this.reportStatus($);break;case"HEDGING":if(this.isStatusCodeInList((q=this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes)!==null&&q!==void 0?q:[],$.code)){(X=this.retryThrottler)===null||X===void 0||X.addCallFailed();let Q;if(T===null)Q=0;else if(T<0){this.state="TRANSPARENT_ONLY",this.commitCall(Y),this.reportStatus($);return}else Q=T;setTimeout(()=>{if(this.maybeStartHedgingAttempt(),this.countActiveCalls()===0)this.commitCall(Y),this.reportStatus($)},Q)}else this.commitCall(Y),this.reportStatus($);break;case"RETRY":if(this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes,$.code))(J=this.retryThrottler)===null||J===void 0||J.addCallFailed(),this.maybeRetryCall(T,(Q)=>{if(!Q)this.commitCall(Y),this.reportStatus($)});else this.commitCall(Y),this.reportStatus($);break}}getPushback($){let Y=$.get("grpc-retry-pushback-ms");if(Y.length===0)return null;try{return parseInt(Y[0])}catch(T){return-1}}handleChildStatus($,Y){var T;if(this.underlyingCalls[Y].state==="COMPLETED")return;if(this.trace("state="+this.state+" handling status with progress "+$.progress+" from child ["+this.underlyingCalls[Y].call.getCallNumber()+"] in state "+this.underlyingCalls[Y].state),this.underlyingCalls[Y].state="COMPLETED",$.code===uq.Status.OK){(T=this.retryThrottler)===null||T===void 0||T.addCallSucceeded(),this.commitCall(Y),this.reportStatus($);return}if(this.state==="NO_RETRY"){this.commitCall(Y),this.reportStatus($);return}if(this.state==="COMMITTED"){this.reportStatus($);return}let q=this.getPushback($.metadata);switch($.progress){case"NOT_STARTED":this.startNewAttempt();break;case"REFUSED":if(this.transparentRetryUsed)this.handleProcessedStatus($,Y,q);else this.transparentRetryUsed=!0,this.startNewAttempt();break;case"DROP":this.commitCall(Y),this.reportStatus($);break;case"PROCESSED":this.handleProcessedStatus($,Y,q);break}}maybeStartHedgingAttempt(){if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;if(this.attempts>=this.maxAttempts)return;this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}maybeStartHedgingTimer(){var $,Y,T;if(this.hedgingTimer)clearTimeout(this.hedgingTimer);if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;let q=this.callConfig.methodConfig.hedgingPolicy;if(this.attempts>=this.maxAttempts)return;let X=($=q.hedgingDelay)!==null&&$!==void 0?$:"0s",J=Number(X.substring(0,X.length-1));this.hedgingTimer=setTimeout(()=>{this.maybeStartHedgingAttempt()},J*1000),(T=(Y=this.hedgingTimer).unref)===null||T===void 0||T.call(Y)}startNewAttempt(){let $=this.channel.createLoadBalancingCall(this.callConfig,this.methodName,this.host,this.credentials,this.deadline);this.trace("Created child call ["+$.getCallNumber()+"] for attempt "+this.attempts);let Y=this.underlyingCalls.length;this.underlyingCalls.push({state:"ACTIVE",call:$,nextMessageToSend:0,startTime:new Date});let T=this.attempts-1,q=this.initialMetadata.clone();if(T>0)q.set(u5,`${T}`);let X=!1;if($.start(q,{onReceiveMetadata:(J)=>{if(this.trace("Received metadata from child ["+$.getCallNumber()+"]"),this.commitCall(Y),X=!0,T>0)J.set(u5,`${T}`);if(this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMetadata(J)},onReceiveMessage:(J)=>{if(this.trace("Received message from child ["+$.getCallNumber()+"]"),this.commitCall(Y),this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMessage(J)},onReceiveStatus:(J)=>{if(this.trace("Received status from child ["+$.getCallNumber()+"]"),!X&&T>0)J.metadata.set(u5,`${T}`);this.handleChildStatus(J,Y)}}),this.sendNextChildMessage(Y),this.readStarted)$.startRead()}start($,Y){this.trace("start called"),this.listener=Y,this.initialMetadata=$,this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}handleChildWriteCompleted($,Y){var T,q;(q=(T=this.getBufferEntry(Y)).callback)===null||q===void 0||q.call(T),this.clearSentMessages();let X=this.underlyingCalls[$];X.nextMessageToSend+=1,this.sendNextChildMessage($)}sendNextChildMessage($){let Y=this.underlyingCalls[$];if(Y.state==="COMPLETED")return;let T=Y.nextMessageToSend;if(this.getBufferEntry(T)){let q=this.getBufferEntry(T);switch(q.entryType){case"MESSAGE":if(Y.call.sendMessageWithContext({callback:(J)=>{this.handleChildWriteCompleted($,T)}},q.message.message),this.getBufferEntry(T+1).entryType==="HALF_CLOSE")this.trace("Sending halfClose immediately after message to child ["+Y.call.getCallNumber()+"] - optimizing for unary/final message"),Y.nextMessageToSend+=1,Y.call.halfClose();break;case"HALF_CLOSE":Y.nextMessageToSend+=1,Y.call.halfClose();break;case"FREED":break}}}sendMessageWithContext($,Y){this.trace("write() called with message of length "+Y.length);let T={message:Y,flags:$.flags},q=this.getNextBufferIndex(),X={entryType:"MESSAGE",message:T,allocated:this.bufferTracker.allocate(Y.length,this.callNumber)};if(this.writeBuffer.push(X),X.allocated){process.nextTick(()=>{var J;(J=$.callback)===null||J===void 0||J.call($)});for(let[J,Q]of this.underlyingCalls.entries())if(Q.state==="ACTIVE"&&Q.nextMessageToSend===q)Q.call.sendMessageWithContext({callback:(U)=>{this.handleChildWriteCompleted(J,q)}},Y)}else{if(this.commitCallWithMostMessages(),this.committedCallIndex===null)return;let J=this.underlyingCalls[this.committedCallIndex];if(X.callback=$.callback,J.state==="ACTIVE"&&J.nextMessageToSend===q)J.call.sendMessageWithContext({callback:(Q)=>{this.handleChildWriteCompleted(this.committedCallIndex,q)}},Y)}}startRead(){this.trace("startRead called"),this.readStarted=!0;for(let $ of this.underlyingCalls)if(($===null||$===void 0?void 0:$.state)==="ACTIVE")$.call.startRead()}halfClose(){this.trace("halfClose called");let $=this.getNextBufferIndex();this.writeBuffer.push({entryType:"HALF_CLOSE",allocated:!1});for(let Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE"){if(Y.nextMessageToSend===$||Y.nextMessageToSend===$-1)this.trace("Sending halfClose immediately to child ["+Y.call.getCallNumber()+"] - all messages already sent"),Y.nextMessageToSend+=1,Y.call.halfClose()}}setCredentials($){throw Error("Method not implemented.")}getMethod(){return this.methodName}getHost(){return this.host}getAuthContext(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getAuthContext();else return null}}JE.RetryingCall=XE});var K6=M((KE)=>{Object.defineProperty(KE,"__esModule",{value:!0});KE.BaseSubchannelWrapper=void 0;class ZE{constructor($){this.child=$,this.healthy=!0,this.healthListeners=new Set,this.refcount=0,this.dataWatchers=new Set,$.addHealthStateWatcher((Y)=>{if(this.healthy)this.updateHealthListeners()})}updateHealthListeners(){for(let $ of this.healthListeners)$(this.isHealthy())}getConnectivityState(){return this.child.getConnectivityState()}addConnectivityStateListener($){this.child.addConnectivityStateListener($)}removeConnectivityStateListener($){this.child.removeConnectivityStateListener($)}startConnecting(){this.child.startConnecting()}getAddress(){return this.child.getAddress()}throttleKeepalive($){this.child.throttleKeepalive($)}ref(){this.child.ref(),this.refcount+=1}unref(){if(this.child.unref(),this.refcount-=1,this.refcount===0)this.destroy()}destroy(){for(let $ of this.dataWatchers)$.destroy()}getChannelzRef(){return this.child.getChannelzRef()}isHealthy(){return this.healthy&&this.child.isHealthy()}addHealthStateWatcher($){this.healthListeners.add($)}removeHealthStateWatcher($){this.healthListeners.delete($)}addDataWatcher($){$.setSubchannel(this.getRealSubchannel()),this.dataWatchers.add($)}setHealthy($){if($!==this.healthy){if(this.healthy=$,this.child.isHealthy())this.updateHealthListeners()}}getRealSubchannel(){return this.child.getRealSubchannel()}realSubchannelEquals($){return this.getRealSubchannel()===$.getRealSubchannel()}getCallCredentials(){return this.child.getCallCredentials()}getChannel(){return this.child.getChannel()}}KE.BaseSubchannelWrapper=ZE});var l5=M((FE)=>{Object.defineProperty(FE,"__esModule",{value:!0});FE.InternalChannel=FE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=void 0;var Xw=PY(),Jw=a7(),Qw=pG(),p5=Y$(),Uw=P0(),v$=i(),Zw=vq(),Kw=L5(),WE=B1(),dq=U0(),Aw=h5(),cq=p0(),N1=l0(),A6=y$(),Ww=oG(),Gw=uY(),Ew=YE(),d5=yq(),Vw=T6(),c5=UE(),Dw=K6(),Fw=2147483647,Nw=1000,Hw=1800000,pq=new Map,zw=16777216,Iw=1048576;class GE extends Dw.BaseSubchannelWrapper{constructor($,Y){super($);this.channel=Y,this.refCount=0,this.subchannelStateListener=(T,q,X,J)=>{Y.throttleKeepalive(J)}}ref(){if(this.refCount===0)this.child.addConnectivityStateListener(this.subchannelStateListener),this.channel.addWrappedSubchannel(this);this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0)this.child.removeConnectivityStateListener(this.subchannelStateListener),this.channel.removeWrappedSubchannel(this)}}class EE{pick($){return{pickResultType:p5.PickResultType.DROP,status:{code:v$.Status.UNAVAILABLE,details:"Channel closed before call started",metadata:new Uw.Metadata},subchannel:null,onCallStarted:null,onCallEnded:null}}}FE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX="grpc.internal.no_subchannel";class VE{constructor($){this.target=$,this.trace=new A6.ChannelzTrace,this.callTracker=new A6.ChannelzCallTracker,this.childrenTracker=new A6.ChannelzChildrenTracker,this.state=N1.ConnectivityState.IDLE}getChannelzInfoCallback(){return()=>{return{target:this.target,state:this.state,trace:this.trace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}}}}class DE{constructor($,Y,T){var q,X,J,Q,U,Z;if(this.credentials=Y,this.options=T,this.connectivityState=N1.ConnectivityState.IDLE,this.currentPicker=new p5.UnavailablePicker,this.configSelectionQueue=[],this.pickQueue=[],this.connectivityStateWatchers=[],this.callRefTimer=null,this.configSelector=null,this.currentResolutionError=null,this.wrappedSubchannels=new Set,this.callCount=0,this.idleTimer=null,this.channelzEnabled=!0,this.randomChannelId=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),typeof $!=="string")throw TypeError("Channel target must be a string");if(!(Y instanceof Xw.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(T){if(typeof T!=="object")throw TypeError("Channel options must be an object")}this.channelzInfoTracker=new VE($);let K=(0,cq.parseUri)($);if(K===null)throw Error(`Could not parse target name "${$}"`);let A=(0,WE.mapUriDefaultScheme)(K);if(A===null)throw Error(`Could not find a default scheme for target name "${$}"`);if(this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1;if(this.channelzRef=(0,A6.registerChannelzChannel)($,this.channelzInfoTracker.getChannelzInfoCallback(),this.channelzEnabled),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Channel created");if(this.options["grpc.default_authority"])this.defaultAuthority=this.options["grpc.default_authority"];else this.defaultAuthority=(0,WE.getDefaultAuthority)(A);let W=(0,Aw.mapProxyName)(A,T);this.target=W.target,this.options=Object.assign({},this.options,W.extraOptions),this.subchannelPool=(0,Qw.getSubchannelPool)(((q=this.options["grpc.use_local_subchannel_pool"])!==null&&q!==void 0?q:0)===0),this.retryBufferTracker=new c5.MessageBufferTracker((X=this.options["grpc.retry_buffer_size"])!==null&&X!==void 0?X:zw,(J=this.options["grpc.per_rpc_retry_buffer_size"])!==null&&J!==void 0?J:Iw),this.keepaliveTime=(Q=this.options["grpc.keepalive_time_ms"])!==null&&Q!==void 0?Q:-1,this.idleTimeoutMs=Math.max((U=this.options["grpc.client_idle_timeout_ms"])!==null&&U!==void 0?U:Hw,Nw);let E={createSubchannel:(F,H)=>{let V={};for(let[v,z]of Object.entries(H))if(!v.startsWith(FE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX))V[v]=z;let B=this.subchannelPool.getOrCreateSubchannel(this.target,F,V,this.credentials);if(B.throttleKeepalive(this.keepaliveTime),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Created subchannel or used existing subchannel",B.getChannelzRef());return new GE(B,this)},updateState:(F,H)=>{this.currentPicker=H;let V=this.pickQueue.slice();if(this.pickQueue=[],V.length>0)this.callRefTimerUnref();for(let B of V)B.doPick();this.updateState(F)},requestReresolution:()=>{throw Error("Resolving load balancer should never call requestReresolution")},addChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.refChild(F)},removeChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.unrefChild(F)}};this.resolvingLoadBalancer=new Jw.ResolvingLoadBalancer(this.target,E,this.options,(F,H)=>{var V;if(F.retryThrottling)pq.set(this.getTarget(),new c5.RetryThrottler(F.retryThrottling.maxTokens,F.retryThrottling.tokenRatio,pq.get(this.getTarget())));else pq.delete(this.getTarget());if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Address resolution succeeded");(V=this.configSelector)===null||V===void 0||V.unref(),this.configSelector=H,this.currentResolutionError=null,process.nextTick(()=>{let B=this.configSelectionQueue;if(this.configSelectionQueue=[],B.length>0)this.callRefTimerUnref();for(let S of B)S.getConfig()})},(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_WARNING","Address resolution failed with code "+F.code+' and details "'+F.details+'"');if(this.configSelectionQueue.length>0)this.trace("Name resolution failed with calls queued for config selection");if(this.configSelector===null)this.currentResolutionError=Object.assign(Object.assign({},(0,Vw.restrictControlPlaneStatusCode)(F.code,F.details)),{metadata:F.metadata});let H=this.configSelectionQueue;if(this.configSelectionQueue=[],H.length>0)this.callRefTimerUnref();for(let V of H)V.reportResolverError(F)}),this.filterStackFactory=new Zw.FilterStackFactory([new Kw.CompressionFilterFactory(this,this.options)]),this.trace("Channel constructed with options "+JSON.stringify(T,void 0,2));let D=Error();if((0,dq.isTracerEnabled)("channel_stacktrace"))(0,dq.trace)(v$.LogVerbosity.DEBUG,"channel_stacktrace","("+this.channelzRef.id+`) Channel constructed
|
|
20
|
-
`+((Z=
|
|
21
|
-
`)+1)));this.lastActivityTimestamp=new Date}trace($,Y){(0,dq.trace)(Y!==null&&Y!==void 0?Y:v$.LogVerbosity.DEBUG,"channel","("+this.channelzRef.id+") "+(0,cq.uriToString)(this.target)+" "+$)}callRefTimerRef(){var $,Y,T,q;if(!this.callRefTimer)this.callRefTimer=setInterval(()=>{},Fw);if(!((Y=($=this.callRefTimer).hasRef)===null||Y===void 0?void 0:Y.call($)))this.trace("callRefTimer.ref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(q=(T=this.callRefTimer).ref)===null||q===void 0||q.call(T)}callRefTimerUnref(){var $,Y,T;if(!(($=this.callRefTimer)===null||$===void 0?void 0:$.hasRef)||this.callRefTimer.hasRef())this.trace("callRefTimer.unref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(T=(Y=this.callRefTimer)===null||Y===void 0?void 0:Y.unref)===null||T===void 0||T.call(Y)}removeConnectivityStateWatcher($){let Y=this.connectivityStateWatchers.findIndex((T)=>T===$);if(Y>=0)this.connectivityStateWatchers.splice(Y,1)}updateState($){if((0,dq.trace)(v$.LogVerbosity.DEBUG,"connectivity_state","("+this.channelzRef.id+") "+(0,cq.uriToString)(this.target)+" "+N1.ConnectivityState[this.connectivityState]+" -> "+N1.ConnectivityState[$]),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Connectivity state change to "+N1.ConnectivityState[$]);this.connectivityState=$,this.channelzInfoTracker.state=$;let Y=this.connectivityStateWatchers.slice();for(let T of Y)if($!==T.currentState){if(T.timer)clearTimeout(T.timer);this.removeConnectivityStateWatcher(T),T.callback()}if($!==N1.ConnectivityState.TRANSIENT_FAILURE)this.currentResolutionError=null}throttleKeepalive($){if($>this.keepaliveTime){this.keepaliveTime=$;for(let Y of this.wrappedSubchannels)Y.throttleKeepalive($)}}addWrappedSubchannel($){this.wrappedSubchannels.add($)}removeWrappedSubchannel($){this.wrappedSubchannels.delete($)}doPick($,Y){return this.currentPicker.pick({metadata:$,extraPickInfo:Y})}queueCallForPick($){this.pickQueue.push($),this.callRefTimerRef()}getConfig($,Y){if(this.connectivityState!==N1.ConnectivityState.SHUTDOWN)this.resolvingLoadBalancer.exitIdle();if(this.configSelector)return{type:"SUCCESS",config:this.configSelector.invoke($,Y,this.randomChannelId)};else if(this.currentResolutionError)return{type:"ERROR",error:this.currentResolutionError};else return{type:"NONE"}}queueCallForConfig($){this.configSelectionQueue.push($),this.callRefTimerRef()}enterIdle(){if(this.resolvingLoadBalancer.destroy(),this.updateState(N1.ConnectivityState.IDLE),this.currentPicker=new p5.QueuePicker(this.resolvingLoadBalancer),this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;if(this.callRefTimer)clearInterval(this.callRefTimer),this.callRefTimer=null}startIdleTimeout($){var Y,T;this.idleTimer=setTimeout(()=>{if(this.callCount>0){this.startIdleTimeout(this.idleTimeoutMs);return}let X=new Date().valueOf()-this.lastActivityTimestamp.valueOf();if(X>=this.idleTimeoutMs)this.trace("Idle timer triggered after "+this.idleTimeoutMs+"ms of inactivity"),this.enterIdle();else this.startIdleTimeout(this.idleTimeoutMs-X)},$),(T=(Y=this.idleTimer).unref)===null||T===void 0||T.call(Y)}maybeStartIdleTimer(){if(this.connectivityState!==N1.ConnectivityState.SHUTDOWN&&!this.idleTimer)this.startIdleTimeout(this.idleTimeoutMs)}onCallStart(){if(this.channelzEnabled)this.channelzInfoTracker.callTracker.addCallStarted();this.callCount+=1}onCallEnd($){if(this.channelzEnabled)if($.code===v$.Status.OK)this.channelzInfoTracker.callTracker.addCallSucceeded();else this.channelzInfoTracker.callTracker.addCallFailed();this.callCount-=1,this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer()}createLoadBalancingCall($,Y,T,q,X){let J=(0,d5.getNextCallNumber)();return this.trace("createLoadBalancingCall ["+J+'] method="'+Y+'"'),new Ww.LoadBalancingCall(this,$,Y,T,q,X,J)}createRetryingCall($,Y,T,q,X){let J=(0,d5.getNextCallNumber)();return this.trace("createRetryingCall ["+J+'] method="'+Y+'"'),new c5.RetryingCall(this,$,Y,T,q,X,J,this.retryBufferTracker,pq.get(this.getTarget()))}createResolvingCall($,Y,T,q,X){let J=(0,d5.getNextCallNumber)();this.trace("createResolvingCall ["+J+'] method="'+$+'", deadline='+(0,Gw.deadlineToString)(Y));let Q={deadline:Y,flags:X!==null&&X!==void 0?X:v$.Propagate.DEFAULTS,host:T!==null&&T!==void 0?T:this.defaultAuthority,parentCall:q},U=new Ew.ResolvingCall(this,$,Q,this.filterStackFactory.clone(),J);return this.onCallStart(),U.addStatusWatcher((Z)=>{this.onCallEnd(Z)}),U}close(){var $;this.resolvingLoadBalancer.destroy(),this.updateState(N1.ConnectivityState.SHUTDOWN),this.currentPicker=new EE;for(let Y of this.configSelectionQueue)Y.cancelWithStatus(v$.Status.UNAVAILABLE,"Channel closed before call started");this.configSelectionQueue=[];for(let Y of this.pickQueue)Y.cancelWithStatus(v$.Status.UNAVAILABLE,"Channel closed before call started");if(this.pickQueue=[],this.callRefTimer)clearInterval(this.callRefTimer);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.channelzEnabled)(0,A6.unregisterChannelzRef)(this.channelzRef);this.subchannelPool.unrefUnusedSubchannels(),($=this.configSelector)===null||$===void 0||$.unref(),this.configSelector=null}getTarget(){return(0,cq.uriToString)(this.target)}getConnectivityState($){let Y=this.connectivityState;if($)this.resolvingLoadBalancer.exitIdle(),this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer();return Y}watchConnectivityState($,Y,T){if(this.connectivityState===N1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");let q=null;if(Y!==1/0){let J=Y instanceof Date?Y:new Date(Y),Q=new Date;if(Y===-1/0||J<=Q){process.nextTick(T,Error("Deadline passed without connectivity state change"));return}q=setTimeout(()=>{this.removeConnectivityStateWatcher(X),T(Error("Deadline passed without connectivity state change"))},J.getTime()-Q.getTime())}let X={currentState:$,callback:T,timer:q};this.connectivityStateWatchers.push(X)}getChannelzRef(){return this.channelzRef}createCall($,Y,T,q,X){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof Y==="number"||Y instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");if(this.connectivityState===N1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");return this.createResolvingCall($,Y,T,q,X)}getOptions(){return this.options}}FE.InternalChannel=DE});var AX=M((IE)=>{Object.defineProperty(IE,"__esModule",{value:!0});IE.ChannelImplementation=void 0;var Mw=PY(),Bw=l5();class zE{constructor($,Y,T){if(typeof $!=="string")throw TypeError("Channel target must be a string");if(!(Y instanceof Mw.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(T){if(typeof T!=="object")throw TypeError("Channel options must be an object")}this.internalChannel=new Bw.InternalChannel($,Y,T)}close(){this.internalChannel.close()}getTarget(){return this.internalChannel.getTarget()}getConnectivityState($){return this.internalChannel.getConnectivityState($)}watchConnectivityState($,Y,T){this.internalChannel.watchConnectivityState($,Y,T)}getChannelzRef(){return this.internalChannel.getChannelzRef()}createCall($,Y,T,q,X){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof Y==="number"||Y instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");return this.internalChannel.createCall($,Y,T,q,X)}}IE.ChannelImplementation=zE});var CE=M((wE)=>{Object.defineProperty(wE,"__esModule",{value:!0});wE.ServerDuplexStreamImpl=wE.ServerWritableStreamImpl=wE.ServerReadableStreamImpl=wE.ServerUnaryCallImpl=void 0;wE.serverErrorToStatus=r5;var Rw=s("events"),n5=s("stream"),i5=i(),BE=P0();function r5($,Y){var T;let q={code:i5.Status.UNKNOWN,details:"message"in $?$.message:"Unknown Error",metadata:(T=Y!==null&&Y!==void 0?Y:$.metadata)!==null&&T!==void 0?T:null};if("code"in $&&typeof $.code==="number"&&Number.isInteger($.code)){if(q.code=$.code,"details"in $&&typeof $.details==="string")q.details=$.details}return q}class RE extends Rw.EventEmitter{constructor($,Y,T,q){super();this.path=$,this.call=Y,this.metadata=T,this.request=q,this.cancelled=!1}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}wE.ServerUnaryCallImpl=RE;class OE extends n5.Readable{constructor($,Y,T){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.cancelled=!1}_read($){this.call.startRead()}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}wE.ServerReadableStreamImpl=OE;class PE extends n5.Writable{constructor($,Y,T,q){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.request=q,this.pendingStatus={code:i5.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new BE.Metadata,this.on("error",(X)=>{this.pendingStatus=r5(X),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_write($,Y,T){this.call.sendMessage($,T)}_final($){var Y;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(Y=this.pendingStatus.metadata)!==null&&Y!==void 0?Y:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}wE.ServerWritableStreamImpl=PE;class LE extends n5.Duplex{constructor($,Y,T){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.pendingStatus={code:i5.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new BE.Metadata,this.on("error",(q)=>{this.pendingStatus=r5(q),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_read($){this.call.startRead()}_write($,Y,T){this.call.sendMessage($,T)}_final($){var Y;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(Y=this.pendingStatus.metadata)!==null&&Y!==void 0?Y:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}wE.ServerDuplexStreamImpl=LE});var lq=M((yE)=>{Object.defineProperty(yE,"__esModule",{value:!0});yE.ServerCredentials=void 0;yE.createCertificateProviderServerCredentials=Sw;yE.createServerCredentialsWithInterceptors=Cw;var a5=a4();class nY{constructor($,Y){this.serverConstructorOptions=$,this.watchers=new Set,this.latestContextOptions=null,this.latestContextOptions=Y!==null&&Y!==void 0?Y:null}_addWatcher($){this.watchers.add($)}_removeWatcher($){this.watchers.delete($)}getWatcherCount(){return this.watchers.size}updateSecureContextOptions($){this.latestContextOptions=$;for(let Y of this.watchers)Y(this.latestContextOptions)}_isSecure(){return this.serverConstructorOptions!==null}_getSecureContextOptions(){return this.latestContextOptions}_getConstructorOptions(){return this.serverConstructorOptions}_getInterceptors(){return[]}static createInsecure(){return new o5}static createSsl($,Y,T=!1){var q;if($!==null&&!Buffer.isBuffer($))throw TypeError("rootCerts must be null or a Buffer");if(!Array.isArray(Y))throw TypeError("keyCertPairs must be an array");if(typeof T!=="boolean")throw TypeError("checkClientCertificate must be a boolean");let X=[],J=[];for(let Q=0;Q<Y.length;Q++){let U=Y[Q];if(U===null||typeof U!=="object")throw TypeError(`keyCertPair[${Q}] must be an object`);if(!Buffer.isBuffer(U.private_key))throw TypeError(`keyCertPair[${Q}].private_key must be a Buffer`);if(!Buffer.isBuffer(U.cert_chain))throw TypeError(`keyCertPair[${Q}].cert_chain must be a Buffer`);X.push(U.cert_chain),J.push(U.private_key)}return new s5({requestCert:T,ciphers:a5.CIPHER_SUITES},{ca:(q=$!==null&&$!==void 0?$:(0,a5.getDefaultRootsData)())!==null&&q!==void 0?q:void 0,cert:X,key:J})}}yE.ServerCredentials=nY;class o5 extends nY{constructor(){super(null)}_getSettings(){return null}_equals($){return $ instanceof o5}}class s5 extends nY{constructor($,Y){super($,Y);this.options=Object.assign(Object.assign({},$),Y)}_equals($){if(this===$)return!0;if(!($ instanceof s5))return!1;if(Buffer.isBuffer(this.options.ca)&&Buffer.isBuffer($.options.ca)){if(!this.options.ca.equals($.options.ca))return!1}else if(this.options.ca!==$.options.ca)return!1;if(Array.isArray(this.options.cert)&&Array.isArray($.options.cert)){if(this.options.cert.length!==$.options.cert.length)return!1;for(let Y=0;Y<this.options.cert.length;Y++){let T=this.options.cert[Y],q=$.options.cert[Y];if(Buffer.isBuffer(T)&&Buffer.isBuffer(q)){if(!T.equals(q))return!1}else if(T!==q)return!1}}else if(this.options.cert!==$.options.cert)return!1;if(Array.isArray(this.options.key)&&Array.isArray($.options.key)){if(this.options.key.length!==$.options.key.length)return!1;for(let Y=0;Y<this.options.key.length;Y++){let T=this.options.key[Y],q=$.options.key[Y];if(Buffer.isBuffer(T)&&Buffer.isBuffer(q)){if(!T.equals(q))return!1}else if(T!==q)return!1}}else if(this.options.key!==$.options.key)return!1;if(this.options.requestCert!==$.options.requestCert)return!1;return!0}}class t5 extends nY{constructor($,Y,T){super({requestCert:Y!==null,rejectUnauthorized:T,ciphers:a5.CIPHER_SUITES});this.identityCertificateProvider=$,this.caCertificateProvider=Y,this.requireClientCertificate=T,this.latestCaUpdate=null,this.latestIdentityUpdate=null,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this)}_addWatcher($){var Y;if(this.getWatcherCount()===0)(Y=this.caCertificateProvider)===null||Y===void 0||Y.addCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);super._addWatcher($)}_removeWatcher($){var Y;if(super._removeWatcher($),this.getWatcherCount()===0)(Y=this.caCertificateProvider)===null||Y===void 0||Y.removeCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_equals($){if(this===$)return!0;if(!($ instanceof t5))return!1;return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&this.requireClientCertificate===$.requireClientCertificate}calculateSecureContextOptions(){var $;if(this.latestIdentityUpdate===null)return null;if(this.caCertificateProvider!==null&&this.latestCaUpdate===null)return null;return{ca:($=this.latestCaUpdate)===null||$===void 0?void 0:$.caCertificate,cert:[this.latestIdentityUpdate.certificate],key:[this.latestIdentityUpdate.privateKey]}}finalizeUpdate(){let $=this.calculateSecureContextOptions();this.updateSecureContextOptions($)}handleCaCertificateUpdate($){this.latestCaUpdate=$,this.finalizeUpdate()}handleIdentityCertitificateUpdate($){this.latestIdentityUpdate=$,this.finalizeUpdate()}}function Sw($,Y,T){return new t5($,Y,T)}class e5 extends nY{constructor($,Y){super({});this.childCredentials=$,this.interceptors=Y}_isSecure(){return this.childCredentials._isSecure()}_equals($){if(!($ instanceof e5))return!1;if(!this.childCredentials._equals($.childCredentials))return!1;if(this.interceptors.length!==$.interceptors.length)return!1;for(let Y=0;Y<this.interceptors.length;Y++)if(this.interceptors[Y]!==$.interceptors[Y])return!1;return!0}_getInterceptors(){return this.interceptors}_addWatcher($){this.childCredentials._addWatcher($)}_removeWatcher($){this.childCredentials._removeWatcher($)}_getConstructorOptions(){return this.childCredentials._getConstructorOptions()}_getSecureContextOptions(){return this.childCredentials._getSecureContextOptions()}}function Cw($,Y){return new e5($,Y)}});var W6=M((vE)=>{Object.defineProperty(vE,"__esModule",{value:!0});vE.durationMessageToDuration=vw;vE.msToDuration=xw;vE.durationToMs=kw;vE.isDuration=hw;vE.isDurationMessage=_w;vE.parseDuration=mw;vE.durationToString=fw;function vw($){return{seconds:Number.parseInt($.seconds),nanos:$.nanos}}function xw($){return{seconds:$/1000|0,nanos:$%1000*1e6|0}}function kw($){return $.seconds*1000+$.nanos/1e6|0}function hw($){return typeof $.seconds==="number"&&typeof $.nanos==="number"}function _w($){return typeof $.seconds==="string"&&typeof $.nanos==="number"}var gw=/^(\d+)(?:\.(\d+))?s$/;function mw($){let Y=$.match(gw);if(!Y)return null;return{seconds:Number.parseInt(Y[1],10),nanos:Y[2]?Number.parseInt(Y[2].padEnd(9,"0"),10):0}}function fw($){if($.nanos===0)return`${$.seconds}s`;let Y;if($.nanos%1e6===0)Y=1e6;else if($.nanos%1000===0)Y=1000;else Y=1;return`${$.seconds}.${$.nanos/Y}s`}});var iq=M((cE)=>{var __dirname="/Users/beatrix/dev/clinee/sdk-wip/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(cE,"__esModule",{value:!0});cE.OrcaOobMetricsSubchannelWrapper=cE.GRPC_METRICS_HEADER=cE.ServerMetricRecorder=cE.PerRequestMetricRecorder=void 0;cE.createOrcaClient=mE;cE.createMetricsReader=ew;var iw=a8(),$J=W6(),rw=PY(),aw=K6(),xE=i(),ow=LY(),sw=l0(),kE=null;function nq(){if(kE)return kE;let $=tT().loadSync,Y=$("xds/service/orca/v3/orca.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto/xds`,`${__dirname}/../../proto/protoc-gen-validate`]});return(0,iw.loadPackageDefinition)(Y)}class _E{constructor(){this.message={}}recordRequestCostMetric($,Y){if(!this.message.request_cost)this.message.request_cost={};this.message.request_cost[$]=Y}recordUtilizationMetric($,Y){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=Y}recordNamedMetric($,Y){if(!this.message.named_metrics)this.message.named_metrics={};this.message.named_metrics[$]=Y}recordCPUUtilizationMetric($){this.message.cpu_utilization=$}recordMemoryUtilizationMetric($){this.message.mem_utilization=$}recordApplicationUtilizationMetric($){this.message.application_utilization=$}recordQpsMetric($){this.message.rps_fractional=$}recordEpsMetric($){this.message.eps=$}serialize(){return nq().xds.data.orca.v3.OrcaLoadReport.serialize(this.message)}}cE.PerRequestMetricRecorder=_E;var tw=30000;class gE{constructor(){this.message={},this.serviceImplementation={StreamCoreMetrics:($)=>{let Y=$.request.report_interval?(0,$J.durationToMs)((0,$J.durationMessageToDuration)($.request.report_interval)):tw,T=setInterval(()=>{$.write(this.message)},Y);$.on("cancelled",()=>{clearInterval(T)})}}}putUtilizationMetric($,Y){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=Y}setAllUtilizationMetrics($){this.message.utilization=Object.assign({},$)}deleteUtilizationMetric($){var Y;(Y=this.message.utilization)===null||Y===void 0||delete Y[$]}setCpuUtilizationMetric($){this.message.cpu_utilization=$}deleteCpuUtilizationMetric(){delete this.message.cpu_utilization}setApplicationUtilizationMetric($){this.message.application_utilization=$}deleteApplicationUtilizationMetric(){delete this.message.application_utilization}setQpsMetric($){this.message.rps_fractional=$}deleteQpsMetric(){delete this.message.rps_fractional}setEpsMetric($){this.message.eps=$}deleteEpsMetric(){delete this.message.eps}addToServer($){let Y=nq().xds.service.orca.v3.OpenRcaService.service;$.addService(Y,this.serviceImplementation)}}cE.ServerMetricRecorder=gE;function mE($){return new(nq()).xds.service.orca.v3.OpenRcaService("unused",rw.ChannelCredentials.createInsecure(),{channelOverride:$})}cE.GRPC_METRICS_HEADER="endpoint-load-metrics-bin";var hE="grpc_orca_load_report";function ew($,Y){return(T,q,X)=>{let J=X.getOpaque(hE);if(J)$(J);else{let Q=X.get(cE.GRPC_METRICS_HEADER);if(Q.length>0)J=nq().xds.data.orca.v3.OrcaLoadReport.deserialize(Q[0]),$(J),X.setOpaque(hE,J)}if(Y)Y(T,q,X)}}var fE="orca_oob_metrics";class bE{constructor($,Y){this.metricsListener=$,this.intervalMs=Y,this.dataProducer=null}setSubchannel($){let Y=$.getOrCreateDataProducer(fE,$S);this.dataProducer=Y,Y.addDataWatcher(this)}destroy(){var $;($=this.dataProducer)===null||$===void 0||$.removeDataWatcher(this)}getInterval(){return this.intervalMs}onMetricsUpdate($){this.metricsListener($)}}class uE{constructor($){this.subchannel=$,this.dataWatchers=new Set,this.orcaSupported=!0,this.metricsCall=null,this.currentInterval=1/0,this.backoffTimer=new ow.BackoffTimeout(()=>this.updateMetricsSubscription()),this.subchannelStateListener=()=>this.updateMetricsSubscription();let Y=$.getChannel();this.client=mE(Y),$.addConnectivityStateListener(this.subchannelStateListener)}addDataWatcher($){this.dataWatchers.add($),this.updateMetricsSubscription()}removeDataWatcher($){var Y;if(this.dataWatchers.delete($),this.dataWatchers.size===0)this.subchannel.removeDataProducer(fE),(Y=this.metricsCall)===null||Y===void 0||Y.cancel(),this.metricsCall=null,this.client.close(),this.subchannel.removeConnectivityStateListener(this.subchannelStateListener);else this.updateMetricsSubscription()}updateMetricsSubscription(){var $;if(this.dataWatchers.size===0||!this.orcaSupported||this.subchannel.getConnectivityState()!==sw.ConnectivityState.READY)return;let Y=Math.min(...Array.from(this.dataWatchers).map((T)=>T.getInterval()));if(!this.metricsCall||Y!==this.currentInterval){($=this.metricsCall)===null||$===void 0||$.cancel(),this.currentInterval=Y;let T=this.client.streamCoreMetrics({report_interval:(0,$J.msToDuration)(Y)});this.metricsCall=T,T.on("data",(q)=>{this.dataWatchers.forEach((X)=>{X.onMetricsUpdate(q)})}),T.on("error",(q)=>{if(this.metricsCall=null,q.code===xE.Status.UNIMPLEMENTED){this.orcaSupported=!1;return}if(q.code===xE.Status.CANCELLED)return;this.backoffTimer.runOnce()})}}}class dE extends aw.BaseSubchannelWrapper{constructor($,Y,T){super($);this.addDataWatcher(new bE(Y,T))}getWrappedSubchannel(){return this.child}}cE.OrcaOobMetricsSubchannelWrapper=dE;function $S($){return new uE($)}});var XJ=M((JV)=>{Object.defineProperty(JV,"__esModule",{value:!0});JV.BaseServerInterceptingCall=JV.ServerInterceptingCall=JV.ResponderBuilder=JV.ServerListenerBuilder=void 0;JV.isInterceptingServerListener=US;JV.getServerInterceptingCall=GS;var oq=P0(),o0=i(),iY=s("http2"),nE=x8(),iE=s("zlib"),JS=_5(),tE=U0(),QS=s("tls"),rE=iq(),eE="server_call";function qY($){tE.trace(o0.LogVerbosity.DEBUG,eE,$)}class $V{constructor(){this.metadata=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withOnReceiveMetadata($){return this.metadata=$,this}withOnReceiveMessage($){return this.message=$,this}withOnReceiveHalfClose($){return this.halfClose=$,this}withOnCancel($){return this.cancel=$,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveHalfClose:this.halfClose,onCancel:this.cancel}}}JV.ServerListenerBuilder=$V;function US($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class YV{constructor($,Y){this.listener=$,this.nextListener=Y,this.cancelled=!1,this.processingMetadata=!1,this.hasPendingMessage=!1,this.pendingMessage=null,this.processingMessage=!1,this.hasPendingHalfClose=!1}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingHalfClose(){if(this.hasPendingHalfClose)this.nextListener.onReceiveHalfClose(),this.hasPendingHalfClose=!1}onReceiveMetadata($){if(this.cancelled)return;this.processingMetadata=!0,this.listener.onReceiveMetadata($,(Y)=>{if(this.processingMetadata=!1,this.cancelled)return;this.nextListener.onReceiveMetadata(Y),this.processPendingMessage(),this.processPendingHalfClose()})}onReceiveMessage($){if(this.cancelled)return;this.processingMessage=!0,this.listener.onReceiveMessage($,(Y)=>{if(this.processingMessage=!1,this.cancelled)return;if(this.processingMetadata)this.pendingMessage=Y,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(Y),this.processPendingHalfClose()})}onReceiveHalfClose(){if(this.cancelled)return;this.listener.onReceiveHalfClose(()=>{if(this.cancelled)return;if(this.processingMetadata||this.processingMessage)this.hasPendingHalfClose=!0;else this.nextListener.onReceiveHalfClose()})}onCancel(){this.cancelled=!0,this.listener.onCancel(),this.nextListener.onCancel()}}class TV{constructor(){this.start=void 0,this.metadata=void 0,this.message=void 0,this.status=void 0}withStart($){return this.start=$,this}withSendMetadata($){return this.metadata=$,this}withSendMessage($){return this.message=$,this}withSendStatus($){return this.status=$,this}build(){return{start:this.start,sendMetadata:this.metadata,sendMessage:this.message,sendStatus:this.status}}}JV.ResponderBuilder=TV;var rq={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveHalfClose:($)=>{$()},onCancel:()=>{}},aq={start:($)=>{$()},sendMetadata:($,Y)=>{Y($)},sendMessage:($,Y)=>{Y($)},sendStatus:($,Y)=>{Y($)}};class qV{constructor($,Y){var T,q,X,J;this.nextCall=$,this.processingMetadata=!1,this.sentMetadata=!1,this.processingMessage=!1,this.pendingMessage=null,this.pendingMessageCallback=null,this.pendingStatus=null,this.responder={start:(T=Y===null||Y===void 0?void 0:Y.start)!==null&&T!==void 0?T:aq.start,sendMetadata:(q=Y===null||Y===void 0?void 0:Y.sendMetadata)!==null&&q!==void 0?q:aq.sendMetadata,sendMessage:(X=Y===null||Y===void 0?void 0:Y.sendMessage)!==null&&X!==void 0?X:aq.sendMessage,sendStatus:(J=Y===null||Y===void 0?void 0:Y.sendStatus)!==null&&J!==void 0?J:aq.sendStatus}}processPendingMessage(){if(this.pendingMessageCallback)this.nextCall.sendMessage(this.pendingMessage,this.pendingMessageCallback),this.pendingMessage=null,this.pendingMessageCallback=null}processPendingStatus(){if(this.pendingStatus)this.nextCall.sendStatus(this.pendingStatus),this.pendingStatus=null}start($){this.responder.start((Y)=>{var T,q,X,J;let Q={onReceiveMetadata:(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)!==null&&T!==void 0?T:rq.onReceiveMetadata,onReceiveMessage:(q=Y===null||Y===void 0?void 0:Y.onReceiveMessage)!==null&&q!==void 0?q:rq.onReceiveMessage,onReceiveHalfClose:(X=Y===null||Y===void 0?void 0:Y.onReceiveHalfClose)!==null&&X!==void 0?X:rq.onReceiveHalfClose,onCancel:(J=Y===null||Y===void 0?void 0:Y.onCancel)!==null&&J!==void 0?J:rq.onCancel},U=new YV(Q,$);this.nextCall.start(U)})}sendMetadata($){this.processingMetadata=!0,this.sentMetadata=!0,this.responder.sendMetadata($,(Y)=>{this.processingMetadata=!1,this.nextCall.sendMetadata(Y),this.processPendingMessage(),this.processPendingStatus()})}sendMessage($,Y){if(this.processingMessage=!0,!this.sentMetadata)this.sendMetadata(new oq.Metadata);this.responder.sendMessage($,(T)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=T,this.pendingMessageCallback=Y;else this.nextCall.sendMessage(T,Y)})}sendStatus($){this.responder.sendStatus($,(Y)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=Y;else this.nextCall.sendStatus(Y)})}startRead(){this.nextCall.startRead()}getPeer(){return this.nextCall.getPeer()}getDeadline(){return this.nextCall.getDeadline()}getHost(){return this.nextCall.getHost()}getAuthContext(){return this.nextCall.getAuthContext()}getConnectionInfo(){return this.nextCall.getConnectionInfo()}getMetricsRecorder(){return this.nextCall.getMetricsRecorder()}}JV.ServerInterceptingCall=qV;var XV="grpc-accept-encoding",TJ="grpc-encoding",aE="grpc-message",oE="grpc-status",YJ="grpc-timeout",ZS=/(\d{1,8})\s*([HMSmun])/,KS={H:3600000,M:60000,S:1000,m:1,u:0.001,n:0.000001},AS={[XV]:"identity,deflate,gzip",[TJ]:"identity"},sE={[iY.constants.HTTP2_HEADER_STATUS]:iY.constants.HTTP_STATUS_OK,[iY.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},WS={waitForTrailers:!0};class qJ{constructor($,Y,T,q,X){var J,Q;if(this.stream=$,this.callEventTracker=T,this.handler=q,this.listener=null,this.deadlineTimer=null,this.deadline=1/0,this.maxSendMessageSize=o0.DEFAULT_MAX_SEND_MESSAGE_LENGTH,this.maxReceiveMessageSize=o0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.cancelled=!1,this.metadataSent=!1,this.wantTrailers=!1,this.cancelNotified=!1,this.incomingEncoding="identity",this.readQueue=[],this.isReadPending=!1,this.receivedHalfClose=!1,this.streamEnded=!1,this.metricsRecorder=new rE.PerRequestMetricRecorder,this.stream.once("error",(W)=>{}),this.stream.once("close",()=>{var W;if(qY("Request to method "+((W=this.handler)===null||W===void 0?void 0:W.path)+" stream closed with rstCode "+this.stream.rstCode),this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!1),this.callEventTracker.onCallEnd({code:o0.Status.CANCELLED,details:"Stream closed before sending status",metadata:null});this.notifyOnCancel()}),this.stream.on("data",(W)=>{this.handleDataFrame(W)}),this.stream.pause(),this.stream.on("end",()=>{this.handleEndEvent()}),"grpc.max_send_message_length"in X)this.maxSendMessageSize=X["grpc.max_send_message_length"];if("grpc.max_receive_message_length"in X)this.maxReceiveMessageSize=X["grpc.max_receive_message_length"];this.host=(J=Y[":authority"])!==null&&J!==void 0?J:Y.host,this.decoder=new JS.StreamDecoder(this.maxReceiveMessageSize);let U=oq.Metadata.fromHttp2Headers(Y);if(tE.isTracerEnabled(eE))qY("Request to "+this.handler.path+" received headers "+JSON.stringify(U.toJSON()));let Z=U.get(YJ);if(Z.length>0)this.handleTimeoutHeader(Z[0]);let K=U.get(TJ);if(K.length>0)this.incomingEncoding=K[0];U.remove(YJ),U.remove(TJ),U.remove(XV),U.remove(iY.constants.HTTP2_HEADER_ACCEPT_ENCODING),U.remove(iY.constants.HTTP2_HEADER_TE),U.remove(iY.constants.HTTP2_HEADER_CONTENT_TYPE),this.metadata=U;let A=(Q=$.session)===null||Q===void 0?void 0:Q.socket;this.connectionInfo={localAddress:A===null||A===void 0?void 0:A.localAddress,localPort:A===null||A===void 0?void 0:A.localPort,remoteAddress:A===null||A===void 0?void 0:A.remoteAddress,remotePort:A===null||A===void 0?void 0:A.remotePort},this.shouldSendMetrics=!!X["grpc.server_call_metric_recording"]}handleTimeoutHeader($){let Y=$.toString().match(ZS);if(Y===null){let X={code:o0.Status.INTERNAL,details:`Invalid ${YJ} value "${$}"`,metadata:null};process.nextTick(()=>{this.sendStatus(X)});return}let T=+Y[1]*KS[Y[2]]|0,q=new Date;this.deadline=q.setMilliseconds(q.getMilliseconds()+T),this.deadlineTimer=setTimeout(()=>{let X={code:o0.Status.DEADLINE_EXCEEDED,details:"Deadline exceeded",metadata:null};this.sendStatus(X)},T)}checkCancelled(){if(!this.cancelled&&(this.stream.destroyed||this.stream.closed))this.notifyOnCancel(),this.cancelled=!0;return this.cancelled}notifyOnCancel(){if(this.cancelNotified)return;if(this.cancelNotified=!0,this.cancelled=!0,process.nextTick(()=>{var $;($=this.listener)===null||$===void 0||$.onCancel()}),this.deadlineTimer)clearTimeout(this.deadlineTimer);this.stream.resume()}maybeSendMetadata(){if(!this.metadataSent)this.sendMetadata(new oq.Metadata)}serializeMessage($){let Y=this.handler.serialize($),T=Y.byteLength,q=Buffer.allocUnsafe(T+5);return q.writeUInt8(0,0),q.writeUInt32BE(T,1),Y.copy(q,5),q}decompressMessage($,Y){let T=$.subarray(5);if(Y==="identity")return T;else if(Y==="deflate"||Y==="gzip"){let q;if(Y==="deflate")q=iE.createInflate();else q=iE.createGunzip();return new Promise((X,J)=>{let Q=0,U=[];q.on("data",(Z)=>{if(U.push(Z),Q+=Z.byteLength,this.maxReceiveMessageSize!==-1&&Q>this.maxReceiveMessageSize)q.destroy(),J({code:o0.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`})}),q.on("end",()=>{X(Buffer.concat(U))}),q.write(T),q.end()})}else return Promise.reject({code:o0.Status.UNIMPLEMENTED,details:`Received message compressed with unsupported encoding "${Y}"`})}async decompressAndMaybePush($){if($.type!=="COMPRESSED")throw Error(`Invalid queue entry type: ${$.type}`);let T=$.compressedMessage.readUInt8(0)===1?this.incomingEncoding:"identity",q;try{q=await this.decompressMessage($.compressedMessage,T)}catch(X){this.sendStatus(X);return}try{$.parsedMessage=this.handler.deserialize(q)}catch(X){this.sendStatus({code:o0.Status.INTERNAL,details:`Error deserializing request: ${X.message}`});return}$.type="READABLE",this.maybePushNextMessage()}maybePushNextMessage(){if(this.listener&&this.isReadPending&&this.readQueue.length>0&&this.readQueue[0].type!=="COMPRESSED"){this.isReadPending=!1;let $=this.readQueue.shift();if($.type==="READABLE")this.listener.onReceiveMessage($.parsedMessage);else this.listener.onReceiveHalfClose()}}handleDataFrame($){var Y;if(this.checkCancelled())return;qY("Request to "+this.handler.path+" received data frame of size "+$.length);let T;try{T=this.decoder.write($)}catch(q){this.sendStatus({code:o0.Status.RESOURCE_EXHAUSTED,details:q.message});return}for(let q of T){this.stream.pause();let X={type:"COMPRESSED",compressedMessage:q,parsedMessage:null};this.readQueue.push(X),this.decompressAndMaybePush(X),(Y=this.callEventTracker)===null||Y===void 0||Y.addMessageReceived()}}handleEndEvent(){this.readQueue.push({type:"HALF_CLOSE",compressedMessage:null,parsedMessage:null}),this.receivedHalfClose=!0,this.maybePushNextMessage()}start($){if(qY("Request to "+this.handler.path+" start called"),this.checkCancelled())return;this.listener=$,$.onReceiveMetadata(this.metadata)}sendMetadata($){if(this.checkCancelled())return;if(this.metadataSent)return;this.metadataSent=!0;let Y=$?$.toHttp2Headers():null,T=Object.assign(Object.assign(Object.assign({},sE),AS),Y);this.stream.respond(T,WS)}sendMessage($,Y){if(this.checkCancelled())return;let T;try{T=this.serializeMessage($)}catch(q){this.sendStatus({code:o0.Status.INTERNAL,details:`Error serializing response: ${(0,nE.getErrorMessage)(q)}`,metadata:null});return}if(this.maxSendMessageSize!==-1&&T.length-5>this.maxSendMessageSize){this.sendStatus({code:o0.Status.RESOURCE_EXHAUSTED,details:`Sent message larger than max (${T.length} vs. ${this.maxSendMessageSize})`,metadata:null});return}this.maybeSendMetadata(),qY("Request to "+this.handler.path+" sent data frame of size "+T.length),this.stream.write(T,(q)=>{var X;if(q){this.sendStatus({code:o0.Status.INTERNAL,details:`Error writing message: ${(0,nE.getErrorMessage)(q)}`,metadata:null});return}(X=this.callEventTracker)===null||X===void 0||X.addMessageSent(),Y()})}sendStatus($){var Y,T,q;if(this.checkCancelled())return;qY("Request to method "+((Y=this.handler)===null||Y===void 0?void 0:Y.path)+" ended with status code: "+o0.Status[$.code]+" details: "+$.details);let X=(q=(T=$.metadata)===null||T===void 0?void 0:T.clone())!==null&&q!==void 0?q:new oq.Metadata;if(this.shouldSendMetrics)X.set(rE.GRPC_METRICS_HEADER,this.metricsRecorder.serialize());if(this.metadataSent)if(!this.wantTrailers)this.wantTrailers=!0,this.stream.once("wantTrailers",()=>{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign({[oE]:$.code,[aE]:encodeURI($.details)},X.toHttp2Headers());this.stream.sendTrailers(J),this.notifyOnCancel()}),this.stream.end();else this.notifyOnCancel();else{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign(Object.assign({[oE]:$.code,[aE]:encodeURI($.details)},sE),X.toHttp2Headers());this.stream.respond(J,{endStream:!0}),this.notifyOnCancel()}}startRead(){if(qY("Request to "+this.handler.path+" startRead called"),this.checkCancelled())return;if(this.isReadPending=!0,this.readQueue.length===0){if(!this.receivedHalfClose)this.stream.resume()}else this.maybePushNextMessage()}getPeer(){var $;let Y=($=this.stream.session)===null||$===void 0?void 0:$.socket;if(Y===null||Y===void 0?void 0:Y.remoteAddress)if(Y.remotePort)return`${Y.remoteAddress}:${Y.remotePort}`;else return Y.remoteAddress;else return"unknown"}getDeadline(){return this.deadline}getHost(){return this.host}getAuthContext(){var $;if((($=this.stream.session)===null||$===void 0?void 0:$.socket)instanceof QS.TLSSocket){let Y=this.stream.session.socket.getPeerCertificate();return{transportSecurityType:"ssl",sslPeerCertificate:Y.raw?Y:void 0}}else return{}}getConnectionInfo(){return this.connectionInfo}getMetricsRecorder(){return this.metricsRecorder}}JV.BaseServerInterceptingCall=qJ;function GS($,Y,T,q,X,J){let Q={path:X.path,requestStream:X.type==="clientStream"||X.type==="bidi",responseStream:X.type==="serverStream"||X.type==="bidi",requestDeserialize:X.deserialize,responseSerialize:X.serialize},U=new qJ(Y,T,q,X,J);return $.reduce((Z,K)=>{return K(Q,Z)},U)}});var EV=M((k$)=>{var HS=k$&&k$.__runInitializers||function($,Y,T){var q=arguments.length>2;for(var X=0;X<Y.length;X++)T=q?Y[X].call($,T):Y[X].call($);return q?T:void 0},zS=k$&&k$.__esDecorate||function($,Y,T,q,X,J){function Q(B){if(B!==void 0&&typeof B!=="function")throw TypeError("Function expected");return B}var U=q.kind,Z=U==="getter"?"get":U==="setter"?"set":"value",K=!Y&&$?q.static?$:$.prototype:null,A=Y||(K?Object.getOwnPropertyDescriptor(K,q.name):{}),W,E=!1;for(var D=T.length-1;D>=0;D--){var F={};for(var H in q)F[H]=H==="access"?{}:q[H];for(var H in q.access)F.access[H]=q.access[H];F.addInitializer=function(B){if(E)throw TypeError("Cannot add initializers after decoration has completed");J.push(Q(B||null))};var V=(0,T[D])(U==="accessor"?{get:A.get,set:A.set}:A[Z],F);if(U==="accessor"){if(V===void 0)continue;if(V===null||typeof V!=="object")throw TypeError("Object expected");if(W=Q(V.get))A.get=W;if(W=Q(V.set))A.set=W;if(W=Q(V.init))X.unshift(W)}else if(W=Q(V))if(U==="field")X.unshift(W);else A[Z]=W}if(K)Object.defineProperty(K,q.name,A);E=!0};Object.defineProperty(k$,"__esModule",{value:!0});k$.Server=void 0;var s0=s("http2"),IS=s("util"),N0=i(),oY=CE(),JJ=lq(),UV=B1(),aY=U0(),x$=r0(),y1=p0(),M0=y$(),ZV=XJ(),rY=2147483647,QJ=2147483647,MS=20000,KV=2147483647,{HTTP2_HEADER_PATH:AV}=s0.constants,BS="server",WV=Buffer.from("max_age");function GV($){aY.trace(N0.LogVerbosity.DEBUG,"server_call",$)}function RS(){}function OS($){return function(Y,T){return IS.deprecate(Y,$)}}function UJ($){return{code:N0.Status.UNIMPLEMENTED,details:`The server does not implement the method ${$}`}}function PS($,Y){let T=UJ(Y);switch($){case"unary":return(q,X)=>{X(T,null)};case"clientStream":return(q,X)=>{X(T,null)};case"serverStream":return(q)=>{q.emit("error",T)};case"bidi":return(q)=>{q.emit("error",T)};default:throw Error(`Invalid handlerType ${$}`)}}var LS=(()=>{var $;let Y=[],T;return $=class{constructor(X){var J,Q,U,Z,K,A;if(this.boundPorts=(HS(this,Y),new Map),this.http2Servers=new Map,this.sessionIdleTimeouts=new Map,this.handlers=new Map,this.sessions=new Map,this.started=!1,this.shutdown=!1,this.serverAddressString="null",this.channelzEnabled=!0,this.options=X!==null&&X!==void 0?X:{},this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new M0.ChannelzTraceStub,this.callTracker=new M0.ChannelzCallTrackerStub,this.listenerChildrenTracker=new M0.ChannelzChildrenTrackerStub,this.sessionChildrenTracker=new M0.ChannelzChildrenTrackerStub;else this.channelzTrace=new M0.ChannelzTrace,this.callTracker=new M0.ChannelzCallTracker,this.listenerChildrenTracker=new M0.ChannelzChildrenTracker,this.sessionChildrenTracker=new M0.ChannelzChildrenTracker;if(this.channelzRef=(0,M0.registerChannelzServer)("server",()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Server created"),this.maxConnectionAgeMs=(J=this.options["grpc.max_connection_age_ms"])!==null&&J!==void 0?J:rY,this.maxConnectionAgeGraceMs=(Q=this.options["grpc.max_connection_age_grace_ms"])!==null&&Q!==void 0?Q:rY,this.keepaliveTimeMs=(U=this.options["grpc.keepalive_time_ms"])!==null&&U!==void 0?U:QJ,this.keepaliveTimeoutMs=(Z=this.options["grpc.keepalive_timeout_ms"])!==null&&Z!==void 0?Z:MS,this.sessionIdleTimeout=(K=this.options["grpc.max_connection_idle_ms"])!==null&&K!==void 0?K:KV,this.commonServerOptions={maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER},"grpc-node.max_session_memory"in this.options)this.commonServerOptions.maxSessionMemory=this.options["grpc-node.max_session_memory"];else this.commonServerOptions.maxSessionMemory=Number.MAX_SAFE_INTEGER;if("grpc.max_concurrent_streams"in this.options)this.commonServerOptions.settings={maxConcurrentStreams:this.options["grpc.max_concurrent_streams"]};this.interceptors=(A=this.options.interceptors)!==null&&A!==void 0?A:[],this.trace("Server constructed")}getChannelzInfo(){return{trace:this.channelzTrace,callTracker:this.callTracker,listenerChildren:this.listenerChildrenTracker.getChildLists(),sessionChildren:this.sessionChildrenTracker.getChildLists()}}getChannelzSessionInfo(X){var J,Q,U;let Z=this.sessions.get(X),K=X.socket,A=K.remoteAddress?(0,x$.stringToSubchannelAddress)(K.remoteAddress,K.remotePort):null,W=K.localAddress?(0,x$.stringToSubchannelAddress)(K.localAddress,K.localPort):null,E;if(X.encrypted){let F=K,H=F.getCipher(),V=F.getCertificate(),B=F.getPeerCertificate();E={cipherSuiteStandardName:(J=H.standardName)!==null&&J!==void 0?J:null,cipherSuiteOtherName:H.standardName?null:H.name,localCertificate:V&&"raw"in V?V.raw:null,remoteCertificate:B&&"raw"in B?B.raw:null}}else E=null;return{remoteAddress:A,localAddress:W,security:E,remoteName:null,streamsStarted:Z.streamTracker.callsStarted,streamsSucceeded:Z.streamTracker.callsSucceeded,streamsFailed:Z.streamTracker.callsFailed,messagesSent:Z.messagesSent,messagesReceived:Z.messagesReceived,keepAlivesSent:Z.keepAlivesSent,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:Z.streamTracker.lastCallStartedTimestamp,lastMessageSentTimestamp:Z.lastMessageSentTimestamp,lastMessageReceivedTimestamp:Z.lastMessageReceivedTimestamp,localFlowControlWindow:(Q=X.state.localWindowSize)!==null&&Q!==void 0?Q:null,remoteFlowControlWindow:(U=X.state.remoteWindowSize)!==null&&U!==void 0?U:null}}trace(X){aY.trace(N0.LogVerbosity.DEBUG,BS,"("+this.channelzRef.id+") "+X)}keepaliveTrace(X){aY.trace(N0.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+X)}addProtoService(){throw Error("Not implemented. Use addService() instead")}addService(X,J){if(X===null||typeof X!=="object"||J===null||typeof J!=="object")throw Error("addService() requires two objects as arguments");let Q=Object.keys(X);if(Q.length===0)throw Error("Cannot add an empty service to a server");Q.forEach((U)=>{let Z=X[U],K;if(Z.requestStream)if(Z.responseStream)K="bidi";else K="clientStream";else if(Z.responseStream)K="serverStream";else K="unary";let A=J[U],W;if(A===void 0&&typeof Z.originalName==="string")A=J[Z.originalName];if(A!==void 0)W=A.bind(J);else W=PS(K,U);if(this.register(Z.path,W,Z.responseSerialize,Z.requestDeserialize,K)===!1)throw Error(`Method handler for ${Z.path} already provided.`)})}removeService(X){if(X===null||typeof X!=="object")throw Error("removeService() requires object as argument");Object.keys(X).forEach((Q)=>{let U=X[Q];this.unregister(U.path)})}bind(X,J){throw Error("Not implemented. Use bindAsync() instead")}experimentalRegisterListenerToChannelz(X){return(0,M0.registerChannelzSocket)((0,x$.subchannelAddressToString)(X),()=>{return{localAddress:X,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalUnregisterListenerFromChannelz(X){(0,M0.unregisterChannelzRef)(X)}createHttp2Server(X){let J;if(X._isSecure()){let Q=X._getConstructorOptions(),U=X._getSecureContextOptions(),Z=Object.assign(Object.assign(Object.assign(Object.assign({},this.commonServerOptions),Q),U),{enableTrace:this.options["grpc-node.tls_enable_trace"]===1}),K=U!==null;this.trace("Initial credentials valid: "+K),J=s0.createSecureServer(Z),J.prependListener("connection",(W)=>{if(!K)this.trace("Dropped connection from "+JSON.stringify(W.address())+" due to unloaded credentials"),W.destroy()}),J.on("secureConnection",(W)=>{W.on("error",(E)=>{this.trace("An incoming TLS connection closed with error: "+E.message)})});let A=(W)=>{if(W){let E=J;try{E.setSecureContext(W)}catch(D){aY.log(N0.LogVerbosity.ERROR,"Failed to set secure context with error "+D.message),W=null}}K=W!==null,this.trace("Post-update credentials valid: "+K)};X._addWatcher(A),J.on("close",()=>{X._removeWatcher(A)})}else J=s0.createServer(this.commonServerOptions);return J.setTimeout(0,RS),this._setupHandlers(J,X._getInterceptors()),J}bindOneAddress(X,J){this.trace("Attempting to bind "+(0,x$.subchannelAddressToString)(X));let Q=this.createHttp2Server(J.credentials);return new Promise((U,Z)=>{let K=(A)=>{this.trace("Failed to bind "+(0,x$.subchannelAddressToString)(X)+" with error "+A.message),U({port:"port"in X?X.port:1,error:A.message})};Q.once("error",K),Q.listen(X,()=>{let A=Q.address(),W;if(typeof A==="string")W={path:A};else W={host:A.address,port:A.port};let E=this.experimentalRegisterListenerToChannelz(W);this.listenerChildrenTracker.refChild(E),this.http2Servers.set(Q,{channelzRef:E,sessions:new Set,ownsChannelzRef:!0}),J.listeningServers.add(Q),this.trace("Successfully bound "+(0,x$.subchannelAddressToString)(W)),U({port:"port"in W?W.port:1}),Q.removeListener("error",K)})})}async bindManyPorts(X,J){if(X.length===0)return{count:0,port:0,errors:[]};if((0,x$.isTcpSubchannelAddress)(X[0])&&X[0].port===0){let Q=await this.bindOneAddress(X[0],J);if(Q.error){let U=await this.bindManyPorts(X.slice(1),J);return Object.assign(Object.assign({},U),{errors:[Q.error,...U.errors]})}else{let U=X.slice(1).map((A)=>(0,x$.isTcpSubchannelAddress)(A)?{host:A.host,port:Q.port}:A),Z=await Promise.all(U.map((A)=>this.bindOneAddress(A,J))),K=[Q,...Z];return{count:K.filter((A)=>A.error===void 0).length,port:Q.port,errors:K.filter((A)=>A.error).map((A)=>A.error)}}}else{let Q=await Promise.all(X.map((U)=>this.bindOneAddress(U,J)));return{count:Q.filter((U)=>U.error===void 0).length,port:Q[0].port,errors:Q.filter((U)=>U.error).map((U)=>U.error)}}}async bindAddressList(X,J){let Q=await this.bindManyPorts(X,J);if(Q.count>0){if(Q.count<X.length)aY.log(N0.LogVerbosity.INFO,`WARNING Only ${Q.count} addresses added out of total ${X.length} resolved`);return Q.port}else{let U=`No address added out of total ${X.length} resolved`;throw aY.log(N0.LogVerbosity.ERROR,U),Error(`${U} errors: [${Q.errors.join(",")}]`)}}resolvePort(X){return new Promise((J,Q)=>{let U=!1,Z=(A,W,E,D)=>{if(U)return!0;if(U=!0,!A.ok)return Q(Error(A.error.details)),!0;let F=[].concat(...A.value.map((H)=>H.addresses));if(F.length===0)return Q(Error(`No addresses resolved for port ${X}`)),!0;return J(F),!0};(0,UV.createResolver)(X,Z,this.options).updateResolution()})}async bindPort(X,J){let Q=await this.resolvePort(X);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");let U=await this.bindAddressList(Q,J);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");return U}normalizePort(X){let J=(0,y1.parseUri)(X);if(J===null)throw Error(`Could not parse port "${X}"`);let Q=(0,UV.mapUriDefaultScheme)(J);if(Q===null)throw Error(`Could not get a default scheme for port "${X}"`);return Q}bindAsync(X,J,Q){if(this.shutdown)throw Error("bindAsync called after shutdown");if(typeof X!=="string")throw TypeError("port must be a string");if(J===null||!(J instanceof JJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(typeof Q!=="function")throw TypeError("callback must be a function");this.trace("bindAsync port="+X);let U=this.normalizePort(X),Z=(E,D)=>{process.nextTick(()=>Q(E,D))},K=this.boundPorts.get((0,y1.uriToString)(U));if(K){if(!J._equals(K.credentials)){Z(Error(`${X} already bound with incompatible credentials`),0);return}if(K.cancelled=!1,K.completionPromise)K.completionPromise.then((E)=>Q(null,E),(E)=>Q(E,0));else Z(null,K.portNumber);return}K={mapKey:(0,y1.uriToString)(U),originalUri:U,completionPromise:null,cancelled:!1,portNumber:0,credentials:J,listeningServers:new Set};let A=(0,y1.splitHostPort)(U.path),W=this.bindPort(U,K);if(K.completionPromise=W,(A===null||A===void 0?void 0:A.port)===0)W.then((E)=>{let D={scheme:U.scheme,authority:U.authority,path:(0,y1.combineHostPort)({host:A.host,port:E})};K.mapKey=(0,y1.uriToString)(D),K.completionPromise=null,K.portNumber=E,this.boundPorts.set(K.mapKey,K),Q(null,E)},(E)=>{Q(E,0)});else this.boundPorts.set(K.mapKey,K),W.then((E)=>{K.completionPromise=null,K.portNumber=E,Q(null,E)},(E)=>{Q(E,0)})}registerInjectorToChannelz(){return(0,M0.registerChannelzSocket)("injector",()=>{return{localAddress:null,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalCreateConnectionInjectorWithChannelzRef(X,J,Q=!1){if(X===null||!(X instanceof JJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(this.channelzEnabled)this.listenerChildrenTracker.refChild(J);let U=this.createHttp2Server(X),Z=new Set;return this.http2Servers.set(U,{channelzRef:J,sessions:Z,ownsChannelzRef:Q}),{injectConnection:(K)=>{U.emit("connection",K)},drain:(K)=>{var A,W;for(let E of Z)this.closeSession(E);(W=(A=setTimeout(()=>{for(let E of Z)E.destroy(s0.constants.NGHTTP2_CANCEL)},K)).unref)===null||W===void 0||W.call(A)},destroy:()=>{this.closeServer(U);for(let K of Z)this.closeSession(K)}}}createConnectionInjector(X){if(X===null||!(X instanceof JJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");let J=this.registerInjectorToChannelz();return this.experimentalCreateConnectionInjectorWithChannelzRef(X,J,!0)}closeServer(X,J){this.trace("Closing server with address "+JSON.stringify(X.address()));let Q=this.http2Servers.get(X);X.close(()=>{if(Q&&Q.ownsChannelzRef)this.listenerChildrenTracker.unrefChild(Q.channelzRef),(0,M0.unregisterChannelzRef)(Q.channelzRef);this.http2Servers.delete(X),J===null||J===void 0||J()})}closeSession(X,J){var Q;this.trace("Closing session initiated by "+((Q=X.socket)===null||Q===void 0?void 0:Q.remoteAddress));let U=this.sessions.get(X),Z=()=>{if(U)this.sessionChildrenTracker.unrefChild(U.ref),(0,M0.unregisterChannelzRef)(U.ref);J===null||J===void 0||J()};if(X.closed)queueMicrotask(Z);else X.close(Z)}completeUnbind(X){for(let J of X.listeningServers){let Q=this.http2Servers.get(J);if(this.closeServer(J,()=>{X.listeningServers.delete(J)}),Q)for(let U of Q.sessions)this.closeSession(U)}this.boundPorts.delete(X.mapKey)}unbind(X){this.trace("unbind port="+X);let J=this.normalizePort(X),Q=(0,y1.splitHostPort)(J.path);if((Q===null||Q===void 0?void 0:Q.port)===0)throw Error("Cannot unbind port 0");let U=this.boundPorts.get((0,y1.uriToString)(J));if(U)if(this.trace("unbinding "+U.mapKey+" originally bound as "+(0,y1.uriToString)(U.originalUri)),U.completionPromise)U.cancelled=!0;else this.completeUnbind(U)}drain(X,J){var Q,U;this.trace("drain port="+X+" graceTimeMs="+J);let Z=this.normalizePort(X),K=(0,y1.splitHostPort)(Z.path);if((K===null||K===void 0?void 0:K.port)===0)throw Error("Cannot drain port 0");let A=this.boundPorts.get((0,y1.uriToString)(Z));if(!A)return;let W=new Set;for(let E of A.listeningServers){let D=this.http2Servers.get(E);if(D)for(let F of D.sessions)W.add(F),this.closeSession(F,()=>{W.delete(F)})}(U=(Q=setTimeout(()=>{for(let E of W)E.destroy(s0.constants.NGHTTP2_CANCEL)},J)).unref)===null||U===void 0||U.call(Q)}forceShutdown(){for(let X of this.boundPorts.values())X.cancelled=!0;this.boundPorts.clear();for(let X of this.http2Servers.keys())this.closeServer(X);this.sessions.forEach((X,J)=>{this.closeSession(J),J.destroy(s0.constants.NGHTTP2_CANCEL)}),this.sessions.clear(),(0,M0.unregisterChannelzRef)(this.channelzRef),this.shutdown=!0}register(X,J,Q,U,Z){if(this.handlers.has(X))return!1;return this.handlers.set(X,{func:J,serialize:Q,deserialize:U,type:Z,path:X}),!0}unregister(X){return this.handlers.delete(X)}start(){if(this.http2Servers.size===0||[...this.http2Servers.keys()].every((X)=>!X.listening))throw Error("server must be bound in order to start");if(this.started===!0)throw Error("server is already started");this.started=!0}tryShutdown(X){var J;let Q=(K)=>{(0,M0.unregisterChannelzRef)(this.channelzRef),X(K)},U=0;function Z(){if(U--,U===0)Q()}this.shutdown=!0;for(let[K,A]of this.http2Servers.entries()){U++;let W=A.channelzRef.name;this.trace("Waiting for server "+W+" to close"),this.closeServer(K,()=>{this.trace("Server "+W+" finished closing"),Z()});for(let E of A.sessions.keys()){U++;let D=(J=E.socket)===null||J===void 0?void 0:J.remoteAddress;this.trace("Waiting for session "+D+" to close"),this.closeSession(E,()=>{this.trace("Session "+D+" finished closing"),Z()})}}if(U===0)Q()}addHttp2Port(){throw Error("Not yet implemented")}getChannelzRef(){return this.channelzRef}_verifyContentType(X,J){let Q=J[s0.constants.HTTP2_HEADER_CONTENT_TYPE];if(typeof Q!=="string"||!Q.startsWith("application/grpc"))return X.respond({[s0.constants.HTTP2_HEADER_STATUS]:s0.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE},{endStream:!0}),!1;return!0}_retrieveHandler(X){GV("Received call to method "+X+" at address "+this.serverAddressString);let J=this.handlers.get(X);if(J===void 0)return GV("No handler registered for method "+X+". Sending UNIMPLEMENTED status."),null;return J}_respondWithError(X,J,Q=null){var U,Z;let K=Object.assign({"grpc-status":(U=X.code)!==null&&U!==void 0?U:N0.Status.INTERNAL,"grpc-message":X.details,[s0.constants.HTTP2_HEADER_STATUS]:s0.constants.HTTP_STATUS_OK,[s0.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},(Z=X.metadata)===null||Z===void 0?void 0:Z.toHttp2Headers());J.respond(K,{endStream:!0}),this.callTracker.addCallFailed(),Q===null||Q===void 0||Q.streamTracker.addCallFailed()}_channelzHandler(X,J,Q){this.onStreamOpened(J);let U=this.sessions.get(J.session);if(this.callTracker.addCallStarted(),U===null||U===void 0||U.streamTracker.addCallStarted(),!this._verifyContentType(J,Q)){this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed();return}let Z=Q[AV],K=this._retrieveHandler(Z);if(!K){this._respondWithError(UJ(Z),J,U);return}let A={addMessageSent:()=>{if(U)U.messagesSent+=1,U.lastMessageSentTimestamp=new Date},addMessageReceived:()=>{if(U)U.messagesReceived+=1,U.lastMessageReceivedTimestamp=new Date},onCallEnd:(E)=>{if(E.code===N0.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()},onStreamEnd:(E)=>{if(U)if(E)U.streamTracker.addCallSucceeded();else U.streamTracker.addCallFailed()}},W=(0,ZV.getServerInterceptingCall)([...X,...this.interceptors],J,Q,A,K,this.options);if(!this._runHandlerForCall(W,K))this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed(),W.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${K.type}`})}_streamHandler(X,J,Q){if(this.onStreamOpened(J),this._verifyContentType(J,Q)!==!0)return;let U=Q[AV],Z=this._retrieveHandler(U);if(!Z){this._respondWithError(UJ(U),J,null);return}let K=(0,ZV.getServerInterceptingCall)([...X,...this.interceptors],J,Q,null,Z,this.options);if(!this._runHandlerForCall(K,Z))K.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${Z.type}`})}_runHandlerForCall(X,J){let{type:Q}=J;if(Q==="unary")wS(X,J);else if(Q==="clientStream")SS(X,J);else if(Q==="serverStream")CS(X,J);else if(Q==="bidi")yS(X,J);else return!1;return!0}_setupHandlers(X,J){if(X===null)return;let Q=X.address(),U="null";if(Q)if(typeof Q==="string")U=Q;else U=Q.address+":"+Q.port;this.serverAddressString=U;let Z=this.channelzEnabled?this._channelzHandler:this._streamHandler,K=this.channelzEnabled?this._channelzSessionHandler(X):this._sessionHandler(X);X.on("stream",Z.bind(this,J)),X.on("session",K)}_sessionHandler(X){return(J)=>{var Q,U;(Q=this.http2Servers.get(X))===null||Q===void 0||Q.sessions.add(J);let Z=null,K=null,A=null,W=!1,E=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==rY){let B=this.maxConnectionAgeMs/10,S=Math.random()*B*2-B;Z=setTimeout(()=>{var v,z;W=!0,this.trace("Connection dropped by max connection age: "+((v=J.socket)===null||v===void 0?void 0:v.remoteAddress));try{J.goaway(s0.constants.NGHTTP2_NO_ERROR,2147483647,WV)}catch(_){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==rY)K=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(z=K.unref)===null||z===void 0||z.call(K)},this.maxConnectionAgeMs+S),(U=Z.unref)===null||U===void 0||U.call(Z)}let D=()=>{if(A)clearTimeout(A),A=null},F=()=>{return!J.destroyed&&this.keepaliveTimeMs<QJ&&this.keepaliveTimeMs>0},H,V=()=>{var B;if(!F())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),A=setTimeout(()=>{D(),H()},this.keepaliveTimeMs),(B=A.unref)===null||B===void 0||B.call(A)};H=()=>{var B;if(!F())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let S="";try{if(!J.ping((z,_,y)=>{if(D(),z)this.keepaliveTrace("Ping failed with error: "+z.message),W=!0,J.destroy();else this.keepaliveTrace("Received ping response"),V()}))S="Ping returned false"}catch(v){S=(v instanceof Error?v.message:"")||"Unknown error"}if(S){this.keepaliveTrace("Ping send failed: "+S),this.trace("Connection dropped due to ping send error: "+S),W=!0,J.destroy();return}A=setTimeout(()=>{D(),this.keepaliveTrace("Ping timeout passed without response"),this.trace("Connection dropped by keepalive timeout"),W=!0,J.destroy()},this.keepaliveTimeoutMs),(B=A.unref)===null||B===void 0||B.call(A)},V(),J.on("close",()=>{var B,S;if(!W)this.trace(`Connection dropped by client ${(B=J.socket)===null||B===void 0?void 0:B.remoteAddress}`);if(Z)clearTimeout(Z);if(K)clearTimeout(K);if(D(),E!==null)clearTimeout(E.timeout),this.sessionIdleTimeouts.delete(J);(S=this.http2Servers.get(X))===null||S===void 0||S.sessions.delete(J)})}}_channelzSessionHandler(X){return(J)=>{var Q,U,Z,K;let A=(0,M0.registerChannelzSocket)((U=(Q=J.socket)===null||Q===void 0?void 0:Q.remoteAddress)!==null&&U!==void 0?U:"unknown",this.getChannelzSessionInfo.bind(this,J),this.channelzEnabled),W={ref:A,streamTracker:new M0.ChannelzCallTracker,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null};(Z=this.http2Servers.get(X))===null||Z===void 0||Z.sessions.add(J),this.sessions.set(J,W);let E=`${J.socket.remoteAddress}:${J.socket.remotePort}`;this.channelzTrace.addTrace("CT_INFO","Connection established by client "+E),this.trace("Connection established by client "+E),this.sessionChildrenTracker.refChild(A);let D=null,F=null,H=null,V=!1,B=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==rY){let y=this.maxConnectionAgeMs/10,k=Math.random()*y*2-y;D=setTimeout(()=>{var m;V=!0,this.channelzTrace.addTrace("CT_INFO","Connection dropped by max connection age from "+E);try{J.goaway(s0.constants.NGHTTP2_NO_ERROR,2147483647,WV)}catch(C){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==rY)F=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(m=F.unref)===null||m===void 0||m.call(F)},this.maxConnectionAgeMs+k),(K=D.unref)===null||K===void 0||K.call(D)}let S=()=>{if(H)clearTimeout(H),H=null},v=()=>{return!J.destroyed&&this.keepaliveTimeMs<QJ&&this.keepaliveTimeMs>0},z,_=()=>{var y;if(!v())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),H=setTimeout(()=>{S(),z()},this.keepaliveTimeMs),(y=H.unref)===null||y===void 0||y.call(H)};z=()=>{var y;if(!v())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let k="";try{if(!J.ping((C,j,I)=>{if(S(),C)this.keepaliveTrace("Ping failed with error: "+C.message),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to error of a ping frame "+C.message+" return in "+j),V=!0,J.destroy();else this.keepaliveTrace("Received ping response"),_()}))k="Ping returned false"}catch(m){k=(m instanceof Error?m.message:"")||"Unknown error"}if(k){this.keepaliveTrace("Ping send failed: "+k),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to ping send error: "+k),V=!0,J.destroy();return}W.keepAlivesSent+=1,H=setTimeout(()=>{S(),this.keepaliveTrace("Ping timeout passed without response"),this.channelzTrace.addTrace("CT_INFO","Connection dropped by keepalive timeout from "+E),V=!0,J.destroy()},this.keepaliveTimeoutMs),(y=H.unref)===null||y===void 0||y.call(H)},_(),J.on("close",()=>{var y;if(!V)this.channelzTrace.addTrace("CT_INFO","Connection dropped by client "+E);if(this.sessionChildrenTracker.unrefChild(A),(0,M0.unregisterChannelzRef)(A),D)clearTimeout(D);if(F)clearTimeout(F);if(S(),B!==null)clearTimeout(B.timeout),this.sessionIdleTimeouts.delete(J);(y=this.http2Servers.get(X))===null||y===void 0||y.sessions.delete(J),this.sessions.delete(J)})}}enableIdleTimeout(X){var J,Q;if(this.sessionIdleTimeout>=KV)return null;let U={activeStreams:0,lastIdle:Date.now(),onClose:this.onStreamClose.bind(this,X),timeout:setTimeout(this.onIdleTimeout,this.sessionIdleTimeout,this,X)};(Q=(J=U.timeout).unref)===null||Q===void 0||Q.call(J),this.sessionIdleTimeouts.set(X,U);let{socket:Z}=X;return this.trace("Enable idle timeout for "+Z.remoteAddress+":"+Z.remotePort),U}onIdleTimeout(X,J){let{socket:Q}=J,U=X.sessionIdleTimeouts.get(J);if(U!==void 0&&U.activeStreams===0)if(Date.now()-U.lastIdle>=X.sessionIdleTimeout)X.trace("Session idle timeout triggered for "+(Q===null||Q===void 0?void 0:Q.remoteAddress)+":"+(Q===null||Q===void 0?void 0:Q.remotePort)+" last idle at "+U.lastIdle),X.closeSession(J);else U.timeout.refresh()}onStreamOpened(X){let J=X.session,Q=this.sessionIdleTimeouts.get(J);if(Q)Q.activeStreams+=1,X.once("close",Q.onClose)}onStreamClose(X){var J,Q;let U=this.sessionIdleTimeouts.get(X);if(U){if(U.activeStreams-=1,U.activeStreams===0)U.lastIdle=Date.now(),U.timeout.refresh(),this.trace("Session onStreamClose"+((J=X.socket)===null||J===void 0?void 0:J.remoteAddress)+":"+((Q=X.socket)===null||Q===void 0?void 0:Q.remotePort)+" at "+U.lastIdle)}}},(()=>{let q=typeof Symbol==="function"&&Symbol.metadata?Object.create(null):void 0;if(T=[OS("Calling start() is no longer necessary. It can be safely omitted.")],zS($,null,T,{kind:"method",name:"start",static:!1,private:!1,access:{has:(X)=>("start"in X),get:(X)=>X.start},metadata:q},null,Y),q)Object.defineProperty($,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:q})})(),$})();k$.Server=LS;async function wS($,Y){let T;function q(Q,U,Z,K){if(Q){$.sendStatus((0,oY.serverErrorToStatus)(Q,Z));return}$.sendMessage(U,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Z!==null&&Z!==void 0?Z:null})})}let X,J=null;$.start({onReceiveMetadata(Q){X=Q,$.startRead()},onReceiveMessage(Q){if(J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}J=Q,$.startRead()},onReceiveHalfClose(){if(!J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}T=new oY.ServerWritableStreamImpl(Y.path,$,X,J);try{Y.func(T,q)}catch(Q){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${Q.message}`,metadata:null})}},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled")}})}function SS($,Y){let T;function q(X,J,Q,U){if(X){$.sendStatus((0,oY.serverErrorToStatus)(X,Q));return}$.sendMessage(J,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Q!==null&&Q!==void 0?Q:null})})}$.start({onReceiveMetadata(X){T=new oY.ServerDuplexStreamImpl(Y.path,$,X);try{Y.func(T,q)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onReceiveMessage(X){T.push(X)},onReceiveHalfClose(){T.push(null)},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}function CS($,Y){let T,q,X=null;$.start({onReceiveMetadata(J){q=J,$.startRead()},onReceiveMessage(J){if(X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}X=J,$.startRead()},onReceiveHalfClose(){if(!X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}T=new oY.ServerWritableStreamImpl(Y.path,$,q,X);try{Y.func(T)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}function yS($,Y){let T;$.start({onReceiveMetadata(q){T=new oY.ServerDuplexStreamImpl(Y.path,$,q);try{Y.func(T)}catch(X){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${X.message}`,metadata:null})}},onReceiveMessage(q){T.push(q)},onReceiveHalfClose(){T.push(null)},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}});var NV=M((DV)=>{Object.defineProperty(DV,"__esModule",{value:!0});DV.StatusBuilder=void 0;class VV{constructor(){this.code=null,this.details=null,this.metadata=null}withCode($){return this.code=$,this}withDetails($){return this.details=$,this}withMetadata($){return this.metadata=$,this}build(){let $={};if(this.code!==null)$.code=this.code;if(this.details!==null)$.details=this.details;if(this.metadata!==null)$.metadata=this.metadata;return $}}DV.StatusBuilder=VV});var V6=M((PV)=>{Object.defineProperty(PV,"__esModule",{value:!0});PV.LeafLoadBalancer=PV.PickFirstLoadBalancer=PV.PickFirstLoadBalancingConfig=void 0;PV.shuffled=BV;PV.setup=mS;var ZJ=M$(),H0=l0(),h$=Y$(),HV=r0(),jS=U0(),vS=i(),zV=r0(),IV=s("net"),xS=l$(),kS="pick_first";function G6($){jS.trace(vS.LogVerbosity.DEBUG,kS,$)}var E6="pick_first",hS=250;class sY{constructor($){this.shuffleAddressList=$}getLoadBalancerName(){return E6}toJsonObject(){return{[E6]:{shuffleAddressList:this.shuffleAddressList}}}getShuffleAddressList(){return this.shuffleAddressList}static createFromJson($){if("shuffleAddressList"in $&&typeof $.shuffleAddressList!=="boolean")throw Error("pick_first config field shuffleAddressList must be a boolean if provided");return new sY($.shuffleAddressList===!0)}}PV.PickFirstLoadBalancingConfig=sY;class MV{constructor($){this.subchannel=$}pick($){return{pickResultType:h$.PickResultType.COMPLETE,subchannel:this.subchannel,status:null,onCallStarted:null,onCallEnded:null}}}function BV($){let Y=$.slice();for(let T=Y.length-1;T>1;T--){let q=Math.floor(Math.random()*(T+1)),X=Y[T];Y[T]=Y[q],Y[q]=X}return Y}function _S($){if($.length===0)return[];let Y=[],T=[],q=[],X=(0,zV.isTcpSubchannelAddress)($[0])&&(0,IV.isIPv6)($[0].host);for(let U of $)if((0,zV.isTcpSubchannelAddress)(U)&&(0,IV.isIPv6)(U.host))T.push(U);else q.push(U);let J=X?T:q,Q=X?q:T;for(let U=0;U<Math.max(J.length,Q.length);U++){if(U<J.length)Y.push(J[U]);if(U<Q.length)Y.push(Q[U])}return Y}var RV="grpc-node.internal.pick-first.report_health_status";class sq{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=H0.ConnectivityState.IDLE,this.currentSubchannelIndex=0,this.currentPick=null,this.subchannelStateListener=(Y,T,q,X,J)=>{this.onSubchannelStateUpdate(Y,T,q,J)},this.pickedSubchannelHealthListener=()=>this.calculateAndReportNewState(),this.stickyTransientFailureMode=!1,this.reportHealthStatus=!1,this.lastError=null,this.latestAddressList=null,this.latestOptions={},this.latestResolutionNote="",this.connectionDelayTimeout=setTimeout(()=>{},0),clearTimeout(this.connectionDelayTimeout)}allChildrenHaveReportedTF(){return this.children.every(($)=>$.hasReportedTransientFailure)}resetChildrenReportedTF(){this.children.every(($)=>$.hasReportedTransientFailure=!1)}calculateAndReportNewState(){var $;if(this.currentPick)if(this.reportHealthStatus&&!this.currentPick.isHealthy()){let Y=`Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else this.updateState(H0.ConnectivityState.READY,new MV(this.currentPick),null);else if((($=this.latestAddressList)===null||$===void 0?void 0:$.length)===0){let Y=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else if(this.children.length===0)this.updateState(H0.ConnectivityState.IDLE,new h$.QueuePicker(this),null);else if(this.stickyTransientFailureMode){let Y=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else this.updateState(H0.ConnectivityState.CONNECTING,new h$.QueuePicker(this),null)}requestReresolution(){this.channelControlHelper.requestReresolution()}maybeEnterStickyTransientFailureMode(){if(!this.allChildrenHaveReportedTF())return;if(this.requestReresolution(),this.resetChildrenReportedTF(),this.stickyTransientFailureMode){this.calculateAndReportNewState();return}this.stickyTransientFailureMode=!0;for(let{subchannel:$}of this.children)$.startConnecting();this.calculateAndReportNewState()}removeCurrentPick(){if(this.currentPick!==null)this.currentPick.removeConnectivityStateListener(this.subchannelStateListener),this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()),this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick.unref(),this.currentPick=null}onSubchannelStateUpdate($,Y,T,q){var X;if((X=this.currentPick)===null||X===void 0?void 0:X.realSubchannelEquals($)){if(T!==H0.ConnectivityState.READY)this.removeCurrentPick(),this.calculateAndReportNewState();return}for(let[J,Q]of this.children.entries())if($.realSubchannelEquals(Q.subchannel)){if(T===H0.ConnectivityState.READY)this.pickSubchannel(Q.subchannel);if(T===H0.ConnectivityState.TRANSIENT_FAILURE){if(Q.hasReportedTransientFailure=!0,q)this.lastError=q;if(this.maybeEnterStickyTransientFailureMode(),J===this.currentSubchannelIndex)this.startNextSubchannelConnecting(J+1)}Q.subchannel.startConnecting();return}}startNextSubchannelConnecting($){clearTimeout(this.connectionDelayTimeout);for(let[Y,T]of this.children.entries())if(Y>=$){let q=T.subchannel.getConnectivityState();if(q===H0.ConnectivityState.IDLE||q===H0.ConnectivityState.CONNECTING){this.startConnecting(Y);return}}this.maybeEnterStickyTransientFailureMode()}startConnecting($){var Y,T;if(clearTimeout(this.connectionDelayTimeout),this.currentSubchannelIndex=$,this.children[$].subchannel.getConnectivityState()===H0.ConnectivityState.IDLE)G6("Start connecting to subchannel with address "+this.children[$].subchannel.getAddress()),process.nextTick(()=>{var q;(q=this.children[$])===null||q===void 0||q.subchannel.startConnecting()});this.connectionDelayTimeout=setTimeout(()=>{this.startNextSubchannelConnecting($+1)},hS),(T=(Y=this.connectionDelayTimeout).unref)===null||T===void 0||T.call(Y)}pickSubchannel($){G6("Pick subchannel with address "+$.getAddress()),this.stickyTransientFailureMode=!1,$.ref(),this.channelControlHelper.addChannelzChild($.getChannelzRef()),this.removeCurrentPick(),this.resetSubchannelList(),$.addConnectivityStateListener(this.subchannelStateListener),$.addHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick=$,clearTimeout(this.connectionDelayTimeout),this.calculateAndReportNewState()}updateState($,Y,T){G6(H0.ConnectivityState[this.currentState]+" -> "+H0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,T)}resetSubchannelList(){for(let $ of this.children)$.subchannel.removeConnectivityStateListener(this.subchannelStateListener),$.subchannel.unref(),this.channelControlHelper.removeChannelzChild($.subchannel.getChannelzRef());this.currentSubchannelIndex=0,this.children=[]}connectToAddressList($,Y){G6("connectToAddressList(["+$.map((q)=>(0,HV.subchannelAddressToString)(q))+"])");let T=$.map((q)=>({subchannel:this.channelControlHelper.createSubchannel(q,Y),hasReportedTransientFailure:!1}));for(let{subchannel:q}of T)if(q.getConnectivityState()===H0.ConnectivityState.READY){this.pickSubchannel(q);return}for(let{subchannel:q}of T)q.ref(),this.channelControlHelper.addChannelzChild(q.getChannelzRef());this.resetSubchannelList(),this.children=T;for(let{subchannel:q}of this.children)q.addConnectivityStateListener(this.subchannelStateListener);for(let q of this.children)if(q.subchannel.getConnectivityState()===H0.ConnectivityState.TRANSIENT_FAILURE)q.hasReportedTransientFailure=!0;this.startNextSubchannelConnecting(0),this.calculateAndReportNewState()}updateAddressList($,Y,T,q){if(!(Y instanceof sY))return!1;if(!$.ok){if(this.children.length===0&&this.currentPick===null)this.channelControlHelper.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker($.error),$.error.details);return!0}let X=$.value;if(this.reportHealthStatus=T[RV],Y.getShuffleAddressList())X=BV(X);let J=[].concat(...X.map((U)=>U.addresses));G6("updateAddressList(["+J.map((U)=>(0,HV.subchannelAddressToString)(U))+"])");let Q=_S(J);if(this.latestAddressList=Q,this.latestOptions=T,this.connectToAddressList(Q,T),this.latestResolutionNote=q,J.length>0)return!0;else return this.lastError="No addresses resolved",!1}exitIdle(){if(this.currentState===H0.ConnectivityState.IDLE&&this.latestAddressList)this.connectToAddressList(this.latestAddressList,this.latestOptions)}resetBackoff(){}destroy(){this.resetSubchannelList(),this.removeCurrentPick()}getTypeName(){return E6}}PV.PickFirstLoadBalancer=sq;var gS=new sY(!1);class OV{constructor($,Y,T,q){this.endpoint=$,this.options=T,this.resolutionNote=q,this.latestState=H0.ConnectivityState.IDLE;let X=(0,ZJ.createChildChannelControlHelper)(Y,{updateState:(J,Q,U)=>{this.latestState=J,this.latestPicker=Q,Y.updateState(J,Q,U)}});this.pickFirstBalancer=new sq(X),this.latestPicker=new h$.QueuePicker(this.pickFirstBalancer)}startConnecting(){this.pickFirstBalancer.updateAddressList((0,xS.statusOrFromValue)([this.endpoint]),gS,Object.assign(Object.assign({},this.options),{[RV]:!0}),this.resolutionNote)}updateEndpoint($,Y){if(this.options=Y,this.endpoint=$,this.latestState!==H0.ConnectivityState.IDLE)this.startConnecting()}getConnectivityState(){return this.latestState}getPicker(){return this.latestPicker}getEndpoint(){return this.endpoint}exitIdle(){this.pickFirstBalancer.exitIdle()}destroy(){this.pickFirstBalancer.destroy()}}PV.LeafLoadBalancer=OV;function mS(){(0,ZJ.registerLoadBalancerType)(E6,sq,sY),(0,ZJ.registerDefaultLoadBalancerType)(E6)}});var yV=M((SV)=>{Object.defineProperty(SV,"__esModule",{value:!0});SV.FileWatcherCertificateProvider=void 0;var cS=s("fs"),pS=U0(),lS=i(),nS=s("util"),iS="certificate_provider";function tq($){pS.trace(lS.LogVerbosity.DEBUG,iS,$)}var KJ=(0,nS.promisify)(cS.readFile);class wV{constructor($){if(this.config=$,this.refreshTimer=null,this.fileResultPromise=null,this.latestCaUpdate=void 0,this.caListeners=new Set,this.latestIdentityUpdate=void 0,this.identityListeners=new Set,this.lastUpdateTime=null,$.certificateFile===void 0!==($.privateKeyFile===void 0))throw Error("certificateFile and privateKeyFile must be set or unset together");if($.certificateFile===void 0&&$.caCertificateFile===void 0)throw Error("At least one of certificateFile and caCertificateFile must be set");tq("File watcher constructed with config "+JSON.stringify($))}updateCertificates(){if(this.fileResultPromise)return;this.fileResultPromise=Promise.allSettled([this.config.certificateFile?KJ(this.config.certificateFile):Promise.reject(),this.config.privateKeyFile?KJ(this.config.privateKeyFile):Promise.reject(),this.config.caCertificateFile?KJ(this.config.caCertificateFile):Promise.reject()]),this.fileResultPromise.then(([$,Y,T])=>{if(!this.refreshTimer)return;if(tq("File watcher read certificates certificate "+$.status+", privateKey "+Y.status+", CA certificate "+T.status),this.lastUpdateTime=new Date,this.fileResultPromise=null,$.status==="fulfilled"&&Y.status==="fulfilled")this.latestIdentityUpdate={certificate:$.value,privateKey:Y.value};else this.latestIdentityUpdate=null;if(T.status==="fulfilled")this.latestCaUpdate={caCertificate:T.value};else this.latestCaUpdate=null;for(let q of this.identityListeners)q(this.latestIdentityUpdate);for(let q of this.caListeners)q(this.latestCaUpdate)}),tq("File watcher initiated certificate update")}maybeStartWatchingFiles(){if(!this.refreshTimer){let $=this.lastUpdateTime?new Date().getTime()-this.lastUpdateTime.getTime():1/0;if($>this.config.refreshIntervalMs)this.updateCertificates();if($>this.config.refreshIntervalMs*2)this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0;this.refreshTimer=setInterval(()=>this.updateCertificates(),this.config.refreshIntervalMs),tq("File watcher started watching")}}maybeStopWatchingFiles(){if(this.caListeners.size===0&&this.identityListeners.size===0){if(this.fileResultPromise=null,this.refreshTimer)clearInterval(this.refreshTimer),this.refreshTimer=null}}addCaCertificateListener($){if(this.caListeners.add($),this.maybeStartWatchingFiles(),this.latestCaUpdate!==void 0)process.nextTick($,this.latestCaUpdate)}removeCaCertificateListener($){this.caListeners.delete($),this.maybeStopWatchingFiles()}addIdentityCertificateListener($){if(this.identityListeners.add($),this.maybeStartWatchingFiles(),this.latestIdentityUpdate!==void 0)process.nextTick($,this.latestIdentityUpdate)}removeIdentityCertificateListener($){this.identityListeners.delete($),this.maybeStopWatchingFiles()}}SV.FileWatcherCertificateProvider=wV});var GJ=M((a)=>{Object.defineProperty(a,"__esModule",{value:!0});a.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=a.createCertificateProviderChannelCredentials=a.FileWatcherCertificateProvider=a.createCertificateProviderServerCredentials=a.createServerCredentialsWithInterceptors=a.BaseSubchannelWrapper=a.registerAdminService=a.FilterStackFactory=a.BaseFilter=a.statusOrFromError=a.statusOrFromValue=a.PickResultType=a.QueuePicker=a.UnavailablePicker=a.ChildLoadBalancerHandler=a.EndpointMap=a.endpointHasAddress=a.endpointToString=a.subchannelAddressToString=a.LeafLoadBalancer=a.isLoadBalancerNameRegistered=a.parseLoadBalancingConfig=a.selectLbConfigFromList=a.registerLoadBalancerType=a.createChildChannelControlHelper=a.BackoffTimeout=a.parseDuration=a.durationToMs=a.splitHostPort=a.uriToString=a.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=a.createResolver=a.registerResolver=a.log=a.trace=void 0;var jV=U0();Object.defineProperty(a,"trace",{enumerable:!0,get:function(){return jV.trace}});Object.defineProperty(a,"log",{enumerable:!0,get:function(){return jV.log}});var AJ=B1();Object.defineProperty(a,"registerResolver",{enumerable:!0,get:function(){return AJ.registerResolver}});Object.defineProperty(a,"createResolver",{enumerable:!0,get:function(){return AJ.createResolver}});Object.defineProperty(a,"CHANNEL_ARGS_CONFIG_SELECTOR_KEY",{enumerable:!0,get:function(){return AJ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY}});var vV=p0();Object.defineProperty(a,"uriToString",{enumerable:!0,get:function(){return vV.uriToString}});Object.defineProperty(a,"splitHostPort",{enumerable:!0,get:function(){return vV.splitHostPort}});var xV=W6();Object.defineProperty(a,"durationToMs",{enumerable:!0,get:function(){return xV.durationToMs}});Object.defineProperty(a,"parseDuration",{enumerable:!0,get:function(){return xV.parseDuration}});var rS=LY();Object.defineProperty(a,"BackoffTimeout",{enumerable:!0,get:function(){return rS.BackoffTimeout}});var D6=M$();Object.defineProperty(a,"createChildChannelControlHelper",{enumerable:!0,get:function(){return D6.createChildChannelControlHelper}});Object.defineProperty(a,"registerLoadBalancerType",{enumerable:!0,get:function(){return D6.registerLoadBalancerType}});Object.defineProperty(a,"selectLbConfigFromList",{enumerable:!0,get:function(){return D6.selectLbConfigFromList}});Object.defineProperty(a,"parseLoadBalancingConfig",{enumerable:!0,get:function(){return D6.parseLoadBalancingConfig}});Object.defineProperty(a,"isLoadBalancerNameRegistered",{enumerable:!0,get:function(){return D6.isLoadBalancerNameRegistered}});var aS=V6();Object.defineProperty(a,"LeafLoadBalancer",{enumerable:!0,get:function(){return aS.LeafLoadBalancer}});var eq=r0();Object.defineProperty(a,"subchannelAddressToString",{enumerable:!0,get:function(){return eq.subchannelAddressToString}});Object.defineProperty(a,"endpointToString",{enumerable:!0,get:function(){return eq.endpointToString}});Object.defineProperty(a,"endpointHasAddress",{enumerable:!0,get:function(){return eq.endpointHasAddress}});Object.defineProperty(a,"EndpointMap",{enumerable:!0,get:function(){return eq.EndpointMap}});var oS=l8();Object.defineProperty(a,"ChildLoadBalancerHandler",{enumerable:!0,get:function(){return oS.ChildLoadBalancerHandler}});var WJ=Y$();Object.defineProperty(a,"UnavailablePicker",{enumerable:!0,get:function(){return WJ.UnavailablePicker}});Object.defineProperty(a,"QueuePicker",{enumerable:!0,get:function(){return WJ.QueuePicker}});Object.defineProperty(a,"PickResultType",{enumerable:!0,get:function(){return WJ.PickResultType}});var kV=l$();Object.defineProperty(a,"statusOrFromValue",{enumerable:!0,get:function(){return kV.statusOrFromValue}});Object.defineProperty(a,"statusOrFromError",{enumerable:!0,get:function(){return kV.statusOrFromError}});var sS=O5();Object.defineProperty(a,"BaseFilter",{enumerable:!0,get:function(){return sS.BaseFilter}});var tS=vq();Object.defineProperty(a,"FilterStackFactory",{enumerable:!0,get:function(){return tS.FilterStackFactory}});var eS=i8();Object.defineProperty(a,"registerAdminService",{enumerable:!0,get:function(){return eS.registerAdminService}});var $C=K6();Object.defineProperty(a,"BaseSubchannelWrapper",{enumerable:!0,get:function(){return $C.BaseSubchannelWrapper}});var hV=lq();Object.defineProperty(a,"createServerCredentialsWithInterceptors",{enumerable:!0,get:function(){return hV.createServerCredentialsWithInterceptors}});Object.defineProperty(a,"createCertificateProviderServerCredentials",{enumerable:!0,get:function(){return hV.createCertificateProviderServerCredentials}});var YC=yV();Object.defineProperty(a,"FileWatcherCertificateProvider",{enumerable:!0,get:function(){return YC.FileWatcherCertificateProvider}});var TC=PY();Object.defineProperty(a,"createCertificateProviderChannelCredentials",{enumerable:!0,get:function(){return TC.createCertificateProviderChannelCredentials}});var qC=l5();Object.defineProperty(a,"SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX",{enumerable:!0,get:function(){return qC.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX}})});var mV=M((gV)=>{Object.defineProperty(gV,"__esModule",{value:!0});gV.setup=UC;var JC=B1(),QC=l$();class _V{constructor($,Y,T){this.listener=Y,this.hasReturnedResult=!1,this.endpoints=[];let q;if($.authority==="")q="/"+$.path;else q=$.path;this.endpoints=[{addresses:[{path:q}]}]}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(this.listener,(0,QC.statusOrFromValue)(this.endpoints),{},null,"")}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return"localhost"}}function UC(){(0,JC.registerResolver)("unix",_V)}});var lV=M((pV)=>{Object.defineProperty(pV,"__esModule",{value:!0});pV.setup=EC;var fV=s("net"),bV=l$(),$9=i(),EJ=P0(),uV=B1(),KC=r0(),dV=p0(),AC=U0(),WC="ip_resolver";function cV($){AC.trace($9.LogVerbosity.DEBUG,WC,$)}var VJ="ipv4",DJ="ipv6",GC=443;class FJ{constructor($,Y,T){var q;this.listener=Y,this.endpoints=[],this.error=null,this.hasReturnedResult=!1,cV("Resolver constructed for target "+(0,dV.uriToString)($));let X=[];if(!($.scheme===VJ||$.scheme===DJ)){this.error={code:$9.Status.UNAVAILABLE,details:`Unrecognized scheme ${$.scheme} in IP resolver`,metadata:new EJ.Metadata};return}let J=$.path.split(",");for(let Q of J){let U=(0,dV.splitHostPort)(Q);if(U===null){this.error={code:$9.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new EJ.Metadata};return}if($.scheme===VJ&&!(0,fV.isIPv4)(U.host)||$.scheme===DJ&&!(0,fV.isIPv6)(U.host)){this.error={code:$9.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new EJ.Metadata};return}X.push({host:U.host,port:(q=U.port)!==null&&q!==void 0?q:GC})}this.endpoints=X.map((Q)=>({addresses:[Q]})),cV("Parsed "+$.scheme+" address list "+X.map(KC.subchannelAddressToString))}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(()=>{if(this.error)this.listener((0,bV.statusOrFromError)(this.error),{},null,"");else this.listener((0,bV.statusOrFromValue)(this.endpoints),{},null,"")})}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return $.path.split(",")[0]}}function EC(){(0,uV.registerResolver)(VJ,FJ),(0,uV.registerResolver)(DJ,FJ)}});var tV=M((oV)=>{Object.defineProperty(oV,"__esModule",{value:!0});oV.RoundRobinLoadBalancer=void 0;oV.setup=IC;var rV=M$(),k0=l0(),F6=Y$(),DC=U0(),FC=i(),nV=r0(),NC=V6(),HC="round_robin";function iV($){DC.trace(FC.LogVerbosity.DEBUG,HC,$)}var Y9="round_robin";class T9{getLoadBalancerName(){return Y9}constructor(){}toJsonObject(){return{[Y9]:{}}}static createFromJson($){return new T9}}class aV{constructor($,Y=0){this.children=$,this.nextIndex=Y}pick($){let Y=this.children[this.nextIndex].picker;return this.nextIndex=(this.nextIndex+1)%this.children.length,Y.pick($)}peekNextEndpoint(){return this.children[this.nextIndex].endpoint}}function zC($,Y){return[...$.slice(Y),...$.slice(0,Y)]}class NJ{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=k0.ConnectivityState.IDLE,this.currentReadyPicker=null,this.updatesPaused=!1,this.lastError=null,this.childChannelControlHelper=(0,rV.createChildChannelControlHelper)($,{updateState:(Y,T,q)=>{if(this.currentState===k0.ConnectivityState.READY&&Y!==k0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(q)this.lastError=q;this.calculateAndUpdateState()}})}countChildrenWithState($){return this.children.filter((Y)=>Y.getConnectivityState()===$).length}calculateAndUpdateState(){if(this.updatesPaused)return;if(this.countChildrenWithState(k0.ConnectivityState.READY)>0){let $=this.children.filter((T)=>T.getConnectivityState()===k0.ConnectivityState.READY),Y=0;if(this.currentReadyPicker!==null){let T=this.currentReadyPicker.peekNextEndpoint();if(Y=$.findIndex((q)=>(0,nV.endpointEqual)(q.getEndpoint(),T)),Y<0)Y=0}this.updateState(k0.ConnectivityState.READY,new aV($.map((T)=>({endpoint:T.getEndpoint(),picker:T.getPicker()})),Y),null)}else if(this.countChildrenWithState(k0.ConnectivityState.CONNECTING)>0)this.updateState(k0.ConnectivityState.CONNECTING,new F6.QueuePicker(this),null);else if(this.countChildrenWithState(k0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new F6.UnavailablePicker({details:$}),$)}else this.updateState(k0.ConnectivityState.IDLE,new F6.QueuePicker(this),null);for(let $ of this.children)if($.getConnectivityState()===k0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,T){if(iV(k0.ConnectivityState[this.currentState]+" -> "+k0.ConnectivityState[$]),$===k0.ConnectivityState.READY)this.currentReadyPicker=Y;else this.currentReadyPicker=null;this.currentState=$,this.channelControlHelper.updateState($,Y,T)}resetSubchannelList(){for(let $ of this.children)$.destroy();this.children=[]}updateAddressList($,Y,T,q){if(!(Y instanceof T9))return!1;if(!$.ok){if(this.children.length===0)this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new F6.UnavailablePicker($.error),$.error.details);return!0}let X=Math.random()*$.value.length|0,J=zC($.value,X);if(this.resetSubchannelList(),J.length===0){let Q=`No addresses resolved. Resolution note: ${q}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new F6.UnavailablePicker({details:Q}),Q)}iV("Connect to endpoint list "+J.map(nV.endpointToString)),this.updatesPaused=!0,this.children=J.map((Q)=>new NC.LeafLoadBalancer(Q,this.childChannelControlHelper,T,q));for(let Q of this.children)Q.startConnecting();return this.updatesPaused=!1,this.calculateAndUpdateState(),!0}exitIdle(){}resetBackoff(){}destroy(){this.resetSubchannelList()}getTypeName(){return Y9}}oV.RoundRobinLoadBalancer=NJ;function IC(){(0,rV.registerLoadBalancerType)(Y9,NJ,T9)}});var Q3=M((X3)=>{var HJ;Object.defineProperty(X3,"__esModule",{value:!0});X3.OutlierDetectionLoadBalancer=X3.OutlierDetectionLoadBalancingConfig=void 0;X3.setup=vC;var BC=l0(),eV=i(),XY=W6(),$3=GJ(),RC=M$(),OC=l8(),PC=Y$(),zJ=r0(),LC=K6(),wC=U0(),SC="outlier_detection";function C0($){wC.trace(eV.LogVerbosity.DEBUG,SC,$)}var BJ="outlier_detection",CC=((HJ=process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION)!==null&&HJ!==void 0?HJ:"true")==="true",yC={stdev_factor:1900,enforcement_percentage:100,minimum_hosts:5,request_volume:100},jC={threshold:85,enforcement_percentage:100,minimum_hosts:5,request_volume:50};function tY($,Y,T,q){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==T){let X=q?`${q}.${Y}`:Y;throw Error(`outlier detection config ${X} parse error: expected ${T}, got ${typeof $[Y]}`)}}function IJ($,Y,T){let q=T?`${T}.${Y}`:Y;if(Y in $&&$[Y]!==void 0){if(!(0,XY.isDuration)($[Y]))throw Error(`outlier detection config ${q} parse error: expected Duration, got ${typeof $[Y]}`);if(!($[Y].seconds>=0&&$[Y].seconds<=315576000000&&$[Y].nanos>=0&&$[Y].nanos<=999999999))throw Error(`outlier detection config ${q} parse error: values out of range for non-negative Duaration`)}}function q9($,Y,T){let q=T?`${T}.${Y}`:Y;if(tY($,Y,"number",T),Y in $&&$[Y]!==void 0&&!($[Y]>=0&&$[Y]<=100))throw Error(`outlier detection config ${q} parse error: value out of range for percentage (0-100)`)}class N6{constructor($,Y,T,q,X,J,Q){if(this.childPolicy=Q,Q.getLoadBalancerName()==="pick_first")throw Error("outlier_detection LB policy cannot have a pick_first child policy");this.intervalMs=$!==null&&$!==void 0?$:1e4,this.baseEjectionTimeMs=Y!==null&&Y!==void 0?Y:30000,this.maxEjectionTimeMs=T!==null&&T!==void 0?T:300000,this.maxEjectionPercent=q!==null&&q!==void 0?q:10,this.successRateEjection=X?Object.assign(Object.assign({},yC),X):null,this.failurePercentageEjection=J?Object.assign(Object.assign({},jC),J):null}getLoadBalancerName(){return BJ}toJsonObject(){var $,Y;return{outlier_detection:{interval:(0,XY.msToDuration)(this.intervalMs),base_ejection_time:(0,XY.msToDuration)(this.baseEjectionTimeMs),max_ejection_time:(0,XY.msToDuration)(this.maxEjectionTimeMs),max_ejection_percent:this.maxEjectionPercent,success_rate_ejection:($=this.successRateEjection)!==null&&$!==void 0?$:void 0,failure_percentage_ejection:(Y=this.failurePercentageEjection)!==null&&Y!==void 0?Y:void 0,child_policy:[this.childPolicy.toJsonObject()]}}}getIntervalMs(){return this.intervalMs}getBaseEjectionTimeMs(){return this.baseEjectionTimeMs}getMaxEjectionTimeMs(){return this.maxEjectionTimeMs}getMaxEjectionPercent(){return this.maxEjectionPercent}getSuccessRateEjectionConfig(){return this.successRateEjection}getFailurePercentageEjectionConfig(){return this.failurePercentageEjection}getChildPolicy(){return this.childPolicy}static createFromJson($){var Y;if(IJ($,"interval"),IJ($,"base_ejection_time"),IJ($,"max_ejection_time"),q9($,"max_ejection_percent"),"success_rate_ejection"in $&&$.success_rate_ejection!==void 0){if(typeof $.success_rate_ejection!=="object")throw Error("outlier detection config success_rate_ejection must be an object");tY($.success_rate_ejection,"stdev_factor","number","success_rate_ejection"),q9($.success_rate_ejection,"enforcement_percentage","success_rate_ejection"),tY($.success_rate_ejection,"minimum_hosts","number","success_rate_ejection"),tY($.success_rate_ejection,"request_volume","number","success_rate_ejection")}if("failure_percentage_ejection"in $&&$.failure_percentage_ejection!==void 0){if(typeof $.failure_percentage_ejection!=="object")throw Error("outlier detection config failure_percentage_ejection must be an object");q9($.failure_percentage_ejection,"threshold","failure_percentage_ejection"),q9($.failure_percentage_ejection,"enforcement_percentage","failure_percentage_ejection"),tY($.failure_percentage_ejection,"minimum_hosts","number","failure_percentage_ejection"),tY($.failure_percentage_ejection,"request_volume","number","failure_percentage_ejection")}if(!("child_policy"in $)||!Array.isArray($.child_policy))throw Error("outlier detection config child_policy must be an array");let T=(0,RC.selectLbConfigFromList)($.child_policy);if(!T)throw Error("outlier detection config child_policy: no valid recognized policy found");return new N6($.interval?(0,XY.durationToMs)($.interval):null,$.base_ejection_time?(0,XY.durationToMs)($.base_ejection_time):null,$.max_ejection_time?(0,XY.durationToMs)($.max_ejection_time):null,(Y=$.max_ejection_percent)!==null&&Y!==void 0?Y:null,$.success_rate_ejection,$.failure_percentage_ejection,T)}}X3.OutlierDetectionLoadBalancingConfig=N6;class Y3 extends LC.BaseSubchannelWrapper{constructor($,Y){super($);this.mapEntry=Y,this.refCount=0}ref(){this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0){if(this.mapEntry){let $=this.mapEntry.subchannelWrappers.indexOf(this);if($>=0)this.mapEntry.subchannelWrappers.splice($,1)}}}eject(){this.setHealthy(!1)}uneject(){this.setHealthy(!0)}getMapEntry(){return this.mapEntry}getWrappedSubchannel(){return this.child}}function MJ(){return{success:0,failure:0}}class T3{constructor(){this.activeBucket=MJ(),this.inactiveBucket=MJ()}addSuccess(){this.activeBucket.success+=1}addFailure(){this.activeBucket.failure+=1}switchBuckets(){this.inactiveBucket=this.activeBucket,this.activeBucket=MJ()}getLastSuccesses(){return this.inactiveBucket.success}getLastFailures(){return this.inactiveBucket.failure}}class q3{constructor($,Y){this.wrappedPicker=$,this.countCalls=Y}pick($){let Y=this.wrappedPicker.pick($);if(Y.pickResultType===PC.PickResultType.COMPLETE){let T=Y.subchannel,q=T.getMapEntry();if(q){let X=Y.onCallEnded;if(this.countCalls)X=(J,Q,U)=>{var Z;if(J===eV.Status.OK)q.counter.addSuccess();else q.counter.addFailure();(Z=Y.onCallEnded)===null||Z===void 0||Z.call(Y,J,Q,U)};return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel(),onCallEnded:X})}else return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel()})}else return Y}}class RJ{constructor($){this.entryMap=new zJ.EndpointMap,this.latestConfig=null,this.timerStartTime=null,this.childBalancer=new OC.ChildLoadBalancerHandler((0,$3.createChildChannelControlHelper)($,{createSubchannel:(Y,T)=>{let q=$.createSubchannel(Y,T),X=this.entryMap.getForSubchannelAddress(Y),J=new Y3(q,X);if((X===null||X===void 0?void 0:X.currentEjectionTimestamp)!==null)J.eject();return X===null||X===void 0||X.subchannelWrappers.push(J),J},updateState:(Y,T,q)=>{if(Y===BC.ConnectivityState.READY)$.updateState(Y,new q3(T,this.isCountingEnabled()),q);else $.updateState(Y,T,q)}})),this.ejectionTimer=setInterval(()=>{},0),clearInterval(this.ejectionTimer)}isCountingEnabled(){return this.latestConfig!==null&&(this.latestConfig.getSuccessRateEjectionConfig()!==null||this.latestConfig.getFailurePercentageEjectionConfig()!==null)}getCurrentEjectionPercent(){let $=0;for(let Y of this.entryMap.values())if(Y.currentEjectionTimestamp!==null)$+=1;return $*100/this.entryMap.size}runSuccessRateCheck($){if(!this.latestConfig)return;let Y=this.latestConfig.getSuccessRateEjectionConfig();if(!Y)return;C0("Running success rate check");let T=Y.request_volume,q=0,X=[];for(let[A,W]of this.entryMap.entries()){let E=W.counter.getLastSuccesses(),D=W.counter.getLastFailures();if(C0("Stats for "+(0,zJ.endpointToString)(A)+": successes="+E+" failures="+D+" targetRequestVolume="+T),E+D>=T)q+=1,X.push(E/(E+D))}if(C0("Found "+q+" success rate candidates; currentEjectionPercent="+this.getCurrentEjectionPercent()+" successRates=["+X+"]"),q<Y.minimum_hosts)return;let J=X.reduce((A,W)=>A+W)/X.length,Q=0;for(let A of X){let W=A-J;Q+=W*W}let U=Q/X.length,Z=Math.sqrt(U),K=J-Z*(Y.stdev_factor/1000);C0("stdev="+Z+" ejectionThreshold="+K);for(let[A,W]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let E=W.counter.getLastSuccesses(),D=W.counter.getLastFailures();if(E+D<T)continue;let F=E/(E+D);if(C0("Checking candidate "+A+" successRate="+F),F<K){let H=Math.random()*100;if(C0("Candidate "+A+" randomNumber="+H+" enforcement_percentage="+Y.enforcement_percentage),H<Y.enforcement_percentage)C0("Ejecting candidate "+A),this.eject(W,$)}}}runFailurePercentageCheck($){if(!this.latestConfig)return;let Y=this.latestConfig.getFailurePercentageEjectionConfig();if(!Y)return;C0("Running failure percentage check. threshold="+Y.threshold+" request volume threshold="+Y.request_volume);let T=0;for(let q of this.entryMap.values()){let X=q.counter.getLastSuccesses(),J=q.counter.getLastFailures();if(X+J>=Y.request_volume)T+=1}if(T<Y.minimum_hosts)return;for(let[q,X]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let J=X.counter.getLastSuccesses(),Q=X.counter.getLastFailures();if(C0("Candidate successes="+J+" failures="+Q),J+Q<Y.request_volume)continue;if(Q*100/(Q+J)>Y.threshold){let Z=Math.random()*100;if(C0("Candidate "+q+" randomNumber="+Z+" enforcement_percentage="+Y.enforcement_percentage),Z<Y.enforcement_percentage)C0("Ejecting candidate "+q),this.eject(X,$)}}}eject($,Y){$.currentEjectionTimestamp=new Date,$.ejectionTimeMultiplier+=1;for(let T of $.subchannelWrappers)T.eject()}uneject($){$.currentEjectionTimestamp=null;for(let Y of $.subchannelWrappers)Y.uneject()}switchAllBuckets(){for(let $ of this.entryMap.values())$.counter.switchBuckets()}startTimer($){var Y,T;this.ejectionTimer=setTimeout(()=>this.runChecks(),$),(T=(Y=this.ejectionTimer).unref)===null||T===void 0||T.call(Y)}runChecks(){let $=new Date;if(C0("Ejection timer running"),this.switchAllBuckets(),!this.latestConfig)return;this.timerStartTime=$,this.startTimer(this.latestConfig.getIntervalMs()),this.runSuccessRateCheck($),this.runFailurePercentageCheck($);for(let[Y,T]of this.entryMap.entries())if(T.currentEjectionTimestamp===null){if(T.ejectionTimeMultiplier>0)T.ejectionTimeMultiplier-=1}else{let q=this.latestConfig.getBaseEjectionTimeMs(),X=this.latestConfig.getMaxEjectionTimeMs(),J=new Date(T.currentEjectionTimestamp.getTime());if(J.setMilliseconds(J.getMilliseconds()+Math.min(q*T.ejectionTimeMultiplier,Math.max(q,X))),J<new Date)C0("Unejecting "+Y),this.uneject(T)}}updateAddressList($,Y,T,q){if(!(Y instanceof N6))return!1;if(C0("Received update with config: "+JSON.stringify(Y.toJsonObject(),void 0,2)),$.ok){for(let J of $.value)if(!this.entryMap.has(J))C0("Adding map entry for "+(0,zJ.endpointToString)(J)),this.entryMap.set(J,{counter:new T3,currentEjectionTimestamp:null,ejectionTimeMultiplier:0,subchannelWrappers:[]});this.entryMap.deleteMissing($.value)}let X=Y.getChildPolicy();if(this.childBalancer.updateAddressList($,X,T,q),Y.getSuccessRateEjectionConfig()||Y.getFailurePercentageEjectionConfig())if(this.timerStartTime){C0("Previous timer existed. Replacing timer"),clearTimeout(this.ejectionTimer);let J=Y.getIntervalMs()-(new Date().getTime()-this.timerStartTime.getTime());this.startTimer(J)}else C0("Starting new timer"),this.timerStartTime=new Date,this.startTimer(Y.getIntervalMs()),this.switchAllBuckets();else{C0("Counting disabled. Cancelling timer."),this.timerStartTime=null,clearTimeout(this.ejectionTimer);for(let J of this.entryMap.values())this.uneject(J),J.ejectionTimeMultiplier=0}return this.latestConfig=Y,!0}exitIdle(){this.childBalancer.exitIdle()}resetBackoff(){this.childBalancer.resetBackoff()}destroy(){clearTimeout(this.ejectionTimer),this.childBalancer.destroy()}getTypeName(){return BJ}}X3.OutlierDetectionLoadBalancer=RJ;function vC(){if(CC)(0,$3.registerLoadBalancerType)(BJ,RJ,N6)}});var A3=M((Z3)=>{Object.defineProperty(Z3,"__esModule",{value:!0});Z3.PriorityQueue=void 0;var eY=0,OJ=($)=>Math.floor($/2),X9=($)=>$*2+1,H6=($)=>$*2+2;class U3{constructor($=(Y,T)=>Y>T){this.comparator=$,this.heap=[]}size(){return this.heap.length}isEmpty(){return this.size()==0}peek(){return this.heap[eY]}push(...$){return $.forEach((Y)=>{this.heap.push(Y),this.siftUp()}),this.size()}pop(){let $=this.peek(),Y=this.size()-1;if(Y>eY)this.swap(eY,Y);return this.heap.pop(),this.siftDown(),$}replace($){let Y=this.peek();return this.heap[eY]=$,this.siftDown(),Y}greater($,Y){return this.comparator(this.heap[$],this.heap[Y])}swap($,Y){[this.heap[$],this.heap[Y]]=[this.heap[Y],this.heap[$]]}siftUp(){let $=this.size()-1;while($>eY&&this.greater($,OJ($)))this.swap($,OJ($)),$=OJ($)}siftDown(){let $=eY;while(X9($)<this.size()&&this.greater(X9($),$)||H6($)<this.size()&&this.greater(H6($),$)){let Y=H6($)<this.size()&&this.greater(H6($),X9($))?H6($):X9($);this.swap($,Y),$=Y}}}Z3.PriorityQueue=U3});var z3=M((N3)=>{Object.defineProperty(N3,"__esModule",{value:!0});N3.WeightedRoundRobinLoadBalancingConfig=void 0;N3.setup=lC;var y0=l0(),hC=i(),J1=W6(),E3=M$(),_C=V6(),gC=U0(),V3=iq(),$T=Y$(),mC=A3(),W3=r0(),fC="weighted_round_robin";function PJ($){gC.trace(hC.LogVerbosity.DEBUG,fC,$)}var LJ="weighted_round_robin",bC=1e4,uC=1e4,dC=180000,cC=1000,pC=1;function G3($,Y,T){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==T)throw Error(`weighted round robin config ${Y} parse error: expected ${T}, got ${typeof $[Y]}`)}function J9($,Y){if(Y in $&&$[Y]!==void 0&&$[Y]!==null){let T;if((0,J1.isDuration)($[Y]))T=$[Y];else if((0,J1.isDurationMessage)($[Y]))T=(0,J1.durationMessageToDuration)($[Y]);else if(typeof $[Y]==="string"){let q=(0,J1.parseDuration)($[Y]);if(!q)throw Error(`weighted round robin config ${Y}: failed to parse duration string ${$[Y]}`);T=q}else throw Error(`weighted round robin config ${Y}: expected duration, got ${typeof $[Y]}`);return(0,J1.durationToMs)(T)}return null}class z6{constructor($,Y,T,q,X,J){this.enableOobLoadReport=$!==null&&$!==void 0?$:!1,this.oobLoadReportingPeriodMs=Y!==null&&Y!==void 0?Y:bC,this.blackoutPeriodMs=T!==null&&T!==void 0?T:uC,this.weightExpirationPeriodMs=q!==null&&q!==void 0?q:dC,this.weightUpdatePeriodMs=Math.max(X!==null&&X!==void 0?X:cC,100),this.errorUtilizationPenalty=J!==null&&J!==void 0?J:pC}getLoadBalancerName(){return LJ}toJsonObject(){return{enable_oob_load_report:this.enableOobLoadReport,oob_load_reporting_period:(0,J1.durationToString)((0,J1.msToDuration)(this.oobLoadReportingPeriodMs)),blackout_period:(0,J1.durationToString)((0,J1.msToDuration)(this.blackoutPeriodMs)),weight_expiration_period:(0,J1.durationToString)((0,J1.msToDuration)(this.weightExpirationPeriodMs)),weight_update_period:(0,J1.durationToString)((0,J1.msToDuration)(this.weightUpdatePeriodMs)),error_utilization_penalty:this.errorUtilizationPenalty}}static createFromJson($){if(G3($,"enable_oob_load_report","boolean"),G3($,"error_utilization_penalty","number"),$.error_utilization_penalty<0)throw Error("weighted round robin config error_utilization_penalty < 0");return new z6($.enable_oob_load_report,J9($,"oob_load_reporting_period"),J9($,"blackout_period"),J9($,"weight_expiration_period"),J9($,"weight_update_period"),$.error_utilization_penalty)}getEnableOobLoadReport(){return this.enableOobLoadReport}getOobLoadReportingPeriodMs(){return this.oobLoadReportingPeriodMs}getBlackoutPeriodMs(){return this.blackoutPeriodMs}getWeightExpirationPeriodMs(){return this.weightExpirationPeriodMs}getWeightUpdatePeriodMs(){return this.weightUpdatePeriodMs}getErrorUtilizationPenalty(){return this.errorUtilizationPenalty}}N3.WeightedRoundRobinLoadBalancingConfig=z6;class D3{constructor($,Y){this.metricsHandler=Y,this.queue=new mC.PriorityQueue((X,J)=>X.deadline<J.deadline);let T=$.filter((X)=>X.weight>0),q;if(T.length<2)q=1;else{let X=0;for(let{weight:J}of T)X+=J;q=X/T.length}for(let X of $){let J=X.weight>0?1/X.weight:q;this.queue.push({endpointName:X.endpointName,picker:X.picker,period:J,deadline:Math.random()*J})}}pick($){let Y=this.queue.pop();this.queue.push(Object.assign(Object.assign({},Y),{deadline:Y.deadline+Y.period}));let T=Y.picker.pick($);if(T.pickResultType===$T.PickResultType.COMPLETE)if(this.metricsHandler)return Object.assign(Object.assign({},T),{onCallEnded:(0,V3.createMetricsReader)((q)=>this.metricsHandler(q,Y.endpointName),T.onCallEnded)});else{let q=T.subchannel;return Object.assign(Object.assign({},T),{subchannel:q.getWrappedSubchannel()})}else return T}}class F3{constructor($){this.channelControlHelper=$,this.latestConfig=null,this.children=new Map,this.currentState=y0.ConnectivityState.IDLE,this.updatesPaused=!1,this.lastError=null,this.weightUpdateTimer=null}countChildrenWithState($){let Y=0;for(let T of this.children.values())if(T.child.getConnectivityState()===$)Y+=1;return Y}updateWeight($,Y){var T,q;let{rps_fractional:X,application_utilization:J}=Y;if(J>0&&X>0)J+=Y.eps/X*((q=(T=this.latestConfig)===null||T===void 0?void 0:T.getErrorUtilizationPenalty())!==null&&q!==void 0?q:0);let Q=J===0?0:X/J;if(Q===0)return;let U=new Date;if($.nonEmptySince===null)$.nonEmptySince=U;$.lastUpdated=U,$.weight=Q}getWeight($){if(!this.latestConfig)return 0;let Y=new Date().getTime();if(Y-$.lastUpdated.getTime()>=this.latestConfig.getWeightExpirationPeriodMs())return $.nonEmptySince=null,0;let T=this.latestConfig.getBlackoutPeriodMs();if(T>0&&($.nonEmptySince===null||Y-$.nonEmptySince.getTime()<T))return 0;return $.weight}calculateAndUpdateState(){if(this.updatesPaused||!this.latestConfig)return;if(this.countChildrenWithState(y0.ConnectivityState.READY)>0){let $=[];for(let[T,q]of this.children){if(q.child.getConnectivityState()!==y0.ConnectivityState.READY)continue;$.push({endpointName:T,picker:q.child.getPicker(),weight:this.getWeight(q)})}PJ("Created picker with weights: "+$.map((T)=>T.endpointName+":"+T.weight).join(","));let Y;if(!this.latestConfig.getEnableOobLoadReport())Y=(T,q)=>{let X=this.children.get(q);if(X)this.updateWeight(X,T)};else Y=null;this.updateState(y0.ConnectivityState.READY,new D3($,Y),null)}else if(this.countChildrenWithState(y0.ConnectivityState.CONNECTING)>0)this.updateState(y0.ConnectivityState.CONNECTING,new $T.QueuePicker(this),null);else if(this.countChildrenWithState(y0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`weighted_round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $T.UnavailablePicker({details:$}),$)}else this.updateState(y0.ConnectivityState.IDLE,new $T.QueuePicker(this),null);for(let{child:$}of this.children.values())if($.getConnectivityState()===y0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,T){PJ(y0.ConnectivityState[this.currentState]+" -> "+y0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,T)}updateAddressList($,Y,T,q){var X,J;if(!(Y instanceof z6))return!1;if(!$.ok){if(this.children.size===0)this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $T.UnavailablePicker($.error),$.error.details);return!0}if($.value.length===0){let Z=`No addresses resolved. Resolution note: ${q}`;return this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $T.UnavailablePicker({details:Z}),Z),!1}PJ("Connect to endpoint list "+$.value.map(W3.endpointToString));let Q=new Date,U=new Set;this.updatesPaused=!0,this.latestConfig=Y;for(let Z of $.value){let K=(0,W3.endpointToString)(Z);U.add(K);let A=this.children.get(K);if(!A)A={child:new _C.LeafLoadBalancer(Z,(0,E3.createChildChannelControlHelper)(this.channelControlHelper,{updateState:(W,E,D)=>{if(this.currentState===y0.ConnectivityState.READY&&W!==y0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(W===y0.ConnectivityState.READY)A.nonEmptySince=null;if(D)this.lastError=D;this.calculateAndUpdateState()},createSubchannel:(W,E)=>{let D=this.channelControlHelper.createSubchannel(W,E);if(A===null||A===void 0?void 0:A.oobMetricsListener)return new V3.OrcaOobMetricsSubchannelWrapper(D,A.oobMetricsListener,this.latestConfig.getOobLoadReportingPeriodMs());else return D}}),T,q),lastUpdated:Q,nonEmptySince:null,weight:0,oobMetricsListener:null},this.children.set(K,A);if(Y.getEnableOobLoadReport())A.oobMetricsListener=(W)=>{this.updateWeight(A,W)};else A.oobMetricsListener=null}for(let[Z,K]of this.children)if(U.has(Z))K.child.startConnecting();else K.child.destroy(),this.children.delete(Z);if(this.updatesPaused=!1,this.calculateAndUpdateState(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer);return this.weightUpdateTimer=(J=(X=setInterval(()=>{if(this.currentState===y0.ConnectivityState.READY)this.calculateAndUpdateState()},Y.getWeightUpdatePeriodMs())).unref)===null||J===void 0?void 0:J.call(X),!0}exitIdle(){}resetBackoff(){}destroy(){for(let $ of this.children.values())$.child.destroy();if(this.children.clear(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer)}getTypeName(){return LJ}}function lC(){(0,E3.registerLoadBalancerType)(LJ,F3,z6)}});var I6=M((T0)=>{Object.defineProperty(T0,"__esModule",{value:!0});T0.experimental=T0.ServerMetricRecorder=T0.ServerInterceptingCall=T0.ResponderBuilder=T0.ServerListenerBuilder=T0.addAdminServicesToServer=T0.getChannelzHandlers=T0.getChannelzServiceDefinition=T0.InterceptorConfigurationError=T0.InterceptingCall=T0.RequesterBuilder=T0.ListenerBuilder=T0.StatusBuilder=T0.getClientChannel=T0.ServerCredentials=T0.Server=T0.setLogVerbosity=T0.setLogger=T0.load=T0.loadObject=T0.CallCredentials=T0.ChannelCredentials=T0.waitForClientReady=T0.closeClient=T0.Channel=T0.makeGenericClientConstructor=T0.makeClientConstructor=T0.loadPackageDefinition=T0.Client=T0.compressionAlgorithms=T0.propagate=T0.connectivityState=T0.status=T0.logVerbosity=T0.Metadata=T0.credentials=void 0;var Q9=g8();Object.defineProperty(T0,"CallCredentials",{enumerable:!0,get:function(){return Q9.CallCredentials}});var iC=AX();Object.defineProperty(T0,"Channel",{enumerable:!0,get:function(){return iC.ChannelImplementation}});var rC=R5();Object.defineProperty(T0,"compressionAlgorithms",{enumerable:!0,get:function(){return rC.CompressionAlgorithms}});var aC=l0();Object.defineProperty(T0,"connectivityState",{enumerable:!0,get:function(){return aC.ConnectivityState}});var U9=PY();Object.defineProperty(T0,"ChannelCredentials",{enumerable:!0,get:function(){return U9.ChannelCredentials}});var I3=KX();Object.defineProperty(T0,"Client",{enumerable:!0,get:function(){return I3.Client}});var wJ=i();Object.defineProperty(T0,"logVerbosity",{enumerable:!0,get:function(){return wJ.LogVerbosity}});Object.defineProperty(T0,"status",{enumerable:!0,get:function(){return wJ.Status}});Object.defineProperty(T0,"propagate",{enumerable:!0,get:function(){return wJ.Propagate}});var M3=U0(),SJ=a8();Object.defineProperty(T0,"loadPackageDefinition",{enumerable:!0,get:function(){return SJ.loadPackageDefinition}});Object.defineProperty(T0,"makeClientConstructor",{enumerable:!0,get:function(){return SJ.makeClientConstructor}});Object.defineProperty(T0,"makeGenericClientConstructor",{enumerable:!0,get:function(){return SJ.makeClientConstructor}});var oC=P0();Object.defineProperty(T0,"Metadata",{enumerable:!0,get:function(){return oC.Metadata}});var sC=EV();Object.defineProperty(T0,"Server",{enumerable:!0,get:function(){return sC.Server}});var tC=lq();Object.defineProperty(T0,"ServerCredentials",{enumerable:!0,get:function(){return tC.ServerCredentials}});var eC=NV();Object.defineProperty(T0,"StatusBuilder",{enumerable:!0,get:function(){return eC.StatusBuilder}});T0.credentials={combineChannelCredentials:($,...Y)=>{return Y.reduce((T,q)=>T.compose(q),$)},combineCallCredentials:($,...Y)=>{return Y.reduce((T,q)=>T.compose(q),$)},createInsecure:U9.ChannelCredentials.createInsecure,createSsl:U9.ChannelCredentials.createSsl,createFromSecureContext:U9.ChannelCredentials.createFromSecureContext,createFromMetadataGenerator:Q9.CallCredentials.createFromMetadataGenerator,createFromGoogleCredential:Q9.CallCredentials.createFromGoogleCredential,createEmpty:Q9.CallCredentials.createEmpty};var $y=($)=>$.close();T0.closeClient=$y;var Yy=($,Y,T)=>$.waitForReady(Y,T);T0.waitForClientReady=Yy;var Ty=($,Y)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};T0.loadObject=Ty;var qy=($,Y,T)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};T0.load=qy;var Xy=($)=>{M3.setLogger($)};T0.setLogger=Xy;var Jy=($)=>{M3.setLoggerVerbosity($)};T0.setLogVerbosity=Jy;var Qy=($)=>{return I3.Client.prototype.getChannel.call($)};T0.getClientChannel=Qy;var Z9=UX();Object.defineProperty(T0,"ListenerBuilder",{enumerable:!0,get:function(){return Z9.ListenerBuilder}});Object.defineProperty(T0,"RequesterBuilder",{enumerable:!0,get:function(){return Z9.RequesterBuilder}});Object.defineProperty(T0,"InterceptingCall",{enumerable:!0,get:function(){return Z9.InterceptingCall}});Object.defineProperty(T0,"InterceptorConfigurationError",{enumerable:!0,get:function(){return Z9.InterceptorConfigurationError}});var B3=y$();Object.defineProperty(T0,"getChannelzServiceDefinition",{enumerable:!0,get:function(){return B3.getChannelzServiceDefinition}});Object.defineProperty(T0,"getChannelzHandlers",{enumerable:!0,get:function(){return B3.getChannelzHandlers}});var Uy=i8();Object.defineProperty(T0,"addAdminServicesToServer",{enumerable:!0,get:function(){return Uy.addAdminServicesToServer}});var CJ=XJ();Object.defineProperty(T0,"ServerListenerBuilder",{enumerable:!0,get:function(){return CJ.ServerListenerBuilder}});Object.defineProperty(T0,"ResponderBuilder",{enumerable:!0,get:function(){return CJ.ResponderBuilder}});Object.defineProperty(T0,"ServerInterceptingCall",{enumerable:!0,get:function(){return CJ.ServerInterceptingCall}});var Zy=iq();Object.defineProperty(T0,"ServerMetricRecorder",{enumerable:!0,get:function(){return Zy.ServerMetricRecorder}});var Ky=GJ();T0.experimental=Ky;var Ay=k5(),Wy=mV(),Gy=lV(),Ey=V6(),Vy=tV(),Dy=Q3(),Fy=z3(),Ny=y$();(()=>{Ay.setup(),Wy.setup(),Gy.setup(),Ey.setup(),Vy.setup(),Dy.setup(),Fy.setup(),Ny.setup()})()});import{existsSync as uJ,mkdirSync as dJ}from"node:fs";import{dirname as cJ,join as J0}from"node:path";var w6="agents",UT="hooks",H1="skills",ZT="rules",KT="workflows",N9="plugins",pJ="cline_mcp_settings.json",W$=process?.env?.HOME||"~",lJ=!1;function nJ($){let Y=$.trim();if(!Y)return;W$=Y,lJ=!0}function S6($){if(lJ)return;let Y=$.trim();if(!Y)return;W$=Y}function AT(){return J0(W$,"Documents","Cline")}function C6(){return J0(AT(),"Agents")}function WT(){return J0(AT(),"Hooks")}function GT(){return J0(AT(),"Rules")}function ET(){return J0(AT(),"Workflows")}function t0(){let $=process.env.CLINE_DATA_DIR?.trim();if($)return $;return J0(W$,".cline","data")}function G$(){let $=process.env.CLINE_SESSION_DATA_DIR?.trim();if($)return $;return J0(t0(),"sessions")}function y6(){let $=process.env.CLINE_TEAM_DATA_DIR?.trim();if($)return $;return J0(t0(),"teams")}function H9(){let $=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if($)return $;return J0(t0(),"settings","providers.json")}function z9(){let $=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if($)return $;return J0(t0(),"settings",pJ)}function VT($){let Y=new Set,T=[];for(let q of $){if(!q||Y.has(q))continue;Y.add(q),T.push(q)}return T}function WD($){if(!$)return[];return[J0($,".clinerules",H1),J0($,".cline",H1),J0($,".claude",H1),J0($,".agents",H1)]}function I9(){return J0(t0(),"settings",w6)}function M9(){return[C6(),I9()]}function B9($){return VT([$?J0($,".clinerules",UT):"",WT()])}function DT($){return VT([...WD($),J0(t0(),"settings",H1),J0(W$,".cline",H1),J0(W$,".agents",H1)])}function R9($){return VT([$?J0($,".clinerules"):"",J0(t0(),"settings",ZT),GT()])}function O9($){return VT([$?J0($,".clinerules","workflows"):"",J0(t0(),"settings",KT),ET()])}function P9($){return VT([$?J0($,".clinerules",N9):"",J0(W$,".cline",N9),J0(W$,".agents",N9)])}function FT($){let Y=cJ($);if(!uJ(Y))dJ(Y,{recursive:!0})}function iJ($){if($?.trim())return FT($),cJ($);let Y=J0(t0(),"hooks");if(!uJ(Y))dJ(Y,{recursive:!0});return Y}import XF from"yaml";import{z as A1}from"zod";import{z as E$}from"zod";var rJ=E$.enum(["connector.started","connector.stopping","message.received","message.completed","message.failed","session.started","session.reused","thread.reset","schedule.delivery.started","schedule.delivery.sent","schedule.delivery.failed"]),GD=E$.object({adapter:E$.string(),botUserName:E$.string().optional(),event:rJ,payload:E$.record(E$.string(),E$.unknown()),ts:E$.string()});var aJ=[{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-native"},{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-codex"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic",runtimeProviderId:"claude-code"},{modelsDevKey:"google",generatedProviderId:"gemini"},{modelsDevKey:"deepseek",generatedProviderId:"deepseek"},{modelsDevKey:"xai",generatedProviderId:"xai"},{modelsDevKey:"togetherai",runtimeProviderId:"together",generatedProviderId:"together"},{modelsDevKey:"sap-ai-core",runtimeProviderId:"sapaicore",generatedProviderId:"sapaicore"},{modelsDevKey:"fireworks-ai",runtimeProviderId:"fireworks",generatedProviderId:"fireworks"},{modelsDevKey:"groq",runtimeProviderId:"groq",generatedProviderId:"groq"},{modelsDevKey:"cerebras",runtimeProviderId:"cerebras",generatedProviderId:"cerebras"},{modelsDevKey:"sambanova",runtimeProviderId:"sambanova",generatedProviderId:"sambanova"},{modelsDevKey:"nebius",runtimeProviderId:"nebius",generatedProviderId:"nebius"},{modelsDevKey:"huggingface",runtimeProviderId:"huggingface",generatedProviderId:"huggingface"},{modelsDevKey:"openrouter",runtimeProviderId:"cline",generatedProviderId:"openrouter"},{modelsDevKey:"ollama",runtimeProviderId:"ollama-cloud"},{modelsDevKey:"ollama-cloud",generatedProviderId:"ollama"},{modelsDevKey:"vercel",runtimeProviderId:"dify",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"vercel",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"aihubmix",runtimeProviderId:"aihubmix",generatedProviderId:"aihubmix"},{modelsDevKey:"hicap",runtimeProviderId:"hicap"},{modelsDevKey:"nous-research",runtimeProviderId:"nousResearch"},{modelsDevKey:"huawei-cloud-maas",runtimeProviderId:"huawei-cloud-maas"},{modelsDevKey:"baseten",runtimeProviderId:"baseten",generatedProviderId:"baseten"},{modelsDevKey:"google-vertex-anthropic",generatedProviderId:"vertex"},{modelsDevKey:"lmstudio",generatedProviderId:"lmstudio"},{modelsDevKey:"zai",generatedProviderId:"zai"},{modelsDevKey:"requesty",generatedProviderId:"requesty"},{modelsDevKey:"amazon-bedrock",generatedProviderId:"bedrock"},{modelsDevKey:"moonshotai",generatedProviderId:"moonshot"},{modelsDevKey:"minimax",generatedProviderId:"minimax"}];function ED($){return Object.fromEntries(aJ.flatMap((Y)=>{let T=$==="modelsDevKey"?Y.modelsDevKey:Y.generatedProviderId;return T?[[Y.modelsDevKey,T]]:[]}))}var VD=ED("generatedProviderId");import{z as v0}from"zod";var DD=v0.object({agentId:v0.string(),conversationId:v0.string(),iteration:v0.number(),abortSignal:v0.custom().optional(),metadata:v0.record(v0.string(),v0.unknown()).optional()}),FD=v0.object({id:v0.string(),name:v0.string(),input:v0.unknown(),output:v0.unknown(),error:v0.string().optional(),durationMs:v0.number(),startedAt:v0.date(),endedAt:v0.date()});import{z as oJ}from"zod";function z1($,Y){let T=$.safeParse(Y);if(!T.success)throw Error(oJ.prettifyError(T.error));return T.data}function I1($){return oJ.toJSONSchema($)}function j6($,Y="act"){return`<user_input mode="${Y}">${$}</user_input>`}function v6($){if(!$?.trim())return"";return sJ($,"user_input")}function sJ($,Y){if(!$?.trim())return"";if(!Y)return $;let T=new RegExp(`<${Y}.*?>(.*?)</${Y}>`,"g");return $.replace(T,"$1")}var x6="runtime.team.progress.v1",k6="runtime.team.lifecycle.v1";function tJ($){let Y=$?.trim();return Y?Y:void 0}function h6($){return tJ($?.rootSessionId)}function eJ($){return tJ($?.hookLogPath)}var L9=["running","completed","failed","cancelled"];var v1={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question"},_$=[v1.READ_FILES,v1.SEARCH_CODEBASE,v1.RUN_COMMANDS,v1.FETCH_WEB_CONTENT,v1.APPLY_PATCH,v1.EDITOR,v1.SKILLS,v1.ASK];import{createTool as V$}from"@clinebot/agents";import{z as r}from"zod";var ND=r.string().describe("The absolute file path of a text file to read content from"),_6=r.object({file_paths:r.array(ND).describe("Array of absolute file paths to get full content from. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),$Q=r.union([_6,r.array(r.string()),r.string()]),g6=r.object({queries:r.array(r.string()).describe("Array of regex search queries to execute")}),w9=r.string(),m6=r.object({commands:r.array(w9).describe("Array of shell commands to execute.")}),YQ=r.union([m6,r.array(w9),w9]),TQ=r.object({url:r.string().describe("The URL to fetch"),prompt:r.string().min(2).describe("Analysis prompt for the fetched content")}),f6=r.object({requests:r.array(TQ).describe("Array of the URLs for the web fetch requests")}),b6=r.object({command:r.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert"),path:r.string().min(1).describe("Absolute file path"),file_text:r.string().nullish().describe("Full file content required for 'create' command"),old_str:r.string().nullish().describe("Exact text to replace (must match exactly once) for 'str_replace' command"),new_str:r.string().nullish().describe("Replacement text for 'str_replace' or 'insert' commands"),insert_line:r.number().int().nullish().describe("Optional one-based line index for 'insert' command")}).refine(($)=>$.command!=="create"||$.file_text!=null,{path:["file_text"],message:"file_text is required for command=create"}).refine(($)=>$.command!=="str_replace"||$.old_str!=null,{path:["old_str"],message:"old_str is required for command=str_replace"}).refine(($)=>$.command!=="insert"||$.insert_line!=null,{path:["insert_line"],message:"insert_line is required for command=insert"}).refine(($)=>$.command!=="insert"||$.new_str!=null,{path:["new_str"],message:"new_str is required for command=insert"}),u6=r.object({input:r.string().min(1).describe("The apply_patch text payload, including patch instructions")}),qQ=r.union([u6,r.string()]),d6=r.object({skill:r.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:r.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),c6=r.object({question:r.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:r.array(r.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function KY($){if($ instanceof Error)return $.message;return String($)}function D$($,Y,T){return Promise.race([$,new Promise((q,X)=>{setTimeout(()=>X(Error(T)),Y)})])}var HD=`This is a custom utility that makes it more convenient to add, remove, move, or edit code in a single file. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` command, you should pass a message of the following structure as "input":
|
|
19
|
+
`+Y);let T;try{T=A$.Metadata.fromHttp2Headers($)}catch(J){T=new A$.Metadata}let q=T.getMap(),X;if(typeof q["grpc-status"]==="string"){let J=Number(q["grpc-status"]);this.trace("received status code "+J+" from server"),T.remove("grpc-status");let Q="";if(typeof q["grpc-message"]==="string"){try{Q=decodeURI(q["grpc-message"])}catch(U){Q=q["grpc-message"]}T.remove("grpc-message"),this.trace('received status details string "'+Q+'" from server')}X={code:J,details:Q,metadata:T}}else if(this.httpStatusCode)X=m5(this.httpStatusCode),X.metadata=T;else X={code:X0.Status.UNKNOWN,details:"No status information received",metadata:T};this.endCall(X)}destroyHttp2Stream(){var $;if(this.http2Stream.destroyed)return;if(this.serverEndedCall)this.http2Stream.end();else{let Y;if((($=this.finalStatus)===null||$===void 0?void 0:$.code)===X0.Status.OK)Y=K$.constants.NGHTTP2_NO_ERROR;else Y=K$.constants.NGHTTP2_CANCEL;this.trace("close http2 stream with code "+Y),this.http2Stream.close(Y)}}cancelWithStatus($,Y){this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),this.endCall({code:$,details:Y,metadata:new A$.Metadata})}getStatus(){return this.finalStatus}getPeer(){return this.transport.getPeerName()}getCallNumber(){return this.callId}getAuthContext(){return this.transport.getAuthContext()}startRead(){if(this.finalStatus!==null&&this.finalStatus.code!==X0.Status.OK){this.readsClosed=!0,this.maybeOutputStatus();return}if(this.canPush=!0,this.unpushedReadMessages.length>0){let $=this.unpushedReadMessages.shift();this.push($);return}this.http2Stream.resume()}sendMessageWithContext($,Y){this.trace("write() called with message of length "+Y.length);let T=(q)=>{process.nextTick(()=>{var X;let J=X0.Status.UNAVAILABLE;if((q===null||q===void 0?void 0:q.code)==="ERR_STREAM_WRITE_AFTER_END")J=X0.Status.INTERNAL;if(q)this.cancelWithStatus(J,`Write error: ${q.message}`);(X=$.callback)===null||X===void 0||X.call($)})};this.trace("sending data chunk of length "+Y.length),this.callEventTracker.addMessageSent();try{this.http2Stream.write(Y,T)}catch(q){this.endCall({code:X0.Status.UNAVAILABLE,details:`Write failed with error ${q.message}`,metadata:new A$.Metadata})}}halfClose(){this.trace("end() called"),this.trace("calling end() on HTTP/2 stream"),this.http2Stream.end()}}mG.Http2SubchannelCall=gG});var lG=B((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});cG.Http2SubchannelConnector=void 0;var $Y=s("http2"),ML=s("tls"),gq=y$(),UT=i(),BL=_5(),lY=U0(),RL=B1(),mq=r0(),f5=p0(),OL=s("net"),PL=bG(),LL=jq(),b5="transport",wL="transport_flowctrl",SL=f4().version,{HTTP2_HEADER_AUTHORITY:CL,HTTP2_HEADER_CONTENT_TYPE:yL,HTTP2_HEADER_METHOD:jL,HTTP2_HEADER_PATH:vL,HTTP2_HEADER_TE:xL,HTTP2_HEADER_USER_AGENT:kL}=$Y.constants,hL=20000,_L=Buffer.from("too_many_pings","ascii");class uG{constructor($,Y,T,q){if(this.session=$,this.options=T,this.remoteName=q,this.keepaliveTimer=null,this.pendingSendKeepalivePing=!1,this.activeCalls=new Set,this.disconnectListeners=[],this.disconnectHandled=!1,this.channelzEnabled=!0,this.keepalivesSent=0,this.messagesSent=0,this.messagesReceived=0,this.lastMessageSentTimestamp=null,this.lastMessageReceivedTimestamp=null,this.subchannelAddressString=(0,mq.subchannelAddressToString)(Y),T["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.streamTracker=new gq.ChannelzCallTrackerStub;else this.streamTracker=new gq.ChannelzCallTracker;if(this.channelzRef=(0,gq.registerChannelzSocket)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.userAgent=[T["grpc.primary_user_agent"],`grpc-node-js/${SL}`,T["grpc.secondary_user_agent"]].filter((X)=>X).join(" "),"grpc.keepalive_time_ms"in T)this.keepaliveTimeMs=T["grpc.keepalive_time_ms"];else this.keepaliveTimeMs=-1;if("grpc.keepalive_timeout_ms"in T)this.keepaliveTimeoutMs=T["grpc.keepalive_timeout_ms"];else this.keepaliveTimeoutMs=hL;if("grpc.keepalive_permit_without_calls"in T)this.keepaliveWithoutCalls=T["grpc.keepalive_permit_without_calls"]===1;else this.keepaliveWithoutCalls=!1;if($.once("close",()=>{this.trace("session closed"),this.handleDisconnect()}),$.once("goaway",(X,J,Q)=>{let U=!1;if(X===$Y.constants.NGHTTP2_ENHANCE_YOUR_CALM&&Q&&Q.equals(_L))U=!0;this.trace("connection closed by GOAWAY with code "+X+" and data "+(Q===null||Q===void 0?void 0:Q.toString())),this.reportDisconnectToOwner(U)}),$.once("error",(X)=>{this.trace("connection closed with error "+X.message),this.handleDisconnect()}),$.socket.once("close",(X)=>{this.trace("connection closed. hadError="+X),this.handleDisconnect()}),lY.isTracerEnabled(b5))$.on("remoteSettings",(X)=>{this.trace("new settings received"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))}),$.on("localSettings",(X)=>{this.trace("local settings acknowledged by remote"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))});if(this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer();if($.socket instanceof ML.TLSSocket)this.authContext={transportSecurityType:"ssl",sslPeerCertificate:$.socket.getPeerCertificate()};else this.authContext={}}getChannelzInfo(){var $,Y,T;let q=this.session.socket,X=q.remoteAddress?(0,mq.stringToSubchannelAddress)(q.remoteAddress,q.remotePort):null,J=q.localAddress?(0,mq.stringToSubchannelAddress)(q.localAddress,q.localPort):null,Q;if(this.session.encrypted){let Z=q,K=Z.getCipher(),A=Z.getCertificate(),W=Z.getPeerCertificate();Q={cipherSuiteStandardName:($=K.standardName)!==null&&$!==void 0?$:null,cipherSuiteOtherName:K.standardName?null:K.name,localCertificate:A&&"raw"in A?A.raw:null,remoteCertificate:W&&"raw"in W?W.raw:null}}else Q=null;return{remoteAddress:X,localAddress:J,security:Q,remoteName:this.remoteName,streamsStarted:this.streamTracker.callsStarted,streamsSucceeded:this.streamTracker.callsSucceeded,streamsFailed:this.streamTracker.callsFailed,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,keepAlivesSent:this.keepalivesSent,lastLocalStreamCreatedTimestamp:this.streamTracker.lastCallStartedTimestamp,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:this.lastMessageSentTimestamp,lastMessageReceivedTimestamp:this.lastMessageReceivedTimestamp,localFlowControlWindow:(Y=this.session.state.localWindowSize)!==null&&Y!==void 0?Y:null,remoteFlowControlWindow:(T=this.session.state.remoteWindowSize)!==null&&T!==void 0?T:null}}trace($){lY.trace(UT.LogVerbosity.DEBUG,b5,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}keepaliveTrace($){lY.trace(UT.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}flowControlTrace($){lY.trace(UT.LogVerbosity.DEBUG,wL,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}internalsTrace($){lY.trace(UT.LogVerbosity.DEBUG,"transport_internals","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}reportDisconnectToOwner($){if(this.disconnectHandled)return;this.disconnectHandled=!0,this.disconnectListeners.forEach((Y)=>Y($))}handleDisconnect(){this.clearKeepaliveTimeout(),this.reportDisconnectToOwner(!1);for(let $ of this.activeCalls)$.onDisconnect();setImmediate(()=>{this.session.destroy()})}addDisconnectListener($){this.disconnectListeners.push($)}canSendPing(){return!this.session.destroyed&&this.keepaliveTimeMs>0&&(this.keepaliveWithoutCalls||this.activeCalls.size>0)}maybeSendPing(){var $,Y;if(!this.canSendPing()){this.pendingSendKeepalivePing=!0;return}if(this.keepaliveTimer){console.error("keepaliveTimeout is not null");return}if(this.channelzEnabled)this.keepalivesSent+=1;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.keepaliveTrace("Ping timeout passed without response"),this.handleDisconnect()},this.keepaliveTimeoutMs),(Y=($=this.keepaliveTimer).unref)===null||Y===void 0||Y.call($);let T="";try{if(!this.session.ping((X,J,Q)=>{if(this.clearKeepaliveTimeout(),X)this.keepaliveTrace("Ping failed with error "+X.message),this.handleDisconnect();else this.keepaliveTrace("Received ping response"),this.maybeStartKeepalivePingTimer()}))T="Ping returned false"}catch(q){T=(q instanceof Error?q.message:"")||"Unknown error"}if(T)this.keepaliveTrace("Ping send failed: "+T),this.handleDisconnect()}maybeStartKeepalivePingTimer(){var $,Y;if(!this.canSendPing())return;if(this.pendingSendKeepalivePing)this.pendingSendKeepalivePing=!1,this.maybeSendPing();else if(!this.keepaliveTimer)this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.maybeSendPing()},this.keepaliveTimeMs),(Y=($=this.keepaliveTimer).unref)===null||Y===void 0||Y.call($)}clearKeepaliveTimeout(){if(this.keepaliveTimer)clearTimeout(this.keepaliveTimer),this.keepaliveTimer=null}removeActiveCall($){if(this.activeCalls.delete($),this.activeCalls.size===0)this.session.unref()}addActiveCall($){if(this.activeCalls.add($),this.activeCalls.size===1){if(this.session.ref(),!this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer()}}createCall($,Y,T,q,X){let J=$.toHttp2Headers();J[CL]=Y,J[kL]=this.userAgent,J[yL]="application/grpc",J[jL]="POST",J[vL]=T,J[xL]="trailers";let Q;try{Q=this.session.request(J)}catch(K){throw this.handleDisconnect(),K}this.flowControlTrace("local window size: "+this.session.state.localWindowSize+" remote window size: "+this.session.state.remoteWindowSize),this.internalsTrace("session.closed="+this.session.closed+" session.destroyed="+this.session.destroyed+" session.socket.destroyed="+this.session.socket.destroyed);let U,Z;if(this.channelzEnabled)this.streamTracker.addCallStarted(),U={addMessageSent:()=>{var K;this.messagesSent+=1,this.lastMessageSentTimestamp=new Date,(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;this.messagesReceived+=1,this.lastMessageReceivedTimestamp=new Date,(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;if(K)this.streamTracker.addCallSucceeded();else this.streamTracker.addCallFailed();(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};else U={addMessageSent:()=>{var K;(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};return Z=new PL.Http2SubchannelCall(Q,U,q,this,(0,LL.getNextCallNumber)()),this.addActiveCall(Z),Z}getChannelzRef(){return this.channelzRef}getPeerName(){return this.subchannelAddressString}getOptions(){return this.options}getAuthContext(){return this.authContext}shutdown(){this.session.close(),(0,gq.unregisterChannelzRef)(this.channelzRef)}}class dG{constructor($){this.channelTarget=$,this.session=null,this.isShutdown=!1}trace($){lY.trace(UT.LogVerbosity.DEBUG,b5,(0,f5.uriToString)(this.channelTarget)+" "+$)}createSession($,Y,T){if(this.isShutdown)return Promise.reject();if($.socket.closed)return Promise.reject("Connection closed before starting HTTP/2 handshake");return new Promise((q,X)=>{var J,Q,U,Z,K,A,W,E;let V=null,F=this.channelTarget;if("grpc.http_connect_target"in T){let C=(0,f5.parseUri)(T["grpc.http_connect_target"]);if(C)F=C,V=(0,f5.uriToString)(C)}let H=$.secure?"https":"http",D=(0,RL.getDefaultAuthority)(F),I=()=>{var C;(C=this.session)===null||C===void 0||C.destroy(),this.session=null,setImmediate(()=>{if(!m)m=!0,X(`${k.trim()} (${new Date().toISOString()})`)})},S=(C)=>{var j;if((j=this.session)===null||j===void 0||j.destroy(),k=C.message,this.trace("connection failed with error "+k),!m)m=!0,X(`${k} (${new Date().toISOString()})`)},v={createConnection:(C,j)=>{return $.socket},settings:{initialWindowSize:(Z=(J=T["grpc-node.flow_control_window"])!==null&&J!==void 0?J:(U=(Q=$Y.getDefaultSettings)===null||Q===void 0?void 0:Q.call($Y))===null||U===void 0?void 0:U.initialWindowSize)!==null&&Z!==void 0?Z:65535},maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER,maxSessionMemory:(K=T["grpc-node.max_session_memory"])!==null&&K!==void 0?K:Number.MAX_SAFE_INTEGER},z=$Y.connect(`${H}://${D}`,v),_=(E=(W=(A=$Y.getDefaultSettings)===null||A===void 0?void 0:A.call($Y))===null||W===void 0?void 0:W.initialWindowSize)!==null&&E!==void 0?E:65535,y=T["grpc-node.flow_control_window"];this.session=z;let k="Failed to connect",m=!1;z.unref(),z.once("remoteSettings",()=>{var C;if(y&&y>_)try{z.setLocalWindowSize(y)}catch(j){let M=y-((C=z.state.localWindowSize)!==null&&C!==void 0?C:_);if(M>0)z.incrementWindowSize(M)}z.removeAllListeners(),$.socket.removeListener("close",I),$.socket.removeListener("error",S),q(new uG(z,Y,T,V)),this.session=null}),z.once("close",I),z.once("error",S),$.socket.once("close",I),$.socket.once("error",S)})}tcpConnect($,Y){return(0,BL.getProxiedConnection)($,Y).then((T)=>{if(T)return T;else return new Promise((q,X)=>{let J=()=>{X(Error("Socket closed"))},Q=(Z)=>{X(Z)},U=OL.connect($,()=>{U.removeListener("close",J),U.removeListener("error",Q),q(U)});U.once("close",J),U.once("error",Q)})})}async connect($,Y,T){if(this.isShutdown)return Promise.reject();let q=null,X=null,J=(0,mq.subchannelAddressToString)($);try{return this.trace(J+" Waiting for secureConnector to be ready"),await Y.waitForReady(),this.trace(J+" secureConnector is ready"),q=await this.tcpConnect($,T),q.setNoDelay(),this.trace(J+" Established TCP connection"),X=await Y.connect(q),this.trace(J+" Established secure connection"),this.createSession(X,$,T)}catch(Q){throw q===null||q===void 0||q.destroy(),X===null||X===void 0||X.socket.destroy(),Q}}shutdown(){var $;this.isShutdown=!0,($=this.session)===null||$===void 0||$.close(),this.session=null}}cG.Http2SubchannelConnector=dG});var rG=B((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});nG.SubchannelPool=void 0;nG.getSubchannelPool=pL;var gL=TZ(),mL=IG(),fL=r0(),bL=p0(),uL=lG(),dL=1e4;class fq{constructor(){this.pool=Object.create(null),this.cleanupTimer=null}unrefUnusedSubchannels(){let $=!0;for(let Y in this.pool){let q=this.pool[Y].filter((X)=>!X.subchannel.unrefIfOneRef());if(q.length>0)$=!1;this.pool[Y]=q}if($&&this.cleanupTimer!==null)clearInterval(this.cleanupTimer),this.cleanupTimer=null}ensureCleanupTask(){var $,Y;if(this.cleanupTimer===null)this.cleanupTimer=setInterval(()=>{this.unrefUnusedSubchannels()},dL),(Y=($=this.cleanupTimer).unref)===null||Y===void 0||Y.call($)}getOrCreateSubchannel($,Y,T,q){this.ensureCleanupTask();let X=(0,bL.uriToString)($);if(X in this.pool){let Q=this.pool[X];for(let U of Q)if((0,fL.subchannelAddressEqual)(Y,U.subchannelAddress)&&(0,gL.channelOptionsEqual)(T,U.channelArguments)&&q._equals(U.channelCredentials))return U.subchannel}let J=new mL.Subchannel($,Y,T,q,new uL.Http2SubchannelConnector($));if(!(X in this.pool))this.pool[X]=[];return this.pool[X].push({subchannelAddress:Y,channelArguments:T,channelCredentials:q,subchannel:J}),J.ref(),J}}nG.SubchannelPool=fq;var cL=new fq;function pL($){if($)return cL;else return new fq}});var $E=B((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});tG.LoadBalancingCall=void 0;var aG=l0(),bq=i(),oG=uY(),uq=P0(),ZT=Y$(),nL=p0(),iL=U0(),u5=TT(),rL=s("http2"),aL="load_balancing_call";class sG{constructor($,Y,T,q,X,J,Q){var U,Z;this.channel=$,this.callConfig=Y,this.methodName=T,this.host=q,this.credentials=X,this.deadline=J,this.callNumber=Q,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.metadata=null,this.listener=null,this.onCallEnded=null,this.childStartTime=null;let K=this.methodName.split("/"),A="";if(K.length>=2)A=K[1];let W=(Z=(U=(0,nL.splitHostPort)(this.host))===null||U===void 0?void 0:U.host)!==null&&Z!==void 0?Z:"localhost";this.serviceUrl=`https://${W}/${A}`,this.startTime=new Date}getDeadlineInfo(){var $,Y;let T=[];if(this.childStartTime){if(this.childStartTime>this.startTime){if(($=this.metadata)===null||$===void 0?void 0:$.getOptions().waitForReady)T.push("wait_for_ready");T.push(`LB pick: ${(0,oG.formatDateDifference)(this.startTime,this.childStartTime)}`)}return T.push(...this.child.getDeadlineInfo()),T}else{if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)T.push("wait_for_ready");T.push("Waiting for LB pick")}return T}trace($){iL.trace(bq.LogVerbosity.DEBUG,aL,"["+this.callNumber+"] "+$)}outputStatus($,Y){var T,q;if(!this.ended){this.ended=!0,this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString());let X=Object.assign(Object.assign({},$),{progress:Y});(T=this.listener)===null||T===void 0||T.onReceiveStatus(X),(q=this.onCallEnded)===null||q===void 0||q.call(this,X.code,X.details,X.metadata)}}doPick(){var $,Y;if(this.ended)return;if(!this.metadata)throw Error("doPick called before start");this.trace("Pick called");let T=this.metadata.clone(),q=this.channel.doPick(T,this.callConfig.pickInformation),X=q.subchannel?"("+q.subchannel.getChannelzRef().id+") "+q.subchannel.getAddress():""+q.subchannel;switch(this.trace("Pick result: "+ZT.PickResultType[q.pickResultType]+" subchannel: "+X+" status: "+(($=q.status)===null||$===void 0?void 0:$.code)+" "+((Y=q.status)===null||Y===void 0?void 0:Y.details)),q.pickResultType){case ZT.PickResultType.COMPLETE:this.credentials.compose(q.subchannel.getCallCredentials()).generateMetadata({method_name:this.methodName,service_url:this.serviceUrl}).then((Z)=>{var K;if(this.ended){this.trace("Credentials metadata generation finished after call ended");return}if(T.merge(Z),T.get("authorization").length>1)this.outputStatus({code:bq.Status.INTERNAL,details:'"authorization" metadata cannot have multiple values',metadata:new uq.Metadata},"PROCESSED");if(q.subchannel.getConnectivityState()!==aG.ConnectivityState.READY){this.trace("Picked subchannel "+X+" has state "+aG.ConnectivityState[q.subchannel.getConnectivityState()]+" after getting credentials metadata. Retrying pick"),this.doPick();return}if(this.deadline!==1/0)T.set("grpc-timeout",(0,oG.getDeadlineTimeoutString)(this.deadline));try{this.child=q.subchannel.getRealSubchannel().createCall(T,this.host,this.methodName,{onReceiveMetadata:(A)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(A)},onReceiveMessage:(A)=>{this.trace("Received message"),this.listener.onReceiveMessage(A)},onReceiveStatus:(A)=>{if(this.trace("Received status"),A.rstCode===rL.constants.NGHTTP2_REFUSED_STREAM)this.outputStatus(A,"REFUSED");else this.outputStatus(A,"PROCESSED")}}),this.childStartTime=new Date}catch(A){this.trace("Failed to start call on picked subchannel "+X+" with error "+A.message),this.outputStatus({code:bq.Status.INTERNAL,details:"Failed to start HTTP/2 stream with error "+A.message,metadata:new uq.Metadata},"NOT_STARTED");return}if((K=q.onCallStarted)===null||K===void 0||K.call(q),this.onCallEnded=q.onCallEnded,this.trace("Created child call ["+this.child.getCallNumber()+"]"),this.readPending)this.child.startRead();if(this.pendingMessage)this.child.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.pendingHalfClose)this.child.halfClose()},(Z)=>{let{code:K,details:A}=(0,u5.restrictControlPlaneStatusCode)(typeof Z.code==="number"?Z.code:bq.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Z.message}`);this.outputStatus({code:K,details:A,metadata:new uq.Metadata},"PROCESSED")});break;case ZT.PickResultType.DROP:let{code:Q,details:U}=(0,u5.restrictControlPlaneStatusCode)(q.status.code,q.status.details);setImmediate(()=>{this.outputStatus({code:Q,details:U,metadata:q.status.metadata},"DROP")});break;case ZT.PickResultType.TRANSIENT_FAILURE:if(this.metadata.getOptions().waitForReady)this.channel.queueCallForPick(this);else{let{code:Z,details:K}=(0,u5.restrictControlPlaneStatusCode)(q.status.code,q.status.details);setImmediate(()=>{this.outputStatus({code:Z,details:K,metadata:q.status.metadata},"PROCESSED")})}break;case ZT.PickResultType.QUEUE:this.channel.queueCallForPick(this)}}cancelWithStatus($,Y){var T;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(T=this.child)===null||T===void 0||T.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new uq.Metadata},"PROCESSED")}getPeer(){var $,Y;return(Y=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.channel.getTarget()}start($,Y){this.trace("start called"),this.listener=Y,this.metadata=$,this.doPick()}sendMessageWithContext($,Y){if(this.trace("write() called with message of length "+Y.length),this.child)this.child.sendMessageWithContext($,Y);else this.pendingMessage={context:$,message:Y}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials($){throw Error("Method not implemented.")}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}tG.LoadBalancingCall=sG});var JE=B((qE)=>{Object.defineProperty(qE,"__esModule",{value:!0});qE.ResolvingCall=void 0;var oL=m8(),YY=i(),TY=uY(),YE=P0(),sL=U0(),tL=TT(),eL="resolving_call";class TE{constructor($,Y,T,q,X){if(this.channel=$,this.method=Y,this.filterStackFactory=q,this.callNumber=X,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.readFilterPending=!1,this.writeFilterPending=!1,this.pendingChildStatus=null,this.metadata=null,this.listener=null,this.statusWatchers=[],this.deadlineTimer=setTimeout(()=>{},0),this.filterStack=null,this.deadlineStartTime=null,this.configReceivedTime=null,this.childStartTime=null,this.credentials=oL.CallCredentials.createEmpty(),this.deadline=T.deadline,this.host=T.host,T.parentCall){if(T.flags&YY.Propagate.CANCELLATION)T.parentCall.on("cancelled",()=>{this.cancelWithStatus(YY.Status.CANCELLED,"Cancelled by parent call")});if(T.flags&YY.Propagate.DEADLINE)this.trace("Propagating deadline from parent: "+T.parentCall.getDeadline()),this.deadline=(0,TY.minDeadline)(this.deadline,T.parentCall.getDeadline())}this.trace("Created"),this.runDeadlineTimer()}trace($){sL.trace(YY.LogVerbosity.DEBUG,eL,"["+this.callNumber+"] "+$)}runDeadlineTimer(){clearTimeout(this.deadlineTimer),this.deadlineStartTime=new Date,this.trace("Deadline: "+(0,TY.deadlineToString)(this.deadline));let $=(0,TY.getRelativeTimeout)(this.deadline);if($!==1/0){this.trace("Deadline will be reached in "+$+"ms");let Y=()=>{if(!this.deadlineStartTime){this.cancelWithStatus(YY.Status.DEADLINE_EXCEEDED,"Deadline exceeded");return}let T=[],q=new Date;if(T.push(`Deadline exceeded after ${(0,TY.formatDateDifference)(this.deadlineStartTime,q)}`),this.configReceivedTime){if(this.configReceivedTime>this.deadlineStartTime)T.push(`name resolution: ${(0,TY.formatDateDifference)(this.deadlineStartTime,this.configReceivedTime)}`);if(this.childStartTime){if(this.childStartTime>this.configReceivedTime)T.push(`metadata filters: ${(0,TY.formatDateDifference)(this.configReceivedTime,this.childStartTime)}`)}else T.push("waiting for metadata filters")}else T.push("waiting for name resolution");if(this.child)T.push(...this.child.getDeadlineInfo());this.cancelWithStatus(YY.Status.DEADLINE_EXCEEDED,T.join(","))};if($<=0)process.nextTick(Y);else this.deadlineTimer=setTimeout(Y,$)}}outputStatus($){if(!this.ended){if(this.ended=!0,!this.filterStack)this.filterStack=this.filterStackFactory.createFilter();clearTimeout(this.deadlineTimer);let Y=this.filterStack.receiveTrailers($);this.trace("ended with status: code="+Y.code+' details="'+Y.details+'"'),this.statusWatchers.forEach((T)=>T(Y)),process.nextTick(()=>{var T;(T=this.listener)===null||T===void 0||T.onReceiveStatus(Y)})}}sendMessageOnChild($,Y){if(!this.child)throw Error("sendMessageonChild called with child not populated");let T=this.child;this.writeFilterPending=!0,this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags})).then((q)=>{if(this.writeFilterPending=!1,T.sendMessageWithContext($,q.message),this.pendingHalfClose)T.halfClose()},(q)=>{this.cancelWithStatus(q.code,q.details)})}getConfig(){if(this.ended)return;if(!this.metadata||!this.listener)throw Error("getConfig called before start");let $=this.channel.getConfig(this.method,this.metadata);if($.type==="NONE"){this.channel.queueCallForConfig(this);return}else if($.type==="ERROR"){if(this.metadata.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($.error);return}this.configReceivedTime=new Date;let Y=$.config;if(Y.status!==YY.Status.OK){let{code:T,details:q}=(0,tL.restrictControlPlaneStatusCode)(Y.status,"Failed to route call to method "+this.method);this.outputStatus({code:T,details:q,metadata:new YE.Metadata});return}if(Y.methodConfig.timeout){let T=new Date;T.setSeconds(T.getSeconds()+Y.methodConfig.timeout.seconds),T.setMilliseconds(T.getMilliseconds()+Y.methodConfig.timeout.nanos/1e6),this.deadline=(0,TY.minDeadline)(this.deadline,T),this.runDeadlineTimer()}this.filterStackFactory.push(Y.dynamicFilterFactories),this.filterStack=this.filterStackFactory.createFilter(),this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((T)=>{if(this.child=this.channel.createRetryingCall(Y,this.method,this.host,this.credentials,this.deadline),this.trace("Created child ["+this.child.getCallNumber()+"]"),this.childStartTime=new Date,this.child.start(T,{onReceiveMetadata:(q)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(q))},onReceiveMessage:(q)=>{this.trace("Received message"),this.readFilterPending=!0,this.filterStack.receiveMessage(q).then((X)=>{if(this.trace("Finished filtering received message"),this.readFilterPending=!1,this.listener.onReceiveMessage(X),this.pendingChildStatus)this.outputStatus(this.pendingChildStatus)},(X)=>{this.cancelWithStatus(X.code,X.details)})},onReceiveStatus:(q)=>{if(this.trace("Received status"),this.readFilterPending)this.pendingChildStatus=q;else this.outputStatus(q)}}),this.readPending)this.child.startRead();if(this.pendingMessage)this.sendMessageOnChild(this.pendingMessage.context,this.pendingMessage.message);else if(this.pendingHalfClose)this.child.halfClose()},(T)=>{this.outputStatus(T)})}reportResolverError($){var Y;if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($)}cancelWithStatus($,Y){var T;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(T=this.child)===null||T===void 0||T.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new YE.Metadata})}getPeer(){var $,Y;return(Y=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.channel.getTarget()}start($,Y){this.trace("start called"),this.metadata=$.clone(),this.listener=Y,this.getConfig()}sendMessageWithContext($,Y){if(this.trace("write() called with message of length "+Y.length),this.child)this.sendMessageOnChild($,Y);else this.pendingMessage={context:$,message:Y}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child&&!this.writeFilterPending)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials($){this.credentials=$}addStatusWatcher($){this.statusWatchers.push($)}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}qE.ResolvingCall=TE});var WE=B((KE)=>{Object.defineProperty(KE,"__esModule",{value:!0});KE.RetryingCall=KE.MessageBufferTracker=KE.RetryThrottler=void 0;var dq=i(),$w=uY(),Yw=P0(),Tw=U0(),qw="retrying_call";class QE{constructor($,Y,T){if(this.maxTokens=$,this.tokenRatio=Y,T)this.tokens=T.tokens*($/T.maxTokens);else this.tokens=$}addCallSucceeded(){this.tokens=Math.min(this.tokens+this.tokenRatio,this.maxTokens)}addCallFailed(){this.tokens=Math.max(this.tokens-1,0)}canRetryCall(){return this.tokens>this.maxTokens/2}}KE.RetryThrottler=QE;class UE{constructor($,Y){this.totalLimit=$,this.limitPerCall=Y,this.totalAllocated=0,this.allocatedPerCall=new Map}allocate($,Y){var T;let q=(T=this.allocatedPerCall.get(Y))!==null&&T!==void 0?T:0;if(this.limitPerCall-q<$||this.totalLimit-this.totalAllocated<$)return!1;return this.allocatedPerCall.set(Y,q+$),this.totalAllocated+=$,!0}free($,Y){var T;if(this.totalAllocated<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > total allocated ${this.totalAllocated}`);this.totalAllocated-=$;let q=(T=this.allocatedPerCall.get(Y))!==null&&T!==void 0?T:0;if(q<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > allocated for call ${q}`);this.allocatedPerCall.set(Y,q-$)}freeAll($){var Y;let T=(Y=this.allocatedPerCall.get($))!==null&&Y!==void 0?Y:0;if(this.totalAllocated<T)throw Error(`Invalid buffer allocation state: call ${$} allocated ${T} > total allocated ${this.totalAllocated}`);this.totalAllocated-=T,this.allocatedPerCall.delete($)}}KE.MessageBufferTracker=UE;var d5="grpc-previous-rpc-attempts",Xw=5;class ZE{constructor($,Y,T,q,X,J,Q,U,Z){var K;this.channel=$,this.callConfig=Y,this.methodName=T,this.host=q,this.credentials=X,this.deadline=J,this.callNumber=Q,this.bufferTracker=U,this.retryThrottler=Z,this.listener=null,this.initialMetadata=null,this.underlyingCalls=[],this.writeBuffer=[],this.writeBufferOffset=0,this.readStarted=!1,this.transparentRetryUsed=!1,this.attempts=0,this.hedgingTimer=null,this.committedCallIndex=null,this.initialRetryBackoffSec=0,this.nextRetryBackoffSec=0;let A=(K=$.getOptions()["grpc-node.retry_max_attempts_limit"])!==null&&K!==void 0?K:Xw;if($.getOptions()["grpc.enable_retries"]===0)this.state="NO_RETRY",this.maxAttempts=1;else if(Y.methodConfig.retryPolicy){this.state="RETRY";let W=Y.methodConfig.retryPolicy;this.nextRetryBackoffSec=this.initialRetryBackoffSec=Number(W.initialBackoff.substring(0,W.initialBackoff.length-1)),this.maxAttempts=Math.min(W.maxAttempts,A)}else if(Y.methodConfig.hedgingPolicy)this.state="HEDGING",this.maxAttempts=Math.min(Y.methodConfig.hedgingPolicy.maxAttempts,A);else this.state="TRANSPARENT_ONLY",this.maxAttempts=1;this.startTime=new Date}getDeadlineInfo(){if(this.underlyingCalls.length===0)return[];let $=[],Y=this.underlyingCalls[this.underlyingCalls.length-1];if(this.underlyingCalls.length>1)$.push(`previous attempts: ${this.underlyingCalls.length-1}`);if(Y.startTime>this.startTime)$.push(`time to current attempt start: ${(0,$w.formatDateDifference)(this.startTime,Y.startTime)}`);return $.push(...Y.call.getDeadlineInfo()),$}getCallNumber(){return this.callNumber}trace($){Tw.trace(dq.LogVerbosity.DEBUG,qw,"["+this.callNumber+"] "+$)}reportStatus($){this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString()),this.bufferTracker.freeAll(this.callNumber),this.writeBufferOffset=this.writeBufferOffset+this.writeBuffer.length,this.writeBuffer=[],process.nextTick(()=>{var Y;(Y=this.listener)===null||Y===void 0||Y.onReceiveStatus({code:$.code,details:$.details,metadata:$.metadata})})}cancelWithStatus($,Y){this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),this.reportStatus({code:$,details:Y,metadata:new Yw.Metadata});for(let{call:T}of this.underlyingCalls)T.cancelWithStatus($,Y)}getPeer(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getPeer();else return"unknown"}getBufferEntry($){var Y;return(Y=this.writeBuffer[$-this.writeBufferOffset])!==null&&Y!==void 0?Y:{entryType:"FREED",allocated:!1}}getNextBufferIndex(){return this.writeBufferOffset+this.writeBuffer.length}clearSentMessages(){if(this.state!=="COMMITTED")return;let $;if(this.underlyingCalls[this.committedCallIndex].state==="COMPLETED")$=this.getNextBufferIndex();else $=this.underlyingCalls[this.committedCallIndex].nextMessageToSend;for(let Y=this.writeBufferOffset;Y<$;Y++){let T=this.getBufferEntry(Y);if(T.allocated)this.bufferTracker.free(T.message.message.length,this.callNumber)}this.writeBuffer=this.writeBuffer.slice($-this.writeBufferOffset),this.writeBufferOffset=$}commitCall($){var Y,T;if(this.state==="COMMITTED")return;this.trace("Committing call ["+this.underlyingCalls[$].call.getCallNumber()+"] at index "+$),this.state="COMMITTED",(T=(Y=this.callConfig).onCommitted)===null||T===void 0||T.call(Y),this.committedCallIndex=$;for(let q=0;q<this.underlyingCalls.length;q++){if(q===$)continue;if(this.underlyingCalls[q].state==="COMPLETED")continue;this.underlyingCalls[q].state="COMPLETED",this.underlyingCalls[q].call.cancelWithStatus(dq.Status.CANCELLED,"Discarded in favor of other hedged attempt")}this.clearSentMessages()}commitCallWithMostMessages(){if(this.state==="COMMITTED")return;let $=-1,Y=-1;for(let[T,q]of this.underlyingCalls.entries())if(q.state==="ACTIVE"&&q.nextMessageToSend>$)$=q.nextMessageToSend,Y=T;if(Y===-1)this.state="TRANSPARENT_ONLY";else this.commitCall(Y)}isStatusCodeInList($,Y){return $.some((T)=>{var q;return T===Y||T.toString().toLowerCase()===((q=dq.Status[Y])===null||q===void 0?void 0:q.toLowerCase())})}getNextRetryJitter(){return Math.random()*0.3999999999999999+0.8}getNextRetryBackoffMs(){var $;let Y=($=this.callConfig)===null||$===void 0?void 0:$.methodConfig.retryPolicy;if(!Y)return 0;let q=this.getNextRetryJitter()*this.nextRetryBackoffSec*1000,X=Number(Y.maxBackoff.substring(0,Y.maxBackoff.length-1));return this.nextRetryBackoffSec=Math.min(this.nextRetryBackoffSec*Y.backoffMultiplier,X),q}maybeRetryCall($,Y){if(this.state!=="RETRY"){Y(!1);return}if(this.attempts>=this.maxAttempts){Y(!1);return}let T;if($===null)T=this.getNextRetryBackoffMs();else if($<0){this.state="TRANSPARENT_ONLY",Y(!1);return}else T=$,this.nextRetryBackoffSec=this.initialRetryBackoffSec;setTimeout(()=>{var q,X;if(this.state!=="RETRY"){Y(!1);return}if((X=(q=this.retryThrottler)===null||q===void 0?void 0:q.canRetryCall())!==null&&X!==void 0?X:!0)Y(!0),this.attempts+=1,this.startNewAttempt();else this.trace("Retry attempt denied by throttling policy"),Y(!1)},T)}countActiveCalls(){let $=0;for(let Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE")$+=1;return $}handleProcessedStatus($,Y,T){var q,X,J;switch(this.state){case"COMMITTED":case"NO_RETRY":case"TRANSPARENT_ONLY":this.commitCall(Y),this.reportStatus($);break;case"HEDGING":if(this.isStatusCodeInList((q=this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes)!==null&&q!==void 0?q:[],$.code)){(X=this.retryThrottler)===null||X===void 0||X.addCallFailed();let Q;if(T===null)Q=0;else if(T<0){this.state="TRANSPARENT_ONLY",this.commitCall(Y),this.reportStatus($);return}else Q=T;setTimeout(()=>{if(this.maybeStartHedgingAttempt(),this.countActiveCalls()===0)this.commitCall(Y),this.reportStatus($)},Q)}else this.commitCall(Y),this.reportStatus($);break;case"RETRY":if(this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes,$.code))(J=this.retryThrottler)===null||J===void 0||J.addCallFailed(),this.maybeRetryCall(T,(Q)=>{if(!Q)this.commitCall(Y),this.reportStatus($)});else this.commitCall(Y),this.reportStatus($);break}}getPushback($){let Y=$.get("grpc-retry-pushback-ms");if(Y.length===0)return null;try{return parseInt(Y[0])}catch(T){return-1}}handleChildStatus($,Y){var T;if(this.underlyingCalls[Y].state==="COMPLETED")return;if(this.trace("state="+this.state+" handling status with progress "+$.progress+" from child ["+this.underlyingCalls[Y].call.getCallNumber()+"] in state "+this.underlyingCalls[Y].state),this.underlyingCalls[Y].state="COMPLETED",$.code===dq.Status.OK){(T=this.retryThrottler)===null||T===void 0||T.addCallSucceeded(),this.commitCall(Y),this.reportStatus($);return}if(this.state==="NO_RETRY"){this.commitCall(Y),this.reportStatus($);return}if(this.state==="COMMITTED"){this.reportStatus($);return}let q=this.getPushback($.metadata);switch($.progress){case"NOT_STARTED":this.startNewAttempt();break;case"REFUSED":if(this.transparentRetryUsed)this.handleProcessedStatus($,Y,q);else this.transparentRetryUsed=!0,this.startNewAttempt();break;case"DROP":this.commitCall(Y),this.reportStatus($);break;case"PROCESSED":this.handleProcessedStatus($,Y,q);break}}maybeStartHedgingAttempt(){if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;if(this.attempts>=this.maxAttempts)return;this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}maybeStartHedgingTimer(){var $,Y,T;if(this.hedgingTimer)clearTimeout(this.hedgingTimer);if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;let q=this.callConfig.methodConfig.hedgingPolicy;if(this.attempts>=this.maxAttempts)return;let X=($=q.hedgingDelay)!==null&&$!==void 0?$:"0s",J=Number(X.substring(0,X.length-1));this.hedgingTimer=setTimeout(()=>{this.maybeStartHedgingAttempt()},J*1000),(T=(Y=this.hedgingTimer).unref)===null||T===void 0||T.call(Y)}startNewAttempt(){let $=this.channel.createLoadBalancingCall(this.callConfig,this.methodName,this.host,this.credentials,this.deadline);this.trace("Created child call ["+$.getCallNumber()+"] for attempt "+this.attempts);let Y=this.underlyingCalls.length;this.underlyingCalls.push({state:"ACTIVE",call:$,nextMessageToSend:0,startTime:new Date});let T=this.attempts-1,q=this.initialMetadata.clone();if(T>0)q.set(d5,`${T}`);let X=!1;if($.start(q,{onReceiveMetadata:(J)=>{if(this.trace("Received metadata from child ["+$.getCallNumber()+"]"),this.commitCall(Y),X=!0,T>0)J.set(d5,`${T}`);if(this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMetadata(J)},onReceiveMessage:(J)=>{if(this.trace("Received message from child ["+$.getCallNumber()+"]"),this.commitCall(Y),this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMessage(J)},onReceiveStatus:(J)=>{if(this.trace("Received status from child ["+$.getCallNumber()+"]"),!X&&T>0)J.metadata.set(d5,`${T}`);this.handleChildStatus(J,Y)}}),this.sendNextChildMessage(Y),this.readStarted)$.startRead()}start($,Y){this.trace("start called"),this.listener=Y,this.initialMetadata=$,this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}handleChildWriteCompleted($,Y){var T,q;(q=(T=this.getBufferEntry(Y)).callback)===null||q===void 0||q.call(T),this.clearSentMessages();let X=this.underlyingCalls[$];X.nextMessageToSend+=1,this.sendNextChildMessage($)}sendNextChildMessage($){let Y=this.underlyingCalls[$];if(Y.state==="COMPLETED")return;let T=Y.nextMessageToSend;if(this.getBufferEntry(T)){let q=this.getBufferEntry(T);switch(q.entryType){case"MESSAGE":if(Y.call.sendMessageWithContext({callback:(J)=>{this.handleChildWriteCompleted($,T)}},q.message.message),this.getBufferEntry(T+1).entryType==="HALF_CLOSE")this.trace("Sending halfClose immediately after message to child ["+Y.call.getCallNumber()+"] - optimizing for unary/final message"),Y.nextMessageToSend+=1,Y.call.halfClose();break;case"HALF_CLOSE":Y.nextMessageToSend+=1,Y.call.halfClose();break;case"FREED":break}}}sendMessageWithContext($,Y){this.trace("write() called with message of length "+Y.length);let T={message:Y,flags:$.flags},q=this.getNextBufferIndex(),X={entryType:"MESSAGE",message:T,allocated:this.bufferTracker.allocate(Y.length,this.callNumber)};if(this.writeBuffer.push(X),X.allocated){process.nextTick(()=>{var J;(J=$.callback)===null||J===void 0||J.call($)});for(let[J,Q]of this.underlyingCalls.entries())if(Q.state==="ACTIVE"&&Q.nextMessageToSend===q)Q.call.sendMessageWithContext({callback:(U)=>{this.handleChildWriteCompleted(J,q)}},Y)}else{if(this.commitCallWithMostMessages(),this.committedCallIndex===null)return;let J=this.underlyingCalls[this.committedCallIndex];if(X.callback=$.callback,J.state==="ACTIVE"&&J.nextMessageToSend===q)J.call.sendMessageWithContext({callback:(Q)=>{this.handleChildWriteCompleted(this.committedCallIndex,q)}},Y)}}startRead(){this.trace("startRead called"),this.readStarted=!0;for(let $ of this.underlyingCalls)if(($===null||$===void 0?void 0:$.state)==="ACTIVE")$.call.startRead()}halfClose(){this.trace("halfClose called");let $=this.getNextBufferIndex();this.writeBuffer.push({entryType:"HALF_CLOSE",allocated:!1});for(let Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE"){if(Y.nextMessageToSend===$||Y.nextMessageToSend===$-1)this.trace("Sending halfClose immediately to child ["+Y.call.getCallNumber()+"] - all messages already sent"),Y.nextMessageToSend+=1,Y.call.halfClose()}}setCredentials($){throw Error("Method not implemented.")}getMethod(){return this.methodName}getHost(){return this.host}getAuthContext(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getAuthContext();else return null}}KE.RetryingCall=ZE});var KT=B((EE)=>{Object.defineProperty(EE,"__esModule",{value:!0});EE.BaseSubchannelWrapper=void 0;class GE{constructor($){this.child=$,this.healthy=!0,this.healthListeners=new Set,this.refcount=0,this.dataWatchers=new Set,$.addHealthStateWatcher((Y)=>{if(this.healthy)this.updateHealthListeners()})}updateHealthListeners(){for(let $ of this.healthListeners)$(this.isHealthy())}getConnectivityState(){return this.child.getConnectivityState()}addConnectivityStateListener($){this.child.addConnectivityStateListener($)}removeConnectivityStateListener($){this.child.removeConnectivityStateListener($)}startConnecting(){this.child.startConnecting()}getAddress(){return this.child.getAddress()}throttleKeepalive($){this.child.throttleKeepalive($)}ref(){this.child.ref(),this.refcount+=1}unref(){if(this.child.unref(),this.refcount-=1,this.refcount===0)this.destroy()}destroy(){for(let $ of this.dataWatchers)$.destroy()}getChannelzRef(){return this.child.getChannelzRef()}isHealthy(){return this.healthy&&this.child.isHealthy()}addHealthStateWatcher($){this.healthListeners.add($)}removeHealthStateWatcher($){this.healthListeners.delete($)}addDataWatcher($){$.setSubchannel(this.getRealSubchannel()),this.dataWatchers.add($)}setHealthy($){if($!==this.healthy){if(this.healthy=$,this.child.isHealthy())this.updateHealthListeners()}}getRealSubchannel(){return this.child.getRealSubchannel()}realSubchannelEquals($){return this.getRealSubchannel()===$.getRealSubchannel()}getCallCredentials(){return this.child.getCallCredentials()}getChannel(){return this.child.getChannel()}}EE.BaseSubchannelWrapper=GE});var n5=B((IE)=>{Object.defineProperty(IE,"__esModule",{value:!0});IE.InternalChannel=IE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=void 0;var Uw=PY(),Zw=e7(),Kw=rG(),l5=Y$(),Aw=P0(),v$=i(),Ww=xq(),Gw=w5(),DE=B1(),cq=U0(),Ew=_5(),pq=p0(),N1=l0(),AT=y$(),Vw=$E(),Dw=uY(),Fw=JE(),c5=jq(),Nw=TT(),p5=WE(),Hw=KT(),zw=2147483647,Iw=1000,Mw=1800000,lq=new Map,Bw=16777216,Rw=1048576;class FE extends Hw.BaseSubchannelWrapper{constructor($,Y){super($);this.channel=Y,this.refCount=0,this.subchannelStateListener=(T,q,X,J)=>{Y.throttleKeepalive(J)}}ref(){if(this.refCount===0)this.child.addConnectivityStateListener(this.subchannelStateListener),this.channel.addWrappedSubchannel(this);this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0)this.child.removeConnectivityStateListener(this.subchannelStateListener),this.channel.removeWrappedSubchannel(this)}}class NE{pick($){return{pickResultType:l5.PickResultType.DROP,status:{code:v$.Status.UNAVAILABLE,details:"Channel closed before call started",metadata:new Aw.Metadata},subchannel:null,onCallStarted:null,onCallEnded:null}}}IE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX="grpc.internal.no_subchannel";class HE{constructor($){this.target=$,this.trace=new AT.ChannelzTrace,this.callTracker=new AT.ChannelzCallTracker,this.childrenTracker=new AT.ChannelzChildrenTracker,this.state=N1.ConnectivityState.IDLE}getChannelzInfoCallback(){return()=>{return{target:this.target,state:this.state,trace:this.trace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}}}}class zE{constructor($,Y,T){var q,X,J,Q,U,Z;if(this.credentials=Y,this.options=T,this.connectivityState=N1.ConnectivityState.IDLE,this.currentPicker=new l5.UnavailablePicker,this.configSelectionQueue=[],this.pickQueue=[],this.connectivityStateWatchers=[],this.callRefTimer=null,this.configSelector=null,this.currentResolutionError=null,this.wrappedSubchannels=new Set,this.callCount=0,this.idleTimer=null,this.channelzEnabled=!0,this.randomChannelId=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),typeof $!=="string")throw TypeError("Channel target must be a string");if(!(Y instanceof Uw.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(T){if(typeof T!=="object")throw TypeError("Channel options must be an object")}this.channelzInfoTracker=new HE($);let K=(0,pq.parseUri)($);if(K===null)throw Error(`Could not parse target name "${$}"`);let A=(0,DE.mapUriDefaultScheme)(K);if(A===null)throw Error(`Could not find a default scheme for target name "${$}"`);if(this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1;if(this.channelzRef=(0,AT.registerChannelzChannel)($,this.channelzInfoTracker.getChannelzInfoCallback(),this.channelzEnabled),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Channel created");if(this.options["grpc.default_authority"])this.defaultAuthority=this.options["grpc.default_authority"];else this.defaultAuthority=(0,DE.getDefaultAuthority)(A);let W=(0,Ew.mapProxyName)(A,T);this.target=W.target,this.options=Object.assign({},this.options,W.extraOptions),this.subchannelPool=(0,Kw.getSubchannelPool)(((q=this.options["grpc.use_local_subchannel_pool"])!==null&&q!==void 0?q:0)===0),this.retryBufferTracker=new p5.MessageBufferTracker((X=this.options["grpc.retry_buffer_size"])!==null&&X!==void 0?X:Bw,(J=this.options["grpc.per_rpc_retry_buffer_size"])!==null&&J!==void 0?J:Rw),this.keepaliveTime=(Q=this.options["grpc.keepalive_time_ms"])!==null&&Q!==void 0?Q:-1,this.idleTimeoutMs=Math.max((U=this.options["grpc.client_idle_timeout_ms"])!==null&&U!==void 0?U:Mw,Iw);let E={createSubchannel:(F,H)=>{let D={};for(let[v,z]of Object.entries(H))if(!v.startsWith(IE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX))D[v]=z;let I=this.subchannelPool.getOrCreateSubchannel(this.target,F,D,this.credentials);if(I.throttleKeepalive(this.keepaliveTime),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Created subchannel or used existing subchannel",I.getChannelzRef());return new FE(I,this)},updateState:(F,H)=>{this.currentPicker=H;let D=this.pickQueue.slice();if(this.pickQueue=[],D.length>0)this.callRefTimerUnref();for(let I of D)I.doPick();this.updateState(F)},requestReresolution:()=>{throw Error("Resolving load balancer should never call requestReresolution")},addChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.refChild(F)},removeChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.unrefChild(F)}};this.resolvingLoadBalancer=new Zw.ResolvingLoadBalancer(this.target,E,this.options,(F,H)=>{var D;if(F.retryThrottling)lq.set(this.getTarget(),new p5.RetryThrottler(F.retryThrottling.maxTokens,F.retryThrottling.tokenRatio,lq.get(this.getTarget())));else lq.delete(this.getTarget());if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Address resolution succeeded");(D=this.configSelector)===null||D===void 0||D.unref(),this.configSelector=H,this.currentResolutionError=null,process.nextTick(()=>{let I=this.configSelectionQueue;if(this.configSelectionQueue=[],I.length>0)this.callRefTimerUnref();for(let S of I)S.getConfig()})},(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_WARNING","Address resolution failed with code "+F.code+' and details "'+F.details+'"');if(this.configSelectionQueue.length>0)this.trace("Name resolution failed with calls queued for config selection");if(this.configSelector===null)this.currentResolutionError=Object.assign(Object.assign({},(0,Nw.restrictControlPlaneStatusCode)(F.code,F.details)),{metadata:F.metadata});let H=this.configSelectionQueue;if(this.configSelectionQueue=[],H.length>0)this.callRefTimerUnref();for(let D of H)D.reportResolverError(F)}),this.filterStackFactory=new Ww.FilterStackFactory([new Gw.CompressionFilterFactory(this,this.options)]),this.trace("Channel constructed with options "+JSON.stringify(T,void 0,2));let V=Error();if((0,cq.isTracerEnabled)("channel_stacktrace"))(0,cq.trace)(v$.LogVerbosity.DEBUG,"channel_stacktrace","("+this.channelzRef.id+`) Channel constructed
|
|
20
|
+
`+((Z=V.stack)===null||Z===void 0?void 0:Z.substring(V.stack.indexOf(`
|
|
21
|
+
`)+1)));this.lastActivityTimestamp=new Date}trace($,Y){(0,cq.trace)(Y!==null&&Y!==void 0?Y:v$.LogVerbosity.DEBUG,"channel","("+this.channelzRef.id+") "+(0,pq.uriToString)(this.target)+" "+$)}callRefTimerRef(){var $,Y,T,q;if(!this.callRefTimer)this.callRefTimer=setInterval(()=>{},zw);if(!((Y=($=this.callRefTimer).hasRef)===null||Y===void 0?void 0:Y.call($)))this.trace("callRefTimer.ref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(q=(T=this.callRefTimer).ref)===null||q===void 0||q.call(T)}callRefTimerUnref(){var $,Y,T;if(!(($=this.callRefTimer)===null||$===void 0?void 0:$.hasRef)||this.callRefTimer.hasRef())this.trace("callRefTimer.unref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(T=(Y=this.callRefTimer)===null||Y===void 0?void 0:Y.unref)===null||T===void 0||T.call(Y)}removeConnectivityStateWatcher($){let Y=this.connectivityStateWatchers.findIndex((T)=>T===$);if(Y>=0)this.connectivityStateWatchers.splice(Y,1)}updateState($){if((0,cq.trace)(v$.LogVerbosity.DEBUG,"connectivity_state","("+this.channelzRef.id+") "+(0,pq.uriToString)(this.target)+" "+N1.ConnectivityState[this.connectivityState]+" -> "+N1.ConnectivityState[$]),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Connectivity state change to "+N1.ConnectivityState[$]);this.connectivityState=$,this.channelzInfoTracker.state=$;let Y=this.connectivityStateWatchers.slice();for(let T of Y)if($!==T.currentState){if(T.timer)clearTimeout(T.timer);this.removeConnectivityStateWatcher(T),T.callback()}if($!==N1.ConnectivityState.TRANSIENT_FAILURE)this.currentResolutionError=null}throttleKeepalive($){if($>this.keepaliveTime){this.keepaliveTime=$;for(let Y of this.wrappedSubchannels)Y.throttleKeepalive($)}}addWrappedSubchannel($){this.wrappedSubchannels.add($)}removeWrappedSubchannel($){this.wrappedSubchannels.delete($)}doPick($,Y){return this.currentPicker.pick({metadata:$,extraPickInfo:Y})}queueCallForPick($){this.pickQueue.push($),this.callRefTimerRef()}getConfig($,Y){if(this.connectivityState!==N1.ConnectivityState.SHUTDOWN)this.resolvingLoadBalancer.exitIdle();if(this.configSelector)return{type:"SUCCESS",config:this.configSelector.invoke($,Y,this.randomChannelId)};else if(this.currentResolutionError)return{type:"ERROR",error:this.currentResolutionError};else return{type:"NONE"}}queueCallForConfig($){this.configSelectionQueue.push($),this.callRefTimerRef()}enterIdle(){if(this.resolvingLoadBalancer.destroy(),this.updateState(N1.ConnectivityState.IDLE),this.currentPicker=new l5.QueuePicker(this.resolvingLoadBalancer),this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;if(this.callRefTimer)clearInterval(this.callRefTimer),this.callRefTimer=null}startIdleTimeout($){var Y,T;this.idleTimer=setTimeout(()=>{if(this.callCount>0){this.startIdleTimeout(this.idleTimeoutMs);return}let X=new Date().valueOf()-this.lastActivityTimestamp.valueOf();if(X>=this.idleTimeoutMs)this.trace("Idle timer triggered after "+this.idleTimeoutMs+"ms of inactivity"),this.enterIdle();else this.startIdleTimeout(this.idleTimeoutMs-X)},$),(T=(Y=this.idleTimer).unref)===null||T===void 0||T.call(Y)}maybeStartIdleTimer(){if(this.connectivityState!==N1.ConnectivityState.SHUTDOWN&&!this.idleTimer)this.startIdleTimeout(this.idleTimeoutMs)}onCallStart(){if(this.channelzEnabled)this.channelzInfoTracker.callTracker.addCallStarted();this.callCount+=1}onCallEnd($){if(this.channelzEnabled)if($.code===v$.Status.OK)this.channelzInfoTracker.callTracker.addCallSucceeded();else this.channelzInfoTracker.callTracker.addCallFailed();this.callCount-=1,this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer()}createLoadBalancingCall($,Y,T,q,X){let J=(0,c5.getNextCallNumber)();return this.trace("createLoadBalancingCall ["+J+'] method="'+Y+'"'),new Vw.LoadBalancingCall(this,$,Y,T,q,X,J)}createRetryingCall($,Y,T,q,X){let J=(0,c5.getNextCallNumber)();return this.trace("createRetryingCall ["+J+'] method="'+Y+'"'),new p5.RetryingCall(this,$,Y,T,q,X,J,this.retryBufferTracker,lq.get(this.getTarget()))}createResolvingCall($,Y,T,q,X){let J=(0,c5.getNextCallNumber)();this.trace("createResolvingCall ["+J+'] method="'+$+'", deadline='+(0,Dw.deadlineToString)(Y));let Q={deadline:Y,flags:X!==null&&X!==void 0?X:v$.Propagate.DEFAULTS,host:T!==null&&T!==void 0?T:this.defaultAuthority,parentCall:q},U=new Fw.ResolvingCall(this,$,Q,this.filterStackFactory.clone(),J);return this.onCallStart(),U.addStatusWatcher((Z)=>{this.onCallEnd(Z)}),U}close(){var $;this.resolvingLoadBalancer.destroy(),this.updateState(N1.ConnectivityState.SHUTDOWN),this.currentPicker=new NE;for(let Y of this.configSelectionQueue)Y.cancelWithStatus(v$.Status.UNAVAILABLE,"Channel closed before call started");this.configSelectionQueue=[];for(let Y of this.pickQueue)Y.cancelWithStatus(v$.Status.UNAVAILABLE,"Channel closed before call started");if(this.pickQueue=[],this.callRefTimer)clearInterval(this.callRefTimer);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.channelzEnabled)(0,AT.unregisterChannelzRef)(this.channelzRef);this.subchannelPool.unrefUnusedSubchannels(),($=this.configSelector)===null||$===void 0||$.unref(),this.configSelector=null}getTarget(){return(0,pq.uriToString)(this.target)}getConnectivityState($){let Y=this.connectivityState;if($)this.resolvingLoadBalancer.exitIdle(),this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer();return Y}watchConnectivityState($,Y,T){if(this.connectivityState===N1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");let q=null;if(Y!==1/0){let J=Y instanceof Date?Y:new Date(Y),Q=new Date;if(Y===-1/0||J<=Q){process.nextTick(T,Error("Deadline passed without connectivity state change"));return}q=setTimeout(()=>{this.removeConnectivityStateWatcher(X),T(Error("Deadline passed without connectivity state change"))},J.getTime()-Q.getTime())}let X={currentState:$,callback:T,timer:q};this.connectivityStateWatchers.push(X)}getChannelzRef(){return this.channelzRef}createCall($,Y,T,q,X){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof Y==="number"||Y instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");if(this.connectivityState===N1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");return this.createResolvingCall($,Y,T,q,X)}getOptions(){return this.options}}IE.InternalChannel=zE});var WX=B((OE)=>{Object.defineProperty(OE,"__esModule",{value:!0});OE.ChannelImplementation=void 0;var Ow=PY(),Pw=n5();class RE{constructor($,Y,T){if(typeof $!=="string")throw TypeError("Channel target must be a string");if(!(Y instanceof Ow.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(T){if(typeof T!=="object")throw TypeError("Channel options must be an object")}this.internalChannel=new Pw.InternalChannel($,Y,T)}close(){this.internalChannel.close()}getTarget(){return this.internalChannel.getTarget()}getConnectivityState($){return this.internalChannel.getConnectivityState($)}watchConnectivityState($,Y,T){this.internalChannel.watchConnectivityState($,Y,T)}getChannelzRef(){return this.internalChannel.getChannelzRef()}createCall($,Y,T,q,X){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof Y==="number"||Y instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");return this.internalChannel.createCall($,Y,T,q,X)}}OE.ChannelImplementation=RE});var xE=B((jE)=>{Object.defineProperty(jE,"__esModule",{value:!0});jE.ServerDuplexStreamImpl=jE.ServerWritableStreamImpl=jE.ServerReadableStreamImpl=jE.ServerUnaryCallImpl=void 0;jE.serverErrorToStatus=a5;var Lw=s("events"),i5=s("stream"),r5=i(),LE=P0();function a5($,Y){var T;let q={code:r5.Status.UNKNOWN,details:"message"in $?$.message:"Unknown Error",metadata:(T=Y!==null&&Y!==void 0?Y:$.metadata)!==null&&T!==void 0?T:null};if("code"in $&&typeof $.code==="number"&&Number.isInteger($.code)){if(q.code=$.code,"details"in $&&typeof $.details==="string")q.details=$.details}return q}class wE extends Lw.EventEmitter{constructor($,Y,T,q){super();this.path=$,this.call=Y,this.metadata=T,this.request=q,this.cancelled=!1}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}jE.ServerUnaryCallImpl=wE;class SE extends i5.Readable{constructor($,Y,T){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.cancelled=!1}_read($){this.call.startRead()}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}jE.ServerReadableStreamImpl=SE;class CE extends i5.Writable{constructor($,Y,T,q){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.request=q,this.pendingStatus={code:r5.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new LE.Metadata,this.on("error",(X)=>{this.pendingStatus=a5(X),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_write($,Y,T){this.call.sendMessage($,T)}_final($){var Y;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(Y=this.pendingStatus.metadata)!==null&&Y!==void 0?Y:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}jE.ServerWritableStreamImpl=CE;class yE extends i5.Duplex{constructor($,Y,T){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.pendingStatus={code:r5.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new LE.Metadata,this.on("error",(q)=>{this.pendingStatus=a5(q),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_read($){this.call.startRead()}_write($,Y,T){this.call.sendMessage($,T)}_final($){var Y;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(Y=this.pendingStatus.metadata)!==null&&Y!==void 0?Y:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}jE.ServerDuplexStreamImpl=yE});var nq=B((kE)=>{Object.defineProperty(kE,"__esModule",{value:!0});kE.ServerCredentials=void 0;kE.createCertificateProviderServerCredentials=jw;kE.createServerCredentialsWithInterceptors=vw;var o5=o4();class nY{constructor($,Y){this.serverConstructorOptions=$,this.watchers=new Set,this.latestContextOptions=null,this.latestContextOptions=Y!==null&&Y!==void 0?Y:null}_addWatcher($){this.watchers.add($)}_removeWatcher($){this.watchers.delete($)}getWatcherCount(){return this.watchers.size}updateSecureContextOptions($){this.latestContextOptions=$;for(let Y of this.watchers)Y(this.latestContextOptions)}_isSecure(){return this.serverConstructorOptions!==null}_getSecureContextOptions(){return this.latestContextOptions}_getConstructorOptions(){return this.serverConstructorOptions}_getInterceptors(){return[]}static createInsecure(){return new s5}static createSsl($,Y,T=!1){var q;if($!==null&&!Buffer.isBuffer($))throw TypeError("rootCerts must be null or a Buffer");if(!Array.isArray(Y))throw TypeError("keyCertPairs must be an array");if(typeof T!=="boolean")throw TypeError("checkClientCertificate must be a boolean");let X=[],J=[];for(let Q=0;Q<Y.length;Q++){let U=Y[Q];if(U===null||typeof U!=="object")throw TypeError(`keyCertPair[${Q}] must be an object`);if(!Buffer.isBuffer(U.private_key))throw TypeError(`keyCertPair[${Q}].private_key must be a Buffer`);if(!Buffer.isBuffer(U.cert_chain))throw TypeError(`keyCertPair[${Q}].cert_chain must be a Buffer`);X.push(U.cert_chain),J.push(U.private_key)}return new t5({requestCert:T,ciphers:o5.CIPHER_SUITES},{ca:(q=$!==null&&$!==void 0?$:(0,o5.getDefaultRootsData)())!==null&&q!==void 0?q:void 0,cert:X,key:J})}}kE.ServerCredentials=nY;class s5 extends nY{constructor(){super(null)}_getSettings(){return null}_equals($){return $ instanceof s5}}class t5 extends nY{constructor($,Y){super($,Y);this.options=Object.assign(Object.assign({},$),Y)}_equals($){if(this===$)return!0;if(!($ instanceof t5))return!1;if(Buffer.isBuffer(this.options.ca)&&Buffer.isBuffer($.options.ca)){if(!this.options.ca.equals($.options.ca))return!1}else if(this.options.ca!==$.options.ca)return!1;if(Array.isArray(this.options.cert)&&Array.isArray($.options.cert)){if(this.options.cert.length!==$.options.cert.length)return!1;for(let Y=0;Y<this.options.cert.length;Y++){let T=this.options.cert[Y],q=$.options.cert[Y];if(Buffer.isBuffer(T)&&Buffer.isBuffer(q)){if(!T.equals(q))return!1}else if(T!==q)return!1}}else if(this.options.cert!==$.options.cert)return!1;if(Array.isArray(this.options.key)&&Array.isArray($.options.key)){if(this.options.key.length!==$.options.key.length)return!1;for(let Y=0;Y<this.options.key.length;Y++){let T=this.options.key[Y],q=$.options.key[Y];if(Buffer.isBuffer(T)&&Buffer.isBuffer(q)){if(!T.equals(q))return!1}else if(T!==q)return!1}}else if(this.options.key!==$.options.key)return!1;if(this.options.requestCert!==$.options.requestCert)return!1;return!0}}class e5 extends nY{constructor($,Y,T){super({requestCert:Y!==null,rejectUnauthorized:T,ciphers:o5.CIPHER_SUITES});this.identityCertificateProvider=$,this.caCertificateProvider=Y,this.requireClientCertificate=T,this.latestCaUpdate=null,this.latestIdentityUpdate=null,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this)}_addWatcher($){var Y;if(this.getWatcherCount()===0)(Y=this.caCertificateProvider)===null||Y===void 0||Y.addCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);super._addWatcher($)}_removeWatcher($){var Y;if(super._removeWatcher($),this.getWatcherCount()===0)(Y=this.caCertificateProvider)===null||Y===void 0||Y.removeCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_equals($){if(this===$)return!0;if(!($ instanceof e5))return!1;return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&this.requireClientCertificate===$.requireClientCertificate}calculateSecureContextOptions(){var $;if(this.latestIdentityUpdate===null)return null;if(this.caCertificateProvider!==null&&this.latestCaUpdate===null)return null;return{ca:($=this.latestCaUpdate)===null||$===void 0?void 0:$.caCertificate,cert:[this.latestIdentityUpdate.certificate],key:[this.latestIdentityUpdate.privateKey]}}finalizeUpdate(){let $=this.calculateSecureContextOptions();this.updateSecureContextOptions($)}handleCaCertificateUpdate($){this.latestCaUpdate=$,this.finalizeUpdate()}handleIdentityCertitificateUpdate($){this.latestIdentityUpdate=$,this.finalizeUpdate()}}function jw($,Y,T){return new e5($,Y,T)}class $J extends nY{constructor($,Y){super({});this.childCredentials=$,this.interceptors=Y}_isSecure(){return this.childCredentials._isSecure()}_equals($){if(!($ instanceof $J))return!1;if(!this.childCredentials._equals($.childCredentials))return!1;if(this.interceptors.length!==$.interceptors.length)return!1;for(let Y=0;Y<this.interceptors.length;Y++)if(this.interceptors[Y]!==$.interceptors[Y])return!1;return!0}_getInterceptors(){return this.interceptors}_addWatcher($){this.childCredentials._addWatcher($)}_removeWatcher($){this.childCredentials._removeWatcher($)}_getConstructorOptions(){return this.childCredentials._getConstructorOptions()}_getSecureContextOptions(){return this.childCredentials._getSecureContextOptions()}}function vw($,Y){return new $J($,Y)}});var WT=B((_E)=>{Object.defineProperty(_E,"__esModule",{value:!0});_E.durationMessageToDuration=hw;_E.msToDuration=_w;_E.durationToMs=gw;_E.isDuration=mw;_E.isDurationMessage=fw;_E.parseDuration=uw;_E.durationToString=dw;function hw($){return{seconds:Number.parseInt($.seconds),nanos:$.nanos}}function _w($){return{seconds:$/1000|0,nanos:$%1000*1e6|0}}function gw($){return $.seconds*1000+$.nanos/1e6|0}function mw($){return typeof $.seconds==="number"&&typeof $.nanos==="number"}function fw($){return typeof $.seconds==="string"&&typeof $.nanos==="number"}var bw=/^(\d+)(?:\.(\d+))?s$/;function uw($){let Y=$.match(bw);if(!Y)return null;return{seconds:Number.parseInt(Y[1],10),nanos:Y[2]?Number.parseInt(Y[2].padEnd(9,"0"),10):0}}function dw($){if($.nanos===0)return`${$.seconds}s`;let Y;if($.nanos%1e6===0)Y=1e6;else if($.nanos%1000===0)Y=1000;else Y=1;return`${$.seconds}.${$.nanos/Y}s`}});var rq=B((iE)=>{var __dirname="/Users/beatrix/dev/clinee/sdk-wip/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(iE,"__esModule",{value:!0});iE.OrcaOobMetricsSubchannelWrapper=iE.GRPC_METRICS_HEADER=iE.ServerMetricRecorder=iE.PerRequestMetricRecorder=void 0;iE.createOrcaClient=dE;iE.createMetricsReader=TS;var ow=o8(),YJ=WT(),sw=PY(),tw=KT(),gE=i(),ew=LY(),$S=l0(),mE=null;function iq(){if(mE)return mE;let $=t6().loadSync,Y=$("xds/service/orca/v3/orca.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto/xds`,`${__dirname}/../../proto/protoc-gen-validate`]});return(0,ow.loadPackageDefinition)(Y)}class bE{constructor(){this.message={}}recordRequestCostMetric($,Y){if(!this.message.request_cost)this.message.request_cost={};this.message.request_cost[$]=Y}recordUtilizationMetric($,Y){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=Y}recordNamedMetric($,Y){if(!this.message.named_metrics)this.message.named_metrics={};this.message.named_metrics[$]=Y}recordCPUUtilizationMetric($){this.message.cpu_utilization=$}recordMemoryUtilizationMetric($){this.message.mem_utilization=$}recordApplicationUtilizationMetric($){this.message.application_utilization=$}recordQpsMetric($){this.message.rps_fractional=$}recordEpsMetric($){this.message.eps=$}serialize(){return iq().xds.data.orca.v3.OrcaLoadReport.serialize(this.message)}}iE.PerRequestMetricRecorder=bE;var YS=30000;class uE{constructor(){this.message={},this.serviceImplementation={StreamCoreMetrics:($)=>{let Y=$.request.report_interval?(0,YJ.durationToMs)((0,YJ.durationMessageToDuration)($.request.report_interval)):YS,T=setInterval(()=>{$.write(this.message)},Y);$.on("cancelled",()=>{clearInterval(T)})}}}putUtilizationMetric($,Y){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=Y}setAllUtilizationMetrics($){this.message.utilization=Object.assign({},$)}deleteUtilizationMetric($){var Y;(Y=this.message.utilization)===null||Y===void 0||delete Y[$]}setCpuUtilizationMetric($){this.message.cpu_utilization=$}deleteCpuUtilizationMetric(){delete this.message.cpu_utilization}setApplicationUtilizationMetric($){this.message.application_utilization=$}deleteApplicationUtilizationMetric(){delete this.message.application_utilization}setQpsMetric($){this.message.rps_fractional=$}deleteQpsMetric(){delete this.message.rps_fractional}setEpsMetric($){this.message.eps=$}deleteEpsMetric(){delete this.message.eps}addToServer($){let Y=iq().xds.service.orca.v3.OpenRcaService.service;$.addService(Y,this.serviceImplementation)}}iE.ServerMetricRecorder=uE;function dE($){return new(iq()).xds.service.orca.v3.OpenRcaService("unused",sw.ChannelCredentials.createInsecure(),{channelOverride:$})}iE.GRPC_METRICS_HEADER="endpoint-load-metrics-bin";var fE="grpc_orca_load_report";function TS($,Y){return(T,q,X)=>{let J=X.getOpaque(fE);if(J)$(J);else{let Q=X.get(iE.GRPC_METRICS_HEADER);if(Q.length>0)J=iq().xds.data.orca.v3.OrcaLoadReport.deserialize(Q[0]),$(J),X.setOpaque(fE,J)}if(Y)Y(T,q,X)}}var cE="orca_oob_metrics";class pE{constructor($,Y){this.metricsListener=$,this.intervalMs=Y,this.dataProducer=null}setSubchannel($){let Y=$.getOrCreateDataProducer(cE,qS);this.dataProducer=Y,Y.addDataWatcher(this)}destroy(){var $;($=this.dataProducer)===null||$===void 0||$.removeDataWatcher(this)}getInterval(){return this.intervalMs}onMetricsUpdate($){this.metricsListener($)}}class lE{constructor($){this.subchannel=$,this.dataWatchers=new Set,this.orcaSupported=!0,this.metricsCall=null,this.currentInterval=1/0,this.backoffTimer=new ew.BackoffTimeout(()=>this.updateMetricsSubscription()),this.subchannelStateListener=()=>this.updateMetricsSubscription();let Y=$.getChannel();this.client=dE(Y),$.addConnectivityStateListener(this.subchannelStateListener)}addDataWatcher($){this.dataWatchers.add($),this.updateMetricsSubscription()}removeDataWatcher($){var Y;if(this.dataWatchers.delete($),this.dataWatchers.size===0)this.subchannel.removeDataProducer(cE),(Y=this.metricsCall)===null||Y===void 0||Y.cancel(),this.metricsCall=null,this.client.close(),this.subchannel.removeConnectivityStateListener(this.subchannelStateListener);else this.updateMetricsSubscription()}updateMetricsSubscription(){var $;if(this.dataWatchers.size===0||!this.orcaSupported||this.subchannel.getConnectivityState()!==$S.ConnectivityState.READY)return;let Y=Math.min(...Array.from(this.dataWatchers).map((T)=>T.getInterval()));if(!this.metricsCall||Y!==this.currentInterval){($=this.metricsCall)===null||$===void 0||$.cancel(),this.currentInterval=Y;let T=this.client.streamCoreMetrics({report_interval:(0,YJ.msToDuration)(Y)});this.metricsCall=T,T.on("data",(q)=>{this.dataWatchers.forEach((X)=>{X.onMetricsUpdate(q)})}),T.on("error",(q)=>{if(this.metricsCall=null,q.code===gE.Status.UNIMPLEMENTED){this.orcaSupported=!1;return}if(q.code===gE.Status.CANCELLED)return;this.backoffTimer.runOnce()})}}}class nE extends tw.BaseSubchannelWrapper{constructor($,Y,T){super($);this.addDataWatcher(new pE(Y,T))}getWrappedSubchannel(){return this.child}}iE.OrcaOobMetricsSubchannelWrapper=nE;function qS($){return new lE($)}});var JJ=B((KV)=>{Object.defineProperty(KV,"__esModule",{value:!0});KV.BaseServerInterceptingCall=KV.ServerInterceptingCall=KV.ResponderBuilder=KV.ServerListenerBuilder=void 0;KV.isInterceptingServerListener=AS;KV.getServerInterceptingCall=DS;var sq=P0(),o0=i(),iY=s("http2"),oE=k8(),sE=s("zlib"),ZS=g5(),TV=U0(),KS=s("tls"),tE=rq(),qV="server_call";function qY($){TV.trace(o0.LogVerbosity.DEBUG,qV,$)}class XV{constructor(){this.metadata=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withOnReceiveMetadata($){return this.metadata=$,this}withOnReceiveMessage($){return this.message=$,this}withOnReceiveHalfClose($){return this.halfClose=$,this}withOnCancel($){return this.cancel=$,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveHalfClose:this.halfClose,onCancel:this.cancel}}}KV.ServerListenerBuilder=XV;function AS($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class JV{constructor($,Y){this.listener=$,this.nextListener=Y,this.cancelled=!1,this.processingMetadata=!1,this.hasPendingMessage=!1,this.pendingMessage=null,this.processingMessage=!1,this.hasPendingHalfClose=!1}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingHalfClose(){if(this.hasPendingHalfClose)this.nextListener.onReceiveHalfClose(),this.hasPendingHalfClose=!1}onReceiveMetadata($){if(this.cancelled)return;this.processingMetadata=!0,this.listener.onReceiveMetadata($,(Y)=>{if(this.processingMetadata=!1,this.cancelled)return;this.nextListener.onReceiveMetadata(Y),this.processPendingMessage(),this.processPendingHalfClose()})}onReceiveMessage($){if(this.cancelled)return;this.processingMessage=!0,this.listener.onReceiveMessage($,(Y)=>{if(this.processingMessage=!1,this.cancelled)return;if(this.processingMetadata)this.pendingMessage=Y,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(Y),this.processPendingHalfClose()})}onReceiveHalfClose(){if(this.cancelled)return;this.listener.onReceiveHalfClose(()=>{if(this.cancelled)return;if(this.processingMetadata||this.processingMessage)this.hasPendingHalfClose=!0;else this.nextListener.onReceiveHalfClose()})}onCancel(){this.cancelled=!0,this.listener.onCancel(),this.nextListener.onCancel()}}class QV{constructor(){this.start=void 0,this.metadata=void 0,this.message=void 0,this.status=void 0}withStart($){return this.start=$,this}withSendMetadata($){return this.metadata=$,this}withSendMessage($){return this.message=$,this}withSendStatus($){return this.status=$,this}build(){return{start:this.start,sendMetadata:this.metadata,sendMessage:this.message,sendStatus:this.status}}}KV.ResponderBuilder=QV;var aq={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveHalfClose:($)=>{$()},onCancel:()=>{}},oq={start:($)=>{$()},sendMetadata:($,Y)=>{Y($)},sendMessage:($,Y)=>{Y($)},sendStatus:($,Y)=>{Y($)}};class UV{constructor($,Y){var T,q,X,J;this.nextCall=$,this.processingMetadata=!1,this.sentMetadata=!1,this.processingMessage=!1,this.pendingMessage=null,this.pendingMessageCallback=null,this.pendingStatus=null,this.responder={start:(T=Y===null||Y===void 0?void 0:Y.start)!==null&&T!==void 0?T:oq.start,sendMetadata:(q=Y===null||Y===void 0?void 0:Y.sendMetadata)!==null&&q!==void 0?q:oq.sendMetadata,sendMessage:(X=Y===null||Y===void 0?void 0:Y.sendMessage)!==null&&X!==void 0?X:oq.sendMessage,sendStatus:(J=Y===null||Y===void 0?void 0:Y.sendStatus)!==null&&J!==void 0?J:oq.sendStatus}}processPendingMessage(){if(this.pendingMessageCallback)this.nextCall.sendMessage(this.pendingMessage,this.pendingMessageCallback),this.pendingMessage=null,this.pendingMessageCallback=null}processPendingStatus(){if(this.pendingStatus)this.nextCall.sendStatus(this.pendingStatus),this.pendingStatus=null}start($){this.responder.start((Y)=>{var T,q,X,J;let Q={onReceiveMetadata:(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)!==null&&T!==void 0?T:aq.onReceiveMetadata,onReceiveMessage:(q=Y===null||Y===void 0?void 0:Y.onReceiveMessage)!==null&&q!==void 0?q:aq.onReceiveMessage,onReceiveHalfClose:(X=Y===null||Y===void 0?void 0:Y.onReceiveHalfClose)!==null&&X!==void 0?X:aq.onReceiveHalfClose,onCancel:(J=Y===null||Y===void 0?void 0:Y.onCancel)!==null&&J!==void 0?J:aq.onCancel},U=new JV(Q,$);this.nextCall.start(U)})}sendMetadata($){this.processingMetadata=!0,this.sentMetadata=!0,this.responder.sendMetadata($,(Y)=>{this.processingMetadata=!1,this.nextCall.sendMetadata(Y),this.processPendingMessage(),this.processPendingStatus()})}sendMessage($,Y){if(this.processingMessage=!0,!this.sentMetadata)this.sendMetadata(new sq.Metadata);this.responder.sendMessage($,(T)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=T,this.pendingMessageCallback=Y;else this.nextCall.sendMessage(T,Y)})}sendStatus($){this.responder.sendStatus($,(Y)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=Y;else this.nextCall.sendStatus(Y)})}startRead(){this.nextCall.startRead()}getPeer(){return this.nextCall.getPeer()}getDeadline(){return this.nextCall.getDeadline()}getHost(){return this.nextCall.getHost()}getAuthContext(){return this.nextCall.getAuthContext()}getConnectionInfo(){return this.nextCall.getConnectionInfo()}getMetricsRecorder(){return this.nextCall.getMetricsRecorder()}}KV.ServerInterceptingCall=UV;var ZV="grpc-accept-encoding",qJ="grpc-encoding",eE="grpc-message",$V="grpc-status",TJ="grpc-timeout",WS=/(\d{1,8})\s*([HMSmun])/,GS={H:3600000,M:60000,S:1000,m:1,u:0.001,n:0.000001},ES={[ZV]:"identity,deflate,gzip",[qJ]:"identity"},YV={[iY.constants.HTTP2_HEADER_STATUS]:iY.constants.HTTP_STATUS_OK,[iY.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},VS={waitForTrailers:!0};class XJ{constructor($,Y,T,q,X){var J,Q;if(this.stream=$,this.callEventTracker=T,this.handler=q,this.listener=null,this.deadlineTimer=null,this.deadline=1/0,this.maxSendMessageSize=o0.DEFAULT_MAX_SEND_MESSAGE_LENGTH,this.maxReceiveMessageSize=o0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.cancelled=!1,this.metadataSent=!1,this.wantTrailers=!1,this.cancelNotified=!1,this.incomingEncoding="identity",this.readQueue=[],this.isReadPending=!1,this.receivedHalfClose=!1,this.streamEnded=!1,this.metricsRecorder=new tE.PerRequestMetricRecorder,this.stream.once("error",(W)=>{}),this.stream.once("close",()=>{var W;if(qY("Request to method "+((W=this.handler)===null||W===void 0?void 0:W.path)+" stream closed with rstCode "+this.stream.rstCode),this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!1),this.callEventTracker.onCallEnd({code:o0.Status.CANCELLED,details:"Stream closed before sending status",metadata:null});this.notifyOnCancel()}),this.stream.on("data",(W)=>{this.handleDataFrame(W)}),this.stream.pause(),this.stream.on("end",()=>{this.handleEndEvent()}),"grpc.max_send_message_length"in X)this.maxSendMessageSize=X["grpc.max_send_message_length"];if("grpc.max_receive_message_length"in X)this.maxReceiveMessageSize=X["grpc.max_receive_message_length"];this.host=(J=Y[":authority"])!==null&&J!==void 0?J:Y.host,this.decoder=new ZS.StreamDecoder(this.maxReceiveMessageSize);let U=sq.Metadata.fromHttp2Headers(Y);if(TV.isTracerEnabled(qV))qY("Request to "+this.handler.path+" received headers "+JSON.stringify(U.toJSON()));let Z=U.get(TJ);if(Z.length>0)this.handleTimeoutHeader(Z[0]);let K=U.get(qJ);if(K.length>0)this.incomingEncoding=K[0];U.remove(TJ),U.remove(qJ),U.remove(ZV),U.remove(iY.constants.HTTP2_HEADER_ACCEPT_ENCODING),U.remove(iY.constants.HTTP2_HEADER_TE),U.remove(iY.constants.HTTP2_HEADER_CONTENT_TYPE),this.metadata=U;let A=(Q=$.session)===null||Q===void 0?void 0:Q.socket;this.connectionInfo={localAddress:A===null||A===void 0?void 0:A.localAddress,localPort:A===null||A===void 0?void 0:A.localPort,remoteAddress:A===null||A===void 0?void 0:A.remoteAddress,remotePort:A===null||A===void 0?void 0:A.remotePort},this.shouldSendMetrics=!!X["grpc.server_call_metric_recording"]}handleTimeoutHeader($){let Y=$.toString().match(WS);if(Y===null){let X={code:o0.Status.INTERNAL,details:`Invalid ${TJ} value "${$}"`,metadata:null};process.nextTick(()=>{this.sendStatus(X)});return}let T=+Y[1]*GS[Y[2]]|0,q=new Date;this.deadline=q.setMilliseconds(q.getMilliseconds()+T),this.deadlineTimer=setTimeout(()=>{let X={code:o0.Status.DEADLINE_EXCEEDED,details:"Deadline exceeded",metadata:null};this.sendStatus(X)},T)}checkCancelled(){if(!this.cancelled&&(this.stream.destroyed||this.stream.closed))this.notifyOnCancel(),this.cancelled=!0;return this.cancelled}notifyOnCancel(){if(this.cancelNotified)return;if(this.cancelNotified=!0,this.cancelled=!0,process.nextTick(()=>{var $;($=this.listener)===null||$===void 0||$.onCancel()}),this.deadlineTimer)clearTimeout(this.deadlineTimer);this.stream.resume()}maybeSendMetadata(){if(!this.metadataSent)this.sendMetadata(new sq.Metadata)}serializeMessage($){let Y=this.handler.serialize($),T=Y.byteLength,q=Buffer.allocUnsafe(T+5);return q.writeUInt8(0,0),q.writeUInt32BE(T,1),Y.copy(q,5),q}decompressMessage($,Y){let T=$.subarray(5);if(Y==="identity")return T;else if(Y==="deflate"||Y==="gzip"){let q;if(Y==="deflate")q=sE.createInflate();else q=sE.createGunzip();return new Promise((X,J)=>{let Q=0,U=[];q.on("data",(Z)=>{if(U.push(Z),Q+=Z.byteLength,this.maxReceiveMessageSize!==-1&&Q>this.maxReceiveMessageSize)q.destroy(),J({code:o0.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`})}),q.on("end",()=>{X(Buffer.concat(U))}),q.write(T),q.end()})}else return Promise.reject({code:o0.Status.UNIMPLEMENTED,details:`Received message compressed with unsupported encoding "${Y}"`})}async decompressAndMaybePush($){if($.type!=="COMPRESSED")throw Error(`Invalid queue entry type: ${$.type}`);let T=$.compressedMessage.readUInt8(0)===1?this.incomingEncoding:"identity",q;try{q=await this.decompressMessage($.compressedMessage,T)}catch(X){this.sendStatus(X);return}try{$.parsedMessage=this.handler.deserialize(q)}catch(X){this.sendStatus({code:o0.Status.INTERNAL,details:`Error deserializing request: ${X.message}`});return}$.type="READABLE",this.maybePushNextMessage()}maybePushNextMessage(){if(this.listener&&this.isReadPending&&this.readQueue.length>0&&this.readQueue[0].type!=="COMPRESSED"){this.isReadPending=!1;let $=this.readQueue.shift();if($.type==="READABLE")this.listener.onReceiveMessage($.parsedMessage);else this.listener.onReceiveHalfClose()}}handleDataFrame($){var Y;if(this.checkCancelled())return;qY("Request to "+this.handler.path+" received data frame of size "+$.length);let T;try{T=this.decoder.write($)}catch(q){this.sendStatus({code:o0.Status.RESOURCE_EXHAUSTED,details:q.message});return}for(let q of T){this.stream.pause();let X={type:"COMPRESSED",compressedMessage:q,parsedMessage:null};this.readQueue.push(X),this.decompressAndMaybePush(X),(Y=this.callEventTracker)===null||Y===void 0||Y.addMessageReceived()}}handleEndEvent(){this.readQueue.push({type:"HALF_CLOSE",compressedMessage:null,parsedMessage:null}),this.receivedHalfClose=!0,this.maybePushNextMessage()}start($){if(qY("Request to "+this.handler.path+" start called"),this.checkCancelled())return;this.listener=$,$.onReceiveMetadata(this.metadata)}sendMetadata($){if(this.checkCancelled())return;if(this.metadataSent)return;this.metadataSent=!0;let Y=$?$.toHttp2Headers():null,T=Object.assign(Object.assign(Object.assign({},YV),ES),Y);this.stream.respond(T,VS)}sendMessage($,Y){if(this.checkCancelled())return;let T;try{T=this.serializeMessage($)}catch(q){this.sendStatus({code:o0.Status.INTERNAL,details:`Error serializing response: ${(0,oE.getErrorMessage)(q)}`,metadata:null});return}if(this.maxSendMessageSize!==-1&&T.length-5>this.maxSendMessageSize){this.sendStatus({code:o0.Status.RESOURCE_EXHAUSTED,details:`Sent message larger than max (${T.length} vs. ${this.maxSendMessageSize})`,metadata:null});return}this.maybeSendMetadata(),qY("Request to "+this.handler.path+" sent data frame of size "+T.length),this.stream.write(T,(q)=>{var X;if(q){this.sendStatus({code:o0.Status.INTERNAL,details:`Error writing message: ${(0,oE.getErrorMessage)(q)}`,metadata:null});return}(X=this.callEventTracker)===null||X===void 0||X.addMessageSent(),Y()})}sendStatus($){var Y,T,q;if(this.checkCancelled())return;qY("Request to method "+((Y=this.handler)===null||Y===void 0?void 0:Y.path)+" ended with status code: "+o0.Status[$.code]+" details: "+$.details);let X=(q=(T=$.metadata)===null||T===void 0?void 0:T.clone())!==null&&q!==void 0?q:new sq.Metadata;if(this.shouldSendMetrics)X.set(tE.GRPC_METRICS_HEADER,this.metricsRecorder.serialize());if(this.metadataSent)if(!this.wantTrailers)this.wantTrailers=!0,this.stream.once("wantTrailers",()=>{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign({[$V]:$.code,[eE]:encodeURI($.details)},X.toHttp2Headers());this.stream.sendTrailers(J),this.notifyOnCancel()}),this.stream.end();else this.notifyOnCancel();else{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign(Object.assign({[$V]:$.code,[eE]:encodeURI($.details)},YV),X.toHttp2Headers());this.stream.respond(J,{endStream:!0}),this.notifyOnCancel()}}startRead(){if(qY("Request to "+this.handler.path+" startRead called"),this.checkCancelled())return;if(this.isReadPending=!0,this.readQueue.length===0){if(!this.receivedHalfClose)this.stream.resume()}else this.maybePushNextMessage()}getPeer(){var $;let Y=($=this.stream.session)===null||$===void 0?void 0:$.socket;if(Y===null||Y===void 0?void 0:Y.remoteAddress)if(Y.remotePort)return`${Y.remoteAddress}:${Y.remotePort}`;else return Y.remoteAddress;else return"unknown"}getDeadline(){return this.deadline}getHost(){return this.host}getAuthContext(){var $;if((($=this.stream.session)===null||$===void 0?void 0:$.socket)instanceof KS.TLSSocket){let Y=this.stream.session.socket.getPeerCertificate();return{transportSecurityType:"ssl",sslPeerCertificate:Y.raw?Y:void 0}}else return{}}getConnectionInfo(){return this.connectionInfo}getMetricsRecorder(){return this.metricsRecorder}}KV.BaseServerInterceptingCall=XJ;function DS($,Y,T,q,X,J){let Q={path:X.path,requestStream:X.type==="clientStream"||X.type==="bidi",responseStream:X.type==="serverStream"||X.type==="bidi",requestDeserialize:X.deserialize,responseSerialize:X.serialize},U=new XJ(Y,T,q,X,J);return $.reduce((Z,K)=>{return K(Q,Z)},U)}});var NV=B((k$)=>{var MS=k$&&k$.__runInitializers||function($,Y,T){var q=arguments.length>2;for(var X=0;X<Y.length;X++)T=q?Y[X].call($,T):Y[X].call($);return q?T:void 0},BS=k$&&k$.__esDecorate||function($,Y,T,q,X,J){function Q(I){if(I!==void 0&&typeof I!=="function")throw TypeError("Function expected");return I}var U=q.kind,Z=U==="getter"?"get":U==="setter"?"set":"value",K=!Y&&$?q.static?$:$.prototype:null,A=Y||(K?Object.getOwnPropertyDescriptor(K,q.name):{}),W,E=!1;for(var V=T.length-1;V>=0;V--){var F={};for(var H in q)F[H]=H==="access"?{}:q[H];for(var H in q.access)F.access[H]=q.access[H];F.addInitializer=function(I){if(E)throw TypeError("Cannot add initializers after decoration has completed");J.push(Q(I||null))};var D=(0,T[V])(U==="accessor"?{get:A.get,set:A.set}:A[Z],F);if(U==="accessor"){if(D===void 0)continue;if(D===null||typeof D!=="object")throw TypeError("Object expected");if(W=Q(D.get))A.get=W;if(W=Q(D.set))A.set=W;if(W=Q(D.init))X.unshift(W)}else if(W=Q(D))if(U==="field")X.unshift(W);else A[Z]=W}if(K)Object.defineProperty(K,q.name,A);E=!0};Object.defineProperty(k$,"__esModule",{value:!0});k$.Server=void 0;var s0=s("http2"),RS=s("util"),N0=i(),oY=xE(),QJ=nq(),WV=B1(),aY=U0(),x$=r0(),y1=p0(),M0=y$(),GV=JJ(),rY=2147483647,UJ=2147483647,OS=20000,EV=2147483647,{HTTP2_HEADER_PATH:VV}=s0.constants,PS="server",DV=Buffer.from("max_age");function FV($){aY.trace(N0.LogVerbosity.DEBUG,"server_call",$)}function LS(){}function wS($){return function(Y,T){return RS.deprecate(Y,$)}}function ZJ($){return{code:N0.Status.UNIMPLEMENTED,details:`The server does not implement the method ${$}`}}function SS($,Y){let T=ZJ(Y);switch($){case"unary":return(q,X)=>{X(T,null)};case"clientStream":return(q,X)=>{X(T,null)};case"serverStream":return(q)=>{q.emit("error",T)};case"bidi":return(q)=>{q.emit("error",T)};default:throw Error(`Invalid handlerType ${$}`)}}var CS=(()=>{var $;let Y=[],T;return $=class{constructor(X){var J,Q,U,Z,K,A;if(this.boundPorts=(MS(this,Y),new Map),this.http2Servers=new Map,this.sessionIdleTimeouts=new Map,this.handlers=new Map,this.sessions=new Map,this.started=!1,this.shutdown=!1,this.serverAddressString="null",this.channelzEnabled=!0,this.options=X!==null&&X!==void 0?X:{},this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new M0.ChannelzTraceStub,this.callTracker=new M0.ChannelzCallTrackerStub,this.listenerChildrenTracker=new M0.ChannelzChildrenTrackerStub,this.sessionChildrenTracker=new M0.ChannelzChildrenTrackerStub;else this.channelzTrace=new M0.ChannelzTrace,this.callTracker=new M0.ChannelzCallTracker,this.listenerChildrenTracker=new M0.ChannelzChildrenTracker,this.sessionChildrenTracker=new M0.ChannelzChildrenTracker;if(this.channelzRef=(0,M0.registerChannelzServer)("server",()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Server created"),this.maxConnectionAgeMs=(J=this.options["grpc.max_connection_age_ms"])!==null&&J!==void 0?J:rY,this.maxConnectionAgeGraceMs=(Q=this.options["grpc.max_connection_age_grace_ms"])!==null&&Q!==void 0?Q:rY,this.keepaliveTimeMs=(U=this.options["grpc.keepalive_time_ms"])!==null&&U!==void 0?U:UJ,this.keepaliveTimeoutMs=(Z=this.options["grpc.keepalive_timeout_ms"])!==null&&Z!==void 0?Z:OS,this.sessionIdleTimeout=(K=this.options["grpc.max_connection_idle_ms"])!==null&&K!==void 0?K:EV,this.commonServerOptions={maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER},"grpc-node.max_session_memory"in this.options)this.commonServerOptions.maxSessionMemory=this.options["grpc-node.max_session_memory"];else this.commonServerOptions.maxSessionMemory=Number.MAX_SAFE_INTEGER;if("grpc.max_concurrent_streams"in this.options)this.commonServerOptions.settings={maxConcurrentStreams:this.options["grpc.max_concurrent_streams"]};this.interceptors=(A=this.options.interceptors)!==null&&A!==void 0?A:[],this.trace("Server constructed")}getChannelzInfo(){return{trace:this.channelzTrace,callTracker:this.callTracker,listenerChildren:this.listenerChildrenTracker.getChildLists(),sessionChildren:this.sessionChildrenTracker.getChildLists()}}getChannelzSessionInfo(X){var J,Q,U;let Z=this.sessions.get(X),K=X.socket,A=K.remoteAddress?(0,x$.stringToSubchannelAddress)(K.remoteAddress,K.remotePort):null,W=K.localAddress?(0,x$.stringToSubchannelAddress)(K.localAddress,K.localPort):null,E;if(X.encrypted){let F=K,H=F.getCipher(),D=F.getCertificate(),I=F.getPeerCertificate();E={cipherSuiteStandardName:(J=H.standardName)!==null&&J!==void 0?J:null,cipherSuiteOtherName:H.standardName?null:H.name,localCertificate:D&&"raw"in D?D.raw:null,remoteCertificate:I&&"raw"in I?I.raw:null}}else E=null;return{remoteAddress:A,localAddress:W,security:E,remoteName:null,streamsStarted:Z.streamTracker.callsStarted,streamsSucceeded:Z.streamTracker.callsSucceeded,streamsFailed:Z.streamTracker.callsFailed,messagesSent:Z.messagesSent,messagesReceived:Z.messagesReceived,keepAlivesSent:Z.keepAlivesSent,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:Z.streamTracker.lastCallStartedTimestamp,lastMessageSentTimestamp:Z.lastMessageSentTimestamp,lastMessageReceivedTimestamp:Z.lastMessageReceivedTimestamp,localFlowControlWindow:(Q=X.state.localWindowSize)!==null&&Q!==void 0?Q:null,remoteFlowControlWindow:(U=X.state.remoteWindowSize)!==null&&U!==void 0?U:null}}trace(X){aY.trace(N0.LogVerbosity.DEBUG,PS,"("+this.channelzRef.id+") "+X)}keepaliveTrace(X){aY.trace(N0.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+X)}addProtoService(){throw Error("Not implemented. Use addService() instead")}addService(X,J){if(X===null||typeof X!=="object"||J===null||typeof J!=="object")throw Error("addService() requires two objects as arguments");let Q=Object.keys(X);if(Q.length===0)throw Error("Cannot add an empty service to a server");Q.forEach((U)=>{let Z=X[U],K;if(Z.requestStream)if(Z.responseStream)K="bidi";else K="clientStream";else if(Z.responseStream)K="serverStream";else K="unary";let A=J[U],W;if(A===void 0&&typeof Z.originalName==="string")A=J[Z.originalName];if(A!==void 0)W=A.bind(J);else W=SS(K,U);if(this.register(Z.path,W,Z.responseSerialize,Z.requestDeserialize,K)===!1)throw Error(`Method handler for ${Z.path} already provided.`)})}removeService(X){if(X===null||typeof X!=="object")throw Error("removeService() requires object as argument");Object.keys(X).forEach((Q)=>{let U=X[Q];this.unregister(U.path)})}bind(X,J){throw Error("Not implemented. Use bindAsync() instead")}experimentalRegisterListenerToChannelz(X){return(0,M0.registerChannelzSocket)((0,x$.subchannelAddressToString)(X),()=>{return{localAddress:X,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalUnregisterListenerFromChannelz(X){(0,M0.unregisterChannelzRef)(X)}createHttp2Server(X){let J;if(X._isSecure()){let Q=X._getConstructorOptions(),U=X._getSecureContextOptions(),Z=Object.assign(Object.assign(Object.assign(Object.assign({},this.commonServerOptions),Q),U),{enableTrace:this.options["grpc-node.tls_enable_trace"]===1}),K=U!==null;this.trace("Initial credentials valid: "+K),J=s0.createSecureServer(Z),J.prependListener("connection",(W)=>{if(!K)this.trace("Dropped connection from "+JSON.stringify(W.address())+" due to unloaded credentials"),W.destroy()}),J.on("secureConnection",(W)=>{W.on("error",(E)=>{this.trace("An incoming TLS connection closed with error: "+E.message)})});let A=(W)=>{if(W){let E=J;try{E.setSecureContext(W)}catch(V){aY.log(N0.LogVerbosity.ERROR,"Failed to set secure context with error "+V.message),W=null}}K=W!==null,this.trace("Post-update credentials valid: "+K)};X._addWatcher(A),J.on("close",()=>{X._removeWatcher(A)})}else J=s0.createServer(this.commonServerOptions);return J.setTimeout(0,LS),this._setupHandlers(J,X._getInterceptors()),J}bindOneAddress(X,J){this.trace("Attempting to bind "+(0,x$.subchannelAddressToString)(X));let Q=this.createHttp2Server(J.credentials);return new Promise((U,Z)=>{let K=(A)=>{this.trace("Failed to bind "+(0,x$.subchannelAddressToString)(X)+" with error "+A.message),U({port:"port"in X?X.port:1,error:A.message})};Q.once("error",K),Q.listen(X,()=>{let A=Q.address(),W;if(typeof A==="string")W={path:A};else W={host:A.address,port:A.port};let E=this.experimentalRegisterListenerToChannelz(W);this.listenerChildrenTracker.refChild(E),this.http2Servers.set(Q,{channelzRef:E,sessions:new Set,ownsChannelzRef:!0}),J.listeningServers.add(Q),this.trace("Successfully bound "+(0,x$.subchannelAddressToString)(W)),U({port:"port"in W?W.port:1}),Q.removeListener("error",K)})})}async bindManyPorts(X,J){if(X.length===0)return{count:0,port:0,errors:[]};if((0,x$.isTcpSubchannelAddress)(X[0])&&X[0].port===0){let Q=await this.bindOneAddress(X[0],J);if(Q.error){let U=await this.bindManyPorts(X.slice(1),J);return Object.assign(Object.assign({},U),{errors:[Q.error,...U.errors]})}else{let U=X.slice(1).map((A)=>(0,x$.isTcpSubchannelAddress)(A)?{host:A.host,port:Q.port}:A),Z=await Promise.all(U.map((A)=>this.bindOneAddress(A,J))),K=[Q,...Z];return{count:K.filter((A)=>A.error===void 0).length,port:Q.port,errors:K.filter((A)=>A.error).map((A)=>A.error)}}}else{let Q=await Promise.all(X.map((U)=>this.bindOneAddress(U,J)));return{count:Q.filter((U)=>U.error===void 0).length,port:Q[0].port,errors:Q.filter((U)=>U.error).map((U)=>U.error)}}}async bindAddressList(X,J){let Q=await this.bindManyPorts(X,J);if(Q.count>0){if(Q.count<X.length)aY.log(N0.LogVerbosity.INFO,`WARNING Only ${Q.count} addresses added out of total ${X.length} resolved`);return Q.port}else{let U=`No address added out of total ${X.length} resolved`;throw aY.log(N0.LogVerbosity.ERROR,U),Error(`${U} errors: [${Q.errors.join(",")}]`)}}resolvePort(X){return new Promise((J,Q)=>{let U=!1,Z=(A,W,E,V)=>{if(U)return!0;if(U=!0,!A.ok)return Q(Error(A.error.details)),!0;let F=[].concat(...A.value.map((H)=>H.addresses));if(F.length===0)return Q(Error(`No addresses resolved for port ${X}`)),!0;return J(F),!0};(0,WV.createResolver)(X,Z,this.options).updateResolution()})}async bindPort(X,J){let Q=await this.resolvePort(X);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");let U=await this.bindAddressList(Q,J);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");return U}normalizePort(X){let J=(0,y1.parseUri)(X);if(J===null)throw Error(`Could not parse port "${X}"`);let Q=(0,WV.mapUriDefaultScheme)(J);if(Q===null)throw Error(`Could not get a default scheme for port "${X}"`);return Q}bindAsync(X,J,Q){if(this.shutdown)throw Error("bindAsync called after shutdown");if(typeof X!=="string")throw TypeError("port must be a string");if(J===null||!(J instanceof QJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(typeof Q!=="function")throw TypeError("callback must be a function");this.trace("bindAsync port="+X);let U=this.normalizePort(X),Z=(E,V)=>{process.nextTick(()=>Q(E,V))},K=this.boundPorts.get((0,y1.uriToString)(U));if(K){if(!J._equals(K.credentials)){Z(Error(`${X} already bound with incompatible credentials`),0);return}if(K.cancelled=!1,K.completionPromise)K.completionPromise.then((E)=>Q(null,E),(E)=>Q(E,0));else Z(null,K.portNumber);return}K={mapKey:(0,y1.uriToString)(U),originalUri:U,completionPromise:null,cancelled:!1,portNumber:0,credentials:J,listeningServers:new Set};let A=(0,y1.splitHostPort)(U.path),W=this.bindPort(U,K);if(K.completionPromise=W,(A===null||A===void 0?void 0:A.port)===0)W.then((E)=>{let V={scheme:U.scheme,authority:U.authority,path:(0,y1.combineHostPort)({host:A.host,port:E})};K.mapKey=(0,y1.uriToString)(V),K.completionPromise=null,K.portNumber=E,this.boundPorts.set(K.mapKey,K),Q(null,E)},(E)=>{Q(E,0)});else this.boundPorts.set(K.mapKey,K),W.then((E)=>{K.completionPromise=null,K.portNumber=E,Q(null,E)},(E)=>{Q(E,0)})}registerInjectorToChannelz(){return(0,M0.registerChannelzSocket)("injector",()=>{return{localAddress:null,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalCreateConnectionInjectorWithChannelzRef(X,J,Q=!1){if(X===null||!(X instanceof QJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(this.channelzEnabled)this.listenerChildrenTracker.refChild(J);let U=this.createHttp2Server(X),Z=new Set;return this.http2Servers.set(U,{channelzRef:J,sessions:Z,ownsChannelzRef:Q}),{injectConnection:(K)=>{U.emit("connection",K)},drain:(K)=>{var A,W;for(let E of Z)this.closeSession(E);(W=(A=setTimeout(()=>{for(let E of Z)E.destroy(s0.constants.NGHTTP2_CANCEL)},K)).unref)===null||W===void 0||W.call(A)},destroy:()=>{this.closeServer(U);for(let K of Z)this.closeSession(K)}}}createConnectionInjector(X){if(X===null||!(X instanceof QJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");let J=this.registerInjectorToChannelz();return this.experimentalCreateConnectionInjectorWithChannelzRef(X,J,!0)}closeServer(X,J){this.trace("Closing server with address "+JSON.stringify(X.address()));let Q=this.http2Servers.get(X);X.close(()=>{if(Q&&Q.ownsChannelzRef)this.listenerChildrenTracker.unrefChild(Q.channelzRef),(0,M0.unregisterChannelzRef)(Q.channelzRef);this.http2Servers.delete(X),J===null||J===void 0||J()})}closeSession(X,J){var Q;this.trace("Closing session initiated by "+((Q=X.socket)===null||Q===void 0?void 0:Q.remoteAddress));let U=this.sessions.get(X),Z=()=>{if(U)this.sessionChildrenTracker.unrefChild(U.ref),(0,M0.unregisterChannelzRef)(U.ref);J===null||J===void 0||J()};if(X.closed)queueMicrotask(Z);else X.close(Z)}completeUnbind(X){for(let J of X.listeningServers){let Q=this.http2Servers.get(J);if(this.closeServer(J,()=>{X.listeningServers.delete(J)}),Q)for(let U of Q.sessions)this.closeSession(U)}this.boundPorts.delete(X.mapKey)}unbind(X){this.trace("unbind port="+X);let J=this.normalizePort(X),Q=(0,y1.splitHostPort)(J.path);if((Q===null||Q===void 0?void 0:Q.port)===0)throw Error("Cannot unbind port 0");let U=this.boundPorts.get((0,y1.uriToString)(J));if(U)if(this.trace("unbinding "+U.mapKey+" originally bound as "+(0,y1.uriToString)(U.originalUri)),U.completionPromise)U.cancelled=!0;else this.completeUnbind(U)}drain(X,J){var Q,U;this.trace("drain port="+X+" graceTimeMs="+J);let Z=this.normalizePort(X),K=(0,y1.splitHostPort)(Z.path);if((K===null||K===void 0?void 0:K.port)===0)throw Error("Cannot drain port 0");let A=this.boundPorts.get((0,y1.uriToString)(Z));if(!A)return;let W=new Set;for(let E of A.listeningServers){let V=this.http2Servers.get(E);if(V)for(let F of V.sessions)W.add(F),this.closeSession(F,()=>{W.delete(F)})}(U=(Q=setTimeout(()=>{for(let E of W)E.destroy(s0.constants.NGHTTP2_CANCEL)},J)).unref)===null||U===void 0||U.call(Q)}forceShutdown(){for(let X of this.boundPorts.values())X.cancelled=!0;this.boundPorts.clear();for(let X of this.http2Servers.keys())this.closeServer(X);this.sessions.forEach((X,J)=>{this.closeSession(J),J.destroy(s0.constants.NGHTTP2_CANCEL)}),this.sessions.clear(),(0,M0.unregisterChannelzRef)(this.channelzRef),this.shutdown=!0}register(X,J,Q,U,Z){if(this.handlers.has(X))return!1;return this.handlers.set(X,{func:J,serialize:Q,deserialize:U,type:Z,path:X}),!0}unregister(X){return this.handlers.delete(X)}start(){if(this.http2Servers.size===0||[...this.http2Servers.keys()].every((X)=>!X.listening))throw Error("server must be bound in order to start");if(this.started===!0)throw Error("server is already started");this.started=!0}tryShutdown(X){var J;let Q=(K)=>{(0,M0.unregisterChannelzRef)(this.channelzRef),X(K)},U=0;function Z(){if(U--,U===0)Q()}this.shutdown=!0;for(let[K,A]of this.http2Servers.entries()){U++;let W=A.channelzRef.name;this.trace("Waiting for server "+W+" to close"),this.closeServer(K,()=>{this.trace("Server "+W+" finished closing"),Z()});for(let E of A.sessions.keys()){U++;let V=(J=E.socket)===null||J===void 0?void 0:J.remoteAddress;this.trace("Waiting for session "+V+" to close"),this.closeSession(E,()=>{this.trace("Session "+V+" finished closing"),Z()})}}if(U===0)Q()}addHttp2Port(){throw Error("Not yet implemented")}getChannelzRef(){return this.channelzRef}_verifyContentType(X,J){let Q=J[s0.constants.HTTP2_HEADER_CONTENT_TYPE];if(typeof Q!=="string"||!Q.startsWith("application/grpc"))return X.respond({[s0.constants.HTTP2_HEADER_STATUS]:s0.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE},{endStream:!0}),!1;return!0}_retrieveHandler(X){FV("Received call to method "+X+" at address "+this.serverAddressString);let J=this.handlers.get(X);if(J===void 0)return FV("No handler registered for method "+X+". Sending UNIMPLEMENTED status."),null;return J}_respondWithError(X,J,Q=null){var U,Z;let K=Object.assign({"grpc-status":(U=X.code)!==null&&U!==void 0?U:N0.Status.INTERNAL,"grpc-message":X.details,[s0.constants.HTTP2_HEADER_STATUS]:s0.constants.HTTP_STATUS_OK,[s0.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},(Z=X.metadata)===null||Z===void 0?void 0:Z.toHttp2Headers());J.respond(K,{endStream:!0}),this.callTracker.addCallFailed(),Q===null||Q===void 0||Q.streamTracker.addCallFailed()}_channelzHandler(X,J,Q){this.onStreamOpened(J);let U=this.sessions.get(J.session);if(this.callTracker.addCallStarted(),U===null||U===void 0||U.streamTracker.addCallStarted(),!this._verifyContentType(J,Q)){this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed();return}let Z=Q[VV],K=this._retrieveHandler(Z);if(!K){this._respondWithError(ZJ(Z),J,U);return}let A={addMessageSent:()=>{if(U)U.messagesSent+=1,U.lastMessageSentTimestamp=new Date},addMessageReceived:()=>{if(U)U.messagesReceived+=1,U.lastMessageReceivedTimestamp=new Date},onCallEnd:(E)=>{if(E.code===N0.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()},onStreamEnd:(E)=>{if(U)if(E)U.streamTracker.addCallSucceeded();else U.streamTracker.addCallFailed()}},W=(0,GV.getServerInterceptingCall)([...X,...this.interceptors],J,Q,A,K,this.options);if(!this._runHandlerForCall(W,K))this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed(),W.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${K.type}`})}_streamHandler(X,J,Q){if(this.onStreamOpened(J),this._verifyContentType(J,Q)!==!0)return;let U=Q[VV],Z=this._retrieveHandler(U);if(!Z){this._respondWithError(ZJ(U),J,null);return}let K=(0,GV.getServerInterceptingCall)([...X,...this.interceptors],J,Q,null,Z,this.options);if(!this._runHandlerForCall(K,Z))K.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${Z.type}`})}_runHandlerForCall(X,J){let{type:Q}=J;if(Q==="unary")yS(X,J);else if(Q==="clientStream")jS(X,J);else if(Q==="serverStream")vS(X,J);else if(Q==="bidi")xS(X,J);else return!1;return!0}_setupHandlers(X,J){if(X===null)return;let Q=X.address(),U="null";if(Q)if(typeof Q==="string")U=Q;else U=Q.address+":"+Q.port;this.serverAddressString=U;let Z=this.channelzEnabled?this._channelzHandler:this._streamHandler,K=this.channelzEnabled?this._channelzSessionHandler(X):this._sessionHandler(X);X.on("stream",Z.bind(this,J)),X.on("session",K)}_sessionHandler(X){return(J)=>{var Q,U;(Q=this.http2Servers.get(X))===null||Q===void 0||Q.sessions.add(J);let Z=null,K=null,A=null,W=!1,E=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==rY){let I=this.maxConnectionAgeMs/10,S=Math.random()*I*2-I;Z=setTimeout(()=>{var v,z;W=!0,this.trace("Connection dropped by max connection age: "+((v=J.socket)===null||v===void 0?void 0:v.remoteAddress));try{J.goaway(s0.constants.NGHTTP2_NO_ERROR,2147483647,DV)}catch(_){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==rY)K=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(z=K.unref)===null||z===void 0||z.call(K)},this.maxConnectionAgeMs+S),(U=Z.unref)===null||U===void 0||U.call(Z)}let V=()=>{if(A)clearTimeout(A),A=null},F=()=>{return!J.destroyed&&this.keepaliveTimeMs<UJ&&this.keepaliveTimeMs>0},H,D=()=>{var I;if(!F())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),A=setTimeout(()=>{V(),H()},this.keepaliveTimeMs),(I=A.unref)===null||I===void 0||I.call(A)};H=()=>{var I;if(!F())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let S="";try{if(!J.ping((z,_,y)=>{if(V(),z)this.keepaliveTrace("Ping failed with error: "+z.message),W=!0,J.destroy();else this.keepaliveTrace("Received ping response"),D()}))S="Ping returned false"}catch(v){S=(v instanceof Error?v.message:"")||"Unknown error"}if(S){this.keepaliveTrace("Ping send failed: "+S),this.trace("Connection dropped due to ping send error: "+S),W=!0,J.destroy();return}A=setTimeout(()=>{V(),this.keepaliveTrace("Ping timeout passed without response"),this.trace("Connection dropped by keepalive timeout"),W=!0,J.destroy()},this.keepaliveTimeoutMs),(I=A.unref)===null||I===void 0||I.call(A)},D(),J.on("close",()=>{var I,S;if(!W)this.trace(`Connection dropped by client ${(I=J.socket)===null||I===void 0?void 0:I.remoteAddress}`);if(Z)clearTimeout(Z);if(K)clearTimeout(K);if(V(),E!==null)clearTimeout(E.timeout),this.sessionIdleTimeouts.delete(J);(S=this.http2Servers.get(X))===null||S===void 0||S.sessions.delete(J)})}}_channelzSessionHandler(X){return(J)=>{var Q,U,Z,K;let A=(0,M0.registerChannelzSocket)((U=(Q=J.socket)===null||Q===void 0?void 0:Q.remoteAddress)!==null&&U!==void 0?U:"unknown",this.getChannelzSessionInfo.bind(this,J),this.channelzEnabled),W={ref:A,streamTracker:new M0.ChannelzCallTracker,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null};(Z=this.http2Servers.get(X))===null||Z===void 0||Z.sessions.add(J),this.sessions.set(J,W);let E=`${J.socket.remoteAddress}:${J.socket.remotePort}`;this.channelzTrace.addTrace("CT_INFO","Connection established by client "+E),this.trace("Connection established by client "+E),this.sessionChildrenTracker.refChild(A);let V=null,F=null,H=null,D=!1,I=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==rY){let y=this.maxConnectionAgeMs/10,k=Math.random()*y*2-y;V=setTimeout(()=>{var m;D=!0,this.channelzTrace.addTrace("CT_INFO","Connection dropped by max connection age from "+E);try{J.goaway(s0.constants.NGHTTP2_NO_ERROR,2147483647,DV)}catch(C){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==rY)F=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(m=F.unref)===null||m===void 0||m.call(F)},this.maxConnectionAgeMs+k),(K=V.unref)===null||K===void 0||K.call(V)}let S=()=>{if(H)clearTimeout(H),H=null},v=()=>{return!J.destroyed&&this.keepaliveTimeMs<UJ&&this.keepaliveTimeMs>0},z,_=()=>{var y;if(!v())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),H=setTimeout(()=>{S(),z()},this.keepaliveTimeMs),(y=H.unref)===null||y===void 0||y.call(H)};z=()=>{var y;if(!v())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let k="";try{if(!J.ping((C,j,M)=>{if(S(),C)this.keepaliveTrace("Ping failed with error: "+C.message),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to error of a ping frame "+C.message+" return in "+j),D=!0,J.destroy();else this.keepaliveTrace("Received ping response"),_()}))k="Ping returned false"}catch(m){k=(m instanceof Error?m.message:"")||"Unknown error"}if(k){this.keepaliveTrace("Ping send failed: "+k),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to ping send error: "+k),D=!0,J.destroy();return}W.keepAlivesSent+=1,H=setTimeout(()=>{S(),this.keepaliveTrace("Ping timeout passed without response"),this.channelzTrace.addTrace("CT_INFO","Connection dropped by keepalive timeout from "+E),D=!0,J.destroy()},this.keepaliveTimeoutMs),(y=H.unref)===null||y===void 0||y.call(H)},_(),J.on("close",()=>{var y;if(!D)this.channelzTrace.addTrace("CT_INFO","Connection dropped by client "+E);if(this.sessionChildrenTracker.unrefChild(A),(0,M0.unregisterChannelzRef)(A),V)clearTimeout(V);if(F)clearTimeout(F);if(S(),I!==null)clearTimeout(I.timeout),this.sessionIdleTimeouts.delete(J);(y=this.http2Servers.get(X))===null||y===void 0||y.sessions.delete(J),this.sessions.delete(J)})}}enableIdleTimeout(X){var J,Q;if(this.sessionIdleTimeout>=EV)return null;let U={activeStreams:0,lastIdle:Date.now(),onClose:this.onStreamClose.bind(this,X),timeout:setTimeout(this.onIdleTimeout,this.sessionIdleTimeout,this,X)};(Q=(J=U.timeout).unref)===null||Q===void 0||Q.call(J),this.sessionIdleTimeouts.set(X,U);let{socket:Z}=X;return this.trace("Enable idle timeout for "+Z.remoteAddress+":"+Z.remotePort),U}onIdleTimeout(X,J){let{socket:Q}=J,U=X.sessionIdleTimeouts.get(J);if(U!==void 0&&U.activeStreams===0)if(Date.now()-U.lastIdle>=X.sessionIdleTimeout)X.trace("Session idle timeout triggered for "+(Q===null||Q===void 0?void 0:Q.remoteAddress)+":"+(Q===null||Q===void 0?void 0:Q.remotePort)+" last idle at "+U.lastIdle),X.closeSession(J);else U.timeout.refresh()}onStreamOpened(X){let J=X.session,Q=this.sessionIdleTimeouts.get(J);if(Q)Q.activeStreams+=1,X.once("close",Q.onClose)}onStreamClose(X){var J,Q;let U=this.sessionIdleTimeouts.get(X);if(U){if(U.activeStreams-=1,U.activeStreams===0)U.lastIdle=Date.now(),U.timeout.refresh(),this.trace("Session onStreamClose"+((J=X.socket)===null||J===void 0?void 0:J.remoteAddress)+":"+((Q=X.socket)===null||Q===void 0?void 0:Q.remotePort)+" at "+U.lastIdle)}}},(()=>{let q=typeof Symbol==="function"&&Symbol.metadata?Object.create(null):void 0;if(T=[wS("Calling start() is no longer necessary. It can be safely omitted.")],BS($,null,T,{kind:"method",name:"start",static:!1,private:!1,access:{has:(X)=>("start"in X),get:(X)=>X.start},metadata:q},null,Y),q)Object.defineProperty($,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:q})})(),$})();k$.Server=CS;async function yS($,Y){let T;function q(Q,U,Z,K){if(Q){$.sendStatus((0,oY.serverErrorToStatus)(Q,Z));return}$.sendMessage(U,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Z!==null&&Z!==void 0?Z:null})})}let X,J=null;$.start({onReceiveMetadata(Q){X=Q,$.startRead()},onReceiveMessage(Q){if(J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}J=Q,$.startRead()},onReceiveHalfClose(){if(!J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}T=new oY.ServerWritableStreamImpl(Y.path,$,X,J);try{Y.func(T,q)}catch(Q){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${Q.message}`,metadata:null})}},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled")}})}function jS($,Y){let T;function q(X,J,Q,U){if(X){$.sendStatus((0,oY.serverErrorToStatus)(X,Q));return}$.sendMessage(J,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Q!==null&&Q!==void 0?Q:null})})}$.start({onReceiveMetadata(X){T=new oY.ServerDuplexStreamImpl(Y.path,$,X);try{Y.func(T,q)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onReceiveMessage(X){T.push(X)},onReceiveHalfClose(){T.push(null)},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}function vS($,Y){let T,q,X=null;$.start({onReceiveMetadata(J){q=J,$.startRead()},onReceiveMessage(J){if(X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}X=J,$.startRead()},onReceiveHalfClose(){if(!X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}T=new oY.ServerWritableStreamImpl(Y.path,$,q,X);try{Y.func(T)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}function xS($,Y){let T;$.start({onReceiveMetadata(q){T=new oY.ServerDuplexStreamImpl(Y.path,$,q);try{Y.func(T)}catch(X){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${X.message}`,metadata:null})}},onReceiveMessage(q){T.push(q)},onReceiveHalfClose(){T.push(null)},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}});var MV=B((zV)=>{Object.defineProperty(zV,"__esModule",{value:!0});zV.StatusBuilder=void 0;class HV{constructor(){this.code=null,this.details=null,this.metadata=null}withCode($){return this.code=$,this}withDetails($){return this.details=$,this}withMetadata($){return this.metadata=$,this}build(){let $={};if(this.code!==null)$.code=this.code;if(this.details!==null)$.details=this.details;if(this.metadata!==null)$.metadata=this.metadata;return $}}zV.StatusBuilder=HV});var VT=B((CV)=>{Object.defineProperty(CV,"__esModule",{value:!0});CV.LeafLoadBalancer=CV.PickFirstLoadBalancer=CV.PickFirstLoadBalancingConfig=void 0;CV.shuffled=LV;CV.setup=uS;var KJ=M$(),H0=l0(),h$=Y$(),BV=r0(),kS=U0(),hS=i(),RV=r0(),OV=s("net"),_S=l$(),gS="pick_first";function GT($){kS.trace(hS.LogVerbosity.DEBUG,gS,$)}var ET="pick_first",mS=250;class sY{constructor($){this.shuffleAddressList=$}getLoadBalancerName(){return ET}toJsonObject(){return{[ET]:{shuffleAddressList:this.shuffleAddressList}}}getShuffleAddressList(){return this.shuffleAddressList}static createFromJson($){if("shuffleAddressList"in $&&typeof $.shuffleAddressList!=="boolean")throw Error("pick_first config field shuffleAddressList must be a boolean if provided");return new sY($.shuffleAddressList===!0)}}CV.PickFirstLoadBalancingConfig=sY;class PV{constructor($){this.subchannel=$}pick($){return{pickResultType:h$.PickResultType.COMPLETE,subchannel:this.subchannel,status:null,onCallStarted:null,onCallEnded:null}}}function LV($){let Y=$.slice();for(let T=Y.length-1;T>1;T--){let q=Math.floor(Math.random()*(T+1)),X=Y[T];Y[T]=Y[q],Y[q]=X}return Y}function fS($){if($.length===0)return[];let Y=[],T=[],q=[],X=(0,RV.isTcpSubchannelAddress)($[0])&&(0,OV.isIPv6)($[0].host);for(let U of $)if((0,RV.isTcpSubchannelAddress)(U)&&(0,OV.isIPv6)(U.host))T.push(U);else q.push(U);let J=X?T:q,Q=X?q:T;for(let U=0;U<Math.max(J.length,Q.length);U++){if(U<J.length)Y.push(J[U]);if(U<Q.length)Y.push(Q[U])}return Y}var wV="grpc-node.internal.pick-first.report_health_status";class tq{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=H0.ConnectivityState.IDLE,this.currentSubchannelIndex=0,this.currentPick=null,this.subchannelStateListener=(Y,T,q,X,J)=>{this.onSubchannelStateUpdate(Y,T,q,J)},this.pickedSubchannelHealthListener=()=>this.calculateAndReportNewState(),this.stickyTransientFailureMode=!1,this.reportHealthStatus=!1,this.lastError=null,this.latestAddressList=null,this.latestOptions={},this.latestResolutionNote="",this.connectionDelayTimeout=setTimeout(()=>{},0),clearTimeout(this.connectionDelayTimeout)}allChildrenHaveReportedTF(){return this.children.every(($)=>$.hasReportedTransientFailure)}resetChildrenReportedTF(){this.children.every(($)=>$.hasReportedTransientFailure=!1)}calculateAndReportNewState(){var $;if(this.currentPick)if(this.reportHealthStatus&&!this.currentPick.isHealthy()){let Y=`Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else this.updateState(H0.ConnectivityState.READY,new PV(this.currentPick),null);else if((($=this.latestAddressList)===null||$===void 0?void 0:$.length)===0){let Y=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else if(this.children.length===0)this.updateState(H0.ConnectivityState.IDLE,new h$.QueuePicker(this),null);else if(this.stickyTransientFailureMode){let Y=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else this.updateState(H0.ConnectivityState.CONNECTING,new h$.QueuePicker(this),null)}requestReresolution(){this.channelControlHelper.requestReresolution()}maybeEnterStickyTransientFailureMode(){if(!this.allChildrenHaveReportedTF())return;if(this.requestReresolution(),this.resetChildrenReportedTF(),this.stickyTransientFailureMode){this.calculateAndReportNewState();return}this.stickyTransientFailureMode=!0;for(let{subchannel:$}of this.children)$.startConnecting();this.calculateAndReportNewState()}removeCurrentPick(){if(this.currentPick!==null)this.currentPick.removeConnectivityStateListener(this.subchannelStateListener),this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()),this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick.unref(),this.currentPick=null}onSubchannelStateUpdate($,Y,T,q){var X;if((X=this.currentPick)===null||X===void 0?void 0:X.realSubchannelEquals($)){if(T!==H0.ConnectivityState.READY)this.removeCurrentPick(),this.calculateAndReportNewState();return}for(let[J,Q]of this.children.entries())if($.realSubchannelEquals(Q.subchannel)){if(T===H0.ConnectivityState.READY)this.pickSubchannel(Q.subchannel);if(T===H0.ConnectivityState.TRANSIENT_FAILURE){if(Q.hasReportedTransientFailure=!0,q)this.lastError=q;if(this.maybeEnterStickyTransientFailureMode(),J===this.currentSubchannelIndex)this.startNextSubchannelConnecting(J+1)}Q.subchannel.startConnecting();return}}startNextSubchannelConnecting($){clearTimeout(this.connectionDelayTimeout);for(let[Y,T]of this.children.entries())if(Y>=$){let q=T.subchannel.getConnectivityState();if(q===H0.ConnectivityState.IDLE||q===H0.ConnectivityState.CONNECTING){this.startConnecting(Y);return}}this.maybeEnterStickyTransientFailureMode()}startConnecting($){var Y,T;if(clearTimeout(this.connectionDelayTimeout),this.currentSubchannelIndex=$,this.children[$].subchannel.getConnectivityState()===H0.ConnectivityState.IDLE)GT("Start connecting to subchannel with address "+this.children[$].subchannel.getAddress()),process.nextTick(()=>{var q;(q=this.children[$])===null||q===void 0||q.subchannel.startConnecting()});this.connectionDelayTimeout=setTimeout(()=>{this.startNextSubchannelConnecting($+1)},mS),(T=(Y=this.connectionDelayTimeout).unref)===null||T===void 0||T.call(Y)}pickSubchannel($){GT("Pick subchannel with address "+$.getAddress()),this.stickyTransientFailureMode=!1,$.ref(),this.channelControlHelper.addChannelzChild($.getChannelzRef()),this.removeCurrentPick(),this.resetSubchannelList(),$.addConnectivityStateListener(this.subchannelStateListener),$.addHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick=$,clearTimeout(this.connectionDelayTimeout),this.calculateAndReportNewState()}updateState($,Y,T){GT(H0.ConnectivityState[this.currentState]+" -> "+H0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,T)}resetSubchannelList(){for(let $ of this.children)$.subchannel.removeConnectivityStateListener(this.subchannelStateListener),$.subchannel.unref(),this.channelControlHelper.removeChannelzChild($.subchannel.getChannelzRef());this.currentSubchannelIndex=0,this.children=[]}connectToAddressList($,Y){GT("connectToAddressList(["+$.map((q)=>(0,BV.subchannelAddressToString)(q))+"])");let T=$.map((q)=>({subchannel:this.channelControlHelper.createSubchannel(q,Y),hasReportedTransientFailure:!1}));for(let{subchannel:q}of T)if(q.getConnectivityState()===H0.ConnectivityState.READY){this.pickSubchannel(q);return}for(let{subchannel:q}of T)q.ref(),this.channelControlHelper.addChannelzChild(q.getChannelzRef());this.resetSubchannelList(),this.children=T;for(let{subchannel:q}of this.children)q.addConnectivityStateListener(this.subchannelStateListener);for(let q of this.children)if(q.subchannel.getConnectivityState()===H0.ConnectivityState.TRANSIENT_FAILURE)q.hasReportedTransientFailure=!0;this.startNextSubchannelConnecting(0),this.calculateAndReportNewState()}updateAddressList($,Y,T,q){if(!(Y instanceof sY))return!1;if(!$.ok){if(this.children.length===0&&this.currentPick===null)this.channelControlHelper.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker($.error),$.error.details);return!0}let X=$.value;if(this.reportHealthStatus=T[wV],Y.getShuffleAddressList())X=LV(X);let J=[].concat(...X.map((U)=>U.addresses));GT("updateAddressList(["+J.map((U)=>(0,BV.subchannelAddressToString)(U))+"])");let Q=fS(J);if(this.latestAddressList=Q,this.latestOptions=T,this.connectToAddressList(Q,T),this.latestResolutionNote=q,J.length>0)return!0;else return this.lastError="No addresses resolved",!1}exitIdle(){if(this.currentState===H0.ConnectivityState.IDLE&&this.latestAddressList)this.connectToAddressList(this.latestAddressList,this.latestOptions)}resetBackoff(){}destroy(){this.resetSubchannelList(),this.removeCurrentPick()}getTypeName(){return ET}}CV.PickFirstLoadBalancer=tq;var bS=new sY(!1);class SV{constructor($,Y,T,q){this.endpoint=$,this.options=T,this.resolutionNote=q,this.latestState=H0.ConnectivityState.IDLE;let X=(0,KJ.createChildChannelControlHelper)(Y,{updateState:(J,Q,U)=>{this.latestState=J,this.latestPicker=Q,Y.updateState(J,Q,U)}});this.pickFirstBalancer=new tq(X),this.latestPicker=new h$.QueuePicker(this.pickFirstBalancer)}startConnecting(){this.pickFirstBalancer.updateAddressList((0,_S.statusOrFromValue)([this.endpoint]),bS,Object.assign(Object.assign({},this.options),{[wV]:!0}),this.resolutionNote)}updateEndpoint($,Y){if(this.options=Y,this.endpoint=$,this.latestState!==H0.ConnectivityState.IDLE)this.startConnecting()}getConnectivityState(){return this.latestState}getPicker(){return this.latestPicker}getEndpoint(){return this.endpoint}exitIdle(){this.pickFirstBalancer.exitIdle()}destroy(){this.pickFirstBalancer.destroy()}}CV.LeafLoadBalancer=SV;function uS(){(0,KJ.registerLoadBalancerType)(ET,tq,sY),(0,KJ.registerDefaultLoadBalancerType)(ET)}});var kV=B((vV)=>{Object.defineProperty(vV,"__esModule",{value:!0});vV.FileWatcherCertificateProvider=void 0;var nS=s("fs"),iS=U0(),rS=i(),aS=s("util"),oS="certificate_provider";function eq($){iS.trace(rS.LogVerbosity.DEBUG,oS,$)}var AJ=(0,aS.promisify)(nS.readFile);class jV{constructor($){if(this.config=$,this.refreshTimer=null,this.fileResultPromise=null,this.latestCaUpdate=void 0,this.caListeners=new Set,this.latestIdentityUpdate=void 0,this.identityListeners=new Set,this.lastUpdateTime=null,$.certificateFile===void 0!==($.privateKeyFile===void 0))throw Error("certificateFile and privateKeyFile must be set or unset together");if($.certificateFile===void 0&&$.caCertificateFile===void 0)throw Error("At least one of certificateFile and caCertificateFile must be set");eq("File watcher constructed with config "+JSON.stringify($))}updateCertificates(){if(this.fileResultPromise)return;this.fileResultPromise=Promise.allSettled([this.config.certificateFile?AJ(this.config.certificateFile):Promise.reject(),this.config.privateKeyFile?AJ(this.config.privateKeyFile):Promise.reject(),this.config.caCertificateFile?AJ(this.config.caCertificateFile):Promise.reject()]),this.fileResultPromise.then(([$,Y,T])=>{if(!this.refreshTimer)return;if(eq("File watcher read certificates certificate "+$.status+", privateKey "+Y.status+", CA certificate "+T.status),this.lastUpdateTime=new Date,this.fileResultPromise=null,$.status==="fulfilled"&&Y.status==="fulfilled")this.latestIdentityUpdate={certificate:$.value,privateKey:Y.value};else this.latestIdentityUpdate=null;if(T.status==="fulfilled")this.latestCaUpdate={caCertificate:T.value};else this.latestCaUpdate=null;for(let q of this.identityListeners)q(this.latestIdentityUpdate);for(let q of this.caListeners)q(this.latestCaUpdate)}),eq("File watcher initiated certificate update")}maybeStartWatchingFiles(){if(!this.refreshTimer){let $=this.lastUpdateTime?new Date().getTime()-this.lastUpdateTime.getTime():1/0;if($>this.config.refreshIntervalMs)this.updateCertificates();if($>this.config.refreshIntervalMs*2)this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0;this.refreshTimer=setInterval(()=>this.updateCertificates(),this.config.refreshIntervalMs),eq("File watcher started watching")}}maybeStopWatchingFiles(){if(this.caListeners.size===0&&this.identityListeners.size===0){if(this.fileResultPromise=null,this.refreshTimer)clearInterval(this.refreshTimer),this.refreshTimer=null}}addCaCertificateListener($){if(this.caListeners.add($),this.maybeStartWatchingFiles(),this.latestCaUpdate!==void 0)process.nextTick($,this.latestCaUpdate)}removeCaCertificateListener($){this.caListeners.delete($),this.maybeStopWatchingFiles()}addIdentityCertificateListener($){if(this.identityListeners.add($),this.maybeStartWatchingFiles(),this.latestIdentityUpdate!==void 0)process.nextTick($,this.latestIdentityUpdate)}removeIdentityCertificateListener($){this.identityListeners.delete($),this.maybeStopWatchingFiles()}}vV.FileWatcherCertificateProvider=jV});var EJ=B((a)=>{Object.defineProperty(a,"__esModule",{value:!0});a.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=a.createCertificateProviderChannelCredentials=a.FileWatcherCertificateProvider=a.createCertificateProviderServerCredentials=a.createServerCredentialsWithInterceptors=a.BaseSubchannelWrapper=a.registerAdminService=a.FilterStackFactory=a.BaseFilter=a.statusOrFromError=a.statusOrFromValue=a.PickResultType=a.QueuePicker=a.UnavailablePicker=a.ChildLoadBalancerHandler=a.EndpointMap=a.endpointHasAddress=a.endpointToString=a.subchannelAddressToString=a.LeafLoadBalancer=a.isLoadBalancerNameRegistered=a.parseLoadBalancingConfig=a.selectLbConfigFromList=a.registerLoadBalancerType=a.createChildChannelControlHelper=a.BackoffTimeout=a.parseDuration=a.durationToMs=a.splitHostPort=a.uriToString=a.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=a.createResolver=a.registerResolver=a.log=a.trace=void 0;var hV=U0();Object.defineProperty(a,"trace",{enumerable:!0,get:function(){return hV.trace}});Object.defineProperty(a,"log",{enumerable:!0,get:function(){return hV.log}});var WJ=B1();Object.defineProperty(a,"registerResolver",{enumerable:!0,get:function(){return WJ.registerResolver}});Object.defineProperty(a,"createResolver",{enumerable:!0,get:function(){return WJ.createResolver}});Object.defineProperty(a,"CHANNEL_ARGS_CONFIG_SELECTOR_KEY",{enumerable:!0,get:function(){return WJ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY}});var _V=p0();Object.defineProperty(a,"uriToString",{enumerable:!0,get:function(){return _V.uriToString}});Object.defineProperty(a,"splitHostPort",{enumerable:!0,get:function(){return _V.splitHostPort}});var gV=WT();Object.defineProperty(a,"durationToMs",{enumerable:!0,get:function(){return gV.durationToMs}});Object.defineProperty(a,"parseDuration",{enumerable:!0,get:function(){return gV.parseDuration}});var sS=LY();Object.defineProperty(a,"BackoffTimeout",{enumerable:!0,get:function(){return sS.BackoffTimeout}});var DT=M$();Object.defineProperty(a,"createChildChannelControlHelper",{enumerable:!0,get:function(){return DT.createChildChannelControlHelper}});Object.defineProperty(a,"registerLoadBalancerType",{enumerable:!0,get:function(){return DT.registerLoadBalancerType}});Object.defineProperty(a,"selectLbConfigFromList",{enumerable:!0,get:function(){return DT.selectLbConfigFromList}});Object.defineProperty(a,"parseLoadBalancingConfig",{enumerable:!0,get:function(){return DT.parseLoadBalancingConfig}});Object.defineProperty(a,"isLoadBalancerNameRegistered",{enumerable:!0,get:function(){return DT.isLoadBalancerNameRegistered}});var tS=VT();Object.defineProperty(a,"LeafLoadBalancer",{enumerable:!0,get:function(){return tS.LeafLoadBalancer}});var $9=r0();Object.defineProperty(a,"subchannelAddressToString",{enumerable:!0,get:function(){return $9.subchannelAddressToString}});Object.defineProperty(a,"endpointToString",{enumerable:!0,get:function(){return $9.endpointToString}});Object.defineProperty(a,"endpointHasAddress",{enumerable:!0,get:function(){return $9.endpointHasAddress}});Object.defineProperty(a,"EndpointMap",{enumerable:!0,get:function(){return $9.EndpointMap}});var eS=n8();Object.defineProperty(a,"ChildLoadBalancerHandler",{enumerable:!0,get:function(){return eS.ChildLoadBalancerHandler}});var GJ=Y$();Object.defineProperty(a,"UnavailablePicker",{enumerable:!0,get:function(){return GJ.UnavailablePicker}});Object.defineProperty(a,"QueuePicker",{enumerable:!0,get:function(){return GJ.QueuePicker}});Object.defineProperty(a,"PickResultType",{enumerable:!0,get:function(){return GJ.PickResultType}});var mV=l$();Object.defineProperty(a,"statusOrFromValue",{enumerable:!0,get:function(){return mV.statusOrFromValue}});Object.defineProperty(a,"statusOrFromError",{enumerable:!0,get:function(){return mV.statusOrFromError}});var $C=P5();Object.defineProperty(a,"BaseFilter",{enumerable:!0,get:function(){return $C.BaseFilter}});var YC=xq();Object.defineProperty(a,"FilterStackFactory",{enumerable:!0,get:function(){return YC.FilterStackFactory}});var TC=r8();Object.defineProperty(a,"registerAdminService",{enumerable:!0,get:function(){return TC.registerAdminService}});var qC=KT();Object.defineProperty(a,"BaseSubchannelWrapper",{enumerable:!0,get:function(){return qC.BaseSubchannelWrapper}});var fV=nq();Object.defineProperty(a,"createServerCredentialsWithInterceptors",{enumerable:!0,get:function(){return fV.createServerCredentialsWithInterceptors}});Object.defineProperty(a,"createCertificateProviderServerCredentials",{enumerable:!0,get:function(){return fV.createCertificateProviderServerCredentials}});var XC=kV();Object.defineProperty(a,"FileWatcherCertificateProvider",{enumerable:!0,get:function(){return XC.FileWatcherCertificateProvider}});var JC=PY();Object.defineProperty(a,"createCertificateProviderChannelCredentials",{enumerable:!0,get:function(){return JC.createCertificateProviderChannelCredentials}});var QC=n5();Object.defineProperty(a,"SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX",{enumerable:!0,get:function(){return QC.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX}})});var dV=B((uV)=>{Object.defineProperty(uV,"__esModule",{value:!0});uV.setup=AC;var ZC=B1(),KC=l$();class bV{constructor($,Y,T){this.listener=Y,this.hasReturnedResult=!1,this.endpoints=[];let q;if($.authority==="")q="/"+$.path;else q=$.path;this.endpoints=[{addresses:[{path:q}]}]}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(this.listener,(0,KC.statusOrFromValue)(this.endpoints),{},null,"")}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return"localhost"}}function AC(){(0,ZC.registerResolver)("unix",bV)}});var aV=B((rV)=>{Object.defineProperty(rV,"__esModule",{value:!0});rV.setup=FC;var cV=s("net"),pV=l$(),Y9=i(),VJ=P0(),lV=B1(),GC=r0(),nV=p0(),EC=U0(),VC="ip_resolver";function iV($){EC.trace(Y9.LogVerbosity.DEBUG,VC,$)}var DJ="ipv4",FJ="ipv6",DC=443;class NJ{constructor($,Y,T){var q;this.listener=Y,this.endpoints=[],this.error=null,this.hasReturnedResult=!1,iV("Resolver constructed for target "+(0,nV.uriToString)($));let X=[];if(!($.scheme===DJ||$.scheme===FJ)){this.error={code:Y9.Status.UNAVAILABLE,details:`Unrecognized scheme ${$.scheme} in IP resolver`,metadata:new VJ.Metadata};return}let J=$.path.split(",");for(let Q of J){let U=(0,nV.splitHostPort)(Q);if(U===null){this.error={code:Y9.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new VJ.Metadata};return}if($.scheme===DJ&&!(0,cV.isIPv4)(U.host)||$.scheme===FJ&&!(0,cV.isIPv6)(U.host)){this.error={code:Y9.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new VJ.Metadata};return}X.push({host:U.host,port:(q=U.port)!==null&&q!==void 0?q:DC})}this.endpoints=X.map((Q)=>({addresses:[Q]})),iV("Parsed "+$.scheme+" address list "+X.map(GC.subchannelAddressToString))}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(()=>{if(this.error)this.listener((0,pV.statusOrFromError)(this.error),{},null,"");else this.listener((0,pV.statusOrFromValue)(this.endpoints),{},null,"")})}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return $.path.split(",")[0]}}function FC(){(0,lV.registerResolver)(DJ,NJ),(0,lV.registerResolver)(FJ,NJ)}});var T3=B(($3)=>{Object.defineProperty($3,"__esModule",{value:!0});$3.RoundRobinLoadBalancer=void 0;$3.setup=RC;var tV=M$(),k0=l0(),FT=Y$(),HC=U0(),zC=i(),oV=r0(),IC=VT(),MC="round_robin";function sV($){HC.trace(zC.LogVerbosity.DEBUG,MC,$)}var T9="round_robin";class q9{getLoadBalancerName(){return T9}constructor(){}toJsonObject(){return{[T9]:{}}}static createFromJson($){return new q9}}class eV{constructor($,Y=0){this.children=$,this.nextIndex=Y}pick($){let Y=this.children[this.nextIndex].picker;return this.nextIndex=(this.nextIndex+1)%this.children.length,Y.pick($)}peekNextEndpoint(){return this.children[this.nextIndex].endpoint}}function BC($,Y){return[...$.slice(Y),...$.slice(0,Y)]}class HJ{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=k0.ConnectivityState.IDLE,this.currentReadyPicker=null,this.updatesPaused=!1,this.lastError=null,this.childChannelControlHelper=(0,tV.createChildChannelControlHelper)($,{updateState:(Y,T,q)=>{if(this.currentState===k0.ConnectivityState.READY&&Y!==k0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(q)this.lastError=q;this.calculateAndUpdateState()}})}countChildrenWithState($){return this.children.filter((Y)=>Y.getConnectivityState()===$).length}calculateAndUpdateState(){if(this.updatesPaused)return;if(this.countChildrenWithState(k0.ConnectivityState.READY)>0){let $=this.children.filter((T)=>T.getConnectivityState()===k0.ConnectivityState.READY),Y=0;if(this.currentReadyPicker!==null){let T=this.currentReadyPicker.peekNextEndpoint();if(Y=$.findIndex((q)=>(0,oV.endpointEqual)(q.getEndpoint(),T)),Y<0)Y=0}this.updateState(k0.ConnectivityState.READY,new eV($.map((T)=>({endpoint:T.getEndpoint(),picker:T.getPicker()})),Y),null)}else if(this.countChildrenWithState(k0.ConnectivityState.CONNECTING)>0)this.updateState(k0.ConnectivityState.CONNECTING,new FT.QueuePicker(this),null);else if(this.countChildrenWithState(k0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new FT.UnavailablePicker({details:$}),$)}else this.updateState(k0.ConnectivityState.IDLE,new FT.QueuePicker(this),null);for(let $ of this.children)if($.getConnectivityState()===k0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,T){if(sV(k0.ConnectivityState[this.currentState]+" -> "+k0.ConnectivityState[$]),$===k0.ConnectivityState.READY)this.currentReadyPicker=Y;else this.currentReadyPicker=null;this.currentState=$,this.channelControlHelper.updateState($,Y,T)}resetSubchannelList(){for(let $ of this.children)$.destroy();this.children=[]}updateAddressList($,Y,T,q){if(!(Y instanceof q9))return!1;if(!$.ok){if(this.children.length===0)this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new FT.UnavailablePicker($.error),$.error.details);return!0}let X=Math.random()*$.value.length|0,J=BC($.value,X);if(this.resetSubchannelList(),J.length===0){let Q=`No addresses resolved. Resolution note: ${q}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new FT.UnavailablePicker({details:Q}),Q)}sV("Connect to endpoint list "+J.map(oV.endpointToString)),this.updatesPaused=!0,this.children=J.map((Q)=>new IC.LeafLoadBalancer(Q,this.childChannelControlHelper,T,q));for(let Q of this.children)Q.startConnecting();return this.updatesPaused=!1,this.calculateAndUpdateState(),!0}exitIdle(){}resetBackoff(){}destroy(){this.resetSubchannelList()}getTypeName(){return T9}}$3.RoundRobinLoadBalancer=HJ;function RC(){(0,tV.registerLoadBalancerType)(T9,HJ,q9)}});var A3=B((Z3)=>{var zJ;Object.defineProperty(Z3,"__esModule",{value:!0});Z3.OutlierDetectionLoadBalancer=Z3.OutlierDetectionLoadBalancingConfig=void 0;Z3.setup=hC;var PC=l0(),q3=i(),XY=WT(),X3=EJ(),LC=M$(),wC=n8(),SC=Y$(),IJ=r0(),CC=KT(),yC=U0(),jC="outlier_detection";function C0($){yC.trace(q3.LogVerbosity.DEBUG,jC,$)}var RJ="outlier_detection",vC=((zJ=process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION)!==null&&zJ!==void 0?zJ:"true")==="true",xC={stdev_factor:1900,enforcement_percentage:100,minimum_hosts:5,request_volume:100},kC={threshold:85,enforcement_percentage:100,minimum_hosts:5,request_volume:50};function tY($,Y,T,q){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==T){let X=q?`${q}.${Y}`:Y;throw Error(`outlier detection config ${X} parse error: expected ${T}, got ${typeof $[Y]}`)}}function MJ($,Y,T){let q=T?`${T}.${Y}`:Y;if(Y in $&&$[Y]!==void 0){if(!(0,XY.isDuration)($[Y]))throw Error(`outlier detection config ${q} parse error: expected Duration, got ${typeof $[Y]}`);if(!($[Y].seconds>=0&&$[Y].seconds<=315576000000&&$[Y].nanos>=0&&$[Y].nanos<=999999999))throw Error(`outlier detection config ${q} parse error: values out of range for non-negative Duaration`)}}function X9($,Y,T){let q=T?`${T}.${Y}`:Y;if(tY($,Y,"number",T),Y in $&&$[Y]!==void 0&&!($[Y]>=0&&$[Y]<=100))throw Error(`outlier detection config ${q} parse error: value out of range for percentage (0-100)`)}class NT{constructor($,Y,T,q,X,J,Q){if(this.childPolicy=Q,Q.getLoadBalancerName()==="pick_first")throw Error("outlier_detection LB policy cannot have a pick_first child policy");this.intervalMs=$!==null&&$!==void 0?$:1e4,this.baseEjectionTimeMs=Y!==null&&Y!==void 0?Y:30000,this.maxEjectionTimeMs=T!==null&&T!==void 0?T:300000,this.maxEjectionPercent=q!==null&&q!==void 0?q:10,this.successRateEjection=X?Object.assign(Object.assign({},xC),X):null,this.failurePercentageEjection=J?Object.assign(Object.assign({},kC),J):null}getLoadBalancerName(){return RJ}toJsonObject(){var $,Y;return{outlier_detection:{interval:(0,XY.msToDuration)(this.intervalMs),base_ejection_time:(0,XY.msToDuration)(this.baseEjectionTimeMs),max_ejection_time:(0,XY.msToDuration)(this.maxEjectionTimeMs),max_ejection_percent:this.maxEjectionPercent,success_rate_ejection:($=this.successRateEjection)!==null&&$!==void 0?$:void 0,failure_percentage_ejection:(Y=this.failurePercentageEjection)!==null&&Y!==void 0?Y:void 0,child_policy:[this.childPolicy.toJsonObject()]}}}getIntervalMs(){return this.intervalMs}getBaseEjectionTimeMs(){return this.baseEjectionTimeMs}getMaxEjectionTimeMs(){return this.maxEjectionTimeMs}getMaxEjectionPercent(){return this.maxEjectionPercent}getSuccessRateEjectionConfig(){return this.successRateEjection}getFailurePercentageEjectionConfig(){return this.failurePercentageEjection}getChildPolicy(){return this.childPolicy}static createFromJson($){var Y;if(MJ($,"interval"),MJ($,"base_ejection_time"),MJ($,"max_ejection_time"),X9($,"max_ejection_percent"),"success_rate_ejection"in $&&$.success_rate_ejection!==void 0){if(typeof $.success_rate_ejection!=="object")throw Error("outlier detection config success_rate_ejection must be an object");tY($.success_rate_ejection,"stdev_factor","number","success_rate_ejection"),X9($.success_rate_ejection,"enforcement_percentage","success_rate_ejection"),tY($.success_rate_ejection,"minimum_hosts","number","success_rate_ejection"),tY($.success_rate_ejection,"request_volume","number","success_rate_ejection")}if("failure_percentage_ejection"in $&&$.failure_percentage_ejection!==void 0){if(typeof $.failure_percentage_ejection!=="object")throw Error("outlier detection config failure_percentage_ejection must be an object");X9($.failure_percentage_ejection,"threshold","failure_percentage_ejection"),X9($.failure_percentage_ejection,"enforcement_percentage","failure_percentage_ejection"),tY($.failure_percentage_ejection,"minimum_hosts","number","failure_percentage_ejection"),tY($.failure_percentage_ejection,"request_volume","number","failure_percentage_ejection")}if(!("child_policy"in $)||!Array.isArray($.child_policy))throw Error("outlier detection config child_policy must be an array");let T=(0,LC.selectLbConfigFromList)($.child_policy);if(!T)throw Error("outlier detection config child_policy: no valid recognized policy found");return new NT($.interval?(0,XY.durationToMs)($.interval):null,$.base_ejection_time?(0,XY.durationToMs)($.base_ejection_time):null,$.max_ejection_time?(0,XY.durationToMs)($.max_ejection_time):null,(Y=$.max_ejection_percent)!==null&&Y!==void 0?Y:null,$.success_rate_ejection,$.failure_percentage_ejection,T)}}Z3.OutlierDetectionLoadBalancingConfig=NT;class J3 extends CC.BaseSubchannelWrapper{constructor($,Y){super($);this.mapEntry=Y,this.refCount=0}ref(){this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0){if(this.mapEntry){let $=this.mapEntry.subchannelWrappers.indexOf(this);if($>=0)this.mapEntry.subchannelWrappers.splice($,1)}}}eject(){this.setHealthy(!1)}uneject(){this.setHealthy(!0)}getMapEntry(){return this.mapEntry}getWrappedSubchannel(){return this.child}}function BJ(){return{success:0,failure:0}}class Q3{constructor(){this.activeBucket=BJ(),this.inactiveBucket=BJ()}addSuccess(){this.activeBucket.success+=1}addFailure(){this.activeBucket.failure+=1}switchBuckets(){this.inactiveBucket=this.activeBucket,this.activeBucket=BJ()}getLastSuccesses(){return this.inactiveBucket.success}getLastFailures(){return this.inactiveBucket.failure}}class U3{constructor($,Y){this.wrappedPicker=$,this.countCalls=Y}pick($){let Y=this.wrappedPicker.pick($);if(Y.pickResultType===SC.PickResultType.COMPLETE){let T=Y.subchannel,q=T.getMapEntry();if(q){let X=Y.onCallEnded;if(this.countCalls)X=(J,Q,U)=>{var Z;if(J===q3.Status.OK)q.counter.addSuccess();else q.counter.addFailure();(Z=Y.onCallEnded)===null||Z===void 0||Z.call(Y,J,Q,U)};return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel(),onCallEnded:X})}else return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel()})}else return Y}}class OJ{constructor($){this.entryMap=new IJ.EndpointMap,this.latestConfig=null,this.timerStartTime=null,this.childBalancer=new wC.ChildLoadBalancerHandler((0,X3.createChildChannelControlHelper)($,{createSubchannel:(Y,T)=>{let q=$.createSubchannel(Y,T),X=this.entryMap.getForSubchannelAddress(Y),J=new J3(q,X);if((X===null||X===void 0?void 0:X.currentEjectionTimestamp)!==null)J.eject();return X===null||X===void 0||X.subchannelWrappers.push(J),J},updateState:(Y,T,q)=>{if(Y===PC.ConnectivityState.READY)$.updateState(Y,new U3(T,this.isCountingEnabled()),q);else $.updateState(Y,T,q)}})),this.ejectionTimer=setInterval(()=>{},0),clearInterval(this.ejectionTimer)}isCountingEnabled(){return this.latestConfig!==null&&(this.latestConfig.getSuccessRateEjectionConfig()!==null||this.latestConfig.getFailurePercentageEjectionConfig()!==null)}getCurrentEjectionPercent(){let $=0;for(let Y of this.entryMap.values())if(Y.currentEjectionTimestamp!==null)$+=1;return $*100/this.entryMap.size}runSuccessRateCheck($){if(!this.latestConfig)return;let Y=this.latestConfig.getSuccessRateEjectionConfig();if(!Y)return;C0("Running success rate check");let T=Y.request_volume,q=0,X=[];for(let[A,W]of this.entryMap.entries()){let E=W.counter.getLastSuccesses(),V=W.counter.getLastFailures();if(C0("Stats for "+(0,IJ.endpointToString)(A)+": successes="+E+" failures="+V+" targetRequestVolume="+T),E+V>=T)q+=1,X.push(E/(E+V))}if(C0("Found "+q+" success rate candidates; currentEjectionPercent="+this.getCurrentEjectionPercent()+" successRates=["+X+"]"),q<Y.minimum_hosts)return;let J=X.reduce((A,W)=>A+W)/X.length,Q=0;for(let A of X){let W=A-J;Q+=W*W}let U=Q/X.length,Z=Math.sqrt(U),K=J-Z*(Y.stdev_factor/1000);C0("stdev="+Z+" ejectionThreshold="+K);for(let[A,W]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let E=W.counter.getLastSuccesses(),V=W.counter.getLastFailures();if(E+V<T)continue;let F=E/(E+V);if(C0("Checking candidate "+A+" successRate="+F),F<K){let H=Math.random()*100;if(C0("Candidate "+A+" randomNumber="+H+" enforcement_percentage="+Y.enforcement_percentage),H<Y.enforcement_percentage)C0("Ejecting candidate "+A),this.eject(W,$)}}}runFailurePercentageCheck($){if(!this.latestConfig)return;let Y=this.latestConfig.getFailurePercentageEjectionConfig();if(!Y)return;C0("Running failure percentage check. threshold="+Y.threshold+" request volume threshold="+Y.request_volume);let T=0;for(let q of this.entryMap.values()){let X=q.counter.getLastSuccesses(),J=q.counter.getLastFailures();if(X+J>=Y.request_volume)T+=1}if(T<Y.minimum_hosts)return;for(let[q,X]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let J=X.counter.getLastSuccesses(),Q=X.counter.getLastFailures();if(C0("Candidate successes="+J+" failures="+Q),J+Q<Y.request_volume)continue;if(Q*100/(Q+J)>Y.threshold){let Z=Math.random()*100;if(C0("Candidate "+q+" randomNumber="+Z+" enforcement_percentage="+Y.enforcement_percentage),Z<Y.enforcement_percentage)C0("Ejecting candidate "+q),this.eject(X,$)}}}eject($,Y){$.currentEjectionTimestamp=new Date,$.ejectionTimeMultiplier+=1;for(let T of $.subchannelWrappers)T.eject()}uneject($){$.currentEjectionTimestamp=null;for(let Y of $.subchannelWrappers)Y.uneject()}switchAllBuckets(){for(let $ of this.entryMap.values())$.counter.switchBuckets()}startTimer($){var Y,T;this.ejectionTimer=setTimeout(()=>this.runChecks(),$),(T=(Y=this.ejectionTimer).unref)===null||T===void 0||T.call(Y)}runChecks(){let $=new Date;if(C0("Ejection timer running"),this.switchAllBuckets(),!this.latestConfig)return;this.timerStartTime=$,this.startTimer(this.latestConfig.getIntervalMs()),this.runSuccessRateCheck($),this.runFailurePercentageCheck($);for(let[Y,T]of this.entryMap.entries())if(T.currentEjectionTimestamp===null){if(T.ejectionTimeMultiplier>0)T.ejectionTimeMultiplier-=1}else{let q=this.latestConfig.getBaseEjectionTimeMs(),X=this.latestConfig.getMaxEjectionTimeMs(),J=new Date(T.currentEjectionTimestamp.getTime());if(J.setMilliseconds(J.getMilliseconds()+Math.min(q*T.ejectionTimeMultiplier,Math.max(q,X))),J<new Date)C0("Unejecting "+Y),this.uneject(T)}}updateAddressList($,Y,T,q){if(!(Y instanceof NT))return!1;if(C0("Received update with config: "+JSON.stringify(Y.toJsonObject(),void 0,2)),$.ok){for(let J of $.value)if(!this.entryMap.has(J))C0("Adding map entry for "+(0,IJ.endpointToString)(J)),this.entryMap.set(J,{counter:new Q3,currentEjectionTimestamp:null,ejectionTimeMultiplier:0,subchannelWrappers:[]});this.entryMap.deleteMissing($.value)}let X=Y.getChildPolicy();if(this.childBalancer.updateAddressList($,X,T,q),Y.getSuccessRateEjectionConfig()||Y.getFailurePercentageEjectionConfig())if(this.timerStartTime){C0("Previous timer existed. Replacing timer"),clearTimeout(this.ejectionTimer);let J=Y.getIntervalMs()-(new Date().getTime()-this.timerStartTime.getTime());this.startTimer(J)}else C0("Starting new timer"),this.timerStartTime=new Date,this.startTimer(Y.getIntervalMs()),this.switchAllBuckets();else{C0("Counting disabled. Cancelling timer."),this.timerStartTime=null,clearTimeout(this.ejectionTimer);for(let J of this.entryMap.values())this.uneject(J),J.ejectionTimeMultiplier=0}return this.latestConfig=Y,!0}exitIdle(){this.childBalancer.exitIdle()}resetBackoff(){this.childBalancer.resetBackoff()}destroy(){clearTimeout(this.ejectionTimer),this.childBalancer.destroy()}getTypeName(){return RJ}}Z3.OutlierDetectionLoadBalancer=OJ;function hC(){if(vC)(0,X3.registerLoadBalancerType)(RJ,OJ,NT)}});var V3=B((G3)=>{Object.defineProperty(G3,"__esModule",{value:!0});G3.PriorityQueue=void 0;var eY=0,PJ=($)=>Math.floor($/2),J9=($)=>$*2+1,HT=($)=>$*2+2;class W3{constructor($=(Y,T)=>Y>T){this.comparator=$,this.heap=[]}size(){return this.heap.length}isEmpty(){return this.size()==0}peek(){return this.heap[eY]}push(...$){return $.forEach((Y)=>{this.heap.push(Y),this.siftUp()}),this.size()}pop(){let $=this.peek(),Y=this.size()-1;if(Y>eY)this.swap(eY,Y);return this.heap.pop(),this.siftDown(),$}replace($){let Y=this.peek();return this.heap[eY]=$,this.siftDown(),Y}greater($,Y){return this.comparator(this.heap[$],this.heap[Y])}swap($,Y){[this.heap[$],this.heap[Y]]=[this.heap[Y],this.heap[$]]}siftUp(){let $=this.size()-1;while($>eY&&this.greater($,PJ($)))this.swap($,PJ($)),$=PJ($)}siftDown(){let $=eY;while(J9($)<this.size()&&this.greater(J9($),$)||HT($)<this.size()&&this.greater(HT($),$)){let Y=HT($)<this.size()&&this.greater(HT($),J9($))?HT($):J9($);this.swap($,Y),$=Y}}}G3.PriorityQueue=W3});var R3=B((M3)=>{Object.defineProperty(M3,"__esModule",{value:!0});M3.WeightedRoundRobinLoadBalancingConfig=void 0;M3.setup=rC;var y0=l0(),mC=i(),J1=WT(),N3=M$(),fC=VT(),bC=U0(),H3=rq(),$6=Y$(),uC=V3(),D3=r0(),dC="weighted_round_robin";function LJ($){bC.trace(mC.LogVerbosity.DEBUG,dC,$)}var wJ="weighted_round_robin",cC=1e4,pC=1e4,lC=180000,nC=1000,iC=1;function F3($,Y,T){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==T)throw Error(`weighted round robin config ${Y} parse error: expected ${T}, got ${typeof $[Y]}`)}function Q9($,Y){if(Y in $&&$[Y]!==void 0&&$[Y]!==null){let T;if((0,J1.isDuration)($[Y]))T=$[Y];else if((0,J1.isDurationMessage)($[Y]))T=(0,J1.durationMessageToDuration)($[Y]);else if(typeof $[Y]==="string"){let q=(0,J1.parseDuration)($[Y]);if(!q)throw Error(`weighted round robin config ${Y}: failed to parse duration string ${$[Y]}`);T=q}else throw Error(`weighted round robin config ${Y}: expected duration, got ${typeof $[Y]}`);return(0,J1.durationToMs)(T)}return null}class zT{constructor($,Y,T,q,X,J){this.enableOobLoadReport=$!==null&&$!==void 0?$:!1,this.oobLoadReportingPeriodMs=Y!==null&&Y!==void 0?Y:cC,this.blackoutPeriodMs=T!==null&&T!==void 0?T:pC,this.weightExpirationPeriodMs=q!==null&&q!==void 0?q:lC,this.weightUpdatePeriodMs=Math.max(X!==null&&X!==void 0?X:nC,100),this.errorUtilizationPenalty=J!==null&&J!==void 0?J:iC}getLoadBalancerName(){return wJ}toJsonObject(){return{enable_oob_load_report:this.enableOobLoadReport,oob_load_reporting_period:(0,J1.durationToString)((0,J1.msToDuration)(this.oobLoadReportingPeriodMs)),blackout_period:(0,J1.durationToString)((0,J1.msToDuration)(this.blackoutPeriodMs)),weight_expiration_period:(0,J1.durationToString)((0,J1.msToDuration)(this.weightExpirationPeriodMs)),weight_update_period:(0,J1.durationToString)((0,J1.msToDuration)(this.weightUpdatePeriodMs)),error_utilization_penalty:this.errorUtilizationPenalty}}static createFromJson($){if(F3($,"enable_oob_load_report","boolean"),F3($,"error_utilization_penalty","number"),$.error_utilization_penalty<0)throw Error("weighted round robin config error_utilization_penalty < 0");return new zT($.enable_oob_load_report,Q9($,"oob_load_reporting_period"),Q9($,"blackout_period"),Q9($,"weight_expiration_period"),Q9($,"weight_update_period"),$.error_utilization_penalty)}getEnableOobLoadReport(){return this.enableOobLoadReport}getOobLoadReportingPeriodMs(){return this.oobLoadReportingPeriodMs}getBlackoutPeriodMs(){return this.blackoutPeriodMs}getWeightExpirationPeriodMs(){return this.weightExpirationPeriodMs}getWeightUpdatePeriodMs(){return this.weightUpdatePeriodMs}getErrorUtilizationPenalty(){return this.errorUtilizationPenalty}}M3.WeightedRoundRobinLoadBalancingConfig=zT;class z3{constructor($,Y){this.metricsHandler=Y,this.queue=new uC.PriorityQueue((X,J)=>X.deadline<J.deadline);let T=$.filter((X)=>X.weight>0),q;if(T.length<2)q=1;else{let X=0;for(let{weight:J}of T)X+=J;q=X/T.length}for(let X of $){let J=X.weight>0?1/X.weight:q;this.queue.push({endpointName:X.endpointName,picker:X.picker,period:J,deadline:Math.random()*J})}}pick($){let Y=this.queue.pop();this.queue.push(Object.assign(Object.assign({},Y),{deadline:Y.deadline+Y.period}));let T=Y.picker.pick($);if(T.pickResultType===$6.PickResultType.COMPLETE)if(this.metricsHandler)return Object.assign(Object.assign({},T),{onCallEnded:(0,H3.createMetricsReader)((q)=>this.metricsHandler(q,Y.endpointName),T.onCallEnded)});else{let q=T.subchannel;return Object.assign(Object.assign({},T),{subchannel:q.getWrappedSubchannel()})}else return T}}class I3{constructor($){this.channelControlHelper=$,this.latestConfig=null,this.children=new Map,this.currentState=y0.ConnectivityState.IDLE,this.updatesPaused=!1,this.lastError=null,this.weightUpdateTimer=null}countChildrenWithState($){let Y=0;for(let T of this.children.values())if(T.child.getConnectivityState()===$)Y+=1;return Y}updateWeight($,Y){var T,q;let{rps_fractional:X,application_utilization:J}=Y;if(J>0&&X>0)J+=Y.eps/X*((q=(T=this.latestConfig)===null||T===void 0?void 0:T.getErrorUtilizationPenalty())!==null&&q!==void 0?q:0);let Q=J===0?0:X/J;if(Q===0)return;let U=new Date;if($.nonEmptySince===null)$.nonEmptySince=U;$.lastUpdated=U,$.weight=Q}getWeight($){if(!this.latestConfig)return 0;let Y=new Date().getTime();if(Y-$.lastUpdated.getTime()>=this.latestConfig.getWeightExpirationPeriodMs())return $.nonEmptySince=null,0;let T=this.latestConfig.getBlackoutPeriodMs();if(T>0&&($.nonEmptySince===null||Y-$.nonEmptySince.getTime()<T))return 0;return $.weight}calculateAndUpdateState(){if(this.updatesPaused||!this.latestConfig)return;if(this.countChildrenWithState(y0.ConnectivityState.READY)>0){let $=[];for(let[T,q]of this.children){if(q.child.getConnectivityState()!==y0.ConnectivityState.READY)continue;$.push({endpointName:T,picker:q.child.getPicker(),weight:this.getWeight(q)})}LJ("Created picker with weights: "+$.map((T)=>T.endpointName+":"+T.weight).join(","));let Y;if(!this.latestConfig.getEnableOobLoadReport())Y=(T,q)=>{let X=this.children.get(q);if(X)this.updateWeight(X,T)};else Y=null;this.updateState(y0.ConnectivityState.READY,new z3($,Y),null)}else if(this.countChildrenWithState(y0.ConnectivityState.CONNECTING)>0)this.updateState(y0.ConnectivityState.CONNECTING,new $6.QueuePicker(this),null);else if(this.countChildrenWithState(y0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`weighted_round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $6.UnavailablePicker({details:$}),$)}else this.updateState(y0.ConnectivityState.IDLE,new $6.QueuePicker(this),null);for(let{child:$}of this.children.values())if($.getConnectivityState()===y0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,T){LJ(y0.ConnectivityState[this.currentState]+" -> "+y0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,T)}updateAddressList($,Y,T,q){var X,J;if(!(Y instanceof zT))return!1;if(!$.ok){if(this.children.size===0)this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $6.UnavailablePicker($.error),$.error.details);return!0}if($.value.length===0){let Z=`No addresses resolved. Resolution note: ${q}`;return this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $6.UnavailablePicker({details:Z}),Z),!1}LJ("Connect to endpoint list "+$.value.map(D3.endpointToString));let Q=new Date,U=new Set;this.updatesPaused=!0,this.latestConfig=Y;for(let Z of $.value){let K=(0,D3.endpointToString)(Z);U.add(K);let A=this.children.get(K);if(!A)A={child:new fC.LeafLoadBalancer(Z,(0,N3.createChildChannelControlHelper)(this.channelControlHelper,{updateState:(W,E,V)=>{if(this.currentState===y0.ConnectivityState.READY&&W!==y0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(W===y0.ConnectivityState.READY)A.nonEmptySince=null;if(V)this.lastError=V;this.calculateAndUpdateState()},createSubchannel:(W,E)=>{let V=this.channelControlHelper.createSubchannel(W,E);if(A===null||A===void 0?void 0:A.oobMetricsListener)return new H3.OrcaOobMetricsSubchannelWrapper(V,A.oobMetricsListener,this.latestConfig.getOobLoadReportingPeriodMs());else return V}}),T,q),lastUpdated:Q,nonEmptySince:null,weight:0,oobMetricsListener:null},this.children.set(K,A);if(Y.getEnableOobLoadReport())A.oobMetricsListener=(W)=>{this.updateWeight(A,W)};else A.oobMetricsListener=null}for(let[Z,K]of this.children)if(U.has(Z))K.child.startConnecting();else K.child.destroy(),this.children.delete(Z);if(this.updatesPaused=!1,this.calculateAndUpdateState(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer);return this.weightUpdateTimer=(J=(X=setInterval(()=>{if(this.currentState===y0.ConnectivityState.READY)this.calculateAndUpdateState()},Y.getWeightUpdatePeriodMs())).unref)===null||J===void 0?void 0:J.call(X),!0}exitIdle(){}resetBackoff(){}destroy(){for(let $ of this.children.values())$.child.destroy();if(this.children.clear(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer)}getTypeName(){return wJ}}function rC(){(0,N3.registerLoadBalancerType)(wJ,I3,zT)}});var IT=B((T0)=>{Object.defineProperty(T0,"__esModule",{value:!0});T0.experimental=T0.ServerMetricRecorder=T0.ServerInterceptingCall=T0.ResponderBuilder=T0.ServerListenerBuilder=T0.addAdminServicesToServer=T0.getChannelzHandlers=T0.getChannelzServiceDefinition=T0.InterceptorConfigurationError=T0.InterceptingCall=T0.RequesterBuilder=T0.ListenerBuilder=T0.StatusBuilder=T0.getClientChannel=T0.ServerCredentials=T0.Server=T0.setLogVerbosity=T0.setLogger=T0.load=T0.loadObject=T0.CallCredentials=T0.ChannelCredentials=T0.waitForClientReady=T0.closeClient=T0.Channel=T0.makeGenericClientConstructor=T0.makeClientConstructor=T0.loadPackageDefinition=T0.Client=T0.compressionAlgorithms=T0.propagate=T0.connectivityState=T0.status=T0.logVerbosity=T0.Metadata=T0.credentials=void 0;var U9=m8();Object.defineProperty(T0,"CallCredentials",{enumerable:!0,get:function(){return U9.CallCredentials}});var oC=WX();Object.defineProperty(T0,"Channel",{enumerable:!0,get:function(){return oC.ChannelImplementation}});var sC=O5();Object.defineProperty(T0,"compressionAlgorithms",{enumerable:!0,get:function(){return sC.CompressionAlgorithms}});var tC=l0();Object.defineProperty(T0,"connectivityState",{enumerable:!0,get:function(){return tC.ConnectivityState}});var Z9=PY();Object.defineProperty(T0,"ChannelCredentials",{enumerable:!0,get:function(){return Z9.ChannelCredentials}});var O3=AX();Object.defineProperty(T0,"Client",{enumerable:!0,get:function(){return O3.Client}});var SJ=i();Object.defineProperty(T0,"logVerbosity",{enumerable:!0,get:function(){return SJ.LogVerbosity}});Object.defineProperty(T0,"status",{enumerable:!0,get:function(){return SJ.Status}});Object.defineProperty(T0,"propagate",{enumerable:!0,get:function(){return SJ.Propagate}});var P3=U0(),CJ=o8();Object.defineProperty(T0,"loadPackageDefinition",{enumerable:!0,get:function(){return CJ.loadPackageDefinition}});Object.defineProperty(T0,"makeClientConstructor",{enumerable:!0,get:function(){return CJ.makeClientConstructor}});Object.defineProperty(T0,"makeGenericClientConstructor",{enumerable:!0,get:function(){return CJ.makeClientConstructor}});var eC=P0();Object.defineProperty(T0,"Metadata",{enumerable:!0,get:function(){return eC.Metadata}});var $y=NV();Object.defineProperty(T0,"Server",{enumerable:!0,get:function(){return $y.Server}});var Yy=nq();Object.defineProperty(T0,"ServerCredentials",{enumerable:!0,get:function(){return Yy.ServerCredentials}});var Ty=MV();Object.defineProperty(T0,"StatusBuilder",{enumerable:!0,get:function(){return Ty.StatusBuilder}});T0.credentials={combineChannelCredentials:($,...Y)=>{return Y.reduce((T,q)=>T.compose(q),$)},combineCallCredentials:($,...Y)=>{return Y.reduce((T,q)=>T.compose(q),$)},createInsecure:Z9.ChannelCredentials.createInsecure,createSsl:Z9.ChannelCredentials.createSsl,createFromSecureContext:Z9.ChannelCredentials.createFromSecureContext,createFromMetadataGenerator:U9.CallCredentials.createFromMetadataGenerator,createFromGoogleCredential:U9.CallCredentials.createFromGoogleCredential,createEmpty:U9.CallCredentials.createEmpty};var qy=($)=>$.close();T0.closeClient=qy;var Xy=($,Y,T)=>$.waitForReady(Y,T);T0.waitForClientReady=Xy;var Jy=($,Y)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};T0.loadObject=Jy;var Qy=($,Y,T)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};T0.load=Qy;var Uy=($)=>{P3.setLogger($)};T0.setLogger=Uy;var Zy=($)=>{P3.setLoggerVerbosity($)};T0.setLogVerbosity=Zy;var Ky=($)=>{return O3.Client.prototype.getChannel.call($)};T0.getClientChannel=Ky;var K9=ZX();Object.defineProperty(T0,"ListenerBuilder",{enumerable:!0,get:function(){return K9.ListenerBuilder}});Object.defineProperty(T0,"RequesterBuilder",{enumerable:!0,get:function(){return K9.RequesterBuilder}});Object.defineProperty(T0,"InterceptingCall",{enumerable:!0,get:function(){return K9.InterceptingCall}});Object.defineProperty(T0,"InterceptorConfigurationError",{enumerable:!0,get:function(){return K9.InterceptorConfigurationError}});var L3=y$();Object.defineProperty(T0,"getChannelzServiceDefinition",{enumerable:!0,get:function(){return L3.getChannelzServiceDefinition}});Object.defineProperty(T0,"getChannelzHandlers",{enumerable:!0,get:function(){return L3.getChannelzHandlers}});var Ay=r8();Object.defineProperty(T0,"addAdminServicesToServer",{enumerable:!0,get:function(){return Ay.addAdminServicesToServer}});var yJ=JJ();Object.defineProperty(T0,"ServerListenerBuilder",{enumerable:!0,get:function(){return yJ.ServerListenerBuilder}});Object.defineProperty(T0,"ResponderBuilder",{enumerable:!0,get:function(){return yJ.ResponderBuilder}});Object.defineProperty(T0,"ServerInterceptingCall",{enumerable:!0,get:function(){return yJ.ServerInterceptingCall}});var Wy=rq();Object.defineProperty(T0,"ServerMetricRecorder",{enumerable:!0,get:function(){return Wy.ServerMetricRecorder}});var Gy=EJ();T0.experimental=Gy;var Ey=h5(),Vy=dV(),Dy=aV(),Fy=VT(),Ny=T3(),Hy=A3(),zy=R3(),Iy=y$();(()=>{Ey.setup(),Vy.setup(),Dy.setup(),Fy.setup(),Ny.setup(),Hy.setup(),zy.setup(),Iy.setup()})()});import{existsSync as pJ,mkdirSync as lJ}from"node:fs";import{dirname as nJ,join as J0}from"node:path";var ST="agents",U6="hooks",H1="skills",Z6="rules",K6="workflows",H9="plugins",iJ="cline_mcp_settings.json",W$=process?.env?.HOME||"~",rJ=!1;function aJ($){let Y=$.trim();if(!Y)return;W$=Y,rJ=!0}function CT($){if(rJ)return;let Y=$.trim();if(!Y)return;W$=Y}function A6(){return J0(W$,"Documents","Cline")}function yT(){return J0(A6(),"Agents")}function W6(){return J0(A6(),"Hooks")}function G6(){return J0(A6(),"Rules")}function E6(){return J0(A6(),"Workflows")}function t0(){let $=process.env.CLINE_DATA_DIR?.trim();if($)return $;return J0(W$,".cline","data")}function G$(){let $=process.env.CLINE_SESSION_DATA_DIR?.trim();if($)return $;return J0(t0(),"sessions")}function jT(){let $=process.env.CLINE_TEAM_DATA_DIR?.trim();if($)return $;return J0(t0(),"teams")}function z9(){let $=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if($)return $;return J0(t0(),"settings","providers.json")}function I9(){let $=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if($)return $;return J0(t0(),"settings",iJ)}function V6($){let Y=new Set,T=[];for(let q of $){if(!q||Y.has(q))continue;Y.add(q),T.push(q)}return T}function VD($){if(!$)return[];return[J0($,".clinerules",H1),J0($,".cline",H1),J0($,".claude",H1),J0($,".agents",H1)]}function M9(){return J0(t0(),"settings",ST)}function B9(){return[yT(),M9()]}function R9($){return V6([$?J0($,".clinerules",U6):"",W6()])}function D6($){return V6([...VD($),J0(t0(),"settings",H1),J0(W$,".cline",H1),J0(W$,".agents",H1)])}function O9($){return V6([$?J0($,".clinerules"):"",J0(t0(),"settings",Z6),G6()])}function P9($){return V6([$?J0($,".clinerules","workflows"):"",J0(t0(),"settings",K6),E6()])}function L9($){return V6([$?J0($,".clinerules",H9):"",J0(W$,".cline",H9),J0(W$,".agents",H9)])}function F6($){let Y=nJ($);if(!pJ(Y))lJ(Y,{recursive:!0})}function oJ($){if($?.trim())return F6($),nJ($);let Y=J0(t0(),"hooks");if(!pJ(Y))lJ(Y,{recursive:!0});return Y}import UF from"yaml";import{z as A1}from"zod";import{z as E$}from"zod";var sJ=E$.enum(["connector.started","connector.stopping","message.received","message.completed","message.failed","session.started","session.reused","thread.reset","schedule.delivery.started","schedule.delivery.sent","schedule.delivery.failed"]),DD=E$.object({adapter:E$.string(),botUserName:E$.string().optional(),event:sJ,payload:E$.record(E$.string(),E$.unknown()),ts:E$.string()});var tJ=[{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-native"},{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-codex"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic",runtimeProviderId:"claude-code"},{modelsDevKey:"google",generatedProviderId:"gemini"},{modelsDevKey:"deepseek",generatedProviderId:"deepseek"},{modelsDevKey:"xai",generatedProviderId:"xai"},{modelsDevKey:"togetherai",runtimeProviderId:"together",generatedProviderId:"together"},{modelsDevKey:"sap-ai-core",runtimeProviderId:"sapaicore",generatedProviderId:"sapaicore"},{modelsDevKey:"fireworks-ai",runtimeProviderId:"fireworks",generatedProviderId:"fireworks"},{modelsDevKey:"groq",runtimeProviderId:"groq",generatedProviderId:"groq"},{modelsDevKey:"cerebras",runtimeProviderId:"cerebras",generatedProviderId:"cerebras"},{modelsDevKey:"sambanova",runtimeProviderId:"sambanova",generatedProviderId:"sambanova"},{modelsDevKey:"nebius",runtimeProviderId:"nebius",generatedProviderId:"nebius"},{modelsDevKey:"huggingface",runtimeProviderId:"huggingface",generatedProviderId:"huggingface"},{modelsDevKey:"openrouter",runtimeProviderId:"cline",generatedProviderId:"openrouter"},{modelsDevKey:"ollama",runtimeProviderId:"ollama-cloud"},{modelsDevKey:"ollama-cloud",generatedProviderId:"ollama"},{modelsDevKey:"vercel",runtimeProviderId:"dify",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"vercel",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"aihubmix",runtimeProviderId:"aihubmix",generatedProviderId:"aihubmix"},{modelsDevKey:"hicap",runtimeProviderId:"hicap"},{modelsDevKey:"nous-research",runtimeProviderId:"nousResearch"},{modelsDevKey:"huawei-cloud-maas",runtimeProviderId:"huawei-cloud-maas"},{modelsDevKey:"baseten",runtimeProviderId:"baseten",generatedProviderId:"baseten"},{modelsDevKey:"google-vertex-anthropic",generatedProviderId:"vertex"},{modelsDevKey:"lmstudio",generatedProviderId:"lmstudio"},{modelsDevKey:"zai",generatedProviderId:"zai"},{modelsDevKey:"requesty",generatedProviderId:"requesty"},{modelsDevKey:"amazon-bedrock",generatedProviderId:"bedrock"},{modelsDevKey:"moonshotai",generatedProviderId:"moonshot"},{modelsDevKey:"minimax",generatedProviderId:"minimax"}];function FD($){return Object.fromEntries(tJ.flatMap((Y)=>{let T=$==="modelsDevKey"?Y.modelsDevKey:Y.generatedProviderId;return T?[[Y.modelsDevKey,T]]:[]}))}var ND=FD("generatedProviderId");import{z as v0}from"zod";var HD=v0.object({agentId:v0.string(),conversationId:v0.string(),iteration:v0.number(),abortSignal:v0.custom().optional(),metadata:v0.record(v0.string(),v0.unknown()).optional()}),zD=v0.object({id:v0.string(),name:v0.string(),input:v0.unknown(),output:v0.unknown(),error:v0.string().optional(),durationMs:v0.number(),startedAt:v0.date(),endedAt:v0.date()});import{z as eJ}from"zod";function z1($,Y){let T=$.safeParse(Y);if(!T.success)throw Error(eJ.prettifyError(T.error));return T.data}function I1($){return eJ.toJSONSchema($)}function vT($,Y="act"){return`<user_input mode="${Y}">${$}</user_input>`}function xT($){if(!$?.trim())return"";return $Q($,"user_input")}function $Q($,Y){if(!$?.trim())return"";if(!Y)return $;let T=new RegExp(`<${Y}.*?>(.*?)</${Y}>`,"g");return $.replace(T,"$1")}var kT="runtime.team.progress.v1",hT="runtime.team.lifecycle.v1";function YQ($){let Y=$?.trim();return Y?Y:void 0}function _T($){return YQ($?.rootSessionId)}function TQ($){return YQ($?.hookLogPath)}var w9=["running","completed","failed","cancelled"];var v1={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question"},_$=[v1.READ_FILES,v1.SEARCH_CODEBASE,v1.RUN_COMMANDS,v1.FETCH_WEB_CONTENT,v1.APPLY_PATCH,v1.EDITOR,v1.SKILLS,v1.ASK];import{createTool as V$}from"@clinebot/agents";import{z as r}from"zod";var ID=r.string().describe("The absolute file path of a text file to read content from"),gT=r.object({file_paths:r.array(ID).describe("Array of absolute file paths to get full content from. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),qQ=r.union([gT,r.array(r.string()),r.string()]),mT=r.object({queries:r.array(r.string()).describe("Array of regex search queries to execute")}),S9=r.string(),fT=r.object({commands:r.array(S9).describe("Array of shell commands to execute.")}),XQ=r.union([fT,r.array(S9),S9]),JQ=r.object({url:r.string().describe("The URL to fetch"),prompt:r.string().min(2).describe("Analysis prompt for the fetched content")}),bT=r.object({requests:r.array(JQ).describe("Array of the URLs for the web fetch requests")}),uT=r.object({command:r.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert"),path:r.string().min(1).describe("Absolute file path"),file_text:r.string().nullish().describe("Full file content required for 'create' command"),old_str:r.string().nullish().describe("Exact text to replace (must match exactly once) for 'str_replace' command"),new_str:r.string().nullish().describe("Replacement text for 'str_replace' or 'insert' commands"),insert_line:r.number().int().nullish().describe("Optional one-based line index for 'insert' command")}).refine(($)=>$.command!=="create"||$.file_text!=null,{path:["file_text"],message:"file_text is required for command=create"}).refine(($)=>$.command!=="str_replace"||$.old_str!=null,{path:["old_str"],message:"old_str is required for command=str_replace"}).refine(($)=>$.command!=="insert"||$.insert_line!=null,{path:["insert_line"],message:"insert_line is required for command=insert"}).refine(($)=>$.command!=="insert"||$.new_str!=null,{path:["new_str"],message:"new_str is required for command=insert"}),dT=r.object({input:r.string().min(1).describe("The apply_patch text payload, including patch instructions")}),QQ=r.union([dT,r.string()]),cT=r.object({skill:r.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:r.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),pT=r.object({question:r.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:r.array(r.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function KY($){if($ instanceof Error)return $.message;return String($)}function D$($,Y,T){return Promise.race([$,new Promise((q,X)=>{setTimeout(()=>X(Error(T)),Y)})])}var MD=`This is a custom utility that makes it more convenient to add, remove, move, or edit code in a single file. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` command, you should pass a message of the following structure as "input":
|
|
22
22
|
|
|
23
23
|
%%bash
|
|
24
24
|
apply_patch <<"EOF"
|
|
@@ -73,46 +73,46 @@ apply_patch <<"EOF"
|
|
|
73
73
|
+ raise NotImplementedError()
|
|
74
74
|
|
|
75
75
|
*** End Patch
|
|
76
|
-
EOF`;function
|
|
76
|
+
EOF`;function UQ($,Y={}){let T=Y.fileReadTimeoutMs??1e4;return V$({name:"read_files",description:"Read the FULL content of text file at the provided absolute paths. Returns file contents or error messages for each path. ",inputSchema:I1(gT),timeoutMs:T*2,retryable:!0,maxRetries:1,execute:async(q,X)=>{let J=z1(qQ,q),Q=Array.isArray(J)?J:typeof J==="object"?J.file_paths:[J];return Promise.all(Q.map(async(U)=>{try{let Z=await D$($(U,X),T,`File read timed out after ${T}ms`);return{query:U,result:Z,success:!0}}catch(Z){let K=KY(Z);return{query:U,result:"",error:`Error reading file: ${K}`,success:!1}}}))}})}function ZQ($,Y={}){let T=Y.searchTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:I1(mT),timeoutMs:T*2,retryable:!0,maxRetries:1,execute:async(X,J)=>{let Q=z1(mT,X);return Promise.all(Q.queries.map(async(U)=>{try{let Z=await D$($(U,q,J),T,`Search timed out after ${T}ms`),K=Z.length>0&&!Z.includes("No results found");return{query:U,result:Z,success:K}}catch(Z){let K=KY(Z);return{query:U,result:"",error:`Search failed: ${K}`,success:!1}}}))}})}function KQ($,Y={}){let T=Y.bashTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({name:"run_commands",description:"Run shell commands at the root of the project. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:I1(fT),timeoutMs:T*2,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=z1(XQ,X),U=Array.isArray(Q)?Q:typeof Q==="object"?Q.commands:[Q];return Promise.all(U.map(async(Z)=>{try{let K=await D$($(Z,q,J),T,`Command timed out after ${T}ms`);return{query:Z,result:K,success:!0}}catch(K){let A=KY(K);return{query:Z,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function AQ($,Y={}){let T=Y.webFetchTimeoutMs??30000;return V$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:I1(bT),timeoutMs:T*2,retryable:!0,maxRetries:2,execute:async(q,X)=>{let J=z1(bT,q);return Promise.all(J.requests.map(async(Q)=>{try{let U=await D$($(Q.url,Q.prompt,X),T,`Web fetch timed out after ${T}ms`);return{query:Q.url,result:U,success:!0}}catch(U){let Z=KY(U);return{query:Q.url,result:"",error:`Error fetching web content: ${Z}`,success:!1}}}))}})}function WQ($,Y={}){let T=Y.applyPatchTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({name:"apply_patch",description:MD,inputSchema:I1(dT),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=z1(QQ,X),U=typeof Q==="string"?Q:Q.input;try{return{query:"apply_patch",result:await D$($({input:U},q,J),T,`apply_patch timed out after ${T}ms`),success:!0}}catch(Z){return{query:"apply_patch",result:"",error:`apply_patch failed: ${KY(Z)}`,success:!1}}}})}function GQ($,Y={}){let T=Y.editorTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert.",inputSchema:I1(uT),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=z1(uT,X);try{let U=await D$($(Q,q,J),T,`Editor operation timed out after ${T}ms`);return{query:`${Q.command}:${Q.path}`,result:U,success:!0}}catch(U){let Z=KY(U);return{query:`${Q.command}:${Q.path}`,result:"",error:`Editor operation failed: ${Z}`,success:!1}}}})}function EQ($,Y={}){let T=Y.skillsTimeoutMs??15000;return V$({name:"skills",description:'Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command (for example "/commit" or "/review-pr"), invoke this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. Available skills are listed in system-reminder messages in the conversation. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',inputSchema:I1(cT),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(q,X)=>{let J=z1(cT,q);return D$($(J.skill,J.args||void 0,X),T,`Skills operation timed out after ${T}ms`)}})}function VQ($,Y={}){let T=Y.askQuestionTimeoutMs??15000;return V$({name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:I1(pT),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(q,X)=>{let J=z1(pT,q);return D$($(J.question,J.options,X),T,`ask_question timed out after ${T}ms`)}})}function AY($){let{executors:Y,enableReadFiles:T=!0,enableSearch:q=!0,enableBash:X=!0,enableWebFetch:J=!0,enableApplyPatch:Q=!1,enableEditor:U=!0,enableSkills:Z=!0,enableAskQuestion:K=!0,...A}=$,W=[];if(T&&Y.readFile)W.push(UQ(Y.readFile,A));if(q&&Y.search)W.push(ZQ(Y.search,A));if(X&&Y.bash)W.push(KQ(Y.bash,A));if(J&&Y.webFetch)W.push(AQ(Y.webFetch,A));if(U&&Y.editor)W.push(GQ(Y.editor,A));else if(Q&&Y.applyPatch)W.push(WQ(Y.applyPatch,A));if(Z&&Y.skills)W.push(EQ(Y.skills,A));if(K&&Y.askQuestion)W.push(VQ(Y.askQuestion,A));return W}import*as Z1 from"node:fs/promises";import*as K1 from"node:path";var n={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},FQ=["%%bash","apply_patch","EOF","```"];class R0 extends Error{constructor($){super($);this.name="DiffError"}}function U1($){let Y={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(T)=>Y[T]??T).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class C9{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,Y){this.lines=$;this.currentFiles=Y}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(n.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(n.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(n.UPDATE)){this.parseUpdate($.substring(n.UPDATE.length).trim());return}if($?.startsWith(n.DELETE)){this.parseDelete($.substring(n.DELETE.length).trim());return}if($?.startsWith(n.ADD)){this.parseAdd($.substring(n.ADD.length).trim());return}throw new R0(`Unknown line while parsing: ${$}`)}checkDuplicate($,Y){if($ in this.patch.actions)throw new R0(`Duplicate ${Y} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let Y=this.lines[this.index]?.startsWith(n.MOVE)?(this.lines[this.index++]??"").substring(n.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new R0(`Update File Error: Missing File: ${$}`);let T=this.currentFiles[$]??"",q=this.parseUpdateFile(T,$);q.movePath=Y,this.patch.actions[$]=q,this.currentPath=void 0}parseUpdateFile($,Y){let T={type:"update",chunks:[]},q=$.split(`
|
|
77
77
|
`),X=0,J=[n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index],U=Q?.startsWith("@@ ")?Q.substring(3):void 0;if(U!==void 0||(Q==="@@"?Q:void 0)!==void 0)this.index++;else if(X!==0)throw new R0(`Invalid Line:
|
|
78
|
-
${this.lines[this.index]}`);if(U?.trim()){let
|
|
79
|
-
`);this.addWarning({path:this.currentPath||Y,chunkIndex:T.chunks.length,message:`Could not find matching context (similarity: ${H.toFixed(2)}). Chunk skipped.`,context:
|
|
80
|
-
`),chunks:[]}}}function
|
|
78
|
+
${this.lines[this.index]}`);if(U?.trim()){let D=U1(U.trim());for(let I=X;I<q.length;I++){let S=q[I];if(S&&(U1(S)===D||U1(S.trim())===D)){if(X=I+1,U1(S.trim())===D&&U1(S)!==D)this.fuzz++;break}}}let[K,A,W,E]=OD(this.lines,this.index),[V,F,H]=RD(q,K,X,E);if(V===-1){let D=K.join(`
|
|
79
|
+
`);this.addWarning({path:this.currentPath||Y,chunkIndex:T.chunks.length,message:`Could not find matching context (similarity: ${H.toFixed(2)}). Chunk skipped.`,context:D.length>200?`${D.substring(0,200)}...`:D}),this.index=W}else{this.fuzz+=F;for(let D of A)D.origIndex+=V,T.chunks.push(D);X=V+K.length,this.index=W}}return T}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new R0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new R0(`Add File Error: File already exists: ${$}`);this.index++;let Y=[],T=[n.END,n.UPDATE,n.DELETE,n.ADD];while(this.hasMoreLines()&&!T.some((q)=>this.lines[this.index]?.startsWith(q.trim()))){let q=this.lines[this.index++];if(q===void 0)break;if(!q.startsWith("+"))throw new R0(`Invalid Add File line (missing '+'): ${q}`);Y.push(q.substring(1))}this.patch.actions[$]={type:"add",newFile:Y.join(`
|
|
80
|
+
`),chunks:[]}}}function DQ($,Y){let T=$.length>Y.length?$:Y,q=$.length>Y.length?Y:$;if(T.length===0)return 1;let X=BD(q,T);return(T.length-X)/T.length}function BD($,Y){let T=Y.length+1,q=$.length+1,X=Array(T*q).fill(0),J=(U,Z)=>X[U*q+Z]??0,Q=(U,Z,K)=>{X[U*q+Z]=K};for(let U=0;U<=Y.length;U++)Q(U,0,U);for(let U=0;U<=$.length;U++)Q(0,U,U);for(let U=1;U<=Y.length;U++)for(let Z=1;Z<=$.length;Z++)if(Y[U-1]===$[Z-1])Q(U,Z,J(U-1,Z-1));else Q(U,Z,1+Math.min(J(U-1,Z-1),J(U,Z-1),J(U-1,Z)));return J(Y.length,$.length)}function RD($,Y,T,q){if(Y.length===0)return[T,0,1];let X=0,J=(Q)=>{let U=U1(Y.join(`
|
|
81
81
|
`));for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).join(`
|
|
82
|
-
`));if(A===U)return[K,0,1];let W=
|
|
82
|
+
`));if(A===U)return[K,0,1];let W=DQ(A,U);if(W>X)X=W}for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).map((E)=>E.trimEnd()).join(`
|
|
83
83
|
`)),W=U1(Y.map((E)=>E.trimEnd()).join(`
|
|
84
84
|
`));if(A===W)return[K,1,1]}for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).map((E)=>E.trim()).join(`
|
|
85
85
|
`)),W=U1(Y.map((E)=>E.trim()).join(`
|
|
86
86
|
`));if(A===W)return[K,100,1]}let Z=0.66;for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).join(`
|
|
87
|
-
`)),W=
|
|
88
|
-
`).map((X)=>X.replace(/\r$/,""));Y=
|
|
89
|
-
`)),q=[];for(let X of T)for(let J of Y){if(!X.startsWith(J))continue;let Q=X.substring(J.length).trim();if(!$.trim().endsWith(Q))q.push(Q);break}return q}function
|
|
87
|
+
`)),W=DQ(A,U);if(W>=Z)return[K,1000,W];if(W>X)X=W}return[-1,0,X]};if(q){let[Q,U,Z]=J($.length-Y.length);if(Q!==-1)return[Q,U,Z];return[Q,U,Z]=J(T),[Q,U+1e4,Z]}return J(T)}function OD($,Y){let T=Y,q=[],X=[],J=[],Q=[],U="keep",Z=["@@",n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(T<$.length){let K=$[T];if(!K||Z.some((E)=>K.startsWith(E.trim())))break;if(K==="***")break;if(K.startsWith("***"))throw new R0(`Invalid line: ${K}`);T++;let A=U,W=K;if(W[0]==="+")U="add";else if(W[0]==="-")U="delete";else if(W[0]===" ")U="keep";else U="keep",W=` ${W}`;if(W=W.slice(1),U==="keep"&&A!==U){if(J.length||X.length)Q.push({origIndex:q.length-X.length,delLines:X,insLines:J});X=[],J=[]}if(U==="delete")X.push(W),q.push(W);else if(U==="add")J.push(W);else q.push(W)}if(J.length||X.length)Q.push({origIndex:q.length-X.length,delLines:X,insLines:J});if(T<$.length&&$[T]===n.END_FILE)return T++,[q,Q,T,!0];return[q,Q,T,!1]}function y9($,Y,T){let q=K1.isAbsolute(Y),X=q?K1.normalize(Y):K1.resolve($,Y);if(!T||q)return X;let J=K1.relative($,X);if(J.startsWith("..")||K1.isAbsolute(J))throw new R0(`Path must stay within cwd: ${Y}`);return X}function NQ($){let Y=[],T=!1,q=!1,X=!1;for(let J=0;J<$.length;J++){let Q=$[J];if(!T&&FQ.some((Z)=>Q.startsWith(Z)))continue;if(Q.startsWith(n.BEGIN)){T=!0,q=!0,Y.push(Q);continue}if(Q===n.END){T=!1,Y.push(Q);continue}let U=Q.startsWith(n.ADD)||Q.startsWith(n.UPDATE)||Q.startsWith(n.DELETE)||Q.startsWith(n.MOVE)||Q.startsWith(n.SECTION)||Q.startsWith("+")||Q.startsWith("-")||Q.startsWith(" ")||Q==="***";if(U&&J!==$.length-1)X=!0;if(T||!q&&U||Q===""&&X)Y.push(Q)}while(Y.length>0&&Y[Y.length-1]==="")Y.pop();return!q&&!X?$:Y}function PD($){let Y=$.split(`
|
|
88
|
+
`).map((X)=>X.replace(/\r$/,""));Y=NQ(Y);let T=Y.length>0&&Y[0].startsWith(n.BEGIN),q=Y.length>0&&Y[Y.length-1]===n.END;if(!T&&!q)return[n.BEGIN,...Y,n.END];if(T&&q)return Y;throw new R0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.")}function LD($,Y){let T=NQ($.split(`
|
|
89
|
+
`)),q=[];for(let X of T)for(let J of Y){if(!X.startsWith(J))continue;let Q=X.substring(J.length).trim();if(!$.trim().endsWith(Q))q.push(Q);break}return q}function wD($,Y,T){if(Y.length===0)return $;let q=$.split(`
|
|
90
90
|
`),X=[],J=0;for(let Q of Y){if(Q.origIndex>q.length)throw new R0(`${T}: chunk.origIndex ${Q.origIndex} > lines.length ${q.length}`);if(J>Q.origIndex)throw new R0(`${T}: currentIndex ${J} > chunk.origIndex ${Q.origIndex}`);X.push(...q.slice(J,Q.origIndex)),X.push(...Q.insLines),J=Q.origIndex+Q.delLines.length}return X.push(...q.slice(J)),X.join(`
|
|
91
|
-
`)}async function
|
|
92
|
-
`)}return J}function
|
|
93
|
-
`)}}import{spawn as
|
|
91
|
+
`)}async function SD($,Y,T,q){let X=LD($,[n.UPDATE,n.DELETE]),J={};for(let Q of X){let U=y9(Y,Q,q),Z;try{Z=await Z1.readFile(U,T)}catch{throw new R0(`File not found: ${Q}`)}J[Q]=Z.replace(/\r\n/g,`
|
|
92
|
+
`)}return J}function CD($,Y){let T={};for(let[q,X]of Object.entries($.actions))switch(X.type){case"delete":T[q]={type:"delete",oldContent:Y[q]};break;case"add":if(X.newFile===void 0)throw new R0("ADD action without file content");T[q]={type:"add",newContent:X.newFile};break;case"update":T[q]={type:"update",oldContent:Y[q],newContent:wD(Y[q]??"",X.chunks,q),movePath:X.movePath};break}return T}async function yD($,Y,T,q){let X=[];for(let[J,Q]of Object.entries($)){let U=y9(Y,J,q);switch(Q.type){case"delete":await Z1.rm(U,{force:!0}),X.push(`${J}: [deleted]`);break;case"add":if(Q.newContent===void 0)throw new R0(`Cannot create ${J} with no content`);await Z1.mkdir(K1.dirname(U),{recursive:!0}),await Z1.writeFile(U,Q.newContent,{encoding:T}),X.push(J);break;case"update":{if(Q.newContent===void 0)throw new R0(`UPDATE change for ${J} has no new content`);if(Q.movePath){let Z=y9(Y,Q.movePath,q);await Z1.mkdir(K1.dirname(Z),{recursive:!0}),await Z1.writeFile(Z,Q.newContent,{encoding:T}),await Z1.rm(U,{force:!0}),X.push(`${J} -> ${Q.movePath}`)}else await Z1.writeFile(U,Q.newContent,{encoding:T}),X.push(J);break}}}return X}function lT($={}){let{encoding:Y="utf-8",restrictToCwd:T=!0}=$;return async(q,X,J)=>{let Q=PD(q.input),U=await SD(q.input,X,Y,T),Z=new C9(Q,U),{patch:K,fuzz:A}=Z.parse(),W=CD(K,U),E=await yD(W,X,Y,T),V=["Successfully applied patch to the following files:"];for(let F of E)V.push(F);if(A>0)V.push(`Note: Patch applied with fuzz factor ${A}`);if(K.warnings&&K.warnings.length>0)for(let F of K.warnings)V.push(`Warning (${F.path}): ${F.message}`);return V.join(`
|
|
93
|
+
`)}}import{spawn as HQ}from"node:child_process";function nT($={}){let{shell:Y=process.platform==="win32"?"cmd.exe":"/bin/bash",timeoutMs:T=30000,maxOutputBytes:q=1e6,env:X={},combineOutput:J=!0}=$;return async(Q,U,Z)=>{return new Promise((K,A)=>{let W=process.platform==="win32"?["/c",Q]:["-c",Q],E=process.platform==="win32",V=HQ(Y,W,{cwd:U,env:{...process.env,...X},stdio:["pipe","pipe","pipe"],detached:!E}),F=V.pid,H="",D="",I=0,S=!1,v=!1,z=(C)=>{if(v)return;v=!0,A(C)},_=(C)=>{if(v)return;v=!0,K(C)},y=()=>{if(!F)return;if(E){HQ("taskkill",["/pid",String(F),"/T","/F"],{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-F,"SIGKILL")}catch{V.kill("SIGKILL")}},k=setTimeout(()=>{S=!0,y(),z(Error(`Command timed out after ${T}ms`))},T),m=()=>{S=!0,y(),z(Error("Command was aborted"))};if(Z.abortSignal)Z.abortSignal.addEventListener("abort",m);V.stdout?.on("data",(C)=>{if(I+=C.length,I<=q)H+=C.toString()}),V.stderr?.on("data",(C)=>{if(I+=C.length,I<=q)D+=C.toString()}),V.on("close",(C)=>{if(clearTimeout(k),Z.abortSignal)Z.abortSignal.removeEventListener("abort",m);if(S)return;let j=J?H+(D?`
|
|
94
94
|
[stderr]
|
|
95
|
-
${
|
|
95
|
+
${D}`:""):H;if(I>q)j+=`
|
|
96
96
|
|
|
97
|
-
[Output truncated: ${
|
|
97
|
+
[Output truncated: ${I} bytes total, showing first ${q} bytes]`;if(C!==0){let M=D||`Command exited with code ${C}`;z(Error(M))}else _(j)}),V.on("error",(C)=>{if(clearTimeout(k),Z.abortSignal)Z.abortSignal.removeEventListener("abort",m);z(Error(`Failed to execute command: ${C.message}`))})})}}import*as s1 from"node:fs/promises";import*as M1 from"node:path";function jD($,Y,T){let q=M1.isAbsolute(Y),X=q?M1.normalize(Y):M1.resolve($,Y);if(!T)return X;if(q)return X;let J=M1.relative($,X);if(J.startsWith("..")||M1.isAbsolute(J))throw Error(`Path must stay within cwd: ${Y}`);return X}function vD($,Y){if(Y.length===0)return 0;return $.split(Y).length-1}function xD($,Y,T){let q=$.split(`
|
|
98
98
|
`),X=Y.split(`
|
|
99
99
|
`),J=Math.max(q.length,X.length),Q=["```diff"],U=0;for(let Z=0;Z<J;Z++){if(U>=T){Q.push("... diff truncated ...");break}let K=q[Z],A=X[Z];if(K===A)continue;let W=Z+1;if(K!==void 0)Q.push(`-${W}: ${K}`),U++;if(A!==void 0&&U<T)Q.push(`+${W}: ${A}`),U++}return Q.push("```"),Q.join(`
|
|
100
|
-
`)}async function
|
|
101
|
-
${Z}`}async function
|
|
100
|
+
`)}async function kD($,Y,T){return await s1.mkdir(M1.dirname($),{recursive:!0}),await s1.writeFile($,Y,{encoding:T}),`File created successfully at: ${$}`}async function hD($,Y,T,q,X){let J=await s1.readFile($,q),Q=vD(J,Y);if(Q===0)throw Error(`No replacement performed: text not found in ${$}.`);if(Q>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let U=J.replace(Y,T??"");await s1.writeFile($,U,{encoding:q});let Z=xD(J,U,X);return`Edited ${$}
|
|
101
|
+
${Z}`}async function _D($,Y,T,q){let J=(await s1.readFile($,q)).split(`
|
|
102
102
|
`),Q=Y-1;if(Q<0||Q>J.length)throw Error(`Invalid line number: ${Y}. Valid range: 1-${J.length}`);return J.splice(Q,0,...T.split(`
|
|
103
103
|
`)),await s1.writeFile($,J.join(`
|
|
104
|
-
`),{encoding:q}),`Inserted content at line ${Y} in ${$}.`}function
|
|
104
|
+
`),{encoding:q}),`Inserted content at line ${Y} in ${$}.`}function iT($={}){let{encoding:Y="utf-8",restrictToCwd:T=!0,maxDiffLines:q=200}=$;return async(X,J,Q)=>{let U=jD(J,X.path,T);switch(X.command){case"create":if(X.file_text==null)throw Error("Parameter `file_text` is required for command: create");return kD(U,X.file_text,Y);case"str_replace":if(X.old_str==null)throw Error("Parameter `old_str` is required for command: str_replace");return hD(U,X.old_str,X.new_str,Y,q);case"insert":if(X.insert_line==null)throw Error("Parameter `insert_line` is required for insert command.");if(X.new_str==null)throw Error("Parameter `new_str` is required for insert command.");return _D(U,X.insert_line,X.new_str,Y);default:throw Error(`Unrecognized command ${X.command}. Allowed commands are: create, str_replace, insert`)}}}import*as rT from"node:fs/promises";import*as WY from"node:path";var gD={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function aT($={}){let{maxFileSizeBytes:Y,encoding:T,includeLineNumbers:q}={...gD,...$};return async(X,J)=>{let Q=WY.isAbsolute(X)?WY.normalize(X):WY.resolve(process.cwd(),X),U=await rT.stat(Q);if(!U.isFile())throw Error(`Path is not a file: ${Q}`);if(U.size>Y)throw Error(`File too large: ${U.size} bytes (max: ${Y} bytes). Consider reading specific sections or using a different approach.`);let Z=await rT.readFile(Q,T);if(q){let K=Z.split(`
|
|
105
105
|
`),A=String(K.length).length;return K.map((W,E)=>`${String(E+1).padStart(A," ")} | ${W}`).join(`
|
|
106
|
-
`)}return Z}}import*as
|
|
107
|
-
`);for(let z=0;z<v.length;z++){let _=v[z];W.lastIndex=0;let y;while((y=W.exec(_))!==null){if(E.length>=q)break;let k=Math.max(0,z-X),m=Math.min(v.length-1,z+X),C=[];for(let j=k;j<=m;j++){let
|
|
108
|
-
Searched ${
|
|
109
|
-
`)}}function
|
|
106
|
+
`)}return Z}}import*as OQ from"node:fs/promises";import*as sT from"node:path";import{spawn as mD}from"node:child_process";import{readdir as fD}from"node:fs/promises";import x9 from"node:path";import{isMainThread as IQ,parentPort as zQ,Worker as bD}from"node:worker_threads";var uD=15000,dD=1000,cD=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]),j9=new Map;function pD($,Y){return x9.relative($,Y).split(x9.sep).join("/")}async function lD($){let T=(await new Promise((q,X)=>{let J=mD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),Q="",U="";J.stdout.on("data",(Z)=>{Q+=Z.toString()}),J.stderr.on("data",(Z)=>{U+=Z.toString()}),J.on("error",X),J.on("close",(Z)=>{if(Z===0){q(Q);return}X(Error(U||`rg exited with code ${Z}`))})})).split(/\r?\n/).map((q)=>q.trim()).filter((q)=>q.length>0).map((q)=>q.replace(/\\/g,"/"));return new Set(T)}async function MQ($,Y,T){let q=await fD(Y,{withFileTypes:!0});for(let X of q){let J=x9.join(Y,X.name);if(X.isDirectory()){if(cD.has(X.name))continue;await MQ($,J,T);continue}if(X.isFile())T.add(pD($,J))}}async function nD($){let Y=new Set;return await MQ($,$,Y),Y}async function k9($){try{return await lD($)}catch{return nD($)}}function iD(){if(IQ||!zQ)return;let $=zQ;$.on("message",(Y)=>{if(Y.type!=="index")return;k9(Y.cwd).then((T)=>{let q={type:"indexResult",requestId:Y.requestId,files:Array.from(T)};$.postMessage(q)}).catch((T)=>{let q={type:"indexResult",requestId:Y.requestId,error:T instanceof Error?T.message:"Failed to build file index"};$.postMessage(q)})})}class BQ{worker=new bD(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let Y=this.pending.get($.requestId);if(!Y)return;if(this.pending.delete($.requestId),$.error){Y.reject(Error($.error));return}Y.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let Y=++this.nextRequestId,T=new Promise((X,J)=>{let Q=setTimeout(()=>{this.pending.delete(Y),J(Error("Timed out waiting for file index worker response"))},dD);Q.unref(),this.pending.set(Y,{resolve:(U)=>{clearTimeout(Q),X(U)},reject:(U)=>{clearTimeout(Q),J(U)}})}),q={type:"index",requestId:Y,cwd:$};return this.worker.postMessage(q),T}flushPending($){for(let[Y,T]of this.pending.entries())T.reject($),this.pending.delete(Y)}}iD();var v9;function rD(){if(!IQ)return null;if(v9===void 0)v9=new BQ;return v9}async function aD($){let Y=rD();if(!Y)return k9($);try{let T=await Y.requestIndex($);return new Set(T)}catch{return k9($)}}async function g$($,Y={}){let T=Y.ttlMs??uD,q=Date.now(),X=j9.get($);if(X&&T>0&&q-X.lastBuiltAt<=T&&X.files.size>0)return X.files;if(X?.pending)return X.pending;let J=aD($).then((Q)=>{return j9.set($,{files:Q,lastBuiltAt:Date.now(),pending:null}),Q});return j9.set($,{files:X?.files??new Set,lastBuiltAt:X?.lastBuiltAt??0,pending:J}),J}async function RQ($,Y={}){await g$($,{...Y,ttlMs:0})}import{stat as oD}from"node:fs/promises";import m$ from"node:path";var sD=/[),.:;!?`'"]+$/,tD=/^[(`'"]+/;function eD($){let Y=$.matchAll(/(^|[\s])@([^\s]+)/g),T=[];for(let q of Y){let X=(q[2]??"").trim();if(X.length===0)continue;let J=X.replace(tD,"").replace(sD,"");if(J.length===0||J.includes("@"))continue;T.push(J)}return Array.from(new Set(T))}function $F($,Y){let T=$.replace(/\\/g,"/"),q=m$.isAbsolute(T)?m$.resolve(T):m$.resolve(Y,T),X=m$.relative(Y,q);if(X.startsWith("..")||m$.isAbsolute(X))return;return X.split(m$.sep).join("/")}async function oT($,Y,T={}){let q=eD($);if(q.length===0)return{prompt:$,matchedFiles:[],ignoredMentions:[]};let{maxFiles:X,maxFileBytes:J,maxTotalBytes:Q}=T,U=await g$(Y,{ttlMs:T.ttlMs}),Z=[],K=[],A=[],W=0;for(let E of q){if(X&&A.length>=X){K.push(E);continue}let V=$F(E,Y);if(!V||!U.has(V)){K.push(E);continue}if(!J||!Q){Z.push(V);continue}let F=m$.join(Y,V);try{if(!(await oD(F)).isFile()){K.push(E);continue}let D=W+J;if(D>Q){K.push(E);continue}W+=D,Z.push(V)}catch{K.push(E)}}return{prompt:$,matchedFiles:Z,ignoredMentions:K}}var YF=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],TF=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"];function qF($,Y,T,q){let X=$.split("/"),J=X[X.length-1]??"";if(X.length-1>q)return!1;for(let Z=0;Z<X.length-1;Z++)if(Y.has(X[Z]??""))return!1;let U=sT.posix.extname(J).slice(1).toLowerCase();return T.has(U)||!U&&!J.startsWith(".")}function tT($={}){let{includeExtensions:Y=YF,excludeDirs:T=TF,maxResults:q=100,contextLines:X=2,maxDepth:J=20}=$,Q=new Set(T),U=new Set(Y.map((Z)=>Z.toLowerCase()));return async(Z,K,A)=>{let W;try{W=new RegExp(Z,"gim")}catch(D){throw Error(`Invalid regex pattern: ${Z}. ${D instanceof Error?D.message:""}`)}let E=[],V=0,F=await g$(K);for(let D of F){if(!qF(D,Q,U,J))continue;if(E.length>=q)break;V++;let I=sT.join(K,D);try{let v=(await OQ.readFile(I,"utf-8")).split(`
|
|
107
|
+
`);for(let z=0;z<v.length;z++){let _=v[z];W.lastIndex=0;let y;while((y=W.exec(_))!==null){if(E.length>=q)break;let k=Math.max(0,z-X),m=Math.min(v.length-1,z+X),C=[];for(let j=k;j<=m;j++){let M=j===z?">":" ";C.push(`${M} ${j+1}: ${v[j]}`)}if(E.push({file:D,line:z+1,column:y.index+1,match:y[0],context:C}),y.index===W.lastIndex)W.lastIndex++}}}catch{}}if(E.length===0)return`No results found for pattern: ${Z}
|
|
108
|
+
Searched ${V} files.`;let H=[`Found ${E.length} result${E.length===1?"":"s"} for pattern: ${Z}`,`Searched ${V} files.`,""];for(let D of E)H.push(`${D.file}:${D.line}:${D.column}`),H.push(...D.context),H.push("");if(E.length>=q)H.push(`(Showing first ${q} results. Refine your search for more specific results.)`);return H.join(`
|
|
109
|
+
`)}}function XF($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
|
|
110
110
|
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(Y,T)=>String.fromCharCode(parseInt(T,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
111
111
|
`).replace(/\n{3,}/g,`
|
|
112
112
|
|
|
113
|
-
`).trim()}function
|
|
113
|
+
`).trim()}function eT($={}){let{timeoutMs:Y=30000,maxResponseBytes:T=5000000,userAgent:q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:X={},followRedirects:J=!0}=$;return async(Q,U,Z)=>{let K;try{K=new URL(Q)}catch{throw Error(`Invalid URL: ${Q}`)}if(!["http:","https:"].includes(K.protocol))throw Error(`Invalid protocol: ${K.protocol}. Only http and https are supported.`);let A=new AbortController,W=setTimeout(()=>A.abort(),Y),E;if(Z.abortSignal)E=()=>A.abort(),Z.abortSignal.addEventListener("abort",E);try{let V=await fetch(Q,{method:"GET",headers:{"User-Agent":q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...X},redirect:J?"follow":"manual",signal:A.signal});if(clearTimeout(W),!J&&V.status>=300&&V.status<400)return`Redirect to: ${V.headers.get("location")}`;if(!V.ok)throw Error(`HTTP ${V.status}: ${V.statusText}`);let F=V.headers.get("content-type")||"",H=V.body?.getReader();if(!H)throw Error("Failed to read response body");let D=[],I=0;while(!0){let{done:k,value:m}=await H.read();if(k)break;if(I+=m.length,I>T)throw H.cancel(),Error(`Response too large: exceeded ${T} bytes`);D.push(m)}let S=new Uint8Array(I),v=0;for(let k of D)S.set(k,v),v+=k.length;let z=new TextDecoder("utf-8").decode(S),_;if(F.includes("text/html")||F.includes("application/xhtml"))_=XF(z);else if(F.includes("application/json"))try{let k=JSON.parse(z);_=JSON.stringify(k,null,2)}catch{_=z}else _=z;let y=[`URL: ${Q}`,`Content-Type: ${F}`,`Size: ${I} bytes`,"","--- Content ---",_.slice(0,50000)];if(_.length>50000)y.push(`
|
|
114
114
|
[Content truncated: showing first 50000 of ${_.length} characters]`);return y.push("","--- Analysis Request ---",`Prompt: ${U}`),y.join(`
|
|
115
|
-
`)}catch(D){if(clearTimeout(W),D instanceof Error){if(D.name==="AbortError")throw Error(`Request timed out after ${Y}ms`);throw D}throw Error(`Fetch failed: ${String(D)}`)}finally{if(Z.abortSignal&&E)Z.abortSignal.removeEventListener("abort",E)}}}function e6($={}){return{readFile:r6($.fileRead),search:s6($.search),bash:l6($.bash),webFetch:t6($.webFetch),applyPatch:p6($.applyPatch),editor:n6($.editor)}}var TF={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"},k9=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function BQ($,Y){if(!Y||Y.length===0)return!0;let T=$.toLowerCase();return Y.some((q)=>T.includes(q.toLowerCase()))}function qF($,Y,T,q){if($.mode&&$.mode!=="any"&&$.mode!==q)return!1;return BQ(Y,$.providerIdIncludes)&&BQ(T,$.modelIdIncludes)}function h9($,Y,T,q){if(!q||q.length===0)return{};let X=new Map;for(let Q of q){if(!qF(Q,$,Y,T))continue;for(let U of Q.disableTools??[])X.set(U,!1);for(let U of Q.enableTools??[])X.set(U,!0)}let J={};for(let[Q,U]of X.entries())J[TF[Q]]=U;return J}var t1={browser:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1},development:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0},readonly:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!0},yolo:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0}};function RQ($){if($!=="yolo")return{};let Y={enabled:!0,autoApprove:!0},T={"*":Y};for(let q of _$)T[q]=Y;return T}function OQ($,Y){let T=t1[$];return AY({...T,...Y})}function NT($={}){let{executorOptions:Y={},executors:T,...q}=$,X={...e6(Y),...T??{}};return AY({...q,executors:X})}var JF=A1.object({name:A1.string().trim().min(1),description:A1.string().trim().min(1),modelId:A1.string().trim().min(1).optional(),tools:A1.union([A1.string(),A1.array(A1.string())]).optional(),skills:A1.union([A1.string(),A1.array(A1.string())]).optional()}),QF=new Set(_$);function PQ($){return/\.(yaml|yml)$/i.test($)}function LQ($){return $.trim().toLowerCase()}function UF($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T=$.match(Y);if(!T)return{data:{},body:$,hadFrontmatter:!1};let[,q,X]=T;try{let J=XF.parse(q);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function ZF($){let Y=$.trim();if(!Y)throw Error("Tool name cannot be empty.");if(!QF.has(Y))throw Error(`Unknown tool '${Y}'. Expected one of: ${_$.join(", ")}.`);return Y}function KF($){if(!$)return[];let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(ZF)))}function AF($){let Y=$.trim();if(!Y)throw Error("Skill name cannot be empty.");return Y}function WF($){if($===void 0)return;let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(AF)))}function GY($){let{data:Y,body:T,hadFrontmatter:q,parseError:X}=UF($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);if(!q)throw Error("Missing YAML frontmatter block in agent config file.");let J=JF.parse(Y),Q=T.trim();if(!Q)throw Error("Missing system prompt body in agent config file.");return{name:J.name,description:J.description,modelId:J.modelId,tools:KF(J.tools),skills:WF(J.skills),systemPrompt:Q}}function $8($,Y){if($.length===0)return[];let T=new Map(Y.map((q)=>[q.name,q]));return $.map((q)=>{let X=T.get(q);if(!X)throw Error(`Configured tool '${q}' is unavailable. Available tools: ${Y.map((J)=>J.name).join(", ")}.`);return X})}function Y8($,Y){let T={systemPrompt:$.systemPrompt};if($.modelId)T.modelId=$.modelId;if($.tools.length>0){if(!Y?.availableTools)throw Error("Configured tools cannot be converted into AgentConfig.tools without availableTools.");T.tools=$8($.tools,Y.availableTools)}return T}function _9($,Y){let T=GY($);return Y8(T,Y)}import{createHash as GF}from"node:crypto";import{watch as EF}from"node:fs";import{readdir as VF,readFile as DF}from"node:fs/promises";import{join as FF}from"node:path";function NF($){return GF("sha1").update($).digest("hex")}function HF($){return Boolean($&&typeof $==="object"&&"code"in $)}function wQ($){return HF($)&&$.code==="ENOENT"}class f${definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,Y){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=Y?.debounceMs??75,this.emitParseErrors=Y?.emitParseErrors??!1;for(let T of $){if(this.definitionsByType.has(T.type))throw Error(`Duplicate unified config definition type '${T.type}'.`);this.definitionsByType.set(T.type,T),this.recordsByType.set(T.type,new Map),this.discoveredDirectoriesByType.set(T.type,new Set);for(let q of T.directories){let X=this.baseTypesByDirectory.get(q);if(X)X.add(T.type);else this.baseTypesByDirectory.set(q,new Set([T.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let Y=this.definitionsByType.get($);if(!Y)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(Y)})}getSnapshot($){let Y=this.recordsByType.get($);return new Map([...Y?.entries()??[]].map(([T,q])=>[T,{...q}]))}getAllSnapshots(){let $=new Map;for(let[Y,T]of this.recordsByType.entries())$.set(Y,new Map([...T.entries()].map(([q,X])=>[q,{...X}])));return $}emit($){for(let Y of this.listeners)Y($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[Y,T]of this.watchersByDirectory.entries()){if($.has(Y))continue;T.close(),this.watchersByDirectory.delete(Y)}this.watchedTypesByDirectory=$;for(let Y of $.keys()){if(this.watchersByDirectory.has(Y))continue;try{let T=EF(Y,()=>{let q=this.watchedTypesByDirectory.get(Y);if(!q)return;for(let X of q)this.pendingTypes.add(X);this.scheduleFlush()});this.watchersByDirectory.set(Y,T),T.on("error",(q)=>{let X=this.watchedTypesByDirectory.get(Y);if(!X)return;for(let J of X)this.emit({kind:"error",type:J,error:q,filePath:Y})})}catch(T){if(!wQ(T)){let q=$.get(Y);if(!q)continue;for(let X of q)this.emit({kind:"error",type:X,error:T,filePath:Y})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let Y of $){let T=this.definitionsByType.get(Y);if(!T)continue;await this.refreshTypeInternal(T)}})},this.debounceMs)}async refreshTypeInternal($){let{records:Y,discoveredDirectories:T}=await this.loadDefinition($),q=this.recordsByType.get($.type)??new Map;for(let[X,J]of q.entries()){if(Y.has(X))continue;this.emit({kind:"remove",type:$.type,id:X,filePath:J.filePath})}for(let[X,J]of Y.entries()){let Q=q.get(X);if(Q&&Q.filePath===J.filePath&&Q.fingerprint===J.fingerprint)continue;this.emit({kind:"upsert",record:{type:J.type,id:X,item:J.item,filePath:J.filePath}})}if(this.recordsByType.set($.type,Y),this.discoveredDirectoriesByType.set($.type,T),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let Y=new Map,T=new Set;for(let q of $.directories){T.add(q);let X=$.discoverFiles?await $.discoverFiles(q):await this.readDirectoryFileCandidates(q);for(let J of X){let{fileName:Q,filePath:U}=J;if(T.add(J.directoryPath),$.includeFile&&!$.includeFile(Q,U))continue;try{let Z=await DF(U,"utf8"),K={type:$.type,directoryPath:J.directoryPath,fileName:Q,filePath:U,content:Z},A=$.parseFile(K),W=$.resolveId(A,K).trim();if(!W)continue;Y.set(W,{type:$.type,id:W,item:A,filePath:U,fingerprint:NF(Z)})}catch(Z){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Z,filePath:U})}}}return{records:Y,discoveredDirectories:T}}buildDesiredTypesByDirectory(){let $=new Map;for(let[Y,T]of this.baseTypesByDirectory.entries())$.set(Y,new Set(T));for(let[Y,T]of this.discoveredDirectoriesByType.entries())for(let q of T){let X=$.get(q);if(X)X.add(Y);else $.set(q,new Set([Y]))}return $}async readDirectoryFileCandidates($){try{return(await VF($,{withFileTypes:!0})).filter((T)=>T.isFile()).map((T)=>({directoryPath:$,fileName:T.name,filePath:FF($,T.name)})).sort((T,q)=>T.fileName.localeCompare(q.fileName))}catch(Y){if(wQ(Y))return[];throw Y}}}function SQ(){return M9()}function zF($){if(Array.isArray($))return[...$];if(typeof $==="string")return[$];return SQ()}function g9($){return{type:"agent",directories:zF($),includeFile:(Y)=>PQ(Y),parseFile:(Y)=>GY(Y.content),resolveId:(Y)=>LQ(Y.name)}}function CQ($){return new f$([g9($?.directoryPathOrPaths)],{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{existsSync as IF,readdirSync as MF}from"node:fs";import{basename as BF,extname as RF,join as OF}from"node:path";function m9($){return B9($)}var T8;((K)=>{K.TaskStart="TaskStart";K.TaskResume="TaskResume";K.TaskCancel="TaskCancel";K.TaskComplete="TaskComplete";K.PreToolUse="PreToolUse";K.PostToolUse="PostToolUse";K.UserPromptSubmit="UserPromptSubmit";K.PreCompact="PreCompact";K.SessionShutdown="SessionShutdown"})(T8||={});var f9={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},PF=new Map(Object.values(T8).map(($)=>[$.toLowerCase(),$]));function b9($){let Y=BF($,RF($)).trim().toLowerCase();return PF.get(Y)}function q8($){let Y=[],T=new Set,q=m9($).filter((X)=>IF(X));for(let X of q)try{for(let J of MF(X,{withFileTypes:!0})){if(!J.isFile())continue;let Q=b9(J.name);if(!Q)continue;let U=OF(X,J.name);if(T.has(U))continue;T.add(U),Y.push({fileName:Q,hookEventName:f9[Q],path:U})}}catch{}return Y.sort((X,J)=>X.path.localeCompare(J.path))}import{existsSync as c9,readdirSync as vF,statSync as xF}from"node:fs";import{join as kF,resolve as kQ}from"node:path";import{resolve as LF}from"node:path";import{pathToFileURL as wF}from"node:url";function jQ($){return typeof $==="object"&&$!==null}function yQ($){return Array.isArray($)&&$.every((Y)=>typeof Y==="string")}function SF($,Y){if(!jQ($.manifest))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);if(!yQ($.manifest.capabilities))throw Error(`Invalid plugin module at ${Y}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${Y}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"hookStages")&&!yQ($.manifest.hookStages))throw Error(`Invalid plugin module at ${Y}: manifest.hookStages must be a string array when provided`)}function CF($,Y){if(!jQ($))throw Error(`Invalid plugin module at ${Y}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${Y}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);SF($,Y)}async function u9($,Y={}){let T=LF(Y.cwd??process.cwd(),$),q=await import(wF(T).href),X=Y.exportName??"plugin",J=q.default??q[X];return CF(J,T),J}async function X8($,Y={}){let T=[];for(let q of $)T.push(await u9(q,Y));return T}import{spawn as yF}from"node:child_process";function vQ($){if($ instanceof Error)return $;return Error(String($))}class J8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}start(){if(this.process&&this.process.exitCode===null)return;let $=yF(process.execPath,["-e",this.options.bootstrapScript],{stdio:["ignore","ignore","ignore","ipc"]});this.process=$,$.on("message",(Y)=>{this.onMessage(Y)}),$.on("error",(Y)=>{this.failPending(Error(`${this.options.name??"sandbox"} process error: ${vQ(Y).message}`))}),$.on("exit",(Y,T)=>{this.process=null,this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Y)}, signal=${String(T)})`))})}async call($,Y,T={}){this.start();let q=this.process;if(!q||q.exitCode!==null)throw Error(`${this.options.name??"sandbox"} process is not available`);let X=`req_${++this.requestCounter}`,J={type:"call",id:X,method:$,args:Y};return await new Promise((Q,U)=>{let Z={resolve:(K)=>Q(K),reject:U};if((T.timeoutMs??0)>0)Z.timeout=setTimeout(()=>{this.pending.delete(X),this.shutdown().catch(()=>{}),U(Error(`${this.options.name??"sandbox"} call timed out after ${T.timeoutMs}ms: ${$}`))},T.timeoutMs);this.pending.set(X,Z),q.send(J,(K)=>{if(!K)return;let A=this.pending.get(X);if(!A)return;if(this.pending.delete(X),A.timeout)clearTimeout(A.timeout);A.reject(Error(`${this.options.name??"sandbox"} failed to send call "${$}": ${vQ(K).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.options.name??"sandbox"} shutdown`));return}await new Promise((Y)=>{let T=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Y()},300);$.once("exit",()=>{clearTimeout(T),Y()});try{$.kill("SIGTERM")}catch{clearTimeout(T),Y()}}),this.failPending(Error(`${this.options.name??"sandbox"} shutdown`))}onMessage($){if(!$||$.type!=="response"||!$.id)return;let Y=this.pending.get($.id);if(!Y)return;if(this.pending.delete($.id),Y.timeout)clearTimeout(Y.timeout);if($.ok){Y.resolve($.result);return}Y.reject(Error($.error?.message||`${this.options.name??"sandbox"} call failed`))}failPending($){for(let[Y,T]of this.pending.entries()){if(this.pending.delete(Y),T.timeout)clearTimeout(T.timeout);T.reject($)}}}var jF=`
|
|
115
|
+
`)}catch(V){if(clearTimeout(W),V instanceof Error){if(V.name==="AbortError")throw Error(`Request timed out after ${Y}ms`);throw V}throw Error(`Fetch failed: ${String(V)}`)}finally{if(Z.abortSignal&&E)Z.abortSignal.removeEventListener("abort",E)}}}function $8($={}){return{readFile:aT($.fileRead),search:tT($.search),bash:nT($.bash),webFetch:eT($.webFetch),applyPatch:lT($.applyPatch),editor:iT($.editor)}}var JF={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"},h9=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function PQ($,Y){if(!Y||Y.length===0)return!0;let T=$.toLowerCase();return Y.some((q)=>T.includes(q.toLowerCase()))}function QF($,Y,T,q){if($.mode&&$.mode!=="any"&&$.mode!==q)return!1;return PQ(Y,$.providerIdIncludes)&&PQ(T,$.modelIdIncludes)}function _9($,Y,T,q){if(!q||q.length===0)return{};let X=new Map;for(let Q of q){if(!QF(Q,$,Y,T))continue;for(let U of Q.disableTools??[])X.set(U,!1);for(let U of Q.enableTools??[])X.set(U,!0)}let J={};for(let[Q,U]of X.entries())J[JF[Q]]=U;return J}var t1={browser:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1},development:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0},readonly:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!0},yolo:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0}};function LQ($){if($!=="yolo")return{};let Y={enabled:!0,autoApprove:!0},T={"*":Y};for(let q of _$)T[q]=Y;return T}function wQ($,Y){let T=t1[$];return AY({...T,...Y})}function N6($={}){let{executorOptions:Y={},executors:T,...q}=$,X={...$8(Y),...T??{}};return AY({...q,executors:X})}var ZF=A1.object({name:A1.string().trim().min(1),description:A1.string().trim().min(1),modelId:A1.string().trim().min(1).optional(),tools:A1.union([A1.string(),A1.array(A1.string())]).optional(),skills:A1.union([A1.string(),A1.array(A1.string())]).optional()}),KF=new Set(_$);function SQ($){return/\.(yaml|yml)$/i.test($)}function CQ($){return $.trim().toLowerCase()}function AF($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T=$.match(Y);if(!T)return{data:{},body:$,hadFrontmatter:!1};let[,q,X]=T;try{let J=UF.parse(q);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function WF($){let Y=$.trim();if(!Y)throw Error("Tool name cannot be empty.");if(!KF.has(Y))throw Error(`Unknown tool '${Y}'. Expected one of: ${_$.join(", ")}.`);return Y}function GF($){if(!$)return[];let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(WF)))}function EF($){let Y=$.trim();if(!Y)throw Error("Skill name cannot be empty.");return Y}function VF($){if($===void 0)return;let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(EF)))}function GY($){let{data:Y,body:T,hadFrontmatter:q,parseError:X}=AF($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);if(!q)throw Error("Missing YAML frontmatter block in agent config file.");let J=ZF.parse(Y),Q=T.trim();if(!Q)throw Error("Missing system prompt body in agent config file.");return{name:J.name,description:J.description,modelId:J.modelId,tools:GF(J.tools),skills:VF(J.skills),systemPrompt:Q}}function Y8($,Y){if($.length===0)return[];let T=new Map(Y.map((q)=>[q.name,q]));return $.map((q)=>{let X=T.get(q);if(!X)throw Error(`Configured tool '${q}' is unavailable. Available tools: ${Y.map((J)=>J.name).join(", ")}.`);return X})}function T8($,Y){let T={systemPrompt:$.systemPrompt};if($.modelId)T.modelId=$.modelId;if($.tools.length>0){if(!Y?.availableTools)throw Error("Configured tools cannot be converted into AgentConfig.tools without availableTools.");T.tools=Y8($.tools,Y.availableTools)}return T}function g9($,Y){let T=GY($);return T8(T,Y)}import{createHash as DF}from"node:crypto";import{watch as FF}from"node:fs";import{readdir as NF,readFile as HF}from"node:fs/promises";import{join as zF}from"node:path";function IF($){return DF("sha1").update($).digest("hex")}function MF($){return Boolean($&&typeof $==="object"&&"code"in $)}function yQ($){return MF($)&&$.code==="ENOENT"}class f${definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,Y){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=Y?.debounceMs??75,this.emitParseErrors=Y?.emitParseErrors??!1;for(let T of $){if(this.definitionsByType.has(T.type))throw Error(`Duplicate unified config definition type '${T.type}'.`);this.definitionsByType.set(T.type,T),this.recordsByType.set(T.type,new Map),this.discoveredDirectoriesByType.set(T.type,new Set);for(let q of T.directories){let X=this.baseTypesByDirectory.get(q);if(X)X.add(T.type);else this.baseTypesByDirectory.set(q,new Set([T.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let Y=this.definitionsByType.get($);if(!Y)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(Y)})}getSnapshot($){let Y=this.recordsByType.get($);return new Map([...Y?.entries()??[]].map(([T,q])=>[T,{...q}]))}getAllSnapshots(){let $=new Map;for(let[Y,T]of this.recordsByType.entries())$.set(Y,new Map([...T.entries()].map(([q,X])=>[q,{...X}])));return $}emit($){for(let Y of this.listeners)Y($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[Y,T]of this.watchersByDirectory.entries()){if($.has(Y))continue;T.close(),this.watchersByDirectory.delete(Y)}this.watchedTypesByDirectory=$;for(let Y of $.keys()){if(this.watchersByDirectory.has(Y))continue;try{let T=FF(Y,()=>{let q=this.watchedTypesByDirectory.get(Y);if(!q)return;for(let X of q)this.pendingTypes.add(X);this.scheduleFlush()});this.watchersByDirectory.set(Y,T),T.on("error",(q)=>{let X=this.watchedTypesByDirectory.get(Y);if(!X)return;for(let J of X)this.emit({kind:"error",type:J,error:q,filePath:Y})})}catch(T){if(!yQ(T)){let q=$.get(Y);if(!q)continue;for(let X of q)this.emit({kind:"error",type:X,error:T,filePath:Y})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let Y of $){let T=this.definitionsByType.get(Y);if(!T)continue;await this.refreshTypeInternal(T)}})},this.debounceMs)}async refreshTypeInternal($){let{records:Y,discoveredDirectories:T}=await this.loadDefinition($),q=this.recordsByType.get($.type)??new Map;for(let[X,J]of q.entries()){if(Y.has(X))continue;this.emit({kind:"remove",type:$.type,id:X,filePath:J.filePath})}for(let[X,J]of Y.entries()){let Q=q.get(X);if(Q&&Q.filePath===J.filePath&&Q.fingerprint===J.fingerprint)continue;this.emit({kind:"upsert",record:{type:J.type,id:X,item:J.item,filePath:J.filePath}})}if(this.recordsByType.set($.type,Y),this.discoveredDirectoriesByType.set($.type,T),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let Y=new Map,T=new Set;for(let q of $.directories){T.add(q);let X=$.discoverFiles?await $.discoverFiles(q):await this.readDirectoryFileCandidates(q);for(let J of X){let{fileName:Q,filePath:U}=J;if(T.add(J.directoryPath),$.includeFile&&!$.includeFile(Q,U))continue;try{let Z=await HF(U,"utf8"),K={type:$.type,directoryPath:J.directoryPath,fileName:Q,filePath:U,content:Z},A=$.parseFile(K),W=$.resolveId(A,K).trim();if(!W)continue;Y.set(W,{type:$.type,id:W,item:A,filePath:U,fingerprint:IF(Z)})}catch(Z){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Z,filePath:U})}}}return{records:Y,discoveredDirectories:T}}buildDesiredTypesByDirectory(){let $=new Map;for(let[Y,T]of this.baseTypesByDirectory.entries())$.set(Y,new Set(T));for(let[Y,T]of this.discoveredDirectoriesByType.entries())for(let q of T){let X=$.get(q);if(X)X.add(Y);else $.set(q,new Set([Y]))}return $}async readDirectoryFileCandidates($){try{return(await NF($,{withFileTypes:!0})).filter((T)=>T.isFile()).map((T)=>({directoryPath:$,fileName:T.name,filePath:zF($,T.name)})).sort((T,q)=>T.fileName.localeCompare(q.fileName))}catch(Y){if(yQ(Y))return[];throw Y}}}function jQ(){return B9()}function BF($){if(Array.isArray($))return[...$];if(typeof $==="string")return[$];return jQ()}function m9($){return{type:"agent",directories:BF($),includeFile:(Y)=>SQ(Y),parseFile:(Y)=>GY(Y.content),resolveId:(Y)=>CQ(Y.name)}}function vQ($){return new f$([m9($?.directoryPathOrPaths)],{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{existsSync as RF,readdirSync as OF}from"node:fs";import{basename as PF,extname as LF,join as wF}from"node:path";function f9($){return R9($)}var q8;((K)=>{K.TaskStart="TaskStart";K.TaskResume="TaskResume";K.TaskCancel="TaskCancel";K.TaskComplete="TaskComplete";K.PreToolUse="PreToolUse";K.PostToolUse="PostToolUse";K.UserPromptSubmit="UserPromptSubmit";K.PreCompact="PreCompact";K.SessionShutdown="SessionShutdown"})(q8||={});var b9={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},SF=new Map(Object.values(q8).map(($)=>[$.toLowerCase(),$]));function u9($){let Y=PF($,LF($)).trim().toLowerCase();return SF.get(Y)}function X8($){let Y=[],T=new Set,q=f9($).filter((X)=>RF(X));for(let X of q)try{for(let J of OF(X,{withFileTypes:!0})){if(!J.isFile())continue;let Q=u9(J.name);if(!Q)continue;let U=wF(X,J.name);if(T.has(U))continue;T.add(U),Y.push({fileName:Q,hookEventName:b9[Q],path:U})}}catch{}return Y.sort((X,J)=>X.path.localeCompare(J.path))}import{existsSync as p9,readdirSync as hF,statSync as _F}from"node:fs";import{join as gF,resolve as gQ}from"node:path";import{resolve as CF}from"node:path";import{pathToFileURL as yF}from"node:url";function kQ($){return typeof $==="object"&&$!==null}function xQ($){return Array.isArray($)&&$.every((Y)=>typeof Y==="string")}function jF($,Y){if(!kQ($.manifest))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);if(!xQ($.manifest.capabilities))throw Error(`Invalid plugin module at ${Y}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${Y}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"hookStages")&&!xQ($.manifest.hookStages))throw Error(`Invalid plugin module at ${Y}: manifest.hookStages must be a string array when provided`)}function vF($,Y){if(!kQ($))throw Error(`Invalid plugin module at ${Y}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${Y}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);jF($,Y)}async function d9($,Y={}){let T=CF(Y.cwd??process.cwd(),$),q=await import(yF(T).href),X=Y.exportName??"plugin",J=q.default??q[X];return vF(J,T),J}async function J8($,Y={}){let T=[];for(let q of $)T.push(await d9(q,Y));return T}import{spawn as xF}from"node:child_process";function hQ($){if($ instanceof Error)return $;return Error(String($))}class Q8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}start(){if(this.process&&this.process.exitCode===null)return;let $=xF(process.execPath,["-e",this.options.bootstrapScript],{stdio:["ignore","ignore","ignore","ipc"]});this.process=$,$.on("message",(Y)=>{this.onMessage(Y)}),$.on("error",(Y)=>{this.failPending(Error(`${this.options.name??"sandbox"} process error: ${hQ(Y).message}`))}),$.on("exit",(Y,T)=>{this.process=null,this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Y)}, signal=${String(T)})`))})}async call($,Y,T={}){this.start();let q=this.process;if(!q||q.exitCode!==null)throw Error(`${this.options.name??"sandbox"} process is not available`);let X=`req_${++this.requestCounter}`,J={type:"call",id:X,method:$,args:Y};return await new Promise((Q,U)=>{let Z={resolve:(K)=>Q(K),reject:U};if((T.timeoutMs??0)>0)Z.timeout=setTimeout(()=>{this.pending.delete(X),this.shutdown().catch(()=>{}),U(Error(`${this.options.name??"sandbox"} call timed out after ${T.timeoutMs}ms: ${$}`))},T.timeoutMs);this.pending.set(X,Z),q.send(J,(K)=>{if(!K)return;let A=this.pending.get(X);if(!A)return;if(this.pending.delete(X),A.timeout)clearTimeout(A.timeout);A.reject(Error(`${this.options.name??"sandbox"} failed to send call "${$}": ${hQ(K).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.options.name??"sandbox"} shutdown`));return}await new Promise((Y)=>{let T=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Y()},300);$.once("exit",()=>{clearTimeout(T),Y()});try{$.kill("SIGTERM")}catch{clearTimeout(T),Y()}}),this.failPending(Error(`${this.options.name??"sandbox"} shutdown`))}onMessage($){if(!$||$.type!=="response"||!$.id)return;let Y=this.pending.get($.id);if(!Y)return;if(this.pending.delete($.id),Y.timeout)clearTimeout(Y.timeout);if($.ok){Y.resolve($.result);return}Y.reject(Error($.error?.message||`${this.options.name??"sandbox"} call failed`))}failPending($){for(let[Y,T]of this.pending.entries()){if(this.pending.delete(Y),T.timeout)clearTimeout(T.timeout);T.reject($)}}}var kF=`
|
|
116
116
|
const { pathToFileURL } = require("node:url");
|
|
117
117
|
let pluginCounter = 0;
|
|
118
118
|
const pluginState = new Map();
|
|
@@ -297,7 +297,7 @@ process.on("message", async (message) => {
|
|
|
297
297
|
sendResponse(message.id, false, undefined, toErrorPayload(error));
|
|
298
298
|
}
|
|
299
299
|
});
|
|
300
|
-
`;function e1($,Y){return $.manifest.hookStages?.includes(Y)===!0}function d9($,Y){return typeof $==="number"&&$>0?$:Y}async function xQ($){let Y=new J8({name:"plugin-sandbox",bootstrapScript:jF}),T=d9($.importTimeoutMs,4000),q=d9($.hookTimeoutMs,3000),X=d9($.contributionTimeoutMs,5000),J;try{J=await Y.call("initialize",{pluginPaths:$.pluginPaths,exportName:$.exportName},{timeoutMs:T})}catch(U){throw await Y.shutdown().catch(()=>{}),U}return{extensions:J.map((U)=>{let Z={name:U.name,manifest:U.manifest,setup:(K)=>{for(let A of U.contributions.tools){let W={name:A.name,description:A.description??"",inputSchema:A.inputSchema??{type:"object",properties:{}},timeoutMs:A.timeoutMs,retryable:A.retryable,execute:async(E,D)=>await Y.call("executeTool",{pluginId:U.pluginId,contributionId:A.id,input:E,context:D},{timeoutMs:X})};K.registerTool(W)}for(let A of U.contributions.commands)K.registerCommand({name:A.name,description:A.description,handler:async(W)=>await Y.call("executeCommand",{pluginId:U.pluginId,contributionId:A.id,input:W},{timeoutMs:X})});for(let A of U.contributions.shortcuts)K.registerShortcut({name:A.name,value:A.value??"",description:A.description});for(let A of U.contributions.flags)K.registerFlag({name:A.name,description:A.description,defaultValue:A.defaultValue});for(let A of U.contributions.messageRenderers)K.registerMessageRenderer({name:A.name,render:()=>`[sandbox renderer ${A.name} requires async bridge]`});for(let A of U.contributions.providers)K.registerProvider({name:A.name,description:A.description,metadata:A.metadata})}};if(e1(Z,"input"))Z.onInput=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onInput",payload:K},{timeoutMs:q});if(e1(Z,"session_start"))Z.onSessionStart=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionStart",payload:K},{timeoutMs:q});if(e1(Z,"before_agent_start"))Z.onBeforeAgentStart=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onBeforeAgentStart",payload:K},{timeoutMs:q});if(e1(Z,"tool_call_before"))Z.onToolCall=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolCall",payload:K},{timeoutMs:q});if(e1(Z,"tool_call_after"))Z.onToolResult=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolResult",payload:K},{timeoutMs:q});if(e1(Z,"turn_end"))Z.onAgentEnd=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onAgentEnd",payload:K},{timeoutMs:q});if(e1(Z,"session_shutdown"))Z.onSessionShutdown=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionShutdown",payload:K},{timeoutMs:q});if(e1(Z,"runtime_event"))Z.onRuntimeEvent=async(K)=>{await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onRuntimeEvent",payload:K},{timeoutMs:q})};if(e1(Z,"error"))Z.onError=async(K)=>{await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onError",payload:K},{timeoutMs:q})};return Z}),shutdown:async()=>{await Y.shutdown()}}}var hQ=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function p9($){return P9($)}function _Q($){let Y=$.lastIndexOf(".");if(Y===-1)return!1;return hQ.has($.slice(Y))}function Q8($){let Y=kQ($);if(!c9(Y))return[];let T=[],q=[Y];while(q.length>0){let X=q.pop();if(!X)continue;for(let J of vF(X,{withFileTypes:!0})){let Q=kF(X,J.name);if(J.isDirectory()){q.push(Q);continue}if(J.isFile()&&_Q(Q))T.push(Q)}}return T.sort((X,J)=>X.localeCompare(J))}function hF($,Y){let T=[];for(let q of $){let X=q.trim();if(!X)continue;let J=kQ(Y,X);if(!c9(J))throw Error(`Plugin path does not exist: ${J}`);if(xF(J).isDirectory()){T.push(...Q8(J));continue}if(!_Q(J))throw Error(`Plugin file must use a supported extension (${[...hQ].join(", ")}): ${J}`);T.push(J)}return T}function l9($={}){let Y=$.cwd??process.cwd(),T=p9($.workspacePath).flatMap((Q)=>Q8(Q)).filter((Q)=>c9(Q)),q=hF($.pluginPaths??[],Y),X=[],J=new Set;for(let Q of[...q,...T]){if(J.has(Q))continue;J.add(Q),X.push(Q)}return X}async function U8($={}){let Y=l9($);if(Y.length===0)return{extensions:[]};if($.mode==="in_process")return{extensions:await X8(Y,{cwd:$.cwd,exportName:$.exportName})};let T=await xQ({pluginPaths:Y,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs});return{extensions:T.extensions??[],shutdown:T.shutdown}}import{readdir as gQ,stat as _F}from"node:fs/promises";import{basename as G8,dirname as gF,extname as n9,join as Z8}from"node:path";import mF from"yaml";var K8="SKILL.md",fF=new Set([".md",".markdown",".txt"]);function i9($){return $.trim().toLowerCase()}function A8($){return fF.has(n9($).toLowerCase())}function r9($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T=$.match(Y);if(!T)return{data:{},body:$,hadFrontmatter:!1};let[,q,X]=T;try{let J=mF.parse(q);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function W8($,Y,T){if($===void 0||$===null){if(T)throw Error(`Missing required frontmatter field '${Y}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${Y}' must be a string.`);let q=$.trim();if(!q&&T)throw Error(`Frontmatter field '${Y}' cannot be empty.`);return q||void 0}function EY($,Y){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${Y}' must be a boolean.`);return $}function a9($,Y){let{data:T,body:q,parseError:X}=r9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in skill file.");let U=W8(T.name,"name",!1)??Y.trim();if(!U)throw Error("Missing skill name.");return{name:U,description:W8(T.description,"description",!1),disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function o9($,Y){let{data:T,body:q,parseError:X}=r9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in rule file.");let Q=W8(T.name,"name",!1)??Y.trim();if(!Q)throw Error("Missing rule name.");return{name:Q,disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function s9($,Y){let{data:T,body:q,parseError:X}=r9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in workflow file.");let Q=W8(T.name,"name",!1)??Y.trim();if(!Q)throw Error("Missing workflow name.");return{name:Q,disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function t9($){return DT($)}function e9($){return R9($)}function $4($){return O9($)}async function bF($){try{let Y=await gQ($,{withFileTypes:!0}),T=[];for(let q of Y){if(q.isFile()&&q.name===K8){T.push({directoryPath:$,fileName:q.name,filePath:Z8($,q.name)});continue}if(q.isDirectory())T.push({directoryPath:Z8($,q.name),fileName:K8,filePath:Z8($,q.name,K8)})}return T}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}async function mQ($){try{if((await _F($)).isFile())return[{directoryPath:gF($),fileName:G8($),filePath:$}]}catch(Y){if(Y.code!=="ENOENT")throw Y}try{return(await gQ($,{withFileTypes:!0})).filter((T)=>T.isFile()&&A8(T.name)).map((T)=>({directoryPath:$,fileName:T.name,filePath:Z8($,T.name)}))}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}function Y4($){return{type:"skill",directories:$?.directories??t9($?.workspacePath),discoverFiles:bF,includeFile:(T)=>T===K8,parseFile:(T)=>a9(T.content,G8(T.directoryPath)),resolveId:(T)=>i9(T.name)}}function T4($){return{type:"rule",directories:$?.directories??e9($?.workspacePath),discoverFiles:mQ,includeFile:(T,q)=>T===".clinerules"||A8(T)||A8(q),parseFile:(T)=>o9(T.content,G8(T.filePath,n9(T.filePath))),resolveId:(T)=>i9(T.name)}}function q4($){return{type:"workflow",directories:$?.directories??$4($?.workspacePath),discoverFiles:mQ,includeFile:(T)=>A8(T),parseFile:(T)=>s9(T.content,G8(T.filePath,n9(T.filePath))),resolveId:(T)=>i9(T.name)}}function E8($){let Y=[Y4($?.skills),T4($?.rules),q4($?.workflows)];return new f$(Y,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}function X4($){return{onAuth:({url:Y,instructions:T})=>{if($.onOutput?.(T??"Complete sign-in in your browser."),$.openUrl)Promise.resolve($.openUrl(Y)).catch((q)=>{$.onOpenUrlError?.({url:Y,error:q})});$.onOutput?.(Y)},onPrompt:$.onPrompt}}function uF(){let $;return{promise:new Promise((T)=>{$=T}),resolve:$}}async function b$($){let Y=await import("node:http"),T=$.host??"127.0.0.1",q=$.timeoutMs??300000,X=$.successHtml??dF,J=uF(),Q=!1,U=null,Z=null,K=(E)=>{if(Q)return;Q=!0,J.resolve(E)},A=()=>{if(U)clearTimeout(U),U=null;if(Z)Z.close(),Z=null},W=async()=>{return U=setTimeout(()=>{A(),K(null)},q),J.promise};for(let E of $.ports){let D=Y.createServer((H,V)=>{try{let B=new URL(H.url||"",`http://${T}:${E}`);if(B.pathname!==$.callbackPath){V.statusCode=404,V.end("Not found");return}let S={url:B,code:B.searchParams.get("code")??void 0,state:B.searchParams.get("state")??void 0,provider:B.searchParams.get("provider")??void 0,error:B.searchParams.get("error")??void 0};if(S.error){V.statusCode=400,V.end(`Authentication failed: ${S.error}`),A(),K(S);return}if(!S.code){V.statusCode=400,V.end("Missing authorization code");return}if($.expectedState&&S.state!==$.expectedState){V.statusCode=400,V.end("State mismatch");return}V.statusCode=200,V.setHeader("Content-Type","text/html; charset=utf-8"),V.end(X),A(),K(S)}catch{V.statusCode=500,V.end("Internal error")}}),F=await new Promise((H)=>{let V=(B)=>{D.off("error",V),H({bound:!1,error:B})};D.once("error",V),D.listen(E,T,()=>{D.off("error",V),Z=D,H({bound:!0})})});if(F.error){if(F.error.code==="EADDRINUSE")continue;throw A(),F.error}if(F.bound)return{callbackUrl:`http://${T}:${E}${$.callbackPath}`,waitForCallback:W,cancelWait:()=>{A(),K(null)},close:()=>{A(),K(null)}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var dF=`<!DOCTYPE html>
|
|
300
|
+
`;function e1($,Y){return $.manifest.hookStages?.includes(Y)===!0}function c9($,Y){return typeof $==="number"&&$>0?$:Y}async function _Q($){let Y=new Q8({name:"plugin-sandbox",bootstrapScript:kF}),T=c9($.importTimeoutMs,4000),q=c9($.hookTimeoutMs,3000),X=c9($.contributionTimeoutMs,5000),J;try{J=await Y.call("initialize",{pluginPaths:$.pluginPaths,exportName:$.exportName},{timeoutMs:T})}catch(U){throw await Y.shutdown().catch(()=>{}),U}return{extensions:J.map((U)=>{let Z={name:U.name,manifest:U.manifest,setup:(K)=>{for(let A of U.contributions.tools){let W={name:A.name,description:A.description??"",inputSchema:A.inputSchema??{type:"object",properties:{}},timeoutMs:A.timeoutMs,retryable:A.retryable,execute:async(E,V)=>await Y.call("executeTool",{pluginId:U.pluginId,contributionId:A.id,input:E,context:V},{timeoutMs:X})};K.registerTool(W)}for(let A of U.contributions.commands)K.registerCommand({name:A.name,description:A.description,handler:async(W)=>await Y.call("executeCommand",{pluginId:U.pluginId,contributionId:A.id,input:W},{timeoutMs:X})});for(let A of U.contributions.shortcuts)K.registerShortcut({name:A.name,value:A.value??"",description:A.description});for(let A of U.contributions.flags)K.registerFlag({name:A.name,description:A.description,defaultValue:A.defaultValue});for(let A of U.contributions.messageRenderers)K.registerMessageRenderer({name:A.name,render:()=>`[sandbox renderer ${A.name} requires async bridge]`});for(let A of U.contributions.providers)K.registerProvider({name:A.name,description:A.description,metadata:A.metadata})}};if(e1(Z,"input"))Z.onInput=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onInput",payload:K},{timeoutMs:q});if(e1(Z,"session_start"))Z.onSessionStart=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionStart",payload:K},{timeoutMs:q});if(e1(Z,"before_agent_start"))Z.onBeforeAgentStart=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onBeforeAgentStart",payload:K},{timeoutMs:q});if(e1(Z,"tool_call_before"))Z.onToolCall=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolCall",payload:K},{timeoutMs:q});if(e1(Z,"tool_call_after"))Z.onToolResult=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolResult",payload:K},{timeoutMs:q});if(e1(Z,"turn_end"))Z.onAgentEnd=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onAgentEnd",payload:K},{timeoutMs:q});if(e1(Z,"session_shutdown"))Z.onSessionShutdown=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionShutdown",payload:K},{timeoutMs:q});if(e1(Z,"runtime_event"))Z.onRuntimeEvent=async(K)=>{await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onRuntimeEvent",payload:K},{timeoutMs:q})};if(e1(Z,"error"))Z.onError=async(K)=>{await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onError",payload:K},{timeoutMs:q})};return Z}),shutdown:async()=>{await Y.shutdown()}}}var mQ=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function l9($){return L9($)}function fQ($){let Y=$.lastIndexOf(".");if(Y===-1)return!1;return mQ.has($.slice(Y))}function U8($){let Y=gQ($);if(!p9(Y))return[];let T=[],q=[Y];while(q.length>0){let X=q.pop();if(!X)continue;for(let J of hF(X,{withFileTypes:!0})){let Q=gF(X,J.name);if(J.isDirectory()){q.push(Q);continue}if(J.isFile()&&fQ(Q))T.push(Q)}}return T.sort((X,J)=>X.localeCompare(J))}function mF($,Y){let T=[];for(let q of $){let X=q.trim();if(!X)continue;let J=gQ(Y,X);if(!p9(J))throw Error(`Plugin path does not exist: ${J}`);if(_F(J).isDirectory()){T.push(...U8(J));continue}if(!fQ(J))throw Error(`Plugin file must use a supported extension (${[...mQ].join(", ")}): ${J}`);T.push(J)}return T}function n9($={}){let Y=$.cwd??process.cwd(),T=l9($.workspacePath).flatMap((Q)=>U8(Q)).filter((Q)=>p9(Q)),q=mF($.pluginPaths??[],Y),X=[],J=new Set;for(let Q of[...q,...T]){if(J.has(Q))continue;J.add(Q),X.push(Q)}return X}async function Z8($={}){let Y=n9($);if(Y.length===0)return{extensions:[]};if($.mode==="in_process")return{extensions:await J8(Y,{cwd:$.cwd,exportName:$.exportName})};let T=await _Q({pluginPaths:Y,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs});return{extensions:T.extensions??[],shutdown:T.shutdown}}import{readdir as bQ,stat as fF}from"node:fs/promises";import{basename as E8,dirname as bF,extname as i9,join as K8}from"node:path";import uF from"yaml";var A8="SKILL.md",dF=new Set([".md",".markdown",".txt"]);function r9($){return $.trim().toLowerCase()}function W8($){return dF.has(i9($).toLowerCase())}function a9($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T=$.match(Y);if(!T)return{data:{},body:$,hadFrontmatter:!1};let[,q,X]=T;try{let J=uF.parse(q);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function G8($,Y,T){if($===void 0||$===null){if(T)throw Error(`Missing required frontmatter field '${Y}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${Y}' must be a string.`);let q=$.trim();if(!q&&T)throw Error(`Frontmatter field '${Y}' cannot be empty.`);return q||void 0}function EY($,Y){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${Y}' must be a boolean.`);return $}function o9($,Y){let{data:T,body:q,parseError:X}=a9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in skill file.");let U=G8(T.name,"name",!1)??Y.trim();if(!U)throw Error("Missing skill name.");return{name:U,description:G8(T.description,"description",!1),disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function s9($,Y){let{data:T,body:q,parseError:X}=a9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in rule file.");let Q=G8(T.name,"name",!1)??Y.trim();if(!Q)throw Error("Missing rule name.");return{name:Q,disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function t9($,Y){let{data:T,body:q,parseError:X}=a9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in workflow file.");let Q=G8(T.name,"name",!1)??Y.trim();if(!Q)throw Error("Missing workflow name.");return{name:Q,disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function e9($){return D6($)}function $4($){return O9($)}function Y4($){return P9($)}async function cF($){try{let Y=await bQ($,{withFileTypes:!0}),T=[];for(let q of Y){if(q.isFile()&&q.name===A8){T.push({directoryPath:$,fileName:q.name,filePath:K8($,q.name)});continue}if(q.isDirectory())T.push({directoryPath:K8($,q.name),fileName:A8,filePath:K8($,q.name,A8)})}return T}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}async function uQ($){try{if((await fF($)).isFile())return[{directoryPath:bF($),fileName:E8($),filePath:$}]}catch(Y){if(Y.code!=="ENOENT")throw Y}try{return(await bQ($,{withFileTypes:!0})).filter((T)=>T.isFile()&&W8(T.name)).map((T)=>({directoryPath:$,fileName:T.name,filePath:K8($,T.name)}))}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}function T4($){return{type:"skill",directories:$?.directories??e9($?.workspacePath),discoverFiles:cF,includeFile:(T)=>T===A8,parseFile:(T)=>o9(T.content,E8(T.directoryPath)),resolveId:(T)=>r9(T.name)}}function q4($){return{type:"rule",directories:$?.directories??$4($?.workspacePath),discoverFiles:uQ,includeFile:(T,q)=>T===".clinerules"||W8(T)||W8(q),parseFile:(T)=>s9(T.content,E8(T.filePath,i9(T.filePath))),resolveId:(T)=>r9(T.name)}}function X4($){return{type:"workflow",directories:$?.directories??Y4($?.workspacePath),discoverFiles:uQ,includeFile:(T)=>W8(T),parseFile:(T)=>t9(T.content,E8(T.filePath,i9(T.filePath))),resolveId:(T)=>r9(T.name)}}function V8($){let Y=[T4($?.skills),q4($?.rules),X4($?.workflows)];return new f$(Y,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}function J4($){return{onAuth:({url:Y,instructions:T})=>{if($.onOutput?.(T??"Complete sign-in in your browser."),$.openUrl)Promise.resolve($.openUrl(Y)).catch((q)=>{$.onOpenUrlError?.({url:Y,error:q})});$.onOutput?.(Y)},onPrompt:$.onPrompt}}function pF(){let $;return{promise:new Promise((T)=>{$=T}),resolve:$}}async function b$($){let Y=await import("node:http"),T=$.host??"127.0.0.1",q=$.timeoutMs??300000,X=$.successHtml??lF,J=pF(),Q=!1,U=null,Z=null,K=(E)=>{if(Q)return;Q=!0,J.resolve(E)},A=()=>{if(U)clearTimeout(U),U=null;if(Z)Z.close(),Z=null},W=async()=>{return U=setTimeout(()=>{A(),K(null)},q),J.promise};for(let E of $.ports){let V=Y.createServer((H,D)=>{try{let I=new URL(H.url||"",`http://${T}:${E}`);if(I.pathname!==$.callbackPath){D.statusCode=404,D.end("Not found");return}let S={url:I,code:I.searchParams.get("code")??void 0,state:I.searchParams.get("state")??void 0,provider:I.searchParams.get("provider")??void 0,error:I.searchParams.get("error")??void 0};if(S.error){D.statusCode=400,D.end(`Authentication failed: ${S.error}`),A(),K(S);return}if(!S.code){D.statusCode=400,D.end("Missing authorization code");return}if($.expectedState&&S.state!==$.expectedState){D.statusCode=400,D.end("State mismatch");return}D.statusCode=200,D.setHeader("Content-Type","text/html; charset=utf-8"),D.end(X),A(),K(S)}catch{D.statusCode=500,D.end("Internal error")}}),F=await new Promise((H)=>{let D=(I)=>{V.off("error",D),H({bound:!1,error:I})};V.once("error",D),V.listen(E,T,()=>{V.off("error",D),Z=V,H({bound:!0})})});if(F.error){if(F.error.code==="EADDRINUSE")continue;throw A(),F.error}if(F.bound)return{callbackUrl:`http://${T}:${E}${$.callbackPath}`,waitForCallback:W,cancelWait:()=>{A(),K(null)},close:()=>{A(),K(null)}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var lF=`<!DOCTYPE html>
|
|
301
301
|
<html lang="en">
|
|
302
302
|
<head>
|
|
303
303
|
<meta charset="utf-8">
|
|
@@ -338,8 +338,8 @@ process.on("message", async (message) => {
|
|
|
338
338
|
</div>
|
|
339
339
|
<script>setTimeout(() => window.close(), 3000);</script>
|
|
340
340
|
</body>
|
|
341
|
-
</html>`;function fQ($){let Y="";for(let T=0;T<$.length;T+=1)Y+=String.fromCharCode($[T]??0);return btoa(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function cF($){let T=new TextEncoder().encode($),q=await crypto.subtle.digest("SHA-256",T);return new Uint8Array(q)}function pF($=32){let Y=new Uint8Array($);return crypto.getRandomValues(Y),fQ(Y)}async function V8(){let $=pF(),Y=fQ(await cF($));return{verifier:$,challenge:Y}}function D8($){return $.endsWith("/")?$.slice(0,-1):$}function F8($,Y){return new URL(Y,`${D8($)}/`).toString()}function VY($,Y={}){let T=$.trim();if(!T)return{};try{let q=new URL(T);return{code:q.searchParams.get("code")??void 0,state:q.searchParams.get("state")??void 0,provider:Y.includeProvider?q.searchParams.get("provider")??void 0:void 0}}catch{}if(Y.allowHashCodeState&&T.includes("#")){let[q,X]=T.split("#",2);return{code:q||void 0,state:X||void 0}}if(T.includes("code=")){let q=new URLSearchParams(T);return{code:q.get("code")??void 0,state:q.get("state")??void 0,provider:Y.includeProvider?q.get("provider")??void 0:void 0}}return{code:T}}function lF($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function W1($){if(!$)return null;try{let Y=$.split(".");if(Y.length!==3)return null;let T=Y[1];if(!T)return null;let q=T.replace(/-/g,"+").replace(/_/g,"/"),X=q.padEnd(q.length+(4-q.length%4)%4,"="),J=lF(X);if(!J)return null;return JSON.parse(J)}catch{return null}}function HT($){try{let Y=JSON.parse($),T=Y.error,q=typeof T==="string"?T:T&&typeof T==="object"&&typeof T.type==="string"?T.type:void 0,X=typeof Y.error_description==="string"?Y.error_description:typeof Y.message==="string"?Y.message:T&&typeof T==="object"&&typeof T.message==="string"?T.message:void 0;return{code:q,message:X}}catch{return{}}}function u$($,Y){return Date.now()>=$.expires-Y}async function DY($){if(!$.onManualCodeInput){let J=await $.waitForCallback();return{code:J?.code,state:J?.state,provider:J?.provider,error:J?.error}}let Y,T,q=$.onManualCodeInput().then((J)=>{Y=J,$.cancelWait()}).catch((J)=>{T=J instanceof Error?J:Error(String(J)),$.cancelWait()}),X=await $.waitForCallback();if(T)throw T;if(X?.code||X?.error)return{code:X.code,state:X.state,provider:X.provider,error:X.error};if(Y)return VY(Y,$.parseOptions);if(await q,T)throw T;if(Y)return VY(Y,$.parseOptions);return{}}var J4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",refresh:"/api/v1/auth/refresh"},nF="/auth",bQ=Array.from({length:11},($,Y)=>48801+Y),iF=300000,rF=30000,Q4=30000;class N8 extends Error{status;errorCode;constructor($,Y){super($);this.name="ClineOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function aF(){let $=globalThis.crypto;if(!$)return Math.random().toString(16).slice(2);let Y=new Uint8Array(16);return $.getRandomValues(Y),Array.from(Y,(T)=>T.toString(16).padStart(2,"0")).join("")}function oF($){let Y=Date.parse($);if(Number.isNaN(Y))throw Error(`Invalid expiresAt value: ${$}`);return Y}function uQ($,Y,T={}){let q=$.userInfo.clineUserId??T.accountId,X=$.refreshToken??T.refresh;if(!X)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:X,expires:oF($.expiresAt),accountId:q??void 0,email:$.userInfo.email||T.email,metadata:{provider:Y,tokenType:$.tokenType,userInfo:$.userInfo}}}async function U4($){if(!$)return{};return typeof $==="function"?await $():$}async function sF($,Y){let T=new URL(F8($.apiBaseUrl,J4.authorize));T.searchParams.set("client_type","extension"),T.searchParams.set("callback_url",Y.callbackUrl),T.searchParams.set("redirect_uri",Y.callbackUrl),T.searchParams.set("state",Y.state);let q=await fetch(T.toString(),{method:"GET",redirect:"manual",headers:await U4($.headers),signal:AbortSignal.timeout($.requestTimeoutMs??Q4)});if(q.status>=300&&q.status<400){let J=q.headers.get("location");if(J)return J}if(!q.ok){let J=await q.text().catch(()=>"");throw Error(`Authentication request failed: ${q.status} ${J}`)}let X=await q.json();if(typeof X.redirect_url==="string"&&X.redirect_url.length>0)return X.redirect_url;throw Error("Authentication request did not return a redirect URL")}async function tF($,Y,T,q){let X={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:Y,provider:q??T.provider},J=await fetch(F8(T.apiBaseUrl,J4.token),{method:"POST",headers:{"Content-Type":"application/json",...await U4(T.headers)},body:JSON.stringify(X),signal:AbortSignal.timeout(T.requestTimeoutMs??Q4)});if(!J.ok){let U=await J.text().catch(()=>""),Z=HT(U);throw new N8(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let Q=await J.json();if(!Q.success||!Q.data?.accessToken)throw Error("Invalid token exchange response");return uQ(Q.data,q??T.provider)}async function H8($){let Y=$.callbackPorts?.length?$.callbackPorts:bQ,T=$.callbackPath??nF,q=aF(),X=await b$({ports:Y,callbackPath:T}),J=X.callbackUrl||`http://127.0.0.1:${Y[0]??bQ[0]}${T}`,Q=await sF($,{callbackUrl:J,state:q});$.callbacks.onAuth({url:Q,instructions:"Continue the authentication process in your browser."});try{let U,Z=$.provider,K=await DY({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(K.error)throw Error(`OAuth error: ${K.error}`);if(K.state&&K.state!==q)throw Error("State mismatch");if(U=K.code,Z=K.provider??Z,!U){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),W=VY(A,{includeProvider:!0});if(W.state&&W.state!==q)throw Error("State mismatch");U=W.code,Z=W.provider??Z}if(!U)throw Error("Missing authorization code");return tF(U,J,$,Z)}finally{X.close()}}async function Z4($,Y){let T=await fetch(F8(Y.apiBaseUrl,J4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await U4(Y.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(Y.requestTimeoutMs??Q4)});if(!T.ok){let J=await T.text().catch(()=>""),Q=HT(J);throw new N8(`Token refresh failed: ${T.status}${Q.message?` - ${Q.message}`:""}`,{status:T.status,errorCode:Q.code})}let q=await T.json();if(!q.success||!q.data?.accessToken)throw Error("Invalid token refresh response");let X=$.metadata?.provider??Y.provider;return uQ(q.data,X,$)}async function K4($,Y,T){if(!$)return null;let q=T?.refreshBufferMs??iF,X=T?.retryableTokenGraceMs??rF;if(T?.forceRefresh!==!0&&!u$($,q))return $;try{return await Z4($,Y)}catch(Q){if(Q instanceof N8&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function eF($){return{id:"cline",name:"Cline Account",usesCallbackServer:!0,async login(Y){return H8({...$,callbacks:Y})},async refreshToken(Y){return Z4(Y,$)},getApiKey(Y){return`workos:${Y.access}`}}}import{nanoid as $N}from"nanoid";var z0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class z8 extends Error{status;errorCode;constructor($,Y){super($);this.name="OpenAICodexOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function YN($,Y,T=z0.redirectUri){let q=await fetch(z0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:z0.clientId,code:$,code_verifier:Y,redirect_uri:T}),signal:AbortSignal.timeout(z0.httpTimeoutMs)});if(!q.ok)return{type:"failed"};let X=await q.json();if(!X.access_token||!X.refresh_token||typeof X.expires_in!=="number")return{type:"failed"};return{type:"success",access:X.access_token,refresh:X.refresh_token,expires:Date.now()+X.expires_in*1000,email:X.email,idToken:X.id_token}}async function TN($){try{let Y=await fetch(z0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:z0.clientId}),signal:AbortSignal.timeout(z0.httpTimeoutMs)});if(!Y.ok){let q=await Y.text().catch(()=>""),X=HT(q);throw new z8(`Token refresh failed: ${Y.status}${X.message?` - ${X.message}`:""}`,{status:Y.status,errorCode:X.code})}let T=await Y.json();if(!T.access_token||!T.refresh_token||typeof T.expires_in!=="number")return{type:"failed"};return{type:"success",access:T.access_token,refresh:T.refresh_token,expires:Date.now()+T.expires_in*1000,email:T.email,idToken:T.id_token}}catch(Y){if(Y instanceof z8)throw Y;return{type:"failed"}}}async function qN($="pi"){let{verifier:Y,challenge:T}=await V8(),q=$N(32),X=new URL(z0.authorizationEndpoint);return X.searchParams.set("response_type","code"),X.searchParams.set("client_id",z0.clientId),X.searchParams.set("redirect_uri",z0.redirectUri),X.searchParams.set("scope",z0.scopes),X.searchParams.set("code_challenge",T),X.searchParams.set("code_challenge_method","S256"),X.searchParams.set("state",q),X.searchParams.set("id_token_add_organizations","true"),X.searchParams.set("codex_cli_simplified_flow","true"),X.searchParams.set("originator",$),{verifier:Y,state:q,url:X.toString()}}function XN(){try{let $=new URL(z0.redirectUri),Y=$.port.length>0?Number.parseInt($.port,10):z0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(Y)?Y:z0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:z0.callbackPort,callbackPath:"/auth/callback",redirectUri:z0.redirectUri}}}function dQ($,Y){let T=Y?W1(Y):W1($),q=T?T:W1($),J=q?.[z0.jwtClaimPath]?.chatgpt_account_id;if(typeof J==="string"&&J.length>0)return J;let Q=q?.organizations;if(Array.isArray(Q)&&Q.length>0){let Z=Q[0];if(typeof Z?.id==="string"&&Z.id.length>0)return Z.id}let U=q?.chatgpt_account_id;if(typeof U==="string"&&U.length>0)return U;return null}function cQ($,Y){let T=dQ($.access,$.idToken)??Y?.accountId;if(!T)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||Y?.refresh||"",expires:$.expires,accountId:T,email:$.email??Y?.email,metadata:{...Y?.metadata??{},provider:"openai-codex"}}}async function I8($){let Y=XN(),{verifier:T,state:q,url:X}=await qN($.originator),J=await b$({host:Y.host,ports:[Y.port],callbackPath:Y.callbackPath,expectedState:q});$.onAuth({url:X,instructions:"Continue the authentication process in your browser."});let Q;try{let U=await DY({waitForCallback:J.waitForCallback,cancelWait:J.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(U.state&&U.state!==q)throw Error("State mismatch");if(Q=U.code,!Q){let K=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=VY(K,{allowHashCodeState:!0});if(A.state&&A.state!==q)throw Error("State mismatch");Q=A.code}if(!Q)throw Error("Missing authorization code");let Z=await YN(Q,T,Y.redirectUri);if(Z.type!=="success")throw Error("Token exchange failed");return cQ(Z)}finally{J.close()}}async function A4($,Y){let T=await TN($);if(T.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let q=cQ(T,Y);if(!q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return q}async function W4($,Y){if(!$)return null;let T=Y?.refreshBufferMs??z0.refreshBufferMs,q=Y?.retryableTokenGraceMs??z0.retryableTokenGraceMs;if(Y?.forceRefresh!==!0&&!u$($,T))return $;try{return await A4($.refresh,$)}catch(J){if(J instanceof z8&&J.isLikelyInvalidGrant())return null;if($.expires-Date.now()>q)return $;return null}}function JN($,Y=z0.refreshBufferMs){return u$($,Y)}function QN($){let Y=$.accountId??dQ($.access);if(!Y)throw Error("Failed to extract accountId from token");return{...$,accountId:Y,metadata:{...$.metadata??{},provider:"openai-codex"}}}var UN={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return I8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return A4($.refresh,$)},getApiKey($){return $.access}};import{nanoid as pQ}from"nanoid";var lQ="a8331954c0cf48ba99b5dd223a14c6ea",nQ="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",iQ="openid offline_access",rQ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",aQ="c1aba3deed5740659981a752714eba33",oQ="https://login-ext.identity.oraclecloud.com",sQ="openid offline_access",tQ="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",eQ="opc-request-id",ZN="/auth/oca",KN=Array.from({length:11},($,Y)=>48801+Y),AN=300000,WN=30000,$U=30000,GN=600000;class M8 extends Error{status;errorCode;constructor($,Y){super($);this.name="OcaOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var F$={internal:{clientId:lQ,idcsUrl:nQ,scopes:iQ,baseUrl:rQ},external:{clientId:aQ,idcsUrl:oQ,scopes:sQ,baseUrl:tQ}},zT=new Map,G4=new Map;function YU($){if(typeof $==="function")return $();return $??"internal"}function TU($){return{internal:{clientId:$?.internal?.clientId??F$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??F$.internal.idcsUrl,scopes:$?.internal?.scopes??F$.internal.scopes,baseUrl:$?.internal?.baseUrl??F$.internal.baseUrl},external:{clientId:$?.external?.clientId??F$.external.clientId,idcsUrl:$?.external?.idcsUrl??F$.external.idcsUrl,scopes:$?.external?.scopes??F$.external.scopes,baseUrl:$?.external?.baseUrl??F$.external.baseUrl}}}function EN($=Date.now()){let Y=$-GN;for(let[T,q]of zT.entries())if(q.createdAt<Y)zT.delete(T)}function VN($,Y,T){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let X=W1(Y)?.exp;if(typeof X==="number"&&X>0)return X*1000;let Q=W1(T)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return Date.now()+3600000}function qU($,Y,T){let q=$.access_token;if(!q)throw Error("Token response did not include an access token");let X=$.refresh_token??T?.refresh;if(!X)throw Error("Token response did not include a refresh token");let J=W1($.id_token),Q=W1(q),U=J?.sub??Q?.sub,Z=J?.email??Q?.email;return{access:q,refresh:X,expires:VN($,q,$.id_token),accountId:U??T?.accountId,email:Z??T?.email,metadata:{...T?.metadata??{},provider:"oca",mode:Y,subject:U,idToken:$.id_token}}}async function XU($,Y){let T=D8($),q=G4.get(T);if(q)return q;let X=`${T}/.well-known/openid-configuration`,J=await fetch(X,{method:"GET",signal:AbortSignal.timeout(Y)});if(!J.ok){let Z=`${T}/oauth2/v1/token`;return G4.set(T,Z),Z}let U=(await J.json()).token_endpoint||`${T}/oauth2/v1/token`;return G4.set(T,U),U}function JU($){return{code:$.error,message:$.error_description}}async function DN($){let Y=zT.get($.state);if(!Y)throw Error("No PKCE verifier found for this state");zT.delete($.state);let T=$.mode==="external"?$.config.external:$.config.internal,q=await XU(T.idcsUrl,$.requestTimeoutMs),X=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:Y.redirectUri,client_id:T.clientId,code_verifier:Y.verifier}),J=await fetch(q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout($.requestTimeoutMs)}),Q=await J.json();if(!J.ok){let Z=JU(Q);throw new M8(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let U=W1(Q.id_token);if(!Q.id_token||!U)throw Error("No ID token received from OCA");if(U.nonce!==Y.nonce)throw Error("OIDC nonce verification failed");return qU(Q,$.mode)}function FN($){let Y=$.mode==="external"?$.config.external:$.config.internal,T=new URL(`${D8(Y.idcsUrl)}/oauth2/v1/authorize`);return T.searchParams.set("client_id",Y.clientId),T.searchParams.set("response_type","code"),T.searchParams.set("scope",Y.scopes),T.searchParams.set("code_challenge",$.challenge),T.searchParams.set("code_challenge_method","S256"),T.searchParams.set("redirect_uri",$.callbackUrl),T.searchParams.set("state",$.state),T.searchParams.set("nonce",$.nonce),T.toString()}async function B8($){let Y=TU($.config),T=YU($.mode),q=$.callbackPorts?.length?$.callbackPorts:KN,X=$.callbackPath??ZN,J=$.requestTimeoutMs??$U,Q=await b$({ports:q,callbackPath:X}),U=Q.callbackUrl;if(!U)throw Error("Unable to bind local OAuth callback server");let Z=pQ(16),K=pQ(16),{verifier:A,challenge:W}=await V8();EN(),zT.set(Z,{verifier:A,nonce:K,mode:T,redirectUri:U,createdAt:Date.now()});let E=FN({callbackUrl:U,mode:T,state:Z,nonce:K,challenge:W,config:Y});$.callbacks.onAuth({url:E,instructions:"Continue the authentication process in your browser."});try{let D=await DY({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),F=D.code,H=D.state;if(D.error)throw Error(`OAuth error: ${D.error}`);if(!F){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!H||H!==Z)throw Error("State mismatch");return await DN({code:F,state:H,mode:T,config:Y,requestTimeoutMs:J})}finally{Q.close()}}async function E4($,Y={}){let T=TU(Y.config),q=Y.requestTimeoutMs??$U,X=$.metadata?.mode,J=X==="internal"||X==="external"?X:YU(Y.mode),Q=J==="external"?T.external:T.internal,U=await XU(Q.idcsUrl,q),Z=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:Q.clientId}),K=await fetch(U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(q)}),A=await K.json();if(!K.ok){let W=JU(A);throw new M8(`Token refresh failed: ${K.status}${W.message?` - ${W.message}`:""}`,{status:K.status,errorCode:W.code})}return qU(A,J,$)}async function V4($,Y,T){if(!$)return null;let q=Y?.refreshBufferMs??T?.refreshBufferMs??AN,X=Y?.retryableTokenGraceMs??T?.retryableTokenGraceMs??WN;if(Y?.forceRefresh!==!0&&!u$($,q))return $;try{return await E4($,T)}catch(Q){if(Q instanceof M8&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function NN($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(Y){return B8({...$,callbacks:Y})},async refreshToken(Y){return E4(Y,$)},getApiKey(Y){return Y.access}}}async function QU($,Y){let T=new TextEncoder,q=async(K)=>{let A=await crypto.subtle.digest("SHA-256",T.encode(K));return Array.from(new Uint8Array(A).slice(0,4),(W)=>W.toString(16).padStart(2,"0")).join("")},[X,J]=await Promise.all([q(Y),q($)]),Q=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),U=new Uint32Array(1);crypto.getRandomValues(U);let Z=(U[0]??0).toString(16).padStart(8,"0");return X+J+Q+Z}async function HN($){let Y=await QU($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[eQ]:Y}}import{createTool as Uh,getClineDefaultSystemPrompt as Zh}from"@clinebot/agents";class D4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let Y=$.apiBaseUrl.trim();if(!Y)throw Error("apiBaseUrl is required");this.apiBaseUrl=Y,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchBalance($){let Y=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(Y)}/balance`)}async fetchUsageTransactions($){let Y=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Y)}/usages`)).items??[]}async fetchPaymentTransactions($){let Y=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Y)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance($){let Y=$.trim();if(!Y)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/balance`)}async fetchOrganizationUsageTransactions($){let Y=$.organizationId.trim();if(!Y)throw Error("organizationId is required");let T=await this.resolveOrganizationMemberId(Y,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/members/${encodeURIComponent(T)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let Y=$?.trim();if(Y)return Y;let q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(q)return q;let X=await this.fetchMe();if(!X.id?.trim())throw Error("Unable to resolve current user id");return X.id}async resolveOrganizationMemberId($,Y){let T=Y?.trim();if(T)return T;let X=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(X)return X;let Q=(await this.fetchUserOrganizations()).find((U)=>U.organizationId===$)?.memberId;if(!Q?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return Q}async request($,Y){let T=(await this.getAuthTokenFn())?.trim();if(!T)throw Error("No Cline account auth token found");let q=this.getHeadersFn?await this.getHeadersFn():{},X=new AbortController,J=setTimeout(()=>X.abort(),this.requestTimeoutMs);try{let Q=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:Y?.method??"GET",headers:{Authorization:`Bearer ${T}`,"Content-Type":"application/json",...q??{}},body:Y?.body!==void 0?JSON.stringify(Y.body):void 0,signal:X.signal});if(Q.status===204||Y?.expectNoContent){if(!Q.ok)throw Error(`Cline account request failed with status ${Q.status}`);return}let U=await Q.text(),Z;if(U.trim())Z=JSON.parse(U);if(!Q.ok){let K=typeof Z==="object"&&Z!==null&&"error"in Z?String(Z.error):`Cline account request failed with status ${Q.status}`;throw Error(K)}if(typeof Z==="object"&&Z!==null){let K=Z;if(typeof K.success==="boolean"){if(!K.success)throw Error(K.error||"Cline account request failed");if(K.data!==void 0)return K.data}}if(Z===void 0||Z===null)throw Error("Cline account response payload was empty");return Z}finally{clearTimeout(J)}}}function UU($){return $.action==="clineAccount"}async function ZU($,Y){switch($.operation){case"fetchMe":return Y.fetchMe();case"fetchBalance":return Y.fetchBalance($.userId);case"fetchUsageTransactions":return Y.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return Y.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return Y.fetchUserOrganizations();case"fetchOrganizationBalance":return Y.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return Y.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await Y.switchAccount($.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class F4{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let Y=$.trim();if(!Y)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:Y})}async fetchOrganizationUsageTransactions($){let Y=$.organizationId.trim();if(!Y)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:Y,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async request($){return(await this.executor.runProviderAction($)).result}}import{z as b}from"zod";var KU=b.object({workspaceRoot:b.string().min(1),cwd:b.string().optional(),provider:b.string().min(1),model:b.string().min(1),mode:b.enum(["act","plan"]).default("act"),apiKey:b.string(),systemPrompt:b.string().optional(),rules:b.string().optional(),maxIterations:b.number().int().positive().optional(),enableTools:b.boolean(),enableSpawn:b.boolean(),enableTeams:b.boolean(),autoApproveTools:b.boolean().optional(),teamName:b.string().min(1),missionStepInterval:b.number().int().positive(),missionTimeIntervalMs:b.number().int().positive()}),AU=b.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),WU=b.enum(["user","assistant","tool","system","status","error"]),GU=b.object({id:b.string().min(1),sessionId:b.string().nullable(),role:WU,content:b.string(),createdAt:b.number().int().nonnegative(),meta:b.object({stream:b.enum(["stdout","stderr"]).optional(),toolName:b.string().optional(),iteration:b.number().int().nonnegative().optional(),agentId:b.string().optional(),conversationId:b.string().optional(),hookEventName:b.string().optional(),inputTokens:b.number().int().nonnegative().optional(),outputTokens:b.number().int().nonnegative().optional()}).optional()}),EU=b.object({toolCalls:b.number().int().nonnegative(),tokensIn:b.number().int().nonnegative(),tokensOut:b.number().int().nonnegative()}),zN=b.object({sessionId:b.string().nullable(),status:AU,config:KU,messages:b.array(GU),rawTranscript:b.string(),error:b.string().nullable(),summary:EU});import{existsSync as IN,readFileSync as MN}from"node:fs";import{z as o}from"zod";var IT=o.record(o.string(),o.string()),VU=o.record(o.string(),o.unknown()),BN=o.object({type:o.literal("stdio"),command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:IT.optional()}),RN=o.object({type:o.literal("sse"),url:o.string().url(),headers:IT.optional()}),ON=o.object({type:o.literal("streamableHttp"),url:o.string().url(),headers:IT.optional()}),PN=o.discriminatedUnion("type",[BN,RN,ON]),LN=o.object({transport:PN,disabled:o.boolean().optional(),metadata:VU.optional()}),wN=o.enum(["stdio","sse","http","streamableHttp"]).optional(),DU=o.object({type:o.enum(["stdio","sse","streamableHttp"]).optional(),transportType:wN,disabled:o.boolean().optional(),metadata:VU.optional()});function N4($){if(!$)return;if($==="http")return"streamableHttp";return $}var SN=DU.extend({command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:IT.optional()}).superRefine(($,Y)=>{let T=$.type??N4($.transportType);if(T&&T!=="stdio")Y.addIssue({code:o.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata})),CN=DU.extend({url:o.string().url(),headers:IT.optional()}).superRefine(($,Y)=>{let T=$.type??N4($.transportType)??"sse";if(T!=="sse"&&T!=="streamableHttp")Y.addIssue({code:o.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??N4($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata}}),yN=o.union([LN,SN,CN]),jN=o.object({mcpServers:o.record(o.string(),yN)}).strict();function R8(){return z9()}function H4($={}){let Y=$.filePath??R8(),T=MN(Y,"utf8"),q;try{q=JSON.parse(T)}catch(J){let Q=J instanceof Error?J.message:String(J);throw Error(`Failed to parse MCP settings JSON at "${Y}": ${Q}`)}let X=jN.safeParse(q);if(!X.success){let J=X.error.issues.map((Q)=>{let U=Q.path.join(".");return U?`${U}: ${Q.message}`:Q.message}).join("; ");throw Error(`Invalid MCP settings at "${Y}": ${J}`)}return X.data}function FU($={}){let Y=$.filePath??R8();return IN(Y)}function z4($={}){let Y=H4($);return Object.entries(Y.mcpServers).map(([T,q])=>({name:T,transport:q.transport,disabled:q.disabled,metadata:q.metadata}))}async function NU($,Y={}){let T=z4(Y);for(let q of T)await $.registerServer(q);return T}function G1(){return Date.now()}function vN($){return $.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}class I4{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let Y=this.servers.get($.name);if(!Y){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:G1()});return}let T=JSON.stringify(Y.registration.transport)!==JSON.stringify($.transport);if(Y.registration={...$},Y.updatedAt=G1(),T)await this.disconnectState(Y),Y.client=void 0,Y.toolCache=void 0,Y.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.disconnectState(Y),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.connectState(Y)})}async disconnectServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.disconnectState(Y)})}async setServerDisabled($,Y){await this.runExclusive($,async()=>{let T=this.requireServer($);if(T.registration={...T.registration,disabled:Y},T.updatedAt=G1(),Y)await this.disconnectState(T)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,Y)=>$.name.localeCompare(Y.name))}async listTools($){let Y=this.requireServer($),T=Y.toolCacheUpdatedAt??0;if(Y.toolCache&&G1()-T<=this.toolsCacheTtlMs)return Y.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let Y=this.requireServer($),q=await(await this.ensureConnectedClient(Y)).listTools(),X=vN(q);return Y.toolCache=X,Y.toolCacheUpdatedAt=G1(),Y.updatedAt=G1(),X})}async callTool($){return this.runExclusive($.serverName,async()=>{let Y=this.requireServer($.serverName),T=await this.ensureConnectedClient(Y);return Y.updatedAt=G1(),T.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let Y of $)await this.unregisterServer(Y)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=G1();try{let Y=$.client??await this.clientFactory($.registration);await Y.connect(),$.client=Y,$.status="connected",$.lastError=void 0,$.updatedAt=G1()}catch(Y){throw $.status="disconnected",$.lastError=Y instanceof Error?Y.message:String(Y),$.updatedAt=G1(),Y}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=G1();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=G1()}}requireServer($){let Y=this.servers.get($);if(!Y)throw Error(`Unknown MCP server: ${$}`);return Y}async runExclusive($,Y){let T=this.operationLocks.get($)??Promise.resolve(),q,X=new Promise((Q)=>{q=Q}),J=T.catch(()=>{return}).then(()=>X);this.operationLocks.set($,J),await T.catch(()=>{return});try{return await Y()}finally{if(q?.(),this.operationLocks.get($)===J)this.operationLocks.delete($)}}}import{existsSync as BU,mkdirSync as pN,readFileSync as lN,writeFileSync as nN}from"node:fs";import{basename as RU,dirname as R4}from"node:path";import{providers as M4}from"@clinebot/llms";import{z as N$}from"zod";var HU=M4.ProviderSettingsSchema,MT=M4.toProviderConfig,zU=N$.object({settings:M4.ProviderSettingsSchema,updatedAt:N$.string().datetime(),tokenSource:N$.enum(["manual","oauth","migration"]).default("manual")}),O8=N$.object({version:N$.literal(1),lastUsedProvider:N$.string().min(1).optional(),providers:N$.record(N$.string(),zU)});function FY(){return{version:1,providers:{}}}import{existsSync as xN,readFileSync as kN}from"node:fs";import{join as IU}from"node:path";import{models as hN,providers as _N}from"@clinebot/llms";function c($){let Y=$?.trim();return Y?Y:void 0}function MU($){if(!xN($))return;try{let Y=kN($,"utf8"),T=JSON.parse(Y);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return}function gN($){let Y=$.dataDir??t0(),T=$.globalStatePath??IU(Y,"globalState.json"),q=$.secretsPath??IU(Y,"secrets.json"),X=MU(T),J=MU(q);if(!X&&!J)return;return{globalState:X??{},secrets:J??{}}}function mN($,Y,T,q){let X=T==="plan"?"planMode":"actMode",J=Y===q?c(T==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,U={openrouter:`${X}OpenRouterModelId`,cline:`${X}ClineModelId`,openai:`${X}OpenAiModelId`,ollama:`${X}OllamaModelId`,lmstudio:`${X}LmStudioModelId`,litellm:`${X}LiteLlmModelId`,requesty:`${X}RequestyModelId`,together:`${X}TogetherModelId`,fireworks:`${X}FireworksModelId`,sapaicore:`${X}SapAiCoreModelId`,groq:`${X}GroqModelId`,baseten:`${X}BasetenModelId`,huggingface:`${X}HuggingFaceModelId`,"huawei-cloud-maas":`${X}HuaweiCloudMaasModelId`,oca:`${X}OcaModelId`,aihubmix:`${X}AihubmixModelId`,hicap:`${X}HicapModelId`,nousResearch:`${X}NousResearchModelId`,"vercel-ai-gateway":`${X}VercelAiGatewayModelId`}[Y];return(U?c(typeof $[U]==="string"?$[U]:void 0):void 0)??J}function fN($,Y,T){let q=T==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,X=T==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,J=T==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,Q=(Y==="gemini"?X:void 0)??q,U=Q==="none"||Q==="low"||Q==="medium"||Q==="high"?Q:void 0,Z=typeof J==="number"&&Number.isInteger(J)&&J>0?J:void 0;if(!U&&Z===void 0)return;return{...U?{effort:U}:{},...Z!==void 0?{budgetTokens:Z}:{}}}function bN($){let Y=$["openai-codex-oauth-credentials"];if(!Y)return;try{let T=JSON.parse(Y),q=c(T.access_token),X=c(T.refresh_token),J=c(T.accountId);if(!q&&!X&&!J)return;return{...q?{apiKey:q}:{},auth:{...q?{accessToken:q}:{},...X?{refreshToken:X}:{},...J?{accountId:J}:{}}}}catch{return}}function uN($){let Y=hN.getGeneratedModelsForProvider($);return Object.keys(Y)[0]??void 0}function dN($,Y,T,q){let X=c(q==="plan"?Y.planModeApiProvider:Y.actModeApiProvider),J=mN(Y,$,q,X)??uN($),Q=fN(Y,$,q),U=typeof Y.requestTimeoutMs==="number"&&Number.isInteger(Y.requestTimeoutMs)&&Y.requestTimeoutMs>0?Y.requestTimeoutMs:void 0,Z={anthropic:T.apiKey,cline:T.clineApiKey,openai:T.openAiApiKey,"openai-native":T.openAiNativeApiKey,openrouter:T.openRouterApiKey,bedrock:T.awsBedrockApiKey,gemini:T.geminiApiKey,ollama:T.ollamaApiKey,deepseek:T.deepSeekApiKey,requesty:T.requestyApiKey,together:T.togetherApiKey,fireworks:T.fireworksApiKey,qwen:T.qwenApiKey,doubao:T.doubaoApiKey,mistral:T.mistralApiKey,litellm:T.liteLlmApiKey,asksage:T.asksageApiKey,xai:T.xaiApiKey,moonshot:T.moonshotApiKey,zai:T.zaiApiKey,huggingface:T.huggingFaceApiKey,nebius:T.nebiusApiKey,sambanova:T.sambanovaApiKey,cerebras:T.cerebrasApiKey,groq:T.groqApiKey,"huawei-cloud-maas":T.huaweiCloudMaasApiKey,baseten:T.basetenApiKey,"vercel-ai-gateway":T.vercelAiGatewayApiKey,dify:T.difyApiKey,minimax:T.minimaxApiKey,hicap:T.hicapApiKey,aihubmix:T.aihubmixApiKey,nousResearch:T.nousResearchApiKey,oca:T.ocaApiKey,sapaicore:T.sapAiCoreClientId},K={};if($==="openai-codex")Object.assign(K,bN(T));if($==="cline"){let V=c(T["cline:clineAccountId"]??T.clineAccountId);if(V)K.auth={...K.auth??{},accountId:V}}if($==="openai"&&Y.openAiHeaders)K.headers=Y.openAiHeaders;if($==="bedrock")K.aws={accessKey:c(T.awsAccessKey),secretKey:c(T.awsSecretKey),sessionToken:c(T.awsSessionToken),region:c(Y.awsRegion),authentication:Y.awsAuthentication,profile:Y.awsUseProfile?c(Y.awsProfile):void 0,usePromptCache:Y.awsBedrockUsePromptCache,useCrossRegionInference:Y.awsUseCrossRegionInference,useGlobalInference:Y.awsUseGlobalInference,endpoint:c(Y.awsBedrockEndpoint),customModelBaseId:c(q==="plan"?Y.planModeAwsBedrockCustomModelBaseId:Y.actModeAwsBedrockCustomModelBaseId)};if($==="vertex")K.gcp={projectId:c(Y.vertexProjectId),region:c(Y.vertexRegion)};if($==="openai"&&(Y.azureApiVersion||Y.azureIdentity!==void 0))K.azure={apiVersion:c(Y.azureApiVersion),useIdentity:Y.azureIdentity};if($==="sapaicore")K.sap={clientId:c(T.sapAiCoreClientId),clientSecret:c(T.sapAiCoreClientSecret),tokenUrl:c(Y.sapAiCoreTokenUrl),resourceGroup:c(Y.sapAiResourceGroup),deploymentId:c(q==="plan"?Y.planModeSapAiCoreDeploymentId:Y.actModeSapAiCoreDeploymentId),useOrchestrationMode:Y.sapAiCoreUseOrchestrationMode};if($==="oca"){K.oca={mode:Y.ocaMode};let V=c(T.ocaRefreshToken);if(V)K.auth={...K.auth??{},refreshToken:V}}if($==="qwen")K.apiLine=Y.qwenApiLine;if($==="moonshot")K.apiLine=Y.moonshotApiLine;if($==="zai")K.apiLine=Y.zaiApiLine;if($==="minimax")K.apiLine=Y.minimaxApiLine;let A={anthropic:Y.anthropicBaseUrl,openai:Y.openAiBaseUrl,ollama:Y.ollamaBaseUrl,lmstudio:Y.lmStudioBaseUrl,litellm:Y.liteLlmBaseUrl,gemini:Y.geminiBaseUrl,requesty:Y.requestyBaseUrl,asksage:Y.asksageApiUrl,dify:Y.difyBaseUrl,oca:Y.ocaBaseUrl,aihubmix:Y.aihubmixBaseUrl,sapaicore:Y.sapAiCoreBaseUrl},W=c(Z[$]),E=c(A[$]),D={provider:$,...W?{apiKey:W}:{},...J?{model:J}:{},...E?{baseUrl:E}:{},...Q?{reasoning:Q}:{},...U?{timeout:U}:{},...K},F=_N.ProviderSettingsSchema.safeParse(D);if(!F.success)return;return Object.keys(D).filter((V)=>V!=="provider").length>0?F.data:void 0}function cN($,Y){let T=new Set;for(let q of[$.actModeApiProvider,$.planModeApiProvider]){let X=c(q);if(X)T.add(X)}if(c(Y.apiKey))T.add("anthropic");if(c(Y.openRouterApiKey))T.add("openrouter");if(c(Y.openAiApiKey))T.add("openai");if(c(Y.openAiNativeApiKey))T.add("openai-native");if(c(Y["openai-codex-oauth-credentials"]))T.add("openai-codex");if(c(Y.geminiApiKey))T.add("gemini");if(c(Y.ollamaApiKey))T.add("ollama");if(c(Y.awsAccessKey)||c(Y.awsBedrockApiKey))T.add("bedrock");if(c($.vertexProjectId)||c($.vertexRegion))T.add("vertex");if(c(Y.clineApiKey))T.add("cline");if(c(Y.ocaApiKey))T.add("oca");return T}function B4($){let Y=$.providerSettingsManager.read(),T=gN($);if(!T)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let{globalState:q,secrets:X}=T,J=q.mode==="plan"?"plan":"act",Q=cN(q,X),U=FY();U.providers={...Y.providers},U.lastUsedProvider=Y.lastUsedProvider;let Z=new Date().toISOString(),K=0;for(let W of Q){if(U.providers[W])continue;let E=dN(W,q,X,J);if(!E)continue;U.providers[W]={settings:E,updatedAt:Z,tokenSource:"migration"},K+=1}if(K===0)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let A=c(J==="plan"?q.planModeApiProvider:q.actModeApiProvider);return U.lastUsedProvider=Y.lastUsedProvider??(A&&U.providers[A]?A:Object.keys(U.providers)[0]),$.providerSettingsManager.write(U),{migrated:!0,providerCount:Object.keys(U.providers).length,lastUsedProvider:U.lastUsedProvider}}function iN(){return new Date().toISOString()}function rN($){if(RU($)!=="providers.json")return;let Y=R4($);if(RU(Y)!=="settings")return;return R4(Y)}class d${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??H9(),this.dataDir=$.dataDir??rN(this.filePath),this.dataDir||!$.filePath)B4({providerSettingsManager:this,dataDir:this.dataDir})}getFilePath(){return this.filePath}read(){if(!BU(this.filePath))return FY();try{let $=lN(this.filePath,"utf8"),Y=JSON.parse($),T=O8.safeParse(Y);if(T.success)return T.data}catch{}return FY()}write($){let Y=O8.parse($),T=R4(this.filePath);if(!BU(T))pN(T,{recursive:!0});nN(this.filePath,`${JSON.stringify(Y,null,2)}
|
|
342
|
-
`,"utf8")}saveProviderSettings($,Y={}){let T=
|
|
341
|
+
</html>`;function dQ($){let Y="";for(let T=0;T<$.length;T+=1)Y+=String.fromCharCode($[T]??0);return btoa(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function nF($){let T=new TextEncoder().encode($),q=await crypto.subtle.digest("SHA-256",T);return new Uint8Array(q)}function iF($=32){let Y=new Uint8Array($);return crypto.getRandomValues(Y),dQ(Y)}async function D8(){let $=iF(),Y=dQ(await nF($));return{verifier:$,challenge:Y}}function F8($){return $.endsWith("/")?$.slice(0,-1):$}function N8($,Y){return new URL(Y,`${F8($)}/`).toString()}function VY($,Y={}){let T=$.trim();if(!T)return{};try{let q=new URL(T);return{code:q.searchParams.get("code")??void 0,state:q.searchParams.get("state")??void 0,provider:Y.includeProvider?q.searchParams.get("provider")??void 0:void 0}}catch{}if(Y.allowHashCodeState&&T.includes("#")){let[q,X]=T.split("#",2);return{code:q||void 0,state:X||void 0}}if(T.includes("code=")){let q=new URLSearchParams(T);return{code:q.get("code")??void 0,state:q.get("state")??void 0,provider:Y.includeProvider?q.get("provider")??void 0:void 0}}return{code:T}}function rF($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function W1($){if(!$)return null;try{let Y=$.split(".");if(Y.length!==3)return null;let T=Y[1];if(!T)return null;let q=T.replace(/-/g,"+").replace(/_/g,"/"),X=q.padEnd(q.length+(4-q.length%4)%4,"="),J=rF(X);if(!J)return null;return JSON.parse(J)}catch{return null}}function H6($){try{let Y=JSON.parse($),T=Y.error,q=typeof T==="string"?T:T&&typeof T==="object"&&typeof T.type==="string"?T.type:void 0,X=typeof Y.error_description==="string"?Y.error_description:typeof Y.message==="string"?Y.message:T&&typeof T==="object"&&typeof T.message==="string"?T.message:void 0;return{code:q,message:X}}catch{return{}}}function u$($,Y){return Date.now()>=$.expires-Y}async function DY($){if(!$.onManualCodeInput){let J=await $.waitForCallback();return{code:J?.code,state:J?.state,provider:J?.provider,error:J?.error}}let Y,T,q=$.onManualCodeInput().then((J)=>{Y=J,$.cancelWait()}).catch((J)=>{T=J instanceof Error?J:Error(String(J)),$.cancelWait()}),X=await $.waitForCallback();if(T)throw T;if(X?.code||X?.error)return{code:X.code,state:X.state,provider:X.provider,error:X.error};if(Y)return VY(Y,$.parseOptions);if(await q,T)throw T;if(Y)return VY(Y,$.parseOptions);return{}}var Q4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",refresh:"/api/v1/auth/refresh"},aF="/auth",cQ=Array.from({length:11},($,Y)=>48801+Y),oF=300000,sF=30000,U4=30000;class H8 extends Error{status;errorCode;constructor($,Y){super($);this.name="ClineOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function tF(){let $=globalThis.crypto;if(!$)return Math.random().toString(16).slice(2);let Y=new Uint8Array(16);return $.getRandomValues(Y),Array.from(Y,(T)=>T.toString(16).padStart(2,"0")).join("")}function eF($){let Y=Date.parse($);if(Number.isNaN(Y))throw Error(`Invalid expiresAt value: ${$}`);return Y}function pQ($,Y,T={}){let q=$.userInfo.clineUserId??T.accountId,X=$.refreshToken??T.refresh;if(!X)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:X,expires:eF($.expiresAt),accountId:q??void 0,email:$.userInfo.email||T.email,metadata:{provider:Y,tokenType:$.tokenType,userInfo:$.userInfo}}}async function Z4($){if(!$)return{};return typeof $==="function"?await $():$}async function $N($,Y){let T=new URL(N8($.apiBaseUrl,Q4.authorize));T.searchParams.set("client_type","extension"),T.searchParams.set("callback_url",Y.callbackUrl),T.searchParams.set("redirect_uri",Y.callbackUrl),T.searchParams.set("state",Y.state);let q=await fetch(T.toString(),{method:"GET",redirect:"manual",headers:await Z4($.headers),signal:AbortSignal.timeout($.requestTimeoutMs??U4)});if(q.status>=300&&q.status<400){let J=q.headers.get("location");if(J)return J}if(!q.ok){let J=await q.text().catch(()=>"");throw Error(`Authentication request failed: ${q.status} ${J}`)}let X=await q.json();if(typeof X.redirect_url==="string"&&X.redirect_url.length>0)return X.redirect_url;throw Error("Authentication request did not return a redirect URL")}async function YN($,Y,T,q){let X={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:Y,provider:q??T.provider},J=await fetch(N8(T.apiBaseUrl,Q4.token),{method:"POST",headers:{"Content-Type":"application/json",...await Z4(T.headers)},body:JSON.stringify(X),signal:AbortSignal.timeout(T.requestTimeoutMs??U4)});if(!J.ok){let U=await J.text().catch(()=>""),Z=H6(U);throw new H8(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let Q=await J.json();if(!Q.success||!Q.data?.accessToken)throw Error("Invalid token exchange response");return pQ(Q.data,q??T.provider)}async function z8($){let Y=$.callbackPorts?.length?$.callbackPorts:cQ,T=$.callbackPath??aF,q=tF(),X=await b$({ports:Y,callbackPath:T}),J=X.callbackUrl||`http://127.0.0.1:${Y[0]??cQ[0]}${T}`,Q=await $N($,{callbackUrl:J,state:q});$.callbacks.onAuth({url:Q,instructions:"Continue the authentication process in your browser."});try{let U,Z=$.provider,K=await DY({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(K.error)throw Error(`OAuth error: ${K.error}`);if(K.state&&K.state!==q)throw Error("State mismatch");if(U=K.code,Z=K.provider??Z,!U){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),W=VY(A,{includeProvider:!0});if(W.state&&W.state!==q)throw Error("State mismatch");U=W.code,Z=W.provider??Z}if(!U)throw Error("Missing authorization code");return YN(U,J,$,Z)}finally{X.close()}}async function K4($,Y){let T=await fetch(N8(Y.apiBaseUrl,Q4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await Z4(Y.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(Y.requestTimeoutMs??U4)});if(!T.ok){let J=await T.text().catch(()=>""),Q=H6(J);throw new H8(`Token refresh failed: ${T.status}${Q.message?` - ${Q.message}`:""}`,{status:T.status,errorCode:Q.code})}let q=await T.json();if(!q.success||!q.data?.accessToken)throw Error("Invalid token refresh response");let X=$.metadata?.provider??Y.provider;return pQ(q.data,X,$)}async function A4($,Y,T){if(!$)return null;let q=T?.refreshBufferMs??oF,X=T?.retryableTokenGraceMs??sF;if(T?.forceRefresh!==!0&&!u$($,q))return $;try{return await K4($,Y)}catch(Q){if(Q instanceof H8&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function TN($){return{id:"cline",name:"Cline Account",usesCallbackServer:!0,async login(Y){return z8({...$,callbacks:Y})},async refreshToken(Y){return K4(Y,$)},getApiKey(Y){return`workos:${Y.access}`}}}import{nanoid as qN}from"nanoid";var z0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class I8 extends Error{status;errorCode;constructor($,Y){super($);this.name="OpenAICodexOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function XN($,Y,T=z0.redirectUri){let q=await fetch(z0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:z0.clientId,code:$,code_verifier:Y,redirect_uri:T}),signal:AbortSignal.timeout(z0.httpTimeoutMs)});if(!q.ok)return{type:"failed"};let X=await q.json();if(!X.access_token||!X.refresh_token||typeof X.expires_in!=="number")return{type:"failed"};return{type:"success",access:X.access_token,refresh:X.refresh_token,expires:Date.now()+X.expires_in*1000,email:X.email,idToken:X.id_token}}async function JN($){try{let Y=await fetch(z0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:z0.clientId}),signal:AbortSignal.timeout(z0.httpTimeoutMs)});if(!Y.ok){let q=await Y.text().catch(()=>""),X=H6(q);throw new I8(`Token refresh failed: ${Y.status}${X.message?` - ${X.message}`:""}`,{status:Y.status,errorCode:X.code})}let T=await Y.json();if(!T.access_token||!T.refresh_token||typeof T.expires_in!=="number")return{type:"failed"};return{type:"success",access:T.access_token,refresh:T.refresh_token,expires:Date.now()+T.expires_in*1000,email:T.email,idToken:T.id_token}}catch(Y){if(Y instanceof I8)throw Y;return{type:"failed"}}}async function QN($="pi"){let{verifier:Y,challenge:T}=await D8(),q=qN(32),X=new URL(z0.authorizationEndpoint);return X.searchParams.set("response_type","code"),X.searchParams.set("client_id",z0.clientId),X.searchParams.set("redirect_uri",z0.redirectUri),X.searchParams.set("scope",z0.scopes),X.searchParams.set("code_challenge",T),X.searchParams.set("code_challenge_method","S256"),X.searchParams.set("state",q),X.searchParams.set("id_token_add_organizations","true"),X.searchParams.set("codex_cli_simplified_flow","true"),X.searchParams.set("originator",$),{verifier:Y,state:q,url:X.toString()}}function UN(){try{let $=new URL(z0.redirectUri),Y=$.port.length>0?Number.parseInt($.port,10):z0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(Y)?Y:z0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:z0.callbackPort,callbackPath:"/auth/callback",redirectUri:z0.redirectUri}}}function lQ($,Y){let T=Y?W1(Y):W1($),q=T?T:W1($),J=q?.[z0.jwtClaimPath]?.chatgpt_account_id;if(typeof J==="string"&&J.length>0)return J;let Q=q?.organizations;if(Array.isArray(Q)&&Q.length>0){let Z=Q[0];if(typeof Z?.id==="string"&&Z.id.length>0)return Z.id}let U=q?.chatgpt_account_id;if(typeof U==="string"&&U.length>0)return U;return null}function nQ($,Y){let T=lQ($.access,$.idToken)??Y?.accountId;if(!T)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||Y?.refresh||"",expires:$.expires,accountId:T,email:$.email??Y?.email,metadata:{...Y?.metadata??{},provider:"openai-codex"}}}async function M8($){let Y=UN(),{verifier:T,state:q,url:X}=await QN($.originator),J=await b$({host:Y.host,ports:[Y.port],callbackPath:Y.callbackPath,expectedState:q});$.onAuth({url:X,instructions:"Continue the authentication process in your browser."});let Q;try{let U=await DY({waitForCallback:J.waitForCallback,cancelWait:J.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(U.state&&U.state!==q)throw Error("State mismatch");if(Q=U.code,!Q){let K=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=VY(K,{allowHashCodeState:!0});if(A.state&&A.state!==q)throw Error("State mismatch");Q=A.code}if(!Q)throw Error("Missing authorization code");let Z=await XN(Q,T,Y.redirectUri);if(Z.type!=="success")throw Error("Token exchange failed");return nQ(Z)}finally{J.close()}}async function W4($,Y){let T=await JN($);if(T.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let q=nQ(T,Y);if(!q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return q}async function G4($,Y){if(!$)return null;let T=Y?.refreshBufferMs??z0.refreshBufferMs,q=Y?.retryableTokenGraceMs??z0.retryableTokenGraceMs;if(Y?.forceRefresh!==!0&&!u$($,T))return $;try{return await W4($.refresh,$)}catch(J){if(J instanceof I8&&J.isLikelyInvalidGrant())return null;if($.expires-Date.now()>q)return $;return null}}function ZN($,Y=z0.refreshBufferMs){return u$($,Y)}function KN($){let Y=$.accountId??lQ($.access);if(!Y)throw Error("Failed to extract accountId from token");return{...$,accountId:Y,metadata:{...$.metadata??{},provider:"openai-codex"}}}var AN={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return M8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return W4($.refresh,$)},getApiKey($){return $.access}};import{nanoid as iQ}from"nanoid";var rQ="a8331954c0cf48ba99b5dd223a14c6ea",aQ="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",oQ="openid offline_access",sQ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",tQ="c1aba3deed5740659981a752714eba33",eQ="https://login-ext.identity.oraclecloud.com",$U="openid offline_access",YU="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",TU="opc-request-id",WN="/auth/oca",GN=Array.from({length:11},($,Y)=>48801+Y),EN=300000,VN=30000,qU=30000,DN=600000;class B8 extends Error{status;errorCode;constructor($,Y){super($);this.name="OcaOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var F$={internal:{clientId:rQ,idcsUrl:aQ,scopes:oQ,baseUrl:sQ},external:{clientId:tQ,idcsUrl:eQ,scopes:$U,baseUrl:YU}},z6=new Map,E4=new Map;function XU($){if(typeof $==="function")return $();return $??"internal"}function JU($){return{internal:{clientId:$?.internal?.clientId??F$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??F$.internal.idcsUrl,scopes:$?.internal?.scopes??F$.internal.scopes,baseUrl:$?.internal?.baseUrl??F$.internal.baseUrl},external:{clientId:$?.external?.clientId??F$.external.clientId,idcsUrl:$?.external?.idcsUrl??F$.external.idcsUrl,scopes:$?.external?.scopes??F$.external.scopes,baseUrl:$?.external?.baseUrl??F$.external.baseUrl}}}function FN($=Date.now()){let Y=$-DN;for(let[T,q]of z6.entries())if(q.createdAt<Y)z6.delete(T)}function NN($,Y,T){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let X=W1(Y)?.exp;if(typeof X==="number"&&X>0)return X*1000;let Q=W1(T)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return Date.now()+3600000}function QU($,Y,T){let q=$.access_token;if(!q)throw Error("Token response did not include an access token");let X=$.refresh_token??T?.refresh;if(!X)throw Error("Token response did not include a refresh token");let J=W1($.id_token),Q=W1(q),U=J?.sub??Q?.sub,Z=J?.email??Q?.email;return{access:q,refresh:X,expires:NN($,q,$.id_token),accountId:U??T?.accountId,email:Z??T?.email,metadata:{...T?.metadata??{},provider:"oca",mode:Y,subject:U,idToken:$.id_token}}}async function UU($,Y){let T=F8($),q=E4.get(T);if(q)return q;let X=`${T}/.well-known/openid-configuration`,J=await fetch(X,{method:"GET",signal:AbortSignal.timeout(Y)});if(!J.ok){let Z=`${T}/oauth2/v1/token`;return E4.set(T,Z),Z}let U=(await J.json()).token_endpoint||`${T}/oauth2/v1/token`;return E4.set(T,U),U}function ZU($){return{code:$.error,message:$.error_description}}async function HN($){let Y=z6.get($.state);if(!Y)throw Error("No PKCE verifier found for this state");z6.delete($.state);let T=$.mode==="external"?$.config.external:$.config.internal,q=await UU(T.idcsUrl,$.requestTimeoutMs),X=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:Y.redirectUri,client_id:T.clientId,code_verifier:Y.verifier}),J=await fetch(q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout($.requestTimeoutMs)}),Q=await J.json();if(!J.ok){let Z=ZU(Q);throw new B8(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let U=W1(Q.id_token);if(!Q.id_token||!U)throw Error("No ID token received from OCA");if(U.nonce!==Y.nonce)throw Error("OIDC nonce verification failed");return QU(Q,$.mode)}function zN($){let Y=$.mode==="external"?$.config.external:$.config.internal,T=new URL(`${F8(Y.idcsUrl)}/oauth2/v1/authorize`);return T.searchParams.set("client_id",Y.clientId),T.searchParams.set("response_type","code"),T.searchParams.set("scope",Y.scopes),T.searchParams.set("code_challenge",$.challenge),T.searchParams.set("code_challenge_method","S256"),T.searchParams.set("redirect_uri",$.callbackUrl),T.searchParams.set("state",$.state),T.searchParams.set("nonce",$.nonce),T.toString()}async function R8($){let Y=JU($.config),T=XU($.mode),q=$.callbackPorts?.length?$.callbackPorts:GN,X=$.callbackPath??WN,J=$.requestTimeoutMs??qU,Q=await b$({ports:q,callbackPath:X}),U=Q.callbackUrl;if(!U)throw Error("Unable to bind local OAuth callback server");let Z=iQ(16),K=iQ(16),{verifier:A,challenge:W}=await D8();FN(),z6.set(Z,{verifier:A,nonce:K,mode:T,redirectUri:U,createdAt:Date.now()});let E=zN({callbackUrl:U,mode:T,state:Z,nonce:K,challenge:W,config:Y});$.callbacks.onAuth({url:E,instructions:"Continue the authentication process in your browser."});try{let V=await DY({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),F=V.code,H=V.state;if(V.error)throw Error(`OAuth error: ${V.error}`);if(!F){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!H||H!==Z)throw Error("State mismatch");return await HN({code:F,state:H,mode:T,config:Y,requestTimeoutMs:J})}finally{Q.close()}}async function V4($,Y={}){let T=JU(Y.config),q=Y.requestTimeoutMs??qU,X=$.metadata?.mode,J=X==="internal"||X==="external"?X:XU(Y.mode),Q=J==="external"?T.external:T.internal,U=await UU(Q.idcsUrl,q),Z=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:Q.clientId}),K=await fetch(U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(q)}),A=await K.json();if(!K.ok){let W=ZU(A);throw new B8(`Token refresh failed: ${K.status}${W.message?` - ${W.message}`:""}`,{status:K.status,errorCode:W.code})}return QU(A,J,$)}async function D4($,Y,T){if(!$)return null;let q=Y?.refreshBufferMs??T?.refreshBufferMs??EN,X=Y?.retryableTokenGraceMs??T?.retryableTokenGraceMs??VN;if(Y?.forceRefresh!==!0&&!u$($,q))return $;try{return await V4($,T)}catch(Q){if(Q instanceof B8&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function IN($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(Y){return R8({...$,callbacks:Y})},async refreshToken(Y){return V4(Y,$)},getApiKey(Y){return Y.access}}}async function KU($,Y){let T=new TextEncoder,q=async(K)=>{let A=await crypto.subtle.digest("SHA-256",T.encode(K));return Array.from(new Uint8Array(A).slice(0,4),(W)=>W.toString(16).padStart(2,"0")).join("")},[X,J]=await Promise.all([q(Y),q($)]),Q=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),U=new Uint32Array(1);crypto.getRandomValues(U);let Z=(U[0]??0).toString(16).padStart(8,"0");return X+J+Q+Z}async function MN($){let Y=await KU($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[TU]:Y}}import{createTool as Eh,getClineDefaultSystemPrompt as Vh}from"@clinebot/agents";class F4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let Y=$.apiBaseUrl.trim();if(!Y)throw Error("apiBaseUrl is required");this.apiBaseUrl=Y,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchBalance($){let Y=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(Y)}/balance`)}async fetchUsageTransactions($){let Y=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Y)}/usages`)).items??[]}async fetchPaymentTransactions($){let Y=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Y)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance($){let Y=$.trim();if(!Y)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/balance`)}async fetchOrganizationUsageTransactions($){let Y=$.organizationId.trim();if(!Y)throw Error("organizationId is required");let T=await this.resolveOrganizationMemberId(Y,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/members/${encodeURIComponent(T)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let Y=$?.trim();if(Y)return Y;let q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(q)return q;let X=await this.fetchMe();if(!X.id?.trim())throw Error("Unable to resolve current user id");return X.id}async resolveOrganizationMemberId($,Y){let T=Y?.trim();if(T)return T;let X=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(X)return X;let Q=(await this.fetchUserOrganizations()).find((U)=>U.organizationId===$)?.memberId;if(!Q?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return Q}async request($,Y){let T=(await this.getAuthTokenFn())?.trim();if(!T)throw Error("No Cline account auth token found");let q=this.getHeadersFn?await this.getHeadersFn():{},X=new AbortController,J=setTimeout(()=>X.abort(),this.requestTimeoutMs);try{let Q=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:Y?.method??"GET",headers:{Authorization:`Bearer ${T}`,"Content-Type":"application/json",...q??{}},body:Y?.body!==void 0?JSON.stringify(Y.body):void 0,signal:X.signal});if(Q.status===204||Y?.expectNoContent){if(!Q.ok)throw Error(`Cline account request failed with status ${Q.status}`);return}let U=await Q.text(),Z;if(U.trim())Z=JSON.parse(U);if(!Q.ok){let K=typeof Z==="object"&&Z!==null&&"error"in Z?String(Z.error):`Cline account request failed with status ${Q.status}`;throw Error(K)}if(typeof Z==="object"&&Z!==null){let K=Z;if(typeof K.success==="boolean"){if(!K.success)throw Error(K.error||"Cline account request failed");if(K.data!==void 0)return K.data}}if(Z===void 0||Z===null)throw Error("Cline account response payload was empty");return Z}finally{clearTimeout(J)}}}function AU($){return $.action==="clineAccount"}async function WU($,Y){switch($.operation){case"fetchMe":return Y.fetchMe();case"fetchBalance":return Y.fetchBalance($.userId);case"fetchUsageTransactions":return Y.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return Y.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return Y.fetchUserOrganizations();case"fetchOrganizationBalance":return Y.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return Y.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await Y.switchAccount($.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class N4{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let Y=$.trim();if(!Y)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:Y})}async fetchOrganizationUsageTransactions($){let Y=$.organizationId.trim();if(!Y)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:Y,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async request($){return(await this.executor.runProviderAction($)).result}}import{z as b}from"zod";var GU=b.object({workspaceRoot:b.string().min(1),cwd:b.string().optional(),provider:b.string().min(1),model:b.string().min(1),mode:b.enum(["act","plan"]).default("act"),apiKey:b.string(),systemPrompt:b.string().optional(),rules:b.string().optional(),maxIterations:b.number().int().positive().optional(),enableTools:b.boolean(),enableSpawn:b.boolean(),enableTeams:b.boolean(),autoApproveTools:b.boolean().optional(),teamName:b.string().min(1),missionStepInterval:b.number().int().positive(),missionTimeIntervalMs:b.number().int().positive()}),EU=b.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),VU=b.enum(["user","assistant","tool","system","status","error"]),DU=b.object({id:b.string().min(1),sessionId:b.string().nullable(),role:VU,content:b.string(),createdAt:b.number().int().nonnegative(),meta:b.object({stream:b.enum(["stdout","stderr"]).optional(),toolName:b.string().optional(),iteration:b.number().int().nonnegative().optional(),agentId:b.string().optional(),conversationId:b.string().optional(),hookEventName:b.string().optional(),inputTokens:b.number().int().nonnegative().optional(),outputTokens:b.number().int().nonnegative().optional()}).optional()}),FU=b.object({toolCalls:b.number().int().nonnegative(),tokensIn:b.number().int().nonnegative(),tokensOut:b.number().int().nonnegative()}),BN=b.object({sessionId:b.string().nullable(),status:EU,config:GU,messages:b.array(DU),rawTranscript:b.string(),error:b.string().nullable(),summary:FU});import{existsSync as RN,readFileSync as ON}from"node:fs";import{z as o}from"zod";var I6=o.record(o.string(),o.string()),NU=o.record(o.string(),o.unknown()),PN=o.object({type:o.literal("stdio"),command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:I6.optional()}),LN=o.object({type:o.literal("sse"),url:o.string().url(),headers:I6.optional()}),wN=o.object({type:o.literal("streamableHttp"),url:o.string().url(),headers:I6.optional()}),SN=o.discriminatedUnion("type",[PN,LN,wN]),CN=o.object({transport:SN,disabled:o.boolean().optional(),metadata:NU.optional()}),yN=o.enum(["stdio","sse","http","streamableHttp"]).optional(),HU=o.object({type:o.enum(["stdio","sse","streamableHttp"]).optional(),transportType:yN,disabled:o.boolean().optional(),metadata:NU.optional()});function H4($){if(!$)return;if($==="http")return"streamableHttp";return $}var jN=HU.extend({command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:I6.optional()}).superRefine(($,Y)=>{let T=$.type??H4($.transportType);if(T&&T!=="stdio")Y.addIssue({code:o.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata})),vN=HU.extend({url:o.string().url(),headers:I6.optional()}).superRefine(($,Y)=>{let T=$.type??H4($.transportType)??"sse";if(T!=="sse"&&T!=="streamableHttp")Y.addIssue({code:o.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??H4($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata}}),xN=o.union([CN,jN,vN]),kN=o.object({mcpServers:o.record(o.string(),xN)}).strict();function O8(){return I9()}function z4($={}){let Y=$.filePath??O8(),T=ON(Y,"utf8"),q;try{q=JSON.parse(T)}catch(J){let Q=J instanceof Error?J.message:String(J);throw Error(`Failed to parse MCP settings JSON at "${Y}": ${Q}`)}let X=kN.safeParse(q);if(!X.success){let J=X.error.issues.map((Q)=>{let U=Q.path.join(".");return U?`${U}: ${Q.message}`:Q.message}).join("; ");throw Error(`Invalid MCP settings at "${Y}": ${J}`)}return X.data}function zU($={}){let Y=$.filePath??O8();return RN(Y)}function I4($={}){let Y=z4($);return Object.entries(Y.mcpServers).map(([T,q])=>({name:T,transport:q.transport,disabled:q.disabled,metadata:q.metadata}))}async function IU($,Y={}){let T=I4(Y);for(let q of T)await $.registerServer(q);return T}function G1(){return Date.now()}function hN($){return $.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}class M4{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let Y=this.servers.get($.name);if(!Y){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:G1()});return}let T=JSON.stringify(Y.registration.transport)!==JSON.stringify($.transport);if(Y.registration={...$},Y.updatedAt=G1(),T)await this.disconnectState(Y),Y.client=void 0,Y.toolCache=void 0,Y.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.disconnectState(Y),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.connectState(Y)})}async disconnectServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.disconnectState(Y)})}async setServerDisabled($,Y){await this.runExclusive($,async()=>{let T=this.requireServer($);if(T.registration={...T.registration,disabled:Y},T.updatedAt=G1(),Y)await this.disconnectState(T)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,Y)=>$.name.localeCompare(Y.name))}async listTools($){let Y=this.requireServer($),T=Y.toolCacheUpdatedAt??0;if(Y.toolCache&&G1()-T<=this.toolsCacheTtlMs)return Y.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let Y=this.requireServer($),q=await(await this.ensureConnectedClient(Y)).listTools(),X=hN(q);return Y.toolCache=X,Y.toolCacheUpdatedAt=G1(),Y.updatedAt=G1(),X})}async callTool($){return this.runExclusive($.serverName,async()=>{let Y=this.requireServer($.serverName),T=await this.ensureConnectedClient(Y);return Y.updatedAt=G1(),T.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let Y of $)await this.unregisterServer(Y)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=G1();try{let Y=$.client??await this.clientFactory($.registration);await Y.connect(),$.client=Y,$.status="connected",$.lastError=void 0,$.updatedAt=G1()}catch(Y){throw $.status="disconnected",$.lastError=Y instanceof Error?Y.message:String(Y),$.updatedAt=G1(),Y}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=G1();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=G1()}}requireServer($){let Y=this.servers.get($);if(!Y)throw Error(`Unknown MCP server: ${$}`);return Y}async runExclusive($,Y){let T=this.operationLocks.get($)??Promise.resolve(),q,X=new Promise((Q)=>{q=Q}),J=T.catch(()=>{return}).then(()=>X);this.operationLocks.set($,J),await T.catch(()=>{return});try{return await Y()}finally{if(q?.(),this.operationLocks.get($)===J)this.operationLocks.delete($)}}}import{existsSync as PU,mkdirSync as iN,readFileSync as rN,writeFileSync as aN}from"node:fs";import{basename as LU,dirname as O4}from"node:path";import{providers as B4}from"@clinebot/llms";import{z as N$}from"zod";var MU=B4.ProviderSettingsSchema,M6=B4.toProviderConfig,BU=N$.object({settings:B4.ProviderSettingsSchema,updatedAt:N$.string().datetime(),tokenSource:N$.enum(["manual","oauth","migration"]).default("manual")}),P8=N$.object({version:N$.literal(1),lastUsedProvider:N$.string().min(1).optional(),providers:N$.record(N$.string(),BU)});function FY(){return{version:1,providers:{}}}import{existsSync as _N,readFileSync as gN}from"node:fs";import{join as RU}from"node:path";import{models as mN,providers as fN}from"@clinebot/llms";function c($){let Y=$?.trim();return Y?Y:void 0}function OU($){if(!_N($))return;try{let Y=gN($,"utf8"),T=JSON.parse(Y);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return}function bN($){let Y=$.dataDir??t0(),T=$.globalStatePath??RU(Y,"globalState.json"),q=$.secretsPath??RU(Y,"secrets.json"),X=OU(T),J=OU(q);if(!X&&!J)return;return{globalState:X??{},secrets:J??{}}}function uN($,Y,T,q){let X=T==="plan"?"planMode":"actMode",J=Y===q?c(T==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,U={openrouter:`${X}OpenRouterModelId`,cline:`${X}ClineModelId`,openai:`${X}OpenAiModelId`,ollama:`${X}OllamaModelId`,lmstudio:`${X}LmStudioModelId`,litellm:`${X}LiteLlmModelId`,requesty:`${X}RequestyModelId`,together:`${X}TogetherModelId`,fireworks:`${X}FireworksModelId`,sapaicore:`${X}SapAiCoreModelId`,groq:`${X}GroqModelId`,baseten:`${X}BasetenModelId`,huggingface:`${X}HuggingFaceModelId`,"huawei-cloud-maas":`${X}HuaweiCloudMaasModelId`,oca:`${X}OcaModelId`,aihubmix:`${X}AihubmixModelId`,hicap:`${X}HicapModelId`,nousResearch:`${X}NousResearchModelId`,"vercel-ai-gateway":`${X}VercelAiGatewayModelId`}[Y];return(U?c(typeof $[U]==="string"?$[U]:void 0):void 0)??J}function dN($,Y,T){let q=T==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,X=T==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,J=T==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,Q=(Y==="gemini"?X:void 0)??q,U=Q==="none"||Q==="low"||Q==="medium"||Q==="high"?Q:void 0,Z=typeof J==="number"&&Number.isInteger(J)&&J>0?J:void 0;if(!U&&Z===void 0)return;return{...U?{effort:U}:{},...Z!==void 0?{budgetTokens:Z}:{}}}function cN($){let Y=$["openai-codex-oauth-credentials"];if(!Y)return;try{let T=JSON.parse(Y),q=c(T.access_token),X=c(T.refresh_token),J=c(T.accountId);if(!q&&!X&&!J)return;return{...q?{apiKey:q}:{},auth:{...q?{accessToken:q}:{},...X?{refreshToken:X}:{},...J?{accountId:J}:{}}}}catch{return}}function pN($){let Y=mN.getGeneratedModelsForProvider($);return Object.keys(Y)[0]??void 0}function lN($,Y,T,q){let X=c(q==="plan"?Y.planModeApiProvider:Y.actModeApiProvider),J=uN(Y,$,q,X)??pN($),Q=dN(Y,$,q),U=typeof Y.requestTimeoutMs==="number"&&Number.isInteger(Y.requestTimeoutMs)&&Y.requestTimeoutMs>0?Y.requestTimeoutMs:void 0,Z={anthropic:T.apiKey,cline:T.clineApiKey,openai:T.openAiApiKey,"openai-native":T.openAiNativeApiKey,openrouter:T.openRouterApiKey,bedrock:T.awsBedrockApiKey,gemini:T.geminiApiKey,ollama:T.ollamaApiKey,deepseek:T.deepSeekApiKey,requesty:T.requestyApiKey,together:T.togetherApiKey,fireworks:T.fireworksApiKey,qwen:T.qwenApiKey,doubao:T.doubaoApiKey,mistral:T.mistralApiKey,litellm:T.liteLlmApiKey,asksage:T.asksageApiKey,xai:T.xaiApiKey,moonshot:T.moonshotApiKey,zai:T.zaiApiKey,huggingface:T.huggingFaceApiKey,nebius:T.nebiusApiKey,sambanova:T.sambanovaApiKey,cerebras:T.cerebrasApiKey,groq:T.groqApiKey,"huawei-cloud-maas":T.huaweiCloudMaasApiKey,baseten:T.basetenApiKey,"vercel-ai-gateway":T.vercelAiGatewayApiKey,dify:T.difyApiKey,minimax:T.minimaxApiKey,hicap:T.hicapApiKey,aihubmix:T.aihubmixApiKey,nousResearch:T.nousResearchApiKey,oca:T.ocaApiKey,sapaicore:T.sapAiCoreClientId},K={};if($==="openai-codex")Object.assign(K,cN(T));if($==="cline"){let D=c(T["cline:clineAccountId"]??T.clineAccountId);if(D)K.auth={...K.auth??{},accountId:D}}if($==="openai"&&Y.openAiHeaders)K.headers=Y.openAiHeaders;if($==="bedrock")K.aws={accessKey:c(T.awsAccessKey),secretKey:c(T.awsSecretKey),sessionToken:c(T.awsSessionToken),region:c(Y.awsRegion),authentication:Y.awsAuthentication,profile:Y.awsUseProfile?c(Y.awsProfile):void 0,usePromptCache:Y.awsBedrockUsePromptCache,useCrossRegionInference:Y.awsUseCrossRegionInference,useGlobalInference:Y.awsUseGlobalInference,endpoint:c(Y.awsBedrockEndpoint),customModelBaseId:c(q==="plan"?Y.planModeAwsBedrockCustomModelBaseId:Y.actModeAwsBedrockCustomModelBaseId)};if($==="vertex")K.gcp={projectId:c(Y.vertexProjectId),region:c(Y.vertexRegion)};if($==="openai"&&(Y.azureApiVersion||Y.azureIdentity!==void 0))K.azure={apiVersion:c(Y.azureApiVersion),useIdentity:Y.azureIdentity};if($==="sapaicore")K.sap={clientId:c(T.sapAiCoreClientId),clientSecret:c(T.sapAiCoreClientSecret),tokenUrl:c(Y.sapAiCoreTokenUrl),resourceGroup:c(Y.sapAiResourceGroup),deploymentId:c(q==="plan"?Y.planModeSapAiCoreDeploymentId:Y.actModeSapAiCoreDeploymentId),useOrchestrationMode:Y.sapAiCoreUseOrchestrationMode};if($==="oca"){K.oca={mode:Y.ocaMode};let D=c(T.ocaRefreshToken);if(D)K.auth={...K.auth??{},refreshToken:D}}if($==="qwen")K.apiLine=Y.qwenApiLine;if($==="moonshot")K.apiLine=Y.moonshotApiLine;if($==="zai")K.apiLine=Y.zaiApiLine;if($==="minimax")K.apiLine=Y.minimaxApiLine;let A={anthropic:Y.anthropicBaseUrl,openai:Y.openAiBaseUrl,ollama:Y.ollamaBaseUrl,lmstudio:Y.lmStudioBaseUrl,litellm:Y.liteLlmBaseUrl,gemini:Y.geminiBaseUrl,requesty:Y.requestyBaseUrl,asksage:Y.asksageApiUrl,dify:Y.difyBaseUrl,oca:Y.ocaBaseUrl,aihubmix:Y.aihubmixBaseUrl,sapaicore:Y.sapAiCoreBaseUrl},W=c(Z[$]),E=c(A[$]),V={provider:$,...W?{apiKey:W}:{},...J?{model:J}:{},...E?{baseUrl:E}:{},...Q?{reasoning:Q}:{},...U?{timeout:U}:{},...K},F=fN.ProviderSettingsSchema.safeParse(V);if(!F.success)return;return Object.keys(V).filter((D)=>D!=="provider").length>0?F.data:void 0}function nN($,Y){let T=new Set;for(let q of[$.actModeApiProvider,$.planModeApiProvider]){let X=c(q);if(X)T.add(X)}if(c(Y.apiKey))T.add("anthropic");if(c(Y.openRouterApiKey))T.add("openrouter");if(c(Y.openAiApiKey))T.add("openai");if(c(Y.openAiNativeApiKey))T.add("openai-native");if(c(Y["openai-codex-oauth-credentials"]))T.add("openai-codex");if(c(Y.geminiApiKey))T.add("gemini");if(c(Y.ollamaApiKey))T.add("ollama");if(c(Y.awsAccessKey)||c(Y.awsBedrockApiKey))T.add("bedrock");if(c($.vertexProjectId)||c($.vertexRegion))T.add("vertex");if(c(Y.clineApiKey))T.add("cline");if(c(Y.ocaApiKey))T.add("oca");return T}function R4($){let Y=$.providerSettingsManager.read(),T=bN($);if(!T)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let{globalState:q,secrets:X}=T,J=q.mode==="plan"?"plan":"act",Q=nN(q,X),U=FY();U.providers={...Y.providers},U.lastUsedProvider=Y.lastUsedProvider;let Z=new Date().toISOString(),K=0;for(let W of Q){if(U.providers[W])continue;let E=lN(W,q,X,J);if(!E)continue;U.providers[W]={settings:E,updatedAt:Z,tokenSource:"migration"},K+=1}if(K===0)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let A=c(J==="plan"?q.planModeApiProvider:q.actModeApiProvider);return U.lastUsedProvider=Y.lastUsedProvider??(A&&U.providers[A]?A:Object.keys(U.providers)[0]),$.providerSettingsManager.write(U),{migrated:!0,providerCount:Object.keys(U.providers).length,lastUsedProvider:U.lastUsedProvider}}function oN(){return new Date().toISOString()}function sN($){if(LU($)!=="providers.json")return;let Y=O4($);if(LU(Y)!=="settings")return;return O4(Y)}class d${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??z9(),this.dataDir=$.dataDir??sN(this.filePath),this.dataDir||!$.filePath)R4({providerSettingsManager:this,dataDir:this.dataDir})}getFilePath(){return this.filePath}read(){if(!PU(this.filePath))return FY();try{let $=rN(this.filePath,"utf8"),Y=JSON.parse($),T=P8.safeParse(Y);if(T.success)return T.data}catch{}return FY()}write($){let Y=P8.parse($),T=O4(this.filePath);if(!PU(T))iN(T,{recursive:!0});aN(this.filePath,`${JSON.stringify(Y,null,2)}
|
|
342
|
+
`,"utf8")}saveProviderSettings($,Y={}){let T=MU.parse($),q=this.read(),X=T.provider,J=Y.setLastUsed!==!1,Q=q.providers[X],U=Y.tokenSource??Q?.tokenSource??"manual",Z={...q,providers:{...q.providers,[X]:{settings:T,updatedAt:oN(),tokenSource:U}},lastUsedProvider:J?X:q.lastUsedProvider};return this.write(Z),Z}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),Y=$.lastUsedProvider;if(!Y)return;return $.providers[Y]?.settings}getProviderConfig($){let Y=this.getProviderSettings($);if(!Y)return;return M6(Y)}getLastUsedProviderConfig(){let $=this.getLastUsedProviderSettings();if(!$)return;return M6($)}}import{existsSync as eN,mkdirSync as $H}from"node:fs";import{join as YH}from"node:path";import{createRequire as tN}from"node:module";function O0(){return new Date().toISOString()}function e0($){return $?1:0}function Q0($){return typeof $==="string"?$:""}function K0($){if(typeof $!=="string")return;let Y=$.trim();return Y.length>0?Y:void 0}function $1($){return $===1||$===!0}function NY($){let Y=tN(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:J}=Y("bun:sqlite"),Q=new J($,{create:!0});return{prepare:(U)=>{let Z=Q.query(U);return{run:(...K)=>Z.run(...K),get:(...K)=>Z.get(...K),all:(...K)=>Z.all(...K)}},exec:(U)=>Q.exec(U)}}try{let J=["node",":sqlite"].join(""),{DatabaseSync:Q}=Y(J),U=new Q($);return{prepare:(Z)=>{let K=U.prepare(Z);return{run:(...A)=>K.run(...A),get:(...A)=>K.get(...A)??null,all:(...A)=>K.all(...A)}},exec:(Z)=>U.exec(Z)}}catch{}let q=["better","-sqlite3"].join("");return new(Y(q))($)}function L8($,Y={}){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
|
|
343
343
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
344
344
|
session_id TEXT PRIMARY KEY,
|
|
345
345
|
source TEXT NOT NULL,
|
|
@@ -430,7 +430,7 @@ process.on("message", async (message) => {
|
|
|
430
430
|
`),$.exec(`
|
|
431
431
|
CREATE INDEX IF NOT EXISTS idx_schedules_next_run
|
|
432
432
|
ON schedules(enabled, next_run_at);
|
|
433
|
-
`),!Y.includeLegacyMigrations)return;let T=$.prepare("PRAGMA table_info(sessions);").all(),q=(Q)=>T.some((U)=>U.name===Q);if(!q("workspace_root"))$.exec("ALTER TABLE sessions ADD COLUMN workspace_root TEXT;"),$.exec("UPDATE sessions SET workspace_root = cwd WHERE workspace_root IS NULL OR workspace_root = '';");if(!q("parent_session_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_session_id TEXT;");if(!q("parent_agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_agent_id TEXT;");if(!q("agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN agent_id TEXT;");if(!q("conversation_id"))$.exec("ALTER TABLE sessions ADD COLUMN conversation_id TEXT;");if(!q("is_subagent"))$.exec("ALTER TABLE sessions ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0;");if(!q("messages_path"))$.exec("ALTER TABLE sessions ADD COLUMN messages_path TEXT;");if(!q("metadata_json"))$.exec("ALTER TABLE sessions ADD COLUMN metadata_json TEXT;");let X=$.prepare("PRAGMA table_info(schedules);").all(),J=(Q)=>X.some((U)=>U.name===Q);if(!J("claim_token"))$.exec("ALTER TABLE schedules ADD COLUMN claim_token TEXT;");if(!J("claim_started_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_started_at TEXT;");if(!J("claim_until_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_until_at TEXT;")}function
|
|
433
|
+
`),!Y.includeLegacyMigrations)return;let T=$.prepare("PRAGMA table_info(sessions);").all(),q=(Q)=>T.some((U)=>U.name===Q);if(!q("workspace_root"))$.exec("ALTER TABLE sessions ADD COLUMN workspace_root TEXT;"),$.exec("UPDATE sessions SET workspace_root = cwd WHERE workspace_root IS NULL OR workspace_root = '';");if(!q("parent_session_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_session_id TEXT;");if(!q("parent_agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_agent_id TEXT;");if(!q("agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN agent_id TEXT;");if(!q("conversation_id"))$.exec("ALTER TABLE sessions ADD COLUMN conversation_id TEXT;");if(!q("is_subagent"))$.exec("ALTER TABLE sessions ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0;");if(!q("messages_path"))$.exec("ALTER TABLE sessions ADD COLUMN messages_path TEXT;");if(!q("metadata_json"))$.exec("ALTER TABLE sessions ADD COLUMN metadata_json TEXT;");let X=$.prepare("PRAGMA table_info(schedules);").all(),J=(Q)=>X.some((U)=>U.name===Q);if(!J("claim_token"))$.exec("ALTER TABLE schedules ADD COLUMN claim_token TEXT;");if(!J("claim_started_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_started_at TEXT;");if(!J("claim_until_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_until_at TEXT;")}function TH(){return jT()}function HY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function qH($){return{...$,tasks:$.tasks.map((Y)=>({...Y,createdAt:new Date(Y.createdAt),updatedAt:new Date(Y.updatedAt)})),mailbox:$.mailbox.map((Y)=>({...Y,sentAt:new Date(Y.sentAt),readAt:Y.readAt?new Date(Y.readAt):void 0})),missionLog:$.missionLog.map((Y)=>({...Y,ts:new Date(Y.ts)})),runs:($.runs??[]).map((Y)=>({...Y,startedAt:new Date(Y.startedAt),endedAt:Y.endedAt?new Date(Y.endedAt):void 0,nextAttemptAt:Y.nextAttemptAt?new Date(Y.nextAttemptAt):void 0,heartbeatAt:Y.heartbeatAt?new Date(Y.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Y)=>({...Y,createdAt:new Date(Y.createdAt),finalizedAt:Y.finalizedAt?new Date(Y.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Y)=>({...Y,createdAt:new Date(Y.createdAt),reviewedAt:Y.reviewedAt?new Date(Y.reviewedAt):void 0}))}}class B6{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??TH()}init(){this.getRawDb()}ensureTeamDir(){if(!eN(this.teamDirPath))$H(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return YH(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=NY(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){$.exec(`
|
|
434
434
|
CREATE TABLE IF NOT EXISTS team_events (
|
|
435
435
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
436
436
|
team_name TEXT NOT NULL,
|
|
@@ -507,7 +507,7 @@ process.on("message", async (message) => {
|
|
|
507
507
|
version INTEGER NOT NULL DEFAULT 1,
|
|
508
508
|
PRIMARY KEY(team_name, fragment_id)
|
|
509
509
|
);
|
|
510
|
-
`)}run($,Y=[]){return this.getRawDb().prepare($).run(...Y)}queryOne($,Y=[]){return this.getRawDb().prepare($).get(...Y)??void 0}queryAll($,Y=[]){return this.getRawDb().prepare($).all(...Y)}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let Y=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[HY($)]);if(!Y)return;return
|
|
510
|
+
`)}run($,Y=[]){return this.getRawDb().prepare($).run(...Y)}queryOne($,Y=[]){return this.getRawDb().prepare($).get(...Y)??void 0}queryAll($,Y=[]){return this.getRawDb().prepare($).all(...Y)}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let Y=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[HY($)]);if(!Y)return;return qH(JSON.parse(Y.state_json))}readHistory($,Y=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[HY($),Y]).map((T)=>({eventType:T.event_type,payload:JSON.parse(T.payload_json),ts:T.ts}))}loadRuntime($){let Y=HY($),T=this.readState(Y),q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Y]),X=q?JSON.parse(q.teammates_json):[],J=this.markInProgressRunsInterrupted(Y,"runtime_recovered");return{state:T,teammates:X,interruptedRunIds:J}}appendTeamEvent($,Y,T,q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
|
|
511
511
|
VALUES (?, ?, ?, ?, NULL, ?)`,[HY($),O0(),Y,JSON.stringify(T),q??null])}persistRuntime($,Y,T){let q=HY($),X=O0();this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
|
|
512
512
|
VALUES (?, ?, ?, ?)
|
|
513
513
|
ON CONFLICT(team_name) DO UPDATE SET
|
|
@@ -554,36 +554,36 @@ process.on("message", async (message) => {
|
|
|
554
554
|
reviewed_by = excluded.reviewed_by,
|
|
555
555
|
reviewed_at = excluded.reviewed_at,
|
|
556
556
|
version = team_outcome_fragments.version + 1`,[q,J.outcomeId,J.id,J.section,J.sourceAgentId,J.sourceRunId??null,J.content,J.status,J.reviewedBy??null,J.reviewedAt?J.reviewedAt.toISOString():null])}markInProgressRunsInterrupted($,Y){let T=HY($),q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[T]);if(q.length===0)return[];let X=O0();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
|
|
557
|
-
WHERE team_name = ? AND status IN ('queued', 'running')`,[Y,X,T]),q.map((J)=>J.run_id)}handleTeamEvent($,Y){this.appendTeamEvent($,Y.type,Y)}}function x1(){return new Date().toISOString()}function
|
|
558
|
-
`,"utf8")}function
|
|
557
|
+
WHERE team_name = ? AND status IN ('queued', 'running')`,[Y,X,T]),q.map((J)=>J.run_id)}handleTeamEvent($,Y){this.appendTeamEvent($,Y.type,Y)}}function x1(){return new Date().toISOString()}function wU($,Y){if(Y<=0)return 0;return Math.round($/Y*100)}function XH($,Y){let T=new Set;for(let X of Y)if(X.status==="reviewed")T.add(`${X.outcomeId}:${X.section}`);let q=new Set;for(let X of $){if(X.status==="finalized")continue;for(let J of X.requiredSections)if(!T.has(`${X.id}:${J}`))q.add(`${X.id}:${J}`)}return[...q].sort((X,J)=>X.localeCompare(J))}function w8($,Y){let T={idle:0,running:0,stopped:0},q={pending:0,in_progress:0,blocked:0,completed:0},X={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},J={draft:0,in_review:0,finalized:0},Q={draft:0,reviewed:0,rejected:0},U=0,Z=0;for(let D of Y.members)if(T[D.status]+=1,D.role==="lead")U+=1;else Z+=1;let K=[],A=[],W=Y.tasks.filter((D)=>D.status==="completed").length,E=new Map(Y.tasks.map((D)=>[D.id,D]));for(let D of Y.tasks){if(q[D.status]+=1,D.status==="blocked"){K.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((S)=>{return E.get(S)?.status==="completed"}))A.push(D.id)}let V=[],F,H=0;for(let D of Y.runs){if(X[D.status]+=1,D.status==="queued"||D.status==="running")V.push(D.id);let I=D.startedAt.getTime();if(I>=H)H=I,F=D.id}for(let D of Y.outcomes)J[D.status]+=1;for(let D of Y.outcomeFragments)Q[D.status]+=1;return{teamName:$,updatedAt:x1(),members:{total:Y.members.length,byStatus:T,leadCount:U,teammateCount:Z},tasks:{total:Y.tasks.length,byStatus:q,blockedTaskIds:K,readyTaskIds:A,completionPct:wU(W,Y.tasks.length)},runs:{total:Y.runs.length,byStatus:X,activeRunIds:V,latestRunId:F},outcomes:{total:Y.outcomes.length,byStatus:J,finalizedPct:wU(J.finalized,Y.outcomes.length),missingRequiredSections:XH(Y.outcomes,Y.outcomeFragments)},fragments:{total:Y.outcomeFragments.length,byStatus:Q}}}function S8($){let{event:Y}=$;switch(Y.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),taskId:Y.task.id,agentId:Y.task.assignee??Y.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),runId:Y.run.id,taskId:Y.run.taskId,agentId:Y.run.agentId,message:Y.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),runId:Y.run.id,taskId:Y.run.taskId,agentId:Y.run.agentId,message:Y.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),outcomeId:Y.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),outcomeId:Y.fragment.outcomeId,fragmentId:Y.fragment.id,agentId:Y.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),taskId:Y.message.taskId,agentId:Y.message.fromAgentId,message:Y.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),taskId:Y.entry.taskId,agentId:Y.entry.agentId,message:Y.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),agentId:Y.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1()}}var P4=w9,R6;((Q)=>{Q.CLI="cli";Q.CLI_SUBAGENT="cli-subagent";Q.CORE="core";Q.CORE_SUBAGENT="core-subagent";Q.DESKTOP="desktop";Q.DESKTOP_CHAT="desktop-chat"})(R6||={});import{mkdir as JH,readFile as QH,writeFile as UH}from"node:fs/promises";import{dirname as CU,join as ZH}from"node:path";import{models as O6}from"@clinebot/llms";function KH($){return $.apiKey??$.auth?.apiKey}function AH($){return($.auth?.accessToken?.trim()??"").length>0}function yU($){return $.split(/[-_]/).filter(Boolean).map((Y)=>Y.charAt(0).toUpperCase()+Y.slice(1)).join(" ")}function WH($){let Y=$.split(/\s+/).map((T)=>T.trim()).filter(Boolean);if(Y.length===0)return"?";if(Y.length===1)return Y[0].slice(0,2).toUpperCase();return`${Y[0][0]}${Y[1][0]}`.toUpperCase()}function GH($){let Y=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],T=0;for(let q of $)T=T*31+q.charCodeAt(0)>>>0;return Y[T%Y.length]}function jU($){return ZH(CU($.getFilePath()),"models.json")}function EH(){return{version:1,providers:{}}}async function vU($){try{let Y=await QH($,"utf8"),T=JSON.parse(Y);if(T&&T.version===1&&T.providers&&typeof T.providers==="object")return{version:1,providers:T.providers}}catch{}return EH()}async function VH($,Y){await JH(CU($),{recursive:!0}),await UH($,`${JSON.stringify(Y,null,2)}
|
|
558
|
+
`,"utf8")}function DH($,Y){return{id:$,name:Y.name??$,supportsAttachments:Y.capabilities?.includes("files"),supportsVision:Y.capabilities?.includes("images"),supportsReasoning:Y.capabilities?.includes("reasoning")||Y.thinkingConfig!=null}}function FH($){if(!$||$.length===0)return;let Y=new Set;if($.includes("reasoning"))Y.add("reasoning");if($.includes("prompt-cache"))Y.add("prompt-cache");if($.includes("tools"))Y.add("tools");return Y.size>0?[...Y]:void 0}function NH($){let Y=new Set;if(!$||$.length===0)return[...Y];if($.includes("streaming"))Y.add("streaming");if($.includes("tools"))Y.add("tools");if($.includes("reasoning"))Y.add("reasoning");if($.includes("prompt-cache"))Y.add("prompt-cache");if($.includes("vision"))Y.add("images"),Y.add("files");return[...Y]}function xU($,Y){let T=NH(Y.provider.capabilities),q=Object.values(Y.models).map((Q)=>Q.id.trim()).filter((Q)=>Q.length>0),X=Y.provider.defaultModelId?.trim()||q[0]||"default",J=Object.fromEntries(q.map((Q)=>[Q,{id:Q,name:Y.models[Q]?.name??Q,capabilities:T.length>0?T:void 0,status:"active"}]));O6.registerProvider({provider:{id:$,name:Y.provider.name.trim()||yU($),protocol:"openai-chat",baseUrl:Y.provider.baseUrl,defaultModelId:X,capabilities:FH(Y.provider.capabilities)},models:J})}var SU=!1;async function HH($){if(SU)return;let Y=jU($),T=await vU(Y);for(let[q,X]of Object.entries(T.providers))xU(q,X);SU=!0}function L4($){if(Array.isArray($))return $.map((Y)=>{if(typeof Y==="string")return Y.trim();if(Y&&typeof Y==="object"&&"id"in Y){let T=Y.id;return typeof T==="string"?T.trim():""}return""}).filter((Y)=>Y.length>0);return[]}function zH($,Y){let T=L4($);if(T.length>0)return T;if(!$||typeof $!=="object")return[];let q=$,X=L4(q.data??q.models);if(X.length>0)return X;if(q.models&&typeof q.models==="object"&&!Array.isArray(q.models)){let Q=Object.keys(q.models).filter((U)=>U.trim().length>0);if(Q.length>0)return Q}let J=q.providers?.[Y];if(J&&typeof J==="object"){let U=L4(J.models??J);if(U.length>0)return U}return[]}async function IH($,Y){let T=await fetch($,{method:"GET"});if(!T.ok)throw Error(`failed to fetch models from ${$}: HTTP ${T.status}`);let q=await T.json();return zH(q,Y)}async function MH($,Y){let T=Y.providerId.trim().toLowerCase();if(!T)throw Error("providerId is required");if(O6.hasProvider(T))throw Error(`provider "${T}" already exists`);let q=Y.name.trim();if(!q)throw Error("name is required");let X=Y.baseUrl.trim();if(!X)throw Error("baseUrl is required");let J=(Y.models??[]).map((I)=>I.trim()).filter((I)=>I.length>0),Q=Y.modelsSourceUrl?.trim(),U=Q?await IH(Q,T):[],Z=[...new Set([...J,...U])];if(Z.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let K=Y.defaultModelId?.trim()&&Z.includes(Y.defaultModelId.trim())?Y.defaultModelId.trim():Z[0],A=Y.capabilities?.length?[...new Set(Y.capabilities)]:void 0,W=Object.entries(Y.headers??{}).filter(([I])=>I.trim().length>0);$.saveProviderSettings({provider:T,apiKey:Y.apiKey?.trim()?Y.apiKey:void 0,baseUrl:X,headers:W.length>0?Object.fromEntries(W):void 0,timeout:Y.timeoutMs,model:K},{setLastUsed:!1});let E=jU($),V=await vU(E),F=A?.includes("vision")??!1,H=F,D=A?.includes("reasoning")??!1;return V.providers[T]={provider:{name:q,baseUrl:X,defaultModelId:K,capabilities:A,modelsSourceUrl:Q},models:Object.fromEntries(Z.map((I)=>[I,{id:I,name:I,supportsVision:F,supportsAttachments:H,supportsReasoning:D}]))},await VH(E,V),xU(T,V.providers[T]),{providerId:T,settingsPath:$.getFilePath(),modelsPath:E,modelsCount:Z.length}}async function BH($){let Y=$.read(),T=O6.getProviderIds().sort((X,J)=>X.localeCompare(J));return{providers:await Promise.all(T.map(async(X)=>{let J=await O6.getProvider(X),Q=await kU(X),U=Y.providers[X]?.settings,Z=J?.name??yU(X);return{id:X,name:Z,models:Q.models.length,color:GH(X),letter:WH(Z),enabled:Boolean(U),apiKey:U?KH(U):void 0,oauthAccessTokenPresent:U?AH(U):void 0,baseUrl:U?.baseUrl??J?.baseUrl,defaultModelId:J?.defaultModelId,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:Q.models}})),settingsPath:$.getFilePath()}}async function kU($){let Y=$.trim(),T=await O6.getModelsForProvider(Y),q=Object.entries(T).sort(([X],[J])=>X.localeCompare(J)).map(([X,J])=>DH(X,J));return{providerId:Y,models:q}}function RH($,Y){let T=Y.providerId.trim(),q=$.read();if(Y.enabled===!1){if(delete q.providers[T],q.lastUsedProvider===T)delete q.lastUsedProvider;return $.write(q),{providerId:T,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(T)??{},provider:T};if(Object.hasOwn(Y,"apiKey")&&typeof Y.apiKey==="string")if((Y.apiKey?.trim()??"").length===0)delete J.apiKey;else J.apiKey=Y.apiKey;if(Object.hasOwn(Y,"baseUrl")&&typeof Y.baseUrl==="string")if((Y.baseUrl?.trim()??"").length===0)delete J.baseUrl;else J.baseUrl=Y.baseUrl;return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:T,enabled:!0,settingsPath:$.getFilePath()}}function OH($){let Y=$.trim().toLowerCase();if(Y==="codex"||Y==="openai-codex")return"openai-codex";if(Y==="cline"||Y==="oca")return Y;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function PH($,Y){if($==="cline")return`workos:${Y.access}`;return Y.access}async function LH($,Y,T){let q=J4({onPrompt:async(X)=>X.defaultValue??"",openUrl:T,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});if($==="cline")return z8({apiBaseUrl:Y?.baseUrl?.trim()||"https://api.cline.bot",callbacks:q});if($==="oca")return R8({mode:Y?.oca?.mode,callbacks:q});return M8(q)}function wH($,Y,T,q){let X={...T?.auth??{},accessToken:PH(Y,q),refreshToken:q.refresh,accountId:q.accountId};X.expiresAt=q.expires;let J={...T??{provider:Y},provider:Y,auth:X};return $.saveProviderSettings(J,{tokenSource:"oauth"}),J}function SH($){let Y=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return Y&&Y.length>0?Y:void 0}function hU($){return $.disabled!==!0}function _U($){if($.length===0)return"";return`
|
|
559
559
|
|
|
560
560
|
# Rules
|
|
561
561
|
${$.map((T)=>`## ${T.name}
|
|
562
562
|
${T.instructions}`).join(`
|
|
563
563
|
|
|
564
|
-
`)}`}function
|
|
564
|
+
`)}`}function gU($){return[...$.getSnapshot("rule").values()].map((T)=>T.item).filter(hU).sort((T,q)=>T.name.localeCompare(q.name))}function CH($){return _U(gU($))}import{existsSync as w4,readdirSync as yH}from"node:fs";import{join as mU}from"node:path";import{AgentTeamsRuntime as jH,bootstrapAgentTeams as vH}from"@clinebot/agents";import{nanoid as xH}from"nanoid";var kH="# Workspace Configuration";function dU(){return`agent-team-${xH(5)}`}function fU($,Y,T,q,X,J,Q){let U=T==="plan"?t1.readonly:t1.development,Z=_9(Y,q,T,X??h9);return N6({cwd:$,...U,...Z,enableSkills:!!J,executors:{...J?{skills:J}:{},...Q??{}}})}var bU="SKILL.md";function hH($){return S4($).filter((Y)=>!Y.disabled).map((Y)=>Y.name.trim()).filter((Y)=>Y.length>0).sort((Y,T)=>Y.localeCompare(T))}function S4($){return[...$.getSnapshot("skill").entries()].map(([T,q])=>{let X=q.item;return{id:T,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0}})}function uU($){for(let Y of D6($)){if(!w4(Y))continue;let T=mU(Y,bU);if(w4(T))return!0;try{let q=yH(Y,{withFileTypes:!0});for(let X of q){if(!X.isDirectory())continue;if(w4(mU(Y,X.name,bU)))return!0}}catch{}}return!1}function _H($,Y){let T=Y.trim().replace(/^\/+/,"").toLowerCase();if(!T)return{error:"Missing skill name."};let q=$.getSnapshot("skill"),X=q.get(T);if(X){let Z=X.item;if(Z.disabled===!0)return{error:`Skill "${Z.name}" is configured but disabled.`};return{id:T,skill:Z}}let J=T.includes(":")?T.split(":").at(-1)??T:T,Q=[...q.entries()].filter(([Z])=>{if(Z===J)return!0;return Z.endsWith(`:${J}`)});if(Q.length===1){let[Z,K]=Q[0],A=K.item;if(A.disabled===!0)return{error:`Skill "${A.name}" is configured but disabled.`};return{id:Z,skill:A}}if(Q.length>1)return{error:`Skill "${Y}" is ambiguous. Use one of: ${Q.map(([Z])=>Z).join(", ")}`};let U=hH($);return{error:U.length>0?`Skill "${Y}" not found. Available skills: ${U.join(", ")}`:"No skills are currently available."}}function gH($,Y){let T=new Set,q=async(X,J)=>{await Y;let Q=_H($,X);if("error"in Q)return Q.error;let{id:U,skill:Z}=Q;if(T.has(U))return`Skill "${Z.name}" is already running.`;T.add(U);try{let K=J?.trim(),A=K?`
|
|
565
565
|
<command-args>${K}</command-args>`:"",W=Z.description?.trim()?`Description: ${Z.description.trim()}
|
|
566
566
|
|
|
567
567
|
`:"";return`<command-name>${Z.name}</command-name>${A}
|
|
568
568
|
<command-instructions>
|
|
569
569
|
${W}${Z.instructions}
|
|
570
|
-
</command-instructions>`}finally{T.delete(U)}};return Object.defineProperty(q,"configuredSkills",{get:()=>
|
|
571
|
-
`,"utf8");let Z=Y.timeoutMs??300000,K=Y.pollIntervalMs??200,A=Date.now();while(Date.now()-A<Z){try{let W=await
|
|
572
|
-
`),q=[...$.appendMessages??[],...Y.appendMessages??[]];return{cancel:$.cancel===!0||Y.cancel===!0?!0:void 0,review:$.review===!0||Y.review===!0?!0:void 0,context:T||void 0,overrideInput:Y.overrideInput!==void 0?Y.overrideInput:$.overrideInput,systemPrompt:Y.systemPrompt!==void 0?Y.systemPrompt:$.systemPrompt,appendMessages:q.length>0?q:void 0}}function
|
|
573
|
-
`).map((J)=>J.trim()).filter(Boolean).filter((J)=>J.startsWith("HOOK_CONTROL\t")).map((J)=>J.slice(13)),X=q.length>0?q[q.length-1]:Y;try{return{parsedJson:JSON.parse(X)}}catch(J){return{parseError:J instanceof Error?J.message:"Failed to parse hook stdout JSON"}}}async function
|
|
574
|
-
`;oH($.hookLogPath),iH($.hookLogPath,X,"utf8")};return{onRunStart:async(q)=>{T({...n0(q,Y),hookName:"agent_start",taskStart:{taskMetadata:{}}}),T({...n0(q,Y),hookName:"prompt_submit",userPromptSubmit:{prompt:q.userMessage,attachments:[]}});return},onToolCallStart:async(q)=>{T({...n0(q,Y),hookName:"tool_call",iteration:q.iteration,tool_call:{id:q.call.id,name:q.call.name,input:q.call.input},preToolUse:{toolName:q.call.name,parameters:y8(q.call.input)}});return},onToolCallEnd:async(q)=>{T({...n0(q,Y),hookName:"tool_result",iteration:q.iteration,tool_result:q.record,postToolUse:{toolName:q.record.name,parameters:y8(q.record.input),result:typeof q.record.output==="string"?q.record.output:JSON.stringify(q.record.output),success:!q.record.error,executionTimeMs:q.record.durationMs}});return},onTurnEnd:async(q)=>{T({...n0(q,Y),hookName:"agent_end",iteration:q.iteration,turn:q.turn,taskComplete:{taskMetadata:{}}});return},onSessionShutdown:async(q)=>{if(dU(q.reason))T({...n0(q,Y),hookName:"agent_abort",reason:q.reason,taskCancel:{taskMetadata:{}}});T({...n0(q,Y),hookName:"session_shutdown",reason:q.reason});return}}}function lU($){let Y=$z($.workspacePath);if(!Object.values(Y).some((Z)=>(Z?.length??0)>0))return;let q=async(Z)=>{let K=Y.agent_start??[];if(K.length>0)zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}}});let A=Y.prompt_submit??[];if(A.length>0)zY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}}})},X=async(Z)=>{let K=Y.tool_call??[];if(K.length===0)return;return Yz({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...n0(Z,$),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:y8(Z.call.input)}}})},J=async(Z)=>{let K=Y.tool_result??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:y8(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}}})},Q=async(Z)=>{let K=Y.agent_end??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_end",iteration:Z.iteration,turn:Z.turn,taskComplete:{taskMetadata:{}}}})},U=async(Z)=>{if(dU(Z.reason)){let A=Y.agent_abort??[];if(A.length>0)zY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_abort",reason:Z.reason,taskCancel:{taskMetadata:{}}}})}let K=Y.session_shutdown??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"session_shutdown",reason:Z.reason}})};return{onRunStart:async(Z)=>{await q(Z);return},onToolCallStart:async(Z)=>X(Z),onToolCallEnd:async(Z)=>{await J(Z);return},onTurnEnd:async(Z)=>{await Q(Z);return},onSessionShutdown:async(Z)=>{await U(Z);return}}}function k1($,Y){let T=$.map((q)=>q[Y]).filter((q)=>typeof q==="function");if(T.length===0)return;return async(q)=>{let X;for(let J of T){let Q=await J(q);X=uU(X,Q)}return X}}function nU($){let Y=$.filter((T)=>T!==void 0);if(Y.length===0)return;return{onRunStart:k1(Y,"onRunStart"),onRunEnd:k1(Y,"onRunEnd"),onIterationStart:k1(Y,"onIterationStart"),onIterationEnd:k1(Y,"onIterationEnd"),onTurnStart:k1(Y,"onTurnStart"),onTurnEnd:k1(Y,"onTurnEnd"),onToolCallStart:k1(Y,"onToolCallStart"),onToolCallEnd:k1(Y,"onToolCallEnd"),onSessionShutdown:k1(Y,"onSessionShutdown"),onError:k1(Y,"onError")}}var Tz="https://api.cline.bot",C4="workos:",qz=["cline","oca","openai-codex"];function Xz($){return qz.includes($)}function Jz($,Y){if($==="cline")return`${C4}${Y}`;return Y}function Qz($,Y){if($==="cline"&&Y.toLowerCase().startsWith(C4))return Y.slice(C4.length);return Y}function Uz($){let T=W1($)?.exp;if(typeof T==="number"&&T>0)return T*1000;return null}function Zz($,Y){let T=$.auth?.expiresAt;if(typeof T==="number"&&Number.isFinite(T)&&T>0)return T;let q=Uz(Y);if(q)return q;return Date.now()-1}function Kz($,Y){let T=Y.auth?.accessToken?.trim(),q=Y.auth?.refreshToken?.trim();if(!T||!q)return null;let X=Qz($,T);if(!X)return null;return{access:X,refresh:q,expires:Zz(Y,X),accountId:Y.auth?.accountId}}function Az($,Y){let T=$?.expiresAt,q=Y?.expiresAt;return $?.accessToken===Y?.accessToken&&$?.refreshToken===Y?.refreshToken&&$?.accountId===Y?.accountId&&T===q}class j8 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class y4{providerSettingsManager;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new d$}async resolveProviderApiKey($){if(!Xz($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,Y=!1){let T=this.refreshInFlight.get($);if(T)return T;let q=this.resolveProviderApiKeyInternal($,Y).catch((X)=>{throw X}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,q),q}async resolveProviderApiKeyInternal($,Y){let T=this.providerSettingsManager.getProviderSettings($);if(!T)return null;let q=Kz($,T);if(!q)return null;let X=await this.resolveCredentials($,T,q,Y);if(!X)throw new j8($);let J=Jz($,X.access),Q={...T.auth??{},accessToken:J,refreshToken:X.refresh,accountId:X.accountId};Q.expiresAt=X.expires;let U={...T,auth:Q},Z=!Az(T.auth,U.auth);if(Z)this.providerSettingsManager.saveProviderSettings(U,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:J,accountId:X.accountId,refreshed:Z}}async resolveCredentials($,Y,T,q){if($==="cline")return K4(T,{apiBaseUrl:Y.baseUrl?.trim()||Tz},{forceRefresh:q});if($==="oca")return V4(T,{forceRefresh:q},{mode:Y.oca?.mode});return W4(T,{forceRefresh:q})}}import{existsSync as j4,mkdirSync as Wz,readdirSync as Gz,rmdirSync as Ez,unlinkSync as Vz}from"node:fs";import{dirname as iU,join as H$}from"node:path";function W0(){return new Date().toISOString()}function $$($){if(!$||!j4($))return;try{Vz($)}catch{}}class v4{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return H$(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let Y=this.sessionArtifactsDir($);if(!j4(Y))Wz(Y,{recursive:!0});return Y}sessionTranscriptPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.log`)}sessionHookPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.hooks.jsonl`)}sessionMessagesPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,Y=!0){let T=Y?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return H$(T,`${$}.json`)}removeSessionDirIfEmpty($){let Y=this.sessionArtifactsDir($),T=this.ensureSessionsDir();while(Y.startsWith(T)&&Y!==T){if(!j4(Y)){Y=iU(Y);continue}try{if(Gz(Y).length>0)break;Ez(Y)}catch{break}Y=iU(Y)}}subagentArtifactPaths($,Y,T){let q=this.ensureSessionArtifactsDir($);return{transcriptPath:H$(q,`${$}.log`),hookPath:H$(q,`${$}.hooks.jsonl`),messagesPath:H$(q,`${$}.messages.json`)}}}import{z as G0}from"zod";var Dz=G0.enum(O4),IY=G0.object({version:G0.literal(1),session_id:G0.string().min(1),source:G0.enum(RT),pid:G0.number().int(),started_at:G0.string().min(1),ended_at:G0.string().min(1).optional(),exit_code:G0.number().int().nullable().optional(),status:Dz,interactive:G0.boolean(),provider:G0.string().min(1),model:G0.string().min(1),cwd:G0.string().min(1),workspace_root:G0.string().min(1),team_name:G0.string().min(1).optional(),enable_tools:G0.boolean(),enable_spawn:G0.boolean(),enable_teams:G0.boolean(),prompt:G0.string().optional(),metadata:G0.record(G0.string(),G0.unknown()).optional(),messages_path:G0.string().min(1).optional()});var Fz="# Workspace Configuration";function rU($){let Y=$.lastIndexOf(Fz);if(Y<0)return;let T=$.slice(Y).trim();return T.length>0?T:void 0}function aU($){if(!$)return!1;return Object.values($).some((Y)=>typeof Y==="function")}function oU($,Y){let T=[...$??[],...Y??[]];if(T.length===0)return;let q=[],X=new Set;for(let J of T){if(X.has(J.name))continue;X.add(J.name),q.push(J)}return q}function sU($){return JSON.stringify($,(Y,T)=>{if(T instanceof Error)return{name:T.name,message:T.message,stack:T.stack};return T})}function tU($,Y){let T=$.map((U)=>({...U})),q=[...T].reverse().findIndex((U)=>U.role==="assistant");if(q===-1)return T;let X=T.length-1-q,J=T[X],Q=Y.usage;return T[X]={...J,providerId:J.providerId??Y.model.provider,modelId:J.modelId??Y.model.id,modelInfo:J.modelInfo??{id:Y.model.id,provider:Y.model.provider},metrics:{...J.metrics??{},inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens,cacheWriteTokens:Q.cacheWriteTokens,cost:Q.totalCost},ts:J.ts??Y.endedAt.getTime()},T}function x4($){let Y=typeof $.metadata_json==="string"&&$.metadata_json.trim().length>0?(()=>{try{let T=JSON.parse($.metadata_json);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return})():void 0;return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive===1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name??void 0,enableTools:$.enable_tools===1,enableSpawn:$.enable_spawn===1,enableTeams:$.enable_teams===1,parentSessionId:$.parent_session_id??void 0,parentAgentId:$.parent_agent_id??void 0,agentId:$.agent_id??void 0,conversationId:$.conversation_id??void 0,isSubagent:$.is_subagent===1,prompt:$.prompt??void 0,metadata:Y,transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??W0()}}function k4(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function h4($,Y){return{inputTokens:$.inputTokens+Math.max(0,Y.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,Y.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,Y.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,Y.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,Y.totalCost??0)}}var eU=5000,Pz=20480000;async function Lz($){let Y=await Hz($);if(!Y.isFile())throw Error("Path is not a file");if(Y.size>Pz)throw Error("File is too large to read into context.");let T=await Nz($,"utf8");if(T.includes("\x00"))throw Error("Cannot read binary file into context.");return T}class v8{sessionService;runtimeBuilder;createAgentInstance;defaultToolExecutors;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultRequestToolApproval;listeners=new Set;sessions=new Map;usageBySession=new Map;constructor($){let Y=zz();if(Y)S6(Y);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new S8,this.createAgentInstance=$.createAgent??((T)=>new Bz(T)),this.defaultToolExecutors=$.defaultToolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new d$,this.oauthTokenManager=$.oauthTokenManager??new y4({providerSettingsManager:this.providerSettingsManager}),this.defaultRequestToolApproval=$.requestToolApproval}resolveStoredProviderSettings($){let Y=this.providerSettingsManager.getProviderSettings($);if(Y)return Y;return{provider:$}}buildResolvedProviderConfig($){let Y=this.resolveStoredProviderSettings($.providerId),T={...Y,provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Y.apiKey,baseUrl:$.baseUrl??Y.baseUrl,headers:$.headers??Y.headers,reasoning:typeof $.thinking==="boolean"||typeof $.reasoningEffort==="string"?{...Y.reasoning??{},...typeof $.thinking==="boolean"?{enabled:$.thinking}:{},...typeof $.reasoningEffort==="string"?{effort:$.reasoningEffort}:{}}:Y.reasoning},q=MT(T);if($.knownModels)q.knownModels=$.knownModels;return q}async start($){let Y=$.source??"cli",T=W0(),q=$.config.sessionId?.trim()??"",X=q.length>0?q:`${Date.now()}_${Oz(5)}`;this.usageBySession.set(X,k4());let J=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!J)throw Error("session service method not available: ensureSessionsDir");let Q=PT(J,X),U=PT(Q,`${X}.log`),Z=PT(Q,`${X}.hooks.jsonl`),K=PT(Q,`${X}.messages.json`),A=PT(Q,`${X}.json`),W=IY.parse({version:1,session_id:X,source:Y,pid:process.pid,started_at:T,status:"running",interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspace_root:$.config.workspaceRoot??$.config.cwd,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,messages_path:K}),E=lU({cwd:$.config.cwd,workspacePath:$.config.workspaceRoot??$.config.cwd,rootSessionId:X,hookLogPath:Z,logger:$.config.logger}),D=aU($.config.hooks)?void 0:pU({hookLogPath:Z,rootSessionId:X,workspacePath:$.config.workspaceRoot??$.config.cwd}),F=nU([$.config.hooks,E,D]),H=await U8({pluginPaths:$.config.pluginPaths,workspacePath:$.config.workspaceRoot??$.config.cwd,cwd:$.config.cwd}),V=oU($.config.extensions,H.extensions),B={...$.config,hooks:F,extensions:V},S=this.buildResolvedProviderConfig(B),v={...B,providerConfig:S},z=this.runtimeBuilder.build({config:v,hooks:F,extensions:V,logger:v.logger,onTeamEvent:(C)=>{this.handleTeamEvent(X,C),v.onTeamEvent?.(C)},createSpawnTool:()=>this.createSpawnTool(v,X),onTeamRestored:$.onTeamRestored,userInstructionWatcher:$.userInstructionWatcher,defaultToolExecutors:$.defaultToolExecutors??this.defaultToolExecutors}),_=[...z.tools,...v.extraTools??[]],y=this.createAgentInstance({providerId:S.providerId,modelId:S.modelId,apiKey:S.apiKey,baseUrl:S.baseUrl,headers:S.headers,knownModels:S.knownModels,providerConfig:S,thinking:v.thinking,reasoningEffort:v.reasoningEffort??S.reasoningEffort,systemPrompt:v.systemPrompt,maxIterations:v.maxIterations,maxConsecutiveMistakes:v.maxConsecutiveMistakes,tools:_,hooks:F,extensions:V,hookErrorMode:v.hookErrorMode,initialMessages:$.initialMessages,userFileContentLoader:Lz,toolPolicies:$.toolPolicies??this.defaultToolPolicies,requestToolApproval:$.requestToolApproval??this.defaultRequestToolApproval,onConsecutiveMistakeLimitReached:v.onConsecutiveMistakeLimitReached,completionGuard:z.completionGuard,logger:z.logger??v.logger,onEvent:(C)=>{let j=this.sessions.get(X);if(C.type==="usage"&&j?.turnUsageBaseline)this.usageBySession.set(X,h4(j.turnUsageBaseline,{inputTokens:C.totalInputTokens,outputTokens:C.totalOutputTokens,totalCost:C.totalCost}));this.emit({type:"agent_event",payload:{sessionId:X,event:C}}),this.emit({type:"chunk",payload:{sessionId:X,stream:"agent",chunk:sU(C),ts:Date.now()}})}}),k={sessionId:X,config:v,source:Y,startedAt:T,pendingPrompt:W.prompt,runtime:z,agent:y,started:!1,aborting:!1,interactive:$.interactive===!0,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pluginSandboxShutdown:H.shutdown};this.sessions.set(k.sessionId,k),this.emitStatus(k.sessionId,"running");let m;try{if($.prompt?.trim()){if(m=await this.runTurn(k,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles}),!k.interactive)await this.finalizeSingleRun(k,m.finishReason)}}catch(C){throw await this.failSession(k),C}return{sessionId:X,manifest:W,manifestPath:A,transcriptPath:U,hookPath:Z,messagesPath:K,result:m}}async send($){let Y=this.sessions.get($.sessionId);if(!Y)throw Error(`session not found: ${$.sessionId}`);try{let T=await this.runTurn(Y,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles});if(!Y.interactive)await this.finalizeSingleRun(Y,T.finishReason);return T}catch(T){throw await this.failSession(Y),T}}async getAccumulatedUsage($){let Y=this.usageBySession.get($);if(!Y)return;return{...Y}}async abort($){let Y=this.sessions.get($);if(!Y)return;Y.aborting=!0,Y.agent.abort()}async stop($){let Y=this.sessions.get($);if(!Y)return;await this.shutdownSession(Y,{status:"cancelled",exitCode:null,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let Y=[...this.sessions.values()];if(Y.length===0)return;await Promise.allSettled(Y.map(async(T)=>{await this.shutdownSession(T,{status:"cancelled",exitCode:null,shutdownReason:$,endReason:"disposed"})})),this.usageBySession.clear()}async get($){let Y=await this.getRow($);return Y?x4(Y):void 0}async list($=200){return(await this.listRows($)).map((T)=>x4(T))}async delete($){if(this.sessions.has($))await this.stop($);let Y=await this.invoke("deleteSession",$);if(Y.deleted)this.usageBySession.delete($);return Y.deleted}async readTranscript($,Y){let T=await this.getRow($);if(!T?.transcript_path||!_4(T.transcript_path))return"";let q=g4(T.transcript_path,"utf8");if(typeof Y==="number"&&Number.isFinite(Y))return q.slice(-Math.max(0,Math.floor(Y)));return q}async readMessages($){let T=(await this.getRow($))?.messages_path?.trim();if(!T||!_4(T))return[];try{let q=g4(T,"utf8");if(!q.trim())return[];let X=JSON.parse(q);return Array.isArray(X)?X:Array.isArray(X.messages)?X.messages??[]:[]}catch{return[]}}async readHooks($,Y=200){let T=await this.getRow($);if(!T?.hook_path||!_4(T.hook_path))return[];return g4(T.hook_path,"utf8").split(`
|
|
575
|
-
`).map((J)=>J.trim()).filter((J)=>J.length>0).slice(-Math.max(1,Math.floor(Y))).map((J)=>{try{return JSON.parse(J)}catch{return{raw:J}}})}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async runTurn($,Y){let T=await this.prepareTurnInput($,Y),q=T.prompt.trim();if(!q)throw Error("prompt cannot be empty");await this.ensureSessionPersisted($),await this.syncOAuthCredentials($);let X=await this.executeAgentTurn($,q,T.userImages,T.userFiles);while(this.shouldAutoContinueTeamRuns($,X.finishReason)){let J=await this.waitForTeamRunUpdates($);if(J.length===0)break;let Q=this.buildTeamRunContinuationPrompt($,J);X=await this.executeAgentTurn($,Q)}return X}async executeAgentTurn($,Y,T,q){let X=$.started||$.agent.getMessages().length>0,J=$.agent.getMessages(),Q=this.usageBySession.get($.sessionId)??
|
|
570
|
+
</command-instructions>`}finally{T.delete(U)}};return Object.defineProperty(q,"configuredSkills",{get:()=>S4($),enumerable:!0,configurable:!1}),q}function mH($,Y){if(!$)return;for(let T of $.getTeammateIds())try{$.shutdownTeammate(T,Y)}catch{}}function fH($){let Y=$.lastIndexOf(kH);if(Y<0)return;let T=$.slice(Y).trim();return T.length>0?T:void 0}function bH($){return{mode:$.mode==="plan"?"plan":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent!==!1,enableAgentTeams:$.enableAgentTeams!==!1,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class C8{build($){let{config:Y,hooks:T,extensions:q,logger:X,createSpawnTool:J,onTeamRestored:Q,userInstructionWatcher:U,defaultToolExecutors:Z}=$,K=$.onTeamEvent??(()=>{}),A=bH(Y),W=[],E=Y.teamName?.trim()||dU(),V=!1,F=Boolean(U),H=U,D=Promise.resolve(),I;if(!H&&A.enableTools&&uU(Y.cwd))H=V8({skills:{workspacePath:Y.cwd},rules:{workspacePath:Y.cwd},workflows:{workspacePath:Y.cwd}}),D=H.start().catch(()=>{});if(A.enableTools&&H&&(F||uU(Y.cwd)||S4(H).length>0))I=gH(H,D);if(A.enableTools)W.push(...fU(Y.cwd,Y.providerId,A.mode,Y.modelId,Y.toolRoutingRules,I,Z));let S,v=A.enableAgentTeams?new B6:void 0;v?.init();let z=v?.loadRuntime(E),_=z?.state,y=z?.teammates??[],k=new Map(y.map((j)=>[j.agentId,j])),m=()=>{if(!A.enableAgentTeams)return;if(!S){if(S=new jH({teamName:E,leadAgentId:"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(j)=>{if(K(j),S&&v){if(j.type==="teammate_spawned"&&j.teammate?.rolePrompt){let M={agentId:j.agentId,rolePrompt:j.teammate.rolePrompt,modelId:j.teammate.modelId,maxIterations:j.teammate.maxIterations};k.set(M.agentId,M)}if(j.type==="teammate_shutdown")k.delete(j.agentId);v.handleTeamEvent(E,j),v.persistRuntime(E,S.exportState(),Array.from(k.values()))}}}),_)S.hydrateState(_),S.markStaleRunsInterrupted("runtime_recovered")}if(!V){if(!S)return;V=!0;let j=vH({runtime:S,leadAgentId:"lead",restoredFromPersistence:Boolean(_),restoredTeammates:y,createBaseTools:A.enableTools?()=>fU(Y.cwd,Y.providerId,A.mode,Y.modelId,Y.toolRoutingRules,I,Z):void 0,teammateRuntime:{providerId:Y.providerId,modelId:Y.modelId,cwd:Y.cwd,apiKey:Y.apiKey??"",baseUrl:Y.baseUrl,headers:Y.headers,providerConfig:Y.providerConfig,knownModels:Y.knownModels,thinking:Y.thinking,clineWorkspaceMetadata:Y.providerId==="cline"?fH(Y.systemPrompt):void 0,maxIterations:Y.maxIterations,hooks:T,extensions:q??Y.extensions,logger:X??Y.logger}});if(j.restoredFromPersistence)Q?.();W.push(...j.tools)}return S};if(A.enableSpawnAgent&&J){let j=J();W.push({...j,execute:async(M,h0)=>{return m(),j.execute(M,h0)}})}if(A.enableAgentTeams)m();let C=S?()=>{let j=S;if(!j)return;let M=j.listTasks(),h0=M.some((L)=>L.status==="in_progress"||L.status==="pending"),P=j.listRuns({}),G=P.some((L)=>L.status==="running"||L.status==="queued");if(h0||G){let L=M.filter((d)=>d.status==="in_progress"||d.status==="pending").map((d)=>`${d.id} (${d.status}): ${d.title}`).join(", "),l=P.filter((d)=>d.status==="running"||d.status==="queued").map((d)=>`${d.id} (${d.status})`).join(", "),u=[];if(L)u.push(`Unfinished tasks: ${L}`);if(l)u.push(`Active runs: ${l}`);return`[SYSTEM] You still have team obligations. ${u.join(". ")}. Use team_run_task to delegate work, or team_complete_task to mark tasks done, or team_await_run / team_await_all_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0;return{tools:W,logger:X??Y.logger,teamRuntime:S,completionGuard:C,shutdown:(j)=>{if(mH(S,j),!F)H?.stop()}}}}import{mkdir as uH,readFile as dH,unlink as C4,writeFile as cH}from"node:fs/promises";import{join as cU}from"node:path";function pH($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function lH($){return new Promise((Y)=>setTimeout(Y,$))}async function nH($,Y={}){let T=Y.approvalDir?.trim(),q=Y.sessionId?.trim();if(!T||!q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await uH(T,{recursive:!0});let X=pH(`${$.toolCallId}`),J=cU(T,`${q}.request.${X}.json`),Q=cU(T,`${q}.decision.${X}.json`),U=Y.nowIso??(()=>new Date().toISOString());await cH(J,`${JSON.stringify({requestId:X,sessionId:q,createdAt:U(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
|
|
571
|
+
`,"utf8");let Z=Y.timeoutMs??300000,K=Y.pollIntervalMs??200,A=Date.now();while(Date.now()-A<Z){try{let W=await dH(Q,"utf8"),E=JSON.parse(W),V={approved:E.approved===!0,reason:typeof E.reason==="string"?E.reason:void 0};try{await C4(Q)}catch{}try{await C4(J)}catch{}return V}catch{}await lH(K)}try{await C4(J)}catch{}return{approved:!1,reason:"Tool approval request timed out"}}function iH($){return $.disabled!==!0}function pU($){return[...$.getSnapshot("workflow").entries()].map(([T,q])=>({id:T,workflow:q.item})).filter(({workflow:T})=>iH(T)).map(({id:T,workflow:q})=>({id:T,name:q.name,instructions:q.instructions})).sort((T,q)=>T.name.localeCompare(q.name))}function rH($,Y){if(!$.startsWith("/")||$.length<2)return $;let T=$.match(/^\/(\S+)/);if(!T)return $;let q=T[1];if(!q)return $;let X=q.length+1,J=$.slice(X),Q=pU(Y).find((U)=>U.name===q);return Q?`${Q.instructions}${J}`:$}import{existsSync as g4,readFileSync as m4}from"node:fs";import{readFile as Iz,stat as Mz}from"node:fs/promises";import{homedir as Bz}from"node:os";import{isAbsolute as Rz,join as P6,resolve as Oz}from"node:path";import{Agent as Pz,createSpawnAgentTool as Lz}from"@clinebot/agents";import{nanoid as wz}from"nanoid";import{spawn as aH}from"node:child_process";import{appendFileSync as oH,readFileSync as sH}from"node:fs";function j8($){if(!$||typeof $!=="object")return{};let Y={};for(let[T,q]of Object.entries($))Y[T]=typeof q==="string"?q:JSON.stringify(q);return Y}function y8($,Y,T){let q=T instanceof Error?`: ${T.message}`:"",X=`${Y}${q}`;if($?.warn){$.warn(X);return}console.warn(X)}function lU($,Y){if(!Y)return $;if(!$)return{...Y};let T=[$.context,Y.context].filter((X)=>typeof X==="string"&&X.length>0).join(`
|
|
572
|
+
`),q=[...$.appendMessages??[],...Y.appendMessages??[]];return{cancel:$.cancel===!0||Y.cancel===!0?!0:void 0,review:$.review===!0||Y.review===!0?!0:void 0,context:T||void 0,overrideInput:Y.overrideInput!==void 0?Y.overrideInput:$.overrideInput,systemPrompt:Y.systemPrompt!==void 0?Y.systemPrompt:$.systemPrompt,appendMessages:q.length>0?q:void 0}}function tH($){if(!$||typeof $!=="object")return;let Y=$,T=typeof Y.context==="string"?Y.context:typeof Y.contextModification==="string"?Y.contextModification:typeof Y.errorMessage==="string"?Y.errorMessage:void 0;return{cancel:typeof Y.cancel==="boolean"?Y.cancel:void 0,review:typeof Y.review==="boolean"?Y.review:void 0,context:T,overrideInput:Object.hasOwn(Y,"overrideInput")?Y.overrideInput:void 0}}function nU($){let Y=String($??"").toLowerCase();return Y.includes("cancel")||Y.includes("abort")||Y.includes("interrupt")}function eH($){F6($)}function n0($,Y){let T=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",q={rootSessionId:Y.rootSessionId||$.conversationId,hookLogPath:Y.hookLogPath};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:q,workspaceRoots:Y.workspacePath?[Y.workspacePath]:[],userId:T,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function $z($){let Y=$.trim();if(!Y)return{};let q=Y.split(`
|
|
573
|
+
`).map((J)=>J.trim()).filter(Boolean).filter((J)=>J.startsWith("HOOK_CONTROL\t")).map((J)=>J.slice(13)),X=q.length>0?q[q.length-1]:Y;try{return{parsedJson:JSON.parse(X)}}catch(J){return{parseError:J instanceof Error?J.message:"Failed to parse hook stdout JSON"}}}async function iU($,Y){if(Y.command.length===0)throw Error("runHookCommand requires non-empty command");let T=aH(Y.command[0],Y.command.slice(1),{cwd:Y.cwd,env:Y.env,stdio:Y.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Y.detached}),q=JSON.stringify($);if(!T.stdin)throw Error("hook command failed to create stdin");if(T.stdin.write(q),T.stdin.end(),Y.detached){await new Promise((Z,K)=>{T.once("error",K),T.once("spawn",()=>Z())}),T.unref();return}if(!T.stdout||!T.stderr)throw Error("hook command failed to create stdout/stderr");let X="",J="",Q=!1,U;return T.stdout.on("data",(Z)=>{X+=Z.toString()}),T.stderr.on("data",(Z)=>{J+=Z.toString()}),await new Promise((Z,K)=>{if(T.once("error",K),(Y.timeoutMs??0)>0)U=setTimeout(()=>{Q=!0,T.kill("SIGKILL")},Y.timeoutMs);T.once("close",(A)=>{if(U)clearTimeout(U);let{parsedJson:W,parseError:E}=$z(X);Z({exitCode:A,stdout:X,stderr:J,parsedJson:W,parseError:E,timedOut:Q})})})}function Yz($){try{let T=sH($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!T?.startsWith("#!"))return;let q=T.slice(2).trim();if(!q)return;let X=q.split(/\s+/).filter(Boolean);return X.length>0?X:void 0}catch{return}}function Tz($){let Y=Yz($);if(Y&&Y.length>0)return[...Y,$];let T=$.toLowerCase();if(T.endsWith(".sh")||T.endsWith(".bash")||T.endsWith(".zsh"))return["/bin/bash",$];if(T.endsWith(".js")||T.endsWith(".mjs")||T.endsWith(".cjs"))return["node",$];if(T.endsWith(".ts")||T.endsWith(".mts")||T.endsWith(".cts"))return["bun","run",$];return["/bin/bash",$]}function qz($){let Y={};for(let T of X8($)){if(!T.hookEventName)continue;let q=Y[T.hookEventName]??[];q.push(Tz(T.path)),Y[T.hookEventName]=q}return Y}async function Xz($){let Y;for(let T of $.commands){let q=T.join(" ");try{let X=await iU($.payload,{command:T,cwd:$.cwd,env:process.env,detached:!1,timeoutMs:$.timeoutMs});if(X?.timedOut){y8($.logger,`hook command timed out: ${q}`);continue}if(X?.parseError){y8($.logger,`hook command returned invalid JSON control output: ${q} (${X.parseError})`);continue}Y=lU(Y,tH(X?.parsedJson))}catch(X){y8($.logger,`hook command failed: ${q}`,X)}}return Y}function zY($){for(let Y of $.commands){let T=Y.join(" ");iU($.payload,{command:Y,cwd:$.cwd,env:process.env,detached:!0}).catch((q)=>{y8($.logger,`hook command failed: ${T}`,q)})}}function rU($){let Y={cwd:$.workspacePath,workspacePath:$.workspacePath,hookLogPath:$.hookLogPath,rootSessionId:$.rootSessionId},T=(q)=>{let X=`${JSON.stringify({ts:new Date().toISOString(),...q})}
|
|
574
|
+
`;eH($.hookLogPath),oH($.hookLogPath,X,"utf8")};return{onRunStart:async(q)=>{T({...n0(q,Y),hookName:"agent_start",taskStart:{taskMetadata:{}}}),T({...n0(q,Y),hookName:"prompt_submit",userPromptSubmit:{prompt:q.userMessage,attachments:[]}});return},onToolCallStart:async(q)=>{T({...n0(q,Y),hookName:"tool_call",iteration:q.iteration,tool_call:{id:q.call.id,name:q.call.name,input:q.call.input},preToolUse:{toolName:q.call.name,parameters:j8(q.call.input)}});return},onToolCallEnd:async(q)=>{T({...n0(q,Y),hookName:"tool_result",iteration:q.iteration,tool_result:q.record,postToolUse:{toolName:q.record.name,parameters:j8(q.record.input),result:typeof q.record.output==="string"?q.record.output:JSON.stringify(q.record.output),success:!q.record.error,executionTimeMs:q.record.durationMs}});return},onTurnEnd:async(q)=>{T({...n0(q,Y),hookName:"agent_end",iteration:q.iteration,turn:q.turn,taskComplete:{taskMetadata:{}}});return},onSessionShutdown:async(q)=>{if(nU(q.reason))T({...n0(q,Y),hookName:"agent_abort",reason:q.reason,taskCancel:{taskMetadata:{}}});T({...n0(q,Y),hookName:"session_shutdown",reason:q.reason});return}}}function aU($){let Y=qz($.workspacePath);if(!Object.values(Y).some((Z)=>(Z?.length??0)>0))return;let q=async(Z)=>{let K=Y.agent_start??[];if(K.length>0)zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}}});let A=Y.prompt_submit??[];if(A.length>0)zY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}}})},X=async(Z)=>{let K=Y.tool_call??[];if(K.length===0)return;return Xz({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...n0(Z,$),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:j8(Z.call.input)}}})},J=async(Z)=>{let K=Y.tool_result??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:j8(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}}})},Q=async(Z)=>{let K=Y.agent_end??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_end",iteration:Z.iteration,turn:Z.turn,taskComplete:{taskMetadata:{}}}})},U=async(Z)=>{if(nU(Z.reason)){let A=Y.agent_abort??[];if(A.length>0)zY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_abort",reason:Z.reason,taskCancel:{taskMetadata:{}}}})}let K=Y.session_shutdown??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"session_shutdown",reason:Z.reason}})};return{onRunStart:async(Z)=>{await q(Z);return},onToolCallStart:async(Z)=>X(Z),onToolCallEnd:async(Z)=>{await J(Z);return},onTurnEnd:async(Z)=>{await Q(Z);return},onSessionShutdown:async(Z)=>{await U(Z);return}}}function k1($,Y){let T=$.map((q)=>q[Y]).filter((q)=>typeof q==="function");if(T.length===0)return;return async(q)=>{let X;for(let J of T){let Q=await J(q);X=lU(X,Q)}return X}}function oU($){let Y=$.filter((T)=>T!==void 0);if(Y.length===0)return;return{onRunStart:k1(Y,"onRunStart"),onRunEnd:k1(Y,"onRunEnd"),onIterationStart:k1(Y,"onIterationStart"),onIterationEnd:k1(Y,"onIterationEnd"),onTurnStart:k1(Y,"onTurnStart"),onTurnEnd:k1(Y,"onTurnEnd"),onToolCallStart:k1(Y,"onToolCallStart"),onToolCallEnd:k1(Y,"onToolCallEnd"),onSessionShutdown:k1(Y,"onSessionShutdown"),onError:k1(Y,"onError")}}var Jz="https://api.cline.bot",y4="workos:",Qz=["cline","oca","openai-codex"];function Uz($){return Qz.includes($)}function Zz($,Y){if($==="cline")return`${y4}${Y}`;return Y}function Kz($,Y){if($==="cline"&&Y.toLowerCase().startsWith(y4))return Y.slice(y4.length);return Y}function Az($){let T=W1($)?.exp;if(typeof T==="number"&&T>0)return T*1000;return null}function Wz($,Y){let T=$.auth?.expiresAt;if(typeof T==="number"&&Number.isFinite(T)&&T>0)return T;let q=Az(Y);if(q)return q;return Date.now()-1}function Gz($,Y){let T=Y.auth?.accessToken?.trim(),q=Y.auth?.refreshToken?.trim();if(!T||!q)return null;let X=Kz($,T);if(!X)return null;return{access:X,refresh:q,expires:Wz(Y,X),accountId:Y.auth?.accountId}}function Ez($,Y){let T=$?.expiresAt,q=Y?.expiresAt;return $?.accessToken===Y?.accessToken&&$?.refreshToken===Y?.refreshToken&&$?.accountId===Y?.accountId&&T===q}class v8 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class j4{providerSettingsManager;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new d$}async resolveProviderApiKey($){if(!Uz($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,Y=!1){let T=this.refreshInFlight.get($);if(T)return T;let q=this.resolveProviderApiKeyInternal($,Y).catch((X)=>{throw X}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,q),q}async resolveProviderApiKeyInternal($,Y){let T=this.providerSettingsManager.getProviderSettings($);if(!T)return null;let q=Gz($,T);if(!q)return null;let X=await this.resolveCredentials($,T,q,Y);if(!X)throw new v8($);let J=Zz($,X.access),Q={...T.auth??{},accessToken:J,refreshToken:X.refresh,accountId:X.accountId};Q.expiresAt=X.expires;let U={...T,auth:Q},Z=!Ez(T.auth,U.auth);if(Z)this.providerSettingsManager.saveProviderSettings(U,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:J,accountId:X.accountId,refreshed:Z}}async resolveCredentials($,Y,T,q){if($==="cline")return A4(T,{apiBaseUrl:Y.baseUrl?.trim()||Jz},{forceRefresh:q});if($==="oca")return D4(T,{forceRefresh:q},{mode:Y.oca?.mode});return G4(T,{forceRefresh:q})}}import{existsSync as v4,mkdirSync as Vz,readdirSync as Dz,rmdirSync as Fz,unlinkSync as Nz}from"node:fs";import{dirname as sU,join as H$}from"node:path";function W0(){return new Date().toISOString()}function $$($){if(!$||!v4($))return;try{Nz($)}catch{}}class x4{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return H$(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let Y=this.sessionArtifactsDir($);if(!v4(Y))Vz(Y,{recursive:!0});return Y}sessionTranscriptPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.log`)}sessionHookPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.hooks.jsonl`)}sessionMessagesPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,Y=!0){let T=Y?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return H$(T,`${$}.json`)}removeSessionDirIfEmpty($){let Y=this.sessionArtifactsDir($),T=this.ensureSessionsDir();while(Y.startsWith(T)&&Y!==T){if(!v4(Y)){Y=sU(Y);continue}try{if(Dz(Y).length>0)break;Fz(Y)}catch{break}Y=sU(Y)}}subagentArtifactPaths($,Y,T){let q=this.ensureSessionArtifactsDir($);return{transcriptPath:H$(q,`${$}.log`),hookPath:H$(q,`${$}.hooks.jsonl`),messagesPath:H$(q,`${$}.messages.json`)}}}import{z as G0}from"zod";var Hz=G0.enum(P4),IY=G0.object({version:G0.literal(1),session_id:G0.string().min(1),source:G0.enum(R6),pid:G0.number().int(),started_at:G0.string().min(1),ended_at:G0.string().min(1).optional(),exit_code:G0.number().int().nullable().optional(),status:Hz,interactive:G0.boolean(),provider:G0.string().min(1),model:G0.string().min(1),cwd:G0.string().min(1),workspace_root:G0.string().min(1),team_name:G0.string().min(1).optional(),enable_tools:G0.boolean(),enable_spawn:G0.boolean(),enable_teams:G0.boolean(),prompt:G0.string().optional(),metadata:G0.record(G0.string(),G0.unknown()).optional(),messages_path:G0.string().min(1).optional()});var zz="# Workspace Configuration";function tU($){let Y=$.lastIndexOf(zz);if(Y<0)return;let T=$.slice(Y).trim();return T.length>0?T:void 0}function eU($){if(!$)return!1;return Object.values($).some((Y)=>typeof Y==="function")}function $7($,Y){let T=[...$??[],...Y??[]];if(T.length===0)return;let q=[],X=new Set;for(let J of T){if(X.has(J.name))continue;X.add(J.name),q.push(J)}return q}function Y7($){return JSON.stringify($,(Y,T)=>{if(T instanceof Error)return{name:T.name,message:T.message,stack:T.stack};return T})}function T7($,Y){let T=$.map((U)=>({...U})),q=[...T].reverse().findIndex((U)=>U.role==="assistant");if(q===-1)return T;let X=T.length-1-q,J=T[X],Q=Y.usage;return T[X]={...J,providerId:J.providerId??Y.model.provider,modelId:J.modelId??Y.model.id,modelInfo:J.modelInfo??{id:Y.model.id,provider:Y.model.provider},metrics:{...J.metrics??{},inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens,cacheWriteTokens:Q.cacheWriteTokens,cost:Q.totalCost},ts:J.ts??Y.endedAt.getTime()},T}function k4($){let Y=typeof $.metadata_json==="string"&&$.metadata_json.trim().length>0?(()=>{try{let T=JSON.parse($.metadata_json);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return})():void 0;return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive===1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name??void 0,enableTools:$.enable_tools===1,enableSpawn:$.enable_spawn===1,enableTeams:$.enable_teams===1,parentSessionId:$.parent_session_id??void 0,parentAgentId:$.parent_agent_id??void 0,agentId:$.agent_id??void 0,conversationId:$.conversation_id??void 0,isSubagent:$.is_subagent===1,prompt:$.prompt??void 0,metadata:Y,transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??W0()}}function h4(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function _4($,Y){return{inputTokens:$.inputTokens+Math.max(0,Y.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,Y.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,Y.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,Y.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,Y.totalCost??0)}}var q7=5000,Sz=20480000;async function Cz($){let Y=await Mz($);if(!Y.isFile())throw Error("Path is not a file");if(Y.size>Sz)throw Error("File is too large to read into context.");let T=await Iz($,"utf8");if(T.includes("\x00"))throw Error("Cannot read binary file into context.");return T}class x8{sessionService;runtimeBuilder;createAgentInstance;defaultToolExecutors;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultRequestToolApproval;listeners=new Set;sessions=new Map;usageBySession=new Map;constructor($){let Y=Bz();if(Y)CT(Y);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new C8,this.createAgentInstance=$.createAgent??((T)=>new Pz(T)),this.defaultToolExecutors=$.defaultToolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new d$,this.oauthTokenManager=$.oauthTokenManager??new j4({providerSettingsManager:this.providerSettingsManager}),this.defaultRequestToolApproval=$.requestToolApproval}resolveStoredProviderSettings($){let Y=this.providerSettingsManager.getProviderSettings($);if(Y)return Y;return{provider:$}}buildResolvedProviderConfig($){let Y=this.resolveStoredProviderSettings($.providerId),T={...Y,provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Y.apiKey,baseUrl:$.baseUrl??Y.baseUrl,headers:$.headers??Y.headers,reasoning:typeof $.thinking==="boolean"||typeof $.reasoningEffort==="string"?{...Y.reasoning??{},...typeof $.thinking==="boolean"?{enabled:$.thinking}:{},...typeof $.reasoningEffort==="string"?{effort:$.reasoningEffort}:{}}:Y.reasoning},q=M6(T);if($.knownModels)q.knownModels=$.knownModels;return q}async start($){let Y=$.source??"cli",T=W0(),q=$.config.sessionId?.trim()??"",X=q.length>0?q:`${Date.now()}_${wz(5)}`;this.usageBySession.set(X,h4());let J=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!J)throw Error("session service method not available: ensureSessionsDir");let Q=P6(J,X),U=P6(Q,`${X}.log`),Z=P6(Q,`${X}.hooks.jsonl`),K=P6(Q,`${X}.messages.json`),A=P6(Q,`${X}.json`),W=IY.parse({version:1,session_id:X,source:Y,pid:process.pid,started_at:T,status:"running",interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspace_root:$.config.workspaceRoot??$.config.cwd,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,messages_path:K}),E=aU({cwd:$.config.cwd,workspacePath:$.config.workspaceRoot??$.config.cwd,rootSessionId:X,hookLogPath:Z,logger:$.config.logger}),V=eU($.config.hooks)?void 0:rU({hookLogPath:Z,rootSessionId:X,workspacePath:$.config.workspaceRoot??$.config.cwd}),F=oU([$.config.hooks,E,V]),H=await Z8({pluginPaths:$.config.pluginPaths,workspacePath:$.config.workspaceRoot??$.config.cwd,cwd:$.config.cwd}),D=$7($.config.extensions,H.extensions),I={...$.config,hooks:F,extensions:D},S=this.buildResolvedProviderConfig(I),v={...I,providerConfig:S},z=this.runtimeBuilder.build({config:v,hooks:F,extensions:D,logger:v.logger,onTeamEvent:(C)=>{this.handleTeamEvent(X,C),v.onTeamEvent?.(C)},createSpawnTool:()=>this.createSpawnTool(v,X),onTeamRestored:$.onTeamRestored,userInstructionWatcher:$.userInstructionWatcher,defaultToolExecutors:$.defaultToolExecutors??this.defaultToolExecutors}),_=[...z.tools,...v.extraTools??[]],y=this.createAgentInstance({providerId:S.providerId,modelId:S.modelId,apiKey:S.apiKey,baseUrl:S.baseUrl,headers:S.headers,knownModels:S.knownModels,providerConfig:S,thinking:v.thinking,reasoningEffort:v.reasoningEffort??S.reasoningEffort,systemPrompt:v.systemPrompt,maxIterations:v.maxIterations,maxConsecutiveMistakes:v.maxConsecutiveMistakes,tools:_,hooks:F,extensions:D,hookErrorMode:v.hookErrorMode,initialMessages:$.initialMessages,userFileContentLoader:Cz,toolPolicies:$.toolPolicies??this.defaultToolPolicies,requestToolApproval:$.requestToolApproval??this.defaultRequestToolApproval,onConsecutiveMistakeLimitReached:v.onConsecutiveMistakeLimitReached,completionGuard:z.completionGuard,logger:z.logger??v.logger,onEvent:(C)=>{let j=this.sessions.get(X);if(C.type==="usage"&&j?.turnUsageBaseline)this.usageBySession.set(X,_4(j.turnUsageBaseline,{inputTokens:C.totalInputTokens,outputTokens:C.totalOutputTokens,totalCost:C.totalCost}));this.emit({type:"agent_event",payload:{sessionId:X,event:C}}),this.emit({type:"chunk",payload:{sessionId:X,stream:"agent",chunk:Y7(C),ts:Date.now()}})}}),k={sessionId:X,config:v,source:Y,startedAt:T,pendingPrompt:W.prompt,runtime:z,agent:y,started:!1,aborting:!1,interactive:$.interactive===!0,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pluginSandboxShutdown:H.shutdown};this.sessions.set(k.sessionId,k),this.emitStatus(k.sessionId,"running");let m;try{if($.prompt?.trim()){if(m=await this.runTurn(k,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles}),!k.interactive)await this.finalizeSingleRun(k,m.finishReason)}}catch(C){throw await this.failSession(k),C}return{sessionId:X,manifest:W,manifestPath:A,transcriptPath:U,hookPath:Z,messagesPath:K,result:m}}async send($){let Y=this.sessions.get($.sessionId);if(!Y)throw Error(`session not found: ${$.sessionId}`);try{let T=await this.runTurn(Y,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles});if(!Y.interactive)await this.finalizeSingleRun(Y,T.finishReason);return T}catch(T){throw await this.failSession(Y),T}}async getAccumulatedUsage($){let Y=this.usageBySession.get($);if(!Y)return;return{...Y}}async abort($){let Y=this.sessions.get($);if(!Y)return;Y.aborting=!0,Y.agent.abort()}async stop($){let Y=this.sessions.get($);if(!Y)return;await this.shutdownSession(Y,{status:"cancelled",exitCode:null,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let Y=[...this.sessions.values()];if(Y.length===0)return;await Promise.allSettled(Y.map(async(T)=>{await this.shutdownSession(T,{status:"cancelled",exitCode:null,shutdownReason:$,endReason:"disposed"})})),this.usageBySession.clear()}async get($){let Y=await this.getRow($);return Y?k4(Y):void 0}async list($=200){return(await this.listRows($)).map((T)=>k4(T))}async delete($){if(this.sessions.has($))await this.stop($);let Y=await this.invoke("deleteSession",$);if(Y.deleted)this.usageBySession.delete($);return Y.deleted}async readTranscript($,Y){let T=await this.getRow($);if(!T?.transcript_path||!g4(T.transcript_path))return"";let q=m4(T.transcript_path,"utf8");if(typeof Y==="number"&&Number.isFinite(Y))return q.slice(-Math.max(0,Math.floor(Y)));return q}async readMessages($){let T=(await this.getRow($))?.messages_path?.trim();if(!T||!g4(T))return[];try{let q=m4(T,"utf8");if(!q.trim())return[];let X=JSON.parse(q);return Array.isArray(X)?X:Array.isArray(X.messages)?X.messages??[]:[]}catch{return[]}}async readHooks($,Y=200){let T=await this.getRow($);if(!T?.hook_path||!g4(T.hook_path))return[];return m4(T.hook_path,"utf8").split(`
|
|
575
|
+
`).map((J)=>J.trim()).filter((J)=>J.length>0).slice(-Math.max(1,Math.floor(Y))).map((J)=>{try{return JSON.parse(J)}catch{return{raw:J}}})}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async runTurn($,Y){let T=await this.prepareTurnInput($,Y),q=T.prompt.trim();if(!q)throw Error("prompt cannot be empty");await this.ensureSessionPersisted($),await this.syncOAuthCredentials($);let X=await this.executeAgentTurn($,q,T.userImages,T.userFiles);while(this.shouldAutoContinueTeamRuns($,X.finishReason)){let J=await this.waitForTeamRunUpdates($);if(J.length===0)break;let Q=this.buildTeamRunContinuationPrompt($,J);X=await this.executeAgentTurn($,Q)}return X}async executeAgentTurn($,Y,T,q){let X=$.started||$.agent.getMessages().length>0,J=$.agent.getMessages(),Q=this.usageBySession.get($.sessionId)??h4();$.turnUsageBaseline=Q;try{let U=X?await this.runWithAuthRetry($,()=>$.agent.continue(Y,T,q),J):await this.runWithAuthRetry($,()=>$.agent.run(Y,T,q),J);$.started=!0;let Z=T7(U.messages,U);return this.usageBySession.set($.sessionId,_4(Q,U.usage)),await this.invoke("persistSessionMessages",$.sessionId,Z,$.config.systemPrompt),U}catch(U){throw await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),U}finally{$.turnUsageBaseline=void 0}}async prepareTurnInput($,Y){let T=$.config.workspaceRoot??$.config.cwd,q=xT(Y.prompt).trim();if(!q)return{prompt:"",userImages:Y.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,Y.userFiles)};let X=await oT(q,T),J=vT(X.prompt,$.config.mode==="plan"?"plan":"act"),Q=this.resolveAbsoluteFilePaths($.config.cwd,Y.userFiles),U=this.resolveAbsoluteFilePaths(T,X.matchedFiles),Z=Array.from(new Set([...Q,...U]));return{prompt:J,userImages:Y.userImages,userFiles:Z.length>0?Z:void 0}}resolveAbsoluteFilePaths($,Y){if(!Y||Y.length===0)return[];let T=Y.map((q)=>q.trim()).filter((q)=>q.length>0).map((q)=>Rz(q)?q:Oz($,q));return Array.from(new Set(T))}async ensureSessionPersisted($){if($.artifacts)return;$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:$.config.workspaceRoot??$.config.cwd,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,startedAt:$.startedAt})}async finalizeSingleRun($,Y){if(this.hasPendingTeamRunWork($))return;if(Y==="aborted"||$.aborting)await this.shutdownSession($,{status:"cancelled",exitCode:null,shutdownReason:"session_complete",endReason:Y});else await this.shutdownSession($,{status:"completed",exitCode:0,shutdownReason:"session_complete",endReason:Y})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,Y){if(this.notifyTeamRunWaiters($),$.artifacts)await this.updateStatus($,Y.status,Y.exitCode);if($.artifacts)await $.agent.shutdown(Y.shutdownReason);if(await Promise.resolve($.runtime.shutdown(Y.shutdownReason)),$.pluginSandboxShutdown)await $.pluginSandboxShutdown();this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:Y.endReason,ts:Date.now()}})}async updateStatus($,Y,T){if(!$.artifacts)return;let q=await this.invoke("updateSessionStatus",$.sessionId,Y,T);if(!q.updated)return;$.artifacts.manifest.status=Y,$.artifacts.manifest.ended_at=q.endedAt??W0(),$.artifacts.manifest.exit_code=typeof T==="number"?T:null,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,$.artifacts.manifest),this.emitStatus($.sessionId,Y)}emitStatus($,Y){this.emit({type:"status",payload:{sessionId:$,status:Y}})}async listRows($){let Y=Math.max(1,Math.floor($));return this.invoke("listSessions",Math.min(Y,q7))}async getRow($){let Y=$.trim();if(!Y)return;return(await this.listRows(q7)).find((q)=>q.session_id===Y)}createSpawnTool($,Y){let T=()=>{if(!$.enableTools)return[];let X=$.mode==="plan"?t1.readonly:t1.development;return N6({cwd:$.cwd,...X,executors:this.defaultToolExecutors})},q=()=>{let X=T();if($.enableSpawnAgent)X.push(this.createSpawnTool($,Y));return X};return Lz({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,providerConfig:$.providerConfig,knownModels:$.knownModels,clineWorkspaceMetadata:$.providerId==="cline"?tU($.systemPrompt):void 0,createSubAgentTools:q,hooks:$.hooks,extensions:$.extensions,toolPolicies:this.defaultToolPolicies,requestToolApproval:this.defaultRequestToolApproval,logger:$.logger,onSubAgentStart:(X)=>{this.invokeOptional("handleSubAgentStart",Y,X)},onSubAgentEnd:(X)=>{this.invokeOptional("handleSubAgentEnd",Y,X)}})}async handleTeamEvent($,Y){let T=this.sessions.get($);if(T)switch(Y.type){case"run_queued":case"run_started":T.activeTeamRunIds.add(Y.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let X;if(Y.type==="run_failed")X=Y.run.error;else if(Y.type==="run_cancelled")X=Y.run.error??Y.reason;else if(Y.type==="run_interrupted")X=Y.run.error??Y.reason;T.activeTeamRunIds.delete(Y.run.id),T.pendingTeamRunUpdates.push({runId:Y.run.id,agentId:Y.run.agentId,taskId:Y.run.taskId,status:Y.type.replace("run_",""),error:X,iterations:Y.run.result?.iterations}),this.notifyTeamRunWaiters(T);break}default:break}switch(Y.type){case"task_start":await this.invokeOptional("onTeamTaskStart",$,Y.agentId,Y.message);break;case"task_end":if(Y.error){await this.invokeOptional("onTeamTaskEnd",$,Y.agentId,"failed",`[error] ${Y.error.message}`,Y.messages);break}if(Y.result?.finishReason==="aborted"){await this.invokeOptional("onTeamTaskEnd",$,Y.agentId,"cancelled","[done] aborted",Y.result.messages);break}await this.invokeOptional("onTeamTaskEnd",$,Y.agentId,"completed",`[done] ${Y.result?.finishReason??"completed"}`,Y.result?.messages);break;default:break}if(!T?.runtime.teamRuntime)return;let q=T.config.teamName?.trim()||"team";this.emit({type:"team_progress",payload:{sessionId:$,teamName:q,lifecycle:S8({teamName:q,sessionId:$,event:Y}),summary:w8(q,T.runtime.teamRuntime.exportState())}})}hasPendingTeamRunWork($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}shouldAutoContinueTeamRuns($,Y){if($.aborting||Y==="aborted"||Y==="error")return!1;if(!$.config.enableAgentTeams)return!1;return this.hasPendingTeamRunWork($)}notifyTeamRunWaiters($){let Y=$.teamRunWaiters.splice(0);for(let T of Y)T()}async waitForTeamRunUpdates($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let Y=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,Y}if($.activeTeamRunIds.size===0)return[];await new Promise((Y)=>{$.teamRunWaiters.push(Y)})}}buildTeamRunContinuationPrompt($,Y){let T=Y.map((J)=>{let Q=`- ${J.runId} (${J.agentId}) -> ${J.status}`,U=J.taskId?` task=${J.taskId}`:"",Z=typeof J.iterations==="number"?` iterations=${J.iterations}`:"",K=J.error?` error=${J.error}`:"";return`${Q}${U}${Z}${K}`}),q=$.activeTeamRunIds.size,X=q>0?`There are still ${q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return vT(`System-delivered teammate async run updates:
|
|
576
576
|
${T.join(`
|
|
577
577
|
`)}
|
|
578
578
|
|
|
579
|
-
${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y($)}async invoke($,...Y){let T=this.sessionService[$];if(typeof T!=="function")throw Error(`session service method not available: ${$}`);return Promise.resolve(T.apply(this.sessionService,Y))}async invokeOptional($,...Y){let T=this.sessionService[$];if(typeof T!=="function")return;await Promise.resolve(T.apply(this.sessionService,Y))}async invokeOptionalValue($,...Y){let T=this.sessionService[$];if(typeof T!=="function")return;return await Promise.resolve(T.apply(this.sessionService,Y))}async runWithAuthRetry($,Y,T){try{return await Y()}catch(q){if(!this.isLikelyAuthError(q,$.config.providerId))throw q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(T),Y()}}isLikelyAuthError($,Y){if(Y!=="cline"&&Y!=="oca"&&Y!=="openai-codex")return!1;let T=$ instanceof Error?$.message.toLowerCase():String($);return T.includes("401")||T.includes("403")||T.includes("unauthorized")||T.includes("forbidden")||T.includes("invalid token")||T.includes("expired token")||T.includes("authentication")}async syncOAuthCredentials($,Y){let T=null;try{T=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:Y?.forceRefresh})}catch(X){if(X instanceof j8)throw Error(`OAuth session for "${X.providerId}" requires re-authentication. Run "clite auth ${X.providerId}" and retry.`);throw X}if(!T?.apiKey)return;if($.config.apiKey===T.apiKey)return;$.config.apiKey=T.apiKey,$.agent.updateConnection?.({apiKey:T.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:T.apiKey})}}import{existsSync as Yj,mkdirSync as Tj}from"node:fs";var XT=ZY(I6(),1),C3=ZY(tT(),1);import{existsSync as jy}from"node:fs";import{dirname as O3,join as JY}from"node:path";import{fileURLToPath as vy}from"node:url";var W9=ZY(I6(),1),v3=ZY(I6(),1),x3=ZY(tT(),1);var kJ=ZY(I6(),1);import{randomUUID as w3}from"node:crypto";import{randomUUID as iy}from"node:crypto";import{randomUUID as S3}from"node:crypto";function y3($){let Y=O3(vy($)),T=new Set([JY(Y,"proto","rpc.proto"),JY(Y,"..","proto","rpc.proto"),JY(Y,"..","src","proto","rpc.proto"),JY(Y,"..","..","src","proto","rpc.proto"),JY(process.cwd(),"src","proto","rpc.proto"),JY(process.cwd(),"packages","rpc","src","proto","rpc.proto")]),q=process.cwd();while(!0){T.add(JY(q,"packages","rpc","src","proto","rpc.proto"));let X=O3(q);if(X===q)break;q=X}for(let X of T)if(jy(X))return X;throw Error("Unable to resolve rpc.proto path")}var xy="cline.rpc.v1",j3="ClineGateway";function ky(){return y3(import.meta.url)}function hy(){let $=C3.loadSync(ky(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),Y=XT.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!Y)throw Error(`Unable to load ${xy}.${j3} from proto`);return Y}function _y($){return new(XT.makeGenericClientConstructor(hy(),j3))($,XT.credentials.createInsecure())}function K9($){if($===null||$===void 0)return{nullValue:"NULL_VALUE"};if(typeof $==="string")return{stringValue:$};if(typeof $==="number")return{numberValue:Number.isFinite($)?$:0};if(typeof $==="boolean")return{boolValue:$};if(Array.isArray($))return{listValue:{values:$.map((Y)=>K9(Y))}};if(typeof $==="object"){let Y={fields:{}};for(let[T,q]of Object.entries($))Y.fields??={},Y.fields[T]=K9(q);return{structValue:Y}}return{stringValue:String($)}}function A9($){if(!$)return;if($.nullValue!==void 0)return null;if($.stringValue!==void 0)return $.stringValue;if($.numberValue!==void 0)return $.numberValue;if($.boolValue!==void 0)return $.boolValue;if($.listValue)return($.listValue.values??[]).map((Y)=>A9(Y));if($.structValue){let Y={};for(let[T,q]of Object.entries($.structValue.fields??{}))Y[T]=A9(q);return Y}return}function Q1($){let Y={};for(let[T,q]of Object.entries($??{}))Y[T]=K9(q);return{fields:Y}}function f0($){if(!$?.fields)return;let Y={};for(let[T,q]of Object.entries($.fields))Y[T]=A9(q);return Y}function QY($){return K9($)}function UY($){return A9($??void 0)}function gy($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??"",exitCode:$.exitCode??0,status:$.status,statusLock:$.statusLock,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??"",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??"",parentAgentId:$.parentAgentId??"",agentId:$.agentId??"",conversationId:$.conversationId??"",isSubagent:$.isSubagent,prompt:$.prompt??"",transcriptPath:$.transcriptPath,hookPath:$.hookPath,messagesPath:$.messagesPath??"",updatedAt:$.updatedAt,metadata:Q1($.metadata)}}function P3($){return{sessionId:$.sessionId??"",source:$.source??"",pid:Number($.pid??0),startedAt:$.startedAt??"",endedAt:$.endedAt?$.endedAt:null,exitCode:typeof $.exitCode==="number"?$.exitCode:null,status:$.status??"running",statusLock:Number($.statusLock??0),interactive:$.interactive===!0,provider:$.provider??"",model:$.model??"",cwd:$.cwd??"",workspaceRoot:$.workspaceRoot??"",teamName:$.teamName||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:$.parentSessionId||void 0,parentAgentId:$.parentAgentId||void 0,agentId:$.agentId||void 0,conversationId:$.conversationId||void 0,isSubagent:$.isSubagent===!0,prompt:$.prompt||void 0,metadata:f0($.metadata),transcriptPath:$.transcriptPath??"",hookPath:$.hookPath??"",messagesPath:$.messagesPath||void 0,updatedAt:$.updatedAt??""}}function my($){let Y=$?.trim();if(!Y)return;try{let T=JSON.parse(Y);if(!Array.isArray(T))return;let q=T.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return q.length>0?q:void 0}catch{return}}function YT($){return{scheduleId:$.scheduleId??"",name:$.name??"",cronPattern:$.cronPattern??"",prompt:$.prompt??"",provider:$.provider??"",model:$.model??"",mode:$.mode==="plan"?"plan":"act",workspaceRoot:$.workspaceRoot?.trim()||void 0,cwd:$.cwd?.trim()||void 0,systemPrompt:$.systemPrompt?.trim()||void 0,maxIterations:$.hasMaxIterations?$.maxIterations:void 0,timeoutSeconds:$.hasTimeoutSeconds?$.timeoutSeconds:void 0,maxParallel:typeof $.maxParallel==="number"&&$.maxParallel>0?$.maxParallel:1,enabled:$.enabled===!0,createdAt:$.createdAt??"",updatedAt:$.updatedAt??"",lastRunAt:$.lastRunAt?.trim()||void 0,nextRunAt:$.nextRunAt?.trim()||void 0,createdBy:$.createdBy?.trim()||void 0,tags:my($.tagsJson??void 0),metadata:f0($.metadata)}}function yJ($){return{executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId?.trim()||void 0,triggeredAt:$.triggeredAt??"",startedAt:$.startedAt?.trim()||void 0,endedAt:$.endedAt?.trim()||void 0,status:$.status==="pending"||$.status==="running"||$.status==="success"||$.status==="failed"||$.status==="timeout"||$.status==="aborted"?$.status:"failed",exitCode:$.hasExitCode?$.exitCode:void 0,errorMessage:$.errorMessage?.trim()||void 0,iterations:$.hasIterations?$.iterations:void 0,tokensUsed:$.hasTokensUsed?$.tokensUsed:void 0,costUsd:$.hasCostUsd?$.costUsd:void 0}}class xJ{client;constructor($){this.client=_y($.address)}close(){this.client.close()}async upsertSession($){await this.unary((Y)=>{let T={session:gy($)};this.client.UpsertSession(T,Y)})}async getSession($){let Y=await this.unary((T)=>{this.client.GetSession({sessionId:$},T)});if(!Y.session)return;return P3(Y.session)}async listSessions($){return((await this.unary((Y)=>{this.client.ListSessions($,Y)})).sessions??[]).map((Y)=>P3(Y))}async updateSession($){let Y={sessionId:$.sessionId,status:$.status,endedAt:$.endedAt??void 0,setRunning:$.setRunning};if($.exitCode!==void 0)Y.hasExitCode=!0,Y.exitCode=$.exitCode??0;if($.prompt!==void 0)Y.hasPrompt=!0,Y.prompt=$.prompt??"";if($.metadata!==void 0)Y.hasMetadata=!0,Y.metadata=Q1($.metadata??void 0);if($.parentSessionId!==void 0)Y.hasParentSessionId=!0,Y.parentSessionId=$.parentSessionId??"";if($.parentAgentId!==void 0)Y.hasParentAgentId=!0,Y.parentAgentId=$.parentAgentId??"";if($.agentId!==void 0)Y.hasAgentId=!0,Y.agentId=$.agentId??"";if($.conversationId!==void 0)Y.hasConversationId=!0,Y.conversationId=$.conversationId??"";if($.expectedStatusLock!==void 0)Y.hasExpectedStatusLock=!0,Y.expectedStatusLock=$.expectedStatusLock;let T=await this.unary((q)=>{this.client.UpdateSession(Y,q)});return{updated:T.updated===!0,statusLock:Number(T.statusLock??0)}}async deleteSession($,Y=!1){return(await this.unary((T)=>{this.client.DeleteSession({sessionId:$,cascade:Y},T)})).deleted===!0}async enqueueSpawnRequest($){await this.unary((Y)=>{this.client.EnqueueSpawnRequest($,Y)})}async claimSpawnRequest($,Y){let T=(await this.unary((q)=>{let X={rootSessionId:$,parentAgentId:Y};this.client.ClaimSpawnRequest(X,q)})).item?.task?.trim();return T?T:void 0}async startRuntimeSession($){let Y={sessionId:$.sessionId??"",workspaceRoot:$.workspaceRoot,cwd:$.cwd??"",provider:$.provider,model:$.model,mode:$.mode,apiKey:$.apiKey,systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools??!1,hasAutoApproveTools:typeof $.autoApproveTools==="boolean",teamName:$.teamName,missionStepInterval:$.missionStepInterval,missionTimeIntervalMs:$.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries($.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:($.initialMessages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),logger:$.logger?{enabled:$.logger.enabled??!1,level:$.logger.level??"",destination:$.logger.destination??"",name:$.logger.name??"",bindings:Q1($.logger.bindings)}:void 0},T=await this.unary((X)=>{this.client.StartRuntimeSession({request:Y},X)}),q=T.startResult?{sessionId:T.startResult.sessionId??"",manifestPath:T.startResult.manifestPath??"",transcriptPath:T.startResult.transcriptPath??"",hookPath:T.startResult.hookPath??"",messagesPath:T.startResult.messagesPath??""}:void 0;return{sessionId:T.sessionId??"",startResult:q}}async sendRuntimeSession($,Y){let T={config:{workspaceRoot:Y.config.workspaceRoot,cwd:Y.config.cwd??"",provider:Y.config.provider,model:Y.config.model,mode:Y.config.mode,apiKey:Y.config.apiKey,systemPrompt:Y.config.systemPrompt??"",maxIterations:Y.config.maxIterations??0,hasMaxIterations:typeof Y.config.maxIterations==="number",enableTools:Y.config.enableTools,enableSpawn:Y.config.enableSpawn,enableTeams:Y.config.enableTeams,autoApproveTools:Y.config.autoApproveTools??!1,hasAutoApproveTools:typeof Y.config.autoApproveTools==="boolean",teamName:Y.config.teamName,missionStepInterval:Y.config.missionStepInterval,missionTimeIntervalMs:Y.config.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries(Y.config.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:(Y.config.initialMessages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),logger:Y.config.logger?{enabled:Y.config.logger.enabled??!1,level:Y.config.logger.level??"",destination:Y.config.logger.destination??"",name:Y.config.logger.name??"",bindings:Q1(Y.config.logger.bindings)}:void 0},messages:(Y.messages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),prompt:Y.prompt,attachments:Y.attachments?{userImages:Y.attachments.userImages??[],userFiles:(Y.attachments.userFiles??[]).map((X)=>({name:X.name,content:X.content}))}:void 0},q=await this.unary((X)=>{this.client.SendRuntimeSession({sessionId:$,request:T},X)});return{result:{text:q.result?.text??"",usage:{inputTokens:Number(q.result?.usage?.inputTokens??0),outputTokens:Number(q.result?.usage?.outputTokens??0),cacheReadTokens:q.result?.usage?.hasCacheReadTokens?Number(q.result?.usage?.cacheReadTokens??0):void 0,cacheWriteTokens:q.result?.usage?.hasCacheWriteTokens?Number(q.result?.usage?.cacheWriteTokens??0):void 0,totalCost:q.result?.usage?.hasTotalCost?Number(q.result?.usage?.totalCost??0):void 0},inputTokens:Number(q.result?.inputTokens??0),outputTokens:Number(q.result?.outputTokens??0),iterations:Number(q.result?.iterations??0),finishReason:q.result?.finishReason??"",messages:(q.result?.messages??[]).map((X)=>({role:X.role??"",content:UY(X.content)})),toolCalls:(q.result?.toolCalls??[]).map((X)=>({name:X.name??"",input:X.hasInput?UY(X.input):void 0,output:X.hasOutput?UY(X.output):void 0,error:X.error?.trim()||void 0,durationMs:X.hasDurationMs?Number(X.durationMs??0):void 0}))}}}async abortRuntimeSession($){return{applied:(await this.unary((Y)=>{this.client.AbortRuntimeSession({sessionId:$},Y)})).applied===!0}}async requestToolApproval($){let Y={approvalId:$.approvalId,sessionId:$.sessionId,taskId:$.taskId,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:$.inputJson,requesterClientId:$.requesterClientId,timeoutMs:$.timeoutMs},T=await this.unary((q)=>{this.client.RequestToolApproval(Y,q)});return{approvalId:T.approvalId??"",decided:T.decided===!0,approved:T.approved===!0,reason:T.reason??""}}async respondToolApproval($){let Y={approvalId:$.approvalId,approved:$.approved,reason:$.reason,responderClientId:$.responderClientId},T=await this.unary((q)=>{this.client.RespondToolApproval(Y,q)});return{approvalId:T.approvalId??"",applied:T.applied===!0}}async listPendingApprovals($){return((await this.unary((Y)=>{this.client.ListPendingApprovals({sessionId:$},Y)})).approvals??[]).map((Y)=>({approvalId:Y.approvalId??"",sessionId:Y.sessionId??"",taskId:Y.taskId??"",toolCallId:Y.toolCallId??"",toolName:Y.toolName??"",inputJson:Y.inputJson??"",requesterClientId:Y.requesterClientId??"",createdAt:Y.createdAt??""}))}async createSchedule($){let Y=await this.unary((T)=>{this.client.CreateSchedule({name:$.name,cronPattern:$.cronPattern,prompt:$.prompt,provider:$.provider,model:$.model,mode:$.mode??"act",workspaceRoot:$.workspaceRoot,cwd:$.cwd,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",timeoutSeconds:$.timeoutSeconds??0,hasTimeoutSeconds:typeof $.timeoutSeconds==="number",maxParallel:$.maxParallel??1,enabled:$.enabled??!0,createdBy:$.createdBy,tagsJson:$.tags?JSON.stringify($.tags):"",metadata:Q1($.metadata)},T)});return Y.schedule?YT(Y.schedule):void 0}async getSchedule($){let Y=await this.unary((T)=>{this.client.GetSchedule({scheduleId:$},T)});return Y.schedule?YT(Y.schedule):void 0}async listSchedules($){return((await this.unary((Y)=>{this.client.ListSchedules({limit:$?.limit??100,hasEnabled:typeof $?.enabled==="boolean",enabled:$?.enabled??!1,tagsJson:$?.tags?JSON.stringify($.tags):""},Y)})).schedules??[]).map((Y)=>YT(Y))}async updateSchedule($,Y){let T={scheduleId:$};if(Y.name!==void 0)T.hasName=!0,T.name=Y.name;if(Y.cronPattern!==void 0)T.hasCronPattern=!0,T.cronPattern=Y.cronPattern;if(Y.prompt!==void 0)T.hasPrompt=!0,T.prompt=Y.prompt;if(Y.provider!==void 0)T.hasProvider=!0,T.provider=Y.provider;if(Y.model!==void 0)T.hasModel=!0,T.model=Y.model;if(Y.mode!==void 0)T.hasMode=!0,T.mode=Y.mode;if(Y.workspaceRoot!==void 0)T.hasWorkspaceRoot=!0,T.workspaceRoot=Y.workspaceRoot;if(Y.cwd!==void 0)T.hasCwd=!0,T.cwd=Y.cwd;if(Y.systemPrompt!==void 0)T.hasSystemPrompt=!0,T.systemPrompt=Y.systemPrompt;if(Y.maxIterations===null)T.clearMaxIterations=!0;else if(Y.maxIterations!==void 0)T.hasMaxIterations=!0,T.maxIterations=Y.maxIterations;if(Y.timeoutSeconds===null)T.clearTimeoutSeconds=!0;else if(Y.timeoutSeconds!==void 0)T.hasTimeoutSeconds=!0,T.timeoutSeconds=Y.timeoutSeconds;if(Y.maxParallel!==void 0)T.hasMaxParallel=!0,T.maxParallel=Y.maxParallel;if(Y.enabled!==void 0)T.hasEnabled=!0,T.enabled=Y.enabled;if(Y.createdBy===null)T.clearCreatedBy=!0;else if(Y.createdBy!==void 0)T.hasCreatedBy=!0,T.createdBy=Y.createdBy;if(Y.tags!==void 0)T.hasTagsJson=!0,T.tagsJson=JSON.stringify(Y.tags);if(Y.metadata!==void 0)T.hasMetadata=!0,T.metadata=Q1(Y.metadata);let q=await this.unary((X)=>{this.client.UpdateSchedule(T,X)});return q.schedule?YT(q.schedule):void 0}async deleteSchedule($){return(await this.unary((Y)=>{this.client.DeleteSchedule({scheduleId:$},Y)})).deleted===!0}async pauseSchedule($){let Y=await this.unary((T)=>{this.client.PauseSchedule({scheduleId:$},T)});return Y.schedule?YT(Y.schedule):void 0}async resumeSchedule($){let Y=await this.unary((T)=>{this.client.ResumeSchedule({scheduleId:$},T)});return Y.schedule?YT(Y.schedule):void 0}async triggerScheduleNow($){let Y=await this.unary((T)=>{this.client.TriggerScheduleNow({scheduleId:$},T)});return Y.execution?yJ(Y.execution):void 0}async listScheduleExecutions($){return((await this.unary((Y)=>{this.client.ListScheduleExecutions({scheduleId:$.scheduleId,status:$.status,limit:$.limit??50},Y)})).executions??[]).map((Y)=>yJ(Y))}async getScheduleStats($){let Y=await this.unary((T)=>{this.client.GetScheduleStats({scheduleId:$},T)});return{totalRuns:Number(Y.totalRuns??0),successRate:Number(Y.successRate??0),avgDurationSeconds:Number(Y.avgDurationSeconds??0),lastFailure:Y.lastFailure?yJ(Y.lastFailure):void 0}}async getActiveScheduledExecutions(){return((await this.unary(($)=>{this.client.GetActiveScheduledExecutions({},$)})).executions??[]).map(($)=>({executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId??"",startedAt:$.startedAt??"",timeoutAt:$.timeoutAt?.trim()||void 0}))}async getUpcomingScheduledRuns($=20){return((await this.unary((Y)=>{this.client.GetUpcomingScheduledRuns({limit:$},Y)})).runs??[]).map((Y)=>({scheduleId:Y.scheduleId??"",name:Y.name??"",nextRunAt:Y.nextRunAt??""}))}async stopRuntimeSession($){return{applied:(await this.unary((Y)=>{this.client.StopRuntimeSession({sessionId:$},Y)})).applied===!0}}async runProviderAction($){let Y=$.action==="listProviders"?{listProviders:{}}:$.action==="getProviderModels"?{getProviderModels:{providerId:$.providerId}}:$.action==="addProvider"?{addProvider:{providerId:$.providerId,name:$.name,baseUrl:$.baseUrl,apiKey:$.apiKey??"",headers:$.headers??{},timeoutMs:$.timeoutMs??0,hasTimeoutMs:typeof $.timeoutMs==="number",models:$.models??[],defaultModelId:$.defaultModelId??"",modelsSourceUrl:$.modelsSourceUrl??"",capabilities:$.capabilities??[]}}:$.action==="saveProviderSettings"?{saveProviderSettings:{providerId:$.providerId,enabled:$.enabled??!1,hasEnabled:typeof $.enabled==="boolean",apiKey:$.apiKey??"",hasApiKey:$.apiKey!==void 0,baseUrl:$.baseUrl??"",hasBaseUrl:$.baseUrl!==void 0}}:{clineAccount:{operation:$.operation,userId:"userId"in $?$.userId??"":"",organizationId:"organizationId"in $?$.organizationId??"":"",memberId:"memberId"in $?$.memberId??"":"",clearOrganizationId:"organizationId"in $&&$.organizationId===null}},T=await this.unary((q)=>{this.client.RunProviderAction({request:Y},q)});return{result:UY(T.result)}}async runProviderOAuthLogin($){let Y=await this.unary((T)=>{this.client.RunProviderOAuthLogin({provider:$},T)});return{provider:Y.provider??"",accessToken:Y.apiKey??""}}async publishEvent($){let Y=await this.unary((T)=>{this.client.PublishEvent({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId,eventType:$.eventType,payload:Q1($.payload),sourceClientId:$.sourceClientId},T)});return{eventId:Y.eventId??"",accepted:Y.accepted===!0}}streamEvents($,Y={}){let T=!1,q=this.client.StreamEvents({clientId:$.clientId??"",sessionIds:$.sessionIds??[]}),X=(U)=>{Y.onEvent?.({eventId:U.eventId??"",sessionId:U.sessionId??"",taskId:U.taskId?.trim()?U.taskId:void 0,eventType:U.eventType??"",payload:f0(U.payload)??{},sourceClientId:U.sourceClientId?.trim()?U.sourceClientId:void 0,ts:U.ts??""})},J=(U)=>{let Z=(typeof U.code==="number"?Number(U.code):void 0)===1||U.message.includes("CANCELLED");if(T&&Z)return;Y.onError?.(U)},Q=()=>{Y.onEnd?.()};return q.on("data",X),q.on("error",J),q.on("end",Q),()=>{T=!0,q.cancel()}}streamTeamProgress($,Y={}){return this.streamEvents($,{onEvent:(T)=>{if(T.eventType===x6){try{let q=T.payload;if(q.type==="team_progress_projection"&&q.version===1)Y.onProjection?.(q)}catch{}return}if(T.eventType===k6)try{Y.onLifecycle?.(T.payload)}catch{}},onError:Y.onError,onEnd:Y.onEnd})}async unary($){return await new Promise((Y,T)=>{$((q,X)=>{if(q){T(q);return}Y(X??{})})})}}var fy="127.0.0.1:4317",by="cline.rpc.v1",k3="ClineGateway";function uy(){return y3(import.meta.url)}function dy(){let $=x3.loadSync(uy(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),Y=v3.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!Y)throw Error(`Unable to load ${by}.${k3} from proto`);return Y}function qT(){return new Date().toISOString()}function N($){return typeof $==="string"?$:""}function cy($){if(!$||typeof $!=="object")return{};let Y={};for(let[T,q]of Object.entries($)){let X=T.trim();if(!X)continue;let J=N(q).trim();if(!J)continue;Y[X]=J}return Y}function py($){if(!Array.isArray($)||$.length===0)return;let Y=new Set;for(let T of $){let q=T.trim();if(q)Y.add(q)}return Y.size>0?Y:void 0}function h3($){if($==="running"||$==="completed"||$==="failed"||$==="cancelled")return $;return"running"}function L3($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??"",exitCode:$.exitCode??0,status:$.status,statusLock:$.statusLock,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??"",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??"",parentAgentId:$.parentAgentId??"",agentId:$.agentId??"",conversationId:$.conversationId??"",isSubagent:$.isSubagent,prompt:$.prompt??"",transcriptPath:$.transcriptPath,hookPath:$.hookPath,messagesPath:$.messagesPath??"",updatedAt:$.updatedAt,metadata:Q1($.metadata)}}function ly($){let Y=N($.sessionId).trim(),T=N($.source).trim(),q=N($.startedAt).trim(),X=N($.provider).trim(),J=N($.model).trim(),Q=N($.cwd).trim(),U=N($.workspaceRoot).trim(),Z=N($.transcriptPath).trim(),K=N($.hookPath).trim();if(!Y||!T||!q||!X||!J||!Q||!U||!Z||!K)throw Error("session record is missing required fields");return{sessionId:Y,source:T,pid:Number($.pid??0),startedAt:q,endedAt:N($.endedAt).trim()||null,exitCode:typeof $.exitCode==="number"?Math.floor($.exitCode):null,status:h3(N($.status).trim()),statusLock:typeof $.statusLock==="number"?Math.floor($.statusLock):0,interactive:$.interactive===!0,provider:X,model:J,cwd:Q,workspaceRoot:U,teamName:N($.teamName).trim()||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:N($.parentSessionId).trim()||void 0,parentAgentId:N($.parentAgentId).trim()||void 0,agentId:N($.agentId).trim()||void 0,conversationId:N($.conversationId).trim()||void 0,isSubagent:$.isSubagent===!0,prompt:N($.prompt).trim()||void 0,metadata:f0($.metadata),transcriptPath:Z,hookPath:K,messagesPath:N($.messagesPath).trim()||void 0,updatedAt:N($.updatedAt).trim()||qT()}}function jJ($){let Y=N($).trim();if(!Y)return;try{let T=JSON.parse(Y);if(!Array.isArray(T))return;let q=T.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return q.length>0?q:void 0}catch{return}}function TT($){return{scheduleId:$.scheduleId,name:$.name,cronPattern:$.cronPattern,prompt:$.prompt,provider:$.provider,model:$.model,mode:$.mode,workspaceRoot:$.workspaceRoot??"",cwd:$.cwd??"",systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",timeoutSeconds:$.timeoutSeconds??0,hasTimeoutSeconds:typeof $.timeoutSeconds==="number",maxParallel:$.maxParallel,enabled:$.enabled,createdAt:$.createdAt,updatedAt:$.updatedAt,lastRunAt:$.lastRunAt??"",nextRunAt:$.nextRunAt??"",createdBy:$.createdBy??"",tagsJson:$.tags?JSON.stringify($.tags):"",metadata:Q1($.metadata)}}function vJ($){return{executionId:$.executionId,scheduleId:$.scheduleId,sessionId:$.sessionId??"",triggeredAt:$.triggeredAt,startedAt:$.startedAt??"",endedAt:$.endedAt??"",status:$.status,exitCode:$.exitCode??0,hasExitCode:typeof $.exitCode==="number",errorMessage:$.errorMessage??"",iterations:$.iterations??0,hasIterations:typeof $.iterations==="number",tokensUsed:$.tokensUsed??0,hasTokensUsed:typeof $.tokensUsed==="number",costUsd:$.costUsd??0,hasCostUsd:typeof $.costUsd==="number"}}function ny($){return new(W9.makeGenericClientConstructor(dy(),k3))($,W9.credentials.createInsecure())}async function _3($){return await new Promise((Y)=>{let T;try{T=ny($)}catch{Y(void 0);return}T.Health({},(q,X)=>{if(T?.close(),q||!X){Y(void 0);return}Y(X)})})}var ry=300000;class g3{publishEvent;approvals=new Map;constructor($){this.publishEvent=$}async requestToolApproval($){let Y=N($.sessionId).trim(),T=N($.toolCallId).trim(),q=N($.toolName).trim();if(!Y||!T||!q)throw Error("sessionId, toolCallId, and toolName are required");let X=N($.approvalId).trim()||`apr_${iy()}`;if(!this.approvals.get(X)){let Z={approvalId:X,sessionId:Y,taskId:N($.taskId).trim()||void 0,toolCallId:T,toolName:q,inputJson:N($.inputJson),requesterClientId:N($.requesterClientId).trim()||void 0,createdAt:qT(),status:"pending",waiters:[]};this.approvals.set(X,Z),this.publishEvent({eventId:"",sessionId:Y,taskId:Z.taskId,eventType:"approval.requested",payload:Q1(Z),sourceClientId:Z.requesterClientId})}let J=this.approvals.get(X);if(!J)throw Error("approval state not found");if(J.status==="approved"||J.status==="rejected")return{approvalId:X,decided:!0,approved:J.status==="approved",reason:J.reason??""};let Q=typeof $.timeoutMs==="number"&&$.timeoutMs>0?Math.floor($.timeoutMs):ry,U=await new Promise((Z)=>{let K=setTimeout(()=>{Z({decided:!1,approved:!1,reason:"Tool approval request timed out"})},Q);J.waiters.push((A)=>{clearTimeout(K),Z(A)})});return{approvalId:X,decided:U.decided,approved:U.approved,reason:U.reason??""}}respondToolApproval($){let Y=N($.approvalId).trim();if(!Y)throw Error("approvalId is required");let T=this.approvals.get(Y);if(!T)return{approvalId:Y,applied:!1};T.status=$.approved===!0?"approved":"rejected",T.reason=N($.reason).trim()||void 0;let q={decided:!0,approved:T.status==="approved",reason:T.reason};for(let X of T.waiters.splice(0))X(q);return this.publishEvent({eventId:"",sessionId:T.sessionId,taskId:T.taskId,eventType:"approval.decided",payload:Q1({approvalId:Y,approved:q.approved,reason:q.reason??"",responderClientId:N($.responderClientId).trim()||""}),sourceClientId:N($.responderClientId).trim()||""}),{approvalId:Y,applied:!0}}listPendingApprovals($){let Y=N($.sessionId).trim(),T=[];for(let q of this.approvals.values()){if(q.status!=="pending")continue;if(Y&&q.sessionId!==Y)continue;T.push({approvalId:q.approvalId,sessionId:q.sessionId,taskId:q.taskId??"",toolCallId:q.toolCallId,toolName:q.toolName,inputJson:q.inputJson,requesterClientId:q.requesterClientId??"",createdAt:q.createdAt})}return T.sort((q,X)=>(q.createdAt??"").localeCompare(X.createdAt??"")),{approvals:T}}}class m3{subscribers=new Map;nextSubscriberId=1;publishEvent($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T={eventId:N($.eventId).trim()||`evt_${S3()}`,sessionId:Y,taskId:N($.taskId).trim()||void 0,eventType:N($.eventType).trim()||"unknown",payload:f0($.payload)??{},sourceClientId:N($.sourceClientId).trim()||void 0,ts:qT()};return this.dispatchEvent(T),{eventId:T.eventId,accepted:!0}}addSubscriber($){let Y=$.request,T=py(Y.sessionIds),q=this.nextSubscriberId;return this.nextSubscriberId+=1,this.subscribers.set(q,{call:$,filterSessionIds:T}),$.on("cancelled",()=>{this.subscribers.delete(q)}),$.on("close",()=>{this.subscribers.delete(q)}),q}removeSubscriber($){this.subscribers.delete($)}broadcastServerEvent($,Y){let T=`evt_${S3()}`,q=qT();for(let X of this.subscribers.values())X.call.write({eventId:T,sessionId:"__rpc__",taskId:"",eventType:$,payload:Q1(Y),sourceClientId:"rpc-server",ts:q})}dispatchEvent($){for(let Y of this.subscribers.values()){if(Y.filterSessionIds&&!Y.filterSessionIds.has($.sessionId))continue;Y.call.write({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId??"",eventType:$.eventType,payload:Q1($.payload),sourceClientId:$.sourceClientId??"",ts:$.ts})}}}class f3{scheduler;constructor($){this.scheduler=$}createSchedule($){let Y=this.requireScheduler(),T={name:N($.name).trim(),cronPattern:N($.cronPattern).trim(),prompt:N($.prompt),provider:N($.provider).trim(),model:N($.model).trim(),mode:N($.mode).trim()==="plan"?"plan":"act",workspaceRoot:N($.workspaceRoot).trim()||void 0,cwd:N($.cwd).trim()||void 0,systemPrompt:N($.systemPrompt)||void 0,maxIterations:$.hasMaxIterations?Math.floor($.maxIterations??0):void 0,timeoutSeconds:$.hasTimeoutSeconds?Math.floor($.timeoutSeconds??0):void 0,maxParallel:typeof $.maxParallel==="number"&&$.maxParallel>0?Math.floor($.maxParallel):1,enabled:$.enabled!==!1,createdBy:N($.createdBy).trim()||void 0,tags:jJ(N($.tagsJson)),metadata:f0($.metadata)};if(!T.name||!T.cronPattern||!T.prompt.trim()||!T.provider||!T.model)throw Error("name, cronPattern, prompt, provider, and model are required");let q=Y.createSchedule(T);return{schedule:TT(q)}}getSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.getSchedule(T);return q?{schedule:TT(q)}:{}}listSchedules($){return{schedules:this.requireScheduler().listSchedules({enabled:$.hasEnabled?$.enabled===!0:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0,tags:jJ(N($.tagsJson))}).map((Y)=>TT(Y))}}updateSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q={};if($.hasName)q.name=N($.name);if($.hasCronPattern)q.cronPattern=N($.cronPattern);if($.hasPrompt)q.prompt=N($.prompt);if($.hasProvider)q.provider=N($.provider);if($.hasModel)q.model=N($.model);if($.hasMode)q.mode=N($.mode).trim()==="plan"?"plan":"act";if($.hasWorkspaceRoot)q.workspaceRoot=N($.workspaceRoot);if($.hasCwd)q.cwd=N($.cwd);if($.hasSystemPrompt)q.systemPrompt=N($.systemPrompt);if($.clearMaxIterations)q.maxIterations=null;else if($.hasMaxIterations)q.maxIterations=Math.floor($.maxIterations??0);if($.clearTimeoutSeconds)q.timeoutSeconds=null;else if($.hasTimeoutSeconds)q.timeoutSeconds=Math.floor($.timeoutSeconds??0);if($.hasMaxParallel)q.maxParallel=Math.floor($.maxParallel??1);if($.hasEnabled)q.enabled=$.enabled===!0;if($.clearCreatedBy)q.createdBy=null;else if($.hasCreatedBy)q.createdBy=N($.createdBy);if($.hasTagsJson)q.tags=jJ(N($.tagsJson))??[];if($.hasMetadata)q.metadata=f0($.metadata)??{};let X=Y.updateSchedule(T,q);return{updated:X!==void 0,schedule:X?TT(X):void 0}}deleteSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");return{deleted:Y.deleteSchedule(T)}}pauseSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.pauseSchedule(T);return{updated:q!==void 0,schedule:q?TT(q):void 0}}resumeSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.resumeSchedule(T);return{updated:q!==void 0,schedule:q?TT(q):void 0}}async triggerScheduleNow($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=await Y.triggerScheduleNow(T);return q?{execution:vJ(q)}:{}}listScheduleExecutions($){let Y=this.requireScheduler(),T=N($.scheduleId).trim()||void 0,q=N($.status).trim()||void 0;return{executions:Y.listScheduleExecutions({scheduleId:T,status:q==="pending"||q==="running"||q==="success"||q==="failed"||q==="timeout"||q==="aborted"?q:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0}).map((X)=>vJ(X))}}getScheduleStats($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.getScheduleStats(T);return{totalRuns:q.totalRuns,successRate:q.successRate,avgDurationSeconds:q.avgDurationSeconds,lastFailure:q.lastFailure?vJ(q.lastFailure):void 0}}getActiveScheduledExecutions($){return{executions:this.requireScheduler().getActiveExecutions().map((Y)=>({executionId:Y.executionId,scheduleId:Y.scheduleId,sessionId:Y.sessionId,startedAt:Y.startedAt,timeoutAt:Y.timeoutAt??""}))}}getUpcomingScheduledRuns($){let Y=this.requireScheduler(),T=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):20;return{runs:Y.getUpcomingRuns(T).map((q)=>({scheduleId:q.scheduleId,name:q.name,nextRunAt:q.nextRunAt}))}}requireScheduler(){if(!this.scheduler)throw Error("scheduler service is not configured");return this.scheduler}}class ay{serverId=w3();address;startedAt;runtimeHandlers;sessions=new Map;tasks=new Map;clients=new Map;store;eventService=new m3;approvalService=new g3(($)=>this.eventService.publishEvent($));scheduleService;constructor($,Y,T,q){this.address=$,this.startedAt=qT(),this.store=Y,this.runtimeHandlers=T,this.scheduleService=new f3(q),this.store.init()}health(){return{serverId:this.serverId,address:this.address,running:!0,startedAt:this.startedAt}}registerClient($){let Y=N($.clientId).trim()||`client_${w3()}`,T=N($.clientType).trim()||void 0,q=cy($),X=qT(),J=this.clients.get(Y),Q=J?{...J,clientType:T??J.clientType,metadata:Object.keys(q).length>0?{...J.metadata??{},...q}:J.metadata,lastRegisteredAt:X,activationCount:J.activationCount+1}:{clientId:Y,clientType:T,metadata:Object.keys(q).length>0?q:void 0,firstRegisteredAt:X,lastRegisteredAt:X,activationCount:1};return this.clients.set(Y,Q),this.broadcastServerEvent("rpc.client.activated",{clientId:Q.clientId,clientType:Q.clientType,metadata:Q.metadata??{},firstRegisteredAt:Q.firstRegisteredAt,lastRegisteredAt:Q.lastRegisteredAt,activationCount:Q.activationCount}),{clientId:Y,registered:!0}}ensureSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.sessions.get(Y);if(T)return T.status=N($.status).trim()||T.status,T.workspaceRoot=N($.workspaceRoot).trim()||T.workspaceRoot,T.clientId=N($.clientId).trim()||T.clientId,T.metadata=f0($.metadata)??T.metadata,{sessionId:Y,created:!1,status:T.status};let q=N($.status).trim()||"running";return this.sessions.set(Y,{sessionId:Y,status:q,workspaceRoot:N($.workspaceRoot).trim()||void 0,clientId:N($.clientId).trim()||void 0,metadata:f0($.metadata)}),{sessionId:Y,created:!0,status:q}}upsertSession($){if(!$.session)throw Error("session is required");return this.store.upsertSession(ly($.session)),{persisted:!0}}getSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.store.getSession(Y);if(!T)return{};return{session:L3(T)}}listSessions($){let Y=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):200;return{sessions:this.store.listSessions({limit:Y,parentSessionId:N($.parentSessionId).trim()||void 0,status:N($.status).trim()||void 0}).map((T)=>L3(T))}}updateSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");return this.store.updateSession({sessionId:Y,status:$.status?h3($.status):void 0,endedAt:$.endedAt?$.endedAt:void 0,exitCode:$.hasExitCode?$.exitCode??null:void 0,prompt:$.hasPrompt?$.prompt??null:void 0,metadata:$.hasMetadata?f0($.metadata)??null:void 0,parentSessionId:$.hasParentSessionId?$.parentSessionId??null:void 0,parentAgentId:$.hasParentAgentId?$.parentAgentId??null:void 0,agentId:$.hasAgentId?$.agentId??null:void 0,conversationId:$.hasConversationId?$.conversationId??null:void 0,expectedStatusLock:$.hasExpectedStatusLock?$.expectedStatusLock:void 0,setRunning:$.setRunning===!0})}deleteSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.store.deleteSession(Y);if($.cascade===!0)this.store.deleteSessionsByParent(Y);return{deleted:T}}enqueueSpawnRequest($){let Y=N($.rootSessionId).trim(),T=N($.parentAgentId).trim();if(!Y||!T)throw Error("rootSessionId and parentAgentId are required");return this.store.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:T,task:N($.task).trim()||void 0,systemPrompt:N($.systemPrompt).trim()||void 0}),{enqueued:!0}}claimSpawnRequest($){let Y=N($.rootSessionId).trim(),T=N($.parentAgentId).trim();if(!Y||!T)throw Error("rootSessionId and parentAgentId are required");let q=this.store.claimSpawnRequest(Y,T);if(!q)return{};return{item:{id:String(q.id),rootSessionId:q.rootSessionId,parentAgentId:q.parentAgentId,task:q.task??"",systemPrompt:q.systemPrompt??"",createdAt:q.createdAt,consumedAt:q.consumedAt??""}}}async startRuntimeSession($){let Y=this.runtimeHandlers?.startSession;if(!Y)throw Error("runtime start handler is not configured");let T=$.request?{sessionId:N($.request.sessionId),workspaceRoot:N($.request.workspaceRoot),cwd:N($.request.cwd),provider:N($.request.provider),model:N($.request.model),mode:N($.request.mode),apiKey:N($.request.apiKey),systemPrompt:N($.request.systemPrompt),maxIterations:$.request.hasMaxIterations?$.request.maxIterations:void 0,enableTools:$.request.enableTools===!0,enableSpawn:$.request.enableSpawn===!0,enableTeams:$.request.enableTeams===!0,autoApproveTools:$.request.hasAutoApproveTools?$.request.autoApproveTools===!0:void 0,teamName:N($.request.teamName),missionStepInterval:$.request.missionStepInterval??3,missionTimeIntervalMs:$.request.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.initialMessages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),logger:$.request.logger?{enabled:$.request.logger.enabled===!0,level:N($.request.logger.level),destination:N($.request.logger.destination),name:N($.request.logger.name),bindings:f0($.request.logger.bindings)}:void 0}:void 0;if(!T)throw Error("runtime start request is required");let q=await Y(T),X=N(q.sessionId).trim();if(!X)throw Error("runtime start handler returned empty sessionId");return{sessionId:X,startResult:q.startResult?{sessionId:N(q.startResult.sessionId),manifestPath:N(q.startResult.manifestPath),transcriptPath:N(q.startResult.transcriptPath),hookPath:N(q.startResult.hookPath),messagesPath:N(q.startResult.messagesPath)}:void 0}}async sendRuntimeSession($){let Y=this.runtimeHandlers?.sendSession;if(!Y)throw Error("runtime send handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");let q=$.request?{config:{workspaceRoot:N($.request.config?.workspaceRoot),cwd:N($.request.config?.cwd),provider:N($.request.config?.provider),model:N($.request.config?.model),mode:N($.request.config?.mode),apiKey:N($.request.config?.apiKey),systemPrompt:N($.request.config?.systemPrompt),maxIterations:$.request.config?.hasMaxIterations?$.request.config?.maxIterations:void 0,enableTools:$.request.config?.enableTools===!0,enableSpawn:$.request.config?.enableSpawn===!0,enableTeams:$.request.config?.enableTeams===!0,autoApproveTools:$.request.config?.hasAutoApproveTools?$.request.config?.autoApproveTools===!0:void 0,teamName:N($.request.config?.teamName),missionStepInterval:$.request.config?.missionStepInterval??3,missionTimeIntervalMs:$.request.config?.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.config?.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.config?.initialMessages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),logger:$.request.config?.logger?{enabled:$.request.config.logger.enabled===!0,level:N($.request.config.logger.level),destination:N($.request.config.logger.destination),name:N($.request.config.logger.name),bindings:f0($.request.config.logger.bindings)}:void 0},messages:($.request.messages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),prompt:N($.request.prompt),attachments:$.request.attachments?{userImages:$.request.attachments.userImages??[],userFiles:($.request.attachments.userFiles??[]).map((J)=>({name:N(J.name),content:N(J.content)}))}:void 0}:void 0;if(!q)throw Error("runtime send request is required");let X=await Y(T,q);return{result:{text:N(X.result.text),usage:{inputTokens:X.result.usage.inputTokens,outputTokens:X.result.usage.outputTokens,cacheReadTokens:X.result.usage.cacheReadTokens??0,hasCacheReadTokens:typeof X.result.usage.cacheReadTokens==="number",cacheWriteTokens:X.result.usage.cacheWriteTokens??0,hasCacheWriteTokens:typeof X.result.usage.cacheWriteTokens==="number",totalCost:X.result.usage.totalCost??0,hasTotalCost:typeof X.result.usage.totalCost==="number"},inputTokens:X.result.inputTokens,outputTokens:X.result.outputTokens,iterations:X.result.iterations,finishReason:N(X.result.finishReason),messages:(X.result.messages??[]).map((J)=>({role:N(J.role),content:QY(J.content)})),toolCalls:(X.result.toolCalls??[]).map((J)=>({name:N(J.name),input:QY(J.input),hasInput:J.input!==void 0,output:QY(J.output),hasOutput:J.output!==void 0,error:N(J.error),durationMs:J.durationMs??0,hasDurationMs:typeof J.durationMs==="number"}))}}}async stopRuntimeSession($){let Y=this.runtimeHandlers?.stopSession;if(!Y)throw Error("runtime stop handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");return{applied:(await Y(T)).applied===!0}}async abortRuntimeSession($){let Y=this.runtimeHandlers?.abortSession;if(!Y)throw Error("runtime abort handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");return{applied:(await Y(T)).applied===!0}}async runProviderAction($){let Y=this.runtimeHandlers?.runProviderAction;if(!Y)throw Error("provider action handler is not configured");if(!$.request)throw Error("provider action request is required");let T;if($.request.listProviders)T={action:"listProviders"};else if($.request.getProviderModels)T={action:"getProviderModels",providerId:N($.request.getProviderModels.providerId)};else if($.request.addProvider)T={action:"addProvider",providerId:N($.request.addProvider.providerId),name:N($.request.addProvider.name),baseUrl:N($.request.addProvider.baseUrl),apiKey:N($.request.addProvider.apiKey)||void 0,headers:$.request.addProvider.headers??void 0,timeoutMs:$.request.addProvider.hasTimeoutMs?$.request.addProvider.timeoutMs:void 0,models:$.request.addProvider.models??void 0,defaultModelId:N($.request.addProvider.defaultModelId)||void 0,modelsSourceUrl:N($.request.addProvider.modelsSourceUrl)||void 0,capabilities:$.request.addProvider.capabilities};else if($.request.saveProviderSettings)T={action:"saveProviderSettings",providerId:N($.request.saveProviderSettings.providerId),enabled:$.request.saveProviderSettings.hasEnabled?$.request.saveProviderSettings.enabled:void 0,apiKey:$.request.saveProviderSettings.hasApiKey?$.request.saveProviderSettings.apiKey:void 0,baseUrl:$.request.saveProviderSettings.hasBaseUrl?$.request.saveProviderSettings.baseUrl:void 0};else{let X=N($.request.clineAccount?.operation);if(X==="fetchMe")T={action:"clineAccount",operation:"fetchMe"};else if(X==="fetchBalance")T={action:"clineAccount",operation:"fetchBalance",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchUsageTransactions")T={action:"clineAccount",operation:"fetchUsageTransactions",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchPaymentTransactions")T={action:"clineAccount",operation:"fetchPaymentTransactions",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchUserOrganizations")T={action:"clineAccount",operation:"fetchUserOrganizations"};else if(X==="fetchOrganizationBalance")T={action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:N($.request.clineAccount?.organizationId)};else if(X==="fetchOrganizationUsageTransactions")T={action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:N($.request.clineAccount?.organizationId),memberId:N($.request.clineAccount?.memberId)||void 0};else T={action:"clineAccount",operation:"switchAccount",organizationId:$.request.clineAccount?.clearOrganizationId?null:N($.request.clineAccount?.organizationId)||void 0}}let q=await Y(T);return{result:QY(q.result)}}async runProviderOAuthLogin($){let Y=this.runtimeHandlers?.runProviderOAuthLogin;if(!Y)throw Error("provider oauth handler is not configured");let T=N($.provider).trim();if(!T)throw Error("provider is required");let q=await Y(T);return{provider:N(q.provider).trim(),apiKey:N(q.accessToken)}}startTask($){let Y=N($.sessionId).trim(),T=N($.taskId).trim();if(!Y||!T)throw Error("sessionId and taskId are required");let q=`${Y}:${T}`;return this.tasks.set(q,{sessionId:Y,taskId:T,title:N($.title).trim()||void 0,status:"running",payload:f0($.payload)??void 0}),this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:T,eventType:"task.started",payload:f0($.payload)??{},sourceClientId:""}),{sessionId:Y,taskId:T,status:"running",updated:!0}}completeTask($){let Y=N($.sessionId).trim(),T=N($.taskId).trim();if(!Y||!T)throw Error("sessionId and taskId are required");let q=`${Y}:${T}`,X=N($.status).trim()||"completed",J=this.tasks.get(q);if(!J)return{sessionId:Y,taskId:T,status:X,updated:!1};return J.status=X,J.result=f0($.result)??void 0,this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:T,eventType:"task.completed",payload:f0($.result)??{},sourceClientId:""}),{sessionId:Y,taskId:T,status:X,updated:!0}}publishEvent($){return this.eventService.publishEvent($)}addSubscriber($){return this.eventService.addSubscriber($)}removeSubscriber($){this.eventService.removeSubscriber($)}requestToolApproval($){return this.approvalService.requestToolApproval($)}respondToolApproval($){return this.approvalService.respondToolApproval($)}listPendingApprovals($){return this.approvalService.listPendingApprovals($)}createSchedule($){return this.scheduleService.createSchedule($)}getSchedule($){return this.scheduleService.getSchedule($)}listSchedules($){return this.scheduleService.listSchedules($)}updateSchedule($){return this.scheduleService.updateSchedule($)}deleteSchedule($){return this.scheduleService.deleteSchedule($)}pauseSchedule($){return this.scheduleService.pauseSchedule($)}resumeSchedule($){return this.scheduleService.resumeSchedule($)}triggerScheduleNow($){return this.scheduleService.triggerScheduleNow($)}listScheduleExecutions($){return this.scheduleService.listScheduleExecutions($)}getScheduleStats($){return this.scheduleService.getScheduleStats($)}getActiveScheduledExecutions($){return this.scheduleService.getActiveScheduledExecutions($)}getUpcomingScheduledRuns($){return this.scheduleService.getUpcomingScheduledRuns($)}broadcastServerEvent($,Y){this.eventService.broadcastServerEvent($,Y)}}function b3(){return fy}import{appendFileSync as u3,existsSync as sy,readFileSync as ty,writeFileSync as B6}from"node:fs";import{nanoid as ey}from"nanoid";import{z as gJ}from"zod";import{nanoid as oy}from"nanoid";function M6($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function G9($,Y){let T=M6($),q=M6(Y),X=`${T}__${q}`;return X.length>180?X.slice(0,180):X}function hJ($,Y){let T=M6($),q=M6(Y);return`${T}__teamtask__${q}__${oy(6)}`}function _J($){switch($.hookName){case"agent_end":return"completed";case"session_shutdown":{let Y=String($.reason??"").toLowerCase();if(Y.includes("cancel")||Y.includes("abort")||Y.includes("interrupt"))return"cancelled";if(Y.includes("fail")||Y.includes("error"))return"failed";return"completed"}default:return"running"}}var d3="cli_subagent",$j=gJ.object({task:gJ.string().optional(),systemPrompt:gJ.string().optional()}).passthrough();function c3($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}class R6{adapter;teamTaskSessionsByAgent=new Map;artifacts;constructor($){this.adapter=$;this.artifacts=new v4(()=>this.ensureSessionsDir())}teamTaskQueueKey($,Y){return`${$}::${Y}`}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}sessionTranscriptPath($){return this.artifacts.sessionTranscriptPath($)}sessionHookPath($){return this.artifacts.sessionHookPath($)}sessionMessagesPath($){return this.artifacts.sessionMessagesPath($)}sessionManifestPath($,Y=!0){return this.artifacts.sessionManifestPath($,Y)}async sessionPathFromStore($,Y){let q=(await this.adapter.getSession($))?.[Y];return typeof q==="string"&&q.trim().length>0?q:void 0}activeTeamTaskSessionId($,Y){let T=this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,Y));if(!T||T.length===0)return;return T[T.length-1]}subagentArtifactPaths($,Y,T,q){return this.artifacts.subagentArtifactPaths(Y,q,this.activeTeamTaskSessionId($,T))}writeSessionManifestFile($,Y){let T=IY.parse(Y);B6($,`${JSON.stringify(T,null,2)}
|
|
580
|
-
`,"utf8")}createRootSessionId(){return`${Date.now()}_${
|
|
581
|
-
`,"utf8"),this.writeSessionManifestFile(U,Z),{manifestPath:U,transcriptPath:X,hookPath:J,messagesPath:Q,manifest:Z}}writeSessionManifest($,Y){this.writeSessionManifestFile($,Y)}async updateSessionStatus($,Y,T){for(let q=0;q<4;q++){let X=await this.adapter.getSession($);if(!X||typeof X.status_lock!=="number")return{updated:!1};let J=W0();if((await this.adapter.updateSession({sessionId:$,status:Y,endedAt:J,exitCode:typeof T==="number"?T:null,expectedStatusLock:X.status_lock})).updated){if(Y==="cancelled")await this.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:J}}}return{updated:!1}}async updateSession($){for(let Y=0;Y<4;Y++){let T=await this.adapter.getSession($.sessionId);if(!T||typeof T.status_lock!=="number")return{updated:!1};if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadataJson:$.metadata===void 0?void 0:
|
|
582
|
-
`,"utf8"),q;return await this.adapter.updateSession({sessionId:q,setRunning:!0,parentSessionId:Y,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X.prompt??U??null,expectedStatusLock:X.status_lock}),q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let Y=
|
|
583
|
-
`,q=await this.sessionPathFromStore($,"hook_path")??this.sessionHookPath($);
|
|
584
|
-
`,"utf8")}async persistSessionMessages($,Y,T){let q=await this.sessionPathFromStore($,"messages_path")??this.sessionMessagesPath($),X={version:1,updated_at:W0(),messages:Y};if(T!==void 0&&T!=="")X.systemPrompt=T;
|
|
585
|
-
`,"utf8")}async applySubagentStatus($,Y){await this.applySubagentStatusBySessionId($,
|
|
586
|
-
`,"utf8"),await this.appendSubagentTranscriptLine(X,`[start] ${T}`),X}async onTeamTaskStart($,Y,T){let q=await this.createTeamTaskSubSession($,Y,T);if(!q)return;let X=this.teamTaskQueueKey($,Y),J=this.teamTaskSessionsByAgent.get(X)??[];J.push(q),this.teamTaskSessionsByAgent.set(X,J)}async onTeamTaskEnd($,Y,T,q,X){let J=this.teamTaskQueueKey($,Y),Q=this.teamTaskSessionsByAgent.get(J);if(!Q||Q.length===0)return;let U=Q.shift();if(Q.length===0)this.teamTaskSessionsByAgent.delete(J);else this.teamTaskSessionsByAgent.set(J,Q);if(!U)return;if(X)await this.persistSessionMessages(U,X);await this.appendSubagentTranscriptLine(U,q??`[done] ${T}`),await this.applySubagentStatusBySessionId(U,T)}async handleSubAgentStart($,Y){let T=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!T)return;await this.appendSubagentTranscriptLine(T,`[start] ${Y.input.task}`),await this.applySubagentStatusBySessionId(T,"running")}async handleSubAgentEnd($,Y){let T=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!T)return;if(Y.error){await this.appendSubagentTranscriptLine(T,`[error] ${Y.error.message}`),await this.applySubagentStatusBySessionId(T,"failed");return}if(await this.appendSubagentTranscriptLine(T,`[done] ${Y.result?.finishReason??"completed"}`),Y.result?.finishReason==="aborted"){await this.applySubagentStatusBySessionId(T,"cancelled");return}await this.applySubagentStatusBySessionId(T,"completed")}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(Y){return typeof Y==="object"&&Y!==null&&"code"in Y&&Y.code==="EPERM"}}async listSessions($=200){let Y=Math.max(1,Math.floor($)),T=Math.min(Y*5,2000),q=await this.adapter.listSessions({limit:T}),X=q.filter((J)=>J.status==="running"&&!this.isPidAlive(J.pid));if(X.length>0){for(let J of X)await this.updateSessionStatus(J.session_id,"failed",1);q=await this.adapter.listSessions({limit:T})}return q.slice(0,Y)}async deleteSession($){let Y=$.trim();if(!Y)throw Error("session id is required");let T=await this.adapter.getSession(Y);if(!T)return{deleted:!1};if(await this.adapter.deleteSession(Y,!1),!T.is_subagent){let q=await this.adapter.listSessions({limit:2000,parentSessionId:Y});await this.adapter.deleteSession(Y,!0);for(let X of q)$$(X.transcript_path),$$(X.hook_path),$$(X.messages_path),$$(this.sessionManifestPath(X.session_id,!1)),this.artifacts.removeSessionDirIfEmpty(X.session_id)}return $$(T.transcript_path),$$(T.hook_path),$$(T.messages_path),$$(this.sessionManifestPath(Y,!1)),this.artifacts.removeSessionDirIfEmpty(Y),{deleted:!0}}}function
|
|
579
|
+
${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y($)}async invoke($,...Y){let T=this.sessionService[$];if(typeof T!=="function")throw Error(`session service method not available: ${$}`);return Promise.resolve(T.apply(this.sessionService,Y))}async invokeOptional($,...Y){let T=this.sessionService[$];if(typeof T!=="function")return;await Promise.resolve(T.apply(this.sessionService,Y))}async invokeOptionalValue($,...Y){let T=this.sessionService[$];if(typeof T!=="function")return;return await Promise.resolve(T.apply(this.sessionService,Y))}async runWithAuthRetry($,Y,T){try{return await Y()}catch(q){if(!this.isLikelyAuthError(q,$.config.providerId))throw q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(T),Y()}}isLikelyAuthError($,Y){if(Y!=="cline"&&Y!=="oca"&&Y!=="openai-codex")return!1;let T=$ instanceof Error?$.message.toLowerCase():String($);return T.includes("401")||T.includes("403")||T.includes("unauthorized")||T.includes("forbidden")||T.includes("invalid token")||T.includes("expired token")||T.includes("authentication")}async syncOAuthCredentials($,Y){let T=null;try{T=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:Y?.forceRefresh})}catch(X){if(X instanceof v8)throw Error(`OAuth session for "${X.providerId}" requires re-authentication. Run "clite auth ${X.providerId}" and retry.`);throw X}if(!T?.apiKey)return;if($.config.apiKey===T.apiKey)return;$.config.apiKey=T.apiKey,$.agent.updateConnection?.({apiKey:T.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:T.apiKey})}}import{existsSync as Xj,mkdirSync as Jj}from"node:fs";var X6=ZY(IT(),1),x3=ZY(t6(),1);import{existsSync as ky}from"node:fs";import{dirname as S3,join as JY}from"node:path";import{fileURLToPath as hy}from"node:url";var G9=ZY(IT(),1),_3=ZY(IT(),1),g3=ZY(t6(),1);var hJ=ZY(IT(),1);import{randomUUID as j3}from"node:crypto";import{randomUUID as oy}from"node:crypto";import{randomUUID as v3}from"node:crypto";function k3($){let Y=S3(hy($)),T=new Set([JY(Y,"proto","rpc.proto"),JY(Y,"..","proto","rpc.proto"),JY(Y,"..","src","proto","rpc.proto"),JY(Y,"..","..","src","proto","rpc.proto"),JY(process.cwd(),"src","proto","rpc.proto"),JY(process.cwd(),"packages","rpc","src","proto","rpc.proto")]),q=process.cwd();while(!0){T.add(JY(q,"packages","rpc","src","proto","rpc.proto"));let X=S3(q);if(X===q)break;q=X}for(let X of T)if(ky(X))return X;throw Error("Unable to resolve rpc.proto path")}var _y="cline.rpc.v1",h3="ClineGateway";function gy(){return k3(import.meta.url)}function my(){let $=x3.loadSync(gy(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),Y=X6.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!Y)throw Error(`Unable to load ${_y}.${h3} from proto`);return Y}function fy($){return new(X6.makeGenericClientConstructor(my(),h3))($,X6.credentials.createInsecure())}function A9($){if($===null||$===void 0)return{nullValue:"NULL_VALUE"};if(typeof $==="string")return{stringValue:$};if(typeof $==="number")return{numberValue:Number.isFinite($)?$:0};if(typeof $==="boolean")return{boolValue:$};if(Array.isArray($))return{listValue:{values:$.map((Y)=>A9(Y))}};if(typeof $==="object"){let Y={fields:{}};for(let[T,q]of Object.entries($))Y.fields??={},Y.fields[T]=A9(q);return{structValue:Y}}return{stringValue:String($)}}function W9($){if(!$)return;if($.nullValue!==void 0)return null;if($.stringValue!==void 0)return $.stringValue;if($.numberValue!==void 0)return $.numberValue;if($.boolValue!==void 0)return $.boolValue;if($.listValue)return($.listValue.values??[]).map((Y)=>W9(Y));if($.structValue){let Y={};for(let[T,q]of Object.entries($.structValue.fields??{}))Y[T]=W9(q);return Y}return}function Q1($){let Y={};for(let[T,q]of Object.entries($??{}))Y[T]=A9(q);return{fields:Y}}function f0($){if(!$?.fields)return;let Y={};for(let[T,q]of Object.entries($.fields))Y[T]=W9(q);return Y}function QY($){return A9($)}function UY($){return W9($??void 0)}function by($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??"",exitCode:$.exitCode??0,status:$.status,statusLock:$.statusLock,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??"",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??"",parentAgentId:$.parentAgentId??"",agentId:$.agentId??"",conversationId:$.conversationId??"",isSubagent:$.isSubagent,prompt:$.prompt??"",transcriptPath:$.transcriptPath,hookPath:$.hookPath,messagesPath:$.messagesPath??"",updatedAt:$.updatedAt,metadata:Q1($.metadata)}}function C3($){return{sessionId:$.sessionId??"",source:$.source??"",pid:Number($.pid??0),startedAt:$.startedAt??"",endedAt:$.endedAt?$.endedAt:null,exitCode:typeof $.exitCode==="number"?$.exitCode:null,status:$.status??"running",statusLock:Number($.statusLock??0),interactive:$.interactive===!0,provider:$.provider??"",model:$.model??"",cwd:$.cwd??"",workspaceRoot:$.workspaceRoot??"",teamName:$.teamName||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:$.parentSessionId||void 0,parentAgentId:$.parentAgentId||void 0,agentId:$.agentId||void 0,conversationId:$.conversationId||void 0,isSubagent:$.isSubagent===!0,prompt:$.prompt||void 0,metadata:f0($.metadata),transcriptPath:$.transcriptPath??"",hookPath:$.hookPath??"",messagesPath:$.messagesPath||void 0,updatedAt:$.updatedAt??""}}function uy($){let Y=$?.trim();if(!Y)return;try{let T=JSON.parse(Y);if(!Array.isArray(T))return;let q=T.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return q.length>0?q:void 0}catch{return}}function Y6($){return{scheduleId:$.scheduleId??"",name:$.name??"",cronPattern:$.cronPattern??"",prompt:$.prompt??"",provider:$.provider??"",model:$.model??"",mode:$.mode==="plan"?"plan":"act",workspaceRoot:$.workspaceRoot?.trim()||void 0,cwd:$.cwd?.trim()||void 0,systemPrompt:$.systemPrompt?.trim()||void 0,maxIterations:$.hasMaxIterations?$.maxIterations:void 0,timeoutSeconds:$.hasTimeoutSeconds?$.timeoutSeconds:void 0,maxParallel:typeof $.maxParallel==="number"&&$.maxParallel>0?$.maxParallel:1,enabled:$.enabled===!0,createdAt:$.createdAt??"",updatedAt:$.updatedAt??"",lastRunAt:$.lastRunAt?.trim()||void 0,nextRunAt:$.nextRunAt?.trim()||void 0,createdBy:$.createdBy?.trim()||void 0,tags:uy($.tagsJson??void 0),metadata:f0($.metadata)}}function jJ($){return{executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId?.trim()||void 0,triggeredAt:$.triggeredAt??"",startedAt:$.startedAt?.trim()||void 0,endedAt:$.endedAt?.trim()||void 0,status:$.status==="pending"||$.status==="running"||$.status==="success"||$.status==="failed"||$.status==="timeout"||$.status==="aborted"?$.status:"failed",exitCode:$.hasExitCode?$.exitCode:void 0,errorMessage:$.errorMessage?.trim()||void 0,iterations:$.hasIterations?$.iterations:void 0,tokensUsed:$.hasTokensUsed?$.tokensUsed:void 0,costUsd:$.hasCostUsd?$.costUsd:void 0}}class kJ{client;constructor($){this.client=fy($.address)}close(){this.client.close()}async upsertSession($){await this.unary((Y)=>{let T={session:by($)};this.client.UpsertSession(T,Y)})}async getSession($){let Y=await this.unary((T)=>{this.client.GetSession({sessionId:$},T)});if(!Y.session)return;return C3(Y.session)}async listSessions($){return((await this.unary((Y)=>{this.client.ListSessions($,Y)})).sessions??[]).map((Y)=>C3(Y))}async updateSession($){let Y={sessionId:$.sessionId,status:$.status,endedAt:$.endedAt??void 0,setRunning:$.setRunning};if($.exitCode!==void 0)Y.hasExitCode=!0,Y.exitCode=$.exitCode??0;if($.prompt!==void 0)Y.hasPrompt=!0,Y.prompt=$.prompt??"";if($.metadata!==void 0)Y.hasMetadata=!0,Y.metadata=Q1($.metadata??void 0);if($.parentSessionId!==void 0)Y.hasParentSessionId=!0,Y.parentSessionId=$.parentSessionId??"";if($.parentAgentId!==void 0)Y.hasParentAgentId=!0,Y.parentAgentId=$.parentAgentId??"";if($.agentId!==void 0)Y.hasAgentId=!0,Y.agentId=$.agentId??"";if($.conversationId!==void 0)Y.hasConversationId=!0,Y.conversationId=$.conversationId??"";if($.expectedStatusLock!==void 0)Y.hasExpectedStatusLock=!0,Y.expectedStatusLock=$.expectedStatusLock;let T=await this.unary((q)=>{this.client.UpdateSession(Y,q)});return{updated:T.updated===!0,statusLock:Number(T.statusLock??0)}}async deleteSession($,Y=!1){return(await this.unary((T)=>{this.client.DeleteSession({sessionId:$,cascade:Y},T)})).deleted===!0}async enqueueSpawnRequest($){await this.unary((Y)=>{this.client.EnqueueSpawnRequest($,Y)})}async claimSpawnRequest($,Y){let T=(await this.unary((q)=>{let X={rootSessionId:$,parentAgentId:Y};this.client.ClaimSpawnRequest(X,q)})).item?.task?.trim();return T?T:void 0}async startRuntimeSession($){let Y={sessionId:$.sessionId??"",workspaceRoot:$.workspaceRoot,cwd:$.cwd??"",provider:$.provider,model:$.model,mode:$.mode,apiKey:$.apiKey,systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools??!1,hasAutoApproveTools:typeof $.autoApproveTools==="boolean",teamName:$.teamName,missionStepInterval:$.missionStepInterval,missionTimeIntervalMs:$.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries($.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:($.initialMessages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),logger:$.logger?{enabled:$.logger.enabled??!1,level:$.logger.level??"",destination:$.logger.destination??"",name:$.logger.name??"",bindings:Q1($.logger.bindings)}:void 0},T=await this.unary((X)=>{this.client.StartRuntimeSession({request:Y},X)}),q=T.startResult?{sessionId:T.startResult.sessionId??"",manifestPath:T.startResult.manifestPath??"",transcriptPath:T.startResult.transcriptPath??"",hookPath:T.startResult.hookPath??"",messagesPath:T.startResult.messagesPath??""}:void 0;return{sessionId:T.sessionId??"",startResult:q}}async sendRuntimeSession($,Y){let T={config:{workspaceRoot:Y.config.workspaceRoot,cwd:Y.config.cwd??"",provider:Y.config.provider,model:Y.config.model,mode:Y.config.mode,apiKey:Y.config.apiKey,systemPrompt:Y.config.systemPrompt??"",maxIterations:Y.config.maxIterations??0,hasMaxIterations:typeof Y.config.maxIterations==="number",enableTools:Y.config.enableTools,enableSpawn:Y.config.enableSpawn,enableTeams:Y.config.enableTeams,autoApproveTools:Y.config.autoApproveTools??!1,hasAutoApproveTools:typeof Y.config.autoApproveTools==="boolean",teamName:Y.config.teamName,missionStepInterval:Y.config.missionStepInterval,missionTimeIntervalMs:Y.config.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries(Y.config.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:(Y.config.initialMessages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),logger:Y.config.logger?{enabled:Y.config.logger.enabled??!1,level:Y.config.logger.level??"",destination:Y.config.logger.destination??"",name:Y.config.logger.name??"",bindings:Q1(Y.config.logger.bindings)}:void 0},messages:(Y.messages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),prompt:Y.prompt,attachments:Y.attachments?{userImages:Y.attachments.userImages??[],userFiles:(Y.attachments.userFiles??[]).map((X)=>({name:X.name,content:X.content}))}:void 0},q=await this.unary((X)=>{this.client.SendRuntimeSession({sessionId:$,request:T},X)});return{result:{text:q.result?.text??"",usage:{inputTokens:Number(q.result?.usage?.inputTokens??0),outputTokens:Number(q.result?.usage?.outputTokens??0),cacheReadTokens:q.result?.usage?.hasCacheReadTokens?Number(q.result?.usage?.cacheReadTokens??0):void 0,cacheWriteTokens:q.result?.usage?.hasCacheWriteTokens?Number(q.result?.usage?.cacheWriteTokens??0):void 0,totalCost:q.result?.usage?.hasTotalCost?Number(q.result?.usage?.totalCost??0):void 0},inputTokens:Number(q.result?.inputTokens??0),outputTokens:Number(q.result?.outputTokens??0),iterations:Number(q.result?.iterations??0),finishReason:q.result?.finishReason??"",messages:(q.result?.messages??[]).map((X)=>({role:X.role??"",content:UY(X.content)})),toolCalls:(q.result?.toolCalls??[]).map((X)=>({name:X.name??"",input:X.hasInput?UY(X.input):void 0,output:X.hasOutput?UY(X.output):void 0,error:X.error?.trim()||void 0,durationMs:X.hasDurationMs?Number(X.durationMs??0):void 0}))}}}async abortRuntimeSession($){return{applied:(await this.unary((Y)=>{this.client.AbortRuntimeSession({sessionId:$},Y)})).applied===!0}}async requestToolApproval($){let Y={approvalId:$.approvalId,sessionId:$.sessionId,taskId:$.taskId,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:$.inputJson,requesterClientId:$.requesterClientId,timeoutMs:$.timeoutMs},T=await this.unary((q)=>{this.client.RequestToolApproval(Y,q)});return{approvalId:T.approvalId??"",decided:T.decided===!0,approved:T.approved===!0,reason:T.reason??""}}async respondToolApproval($){let Y={approvalId:$.approvalId,approved:$.approved,reason:$.reason,responderClientId:$.responderClientId},T=await this.unary((q)=>{this.client.RespondToolApproval(Y,q)});return{approvalId:T.approvalId??"",applied:T.applied===!0}}async listPendingApprovals($){return((await this.unary((Y)=>{this.client.ListPendingApprovals({sessionId:$},Y)})).approvals??[]).map((Y)=>({approvalId:Y.approvalId??"",sessionId:Y.sessionId??"",taskId:Y.taskId??"",toolCallId:Y.toolCallId??"",toolName:Y.toolName??"",inputJson:Y.inputJson??"",requesterClientId:Y.requesterClientId??"",createdAt:Y.createdAt??""}))}async createSchedule($){let Y=await this.unary((T)=>{this.client.CreateSchedule({name:$.name,cronPattern:$.cronPattern,prompt:$.prompt,provider:$.provider,model:$.model,mode:$.mode??"act",workspaceRoot:$.workspaceRoot,cwd:$.cwd,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",timeoutSeconds:$.timeoutSeconds??0,hasTimeoutSeconds:typeof $.timeoutSeconds==="number",maxParallel:$.maxParallel??1,enabled:$.enabled??!0,createdBy:$.createdBy,tagsJson:$.tags?JSON.stringify($.tags):"",metadata:Q1($.metadata)},T)});return Y.schedule?Y6(Y.schedule):void 0}async getSchedule($){let Y=await this.unary((T)=>{this.client.GetSchedule({scheduleId:$},T)});return Y.schedule?Y6(Y.schedule):void 0}async listSchedules($){return((await this.unary((Y)=>{this.client.ListSchedules({limit:$?.limit??100,hasEnabled:typeof $?.enabled==="boolean",enabled:$?.enabled??!1,tagsJson:$?.tags?JSON.stringify($.tags):""},Y)})).schedules??[]).map((Y)=>Y6(Y))}async updateSchedule($,Y){let T={scheduleId:$};if(Y.name!==void 0)T.hasName=!0,T.name=Y.name;if(Y.cronPattern!==void 0)T.hasCronPattern=!0,T.cronPattern=Y.cronPattern;if(Y.prompt!==void 0)T.hasPrompt=!0,T.prompt=Y.prompt;if(Y.provider!==void 0)T.hasProvider=!0,T.provider=Y.provider;if(Y.model!==void 0)T.hasModel=!0,T.model=Y.model;if(Y.mode!==void 0)T.hasMode=!0,T.mode=Y.mode;if(Y.workspaceRoot!==void 0)T.hasWorkspaceRoot=!0,T.workspaceRoot=Y.workspaceRoot;if(Y.cwd!==void 0)T.hasCwd=!0,T.cwd=Y.cwd;if(Y.systemPrompt!==void 0)T.hasSystemPrompt=!0,T.systemPrompt=Y.systemPrompt;if(Y.maxIterations===null)T.clearMaxIterations=!0;else if(Y.maxIterations!==void 0)T.hasMaxIterations=!0,T.maxIterations=Y.maxIterations;if(Y.timeoutSeconds===null)T.clearTimeoutSeconds=!0;else if(Y.timeoutSeconds!==void 0)T.hasTimeoutSeconds=!0,T.timeoutSeconds=Y.timeoutSeconds;if(Y.maxParallel!==void 0)T.hasMaxParallel=!0,T.maxParallel=Y.maxParallel;if(Y.enabled!==void 0)T.hasEnabled=!0,T.enabled=Y.enabled;if(Y.createdBy===null)T.clearCreatedBy=!0;else if(Y.createdBy!==void 0)T.hasCreatedBy=!0,T.createdBy=Y.createdBy;if(Y.tags!==void 0)T.hasTagsJson=!0,T.tagsJson=JSON.stringify(Y.tags);if(Y.metadata!==void 0)T.hasMetadata=!0,T.metadata=Q1(Y.metadata);let q=await this.unary((X)=>{this.client.UpdateSchedule(T,X)});return q.schedule?Y6(q.schedule):void 0}async deleteSchedule($){return(await this.unary((Y)=>{this.client.DeleteSchedule({scheduleId:$},Y)})).deleted===!0}async pauseSchedule($){let Y=await this.unary((T)=>{this.client.PauseSchedule({scheduleId:$},T)});return Y.schedule?Y6(Y.schedule):void 0}async resumeSchedule($){let Y=await this.unary((T)=>{this.client.ResumeSchedule({scheduleId:$},T)});return Y.schedule?Y6(Y.schedule):void 0}async triggerScheduleNow($){let Y=await this.unary((T)=>{this.client.TriggerScheduleNow({scheduleId:$},T)});return Y.execution?jJ(Y.execution):void 0}async listScheduleExecutions($){return((await this.unary((Y)=>{this.client.ListScheduleExecutions({scheduleId:$.scheduleId,status:$.status,limit:$.limit??50},Y)})).executions??[]).map((Y)=>jJ(Y))}async getScheduleStats($){let Y=await this.unary((T)=>{this.client.GetScheduleStats({scheduleId:$},T)});return{totalRuns:Number(Y.totalRuns??0),successRate:Number(Y.successRate??0),avgDurationSeconds:Number(Y.avgDurationSeconds??0),lastFailure:Y.lastFailure?jJ(Y.lastFailure):void 0}}async getActiveScheduledExecutions(){return((await this.unary(($)=>{this.client.GetActiveScheduledExecutions({},$)})).executions??[]).map(($)=>({executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId??"",startedAt:$.startedAt??"",timeoutAt:$.timeoutAt?.trim()||void 0}))}async getUpcomingScheduledRuns($=20){return((await this.unary((Y)=>{this.client.GetUpcomingScheduledRuns({limit:$},Y)})).runs??[]).map((Y)=>({scheduleId:Y.scheduleId??"",name:Y.name??"",nextRunAt:Y.nextRunAt??""}))}async stopRuntimeSession($){return{applied:(await this.unary((Y)=>{this.client.StopRuntimeSession({sessionId:$},Y)})).applied===!0}}async runProviderAction($){let Y=$.action==="listProviders"?{listProviders:{}}:$.action==="getProviderModels"?{getProviderModels:{providerId:$.providerId}}:$.action==="addProvider"?{addProvider:{providerId:$.providerId,name:$.name,baseUrl:$.baseUrl,apiKey:$.apiKey??"",headers:$.headers??{},timeoutMs:$.timeoutMs??0,hasTimeoutMs:typeof $.timeoutMs==="number",models:$.models??[],defaultModelId:$.defaultModelId??"",modelsSourceUrl:$.modelsSourceUrl??"",capabilities:$.capabilities??[]}}:$.action==="saveProviderSettings"?{saveProviderSettings:{providerId:$.providerId,enabled:$.enabled??!1,hasEnabled:typeof $.enabled==="boolean",apiKey:$.apiKey??"",hasApiKey:$.apiKey!==void 0,baseUrl:$.baseUrl??"",hasBaseUrl:$.baseUrl!==void 0}}:{clineAccount:{operation:$.operation,userId:"userId"in $?$.userId??"":"",organizationId:"organizationId"in $?$.organizationId??"":"",memberId:"memberId"in $?$.memberId??"":"",clearOrganizationId:"organizationId"in $&&$.organizationId===null}},T=await this.unary((q)=>{this.client.RunProviderAction({request:Y},q)});return{result:UY(T.result)}}async runProviderOAuthLogin($){let Y=await this.unary((T)=>{this.client.RunProviderOAuthLogin({provider:$},T)});return{provider:Y.provider??"",accessToken:Y.apiKey??""}}async publishEvent($){let Y=await this.unary((T)=>{this.client.PublishEvent({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId,eventType:$.eventType,payload:Q1($.payload),sourceClientId:$.sourceClientId},T)});return{eventId:Y.eventId??"",accepted:Y.accepted===!0}}streamEvents($,Y={}){let T=!1,q=this.client.StreamEvents({clientId:$.clientId??"",sessionIds:$.sessionIds??[]}),X=(U)=>{Y.onEvent?.({eventId:U.eventId??"",sessionId:U.sessionId??"",taskId:U.taskId?.trim()?U.taskId:void 0,eventType:U.eventType??"",payload:f0(U.payload)??{},sourceClientId:U.sourceClientId?.trim()?U.sourceClientId:void 0,ts:U.ts??""})},J=(U)=>{let Z=(typeof U.code==="number"?Number(U.code):void 0)===1||U.message.includes("CANCELLED");if(T&&Z)return;Y.onError?.(U)},Q=()=>{Y.onEnd?.()};return q.on("data",X),q.on("error",J),q.on("end",Q),()=>{T=!0,q.cancel()}}streamTeamProgress($,Y={}){return this.streamEvents($,{onEvent:(T)=>{if(T.eventType===kT){try{let q=T.payload;if(q.type==="team_progress_projection"&&q.version===1)Y.onProjection?.(q)}catch{}return}if(T.eventType===hT)try{Y.onLifecycle?.(T.payload)}catch{}},onError:Y.onError,onEnd:Y.onEnd})}async unary($){return await new Promise((Y,T)=>{$((q,X)=>{if(q){T(q);return}Y(X??{})})})}}var dy="127.0.0.1:4317",cy="cline.rpc.v1",m3="ClineGateway";function py(){return k3(import.meta.url)}function ly(){let $=g3.loadSync(py(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),Y=_3.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!Y)throw Error(`Unable to load ${cy}.${m3} from proto`);return Y}function q6(){return new Date().toISOString()}function N($){return typeof $==="string"?$:""}function ny($){if(!$||typeof $!=="object")return{};let Y={};for(let[T,q]of Object.entries($)){let X=T.trim();if(!X)continue;let J=N(q).trim();if(!J)continue;Y[X]=J}return Y}function iy($){if(!Array.isArray($)||$.length===0)return;let Y=new Set;for(let T of $){let q=T.trim();if(q)Y.add(q)}return Y.size>0?Y:void 0}function f3($){if($==="running"||$==="completed"||$==="failed"||$==="cancelled")return $;return"running"}function y3($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??"",exitCode:$.exitCode??0,status:$.status,statusLock:$.statusLock,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??"",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??"",parentAgentId:$.parentAgentId??"",agentId:$.agentId??"",conversationId:$.conversationId??"",isSubagent:$.isSubagent,prompt:$.prompt??"",transcriptPath:$.transcriptPath,hookPath:$.hookPath,messagesPath:$.messagesPath??"",updatedAt:$.updatedAt,metadata:Q1($.metadata)}}function ry($){let Y=N($.sessionId).trim(),T=N($.source).trim(),q=N($.startedAt).trim(),X=N($.provider).trim(),J=N($.model).trim(),Q=N($.cwd).trim(),U=N($.workspaceRoot).trim(),Z=N($.transcriptPath).trim(),K=N($.hookPath).trim();if(!Y||!T||!q||!X||!J||!Q||!U||!Z||!K)throw Error("session record is missing required fields");return{sessionId:Y,source:T,pid:Number($.pid??0),startedAt:q,endedAt:N($.endedAt).trim()||null,exitCode:typeof $.exitCode==="number"?Math.floor($.exitCode):null,status:f3(N($.status).trim()),statusLock:typeof $.statusLock==="number"?Math.floor($.statusLock):0,interactive:$.interactive===!0,provider:X,model:J,cwd:Q,workspaceRoot:U,teamName:N($.teamName).trim()||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:N($.parentSessionId).trim()||void 0,parentAgentId:N($.parentAgentId).trim()||void 0,agentId:N($.agentId).trim()||void 0,conversationId:N($.conversationId).trim()||void 0,isSubagent:$.isSubagent===!0,prompt:N($.prompt).trim()||void 0,metadata:f0($.metadata),transcriptPath:Z,hookPath:K,messagesPath:N($.messagesPath).trim()||void 0,updatedAt:N($.updatedAt).trim()||q6()}}function vJ($){let Y=N($).trim();if(!Y)return;try{let T=JSON.parse(Y);if(!Array.isArray(T))return;let q=T.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return q.length>0?q:void 0}catch{return}}function T6($){return{scheduleId:$.scheduleId,name:$.name,cronPattern:$.cronPattern,prompt:$.prompt,provider:$.provider,model:$.model,mode:$.mode,workspaceRoot:$.workspaceRoot??"",cwd:$.cwd??"",systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",timeoutSeconds:$.timeoutSeconds??0,hasTimeoutSeconds:typeof $.timeoutSeconds==="number",maxParallel:$.maxParallel,enabled:$.enabled,createdAt:$.createdAt,updatedAt:$.updatedAt,lastRunAt:$.lastRunAt??"",nextRunAt:$.nextRunAt??"",createdBy:$.createdBy??"",tagsJson:$.tags?JSON.stringify($.tags):"",metadata:Q1($.metadata)}}function xJ($){return{executionId:$.executionId,scheduleId:$.scheduleId,sessionId:$.sessionId??"",triggeredAt:$.triggeredAt,startedAt:$.startedAt??"",endedAt:$.endedAt??"",status:$.status,exitCode:$.exitCode??0,hasExitCode:typeof $.exitCode==="number",errorMessage:$.errorMessage??"",iterations:$.iterations??0,hasIterations:typeof $.iterations==="number",tokensUsed:$.tokensUsed??0,hasTokensUsed:typeof $.tokensUsed==="number",costUsd:$.costUsd??0,hasCostUsd:typeof $.costUsd==="number"}}function ay($){return new(G9.makeGenericClientConstructor(ly(),m3))($,G9.credentials.createInsecure())}async function b3($){return await new Promise((Y)=>{let T;try{T=ay($)}catch{Y(void 0);return}T.Health({},(q,X)=>{if(T?.close(),q||!X){Y(void 0);return}Y(X)})})}var sy=300000;class u3{publishEvent;approvals=new Map;constructor($){this.publishEvent=$}async requestToolApproval($){let Y=N($.sessionId).trim(),T=N($.toolCallId).trim(),q=N($.toolName).trim();if(!Y||!T||!q)throw Error("sessionId, toolCallId, and toolName are required");let X=N($.approvalId).trim()||`apr_${oy()}`;if(!this.approvals.get(X)){let Z={approvalId:X,sessionId:Y,taskId:N($.taskId).trim()||void 0,toolCallId:T,toolName:q,inputJson:N($.inputJson),requesterClientId:N($.requesterClientId).trim()||void 0,createdAt:q6(),status:"pending",waiters:[]};this.approvals.set(X,Z),this.publishEvent({eventId:"",sessionId:Y,taskId:Z.taskId,eventType:"approval.requested",payload:Q1(Z),sourceClientId:Z.requesterClientId})}let J=this.approvals.get(X);if(!J)throw Error("approval state not found");if(J.status==="approved"||J.status==="rejected")return{approvalId:X,decided:!0,approved:J.status==="approved",reason:J.reason??""};let Q=typeof $.timeoutMs==="number"&&$.timeoutMs>0?Math.floor($.timeoutMs):sy,U=await new Promise((Z)=>{let K=setTimeout(()=>{Z({decided:!1,approved:!1,reason:"Tool approval request timed out"})},Q);J.waiters.push((A)=>{clearTimeout(K),Z(A)})});return{approvalId:X,decided:U.decided,approved:U.approved,reason:U.reason??""}}respondToolApproval($){let Y=N($.approvalId).trim();if(!Y)throw Error("approvalId is required");let T=this.approvals.get(Y);if(!T)return{approvalId:Y,applied:!1};T.status=$.approved===!0?"approved":"rejected",T.reason=N($.reason).trim()||void 0;let q={decided:!0,approved:T.status==="approved",reason:T.reason};for(let X of T.waiters.splice(0))X(q);return this.publishEvent({eventId:"",sessionId:T.sessionId,taskId:T.taskId,eventType:"approval.decided",payload:Q1({approvalId:Y,approved:q.approved,reason:q.reason??"",responderClientId:N($.responderClientId).trim()||""}),sourceClientId:N($.responderClientId).trim()||""}),{approvalId:Y,applied:!0}}listPendingApprovals($){let Y=N($.sessionId).trim(),T=[];for(let q of this.approvals.values()){if(q.status!=="pending")continue;if(Y&&q.sessionId!==Y)continue;T.push({approvalId:q.approvalId,sessionId:q.sessionId,taskId:q.taskId??"",toolCallId:q.toolCallId,toolName:q.toolName,inputJson:q.inputJson,requesterClientId:q.requesterClientId??"",createdAt:q.createdAt})}return T.sort((q,X)=>(q.createdAt??"").localeCompare(X.createdAt??"")),{approvals:T}}}class d3{subscribers=new Map;nextSubscriberId=1;publishEvent($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T={eventId:N($.eventId).trim()||`evt_${v3()}`,sessionId:Y,taskId:N($.taskId).trim()||void 0,eventType:N($.eventType).trim()||"unknown",payload:f0($.payload)??{},sourceClientId:N($.sourceClientId).trim()||void 0,ts:q6()};return this.dispatchEvent(T),{eventId:T.eventId,accepted:!0}}addSubscriber($){let Y=$.request,T=iy(Y.sessionIds),q=this.nextSubscriberId;return this.nextSubscriberId+=1,this.subscribers.set(q,{call:$,filterSessionIds:T}),$.on("cancelled",()=>{this.subscribers.delete(q)}),$.on("close",()=>{this.subscribers.delete(q)}),q}removeSubscriber($){this.subscribers.delete($)}broadcastServerEvent($,Y){let T=`evt_${v3()}`,q=q6();for(let X of this.subscribers.values())X.call.write({eventId:T,sessionId:"__rpc__",taskId:"",eventType:$,payload:Q1(Y),sourceClientId:"rpc-server",ts:q})}dispatchEvent($){for(let Y of this.subscribers.values()){if(Y.filterSessionIds&&!Y.filterSessionIds.has($.sessionId))continue;Y.call.write({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId??"",eventType:$.eventType,payload:Q1($.payload),sourceClientId:$.sourceClientId??"",ts:$.ts})}}}class c3{scheduler;constructor($){this.scheduler=$}createSchedule($){let Y=this.requireScheduler(),T={name:N($.name).trim(),cronPattern:N($.cronPattern).trim(),prompt:N($.prompt),provider:N($.provider).trim(),model:N($.model).trim(),mode:N($.mode).trim()==="plan"?"plan":"act",workspaceRoot:N($.workspaceRoot).trim()||void 0,cwd:N($.cwd).trim()||void 0,systemPrompt:N($.systemPrompt)||void 0,maxIterations:$.hasMaxIterations?Math.floor($.maxIterations??0):void 0,timeoutSeconds:$.hasTimeoutSeconds?Math.floor($.timeoutSeconds??0):void 0,maxParallel:typeof $.maxParallel==="number"&&$.maxParallel>0?Math.floor($.maxParallel):1,enabled:$.enabled!==!1,createdBy:N($.createdBy).trim()||void 0,tags:vJ(N($.tagsJson)),metadata:f0($.metadata)};if(!T.name||!T.cronPattern||!T.prompt.trim()||!T.provider||!T.model)throw Error("name, cronPattern, prompt, provider, and model are required");let q=Y.createSchedule(T);return{schedule:T6(q)}}getSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.getSchedule(T);return q?{schedule:T6(q)}:{}}listSchedules($){return{schedules:this.requireScheduler().listSchedules({enabled:$.hasEnabled?$.enabled===!0:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0,tags:vJ(N($.tagsJson))}).map((Y)=>T6(Y))}}updateSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q={};if($.hasName)q.name=N($.name);if($.hasCronPattern)q.cronPattern=N($.cronPattern);if($.hasPrompt)q.prompt=N($.prompt);if($.hasProvider)q.provider=N($.provider);if($.hasModel)q.model=N($.model);if($.hasMode)q.mode=N($.mode).trim()==="plan"?"plan":"act";if($.hasWorkspaceRoot)q.workspaceRoot=N($.workspaceRoot);if($.hasCwd)q.cwd=N($.cwd);if($.hasSystemPrompt)q.systemPrompt=N($.systemPrompt);if($.clearMaxIterations)q.maxIterations=null;else if($.hasMaxIterations)q.maxIterations=Math.floor($.maxIterations??0);if($.clearTimeoutSeconds)q.timeoutSeconds=null;else if($.hasTimeoutSeconds)q.timeoutSeconds=Math.floor($.timeoutSeconds??0);if($.hasMaxParallel)q.maxParallel=Math.floor($.maxParallel??1);if($.hasEnabled)q.enabled=$.enabled===!0;if($.clearCreatedBy)q.createdBy=null;else if($.hasCreatedBy)q.createdBy=N($.createdBy);if($.hasTagsJson)q.tags=vJ(N($.tagsJson))??[];if($.hasMetadata)q.metadata=f0($.metadata)??{};let X=Y.updateSchedule(T,q);return{updated:X!==void 0,schedule:X?T6(X):void 0}}deleteSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");return{deleted:Y.deleteSchedule(T)}}pauseSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.pauseSchedule(T);return{updated:q!==void 0,schedule:q?T6(q):void 0}}resumeSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.resumeSchedule(T);return{updated:q!==void 0,schedule:q?T6(q):void 0}}async triggerScheduleNow($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=await Y.triggerScheduleNow(T);return q?{execution:xJ(q)}:{}}listScheduleExecutions($){let Y=this.requireScheduler(),T=N($.scheduleId).trim()||void 0,q=N($.status).trim()||void 0;return{executions:Y.listScheduleExecutions({scheduleId:T,status:q==="pending"||q==="running"||q==="success"||q==="failed"||q==="timeout"||q==="aborted"?q:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0}).map((X)=>xJ(X))}}getScheduleStats($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.getScheduleStats(T);return{totalRuns:q.totalRuns,successRate:q.successRate,avgDurationSeconds:q.avgDurationSeconds,lastFailure:q.lastFailure?xJ(q.lastFailure):void 0}}getActiveScheduledExecutions($){return{executions:this.requireScheduler().getActiveExecutions().map((Y)=>({executionId:Y.executionId,scheduleId:Y.scheduleId,sessionId:Y.sessionId,startedAt:Y.startedAt,timeoutAt:Y.timeoutAt??""}))}}getUpcomingScheduledRuns($){let Y=this.requireScheduler(),T=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):20;return{runs:Y.getUpcomingRuns(T).map((q)=>({scheduleId:q.scheduleId,name:q.name,nextRunAt:q.nextRunAt}))}}requireScheduler(){if(!this.scheduler)throw Error("scheduler service is not configured");return this.scheduler}}class ty{serverId=j3();address;startedAt;runtimeHandlers;sessions=new Map;tasks=new Map;clients=new Map;store;eventService=new d3;approvalService=new u3(($)=>this.eventService.publishEvent($));scheduleService;constructor($,Y,T,q){this.address=$,this.startedAt=q6(),this.store=Y,this.runtimeHandlers=T,this.scheduleService=new c3(q),this.store.init()}health(){return{serverId:this.serverId,address:this.address,running:!0,startedAt:this.startedAt}}registerClient($){let Y=N($.clientId).trim()||`client_${j3()}`,T=N($.clientType).trim()||void 0,q=ny($),X=q6(),J=this.clients.get(Y),Q=J?{...J,clientType:T??J.clientType,metadata:Object.keys(q).length>0?{...J.metadata??{},...q}:J.metadata,lastRegisteredAt:X,activationCount:J.activationCount+1}:{clientId:Y,clientType:T,metadata:Object.keys(q).length>0?q:void 0,firstRegisteredAt:X,lastRegisteredAt:X,activationCount:1};return this.clients.set(Y,Q),this.broadcastServerEvent("rpc.client.activated",{clientId:Q.clientId,clientType:Q.clientType,metadata:Q.metadata??{},firstRegisteredAt:Q.firstRegisteredAt,lastRegisteredAt:Q.lastRegisteredAt,activationCount:Q.activationCount}),{clientId:Y,registered:!0}}ensureSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.sessions.get(Y);if(T)return T.status=N($.status).trim()||T.status,T.workspaceRoot=N($.workspaceRoot).trim()||T.workspaceRoot,T.clientId=N($.clientId).trim()||T.clientId,T.metadata=f0($.metadata)??T.metadata,{sessionId:Y,created:!1,status:T.status};let q=N($.status).trim()||"running";return this.sessions.set(Y,{sessionId:Y,status:q,workspaceRoot:N($.workspaceRoot).trim()||void 0,clientId:N($.clientId).trim()||void 0,metadata:f0($.metadata)}),{sessionId:Y,created:!0,status:q}}upsertSession($){if(!$.session)throw Error("session is required");return this.store.upsertSession(ry($.session)),{persisted:!0}}getSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.store.getSession(Y);if(!T)return{};return{session:y3(T)}}listSessions($){let Y=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):200;return{sessions:this.store.listSessions({limit:Y,parentSessionId:N($.parentSessionId).trim()||void 0,status:N($.status).trim()||void 0}).map((T)=>y3(T))}}updateSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");return this.store.updateSession({sessionId:Y,status:$.status?f3($.status):void 0,endedAt:$.endedAt?$.endedAt:void 0,exitCode:$.hasExitCode?$.exitCode??null:void 0,prompt:$.hasPrompt?$.prompt??null:void 0,metadata:$.hasMetadata?f0($.metadata)??null:void 0,parentSessionId:$.hasParentSessionId?$.parentSessionId??null:void 0,parentAgentId:$.hasParentAgentId?$.parentAgentId??null:void 0,agentId:$.hasAgentId?$.agentId??null:void 0,conversationId:$.hasConversationId?$.conversationId??null:void 0,expectedStatusLock:$.hasExpectedStatusLock?$.expectedStatusLock:void 0,setRunning:$.setRunning===!0})}deleteSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.store.deleteSession(Y);if($.cascade===!0)this.store.deleteSessionsByParent(Y);return{deleted:T}}enqueueSpawnRequest($){let Y=N($.rootSessionId).trim(),T=N($.parentAgentId).trim();if(!Y||!T)throw Error("rootSessionId and parentAgentId are required");return this.store.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:T,task:N($.task).trim()||void 0,systemPrompt:N($.systemPrompt).trim()||void 0}),{enqueued:!0}}claimSpawnRequest($){let Y=N($.rootSessionId).trim(),T=N($.parentAgentId).trim();if(!Y||!T)throw Error("rootSessionId and parentAgentId are required");let q=this.store.claimSpawnRequest(Y,T);if(!q)return{};return{item:{id:String(q.id),rootSessionId:q.rootSessionId,parentAgentId:q.parentAgentId,task:q.task??"",systemPrompt:q.systemPrompt??"",createdAt:q.createdAt,consumedAt:q.consumedAt??""}}}async startRuntimeSession($){let Y=this.runtimeHandlers?.startSession;if(!Y)throw Error("runtime start handler is not configured");let T=$.request?{sessionId:N($.request.sessionId),workspaceRoot:N($.request.workspaceRoot),cwd:N($.request.cwd),provider:N($.request.provider),model:N($.request.model),mode:N($.request.mode),apiKey:N($.request.apiKey),systemPrompt:N($.request.systemPrompt),maxIterations:$.request.hasMaxIterations?$.request.maxIterations:void 0,enableTools:$.request.enableTools===!0,enableSpawn:$.request.enableSpawn===!0,enableTeams:$.request.enableTeams===!0,autoApproveTools:$.request.hasAutoApproveTools?$.request.autoApproveTools===!0:void 0,teamName:N($.request.teamName),missionStepInterval:$.request.missionStepInterval??3,missionTimeIntervalMs:$.request.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.initialMessages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),logger:$.request.logger?{enabled:$.request.logger.enabled===!0,level:N($.request.logger.level),destination:N($.request.logger.destination),name:N($.request.logger.name),bindings:f0($.request.logger.bindings)}:void 0}:void 0;if(!T)throw Error("runtime start request is required");let q=await Y(T),X=N(q.sessionId).trim();if(!X)throw Error("runtime start handler returned empty sessionId");return{sessionId:X,startResult:q.startResult?{sessionId:N(q.startResult.sessionId),manifestPath:N(q.startResult.manifestPath),transcriptPath:N(q.startResult.transcriptPath),hookPath:N(q.startResult.hookPath),messagesPath:N(q.startResult.messagesPath)}:void 0}}async sendRuntimeSession($){let Y=this.runtimeHandlers?.sendSession;if(!Y)throw Error("runtime send handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");let q=$.request?{config:{workspaceRoot:N($.request.config?.workspaceRoot),cwd:N($.request.config?.cwd),provider:N($.request.config?.provider),model:N($.request.config?.model),mode:N($.request.config?.mode),apiKey:N($.request.config?.apiKey),systemPrompt:N($.request.config?.systemPrompt),maxIterations:$.request.config?.hasMaxIterations?$.request.config?.maxIterations:void 0,enableTools:$.request.config?.enableTools===!0,enableSpawn:$.request.config?.enableSpawn===!0,enableTeams:$.request.config?.enableTeams===!0,autoApproveTools:$.request.config?.hasAutoApproveTools?$.request.config?.autoApproveTools===!0:void 0,teamName:N($.request.config?.teamName),missionStepInterval:$.request.config?.missionStepInterval??3,missionTimeIntervalMs:$.request.config?.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.config?.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.config?.initialMessages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),logger:$.request.config?.logger?{enabled:$.request.config.logger.enabled===!0,level:N($.request.config.logger.level),destination:N($.request.config.logger.destination),name:N($.request.config.logger.name),bindings:f0($.request.config.logger.bindings)}:void 0},messages:($.request.messages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),prompt:N($.request.prompt),attachments:$.request.attachments?{userImages:$.request.attachments.userImages??[],userFiles:($.request.attachments.userFiles??[]).map((J)=>({name:N(J.name),content:N(J.content)}))}:void 0}:void 0;if(!q)throw Error("runtime send request is required");let X=await Y(T,q);return{result:{text:N(X.result.text),usage:{inputTokens:X.result.usage.inputTokens,outputTokens:X.result.usage.outputTokens,cacheReadTokens:X.result.usage.cacheReadTokens??0,hasCacheReadTokens:typeof X.result.usage.cacheReadTokens==="number",cacheWriteTokens:X.result.usage.cacheWriteTokens??0,hasCacheWriteTokens:typeof X.result.usage.cacheWriteTokens==="number",totalCost:X.result.usage.totalCost??0,hasTotalCost:typeof X.result.usage.totalCost==="number"},inputTokens:X.result.inputTokens,outputTokens:X.result.outputTokens,iterations:X.result.iterations,finishReason:N(X.result.finishReason),messages:(X.result.messages??[]).map((J)=>({role:N(J.role),content:QY(J.content)})),toolCalls:(X.result.toolCalls??[]).map((J)=>({name:N(J.name),input:QY(J.input),hasInput:J.input!==void 0,output:QY(J.output),hasOutput:J.output!==void 0,error:N(J.error),durationMs:J.durationMs??0,hasDurationMs:typeof J.durationMs==="number"}))}}}async stopRuntimeSession($){let Y=this.runtimeHandlers?.stopSession;if(!Y)throw Error("runtime stop handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");return{applied:(await Y(T)).applied===!0}}async abortRuntimeSession($){let Y=this.runtimeHandlers?.abortSession;if(!Y)throw Error("runtime abort handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");return{applied:(await Y(T)).applied===!0}}async runProviderAction($){let Y=this.runtimeHandlers?.runProviderAction;if(!Y)throw Error("provider action handler is not configured");if(!$.request)throw Error("provider action request is required");let T;if($.request.listProviders)T={action:"listProviders"};else if($.request.getProviderModels)T={action:"getProviderModels",providerId:N($.request.getProviderModels.providerId)};else if($.request.addProvider)T={action:"addProvider",providerId:N($.request.addProvider.providerId),name:N($.request.addProvider.name),baseUrl:N($.request.addProvider.baseUrl),apiKey:N($.request.addProvider.apiKey)||void 0,headers:$.request.addProvider.headers??void 0,timeoutMs:$.request.addProvider.hasTimeoutMs?$.request.addProvider.timeoutMs:void 0,models:$.request.addProvider.models??void 0,defaultModelId:N($.request.addProvider.defaultModelId)||void 0,modelsSourceUrl:N($.request.addProvider.modelsSourceUrl)||void 0,capabilities:$.request.addProvider.capabilities};else if($.request.saveProviderSettings)T={action:"saveProviderSettings",providerId:N($.request.saveProviderSettings.providerId),enabled:$.request.saveProviderSettings.hasEnabled?$.request.saveProviderSettings.enabled:void 0,apiKey:$.request.saveProviderSettings.hasApiKey?$.request.saveProviderSettings.apiKey:void 0,baseUrl:$.request.saveProviderSettings.hasBaseUrl?$.request.saveProviderSettings.baseUrl:void 0};else{let X=N($.request.clineAccount?.operation);if(X==="fetchMe")T={action:"clineAccount",operation:"fetchMe"};else if(X==="fetchBalance")T={action:"clineAccount",operation:"fetchBalance",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchUsageTransactions")T={action:"clineAccount",operation:"fetchUsageTransactions",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchPaymentTransactions")T={action:"clineAccount",operation:"fetchPaymentTransactions",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchUserOrganizations")T={action:"clineAccount",operation:"fetchUserOrganizations"};else if(X==="fetchOrganizationBalance")T={action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:N($.request.clineAccount?.organizationId)};else if(X==="fetchOrganizationUsageTransactions")T={action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:N($.request.clineAccount?.organizationId),memberId:N($.request.clineAccount?.memberId)||void 0};else T={action:"clineAccount",operation:"switchAccount",organizationId:$.request.clineAccount?.clearOrganizationId?null:N($.request.clineAccount?.organizationId)||void 0}}let q=await Y(T);return{result:QY(q.result)}}async runProviderOAuthLogin($){let Y=this.runtimeHandlers?.runProviderOAuthLogin;if(!Y)throw Error("provider oauth handler is not configured");let T=N($.provider).trim();if(!T)throw Error("provider is required");let q=await Y(T);return{provider:N(q.provider).trim(),apiKey:N(q.accessToken)}}startTask($){let Y=N($.sessionId).trim(),T=N($.taskId).trim();if(!Y||!T)throw Error("sessionId and taskId are required");let q=`${Y}:${T}`;return this.tasks.set(q,{sessionId:Y,taskId:T,title:N($.title).trim()||void 0,status:"running",payload:f0($.payload)??void 0}),this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:T,eventType:"task.started",payload:f0($.payload)??{},sourceClientId:""}),{sessionId:Y,taskId:T,status:"running",updated:!0}}completeTask($){let Y=N($.sessionId).trim(),T=N($.taskId).trim();if(!Y||!T)throw Error("sessionId and taskId are required");let q=`${Y}:${T}`,X=N($.status).trim()||"completed",J=this.tasks.get(q);if(!J)return{sessionId:Y,taskId:T,status:X,updated:!1};return J.status=X,J.result=f0($.result)??void 0,this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:T,eventType:"task.completed",payload:f0($.result)??{},sourceClientId:""}),{sessionId:Y,taskId:T,status:X,updated:!0}}publishEvent($){return this.eventService.publishEvent($)}addSubscriber($){return this.eventService.addSubscriber($)}removeSubscriber($){this.eventService.removeSubscriber($)}requestToolApproval($){return this.approvalService.requestToolApproval($)}respondToolApproval($){return this.approvalService.respondToolApproval($)}listPendingApprovals($){return this.approvalService.listPendingApprovals($)}createSchedule($){return this.scheduleService.createSchedule($)}getSchedule($){return this.scheduleService.getSchedule($)}listSchedules($){return this.scheduleService.listSchedules($)}updateSchedule($){return this.scheduleService.updateSchedule($)}deleteSchedule($){return this.scheduleService.deleteSchedule($)}pauseSchedule($){return this.scheduleService.pauseSchedule($)}resumeSchedule($){return this.scheduleService.resumeSchedule($)}triggerScheduleNow($){return this.scheduleService.triggerScheduleNow($)}listScheduleExecutions($){return this.scheduleService.listScheduleExecutions($)}getScheduleStats($){return this.scheduleService.getScheduleStats($)}getActiveScheduledExecutions($){return this.scheduleService.getActiveScheduledExecutions($)}getUpcomingScheduledRuns($){return this.scheduleService.getUpcomingScheduledRuns($)}broadcastServerEvent($,Y){this.eventService.broadcastServerEvent($,Y)}}function p3(){return dy}import{appendFileSync as l3,existsSync as $j,readFileSync as Yj,writeFileSync as BT}from"node:fs";import{nanoid as Tj}from"nanoid";import{z as mJ}from"zod";import{nanoid as ey}from"nanoid";function MT($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function E9($,Y){let T=MT($),q=MT(Y),X=`${T}__${q}`;return X.length>180?X.slice(0,180):X}function _J($,Y){let T=MT($),q=MT(Y);return`${T}__teamtask__${q}__${ey(6)}`}function gJ($){switch($.hookName){case"agent_end":return"completed";case"session_shutdown":{let Y=String($.reason??"").toLowerCase();if(Y.includes("cancel")||Y.includes("abort")||Y.includes("interrupt"))return"cancelled";if(Y.includes("fail")||Y.includes("error"))return"failed";return"completed"}default:return"running"}}var n3="cli_subagent",qj=mJ.object({task:mJ.string().optional(),systemPrompt:mJ.string().optional()}).passthrough();function fJ($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function bJ($){let Y=$?.trim();return Y?Y.slice(0,120):void 0}function RT($){if(!$)return;let Y={...$};return delete Y.title,Object.keys(Y).length>0?Y:void 0}class OT{adapter;teamTaskSessionsByAgent=new Map;artifacts;constructor($){this.adapter=$;this.artifacts=new x4(()=>this.ensureSessionsDir())}teamTaskQueueKey($,Y){return`${$}::${Y}`}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}sessionTranscriptPath($){return this.artifacts.sessionTranscriptPath($)}sessionHookPath($){return this.artifacts.sessionHookPath($)}sessionMessagesPath($){return this.artifacts.sessionMessagesPath($)}sessionManifestPath($,Y=!0){return this.artifacts.sessionManifestPath($,Y)}async sessionPathFromStore($,Y){let q=(await this.adapter.getSession($))?.[Y];return typeof q==="string"&&q.trim().length>0?q:void 0}activeTeamTaskSessionId($,Y){let T=this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,Y));if(!T||T.length===0)return;return T[T.length-1]}subagentArtifactPaths($,Y,T,q){return this.artifacts.subagentArtifactPaths(Y,q,this.activeTeamTaskSessionId($,T))}writeSessionManifestFile($,Y){let T=IY.parse(Y);BT($,`${JSON.stringify(T,null,2)}
|
|
580
|
+
`,"utf8")}readSessionManifestFile($){let Y=this.sessionManifestPath($,!1);if(!$j(Y))return{path:Y};try{let T=IY.parse(JSON.parse(Yj(Y,"utf8")));return{path:Y,manifest:T}}catch{return{path:Y}}}applyResolvedTitleToRow($){let Y=typeof $.metadata_json==="string"&&$.metadata_json.trim().length>0?(()=>{try{let Q=JSON.parse($.metadata_json);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})():void 0,T=RT(Y),{manifest:q}=this.readSessionManifestFile($.session_id),X=bJ(typeof q?.metadata?.title==="string"?q.metadata.title:void 0),J=X?{...T??{},title:X}:T;return{...$,metadata_json:fJ(J)}}createRootSessionId(){return`${Date.now()}_${Tj(5)}`}async createRootSessionWithArtifacts($){let Y=$.startedAt??W0(),T=$.sessionId.trim(),q=T.length>0?T:this.createRootSessionId(),X=this.sessionTranscriptPath(q),J=this.sessionHookPath(q),Q=this.sessionMessagesPath(q),U=this.sessionManifestPath(q),Z=IY.parse({version:1,session_id:q,source:$.source,pid:$.pid,started_at:Y,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:$.metadata,messages_path:Q}),K=RT(Z.metadata);return await this.adapter.upsertSession({session_id:q,source:$.source,pid:$.pid,started_at:Y,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:$.interactive?1:0,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??null,enable_tools:$.enableTools?1:0,enable_spawn:$.enableSpawn?1:0,enable_teams:$.enableTeams?1:0,parent_session_id:null,parent_agent_id:null,agent_id:null,conversation_id:null,is_subagent:0,prompt:Z.prompt??null,metadata_json:fJ(K),transcript_path:X,hook_path:J,messages_path:Q,updated_at:W0()}),BT(Q,`${JSON.stringify({version:1,updated_at:Y,messages:[]},null,2)}
|
|
581
|
+
`,"utf8"),this.writeSessionManifestFile(U,Z),{manifestPath:U,transcriptPath:X,hookPath:J,messagesPath:Q,manifest:Z}}writeSessionManifest($,Y){this.writeSessionManifestFile($,Y)}async updateSessionStatus($,Y,T){for(let q=0;q<4;q++){let X=await this.adapter.getSession($);if(!X||typeof X.status_lock!=="number")return{updated:!1};let J=W0();if((await this.adapter.updateSession({sessionId:$,status:Y,endedAt:J,exitCode:typeof T==="number"?T:null,expectedStatusLock:X.status_lock})).updated){if(Y==="cancelled")await this.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:J}}}return{updated:!1}}async updateSession($){for(let Y=0;Y<4;Y++){let T=await this.adapter.getSession($.sessionId);if(!T||typeof T.status_lock!=="number")return{updated:!1};let q=$.metadata===void 0?void 0:RT($.metadata);if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadataJson:$.metadata===void 0?void 0:fJ(q),title:$.title,expectedStatusLock:T.status_lock})).updated)continue;let{path:J,manifest:Q}=this.readSessionManifestFile($.sessionId);if(Q){if($.prompt!==void 0)Q.prompt=$.prompt??void 0;let U=bJ(typeof Q.metadata?.title==="string"?Q.metadata.title:void 0),Z=$.title!==void 0?bJ($.title):U,K=$.metadata!==void 0?{...RT($.metadata)??{}}:{...RT(Q.metadata)??{}};if(Z)K.title=Z;Q.metadata=Object.keys(K).length>0?K:void 0,this.writeSessionManifestFile(J,Q)}return{updated:!0}}return{updated:!1}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let Y=_T($.sessionContext);if(!Y)return;let T=qj.safeParse($.tool_call.input),q=T.success?T.data.task:void 0,X=T.success?T.data.systemPrompt:void 0;await this.adapter.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:$.agent_id,task:q,systemPrompt:X})}async readRootSession($){return await this.adapter.getSession($)??null}async claimQueuedSpawnTask($,Y){return await this.adapter.claimSpawnRequest($,Y)}async upsertSubagentSession($){let Y=$.rootSessionId;if(!Y)return;let T=await this.readRootSession(Y);if(!T)return;let q=E9(Y,$.agentId),X=await this.adapter.getSession(q),J=W0(),Q=this.subagentArtifactPaths(Y,q,$.parentAgentId,$.agentId),U=$.prompt??X?.prompt??void 0;if(!U)U=await this.claimQueuedSpawnTask(Y,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!X)return await this.adapter.upsertSession({session_id:q,source:n3,pid:process.ppid,started_at:J,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:T.provider,model:T.model,cwd:T.cwd,workspace_root:T.workspace_root,team_name:T.team_name??null,enable_tools:T.enable_tools,enable_spawn:T.enable_spawn,enable_teams:T.enable_teams,parent_session_id:Y,parent_agent_id:$.parentAgentId,agent_id:$.agentId,conversation_id:$.conversationId,is_subagent:1,prompt:U,metadata_json:null,transcript_path:Q.transcriptPath,hook_path:Q.hookPath,messages_path:Q.messagesPath,updated_at:J}),BT(Q.messagesPath,`${JSON.stringify({version:1,updated_at:J,messages:[]},null,2)}
|
|
582
|
+
`,"utf8"),q;return await this.adapter.updateSession({sessionId:q,setRunning:!0,parentSessionId:Y,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X.prompt??U??null,expectedStatusLock:X.status_lock}),q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let Y=_T($.sessionContext);if(!Y)return;if($.hookName==="session_shutdown"){let T=E9(Y,$.agent_id);return await this.adapter.getSession(T)?T:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:Y})}async appendSubagentHookAudit($,Y){let T=`${JSON.stringify({ts:W0(),...Y})}
|
|
583
|
+
`,q=await this.sessionPathFromStore($,"hook_path")??this.sessionHookPath($);l3(q,T,"utf8")}async appendSubagentTranscriptLine($,Y){if(!Y.trim())return;let T=await this.sessionPathFromStore($,"transcript_path")??this.sessionTranscriptPath($);l3(T,`${Y}
|
|
584
|
+
`,"utf8")}async persistSessionMessages($,Y,T){let q=await this.sessionPathFromStore($,"messages_path")??this.sessionMessagesPath($),X={version:1,updated_at:W0(),messages:Y};if(T!==void 0&&T!=="")X.systemPrompt=T;BT(q,`${JSON.stringify(X,null,2)}
|
|
585
|
+
`,"utf8")}async applySubagentStatus($,Y){await this.applySubagentStatusBySessionId($,gJ(Y))}async applySubagentStatusBySessionId($,Y){let T=await this.adapter.getSession($);if(!T||typeof T.status_lock!=="number")return;let q=W0(),X=Y==="running"?null:q,J=Y==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:Y,endedAt:X,exitCode:Y==="running"?null:J,expectedStatusLock:T.status_lock})}async applyStatusToRunningChildSessions($,Y){if(!$)return;let T=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let q of T)await this.applySubagentStatusBySessionId(q.session_id,Y)}async createTeamTaskSubSession($,Y,T){let q=await this.readRootSession($);if(!q)return;let X=_J($,Y),J=W0(),Q=this.sessionTranscriptPath(X),U=this.sessionHookPath(X),Z=this.sessionMessagesPath(X);return await this.adapter.upsertSession({session_id:X,source:n3,pid:process.ppid,started_at:J,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:q.provider,model:q.model,cwd:q.cwd,workspace_root:q.workspace_root,team_name:q.team_name??null,enable_tools:q.enable_tools,enable_spawn:q.enable_spawn,enable_teams:q.enable_teams,parent_session_id:$,parent_agent_id:"lead",agent_id:Y,conversation_id:null,is_subagent:1,prompt:T||`Team task for ${Y}`,metadata_json:null,transcript_path:Q,hook_path:U,messages_path:Z,updated_at:J}),BT(Z,`${JSON.stringify({version:1,updated_at:J,messages:[]},null,2)}
|
|
586
|
+
`,"utf8"),await this.appendSubagentTranscriptLine(X,`[start] ${T}`),X}async onTeamTaskStart($,Y,T){let q=await this.createTeamTaskSubSession($,Y,T);if(!q)return;let X=this.teamTaskQueueKey($,Y),J=this.teamTaskSessionsByAgent.get(X)??[];J.push(q),this.teamTaskSessionsByAgent.set(X,J)}async onTeamTaskEnd($,Y,T,q,X){let J=this.teamTaskQueueKey($,Y),Q=this.teamTaskSessionsByAgent.get(J);if(!Q||Q.length===0)return;let U=Q.shift();if(Q.length===0)this.teamTaskSessionsByAgent.delete(J);else this.teamTaskSessionsByAgent.set(J,Q);if(!U)return;if(X)await this.persistSessionMessages(U,X);await this.appendSubagentTranscriptLine(U,q??`[done] ${T}`),await this.applySubagentStatusBySessionId(U,T)}async handleSubAgentStart($,Y){let T=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!T)return;await this.appendSubagentTranscriptLine(T,`[start] ${Y.input.task}`),await this.applySubagentStatusBySessionId(T,"running")}async handleSubAgentEnd($,Y){let T=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!T)return;if(Y.error){await this.appendSubagentTranscriptLine(T,`[error] ${Y.error.message}`),await this.applySubagentStatusBySessionId(T,"failed");return}if(await this.appendSubagentTranscriptLine(T,`[done] ${Y.result?.finishReason??"completed"}`),Y.result?.finishReason==="aborted"){await this.applySubagentStatusBySessionId(T,"cancelled");return}await this.applySubagentStatusBySessionId(T,"completed")}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(Y){return typeof Y==="object"&&Y!==null&&"code"in Y&&Y.code==="EPERM"}}async listSessions($=200){let Y=Math.max(1,Math.floor($)),T=Math.min(Y*5,2000),q=await this.adapter.listSessions({limit:T}),X=q.filter((J)=>J.status==="running"&&!this.isPidAlive(J.pid));if(X.length>0){for(let J of X)await this.updateSessionStatus(J.session_id,"failed",1);q=await this.adapter.listSessions({limit:T})}return q.slice(0,Y).map((J)=>this.applyResolvedTitleToRow(J))}async deleteSession($){let Y=$.trim();if(!Y)throw Error("session id is required");let T=await this.adapter.getSession(Y);if(!T)return{deleted:!1};if(await this.adapter.deleteSession(Y,!1),!T.is_subagent){let q=await this.adapter.listSessions({limit:2000,parentSessionId:Y});await this.adapter.deleteSession(Y,!0);for(let X of q)$$(X.transcript_path),$$(X.hook_path),$$(X.messages_path),$$(this.sessionManifestPath(X.session_id,!1)),this.artifacts.removeSessionDirIfEmpty(X.session_id)}return $$(T.transcript_path),$$(T.hook_path),$$(T.messages_path),$$(this.sessionManifestPath(Y,!1)),this.artifacts.removeSessionDirIfEmpty(Y),{deleted:!0}}}function i3($){return{session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:$.endedAt??null,exit_code:$.exitCode??null,status:$.status,status_lock:$.statusLock,interactive:$.interactive?1:0,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??null,enable_tools:$.enableTools?1:0,enable_spawn:$.enableSpawn?1:0,enable_teams:$.enableTeams?1:0,parent_session_id:$.parentSessionId??null,parent_agent_id:$.parentAgentId??null,agent_id:$.agentId??null,conversation_id:$.conversationId??null,is_subagent:$.isSubagent?1:0,prompt:$.prompt??null,metadata_json:$.metadata?JSON.stringify($.metadata):null,transcript_path:$.transcriptPath,hook_path:$.hookPath,messages_path:$.messagesPath??null,updated_at:$.updatedAt}}function Qj($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,statusLock:$.status_lock??0,interactive:$.interactive===1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name??void 0,enableTools:$.enable_tools===1,enableSpawn:$.enable_spawn===1,enableTeams:$.enable_teams===1,parentSessionId:$.parent_session_id??void 0,parentAgentId:$.parent_agent_id??void 0,agentId:$.agent_id??void 0,conversationId:$.conversation_id??void 0,isSubagent:$.is_subagent===1,prompt:$.prompt??void 0,metadata:(()=>{if(!$.metadata_json)return;try{let Y=JSON.parse($.metadata_json);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y}catch{}return})(),transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??W0()}}class r3{client;constructor($){this.client=$}ensureSessionsDir(){return""}async upsertSession($){await this.client.upsertSession(Qj($))}async getSession($){let Y=await this.client.getSession($);return Y?i3(Y):void 0}async listSessions($){return(await this.client.listSessions($)).map((T)=>i3(T))}async updateSession($){return await this.client.updateSession({sessionId:$.sessionId,status:$.status,endedAt:$.endedAt,exitCode:$.exitCode,prompt:$.prompt,metadata:$.metadataJson===void 0?void 0:$.metadataJson?JSON.parse($.metadataJson):null,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,expectedStatusLock:$.expectedStatusLock,setRunning:$.setRunning})}async deleteSession($,Y){return await this.client.deleteSession($,Y)}async enqueueSpawnRequest($){await this.client.enqueueSpawnRequest($)}async claimSpawnRequest($,Y){return await this.client.claimSpawnRequest($,Y)}}class V9 extends OT{sessionsDirPath;client;constructor($){let Y=new kJ({address:$.address?.trim()||"127.0.0.1:4317"});super(new r3(Y));this.sessionsDirPath=$.sessionsDir,this.client=Y}ensureSessionsDir(){if(!Xj(this.sessionsDirPath))Jj(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}close(){this.client.close()}}import{spawn as Wj}from"node:child_process";import{existsSync as t3,mkdirSync as Gj,readFileSync as Ej,writeFileSync as Vj}from"node:fs";import{resolve as e3}from"node:path";import{nanoid as Dj}from"nanoid";import{existsSync as Uj,mkdirSync as Zj}from"node:fs";import{join as Kj}from"node:path";function Aj(){return G$()}class J6{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Aj()}init(){this.getRawDb()}ensureSessionsDir(){if(!Uj(this.sessionsDirPath))Zj(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Kj(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=NY(this.sessionDbPath());return L8($,{includeLegacyMigrations:!0}),this.db=$,$}run($,Y=[]){return this.getRawDb().prepare($).run(...Y)}queryOne($,Y=[]){return this.getRawDb().prepare($).get(...Y)??void 0}queryAll($,Y=[]){return this.getRawDb().prepare($).all(...Y)}create($){let Y=O0();this.run(`INSERT OR REPLACE INTO sessions (
|
|
587
587
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
588
588
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
589
589
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
@@ -593,7 +593,7 @@ ${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y
|
|
|
593
593
|
enable_tools, enable_spawn, enable_teams,
|
|
594
594
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
|
|
595
595
|
prompt, metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
596
|
-
FROM sessions WHERE session_id = ?`,[$]);if(!Y)return;return{sessionId:Q0(Y.session_id),source:Q0(Y.source),pid:Number(Y.pid??0),startedAt:Q0(Y.started_at),endedAt:Y.ended_at??null,exitCode:Y.exit_code??null,status:Q0(Y.status),interactive:$1(Y.interactive),provider:Q0(Y.provider),model:Q0(Y.model),cwd:Q0(Y.cwd),workspaceRoot:Q0(Y.workspace_root),teamName:K0(Y.team_name),enableTools:$1(Y.enable_tools),enableSpawn:$1(Y.enable_spawn),enableTeams:$1(Y.enable_teams),parentSessionId:K0(Y.parent_session_id),parentAgentId:K0(Y.parent_agent_id),agentId:K0(Y.agent_id),conversationId:K0(Y.conversation_id),isSubagent:$1(Y.is_subagent),prompt:K0(Y.prompt),metadata:(()=>{let T=K0(Y.metadata_json);if(!T)return;try{let q=JSON.parse(T);if(q&&typeof q==="object"&&!Array.isArray(q))return q}catch{}return})(),transcriptPath:K0(Y.transcript_path),hookPath:K0(Y.hook_path),messagesPath:K0(Y.messages_path),updatedAt:K0(Y.updated_at)??O0()}}list($=200){let Y=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),T=[];for(let q of Y){let X=this.get(Q0(q.session_id));if(X)T.push(X)}return T}delete($,Y=!1){let T=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return T>0}}class
|
|
596
|
+
FROM sessions WHERE session_id = ?`,[$]);if(!Y)return;return{sessionId:Q0(Y.session_id),source:Q0(Y.source),pid:Number(Y.pid??0),startedAt:Q0(Y.started_at),endedAt:Y.ended_at??null,exitCode:Y.exit_code??null,status:Q0(Y.status),interactive:$1(Y.interactive),provider:Q0(Y.provider),model:Q0(Y.model),cwd:Q0(Y.cwd),workspaceRoot:Q0(Y.workspace_root),teamName:K0(Y.team_name),enableTools:$1(Y.enable_tools),enableSpawn:$1(Y.enable_spawn),enableTeams:$1(Y.enable_teams),parentSessionId:K0(Y.parent_session_id),parentAgentId:K0(Y.parent_agent_id),agentId:K0(Y.agent_id),conversationId:K0(Y.conversation_id),isSubagent:$1(Y.is_subagent),prompt:K0(Y.prompt),metadata:(()=>{let T=K0(Y.metadata_json);if(!T)return;try{let q=JSON.parse(T);if(q&&typeof q==="object"&&!Array.isArray(q))return q}catch{}return})(),transcriptPath:K0(Y.transcript_path),hookPath:K0(Y.hook_path),messagesPath:K0(Y.messages_path),updatedAt:K0(Y.updated_at)??O0()}}list($=200){let Y=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),T=[];for(let q of Y){let X=this.get(Q0(q.session_id));if(X)T.push(X)}return T}delete($,Y=!1){let T=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return T>0}}class a3{store;constructor($){this.store=$}ensureSessionsDir(){return this.store.ensureSessionsDir()}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
597
597
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
598
598
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
599
599
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
@@ -616,12 +616,12 @@ ${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y
|
|
|
616
616
|
WHERE session_id = ? AND status_lock = ?`,[W0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let Y=[],T=[];if($.status!==void 0)Y.push("status = ?"),T.push($.status);if($.endedAt!==void 0)Y.push("ended_at = ?"),T.push($.endedAt);if($.exitCode!==void 0)Y.push("exit_code = ?"),T.push($.exitCode);if($.prompt!==void 0)Y.push("prompt = ?"),T.push($.prompt??null);if($.metadataJson!==void 0)Y.push("metadata_json = ?"),T.push($.metadataJson??null);if($.parentSessionId!==void 0)Y.push("parent_session_id = ?"),T.push($.parentSessionId??null);if($.parentAgentId!==void 0)Y.push("parent_agent_id = ?"),T.push($.parentAgentId??null);if($.agentId!==void 0)Y.push("agent_id = ?"),T.push($.agentId??null);if($.conversationId!==void 0)Y.push("conversation_id = ?"),T.push($.conversationId??null);if(Y.length===0){let Q=await this.getSession($.sessionId);return{updated:!!Q,statusLock:Q?.status_lock??0}}let q=0;if($.expectedStatusLock!==void 0)q=$.expectedStatusLock+1,Y.push("status_lock = ?"),T.push(q);Y.push("updated_at = ?"),T.push(W0());let X=`UPDATE sessions SET ${Y.join(", ")} WHERE session_id = ?`;if(T.push($.sessionId),$.expectedStatusLock!==void 0)X+=" AND status_lock = ?",T.push($.expectedStatusLock);if((this.store.run(X,T).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)q=(await this.getSession($.sessionId))?.status_lock??0;return{updated:!0,statusLock:q}}async deleteSession($,Y){let T=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return T>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
|
|
617
617
|
VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,W0()])}async claimSpawnRequest($,Y){let T=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
|
|
618
618
|
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
619
|
-
ORDER BY id ASC LIMIT 1`,[$,Y]);if(!T||typeof T.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[W0(),T.id]),T.task??void 0}}class
|
|
619
|
+
ORDER BY id ASC LIMIT 1`,[$,Y]);if(!T||typeof T.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[W0(),T.id]),T.task??void 0}}class D9 extends OT{store;constructor($){super(new a3($));this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
620
620
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
621
621
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
622
622
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
623
623
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
624
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath,$.hookPath,$.messagesPath,W0()])}}var
|
|
624
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath,$.hookPath,$.messagesPath,W0()])}}var Fj=process.env.CLINE_RPC_ADDRESS?.trim()||p3(),a1,PT;function Nj($){let Y=process.execPath,T=process.argv[1]?.trim();if(!T)return;let q=e3(process.cwd(),T);if(!t3(q))return;let X=process.execArgv.find((U)=>U.startsWith("--conditions=")),J=[...X?[X]:[],q,"rpc","start","--address",$];Wj(Y,J,{detached:!0,stdio:"ignore",env:{...process.env,CLINE_NO_INTERACTIVE:"1"},cwd:process.cwd()}).unref()}async function o3($){try{if(!await b3($))return;return new V9({address:$,sessionsDir:G$()})}catch{return}}function s3(){return new D9(new J6)}function Hj($){if(typeof $==="string"&&$.trim().length>0)return $.trim();let Y=G$(),T=e3(Y,"machine-id");try{if(t3(T)){let X=Ej(T,"utf8").trim();if(X.length>0)return X}}catch{}let q=Dj();try{Gj(Y,{recursive:!0}),Vj(T,q,"utf8")}catch{}return q}async function $D($){if(a1)return a1;if(PT)return await PT;let Y=$.backendMode??"auto",T=$.rpcAddress?.trim()||Fj,q=Math.max(1,$.rpcConnectAttempts??5),X=Math.max(0,$.rpcConnectDelayMs??100),J=$.autoStartRpcServer!==!1;return PT=(async()=>{if(Y==="local")return a1=s3(),a1;let Q=await o3(T);if(Q)return a1=Q,a1;if(Y==="rpc")throw Error(`RPC backend unavailable at ${T}`);if(J){try{Nj(T)}catch{}for(let U=0;U<q;U+=1){let Z=await o3(T);if(Z)return a1=Z,a1;if(X>0)await new Promise((K)=>setTimeout(K,X))}}return a1=s3(),a1})().finally(()=>{PT=void 0}),await PT}async function zj($){let Y=$.sessionService??await $D($);return new x8({sessionService:Y,defaultToolExecutors:$.defaultToolExecutors,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,distinctId:Hj($.distinctId)})}class uJ{store;constructor($={}){this.store=new J6({sessionsDir:$.sessionsDir})}init(){this.store.init()}upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
625
625
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
626
626
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
627
627
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
@@ -638,5 +638,5 @@ ${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y
|
|
|
638
638
|
VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,O0()])}claimSpawnRequest($,Y){let T=this.store.queryOne(`SELECT id, root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at
|
|
639
639
|
FROM subagent_spawn_queue
|
|
640
640
|
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
641
|
-
ORDER BY id ASC LIMIT 1`,[$,Y]);if(!T||typeof T.id!=="number")return;let q=O0();return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[q,T.id]),{id:T.id,rootSessionId:Q0(T.root_session_id),parentAgentId:Q0(T.parent_agent_id),task:K0(T.task),systemPrompt:K0(T.system_prompt),createdAt:Q0(T.created_at),consumedAt:q}}}function
|
|
642
|
-
${JSON.stringify(T,null,2)}`}class
|
|
641
|
+
ORDER BY id ASC LIMIT 1`,[$,Y]);if(!T||typeof T.id!=="number")return;let q=O0();return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[q,T.id]),{id:T.id,rootSessionId:Q0(T.root_session_id),parentAgentId:Q0(T.parent_agent_id),task:K0(T.task),systemPrompt:K0(T.system_prompt),createdAt:Q0(T.created_at),consumedAt:q}}}function Ij($={}){return new uJ($)}import{basename as Mj,resolve as Bj}from"node:path";import Rj from"simple-git";import{z as j1}from"zod";var YD=j1.object({rootPath:j1.string().min(1),hint:j1.string().min(1).optional(),associatedRemoteUrls:j1.array(j1.string().min(1)).optional(),latestGitCommitHash:j1.string().min(1).optional(),latestGitBranchName:j1.string().min(1).optional()}),Q6=j1.object({currentWorkspacePath:j1.string().min(1).optional(),workspaces:j1.record(j1.string().min(1),YD)});function Oj(){return{workspaces:{}}}function LT($){return Bj($)}async function F9($){let Y=LT($),T={rootPath:Y,hint:Mj(Y)};try{let q=Rj({baseDir:Y});if(!await q.checkIsRepo())return T;let J=await q.getRemotes(!0);if(J.length>0){let Z=J.map((K)=>{let A=K.refs.fetch||K.refs.push;return`${K.name}: ${A}`});T.associatedRemoteUrls=Z}let Q=(await q.revparse(["HEAD"])).trim();if(Q.length>0)T.latestGitCommitHash=Q;let U=(await q.branch()).current.trim();if(U.length>0)T.latestGitBranchName=U}catch{}return T}function dJ($,Y){let T={...$,workspaces:{...$.workspaces,[Y.rootPath]:Y}};if(!T.currentWorkspacePath)T.currentWorkspacePath=Y.rootPath;return Q6.parse(T)}async function Pj($){let Y=await F9($),T={workspaces:{[Y.rootPath]:{hint:Y.hint,associatedRemoteUrls:Y.associatedRemoteUrls,latestGitCommitHash:Y.latestGitCommitHash,latestGitBranchName:Y.latestGitBranchName}}};return`# Workspace Configuration
|
|
642
|
+
${JSON.stringify(T,null,2)}`}class TD{manifest;listeners=new Set;constructor($){this.manifest=Q6.parse($??{workspaces:{}})}async addWorkspacePath($){let Y=await F9($);return this.manifest=dJ(this.manifest,Y),this.emit({type:"workspace_added",workspace:Y}),Y}async switchWorkspace($){let Y=LT($),T=this.manifest.workspaces[Y];if(T)return this.manifest=Q6.parse({...this.manifest,currentWorkspacePath:Y}),this.emit({type:"workspace_switched",workspace:T}),T;let q=await this.addWorkspacePath(Y);return this.manifest=Q6.parse({...this.manifest,currentWorkspacePath:q.rootPath}),this.emit({type:"workspace_switched",workspace:q}),q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let Y=LT($);return this.manifest.workspaces[Y]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let Y of this.listeners)Y($)}}export{dJ as upsertWorkspaceInfo,S8 as toTeamProgressLifecycleEvent,T8 as toPartialAgentConfig,u9 as toHookConfigFileName,b$ as startLocalOAuthServer,CT as setHomeDirIfUnset,aJ as setHomeDir,RH as saveLocalProviderSettings,wH as saveLocalProviderOAuthCredentials,MT as sanitizeSessionToken,Y4 as resolveWorkflowsConfigSearchPaths,rH as resolveWorkflowSlashCommandFromWatcher,e9 as resolveSkillsConfigSearchPaths,G$ as resolveSessionDataDir,$D as resolveSessionBackend,$4 as resolveRulesConfigSearchPaths,l9 as resolvePluginConfigSearchPaths,I4 as resolveMcpServerRegistrations,SH as resolveLocalClineAuthToken,f9 as resolveHooksConfigSearchPaths,TQ as resolveHookLogPath,E6 as resolveDocumentsWorkflowsDirectoryPath,G6 as resolveDocumentsRulesDirectoryPath,W6 as resolveDocumentsHooksDirectoryPath,O8 as resolveDefaultMcpSettingsPath,t0 as resolveClineDataDir,Z8 as resolveAndLoadAgentPlugins,Y8 as resolveAgentTools,n9 as resolveAgentPluginPaths,nH as requestDesktopToolApproval,IU as registerMcpServersFromSettingsFile,W4 as refreshOpenAICodexToken,V4 as refreshOcaToken,K4 as refreshClineToken,RQ as prewarmFileIndex,t9 as parseWorkflowConfigFromMarkdown,o9 as parseSkillConfigFromMarkdown,s9 as parseRuleConfigFromMarkdown,g9 as parsePartialAgentConfigFromYaml,GY as parseAgentConfigFromYaml,AN as openaiCodexOAuthProvider,LT as normalizeWorkspacePath,xT as normalizeUserInput,KN as normalizeOpenAICodexCredentials,OH as normalizeOAuthProvider,R4 as migrateLegacyProviderSettings,_J as makeTeamTaskSubSessionId,E9 as makeSubSessionId,M8 as loginOpenAICodex,R8 as loginOcaOAuth,LH as loginLocalProvider,z8 as loginClineOAuth,CH as loadRulesForSystemPromptFromWatcher,z4 as loadMcpSettingsFile,J8 as loadAgentPluginsFromPaths,d9 as loadAgentPluginFromPath,BH as listLocalProviders,X8 as listHookConfigFiles,gU as listEnabledRulesFromWatcher,pU as listAvailableWorkflowsFromWatcher,hU as isRuleEnabled,AU as isRpcClineAccountActionRequest,ZN as isOpenAICodexTokenExpired,zU as hasMcpSettingsFile,G4 as getValidOpenAICodexCredentials,D4 as getValidOcaCredentials,A4 as getValidClineCredentials,kU as getLocalProviderModels,g$ as getFileIndex,Vh as getClineDefaultSystemPrompt,F9 as generateWorkspaceInfo,KU as generateOcaOpcRequestId,_U as formatRulesForSystemPrompt,WU as executeRpcClineAccountAction,F6 as ensureParentDir,oJ as ensureHookLogDir,HH as ensureCustomProvidersLoaded,oT as enrichPromptWithMentions,Oj as emptyWorkspaceManifest,FY as emptyStoredProviderSettings,U8 as discoverPluginModulePaths,gJ as deriveSubsessionStatus,X4 as createWorkflowsConfigDefinition,V8 as createUserInstructionConfigWatcher,LQ as createToolPoliciesWithPreset,Eh as createTool,dU as createTeamName,Ij as createSqliteRpcSessionBackend,T4 as createSkillsConfigDefinition,zj as createSessionHost,q4 as createRulesConfigDefinition,MN as createOcaRequestHeaders,IN as createOcaOAuthProvider,J4 as createOAuthClientCallbacks,wQ as createDefaultToolsWithPreset,AY as createDefaultTools,$8 as createDefaultExecutors,TN as createClineOAuthProvider,N6 as createBuiltinTools,vQ as createAgentConfigWatcher,m9 as createAgentConfigDefinition,Pj as buildWorkspaceMetadata,w8 as buildTeamProgressSummary,MH as addLocalProvider,Q6 as WorkspaceManifestSchema,YD as WorkspaceInfoSchema,K6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,f$ as UnifiedConfigFileWatcher,t1 as ToolPresets,Q8 as SubprocessSandbox,P8 as StoredProviderSettingsSchema,BU as StoredProviderSettingsEntrySchema,B6 as SqliteTeamStore,J6 as SqliteSessionStore,uJ as SqliteRpcSessionBackend,R6 as SessionSource,H1 as SKILLS_CONFIG_DIRECTORY_NAME,P4 as SESSION_STATUSES,V9 as RpcCoreSessionService,N4 as RpcClineAccountService,Z6 as RULES_CONFIG_DIRECTORY_NAME,kT as RPC_TEAM_PROGRESS_EVENT_TYPE,hT as RPC_TEAM_LIFECYCLE_EVENT_TYPE,d$ as ProviderSettingsManager,TU as OCI_HEADER_OPC_REQUEST_ID,TD as InMemoryWorkspaceManager,M4 as InMemoryMcpManager,q8 as HookConfigFileName,b9 as HOOK_CONFIG_FILE_EVENT_MAP,U6 as HOOKS_CONFIG_DIRECTORY_NAME,v1 as DefaultToolNames,x8 as DefaultSessionManager,C8 as DefaultRuntimeBuilder,sQ as DEFAULT_INTERNAL_OCA_BASE_URL,aQ as DEFAULT_INTERNAL_IDCS_URL,oQ as DEFAULT_INTERNAL_IDCS_SCOPES,rQ as DEFAULT_INTERNAL_IDCS_CLIENT_ID,YU as DEFAULT_EXTERNAL_OCA_BASE_URL,eQ as DEFAULT_EXTERNAL_IDCS_URL,$U as DEFAULT_EXTERNAL_IDCS_SCOPES,tQ as DEFAULT_EXTERNAL_IDCS_CLIENT_ID,D9 as CoreSessionService,F4 as ClineAccountService,BN as ChatViewStateSchema,FU as ChatSummarySchema,EU as ChatSessionStatusSchema,GU as ChatSessionConfigSchema,DU as ChatMessageSchema,VU as ChatMessageRoleSchema,_$ as ALL_DEFAULT_TOOL_NAMES};
|