@interactive-inc/claude-funnel 0.23.0 → 0.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js
CHANGED
|
@@ -904,7 +904,7 @@ Since you have not provided a token or authorize, you might be missing one or mo
|
|
|
904
904
|
* Copyright(c) 2013 Roman Shtylman
|
|
905
905
|
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
|
906
906
|
* MIT Licensed
|
|
907
|
-
*/var ap=Yxq(),X9K=gA("events").EventEmitter,IMq=Xxq(),PMq=JOq(),NMq=F4A(),_Mq=cOq(),wMq=OMq();ZG=BMq.exports=G9K;function G9K(){var A=function(q,K,F){A.handle(q,K,F)};return IMq(A,X9K.prototype,!1),IMq(A,PMq,!1),A.request=Object.create(_Mq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.response=Object.create(wMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.init(),A}ZG.application=PMq;ZG.request=_Mq;ZG.response=wMq;ZG.Route=NMq.Route;ZG.Router=NMq;ZG.json=ap.json;ZG.raw=ap.raw;ZG.static=zMq();ZG.text=ap.text;ZG.urlencoded=ap.urlencoded});var yMq=I((b$)=>{var j9K=b$&&b$.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),J9K=b$&&b$.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),SMq=b$&&b$.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))j9K(q,A,K)}return J9K(q,A),q},dp=b$&&b$.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(b$,"__esModule",{value:!0});b$.buildBodyParserMiddleware=b$.verifySignatureAndParseBody=b$.verifySignatureAndParseRawBody=b$.respondToUrlVerification=b$.respondToSslCheck=void 0;var H9K=dp(gA("crypto")),E9K=gA("http"),W9K=gA("https"),g9K=dp(gA("querystring")),RMq=gY(),V9K=FR(),TMq=SMq(DMq()),L9K=dp(Qp()),x9K=dp(Xp()),Z7=xY(),nz=SMq(JR()),O9K=jp(),M9K=Hp(),z9K=["ALPNProtocols","clientCertEngine","enableTrace","handshakeTimeout","rejectUnauthorized","requestCert","sessionTimeout","SNICallback","ticketKeys","pskCallback","pskIdentityHint","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext"],z4A="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",I9K=(A,q,K)=>{if(A.body?.ssl_check){q.send();return}K()};b$.respondToSslCheck=I9K;var P9K=(A,q,K)=>{if(A.body?.type&&A.body.type==="url_verification"){q.json({challenge:A.body.challenge});return}K()};b$.respondToUrlVerification=P9K;class bMq{app;server;bolt;logger;processBeforeResponse;signatureVerification;router;installer=void 0;installerOptions;customPropertiesExtractor;dispatchErrorHandler;processEventErrorHandler;unhandledRequestHandler;unhandledRequestTimeoutMillis;constructor({signingSecret:A="",logger:q=void 0,logLevel:K=RMq.LogLevel.INFO,endpoints:F={events:"/slack/events"},processBeforeResponse:Z=!1,signatureVerification:$=!0,clientId:U=void 0,clientSecret:Y=void 0,stateSecret:X=void 0,redirectUri:j=void 0,installationStore:J=void 0,scopes:E=void 0,installerOptions:W={},app:g=void 0,router:L=void 0,customPropertiesExtractor:M=(v)=>({}),dispatchErrorHandler:O=nz.defaultAsyncDispatchErrorHandler,processEventErrorHandler:_=nz.defaultProcessEventErrorHandler,unhandledRequestHandler:R=nz.defaultUnhandledRequestHandler,unhandledRequestTimeoutMillis:T=3001}){if(this.app=g!==void 0?g:(0,TMq.default)(),typeof q<"u")this.logger=q;else this.logger=new RMq.ConsoleLogger,this.logger.setLevel(K);this.signatureVerification=$;let y=[this.signatureVerification?vMq(this.logger,A):CMq(this.logger),b$.respondToSslCheck,b$.respondToUrlVerification,this.requestHandler.bind(this)];this.processBeforeResponse=Z;let i=typeof F==="string"?[F]:Object.values(F);this.router=L!==void 0?L:(0,TMq.Router)();for(let n of i)this.router.post(n,...y);if(this.customPropertiesExtractor=M,this.dispatchErrorHandler=O,this.processEventErrorHandler=_,this.unhandledRequestHandler=R,this.unhandledRequestTimeoutMillis=T,(0,M9K.verifyRedirectOpts)({redirectUri:j,redirectUriPath:W.redirectUriPath}),U!==void 0&&Y!==void 0&&(W.stateVerification===!1||X!==void 0||W.stateStore!==void 0))this.installer=new V9K.InstallProvider({clientId:U,clientSecret:Y,stateSecret:X,installationStore:J,logLevel:K,logger:q,directInstall:W.directInstall,stateStore:W.stateStore,stateVerification:W.stateVerification,legacyStateVerification:W.legacyStateVerification,stateCookieName:W.stateCookieName,stateCookieExpirationSeconds:W.stateCookieExpirationSeconds,renderHtmlForInstallPath:W.renderHtmlForInstallPath,authVersion:W.authVersion??"v2",clientOptions:W.clientOptions,authorizationUrl:W.authorizationUrl});let l={metadata:W.metadata,scopes:E??[],userScopes:W.userScopes,redirectUri:j};if(this.installer!==void 0){let{installer:n}=this,a=W.redirectUriPath===void 0?"/slack/oauth_redirect":W.redirectUriPath,{callbackOptions:qA,stateVerification:JA}=W;this.router.use(a,async(sA,_A)=>{try{if(JA===!1)await n.handleCallback(sA,_A,qA,l);else await n.handleCallback(sA,_A,qA)}catch(zA){await this.dispatchErrorHandler({error:zA,logger:this.logger,request:sA,response:_A})}});let VA=W.installPath===void 0?"/slack/install":W.installPath,{installPathOptions:mA}=W;this.router.get(VA,async(sA,_A,zA)=>{try{try{await n.handleInstallPath(sA,_A,mA,l)}catch(e){zA(e)}}catch(e){await this.dispatchErrorHandler({error:e,logger:this.logger,request:sA,response:_A})}})}this.app.use(this.router)}async requestHandler(A,q){let K=new O9K.HTTPResponseAck({logger:this.logger,processBeforeResponse:this.processBeforeResponse,unhandledRequestHandler:this.unhandledRequestHandler,unhandledRequestTimeoutMillis:this.unhandledRequestTimeoutMillis,httpRequest:A,httpRequestBody:A.body,httpResponse:q}),F={body:A.body,ack:K.bind(),retryNum:nz.extractRetryNumFromHTTPRequest(A),retryReason:nz.extractRetryReasonFromHTTPRequest(A),customProperties:this.customPropertiesExtractor(A)};try{if(await this.bolt?.processEvent(F),K.storedResponse!==void 0)nz.buildContentResponse(q,K.storedResponse),this.logger.debug("stored response sent")}catch(Z){if(await this.processEventErrorHandler({error:Z,logger:this.logger,request:A,response:q,storedResponse:K.storedResponse}))K.ack()}}init(A){this.bolt=A}start(A,q={}){let K=E9K.createServer;if(Object.keys(q).filter((F)=>z9K.includes(F)).length>0)K=W9K.createServer;if(this.server!==void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be started because it was already started."));return this.server=K(q,this.app),new Promise((F,Z)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.on("error",($)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.close(),Z($)}),this.server.on("close",()=>{this.server=void 0}),this.server.listen(A,()=>{if(this.server===void 0)return Z(new Z7.ReceiverInconsistentStateError(z4A));return F(this.server)})})}stop(){if(this.server===void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be stopped because it was not started."));return new Promise((A,q)=>{this.server?.close((K)=>{if(K!==void 0)return q(K);return this.server=void 0,A()})})}}b$.default=bMq;function N9K(A,q){return vMq(A,q)}b$.verifySignatureAndParseRawBody=N9K;function vMq(A,q){return async(K,F,Z)=>{let $=await hMq(K);try{K.body=kMq(typeof q==="string"?q:await q(),$,K.headers)}catch(U){if(U){if(U instanceof Z7.ReceiverAuthenticityError){I4A(A,"Request verification failed",U),F.status(401).send();return}I4A(A,"Parsing request body failed",U),F.status(400).send();return}}Z()}}function I4A(A,q,K){let F="code"in K?`${q} (code: ${K.code}, message: ${K.message})`:`${q} (error: ${K})`;A.warn(F)}function _9K(A,q,K,F){if(K===void 0||F===void 0)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Some headers are missing.");let Z=Number(F);if(Number.isNaN(Z))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is invalid.");let $=Math.floor(Date.now()/1000)-300;if(Z<$)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is too old.");let U=H9K.default.createHmac("sha256",A),[Y,X]=K.split("=");if(U.update(`${Y}:${Z}:${q}`),!(0,x9K.default)(X,U.digest("hex")))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function kMq(A,q,K){let{"x-slack-signature":F,"x-slack-request-timestamp":Z,"content-type":$}=K;return _9K(A,q,F,Z),fMq(q,$)}b$.verifySignatureAndParseBody=kMq;function CMq(A){return async(q,K,F)=>{let Z=await hMq(q);try{let{"content-type":$}=q.headers;q.body=fMq(Z,$)}catch($){if($){I4A(A,"Parsing request body failed",$),K.status(400).send();return}}F()}}b$.buildBodyParserMiddleware=CMq;function fMq(A,q){if(q==="application/x-www-form-urlencoded"){let K=g9K.default.parse(A);if(typeof K.payload==="string")return JSON.parse(K.payload);return K}return JSON.parse(A)}async function hMq(A){if("rawBody"in A&&A.rawBody)return Promise.resolve(A.rawBody.toString());return(await(0,L9K.default)(A)).toString()}});var lMq=I((mMq)=>{Object.defineProperty(mMq,"__esModule",{value:!0});mMq.DefaultThreadContextStore=void 0;var uMq=P4A();class cMq{context={};async get(A){let{context:q,client:K,payload:F,logger:Z}=A;if(Z.debug("DefaultAssistantThreadStore: get method called"),this.context.channel_id)return this.context;let{channelId:$,threadTs:U}=(0,uMq.extractThreadInfo)(F),Y=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!Y.messages)return{};let X=Y.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);return(X?.metadata?X.metadata.event_payload:null)||{}}async save(A){let{context:q,client:K,payload:F,logger:Z}=A,{channelId:$,threadTs:U,context:Y}=(0,uMq.extractThreadInfo)(F);Z.debug("DefaultAssistantThreadStore: save method called");let X=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!X.messages)return;let j=X.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);if(j?.ts){let J={channel:$,ts:j.ts,text:j.text,blocks:j.blocks?j.blocks:[],metadata:{event_type:"assistant_thread_context",event_payload:Y}};await K.chat.update(J)}this.context=Y}}mMq.DefaultThreadContextStore=cMq});var P4A=I((l9)=>{var w9K=l9&&l9.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(l9,"__esModule",{value:!0});l9.extractThreadInfo=l9.processAssistantMiddleware=l9.validate=l9.isAssistantMessage=l9.matchesConstraints=l9.isAssistantEvent=l9.enrichAssistantArgs=l9.Assistant=void 0;var B9K=lMq(),iMq=T8A(),SL=xY(),np=rc(),D9K=w9K(tc()),R9K=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class aMq{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor(A){rMq(A);let{threadContextStore:q=new B9K.DefaultThreadContextStore,threadStarted:K,threadContextChanged:F=($)=>q.save($),userMessage:Z}=A;this.threadContextStore=q,this.threadStarted=Array.isArray(K)?K:[K],this.threadContextChanged=Array.isArray(F)?F:[F],this.userMessage=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(nMq(A)&&sMq(A))return this.processEvent(A);return A.next()}}async processEvent(A){let{payload:q}=A,K=dMq(this.threadContextStore,A),F=this.getAssistantMiddleware(q);return tMq(K,F)}getAssistantMiddleware(A){switch(A.type){case"assistant_thread_started":return this.threadStarted;case"assistant_thread_context_changed":return this.threadContextChanged;case"message":return this.userMessage;default:return[]}}}l9.Assistant=aMq;function dMq(A,q){let{next:K,...F}=q,Z={...F};return Z.getThreadContext=()=>A.get(q),Z.saveThreadContext=()=>A.save(q),Z.say=T9K(Z),Z.sayStream=S9K(Z),Z.setStatus=b9K(Z),Z.setSuggestedPrompts=v9K(Z),Z.setTitle=k9K(Z),Z}l9.enrichAssistantArgs=dMq;function nMq(A){return R9K.has(A.payload.type)}l9.isAssistantEvent=nMq;function sMq(A){return A.payload.type==="message"?oMq(A.payload):!0}l9.matchesConstraints=sMq;function oMq(A){let q="channel"in A&&"thread_ts"in A,K="channel_type"in A&&A.channel_type==="im"&&(!("subtype"in A)||A.subtype==="file_share"||A.subtype===void 0);return q&&K}l9.isAssistantMessage=oMq;function rMq(A){if(typeof A!=="object")throw new SL.AssistantInitializationError("Assistant expects a configuration object as the argument");let q=["threadStarted","userMessage"],K=[];for(let Z of q)if(A[Z]===void 0)K.push(Z);if(K.length>0){let Z=`Assistant is missing required keys: ${K.join(", ")}`;throw new SL.AssistantInitializationError(Z)}let F=["threadStarted","userMessage"];if("threadContextChanged"in A)F.push("threadContextChanged");for(let Z of F)if(typeof A[Z]!=="function"&&!Array.isArray(A[Z])){let $=`Assistant ${Z} property must be a function or an array of functions`;throw new SL.AssistantInitializationError($)}if(A.threadContextStore){if(typeof A.threadContextStore!=="object")throw new SL.AssistantInitializationError("Assistant expects threadContextStore to be a configuration object");let Z=["get","save"],$=[];for(let Y of Z)if(A.threadContextStore&&A.threadContextStore[Y]===void 0)$.push(Y);if($.length>0){let Y=`threadContextStore is missing required keys: ${$.join(", ")}`;throw new SL.AssistantInitializationError(Y)}let U=["get","save"];for(let Y of U)if(A.threadContextStore&&typeof A.threadContextStore[Y]!=="function"){let X=`threadContextStore ${Y} property must be a function`;throw new SL.AssistantInitializationError(X)}}}l9.validate=rMq;async function tMq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,D9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}l9.processAssistantMiddleware=tMq;function T9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z,context:$}=sz(K);return async(U)=>{let Y=$.channel_id?$:await A.getThreadContext(),X=typeof U==="string"?{text:U,channel:F,thread_ts:Z}:{...U,channel:F,thread_ts:Z};if(Y||X.metadata)X.metadata={event_type:X.metadata?.event_type??"assistant_thread_context",event_payload:{...Y,...X.metadata?.event_payload??{}}};return q.chat.postMessage(X)}}function S9K(A){let{client:q,context:K,payload:F}=A,{channelId:Z,threadTs:$}=sz(F);return(0,iMq.createSayStream)(q,K,Z,$)}function b9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return(0,iMq.createSetStatus)(q,F,Z)}function v9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>{let{prompts:U,title:Y}=$;return q.assistant.threads.setSuggestedPrompts({channel_id:F,thread_ts:Z,prompts:U,title:Y})}}function k9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>q.assistant.threads.setTitle({channel_id:F,thread_ts:Z,title:$})}function sz(A){let q={};if("assistant_thread"in A&&(0,np.isRecord)(A.assistant_thread)){if((0,np.isRecord)(A.assistant_thread.context))q=A.assistant_thread.context}let K=(0,np.extractEventChannelId)(A),F=(0,np.extractEventThreadTs)(A);if(!K||!F){let Z=[];if(!K)Z.push("channel_id");if(!F)Z.push("thread_ts");throw new SL.AssistantMissingPropertyError(`Assistant message event is missing required properties: ${Z.join(", ")}`)}return{channelId:K,threadTs:F,context:q}}l9.extractThreadInfo=sz});var Zzq=I((F8)=>{var C9K=F8&&F8.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(F8,"__esModule",{value:!0});F8.prepareStepArgs=F8.isStepEvent=F8.processStepMiddleware=F8.validate=F8.WorkflowStep=void 0;var sp=xY(),f9K=C9K(tc()),h9K=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class eMq{callbackId;edit;save;execute;constructor(A,q){Azq(A,q);let{save:K,edit:F,execute:Z}=q;this.callbackId=A,this.save=Array.isArray(K)?K:[K],this.edit=Array.isArray(F)?F:[F],this.execute=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(Kzq(A)&&this.matchesConstraints(A))return this.processEvent(A);return A.next()}}matchesConstraints(A){return A.payload.callback_id===this.callbackId}async processEvent(A){let{payload:q}=A,K=Fzq(A),F=this.getStepMiddleware(q);return qzq(K,F)}getStepMiddleware(A){switch(A.type){case"workflow_step_edit":return this.edit;case"workflow_step":return this.save;case"workflow_step_execute":return this.execute;default:return[]}}}F8.WorkflowStep=eMq;function Azq(A,q){if(typeof A!=="string")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof q!=="object")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a configuration object as the second argument");let K=["save","edit","execute"],F=[];for(let $ of K)if(q[$]===void 0)F.push($);if(F.length>0){let $=`WorkflowStep is missing required keys: ${F.join(", ")}`;throw new sp.WorkflowStepInitializationError($)}let Z=["save","edit","execute"];for(let $ of Z)if(typeof q[$]!=="function"&&!Array.isArray(q[$])){let U=`WorkflowStep ${$} property must be a function or an array of functions`;throw new sp.WorkflowStepInitializationError(U)}}F8.validate=Azq;async function qzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,f9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}F8.processStepMiddleware=qzq;function Kzq(A){return h9K.has(A.payload.type)}F8.isStepEvent=Kzq;function op(A){return A.botToken!==void 0?A.botToken:A.userToken}function y9K(A){let{context:q,client:K,body:{callback_id:F,trigger_id:Z}}=A,$=op(q);return(U)=>K.views.open({token:$,trigger_id:Z,view:{callback_id:F,type:"workflow_step",...U}})}function u9K(A){let{context:q,client:K,body:{workflow_step:{workflow_step_edit_id:F}}}=A,Z=op(q);return($={})=>K.workflows.updateStep({token:Z,workflow_step_edit_id:F,...$})}function c9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($={})=>K.workflows.stepCompleted({token:Z,workflow_step_execute_id:F,...$})}function m9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($)=>{let{error:U}=$;return K.workflows.stepFailed({token:Z,workflow_step_execute_id:F,error:U})}}function Fzq(A){let{next:q,...K}=A,F={...K};switch(F.payload.type){case"workflow_step_edit":F.step=F.action.workflow_step,F.configure=y9K(F);break;case"workflow_step":F.step=F.body.workflow_step,F.update=u9K(F);break;case"workflow_step_execute":F.step=F.event.workflow_step,F.complete=c9K(F),F.fail=m9K(F);break;default:break}return F}F8.prepareStepArgs=Fzq});var Xzq=I((WK)=>{var $zq=WK&&WK.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),p9K=WK&&WK.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),N4A=WK&&WK.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))$zq(q,A,K)}return p9K(q,A),q},_4A=WK&&WK.__exportStar||function(A,q){for(var K in A)if(K!=="default"&&!Object.prototype.hasOwnProperty.call(q,K))$zq(q,A,K)},fR=WK&&WK.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(WK,"__esModule",{value:!0});WK.webApi=WK.types=WK.FileInstallationStore=WK.MemoryInstallationStore=WK.WorkflowStep=WK.Assistant=WK.buildReceiverRoutes=WK.MemoryStore=WK.defaultProcessEventErrorHandler=WK.HTTPResponseAck=WK.HTTPModuleFunctions=WK.AwsLambdaReceiver=WK.HTTPReceiver=WK.SocketModeReceiver=WK.ExpressReceiver=WK.isValidSlackRequest=WK.verifySlackRequest=WK.App=WK.LogLevel=void 0;var Uzq=fR(gjA());WK.App=Uzq.default;var l9K=gjA();Object.defineProperty(WK,"LogLevel",{enumerable:!0,get:function(){return l9K.LogLevel}});WK.default=Uzq.default;var Yzq=KjA();Object.defineProperty(WK,"verifySlackRequest",{enumerable:!0,get:function(){return Yzq.verifySlackRequest}});Object.defineProperty(WK,"isValidSlackRequest",{enumerable:!0,get:function(){return Yzq.isValidSlackRequest}});var i9K=fR(DLq());WK.AwsLambdaReceiver=i9K.default;var a9K=fR(yMq());WK.ExpressReceiver=a9K.default;var d9K=fR(ZjA());WK.HTTPReceiver=d9K.default;var n9K=fR(GjA());WK.SocketModeReceiver=n9K.default;WK.HTTPModuleFunctions=N4A(JR());var s9K=jp();Object.defineProperty(WK,"HTTPResponseAck",{enumerable:!0,get:function(){return s9K.HTTPResponseAck}});var o9K=XjA();Object.defineProperty(WK,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return o9K.defaultProcessEventErrorHandler}});_4A(xY(),WK);_4A(oc(),WK);_4A(JjA(),WK);var r9K=S8A();Object.defineProperty(WK,"MemoryStore",{enumerable:!0,get:function(){return r9K.MemoryStore}});var t9K=Jp();Object.defineProperty(WK,"buildReceiverRoutes",{enumerable:!0,get:function(){return t9K.buildReceiverRoutes}});var e9K=P4A();Object.defineProperty(WK,"Assistant",{enumerable:!0,get:function(){return e9K.Assistant}});var AUK=Zzq();Object.defineProperty(WK,"WorkflowStep",{enumerable:!0,get:function(){return AUK.WorkflowStep}});var Qzq=FR();Object.defineProperty(WK,"MemoryInstallationStore",{enumerable:!0,get:function(){return Qzq.MemoryInstallationStore}});Object.defineProperty(WK,"FileInstallationStore",{enumerable:!0,get:function(){return Qzq.FileInstallationStore}});WK.types=N4A(O8A());WK.webApi=N4A(sc())});var f7A={name:"@interactive-inc/claude-funnel",version:"0.23.0",description:"Hub CLI that routes external events (Slack / GitHub / Discord) to Claude Code agents through subscription channels over MCP.",keywords:["bun","claude","claude-code","cli","discord","github","mcp","slack"],homepage:"https://github.com/interactive-inc/open-claude-funnel#readme",bugs:{url:"https://github.com/interactive-inc/open-claude-funnel/issues"},license:"MIT",author:"Interactive Inc.",repository:{type:"git",url:"git+https://github.com/interactive-inc/open-claude-funnel.git"},bin:{fnl:"./dist/bin.js",funnel:"./dist/bin.js"},files:["dist/**/*","funnel.schema.json","README.md","LICENSE"],type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./connectors/slack":{types:"./dist/connectors/slack.d.ts",import:"./dist/connectors/slack.js",default:"./dist/connectors/slack.js"},"./connectors/discord":{types:"./dist/connectors/discord.d.ts",import:"./dist/connectors/discord.js",default:"./dist/connectors/discord.js"},"./connectors/gh":{types:"./dist/connectors/gh.d.ts",import:"./dist/connectors/gh.js",default:"./dist/connectors/gh.js"},"./connectors/schedule":{types:"./dist/connectors/schedule.d.ts",import:"./dist/connectors/schedule.js",default:"./dist/connectors/schedule.js"},"./bin":"./dist/bin.js","./package.json":"./package.json"},publishConfig:{access:"public"},dependencies:{"@hono/zod-validator":"^0.8.0","@modelcontextprotocol/sdk":"^1.29.0","@opentui/core":"^0.2.12","@opentui/react":"^0.2.12","@slack/bolt":"^4.7.2","@slack/web-api":"^7.16.0","discord.js":"^14.26.4",hono:"^4.12.19",react:"^19.2.6",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@types/react":"^19.2.14","@typescript/native-preview":"^7.0.0-dev.20260516.1","vite-plus":"^0.1.21",vitest:"^4.1.6"},engines:{bun:">=1.3.0"},scripts:{prepack:"make build"}};var pK=class extends Error{res;status;constructor(A=500,q){super(q?.message,{cause:q?.cause});this.res=q?.res,this.status=A}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var c={};iG(c,{xor:()=>WHA,xid:()=>hJA,void:()=>XHA,uuidv7:()=>RJA,uuidv6:()=>DJA,uuidv4:()=>BJA,uuid:()=>wJA,util:()=>oq,url:()=>TJA,uppercase:()=>Yx,unknown:()=>g5,union:()=>fb,undefined:()=>YHA,ulid:()=>fJA,uint64:()=>$HA,uint32:()=>KHA,tuple:()=>fo,trim:()=>Hx,treeifyError:()=>wi,transform:()=>yb,toUpperCase:()=>Wx,toLowerCase:()=>Ex,toJSONSchema:()=>Gb,templateLiteral:()=>DHA,symbol:()=>UHA,superRefine:()=>Jr,success:()=>NHA,stringbool:()=>fHA,stringFormat:()=>sJA,string:()=>nP,strictObject:()=>HHA,startsWith:()=>Xx,slugify:()=>gx,size:()=>H5,setErrorMap:()=>DNq,set:()=>OHA,safeParseAsync:()=>jo,safeParse:()=>Go,safeEncodeAsync:()=>Lo,safeEncode:()=>go,safeDecodeAsync:()=>xo,safeDecode:()=>Vo,registry:()=>kS,regexes:()=>O8,regex:()=>$x,refine:()=>jr,record:()=>ho,readonly:()=>$r,property:()=>Ub,promise:()=>RHA,prettifyError:()=>Bi,preprocess:()=>yHA,prefault:()=>ro,positive:()=>Kb,pipe:()=>Vb,partialRecord:()=>VHA,parseAsync:()=>Xo,parse:()=>Qo,overwrite:()=>aG,optional:()=>oP,object:()=>JHA,number:()=>Mo,nullish:()=>PHA,nullable:()=>rP,null:()=>_o,normalize:()=>Jx,nonpositive:()=>Zb,nonoptional:()=>to,nonnegative:()=>$b,never:()=>Cb,negative:()=>Fb,nativeEnum:()=>MHA,nanoid:()=>vJA,nan:()=>_HA,multipleOf:()=>xE,minSize:()=>x4,minLength:()=>$J,mime:()=>jx,meta:()=>kHA,maxSize:()=>OE,maxLength:()=>E5,map:()=>xHA,mac:()=>cJA,lte:()=>M8,lt:()=>V4,lowercase:()=>Ux,looseRecord:()=>LHA,looseObject:()=>EHA,locales:()=>lP,literal:()=>zHA,length:()=>W5,lazy:()=>Qr,ksuid:()=>yJA,keyof:()=>jHA,jwt:()=>nJA,json:()=>hHA,iso:()=>xx,ipv6:()=>mJA,ipv4:()=>uJA,invertCodec:()=>BHA,intersection:()=>ko,int64:()=>ZHA,int32:()=>qHA,int:()=>gb,instanceof:()=>CHA,includes:()=>Qx,httpUrl:()=>SJA,hostname:()=>oJA,hex:()=>rJA,hash:()=>tJA,guid:()=>_JA,gte:()=>DQ,gt:()=>L4,globalRegistry:()=>rU,getErrorMap:()=>RNq,function:()=>THA,fromJSONSchema:()=>cHA,formatError:()=>bP,float64:()=>AHA,float32:()=>eJA,flattenError:()=>SP,file:()=>IHA,exactOptional:()=>io,enum:()=>hb,endsWith:()=>Gx,encodeAsync:()=>Eo,encode:()=>Jo,emoji:()=>bJA,email:()=>NJA,e164:()=>dJA,discriminatedUnion:()=>gHA,describe:()=>vHA,decodeAsync:()=>Wo,decode:()=>Ho,date:()=>GHA,custom:()=>bHA,cuid2:()=>CJA,cuid:()=>kJA,core:()=>UJ,config:()=>d$,coerce:()=>Er,codec:()=>wHA,clone:()=>wQ,cidrv6:()=>lJA,cidrv4:()=>pJA,check:()=>SHA,catch:()=>qr,boolean:()=>zo,bigint:()=>FHA,base64url:()=>aJA,base64:()=>iJA,array:()=>qN,any:()=>QHA,_function:()=>THA,_default:()=>so,_ZodString:()=>Lb,ZodXor:()=>So,ZodXID:()=>Nb,ZodVoid:()=>Ro,ZodUnknown:()=>Bo,ZodUnion:()=>FN,ZodUndefined:()=>Po,ZodUUID:()=>O4,ZodURL:()=>eP,ZodULID:()=>Pb,ZodType:()=>ZF,ZodTuple:()=>Co,ZodTransform:()=>po,ZodTemplateLiteral:()=>Ur,ZodSymbol:()=>Io,ZodSuccess:()=>eo,ZodStringFormat:()=>o1,ZodString:()=>zx,ZodSet:()=>uo,ZodRecord:()=>Ox,ZodRealError:()=>_0,ZodReadonly:()=>Zr,ZodPromise:()=>Xr,ZodPreprocess:()=>Fr,ZodPrefault:()=>oo,ZodPipe:()=>ZN,ZodOptional:()=>ub,ZodObject:()=>KN,ZodNumberFormat:()=>V5,ZodNumber:()=>Px,ZodNullable:()=>ao,ZodNull:()=>No,ZodNonOptional:()=>cb,ZodNever:()=>Do,ZodNanoID:()=>Mb,ZodNaN:()=>Kr,ZodMap:()=>yo,ZodMAC:()=>Oo,ZodLiteral:()=>co,ZodLazy:()=>Yr,ZodKSUID:()=>_b,ZodJWT:()=>vb,ZodIssueCode:()=>BNq,ZodIntersection:()=>vo,ZodISOTime:()=>Eb,ZodISODuration:()=>Wb,ZodISODateTime:()=>Jb,ZodISODate:()=>Hb,ZodIPv6:()=>Bb,ZodIPv4:()=>wb,ZodGUID:()=>sP,ZodFunction:()=>Gr,ZodFirstPartyTypeKind:()=>Hr,ZodFile:()=>mo,ZodExactOptional:()=>lo,ZodError:()=>_Nq,ZodEnum:()=>Mx,ZodEmoji:()=>Ob,ZodEmail:()=>xb,ZodE164:()=>bb,ZodDiscriminatedUnion:()=>bo,ZodDefault:()=>no,ZodDate:()=>AN,ZodCustomStringFormat:()=>Ix,ZodCustom:()=>UN,ZodCodec:()=>$N,ZodCatch:()=>Ar,ZodCUID2:()=>Ib,ZodCUID:()=>zb,ZodCIDRv6:()=>Rb,ZodCIDRv4:()=>Db,ZodBoolean:()=>Nx,ZodBigIntFormat:()=>kb,ZodBigInt:()=>_x,ZodBase64URL:()=>Sb,ZodBase64:()=>Tb,ZodArray:()=>To,ZodAny:()=>wo,TimePrecision:()=>Cn,NEVER:()=>Wi,$output:()=>Rn,$input:()=>Tn,$brand:()=>gi});var UJ={};iG(UJ,{version:()=>Pa,util:()=>oq,treeifyError:()=>wi,toJSONSchema:()=>Gb,toDotPath:()=>l7A,safeParseAsync:()=>Ri,safeParse:()=>Di,safeEncodeAsync:()=>BIq,safeEncode:()=>_Iq,safeDecodeAsync:()=>DIq,safeDecode:()=>wIq,registry:()=>kS,regexes:()=>O8,process:()=>D1,prettifyError:()=>Bi,parseAsync:()=>HS,parse:()=>JS,meta:()=>Vs,locales:()=>lP,isValidJWT:()=>JJA,isValidBase64URL:()=>jJA,isValidBase64:()=>aa,initializeContext:()=>ME,globalRegistry:()=>rU,globalConfig:()=>Q5,formatError:()=>bP,flattenError:()=>SP,finalize:()=>IE,extractDefs:()=>zE,encodeAsync:()=>PIq,encode:()=>zIq,describe:()=>gs,decodeAsync:()=>NIq,decode:()=>IIq,createToJSONSchemaMethod:()=>xs,createStandardJSONSchemaMethod:()=>Lx,config:()=>d$,clone:()=>wQ,_xor:()=>KNq,_xid:()=>aS,_void:()=>Ys,_uuidv7:()=>uS,_uuidv6:()=>yS,_uuidv4:()=>hS,_uuid:()=>fS,_url:()=>aP,_uppercase:()=>Yx,_unknown:()=>$s,_union:()=>qNq,_undefined:()=>Ks,_ulid:()=>iS,_uint64:()=>As,_uint32:()=>nn,_tuple:()=>$Nq,_trim:()=>Hx,_transform:()=>JNq,_toUpperCase:()=>Wx,_toLowerCase:()=>Ex,_templateLiteral:()=>MNq,_symbol:()=>qs,_superRefine:()=>Ws,_success:()=>VNq,_stringbool:()=>Ls,_stringFormat:()=>Vx,_string:()=>bn,_startsWith:()=>Xx,_slugify:()=>gx,_size:()=>H5,_set:()=>QNq,_safeParseAsync:()=>Kx,_safeParse:()=>qx,_safeEncodeAsync:()=>OS,_safeEncode:()=>LS,_safeDecodeAsync:()=>MS,_safeDecode:()=>xS,_regex:()=>$x,_refine:()=>Es,_record:()=>UNq,_readonly:()=>ONq,_property:()=>Ub,_promise:()=>INq,_positive:()=>Kb,_pipe:()=>xNq,_parseAsync:()=>Ax,_parse:()=>e2,_overwrite:()=>aG,_optional:()=>HNq,_number:()=>cn,_nullable:()=>ENq,_null:()=>Fs,_normalize:()=>Jx,_nonpositive:()=>Zb,_nonoptional:()=>gNq,_nonnegative:()=>$b,_never:()=>Us,_negative:()=>Fb,_nativeEnum:()=>GNq,_nanoid:()=>mS,_nan:()=>Gs,_multipleOf:()=>xE,_minSize:()=>x4,_minLength:()=>$J,_min:()=>DQ,_mime:()=>jx,_maxSize:()=>OE,_maxLength:()=>E5,_max:()=>M8,_map:()=>YNq,_mac:()=>kn,_lte:()=>M8,_lt:()=>V4,_lowercase:()=>Ux,_literal:()=>jNq,_length:()=>W5,_lazy:()=>zNq,_ksuid:()=>dS,_jwt:()=>qb,_isoTime:()=>yn,_isoDuration:()=>un,_isoDateTime:()=>fn,_isoDate:()=>hn,_ipv6:()=>sS,_ipv4:()=>nS,_intersection:()=>ZNq,_int64:()=>en,_int32:()=>dn,_int:()=>pn,_includes:()=>Qx,_guid:()=>iP,_gte:()=>DQ,_gt:()=>L4,_float64:()=>an,_float32:()=>ln,_file:()=>Js,_enum:()=>XNq,_endsWith:()=>Gx,_encodeAsync:()=>gS,_encode:()=>ES,_emoji:()=>cS,_email:()=>CS,_e164:()=>Ab,_discriminatedUnion:()=>FNq,_default:()=>WNq,_decodeAsync:()=>VS,_decode:()=>WS,_date:()=>Qs,_custom:()=>Hs,_cuid2:()=>lS,_cuid:()=>pS,_coercedString:()=>vn,_coercedNumber:()=>mn,_coercedDate:()=>Xs,_coercedBoolean:()=>on,_coercedBigint:()=>tn,_cidrv6:()=>rS,_cidrv4:()=>oS,_check:()=>MJA,_catch:()=>LNq,_boolean:()=>sn,_bigint:()=>rn,_base64url:()=>eS,_base64:()=>tS,_array:()=>js,_any:()=>Zs,TimePrecision:()=>Cn,NEVER:()=>Wi,JSONSchemaGenerator:()=>Fo,JSONSchema:()=>zJA,Doc:()=>NS,$output:()=>Rn,$input:()=>Tn,$constructor:()=>nA,$brand:()=>gi,$ZodXor:()=>Gd,$ZodXID:()=>ka,$ZodVoid:()=>Ud,$ZodUnknown:()=>Zd,$ZodUnion:()=>hP,$ZodUndefined:()=>qd,$ZodUUID:()=>wa,$ZodURL:()=>Da,$ZodULID:()=>va,$ZodType:()=>yK,$ZodTuple:()=>SS,$ZodTransform:()=>xd,$ZodTemplateLiteral:()=>Rd,$ZodSymbol:()=>Ad,$ZodSuccess:()=>Nd,$ZodStringFormat:()=>s1,$ZodString:()=>J5,$ZodSet:()=>Wd,$ZodRegistry:()=>Sn,$ZodRecord:()=>Hd,$ZodRealError:()=>N0,$ZodReadonly:()=>Dd,$ZodPromise:()=>Sd,$ZodPreprocess:()=>Bd,$ZodPrefault:()=>Id,$ZodPipe:()=>vS,$ZodOptional:()=>bS,$ZodObjectJIT:()=>Xd,$ZodObject:()=>WJA,$ZodNumberFormat:()=>ta,$ZodNumber:()=>RS,$ZodNullable:()=>Md,$ZodNull:()=>Kd,$ZodNonOptional:()=>Pd,$ZodNever:()=>$d,$ZodNanoID:()=>Ta,$ZodNaN:()=>wd,$ZodMap:()=>Ed,$ZodMAC:()=>pa,$ZodLiteral:()=>Vd,$ZodLazy:()=>bd,$ZodKSUID:()=>Ca,$ZodJWT:()=>oa,$ZodIntersection:()=>Jd,$ZodISOTime:()=>ya,$ZodISODuration:()=>ua,$ZodISODateTime:()=>fa,$ZodISODate:()=>ha,$ZodIPv6:()=>ma,$ZodIPv4:()=>ca,$ZodGUID:()=>_a,$ZodFunction:()=>Td,$ZodFile:()=>Ld,$ZodExactOptional:()=>Od,$ZodError:()=>TP,$ZodEnum:()=>gd,$ZodEncodeError:()=>X5,$ZodEmoji:()=>Ra,$ZodEmail:()=>Ba,$ZodE164:()=>sa,$ZodDiscriminatedUnion:()=>jd,$ZodDefault:()=>zd,$ZodDate:()=>Yd,$ZodCustomStringFormat:()=>ra,$ZodCustom:()=>vd,$ZodCodec:()=>yP,$ZodCheckUpperCase:()=>Va,$ZodCheckStringFormat:()=>Fx,$ZodCheckStartsWith:()=>xa,$ZodCheckSizeEquals:()=>ja,$ZodCheckRegex:()=>Wa,$ZodCheckProperty:()=>Ma,$ZodCheckOverwrite:()=>Ia,$ZodCheckNumberFormat:()=>Ya,$ZodCheckMultipleOf:()=>Ua,$ZodCheckMinSize:()=>Ga,$ZodCheckMinLength:()=>Ha,$ZodCheckMimeType:()=>za,$ZodCheckMaxSize:()=>Xa,$ZodCheckMaxLength:()=>Ja,$ZodCheckLowerCase:()=>ga,$ZodCheckLessThan:()=>IS,$ZodCheckLengthEquals:()=>Ea,$ZodCheckIncludes:()=>La,$ZodCheckGreaterThan:()=>PS,$ZodCheckEndsWith:()=>Oa,$ZodCheckBigIntFormat:()=>Qa,$ZodCheck:()=>XZ,$ZodCatch:()=>_d,$ZodCUID2:()=>ba,$ZodCUID:()=>Sa,$ZodCIDRv6:()=>ia,$ZodCIDRv4:()=>la,$ZodBoolean:()=>fP,$ZodBigIntFormat:()=>ea,$ZodBigInt:()=>TS,$ZodBase64URL:()=>na,$ZodBase64:()=>da,$ZodAsyncError:()=>g4,$ZodArray:()=>Qd,$ZodAny:()=>Fd});var h7A,Wi=Object.freeze({status:"aborted"});function nA(A,q,K){function F(Y,X){if(!Y._zod)Object.defineProperty(Y,"_zod",{value:{def:X,constr:U,traits:new Set},enumerable:!1});if(Y._zod.traits.has(A))return;Y._zod.traits.add(A),q(Y,X);let j=U.prototype,J=Object.keys(j);for(let E=0;E<J.length;E++){let W=J[E];if(!(W in Y))Y[W]=j[W].bind(Y)}}let Z=K?.Parent??Object;class $ extends Z{}Object.defineProperty($,"name",{value:A});function U(Y){var X;let j=K?.Parent?new $:this;F(j,Y),(X=j._zod).deferred??(X.deferred=[]);for(let J of j._zod.deferred)J();return j}return Object.defineProperty(U,"init",{value:F}),Object.defineProperty(U,Symbol.hasInstance,{value:(Y)=>{if(K?.Parent&&Y instanceof K.Parent)return!0;return Y?._zod?.traits?.has(A)}}),Object.defineProperty(U,"name",{value:A}),U}var gi=Symbol("zod_brand");class g4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class X5 extends Error{constructor(A){super(`Encountered unidirectional transform during encode: ${A}`);this.name="ZodEncodeError"}}(h7A=globalThis).__zod_globalConfig??(h7A.__zod_globalConfig={});var Q5=globalThis.__zod_globalConfig;function d$(A){if(A)Object.assign(Q5,A);return Q5}var oq={};iG(oq,{unwrapMessage:()=>NP,uint8ArrayToHex:()=>OIq,uint8ArrayToBase64url:()=>LIq,uint8ArrayToBase64:()=>c7A,stringifyPrimitive:()=>pq,slugify:()=>xi,shallowClone:()=>Mi,safeExtend:()=>JIq,required:()=>WIq,randomString:()=>$Iq,propertyKeyTypes:()=>BP,promiseAllObject:()=>ZIq,primitiveTypes:()=>zi,prefixIssues:()=>P0,pick:()=>XIq,partial:()=>EIq,parsedType:()=>nq,optionalKeys:()=>Ii,omit:()=>GIq,objectClone:()=>qIq,numKeys:()=>UIq,nullish:()=>WE,normalizeParams:()=>A6,mergeDefs:()=>ZJ,merge:()=>HIq,jsonStringifyReplacer:()=>o2,joinValues:()=>Qq,issue:()=>t2,isPlainObject:()=>VE,isObject:()=>G5,hexToUint8Array:()=>xIq,getSizableOrigin:()=>DP,getParsedType:()=>YIq,getLengthableOrigin:()=>RP,getEnumValues:()=>_P,getElementAtPath:()=>FIq,floatSafeRemainder:()=>Li,finalizeIssue:()=>BQ,extend:()=>jIq,explicitlyAborted:()=>_i,escapeRegex:()=>PX,esc:()=>GS,defineLazy:()=>NF,createTransparentProxy:()=>QIq,cloneDef:()=>KIq,clone:()=>wQ,cleanRegex:()=>wP,cleanEnum:()=>gIq,captureStackTrace:()=>jS,cached:()=>r2,base64urlToUint8Array:()=>VIq,base64ToUint8Array:()=>u7A,assignProp:()=>gE,assertNotEqual:()=>rzq,assertNever:()=>ezq,assertIs:()=>tzq,assertEqual:()=>ozq,assert:()=>AIq,allowsEval:()=>Oi,aborted:()=>LE,NUMBER_FORMAT_RANGES:()=>Pi,Class:()=>m7A,BIGINT_FORMAT_RANGES:()=>Ni});function ozq(A){return A}function rzq(A){return A}function tzq(A){}function ezq(A){throw Error("Unexpected value in exhaustive check")}function AIq(A){}function _P(A){let q=Object.values(A).filter((F)=>typeof F==="number");return Object.entries(A).filter(([F,Z])=>q.indexOf(+F)===-1).map(([F,Z])=>Z)}function Qq(A,q="|"){return A.map((K)=>pq(K)).join(q)}function o2(A,q){if(typeof q==="bigint")return q.toString();return q}function r2(A){return{get value(){{let K=A();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function WE(A){return A===null||A===void 0}function wP(A){let q=A.startsWith("^")?1:0,K=A.endsWith("$")?A.length-1:A.length;return A.slice(q,K)}function Li(A,q){let K=A/q,F=Math.round(K),Z=Number.EPSILON*Math.max(Math.abs(K),1);if(Math.abs(K-F)<Z)return 0;return K-F}var y7A=Symbol("evaluating");function NF(A,q,K){let F=void 0;Object.defineProperty(A,q,{get(){if(F===y7A)return;if(F===void 0)F=y7A,F=K();return F},set(Z){Object.defineProperty(A,q,{value:Z})},configurable:!0})}function qIq(A){return Object.create(Object.getPrototypeOf(A),Object.getOwnPropertyDescriptors(A))}function gE(A,q,K){Object.defineProperty(A,q,{value:K,writable:!0,enumerable:!0,configurable:!0})}function ZJ(...A){let q={};for(let K of A){let F=Object.getOwnPropertyDescriptors(K);Object.assign(q,F)}return Object.defineProperties({},q)}function KIq(A){return ZJ(A._zod.def)}function FIq(A,q){if(!q)return A;return q.reduce((K,F)=>K?.[F],A)}function ZIq(A){let q=Object.keys(A),K=q.map((F)=>A[F]);return Promise.all(K).then((F)=>{let Z={};for(let $=0;$<q.length;$++)Z[q[$]]=F[$];return Z})}function $Iq(A=10){let K="";for(let F=0;F<A;F++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function GS(A){return JSON.stringify(A)}function xi(A){return A.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var jS="captureStackTrace"in Error?Error.captureStackTrace:(...A)=>{};function G5(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var Oi=r2(()=>{if(Q5.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(A){return!1}});function VE(A){if(G5(A)===!1)return!1;let q=A.constructor;if(q===void 0)return!0;if(typeof q!=="function")return!0;let K=q.prototype;if(G5(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function Mi(A){if(VE(A))return{...A};if(Array.isArray(A))return[...A];if(A instanceof Map)return new Map(A);if(A instanceof Set)return new Set(A);return A}function UIq(A){let q=0;for(let K in A)if(Object.prototype.hasOwnProperty.call(A,K))q++;return q}var YIq=(A)=>{let q=typeof A;switch(q){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(A)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(A))return"array";if(A===null)return"null";if(A.then&&typeof A.then==="function"&&A.catch&&typeof A.catch==="function")return"promise";if(typeof Map<"u"&&A instanceof Map)return"map";if(typeof Set<"u"&&A instanceof Set)return"set";if(typeof Date<"u"&&A instanceof Date)return"date";if(typeof File<"u"&&A instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${q}`)}},BP=new Set(["string","number","symbol"]),zi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function PX(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wQ(A,q,K){let F=new A._zod.constr(q??A._zod.def);if(!q||K?.parent)F._zod.parent=A;return F}function A6(A){let q=A;if(!q)return{};if(typeof q==="string")return{error:()=>q};if(q?.message!==void 0){if(q?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");q.error=q.message}if(delete q.message,typeof q.error==="string")return{...q,error:()=>q.error};return q}function QIq(A){let q;return new Proxy({},{get(K,F,Z){return q??(q=A()),Reflect.get(q,F,Z)},set(K,F,Z,$){return q??(q=A()),Reflect.set(q,F,Z,$)},has(K,F){return q??(q=A()),Reflect.has(q,F)},deleteProperty(K,F){return q??(q=A()),Reflect.deleteProperty(q,F)},ownKeys(K){return q??(q=A()),Reflect.ownKeys(q)},getOwnPropertyDescriptor(K,F){return q??(q=A()),Reflect.getOwnPropertyDescriptor(q,F)},defineProperty(K,F,Z){return q??(q=A()),Reflect.defineProperty(q,F,Z)}})}function pq(A){if(typeof A==="bigint")return A.toString()+"n";if(typeof A==="string")return`"${A}"`;return`${A}`}function Ii(A){return Object.keys(A).filter((q)=>{return A[q]._zod.optin==="optional"&&A[q]._zod.optout==="optional"})}var Pi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ni={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function XIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;U[Y]=K.shape[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function GIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={...A._zod.def.shape};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;delete U[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function jIq(A,q){if(!VE(q))throw Error("Invalid input to extend: expected a plain object");let K=A._zod.def.checks;if(K&&K.length>0){let $=A._zod.def.shape;for(let U in q)if(Object.getOwnPropertyDescriptor($,U)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Z=ZJ(A._zod.def,{get shape(){let $={...A._zod.def.shape,...q};return gE(this,"shape",$),$}});return wQ(A,Z)}function JIq(A,q){if(!VE(q))throw Error("Invalid input to safeExtend: expected a plain object");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q};return gE(this,"shape",F),F}});return wQ(A,K)}function HIq(A,q){if(A._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q._zod.def.shape};return gE(this,"shape",F),F},get catchall(){return q._zod.def.catchall},checks:q._zod.def.checks??[]});return wQ(A,K)}function EIq(A,q,K){let Z=q._zod.def.checks;if(Z&&Z.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let U=ZJ(q._zod.def,{get shape(){let Y=q._zod.def.shape,X={...Y};if(K)for(let j in K){if(!(j in Y))throw Error(`Unrecognized key: "${j}"`);if(!K[j])continue;X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j]}else for(let j in Y)X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j];return gE(this,"shape",X),X},checks:[]});return wQ(q,U)}function WIq(A,q,K){let F=ZJ(q._zod.def,{get shape(){let Z=q._zod.def.shape,$={...Z};if(K)for(let U in K){if(!(U in $))throw Error(`Unrecognized key: "${U}"`);if(!K[U])continue;$[U]=new A({type:"nonoptional",innerType:Z[U]})}else for(let U in Z)$[U]=new A({type:"nonoptional",innerType:Z[U]});return gE(this,"shape",$),$}});return wQ(q,F)}function LE(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue!==!0)return!0;return!1}function _i(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue===!1)return!0;return!1}function P0(A,q){return q.map((K)=>{var F;return(F=K).path??(F.path=[]),K.path.unshift(A),K})}function NP(A){return typeof A==="string"?A:A?.message}function BQ(A,q,K){let F=A.message?A.message:NP(A.inst?._zod.def?.error?.(A))??NP(q?.error?.(A))??NP(K.customError?.(A))??NP(K.localeError?.(A))??"Invalid input",{inst:Z,continue:$,input:U,...Y}=A;if(Y.path??(Y.path=[]),Y.message=F,q?.reportInput)Y.input=U;return Y}function DP(A){if(A instanceof Set)return"set";if(A instanceof Map)return"map";if(A instanceof File)return"file";return"unknown"}function RP(A){if(Array.isArray(A))return"array";if(typeof A==="string")return"string";return"unknown"}function nq(A){let q=typeof A;switch(q){case"number":return Number.isNaN(A)?"nan":"number";case"object":{if(A===null)return"null";if(Array.isArray(A))return"array";let K=A;if(K&&Object.getPrototypeOf(K)!==Object.prototype&&"constructor"in K&&K.constructor)return K.constructor.name}}return q}function t2(...A){let[q,K,F]=A;if(typeof q==="string")return{message:q,code:"custom",input:K,inst:F};return{...q}}function gIq(A){return Object.entries(A).filter(([q,K])=>{return Number.isNaN(Number.parseInt(q,10))}).map((q)=>q[1])}function u7A(A){let q=atob(A),K=new Uint8Array(q.length);for(let F=0;F<q.length;F++)K[F]=q.charCodeAt(F);return K}function c7A(A){let q="";for(let K=0;K<A.length;K++)q+=String.fromCharCode(A[K]);return btoa(q)}function VIq(A){let q=A.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-q.length%4)%4);return u7A(q+K)}function LIq(A){return c7A(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xIq(A){let q=A.replace(/^0x/,"");if(q.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(q.length/2);for(let F=0;F<q.length;F+=2)K[F/2]=Number.parseInt(q.slice(F,F+2),16);return K}function OIq(A){return Array.from(A).map((q)=>q.toString(16).padStart(2,"0")).join("")}class m7A{constructor(...A){}}var p7A=(A,q)=>{A.name="$ZodError",Object.defineProperty(A,"_zod",{value:A._zod,enumerable:!1}),Object.defineProperty(A,"issues",{value:q,enumerable:!1}),A.message=JSON.stringify(q,o2,2),Object.defineProperty(A,"toString",{value:()=>A.message,enumerable:!1})},TP=nA("$ZodError",p7A),N0=nA("$ZodError",p7A,{Parent:Error});function SP(A,q=(K)=>K.message){let K={},F=[];for(let Z of A.issues)if(Z.path.length>0)K[Z.path[0]]=K[Z.path[0]]||[],K[Z.path[0]].push(q(Z));else F.push(q(Z));return{formErrors:F,fieldErrors:K}}function bP(A,q=(K)=>K.message){let K={_errors:[]},F=(Z,$=[])=>{for(let U of Z.issues)if(U.code==="invalid_union"&&U.errors.length)U.errors.map((Y)=>F({issues:Y},[...$,...U.path]));else if(U.code==="invalid_key")F({issues:U.issues},[...$,...U.path]);else if(U.code==="invalid_element")F({issues:U.issues},[...$,...U.path]);else{let Y=[...$,...U.path];if(Y.length===0)K._errors.push(q(U));else{let X=K,j=0;while(j<Y.length){let J=Y[j];if(j!==Y.length-1)X[J]=X[J]||{_errors:[]};else X[J]=X[J]||{_errors:[]},X[J]._errors.push(q(U));X=X[J],j++}}}};return F(A),K}function wi(A,q=(K)=>K.message){let K={errors:[]},F=(Z,$=[])=>{var U,Y;for(let X of Z.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((j)=>F({issues:j},[...$,...X.path]));else if(X.code==="invalid_key")F({issues:X.issues},[...$,...X.path]);else if(X.code==="invalid_element")F({issues:X.issues},[...$,...X.path]);else{let j=[...$,...X.path];if(j.length===0){K.errors.push(q(X));continue}let J=K,E=0;while(E<j.length){let W=j[E],g=E===j.length-1;if(typeof W==="string")J.properties??(J.properties={}),(U=J.properties)[W]??(U[W]={errors:[]}),J=J.properties[W];else J.items??(J.items=[]),(Y=J.items)[W]??(Y[W]={errors:[]}),J=J.items[W];if(g)J.errors.push(q(X));E++}}};return F(A),K}function l7A(A){let q=[],K=A.map((F)=>typeof F==="object"?F.key:F);for(let F of K)if(typeof F==="number")q.push(`[${F}]`);else if(typeof F==="symbol")q.push(`[${JSON.stringify(String(F))}]`);else if(/[^\w$]/.test(F))q.push(`[${JSON.stringify(F)}]`);else{if(q.length)q.push(".");q.push(F)}return q.join("")}function Bi(A){let q=[],K=[...A.issues].sort((F,Z)=>(F.path??[]).length-(Z.path??[]).length);for(let F of K)if(q.push(`\u2716 ${F.message}`),F.path?.length)q.push(` \u2192 at ${l7A(F.path)}`);return q.join(`
|
|
907
|
+
*/var ap=Yxq(),X9K=gA("events").EventEmitter,IMq=Xxq(),PMq=JOq(),NMq=F4A(),_Mq=cOq(),wMq=OMq();ZG=BMq.exports=G9K;function G9K(){var A=function(q,K,F){A.handle(q,K,F)};return IMq(A,X9K.prototype,!1),IMq(A,PMq,!1),A.request=Object.create(_Mq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.response=Object.create(wMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.init(),A}ZG.application=PMq;ZG.request=_Mq;ZG.response=wMq;ZG.Route=NMq.Route;ZG.Router=NMq;ZG.json=ap.json;ZG.raw=ap.raw;ZG.static=zMq();ZG.text=ap.text;ZG.urlencoded=ap.urlencoded});var yMq=I((b$)=>{var j9K=b$&&b$.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),J9K=b$&&b$.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),SMq=b$&&b$.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))j9K(q,A,K)}return J9K(q,A),q},dp=b$&&b$.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(b$,"__esModule",{value:!0});b$.buildBodyParserMiddleware=b$.verifySignatureAndParseBody=b$.verifySignatureAndParseRawBody=b$.respondToUrlVerification=b$.respondToSslCheck=void 0;var H9K=dp(gA("crypto")),E9K=gA("http"),W9K=gA("https"),g9K=dp(gA("querystring")),RMq=gY(),V9K=FR(),TMq=SMq(DMq()),L9K=dp(Qp()),x9K=dp(Xp()),Z7=xY(),nz=SMq(JR()),O9K=jp(),M9K=Hp(),z9K=["ALPNProtocols","clientCertEngine","enableTrace","handshakeTimeout","rejectUnauthorized","requestCert","sessionTimeout","SNICallback","ticketKeys","pskCallback","pskIdentityHint","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext"],z4A="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",I9K=(A,q,K)=>{if(A.body?.ssl_check){q.send();return}K()};b$.respondToSslCheck=I9K;var P9K=(A,q,K)=>{if(A.body?.type&&A.body.type==="url_verification"){q.json({challenge:A.body.challenge});return}K()};b$.respondToUrlVerification=P9K;class bMq{app;server;bolt;logger;processBeforeResponse;signatureVerification;router;installer=void 0;installerOptions;customPropertiesExtractor;dispatchErrorHandler;processEventErrorHandler;unhandledRequestHandler;unhandledRequestTimeoutMillis;constructor({signingSecret:A="",logger:q=void 0,logLevel:K=RMq.LogLevel.INFO,endpoints:F={events:"/slack/events"},processBeforeResponse:Z=!1,signatureVerification:$=!0,clientId:U=void 0,clientSecret:Y=void 0,stateSecret:X=void 0,redirectUri:j=void 0,installationStore:J=void 0,scopes:E=void 0,installerOptions:W={},app:g=void 0,router:L=void 0,customPropertiesExtractor:M=(v)=>({}),dispatchErrorHandler:O=nz.defaultAsyncDispatchErrorHandler,processEventErrorHandler:_=nz.defaultProcessEventErrorHandler,unhandledRequestHandler:R=nz.defaultUnhandledRequestHandler,unhandledRequestTimeoutMillis:T=3001}){if(this.app=g!==void 0?g:(0,TMq.default)(),typeof q<"u")this.logger=q;else this.logger=new RMq.ConsoleLogger,this.logger.setLevel(K);this.signatureVerification=$;let y=[this.signatureVerification?vMq(this.logger,A):CMq(this.logger),b$.respondToSslCheck,b$.respondToUrlVerification,this.requestHandler.bind(this)];this.processBeforeResponse=Z;let i=typeof F==="string"?[F]:Object.values(F);this.router=L!==void 0?L:(0,TMq.Router)();for(let n of i)this.router.post(n,...y);if(this.customPropertiesExtractor=M,this.dispatchErrorHandler=O,this.processEventErrorHandler=_,this.unhandledRequestHandler=R,this.unhandledRequestTimeoutMillis=T,(0,M9K.verifyRedirectOpts)({redirectUri:j,redirectUriPath:W.redirectUriPath}),U!==void 0&&Y!==void 0&&(W.stateVerification===!1||X!==void 0||W.stateStore!==void 0))this.installer=new V9K.InstallProvider({clientId:U,clientSecret:Y,stateSecret:X,installationStore:J,logLevel:K,logger:q,directInstall:W.directInstall,stateStore:W.stateStore,stateVerification:W.stateVerification,legacyStateVerification:W.legacyStateVerification,stateCookieName:W.stateCookieName,stateCookieExpirationSeconds:W.stateCookieExpirationSeconds,renderHtmlForInstallPath:W.renderHtmlForInstallPath,authVersion:W.authVersion??"v2",clientOptions:W.clientOptions,authorizationUrl:W.authorizationUrl});let l={metadata:W.metadata,scopes:E??[],userScopes:W.userScopes,redirectUri:j};if(this.installer!==void 0){let{installer:n}=this,a=W.redirectUriPath===void 0?"/slack/oauth_redirect":W.redirectUriPath,{callbackOptions:qA,stateVerification:JA}=W;this.router.use(a,async(sA,_A)=>{try{if(JA===!1)await n.handleCallback(sA,_A,qA,l);else await n.handleCallback(sA,_A,qA)}catch(zA){await this.dispatchErrorHandler({error:zA,logger:this.logger,request:sA,response:_A})}});let VA=W.installPath===void 0?"/slack/install":W.installPath,{installPathOptions:mA}=W;this.router.get(VA,async(sA,_A,zA)=>{try{try{await n.handleInstallPath(sA,_A,mA,l)}catch(e){zA(e)}}catch(e){await this.dispatchErrorHandler({error:e,logger:this.logger,request:sA,response:_A})}})}this.app.use(this.router)}async requestHandler(A,q){let K=new O9K.HTTPResponseAck({logger:this.logger,processBeforeResponse:this.processBeforeResponse,unhandledRequestHandler:this.unhandledRequestHandler,unhandledRequestTimeoutMillis:this.unhandledRequestTimeoutMillis,httpRequest:A,httpRequestBody:A.body,httpResponse:q}),F={body:A.body,ack:K.bind(),retryNum:nz.extractRetryNumFromHTTPRequest(A),retryReason:nz.extractRetryReasonFromHTTPRequest(A),customProperties:this.customPropertiesExtractor(A)};try{if(await this.bolt?.processEvent(F),K.storedResponse!==void 0)nz.buildContentResponse(q,K.storedResponse),this.logger.debug("stored response sent")}catch(Z){if(await this.processEventErrorHandler({error:Z,logger:this.logger,request:A,response:q,storedResponse:K.storedResponse}))K.ack()}}init(A){this.bolt=A}start(A,q={}){let K=E9K.createServer;if(Object.keys(q).filter((F)=>z9K.includes(F)).length>0)K=W9K.createServer;if(this.server!==void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be started because it was already started."));return this.server=K(q,this.app),new Promise((F,Z)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.on("error",($)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.close(),Z($)}),this.server.on("close",()=>{this.server=void 0}),this.server.listen(A,()=>{if(this.server===void 0)return Z(new Z7.ReceiverInconsistentStateError(z4A));return F(this.server)})})}stop(){if(this.server===void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be stopped because it was not started."));return new Promise((A,q)=>{this.server?.close((K)=>{if(K!==void 0)return q(K);return this.server=void 0,A()})})}}b$.default=bMq;function N9K(A,q){return vMq(A,q)}b$.verifySignatureAndParseRawBody=N9K;function vMq(A,q){return async(K,F,Z)=>{let $=await hMq(K);try{K.body=kMq(typeof q==="string"?q:await q(),$,K.headers)}catch(U){if(U){if(U instanceof Z7.ReceiverAuthenticityError){I4A(A,"Request verification failed",U),F.status(401).send();return}I4A(A,"Parsing request body failed",U),F.status(400).send();return}}Z()}}function I4A(A,q,K){let F="code"in K?`${q} (code: ${K.code}, message: ${K.message})`:`${q} (error: ${K})`;A.warn(F)}function _9K(A,q,K,F){if(K===void 0||F===void 0)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Some headers are missing.");let Z=Number(F);if(Number.isNaN(Z))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is invalid.");let $=Math.floor(Date.now()/1000)-300;if(Z<$)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is too old.");let U=H9K.default.createHmac("sha256",A),[Y,X]=K.split("=");if(U.update(`${Y}:${Z}:${q}`),!(0,x9K.default)(X,U.digest("hex")))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function kMq(A,q,K){let{"x-slack-signature":F,"x-slack-request-timestamp":Z,"content-type":$}=K;return _9K(A,q,F,Z),fMq(q,$)}b$.verifySignatureAndParseBody=kMq;function CMq(A){return async(q,K,F)=>{let Z=await hMq(q);try{let{"content-type":$}=q.headers;q.body=fMq(Z,$)}catch($){if($){I4A(A,"Parsing request body failed",$),K.status(400).send();return}}F()}}b$.buildBodyParserMiddleware=CMq;function fMq(A,q){if(q==="application/x-www-form-urlencoded"){let K=g9K.default.parse(A);if(typeof K.payload==="string")return JSON.parse(K.payload);return K}return JSON.parse(A)}async function hMq(A){if("rawBody"in A&&A.rawBody)return Promise.resolve(A.rawBody.toString());return(await(0,L9K.default)(A)).toString()}});var lMq=I((mMq)=>{Object.defineProperty(mMq,"__esModule",{value:!0});mMq.DefaultThreadContextStore=void 0;var uMq=P4A();class cMq{context={};async get(A){let{context:q,client:K,payload:F,logger:Z}=A;if(Z.debug("DefaultAssistantThreadStore: get method called"),this.context.channel_id)return this.context;let{channelId:$,threadTs:U}=(0,uMq.extractThreadInfo)(F),Y=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!Y.messages)return{};let X=Y.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);return(X?.metadata?X.metadata.event_payload:null)||{}}async save(A){let{context:q,client:K,payload:F,logger:Z}=A,{channelId:$,threadTs:U,context:Y}=(0,uMq.extractThreadInfo)(F);Z.debug("DefaultAssistantThreadStore: save method called");let X=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!X.messages)return;let j=X.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);if(j?.ts){let J={channel:$,ts:j.ts,text:j.text,blocks:j.blocks?j.blocks:[],metadata:{event_type:"assistant_thread_context",event_payload:Y}};await K.chat.update(J)}this.context=Y}}mMq.DefaultThreadContextStore=cMq});var P4A=I((l9)=>{var w9K=l9&&l9.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(l9,"__esModule",{value:!0});l9.extractThreadInfo=l9.processAssistantMiddleware=l9.validate=l9.isAssistantMessage=l9.matchesConstraints=l9.isAssistantEvent=l9.enrichAssistantArgs=l9.Assistant=void 0;var B9K=lMq(),iMq=T8A(),SL=xY(),np=rc(),D9K=w9K(tc()),R9K=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class aMq{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor(A){rMq(A);let{threadContextStore:q=new B9K.DefaultThreadContextStore,threadStarted:K,threadContextChanged:F=($)=>q.save($),userMessage:Z}=A;this.threadContextStore=q,this.threadStarted=Array.isArray(K)?K:[K],this.threadContextChanged=Array.isArray(F)?F:[F],this.userMessage=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(nMq(A)&&sMq(A))return this.processEvent(A);return A.next()}}async processEvent(A){let{payload:q}=A,K=dMq(this.threadContextStore,A),F=this.getAssistantMiddleware(q);return tMq(K,F)}getAssistantMiddleware(A){switch(A.type){case"assistant_thread_started":return this.threadStarted;case"assistant_thread_context_changed":return this.threadContextChanged;case"message":return this.userMessage;default:return[]}}}l9.Assistant=aMq;function dMq(A,q){let{next:K,...F}=q,Z={...F};return Z.getThreadContext=()=>A.get(q),Z.saveThreadContext=()=>A.save(q),Z.say=T9K(Z),Z.sayStream=S9K(Z),Z.setStatus=b9K(Z),Z.setSuggestedPrompts=v9K(Z),Z.setTitle=k9K(Z),Z}l9.enrichAssistantArgs=dMq;function nMq(A){return R9K.has(A.payload.type)}l9.isAssistantEvent=nMq;function sMq(A){return A.payload.type==="message"?oMq(A.payload):!0}l9.matchesConstraints=sMq;function oMq(A){let q="channel"in A&&"thread_ts"in A,K="channel_type"in A&&A.channel_type==="im"&&(!("subtype"in A)||A.subtype==="file_share"||A.subtype===void 0);return q&&K}l9.isAssistantMessage=oMq;function rMq(A){if(typeof A!=="object")throw new SL.AssistantInitializationError("Assistant expects a configuration object as the argument");let q=["threadStarted","userMessage"],K=[];for(let Z of q)if(A[Z]===void 0)K.push(Z);if(K.length>0){let Z=`Assistant is missing required keys: ${K.join(", ")}`;throw new SL.AssistantInitializationError(Z)}let F=["threadStarted","userMessage"];if("threadContextChanged"in A)F.push("threadContextChanged");for(let Z of F)if(typeof A[Z]!=="function"&&!Array.isArray(A[Z])){let $=`Assistant ${Z} property must be a function or an array of functions`;throw new SL.AssistantInitializationError($)}if(A.threadContextStore){if(typeof A.threadContextStore!=="object")throw new SL.AssistantInitializationError("Assistant expects threadContextStore to be a configuration object");let Z=["get","save"],$=[];for(let Y of Z)if(A.threadContextStore&&A.threadContextStore[Y]===void 0)$.push(Y);if($.length>0){let Y=`threadContextStore is missing required keys: ${$.join(", ")}`;throw new SL.AssistantInitializationError(Y)}let U=["get","save"];for(let Y of U)if(A.threadContextStore&&typeof A.threadContextStore[Y]!=="function"){let X=`threadContextStore ${Y} property must be a function`;throw new SL.AssistantInitializationError(X)}}}l9.validate=rMq;async function tMq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,D9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}l9.processAssistantMiddleware=tMq;function T9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z,context:$}=sz(K);return async(U)=>{let Y=$.channel_id?$:await A.getThreadContext(),X=typeof U==="string"?{text:U,channel:F,thread_ts:Z}:{...U,channel:F,thread_ts:Z};if(Y||X.metadata)X.metadata={event_type:X.metadata?.event_type??"assistant_thread_context",event_payload:{...Y,...X.metadata?.event_payload??{}}};return q.chat.postMessage(X)}}function S9K(A){let{client:q,context:K,payload:F}=A,{channelId:Z,threadTs:$}=sz(F);return(0,iMq.createSayStream)(q,K,Z,$)}function b9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return(0,iMq.createSetStatus)(q,F,Z)}function v9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>{let{prompts:U,title:Y}=$;return q.assistant.threads.setSuggestedPrompts({channel_id:F,thread_ts:Z,prompts:U,title:Y})}}function k9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>q.assistant.threads.setTitle({channel_id:F,thread_ts:Z,title:$})}function sz(A){let q={};if("assistant_thread"in A&&(0,np.isRecord)(A.assistant_thread)){if((0,np.isRecord)(A.assistant_thread.context))q=A.assistant_thread.context}let K=(0,np.extractEventChannelId)(A),F=(0,np.extractEventThreadTs)(A);if(!K||!F){let Z=[];if(!K)Z.push("channel_id");if(!F)Z.push("thread_ts");throw new SL.AssistantMissingPropertyError(`Assistant message event is missing required properties: ${Z.join(", ")}`)}return{channelId:K,threadTs:F,context:q}}l9.extractThreadInfo=sz});var Zzq=I((F8)=>{var C9K=F8&&F8.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(F8,"__esModule",{value:!0});F8.prepareStepArgs=F8.isStepEvent=F8.processStepMiddleware=F8.validate=F8.WorkflowStep=void 0;var sp=xY(),f9K=C9K(tc()),h9K=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class eMq{callbackId;edit;save;execute;constructor(A,q){Azq(A,q);let{save:K,edit:F,execute:Z}=q;this.callbackId=A,this.save=Array.isArray(K)?K:[K],this.edit=Array.isArray(F)?F:[F],this.execute=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(Kzq(A)&&this.matchesConstraints(A))return this.processEvent(A);return A.next()}}matchesConstraints(A){return A.payload.callback_id===this.callbackId}async processEvent(A){let{payload:q}=A,K=Fzq(A),F=this.getStepMiddleware(q);return qzq(K,F)}getStepMiddleware(A){switch(A.type){case"workflow_step_edit":return this.edit;case"workflow_step":return this.save;case"workflow_step_execute":return this.execute;default:return[]}}}F8.WorkflowStep=eMq;function Azq(A,q){if(typeof A!=="string")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof q!=="object")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a configuration object as the second argument");let K=["save","edit","execute"],F=[];for(let $ of K)if(q[$]===void 0)F.push($);if(F.length>0){let $=`WorkflowStep is missing required keys: ${F.join(", ")}`;throw new sp.WorkflowStepInitializationError($)}let Z=["save","edit","execute"];for(let $ of Z)if(typeof q[$]!=="function"&&!Array.isArray(q[$])){let U=`WorkflowStep ${$} property must be a function or an array of functions`;throw new sp.WorkflowStepInitializationError(U)}}F8.validate=Azq;async function qzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,f9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}F8.processStepMiddleware=qzq;function Kzq(A){return h9K.has(A.payload.type)}F8.isStepEvent=Kzq;function op(A){return A.botToken!==void 0?A.botToken:A.userToken}function y9K(A){let{context:q,client:K,body:{callback_id:F,trigger_id:Z}}=A,$=op(q);return(U)=>K.views.open({token:$,trigger_id:Z,view:{callback_id:F,type:"workflow_step",...U}})}function u9K(A){let{context:q,client:K,body:{workflow_step:{workflow_step_edit_id:F}}}=A,Z=op(q);return($={})=>K.workflows.updateStep({token:Z,workflow_step_edit_id:F,...$})}function c9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($={})=>K.workflows.stepCompleted({token:Z,workflow_step_execute_id:F,...$})}function m9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($)=>{let{error:U}=$;return K.workflows.stepFailed({token:Z,workflow_step_execute_id:F,error:U})}}function Fzq(A){let{next:q,...K}=A,F={...K};switch(F.payload.type){case"workflow_step_edit":F.step=F.action.workflow_step,F.configure=y9K(F);break;case"workflow_step":F.step=F.body.workflow_step,F.update=u9K(F);break;case"workflow_step_execute":F.step=F.event.workflow_step,F.complete=c9K(F),F.fail=m9K(F);break;default:break}return F}F8.prepareStepArgs=Fzq});var Xzq=I((WK)=>{var $zq=WK&&WK.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),p9K=WK&&WK.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),N4A=WK&&WK.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))$zq(q,A,K)}return p9K(q,A),q},_4A=WK&&WK.__exportStar||function(A,q){for(var K in A)if(K!=="default"&&!Object.prototype.hasOwnProperty.call(q,K))$zq(q,A,K)},fR=WK&&WK.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(WK,"__esModule",{value:!0});WK.webApi=WK.types=WK.FileInstallationStore=WK.MemoryInstallationStore=WK.WorkflowStep=WK.Assistant=WK.buildReceiverRoutes=WK.MemoryStore=WK.defaultProcessEventErrorHandler=WK.HTTPResponseAck=WK.HTTPModuleFunctions=WK.AwsLambdaReceiver=WK.HTTPReceiver=WK.SocketModeReceiver=WK.ExpressReceiver=WK.isValidSlackRequest=WK.verifySlackRequest=WK.App=WK.LogLevel=void 0;var Uzq=fR(gjA());WK.App=Uzq.default;var l9K=gjA();Object.defineProperty(WK,"LogLevel",{enumerable:!0,get:function(){return l9K.LogLevel}});WK.default=Uzq.default;var Yzq=KjA();Object.defineProperty(WK,"verifySlackRequest",{enumerable:!0,get:function(){return Yzq.verifySlackRequest}});Object.defineProperty(WK,"isValidSlackRequest",{enumerable:!0,get:function(){return Yzq.isValidSlackRequest}});var i9K=fR(DLq());WK.AwsLambdaReceiver=i9K.default;var a9K=fR(yMq());WK.ExpressReceiver=a9K.default;var d9K=fR(ZjA());WK.HTTPReceiver=d9K.default;var n9K=fR(GjA());WK.SocketModeReceiver=n9K.default;WK.HTTPModuleFunctions=N4A(JR());var s9K=jp();Object.defineProperty(WK,"HTTPResponseAck",{enumerable:!0,get:function(){return s9K.HTTPResponseAck}});var o9K=XjA();Object.defineProperty(WK,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return o9K.defaultProcessEventErrorHandler}});_4A(xY(),WK);_4A(oc(),WK);_4A(JjA(),WK);var r9K=S8A();Object.defineProperty(WK,"MemoryStore",{enumerable:!0,get:function(){return r9K.MemoryStore}});var t9K=Jp();Object.defineProperty(WK,"buildReceiverRoutes",{enumerable:!0,get:function(){return t9K.buildReceiverRoutes}});var e9K=P4A();Object.defineProperty(WK,"Assistant",{enumerable:!0,get:function(){return e9K.Assistant}});var AUK=Zzq();Object.defineProperty(WK,"WorkflowStep",{enumerable:!0,get:function(){return AUK.WorkflowStep}});var Qzq=FR();Object.defineProperty(WK,"MemoryInstallationStore",{enumerable:!0,get:function(){return Qzq.MemoryInstallationStore}});Object.defineProperty(WK,"FileInstallationStore",{enumerable:!0,get:function(){return Qzq.FileInstallationStore}});WK.types=N4A(O8A());WK.webApi=N4A(sc())});var f7A={name:"@interactive-inc/claude-funnel",version:"0.23.1",description:"Hub CLI that routes external events (Slack / GitHub / Discord) to Claude Code agents through subscription channels over MCP.",keywords:["bun","claude","claude-code","cli","discord","github","mcp","slack"],homepage:"https://github.com/interactive-inc/open-claude-funnel#readme",bugs:{url:"https://github.com/interactive-inc/open-claude-funnel/issues"},license:"MIT",author:"Interactive Inc.",repository:{type:"git",url:"git+https://github.com/interactive-inc/open-claude-funnel.git"},bin:{fnl:"./dist/bin.js",funnel:"./dist/bin.js"},files:["dist/**/*","funnel.schema.json","README.md","LICENSE"],type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./connectors/slack":{types:"./dist/connectors/slack.d.ts",import:"./dist/connectors/slack.js",default:"./dist/connectors/slack.js"},"./connectors/discord":{types:"./dist/connectors/discord.d.ts",import:"./dist/connectors/discord.js",default:"./dist/connectors/discord.js"},"./connectors/gh":{types:"./dist/connectors/gh.d.ts",import:"./dist/connectors/gh.js",default:"./dist/connectors/gh.js"},"./connectors/schedule":{types:"./dist/connectors/schedule.d.ts",import:"./dist/connectors/schedule.js",default:"./dist/connectors/schedule.js"},"./bin":"./dist/bin.js","./package.json":"./package.json"},publishConfig:{access:"public"},dependencies:{"@hono/zod-validator":"^0.8.0","@modelcontextprotocol/sdk":"^1.29.0","@opentui/core":"^0.2.12","@opentui/react":"^0.2.12","@slack/bolt":"^4.7.2","@slack/web-api":"^7.16.0","discord.js":"^14.26.4",hono:"^4.12.19",react:"^19.2.6",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@types/react":"^19.2.14","@typescript/native-preview":"^7.0.0-dev.20260516.1","vite-plus":"^0.1.21",vitest:"^4.1.6"},engines:{bun:">=1.3.0"},scripts:{prepack:"make build"}};var pK=class extends Error{res;status;constructor(A=500,q){super(q?.message,{cause:q?.cause});this.res=q?.res,this.status=A}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var c={};iG(c,{xor:()=>WHA,xid:()=>hJA,void:()=>XHA,uuidv7:()=>RJA,uuidv6:()=>DJA,uuidv4:()=>BJA,uuid:()=>wJA,util:()=>oq,url:()=>TJA,uppercase:()=>Yx,unknown:()=>g5,union:()=>fb,undefined:()=>YHA,ulid:()=>fJA,uint64:()=>$HA,uint32:()=>KHA,tuple:()=>fo,trim:()=>Hx,treeifyError:()=>wi,transform:()=>yb,toUpperCase:()=>Wx,toLowerCase:()=>Ex,toJSONSchema:()=>Gb,templateLiteral:()=>DHA,symbol:()=>UHA,superRefine:()=>Jr,success:()=>NHA,stringbool:()=>fHA,stringFormat:()=>sJA,string:()=>nP,strictObject:()=>HHA,startsWith:()=>Xx,slugify:()=>gx,size:()=>H5,setErrorMap:()=>DNq,set:()=>OHA,safeParseAsync:()=>jo,safeParse:()=>Go,safeEncodeAsync:()=>Lo,safeEncode:()=>go,safeDecodeAsync:()=>xo,safeDecode:()=>Vo,registry:()=>kS,regexes:()=>O8,regex:()=>$x,refine:()=>jr,record:()=>ho,readonly:()=>$r,property:()=>Ub,promise:()=>RHA,prettifyError:()=>Bi,preprocess:()=>yHA,prefault:()=>ro,positive:()=>Kb,pipe:()=>Vb,partialRecord:()=>VHA,parseAsync:()=>Xo,parse:()=>Qo,overwrite:()=>aG,optional:()=>oP,object:()=>JHA,number:()=>Mo,nullish:()=>PHA,nullable:()=>rP,null:()=>_o,normalize:()=>Jx,nonpositive:()=>Zb,nonoptional:()=>to,nonnegative:()=>$b,never:()=>Cb,negative:()=>Fb,nativeEnum:()=>MHA,nanoid:()=>vJA,nan:()=>_HA,multipleOf:()=>xE,minSize:()=>x4,minLength:()=>$J,mime:()=>jx,meta:()=>kHA,maxSize:()=>OE,maxLength:()=>E5,map:()=>xHA,mac:()=>cJA,lte:()=>M8,lt:()=>V4,lowercase:()=>Ux,looseRecord:()=>LHA,looseObject:()=>EHA,locales:()=>lP,literal:()=>zHA,length:()=>W5,lazy:()=>Qr,ksuid:()=>yJA,keyof:()=>jHA,jwt:()=>nJA,json:()=>hHA,iso:()=>xx,ipv6:()=>mJA,ipv4:()=>uJA,invertCodec:()=>BHA,intersection:()=>ko,int64:()=>ZHA,int32:()=>qHA,int:()=>gb,instanceof:()=>CHA,includes:()=>Qx,httpUrl:()=>SJA,hostname:()=>oJA,hex:()=>rJA,hash:()=>tJA,guid:()=>_JA,gte:()=>DQ,gt:()=>L4,globalRegistry:()=>rU,getErrorMap:()=>RNq,function:()=>THA,fromJSONSchema:()=>cHA,formatError:()=>bP,float64:()=>AHA,float32:()=>eJA,flattenError:()=>SP,file:()=>IHA,exactOptional:()=>io,enum:()=>hb,endsWith:()=>Gx,encodeAsync:()=>Eo,encode:()=>Jo,emoji:()=>bJA,email:()=>NJA,e164:()=>dJA,discriminatedUnion:()=>gHA,describe:()=>vHA,decodeAsync:()=>Wo,decode:()=>Ho,date:()=>GHA,custom:()=>bHA,cuid2:()=>CJA,cuid:()=>kJA,core:()=>UJ,config:()=>d$,coerce:()=>Er,codec:()=>wHA,clone:()=>wQ,cidrv6:()=>lJA,cidrv4:()=>pJA,check:()=>SHA,catch:()=>qr,boolean:()=>zo,bigint:()=>FHA,base64url:()=>aJA,base64:()=>iJA,array:()=>qN,any:()=>QHA,_function:()=>THA,_default:()=>so,_ZodString:()=>Lb,ZodXor:()=>So,ZodXID:()=>Nb,ZodVoid:()=>Ro,ZodUnknown:()=>Bo,ZodUnion:()=>FN,ZodUndefined:()=>Po,ZodUUID:()=>O4,ZodURL:()=>eP,ZodULID:()=>Pb,ZodType:()=>ZF,ZodTuple:()=>Co,ZodTransform:()=>po,ZodTemplateLiteral:()=>Ur,ZodSymbol:()=>Io,ZodSuccess:()=>eo,ZodStringFormat:()=>o1,ZodString:()=>zx,ZodSet:()=>uo,ZodRecord:()=>Ox,ZodRealError:()=>_0,ZodReadonly:()=>Zr,ZodPromise:()=>Xr,ZodPreprocess:()=>Fr,ZodPrefault:()=>oo,ZodPipe:()=>ZN,ZodOptional:()=>ub,ZodObject:()=>KN,ZodNumberFormat:()=>V5,ZodNumber:()=>Px,ZodNullable:()=>ao,ZodNull:()=>No,ZodNonOptional:()=>cb,ZodNever:()=>Do,ZodNanoID:()=>Mb,ZodNaN:()=>Kr,ZodMap:()=>yo,ZodMAC:()=>Oo,ZodLiteral:()=>co,ZodLazy:()=>Yr,ZodKSUID:()=>_b,ZodJWT:()=>vb,ZodIssueCode:()=>BNq,ZodIntersection:()=>vo,ZodISOTime:()=>Eb,ZodISODuration:()=>Wb,ZodISODateTime:()=>Jb,ZodISODate:()=>Hb,ZodIPv6:()=>Bb,ZodIPv4:()=>wb,ZodGUID:()=>sP,ZodFunction:()=>Gr,ZodFirstPartyTypeKind:()=>Hr,ZodFile:()=>mo,ZodExactOptional:()=>lo,ZodError:()=>_Nq,ZodEnum:()=>Mx,ZodEmoji:()=>Ob,ZodEmail:()=>xb,ZodE164:()=>bb,ZodDiscriminatedUnion:()=>bo,ZodDefault:()=>no,ZodDate:()=>AN,ZodCustomStringFormat:()=>Ix,ZodCustom:()=>UN,ZodCodec:()=>$N,ZodCatch:()=>Ar,ZodCUID2:()=>Ib,ZodCUID:()=>zb,ZodCIDRv6:()=>Rb,ZodCIDRv4:()=>Db,ZodBoolean:()=>Nx,ZodBigIntFormat:()=>kb,ZodBigInt:()=>_x,ZodBase64URL:()=>Sb,ZodBase64:()=>Tb,ZodArray:()=>To,ZodAny:()=>wo,TimePrecision:()=>Cn,NEVER:()=>Wi,$output:()=>Rn,$input:()=>Tn,$brand:()=>gi});var UJ={};iG(UJ,{version:()=>Pa,util:()=>oq,treeifyError:()=>wi,toJSONSchema:()=>Gb,toDotPath:()=>l7A,safeParseAsync:()=>Ri,safeParse:()=>Di,safeEncodeAsync:()=>BIq,safeEncode:()=>_Iq,safeDecodeAsync:()=>DIq,safeDecode:()=>wIq,registry:()=>kS,regexes:()=>O8,process:()=>D1,prettifyError:()=>Bi,parseAsync:()=>HS,parse:()=>JS,meta:()=>Vs,locales:()=>lP,isValidJWT:()=>JJA,isValidBase64URL:()=>jJA,isValidBase64:()=>aa,initializeContext:()=>ME,globalRegistry:()=>rU,globalConfig:()=>Q5,formatError:()=>bP,flattenError:()=>SP,finalize:()=>IE,extractDefs:()=>zE,encodeAsync:()=>PIq,encode:()=>zIq,describe:()=>gs,decodeAsync:()=>NIq,decode:()=>IIq,createToJSONSchemaMethod:()=>xs,createStandardJSONSchemaMethod:()=>Lx,config:()=>d$,clone:()=>wQ,_xor:()=>KNq,_xid:()=>aS,_void:()=>Ys,_uuidv7:()=>uS,_uuidv6:()=>yS,_uuidv4:()=>hS,_uuid:()=>fS,_url:()=>aP,_uppercase:()=>Yx,_unknown:()=>$s,_union:()=>qNq,_undefined:()=>Ks,_ulid:()=>iS,_uint64:()=>As,_uint32:()=>nn,_tuple:()=>$Nq,_trim:()=>Hx,_transform:()=>JNq,_toUpperCase:()=>Wx,_toLowerCase:()=>Ex,_templateLiteral:()=>MNq,_symbol:()=>qs,_superRefine:()=>Ws,_success:()=>VNq,_stringbool:()=>Ls,_stringFormat:()=>Vx,_string:()=>bn,_startsWith:()=>Xx,_slugify:()=>gx,_size:()=>H5,_set:()=>QNq,_safeParseAsync:()=>Kx,_safeParse:()=>qx,_safeEncodeAsync:()=>OS,_safeEncode:()=>LS,_safeDecodeAsync:()=>MS,_safeDecode:()=>xS,_regex:()=>$x,_refine:()=>Es,_record:()=>UNq,_readonly:()=>ONq,_property:()=>Ub,_promise:()=>INq,_positive:()=>Kb,_pipe:()=>xNq,_parseAsync:()=>Ax,_parse:()=>e2,_overwrite:()=>aG,_optional:()=>HNq,_number:()=>cn,_nullable:()=>ENq,_null:()=>Fs,_normalize:()=>Jx,_nonpositive:()=>Zb,_nonoptional:()=>gNq,_nonnegative:()=>$b,_never:()=>Us,_negative:()=>Fb,_nativeEnum:()=>GNq,_nanoid:()=>mS,_nan:()=>Gs,_multipleOf:()=>xE,_minSize:()=>x4,_minLength:()=>$J,_min:()=>DQ,_mime:()=>jx,_maxSize:()=>OE,_maxLength:()=>E5,_max:()=>M8,_map:()=>YNq,_mac:()=>kn,_lte:()=>M8,_lt:()=>V4,_lowercase:()=>Ux,_literal:()=>jNq,_length:()=>W5,_lazy:()=>zNq,_ksuid:()=>dS,_jwt:()=>qb,_isoTime:()=>yn,_isoDuration:()=>un,_isoDateTime:()=>fn,_isoDate:()=>hn,_ipv6:()=>sS,_ipv4:()=>nS,_intersection:()=>ZNq,_int64:()=>en,_int32:()=>dn,_int:()=>pn,_includes:()=>Qx,_guid:()=>iP,_gte:()=>DQ,_gt:()=>L4,_float64:()=>an,_float32:()=>ln,_file:()=>Js,_enum:()=>XNq,_endsWith:()=>Gx,_encodeAsync:()=>gS,_encode:()=>ES,_emoji:()=>cS,_email:()=>CS,_e164:()=>Ab,_discriminatedUnion:()=>FNq,_default:()=>WNq,_decodeAsync:()=>VS,_decode:()=>WS,_date:()=>Qs,_custom:()=>Hs,_cuid2:()=>lS,_cuid:()=>pS,_coercedString:()=>vn,_coercedNumber:()=>mn,_coercedDate:()=>Xs,_coercedBoolean:()=>on,_coercedBigint:()=>tn,_cidrv6:()=>rS,_cidrv4:()=>oS,_check:()=>MJA,_catch:()=>LNq,_boolean:()=>sn,_bigint:()=>rn,_base64url:()=>eS,_base64:()=>tS,_array:()=>js,_any:()=>Zs,TimePrecision:()=>Cn,NEVER:()=>Wi,JSONSchemaGenerator:()=>Fo,JSONSchema:()=>zJA,Doc:()=>NS,$output:()=>Rn,$input:()=>Tn,$constructor:()=>nA,$brand:()=>gi,$ZodXor:()=>Gd,$ZodXID:()=>ka,$ZodVoid:()=>Ud,$ZodUnknown:()=>Zd,$ZodUnion:()=>hP,$ZodUndefined:()=>qd,$ZodUUID:()=>wa,$ZodURL:()=>Da,$ZodULID:()=>va,$ZodType:()=>yK,$ZodTuple:()=>SS,$ZodTransform:()=>xd,$ZodTemplateLiteral:()=>Rd,$ZodSymbol:()=>Ad,$ZodSuccess:()=>Nd,$ZodStringFormat:()=>s1,$ZodString:()=>J5,$ZodSet:()=>Wd,$ZodRegistry:()=>Sn,$ZodRecord:()=>Hd,$ZodRealError:()=>N0,$ZodReadonly:()=>Dd,$ZodPromise:()=>Sd,$ZodPreprocess:()=>Bd,$ZodPrefault:()=>Id,$ZodPipe:()=>vS,$ZodOptional:()=>bS,$ZodObjectJIT:()=>Xd,$ZodObject:()=>WJA,$ZodNumberFormat:()=>ta,$ZodNumber:()=>RS,$ZodNullable:()=>Md,$ZodNull:()=>Kd,$ZodNonOptional:()=>Pd,$ZodNever:()=>$d,$ZodNanoID:()=>Ta,$ZodNaN:()=>wd,$ZodMap:()=>Ed,$ZodMAC:()=>pa,$ZodLiteral:()=>Vd,$ZodLazy:()=>bd,$ZodKSUID:()=>Ca,$ZodJWT:()=>oa,$ZodIntersection:()=>Jd,$ZodISOTime:()=>ya,$ZodISODuration:()=>ua,$ZodISODateTime:()=>fa,$ZodISODate:()=>ha,$ZodIPv6:()=>ma,$ZodIPv4:()=>ca,$ZodGUID:()=>_a,$ZodFunction:()=>Td,$ZodFile:()=>Ld,$ZodExactOptional:()=>Od,$ZodError:()=>TP,$ZodEnum:()=>gd,$ZodEncodeError:()=>X5,$ZodEmoji:()=>Ra,$ZodEmail:()=>Ba,$ZodE164:()=>sa,$ZodDiscriminatedUnion:()=>jd,$ZodDefault:()=>zd,$ZodDate:()=>Yd,$ZodCustomStringFormat:()=>ra,$ZodCustom:()=>vd,$ZodCodec:()=>yP,$ZodCheckUpperCase:()=>Va,$ZodCheckStringFormat:()=>Fx,$ZodCheckStartsWith:()=>xa,$ZodCheckSizeEquals:()=>ja,$ZodCheckRegex:()=>Wa,$ZodCheckProperty:()=>Ma,$ZodCheckOverwrite:()=>Ia,$ZodCheckNumberFormat:()=>Ya,$ZodCheckMultipleOf:()=>Ua,$ZodCheckMinSize:()=>Ga,$ZodCheckMinLength:()=>Ha,$ZodCheckMimeType:()=>za,$ZodCheckMaxSize:()=>Xa,$ZodCheckMaxLength:()=>Ja,$ZodCheckLowerCase:()=>ga,$ZodCheckLessThan:()=>IS,$ZodCheckLengthEquals:()=>Ea,$ZodCheckIncludes:()=>La,$ZodCheckGreaterThan:()=>PS,$ZodCheckEndsWith:()=>Oa,$ZodCheckBigIntFormat:()=>Qa,$ZodCheck:()=>XZ,$ZodCatch:()=>_d,$ZodCUID2:()=>ba,$ZodCUID:()=>Sa,$ZodCIDRv6:()=>ia,$ZodCIDRv4:()=>la,$ZodBoolean:()=>fP,$ZodBigIntFormat:()=>ea,$ZodBigInt:()=>TS,$ZodBase64URL:()=>na,$ZodBase64:()=>da,$ZodAsyncError:()=>g4,$ZodArray:()=>Qd,$ZodAny:()=>Fd});var h7A,Wi=Object.freeze({status:"aborted"});function nA(A,q,K){function F(Y,X){if(!Y._zod)Object.defineProperty(Y,"_zod",{value:{def:X,constr:U,traits:new Set},enumerable:!1});if(Y._zod.traits.has(A))return;Y._zod.traits.add(A),q(Y,X);let j=U.prototype,J=Object.keys(j);for(let E=0;E<J.length;E++){let W=J[E];if(!(W in Y))Y[W]=j[W].bind(Y)}}let Z=K?.Parent??Object;class $ extends Z{}Object.defineProperty($,"name",{value:A});function U(Y){var X;let j=K?.Parent?new $:this;F(j,Y),(X=j._zod).deferred??(X.deferred=[]);for(let J of j._zod.deferred)J();return j}return Object.defineProperty(U,"init",{value:F}),Object.defineProperty(U,Symbol.hasInstance,{value:(Y)=>{if(K?.Parent&&Y instanceof K.Parent)return!0;return Y?._zod?.traits?.has(A)}}),Object.defineProperty(U,"name",{value:A}),U}var gi=Symbol("zod_brand");class g4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class X5 extends Error{constructor(A){super(`Encountered unidirectional transform during encode: ${A}`);this.name="ZodEncodeError"}}(h7A=globalThis).__zod_globalConfig??(h7A.__zod_globalConfig={});var Q5=globalThis.__zod_globalConfig;function d$(A){if(A)Object.assign(Q5,A);return Q5}var oq={};iG(oq,{unwrapMessage:()=>NP,uint8ArrayToHex:()=>OIq,uint8ArrayToBase64url:()=>LIq,uint8ArrayToBase64:()=>c7A,stringifyPrimitive:()=>pq,slugify:()=>xi,shallowClone:()=>Mi,safeExtend:()=>JIq,required:()=>WIq,randomString:()=>$Iq,propertyKeyTypes:()=>BP,promiseAllObject:()=>ZIq,primitiveTypes:()=>zi,prefixIssues:()=>P0,pick:()=>XIq,partial:()=>EIq,parsedType:()=>nq,optionalKeys:()=>Ii,omit:()=>GIq,objectClone:()=>qIq,numKeys:()=>UIq,nullish:()=>WE,normalizeParams:()=>A6,mergeDefs:()=>ZJ,merge:()=>HIq,jsonStringifyReplacer:()=>o2,joinValues:()=>Qq,issue:()=>t2,isPlainObject:()=>VE,isObject:()=>G5,hexToUint8Array:()=>xIq,getSizableOrigin:()=>DP,getParsedType:()=>YIq,getLengthableOrigin:()=>RP,getEnumValues:()=>_P,getElementAtPath:()=>FIq,floatSafeRemainder:()=>Li,finalizeIssue:()=>BQ,extend:()=>jIq,explicitlyAborted:()=>_i,escapeRegex:()=>PX,esc:()=>GS,defineLazy:()=>NF,createTransparentProxy:()=>QIq,cloneDef:()=>KIq,clone:()=>wQ,cleanRegex:()=>wP,cleanEnum:()=>gIq,captureStackTrace:()=>jS,cached:()=>r2,base64urlToUint8Array:()=>VIq,base64ToUint8Array:()=>u7A,assignProp:()=>gE,assertNotEqual:()=>rzq,assertNever:()=>ezq,assertIs:()=>tzq,assertEqual:()=>ozq,assert:()=>AIq,allowsEval:()=>Oi,aborted:()=>LE,NUMBER_FORMAT_RANGES:()=>Pi,Class:()=>m7A,BIGINT_FORMAT_RANGES:()=>Ni});function ozq(A){return A}function rzq(A){return A}function tzq(A){}function ezq(A){throw Error("Unexpected value in exhaustive check")}function AIq(A){}function _P(A){let q=Object.values(A).filter((F)=>typeof F==="number");return Object.entries(A).filter(([F,Z])=>q.indexOf(+F)===-1).map(([F,Z])=>Z)}function Qq(A,q="|"){return A.map((K)=>pq(K)).join(q)}function o2(A,q){if(typeof q==="bigint")return q.toString();return q}function r2(A){return{get value(){{let K=A();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function WE(A){return A===null||A===void 0}function wP(A){let q=A.startsWith("^")?1:0,K=A.endsWith("$")?A.length-1:A.length;return A.slice(q,K)}function Li(A,q){let K=A/q,F=Math.round(K),Z=Number.EPSILON*Math.max(Math.abs(K),1);if(Math.abs(K-F)<Z)return 0;return K-F}var y7A=Symbol("evaluating");function NF(A,q,K){let F=void 0;Object.defineProperty(A,q,{get(){if(F===y7A)return;if(F===void 0)F=y7A,F=K();return F},set(Z){Object.defineProperty(A,q,{value:Z})},configurable:!0})}function qIq(A){return Object.create(Object.getPrototypeOf(A),Object.getOwnPropertyDescriptors(A))}function gE(A,q,K){Object.defineProperty(A,q,{value:K,writable:!0,enumerable:!0,configurable:!0})}function ZJ(...A){let q={};for(let K of A){let F=Object.getOwnPropertyDescriptors(K);Object.assign(q,F)}return Object.defineProperties({},q)}function KIq(A){return ZJ(A._zod.def)}function FIq(A,q){if(!q)return A;return q.reduce((K,F)=>K?.[F],A)}function ZIq(A){let q=Object.keys(A),K=q.map((F)=>A[F]);return Promise.all(K).then((F)=>{let Z={};for(let $=0;$<q.length;$++)Z[q[$]]=F[$];return Z})}function $Iq(A=10){let K="";for(let F=0;F<A;F++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function GS(A){return JSON.stringify(A)}function xi(A){return A.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var jS="captureStackTrace"in Error?Error.captureStackTrace:(...A)=>{};function G5(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var Oi=r2(()=>{if(Q5.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(A){return!1}});function VE(A){if(G5(A)===!1)return!1;let q=A.constructor;if(q===void 0)return!0;if(typeof q!=="function")return!0;let K=q.prototype;if(G5(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function Mi(A){if(VE(A))return{...A};if(Array.isArray(A))return[...A];if(A instanceof Map)return new Map(A);if(A instanceof Set)return new Set(A);return A}function UIq(A){let q=0;for(let K in A)if(Object.prototype.hasOwnProperty.call(A,K))q++;return q}var YIq=(A)=>{let q=typeof A;switch(q){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(A)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(A))return"array";if(A===null)return"null";if(A.then&&typeof A.then==="function"&&A.catch&&typeof A.catch==="function")return"promise";if(typeof Map<"u"&&A instanceof Map)return"map";if(typeof Set<"u"&&A instanceof Set)return"set";if(typeof Date<"u"&&A instanceof Date)return"date";if(typeof File<"u"&&A instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${q}`)}},BP=new Set(["string","number","symbol"]),zi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function PX(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wQ(A,q,K){let F=new A._zod.constr(q??A._zod.def);if(!q||K?.parent)F._zod.parent=A;return F}function A6(A){let q=A;if(!q)return{};if(typeof q==="string")return{error:()=>q};if(q?.message!==void 0){if(q?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");q.error=q.message}if(delete q.message,typeof q.error==="string")return{...q,error:()=>q.error};return q}function QIq(A){let q;return new Proxy({},{get(K,F,Z){return q??(q=A()),Reflect.get(q,F,Z)},set(K,F,Z,$){return q??(q=A()),Reflect.set(q,F,Z,$)},has(K,F){return q??(q=A()),Reflect.has(q,F)},deleteProperty(K,F){return q??(q=A()),Reflect.deleteProperty(q,F)},ownKeys(K){return q??(q=A()),Reflect.ownKeys(q)},getOwnPropertyDescriptor(K,F){return q??(q=A()),Reflect.getOwnPropertyDescriptor(q,F)},defineProperty(K,F,Z){return q??(q=A()),Reflect.defineProperty(q,F,Z)}})}function pq(A){if(typeof A==="bigint")return A.toString()+"n";if(typeof A==="string")return`"${A}"`;return`${A}`}function Ii(A){return Object.keys(A).filter((q)=>{return A[q]._zod.optin==="optional"&&A[q]._zod.optout==="optional"})}var Pi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ni={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function XIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;U[Y]=K.shape[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function GIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={...A._zod.def.shape};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;delete U[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function jIq(A,q){if(!VE(q))throw Error("Invalid input to extend: expected a plain object");let K=A._zod.def.checks;if(K&&K.length>0){let $=A._zod.def.shape;for(let U in q)if(Object.getOwnPropertyDescriptor($,U)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Z=ZJ(A._zod.def,{get shape(){let $={...A._zod.def.shape,...q};return gE(this,"shape",$),$}});return wQ(A,Z)}function JIq(A,q){if(!VE(q))throw Error("Invalid input to safeExtend: expected a plain object");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q};return gE(this,"shape",F),F}});return wQ(A,K)}function HIq(A,q){if(A._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q._zod.def.shape};return gE(this,"shape",F),F},get catchall(){return q._zod.def.catchall},checks:q._zod.def.checks??[]});return wQ(A,K)}function EIq(A,q,K){let Z=q._zod.def.checks;if(Z&&Z.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let U=ZJ(q._zod.def,{get shape(){let Y=q._zod.def.shape,X={...Y};if(K)for(let j in K){if(!(j in Y))throw Error(`Unrecognized key: "${j}"`);if(!K[j])continue;X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j]}else for(let j in Y)X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j];return gE(this,"shape",X),X},checks:[]});return wQ(q,U)}function WIq(A,q,K){let F=ZJ(q._zod.def,{get shape(){let Z=q._zod.def.shape,$={...Z};if(K)for(let U in K){if(!(U in $))throw Error(`Unrecognized key: "${U}"`);if(!K[U])continue;$[U]=new A({type:"nonoptional",innerType:Z[U]})}else for(let U in Z)$[U]=new A({type:"nonoptional",innerType:Z[U]});return gE(this,"shape",$),$}});return wQ(q,F)}function LE(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue!==!0)return!0;return!1}function _i(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue===!1)return!0;return!1}function P0(A,q){return q.map((K)=>{var F;return(F=K).path??(F.path=[]),K.path.unshift(A),K})}function NP(A){return typeof A==="string"?A:A?.message}function BQ(A,q,K){let F=A.message?A.message:NP(A.inst?._zod.def?.error?.(A))??NP(q?.error?.(A))??NP(K.customError?.(A))??NP(K.localeError?.(A))??"Invalid input",{inst:Z,continue:$,input:U,...Y}=A;if(Y.path??(Y.path=[]),Y.message=F,q?.reportInput)Y.input=U;return Y}function DP(A){if(A instanceof Set)return"set";if(A instanceof Map)return"map";if(A instanceof File)return"file";return"unknown"}function RP(A){if(Array.isArray(A))return"array";if(typeof A==="string")return"string";return"unknown"}function nq(A){let q=typeof A;switch(q){case"number":return Number.isNaN(A)?"nan":"number";case"object":{if(A===null)return"null";if(Array.isArray(A))return"array";let K=A;if(K&&Object.getPrototypeOf(K)!==Object.prototype&&"constructor"in K&&K.constructor)return K.constructor.name}}return q}function t2(...A){let[q,K,F]=A;if(typeof q==="string")return{message:q,code:"custom",input:K,inst:F};return{...q}}function gIq(A){return Object.entries(A).filter(([q,K])=>{return Number.isNaN(Number.parseInt(q,10))}).map((q)=>q[1])}function u7A(A){let q=atob(A),K=new Uint8Array(q.length);for(let F=0;F<q.length;F++)K[F]=q.charCodeAt(F);return K}function c7A(A){let q="";for(let K=0;K<A.length;K++)q+=String.fromCharCode(A[K]);return btoa(q)}function VIq(A){let q=A.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-q.length%4)%4);return u7A(q+K)}function LIq(A){return c7A(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xIq(A){let q=A.replace(/^0x/,"");if(q.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(q.length/2);for(let F=0;F<q.length;F+=2)K[F/2]=Number.parseInt(q.slice(F,F+2),16);return K}function OIq(A){return Array.from(A).map((q)=>q.toString(16).padStart(2,"0")).join("")}class m7A{constructor(...A){}}var p7A=(A,q)=>{A.name="$ZodError",Object.defineProperty(A,"_zod",{value:A._zod,enumerable:!1}),Object.defineProperty(A,"issues",{value:q,enumerable:!1}),A.message=JSON.stringify(q,o2,2),Object.defineProperty(A,"toString",{value:()=>A.message,enumerable:!1})},TP=nA("$ZodError",p7A),N0=nA("$ZodError",p7A,{Parent:Error});function SP(A,q=(K)=>K.message){let K={},F=[];for(let Z of A.issues)if(Z.path.length>0)K[Z.path[0]]=K[Z.path[0]]||[],K[Z.path[0]].push(q(Z));else F.push(q(Z));return{formErrors:F,fieldErrors:K}}function bP(A,q=(K)=>K.message){let K={_errors:[]},F=(Z,$=[])=>{for(let U of Z.issues)if(U.code==="invalid_union"&&U.errors.length)U.errors.map((Y)=>F({issues:Y},[...$,...U.path]));else if(U.code==="invalid_key")F({issues:U.issues},[...$,...U.path]);else if(U.code==="invalid_element")F({issues:U.issues},[...$,...U.path]);else{let Y=[...$,...U.path];if(Y.length===0)K._errors.push(q(U));else{let X=K,j=0;while(j<Y.length){let J=Y[j];if(j!==Y.length-1)X[J]=X[J]||{_errors:[]};else X[J]=X[J]||{_errors:[]},X[J]._errors.push(q(U));X=X[J],j++}}}};return F(A),K}function wi(A,q=(K)=>K.message){let K={errors:[]},F=(Z,$=[])=>{var U,Y;for(let X of Z.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((j)=>F({issues:j},[...$,...X.path]));else if(X.code==="invalid_key")F({issues:X.issues},[...$,...X.path]);else if(X.code==="invalid_element")F({issues:X.issues},[...$,...X.path]);else{let j=[...$,...X.path];if(j.length===0){K.errors.push(q(X));continue}let J=K,E=0;while(E<j.length){let W=j[E],g=E===j.length-1;if(typeof W==="string")J.properties??(J.properties={}),(U=J.properties)[W]??(U[W]={errors:[]}),J=J.properties[W];else J.items??(J.items=[]),(Y=J.items)[W]??(Y[W]={errors:[]}),J=J.items[W];if(g)J.errors.push(q(X));E++}}};return F(A),K}function l7A(A){let q=[],K=A.map((F)=>typeof F==="object"?F.key:F);for(let F of K)if(typeof F==="number")q.push(`[${F}]`);else if(typeof F==="symbol")q.push(`[${JSON.stringify(String(F))}]`);else if(/[^\w$]/.test(F))q.push(`[${JSON.stringify(F)}]`);else{if(q.length)q.push(".");q.push(F)}return q.join("")}function Bi(A){let q=[],K=[...A.issues].sort((F,Z)=>(F.path??[]).length-(Z.path??[]).length);for(let F of K)if(q.push(`\u2716 ${F.message}`),F.path?.length)q.push(` \u2192 at ${l7A(F.path)}`);return q.join(`
|
|
908
908
|
`)}var e2=(A)=>(q,K,F,Z)=>{let $=F?{...F,async:!1}:{async:!1},U=q._zod.run({value:K,issues:[]},$);if(U instanceof Promise)throw new g4;if(U.issues.length){let Y=new(Z?.Err??A)(U.issues.map((X)=>BQ(X,$,d$())));throw jS(Y,Z?.callee),Y}return U.value},JS=e2(N0),Ax=(A)=>async(q,K,F,Z)=>{let $=F?{...F,async:!0}:{async:!0},U=q._zod.run({value:K,issues:[]},$);if(U instanceof Promise)U=await U;if(U.issues.length){let Y=new(Z?.Err??A)(U.issues.map((X)=>BQ(X,$,d$())));throw jS(Y,Z?.callee),Y}return U.value},HS=Ax(N0),qx=(A)=>(q,K,F)=>{let Z=F?{...F,async:!1}:{async:!1},$=q._zod.run({value:K,issues:[]},Z);if($ instanceof Promise)throw new g4;return $.issues.length?{success:!1,error:new(A??TP)($.issues.map((U)=>BQ(U,Z,d$())))}:{success:!0,data:$.value}},Di=qx(N0),Kx=(A)=>async(q,K,F)=>{let Z=F?{...F,async:!0}:{async:!0},$=q._zod.run({value:K,issues:[]},Z);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new A($.issues.map((U)=>BQ(U,Z,d$())))}:{success:!0,data:$.value}},Ri=Kx(N0),ES=(A)=>(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return e2(A)(q,K,Z)},zIq=ES(N0),WS=(A)=>(q,K,F)=>{return e2(A)(q,K,F)},IIq=WS(N0),gS=(A)=>async(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return Ax(A)(q,K,Z)},PIq=gS(N0),VS=(A)=>async(q,K,F)=>{return Ax(A)(q,K,F)},NIq=VS(N0),LS=(A)=>(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return qx(A)(q,K,Z)},_Iq=LS(N0),xS=(A)=>(q,K,F)=>{return qx(A)(q,K,F)},wIq=xS(N0),OS=(A)=>async(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return Kx(A)(q,K,Z)},BIq=OS(N0),MS=(A)=>async(q,K,F)=>{return Kx(A)(q,K,F)},DIq=MS(N0);var O8={};iG(O8,{xid:()=>vi,uuid7:()=>bIq,uuid6:()=>SIq,uuid4:()=>TIq,uuid:()=>j5,uppercase:()=>$a,unicodeEmail:()=>i7A,undefined:()=>Fa,ulid:()=>bi,time:()=>oi,string:()=>ti,sha512_hex:()=>APq,sha512_base64url:()=>KPq,sha512_base64:()=>qPq,sha384_hex:()=>rIq,sha384_base64url:()=>eIq,sha384_base64:()=>tIq,sha256_hex:()=>nIq,sha256_base64url:()=>oIq,sha256_base64:()=>sIq,sha1_hex:()=>iIq,sha1_base64url:()=>dIq,sha1_base64:()=>aIq,rfc5322Email:()=>kIq,number:()=>vP,null:()=>Ka,nanoid:()=>Ci,md5_hex:()=>mIq,md5_base64url:()=>lIq,md5_base64:()=>pIq,mac:()=>pi,lowercase:()=>Za,ksuid:()=>ki,ipv6:()=>mi,ipv4:()=>ci,integer:()=>Aa,idnEmail:()=>CIq,httpProtocol:()=>di,html5Email:()=>vIq,hostname:()=>yIq,hex:()=>cIq,guid:()=>hi,extendedDuration:()=>RIq,emoji:()=>ui,email:()=>yi,e164:()=>ni,duration:()=>fi,domain:()=>uIq,datetime:()=>ri,date:()=>si,cuid2:()=>Si,cuid:()=>Ti,cidrv6:()=>ii,cidrv4:()=>li,browserEmail:()=>fIq,boolean:()=>qa,bigint:()=>ei,base64url:()=>zS,base64:()=>ai});var Ti=/^[cC][0-9a-z]{6,}$/,Si=/^[0-9a-z]+$/,bi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vi=/^[0-9a-vA-V]{20}$/,ki=/^[A-Za-z0-9]{27}$/,Ci=/^[a-zA-Z0-9_-]{21}$/,fi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,RIq=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,j5=(A)=>{if(!A)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${A}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},TIq=j5(4),SIq=j5(6),bIq=j5(7),yi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vIq=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,kIq=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,i7A=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,CIq=i7A,fIq=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,hIq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ui(){return new RegExp(hIq,"u")}var ci=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,mi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,pi=(A)=>{let q=PX(A??":");return new RegExp(`^(?:[0-9A-F]{2}${q}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${q}){5}[0-9a-f]{2}$`)},li=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ii=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ai=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zS=/^[A-Za-z0-9_-]*$/,yIq=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,uIq=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,di=/^https?$/,ni=/^\+[1-9]\d{6,14}$/,a7A="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",si=new RegExp(`^${a7A}$`);function d7A(A){return typeof A.precision==="number"?A.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":A.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${A.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function oi(A){return new RegExp(`^${d7A(A)}$`)}function ri(A){let q=d7A({precision:A.precision}),K=["Z"];if(A.local)K.push("");if(A.offset)K.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let F=`${q}(?:${K.join("|")})`;return new RegExp(`^${a7A}T(?:${F})$`)}var ti=(A)=>{let q=A?`[\\s\\S]{${A?.minimum??0},${A?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${q}$`)},ei=/^-?\d+n?$/,Aa=/^-?\d+$/,vP=/^-?\d+(?:\.\d+)?$/,qa=/^(?:true|false)$/i,Ka=/^null$/i;var Fa=/^undefined$/i;var Za=/^[^A-Z]*$/,$a=/^[^a-z]*$/,cIq=/^[0-9a-fA-F]*$/;function kP(A,q){return new RegExp(`^[A-Za-z0-9+/]{${A}}${q}$`)}function CP(A){return new RegExp(`^[A-Za-z0-9_-]{${A}}$`)}var mIq=/^[0-9a-fA-F]{32}$/,pIq=kP(22,"=="),lIq=CP(22),iIq=/^[0-9a-fA-F]{40}$/,aIq=kP(27,"="),dIq=CP(27),nIq=/^[0-9a-fA-F]{64}$/,sIq=kP(43,"="),oIq=CP(43),rIq=/^[0-9a-fA-F]{96}$/,tIq=kP(64,""),eIq=CP(64),APq=/^[0-9a-fA-F]{128}$/,qPq=kP(86,"=="),KPq=CP(86);var XZ=nA("$ZodCheck",(A,q)=>{var K;A._zod??(A._zod={}),A._zod.def=q,(K=A._zod).onattach??(K.onattach=[])}),s7A={number:"number",bigint:"bigint",object:"date"},IS=nA("$ZodCheckLessThan",(A,q)=>{XZ.init(A,q);let K=s7A[typeof q.value];A._zod.onattach.push((F)=>{let Z=F._zod.bag,$=(q.inclusive?Z.maximum:Z.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(q.value<$)if(q.inclusive)Z.maximum=q.value;else Z.exclusiveMaximum=q.value}),A._zod.check=(F)=>{if(q.inclusive?F.value<=q.value:F.value<q.value)return;F.issues.push({origin:K,code:"too_big",maximum:typeof q.value==="object"?q.value.getTime():q.value,input:F.value,inclusive:q.inclusive,inst:A,continue:!q.abort})}}),PS=nA("$ZodCheckGreaterThan",(A,q)=>{XZ.init(A,q);let K=s7A[typeof q.value];A._zod.onattach.push((F)=>{let Z=F._zod.bag,$=(q.inclusive?Z.minimum:Z.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(q.value>$)if(q.inclusive)Z.minimum=q.value;else Z.exclusiveMinimum=q.value}),A._zod.check=(F)=>{if(q.inclusive?F.value>=q.value:F.value>q.value)return;F.issues.push({origin:K,code:"too_small",minimum:typeof q.value==="object"?q.value.getTime():q.value,input:F.value,inclusive:q.inclusive,inst:A,continue:!q.abort})}}),Ua=nA("$ZodCheckMultipleOf",(A,q)=>{XZ.init(A,q),A._zod.onattach.push((K)=>{var F;(F=K._zod.bag).multipleOf??(F.multipleOf=q.value)}),A._zod.check=(K)=>{if(typeof K.value!==typeof q.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof K.value==="bigint"?K.value%q.value===BigInt(0):Li(K.value,q.value)===0)return;K.issues.push({origin:typeof K.value,code:"not_multiple_of",divisor:q.value,input:K.value,inst:A,continue:!q.abort})}}),Ya=nA("$ZodCheckNumberFormat",(A,q)=>{XZ.init(A,q),q.format=q.format||"float64";let K=q.format?.includes("int"),F=K?"int":"number",[Z,$]=Pi[q.format];A._zod.onattach.push((U)=>{let Y=U._zod.bag;if(Y.format=q.format,Y.minimum=Z,Y.maximum=$,K)Y.pattern=Aa}),A._zod.check=(U)=>{let Y=U.value;if(K){if(!Number.isInteger(Y)){U.issues.push({expected:F,format:q.format,code:"invalid_type",continue:!1,input:Y,inst:A});return}if(!Number.isSafeInteger(Y)){if(Y>0)U.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:A,origin:F,inclusive:!0,continue:!q.abort});else U.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:A,origin:F,inclusive:!0,continue:!q.abort});return}}if(Y<Z)U.issues.push({origin:"number",input:Y,code:"too_small",minimum:Z,inclusive:!0,inst:A,continue:!q.abort});if(Y>$)U.issues.push({origin:"number",input:Y,code:"too_big",maximum:$,inclusive:!0,inst:A,continue:!q.abort})}}),Qa=nA("$ZodCheckBigIntFormat",(A,q)=>{XZ.init(A,q);let[K,F]=Ni[q.format];A._zod.onattach.push((Z)=>{let $=Z._zod.bag;$.format=q.format,$.minimum=K,$.maximum=F}),A._zod.check=(Z)=>{let $=Z.value;if($<K)Z.issues.push({origin:"bigint",input:$,code:"too_small",minimum:K,inclusive:!0,inst:A,continue:!q.abort});if($>F)Z.issues.push({origin:"bigint",input:$,code:"too_big",maximum:F,inclusive:!0,inst:A,continue:!q.abort})}}),Xa=nA("$ZodCheckMaxSize",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.size!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.maximum??Number.POSITIVE_INFINITY;if(q.maximum<Z)F._zod.bag.maximum=q.maximum}),A._zod.check=(F)=>{let Z=F.value;if(Z.size<=q.maximum)return;F.issues.push({origin:DP(Z),code:"too_big",maximum:q.maximum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),Ga=nA("$ZodCheckMinSize",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.size!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(q.minimum>Z)F._zod.bag.minimum=q.minimum}),A._zod.check=(F)=>{let Z=F.value;if(Z.size>=q.minimum)return;F.issues.push({origin:DP(Z),code:"too_small",minimum:q.minimum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),ja=nA("$ZodCheckSizeEquals",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.size!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.minimum=q.size,Z.maximum=q.size,Z.size=q.size}),A._zod.check=(F)=>{let Z=F.value,$=Z.size;if($===q.size)return;let U=$>q.size;F.issues.push({origin:DP(Z),...U?{code:"too_big",maximum:q.size}:{code:"too_small",minimum:q.size},inclusive:!0,exact:!0,input:F.value,inst:A,continue:!q.abort})}}),Ja=nA("$ZodCheckMaxLength",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.length!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.maximum??Number.POSITIVE_INFINITY;if(q.maximum<Z)F._zod.bag.maximum=q.maximum}),A._zod.check=(F)=>{let Z=F.value;if(Z.length<=q.maximum)return;let U=RP(Z);F.issues.push({origin:U,code:"too_big",maximum:q.maximum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),Ha=nA("$ZodCheckMinLength",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.length!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(q.minimum>Z)F._zod.bag.minimum=q.minimum}),A._zod.check=(F)=>{let Z=F.value;if(Z.length>=q.minimum)return;let U=RP(Z);F.issues.push({origin:U,code:"too_small",minimum:q.minimum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),Ea=nA("$ZodCheckLengthEquals",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.length!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.minimum=q.length,Z.maximum=q.length,Z.length=q.length}),A._zod.check=(F)=>{let Z=F.value,$=Z.length;if($===q.length)return;let U=RP(Z),Y=$>q.length;F.issues.push({origin:U,...Y?{code:"too_big",maximum:q.length}:{code:"too_small",minimum:q.length},inclusive:!0,exact:!0,input:F.value,inst:A,continue:!q.abort})}}),Fx=nA("$ZodCheckStringFormat",(A,q)=>{var K,F;if(XZ.init(A,q),A._zod.onattach.push((Z)=>{let $=Z._zod.bag;if($.format=q.format,q.pattern)$.patterns??($.patterns=new Set),$.patterns.add(q.pattern)}),q.pattern)(K=A._zod).check??(K.check=(Z)=>{if(q.pattern.lastIndex=0,q.pattern.test(Z.value))return;Z.issues.push({origin:"string",code:"invalid_format",format:q.format,input:Z.value,...q.pattern?{pattern:q.pattern.toString()}:{},inst:A,continue:!q.abort})});else(F=A._zod).check??(F.check=()=>{})}),Wa=nA("$ZodCheckRegex",(A,q)=>{Fx.init(A,q),A._zod.check=(K)=>{if(q.pattern.lastIndex=0,q.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:"regex",input:K.value,pattern:q.pattern.toString(),inst:A,continue:!q.abort})}}),ga=nA("$ZodCheckLowerCase",(A,q)=>{q.pattern??(q.pattern=Za),Fx.init(A,q)}),Va=nA("$ZodCheckUpperCase",(A,q)=>{q.pattern??(q.pattern=$a),Fx.init(A,q)}),La=nA("$ZodCheckIncludes",(A,q)=>{XZ.init(A,q);let K=PX(q.includes),F=new RegExp(typeof q.position==="number"?`^.{${q.position}}${K}`:K);q.pattern=F,A._zod.onattach.push((Z)=>{let $=Z._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(F)}),A._zod.check=(Z)=>{if(Z.value.includes(q.includes,q.position))return;Z.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:q.includes,input:Z.value,inst:A,continue:!q.abort})}}),xa=nA("$ZodCheckStartsWith",(A,q)=>{XZ.init(A,q);let K=new RegExp(`^${PX(q.prefix)}.*`);q.pattern??(q.pattern=K),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.patterns??(Z.patterns=new Set),Z.patterns.add(K)}),A._zod.check=(F)=>{if(F.value.startsWith(q.prefix))return;F.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:q.prefix,input:F.value,inst:A,continue:!q.abort})}}),Oa=nA("$ZodCheckEndsWith",(A,q)=>{XZ.init(A,q);let K=new RegExp(`.*${PX(q.suffix)}$`);q.pattern??(q.pattern=K),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.patterns??(Z.patterns=new Set),Z.patterns.add(K)}),A._zod.check=(F)=>{if(F.value.endsWith(q.suffix))return;F.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:q.suffix,input:F.value,inst:A,continue:!q.abort})}});function n7A(A,q,K){if(A.issues.length)q.issues.push(...P0(K,A.issues))}var Ma=nA("$ZodCheckProperty",(A,q)=>{XZ.init(A,q),A._zod.check=(K)=>{let F=q.schema._zod.run({value:K.value[q.property],issues:[]},{});if(F instanceof Promise)return F.then((Z)=>n7A(Z,K,q.property));n7A(F,K,q.property);return}}),za=nA("$ZodCheckMimeType",(A,q)=>{XZ.init(A,q);let K=new Set(q.mime);A._zod.onattach.push((F)=>{F._zod.bag.mime=q.mime}),A._zod.check=(F)=>{if(K.has(F.value.type))return;F.issues.push({code:"invalid_value",values:q.mime,input:F.value.type,inst:A,continue:!q.abort})}}),Ia=nA("$ZodCheckOverwrite",(A,q)=>{XZ.init(A,q),A._zod.check=(K)=>{K.value=q.tx(K.value)}});class NS{constructor(A=[]){if(this.content=[],this.indent=0,this)this.args=A}indented(A){this.indent+=1,A(this),this.indent-=1}write(A){if(typeof A==="function"){A(this,{execution:"sync"}),A(this,{execution:"async"});return}let K=A.split(`
|
|
909
909
|
`).filter(($)=>$),F=Math.min(...K.map(($)=>$.length-$.trimStart().length)),Z=K.map(($)=>$.slice(F)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of Z)this.content.push($)}compile(){let A=Function,q=this?.args,F=[...(this?.content??[""]).map((Z)=>` ${Z}`)];return new A(...q,F.join(`
|
|
910
910
|
`))}}var Pa={major:4,minor:4,patch:3};var yK=nA("$ZodType",(A,q)=>{var K;A??(A={}),A._zod.def=q,A._zod.bag=A._zod.bag||{},A._zod.version=Pa;let F=[...A._zod.def.checks??[]];if(A._zod.traits.has("$ZodCheck"))F.unshift(A);for(let Z of F)for(let $ of Z._zod.onattach)$(A);if(F.length===0)(K=A._zod).deferred??(K.deferred=[]),A._zod.deferred?.push(()=>{A._zod.run=A._zod.parse});else{let Z=(U,Y,X)=>{let j=LE(U),J;for(let E of Y){if(E._zod.def.when){if(_i(U))continue;if(!E._zod.def.when(U))continue}else if(j)continue;let W=U.issues.length,g=E._zod.check(U);if(g instanceof Promise&&X?.async===!1)throw new g4;if(J||g instanceof Promise)J=(J??Promise.resolve()).then(async()=>{if(await g,U.issues.length===W)return;if(!j)j=LE(U,W)});else{if(U.issues.length===W)continue;if(!j)j=LE(U,W)}}if(J)return J.then(()=>{return U});return U},$=(U,Y,X)=>{if(LE(U))return U.aborted=!0,U;let j=Z(Y,F,X);if(j instanceof Promise){if(X.async===!1)throw new g4;return j.then((J)=>A._zod.parse(J,X))}return A._zod.parse(j,X)};A._zod.run=(U,Y)=>{if(Y.skipChecks)return A._zod.parse(U,Y);if(Y.direction==="backward"){let j=A._zod.parse({value:U.value,issues:[]},{...Y,skipChecks:!0});if(j instanceof Promise)return j.then((J)=>{return $(J,U,Y)});return $(j,U,Y)}let X=A._zod.parse(U,Y);if(X instanceof Promise){if(Y.async===!1)throw new g4;return X.then((j)=>Z(j,F,Y))}return Z(X,F,Y)}}NF(A,"~standard",()=>({validate:(Z)=>{try{let $=Di(A,Z);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return Ri(A,Z).then((U)=>U.success?{value:U.data}:{issues:U.error?.issues})}},vendor:"zod",version:1}))}),J5=nA("$ZodString",(A,q)=>{yK.init(A,q),A._zod.pattern=[...A?._zod.bag?.patterns??[]].pop()??ti(A._zod.bag),A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=String(K.value)}catch(Z){}if(typeof K.value==="string")return K;return K.issues.push({expected:"string",code:"invalid_type",input:K.value,inst:A}),K}}),s1=nA("$ZodStringFormat",(A,q)=>{Fx.init(A,q),J5.init(A,q)}),_a=nA("$ZodGUID",(A,q)=>{q.pattern??(q.pattern=hi),s1.init(A,q)}),wa=nA("$ZodUUID",(A,q)=>{if(q.version){let F={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[q.version];if(F===void 0)throw Error(`Invalid UUID version: "${q.version}"`);q.pattern??(q.pattern=j5(F))}else q.pattern??(q.pattern=j5());s1.init(A,q)}),Ba=nA("$ZodEmail",(A,q)=>{q.pattern??(q.pattern=yi),s1.init(A,q)}),Da=nA("$ZodURL",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{try{let F=K.value.trim();if(!q.normalize&&q.protocol?.source===di.source){if(!/^https?:\/\//i.test(F)){K.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:K.value,inst:A,continue:!q.abort});return}}let Z=new URL(F);if(q.hostname){if(q.hostname.lastIndex=0,!q.hostname.test(Z.hostname))K.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:q.hostname.source,input:K.value,inst:A,continue:!q.abort})}if(q.protocol){if(q.protocol.lastIndex=0,!q.protocol.test(Z.protocol.endsWith(":")?Z.protocol.slice(0,-1):Z.protocol))K.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:q.protocol.source,input:K.value,inst:A,continue:!q.abort})}if(q.normalize)K.value=Z.href;else K.value=F;return}catch(F){K.issues.push({code:"invalid_format",format:"url",input:K.value,inst:A,continue:!q.abort})}}}),Ra=nA("$ZodEmoji",(A,q)=>{q.pattern??(q.pattern=ui()),s1.init(A,q)}),Ta=nA("$ZodNanoID",(A,q)=>{q.pattern??(q.pattern=Ci),s1.init(A,q)}),Sa=nA("$ZodCUID",(A,q)=>{q.pattern??(q.pattern=Ti),s1.init(A,q)}),ba=nA("$ZodCUID2",(A,q)=>{q.pattern??(q.pattern=Si),s1.init(A,q)}),va=nA("$ZodULID",(A,q)=>{q.pattern??(q.pattern=bi),s1.init(A,q)}),ka=nA("$ZodXID",(A,q)=>{q.pattern??(q.pattern=vi),s1.init(A,q)}),Ca=nA("$ZodKSUID",(A,q)=>{q.pattern??(q.pattern=ki),s1.init(A,q)}),fa=nA("$ZodISODateTime",(A,q)=>{q.pattern??(q.pattern=ri(q)),s1.init(A,q)}),ha=nA("$ZodISODate",(A,q)=>{q.pattern??(q.pattern=si),s1.init(A,q)}),ya=nA("$ZodISOTime",(A,q)=>{q.pattern??(q.pattern=oi(q)),s1.init(A,q)}),ua=nA("$ZodISODuration",(A,q)=>{q.pattern??(q.pattern=fi),s1.init(A,q)}),ca=nA("$ZodIPv4",(A,q)=>{q.pattern??(q.pattern=ci),s1.init(A,q),A._zod.bag.format="ipv4"}),ma=nA("$ZodIPv6",(A,q)=>{q.pattern??(q.pattern=mi),s1.init(A,q),A._zod.bag.format="ipv6",A._zod.check=(K)=>{try{new URL(`http://[${K.value}]`)}catch{K.issues.push({code:"invalid_format",format:"ipv6",input:K.value,inst:A,continue:!q.abort})}}}),pa=nA("$ZodMAC",(A,q)=>{q.pattern??(q.pattern=pi(q.delimiter)),s1.init(A,q),A._zod.bag.format="mac"}),la=nA("$ZodCIDRv4",(A,q)=>{q.pattern??(q.pattern=li),s1.init(A,q)}),ia=nA("$ZodCIDRv6",(A,q)=>{q.pattern??(q.pattern=ii),s1.init(A,q),A._zod.check=(K)=>{let F=K.value.split("/");try{if(F.length!==2)throw Error();let[Z,$]=F;if(!$)throw Error();let U=Number($);if(`${U}`!==$)throw Error();if(U<0||U>128)throw Error();new URL(`http://[${Z}]`)}catch{K.issues.push({code:"invalid_format",format:"cidrv6",input:K.value,inst:A,continue:!q.abort})}}});function aa(A){if(A==="")return!0;if(/\s/.test(A))return!1;if(A.length%4!==0)return!1;try{return atob(A),!0}catch{return!1}}var da=nA("$ZodBase64",(A,q)=>{q.pattern??(q.pattern=ai),s1.init(A,q),A._zod.bag.contentEncoding="base64",A._zod.check=(K)=>{if(aa(K.value))return;K.issues.push({code:"invalid_format",format:"base64",input:K.value,inst:A,continue:!q.abort})}});function jJA(A){if(!zS.test(A))return!1;let q=A.replace(/[-_]/g,(F)=>F==="-"?"+":"/"),K=q.padEnd(Math.ceil(q.length/4)*4,"=");return aa(K)}var na=nA("$ZodBase64URL",(A,q)=>{q.pattern??(q.pattern=zS),s1.init(A,q),A._zod.bag.contentEncoding="base64url",A._zod.check=(K)=>{if(jJA(K.value))return;K.issues.push({code:"invalid_format",format:"base64url",input:K.value,inst:A,continue:!q.abort})}}),sa=nA("$ZodE164",(A,q)=>{q.pattern??(q.pattern=ni),s1.init(A,q)});function JJA(A,q=null){try{let K=A.split(".");if(K.length!==3)return!1;let[F]=K;if(!F)return!1;let Z=JSON.parse(atob(F));if("typ"in Z&&Z?.typ!=="JWT")return!1;if(!Z.alg)return!1;if(q&&(!("alg"in Z)||Z.alg!==q))return!1;return!0}catch{return!1}}var oa=nA("$ZodJWT",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{if(JJA(K.value,q.alg))return;K.issues.push({code:"invalid_format",format:"jwt",input:K.value,inst:A,continue:!q.abort})}}),ra=nA("$ZodCustomStringFormat",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{if(q.fn(K.value))return;K.issues.push({code:"invalid_format",format:q.format,input:K.value,inst:A,continue:!q.abort})}}),RS=nA("$ZodNumber",(A,q)=>{yK.init(A,q),A._zod.pattern=A._zod.bag.pattern??vP,A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=Number(K.value)}catch(U){}let Z=K.value;if(typeof Z==="number"&&!Number.isNaN(Z)&&Number.isFinite(Z))return K;let $=typeof Z==="number"?Number.isNaN(Z)?"NaN":!Number.isFinite(Z)?"Infinity":void 0:void 0;return K.issues.push({expected:"number",code:"invalid_type",input:Z,inst:A,...$?{received:$}:{}}),K}}),ta=nA("$ZodNumberFormat",(A,q)=>{Ya.init(A,q),RS.init(A,q)}),fP=nA("$ZodBoolean",(A,q)=>{yK.init(A,q),A._zod.pattern=qa,A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=Boolean(K.value)}catch($){}let Z=K.value;if(typeof Z==="boolean")return K;return K.issues.push({expected:"boolean",code:"invalid_type",input:Z,inst:A}),K}}),TS=nA("$ZodBigInt",(A,q)=>{yK.init(A,q),A._zod.pattern=ei,A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=BigInt(K.value)}catch(Z){}if(typeof K.value==="bigint")return K;return K.issues.push({expected:"bigint",code:"invalid_type",input:K.value,inst:A}),K}}),ea=nA("$ZodBigIntFormat",(A,q)=>{Qa.init(A,q),TS.init(A,q)}),Ad=nA("$ZodSymbol",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{let Z=K.value;if(typeof Z==="symbol")return K;return K.issues.push({expected:"symbol",code:"invalid_type",input:Z,inst:A}),K}}),qd=nA("$ZodUndefined",(A,q)=>{yK.init(A,q),A._zod.pattern=Fa,A._zod.values=new Set([void 0]),A._zod.parse=(K,F)=>{let Z=K.value;if(typeof Z>"u")return K;return K.issues.push({expected:"undefined",code:"invalid_type",input:Z,inst:A}),K}}),Kd=nA("$ZodNull",(A,q)=>{yK.init(A,q),A._zod.pattern=Ka,A._zod.values=new Set([null]),A._zod.parse=(K,F)=>{let Z=K.value;if(Z===null)return K;return K.issues.push({expected:"null",code:"invalid_type",input:Z,inst:A}),K}}),Fd=nA("$ZodAny",(A,q)=>{yK.init(A,q),A._zod.parse=(K)=>K}),Zd=nA("$ZodUnknown",(A,q)=>{yK.init(A,q),A._zod.parse=(K)=>K}),$d=nA("$ZodNever",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{return K.issues.push({expected:"never",code:"invalid_type",input:K.value,inst:A}),K}}),Ud=nA("$ZodVoid",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{let Z=K.value;if(typeof Z>"u")return K;return K.issues.push({expected:"void",code:"invalid_type",input:Z,inst:A}),K}}),Yd=nA("$ZodDate",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=new Date(K.value)}catch(Y){}let Z=K.value,$=Z instanceof Date;if($&&!Number.isNaN(Z.getTime()))return K;return K.issues.push({expected:"date",code:"invalid_type",input:Z,...$?{received:"Invalid Date"}:{},inst:A}),K}});function r7A(A,q,K){if(A.issues.length)q.issues.push(...P0(K,A.issues));q.value[K]=A.value}var Qd=nA("$ZodArray",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{let Z=K.value;if(!Array.isArray(Z))return K.issues.push({expected:"array",code:"invalid_type",input:Z,inst:A}),K;K.value=Array(Z.length);let $=[];for(let U=0;U<Z.length;U++){let Y=Z[U],X=q.element._zod.run({value:Y,issues:[]},F);if(X instanceof Promise)$.push(X.then((j)=>r7A(j,K,U)));else r7A(X,K,U)}if($.length)return Promise.all($).then(()=>K);return K}});function DS(A,q,K,F,Z,$){let U=K in F;if(A.issues.length){if(Z&&$&&!U)return;q.issues.push(...P0(K,A.issues))}if(!U&&!Z){if(!A.issues.length)q.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[K]});return}if(A.value===void 0){if(U)q.value[K]=void 0}else q.value[K]=A.value}function HJA(A){let q=Object.keys(A.shape);for(let F of q)if(!A.shape?.[F]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${F}": expected a Zod schema`);let K=Ii(A.shape);return{...A,keys:q,keySet:new Set(q),numKeys:q.length,optionalKeys:new Set(K)}}function EJA(A,q,K,F,Z,$){let U=[],Y=Z.keySet,X=Z.catchall._zod,j=X.def.type,J=X.optin==="optional",E=X.optout==="optional";for(let W in q){if(W==="__proto__")continue;if(Y.has(W))continue;if(j==="never"){U.push(W);continue}let g=X.run({value:q[W],issues:[]},F);if(g instanceof Promise)A.push(g.then((L)=>DS(L,K,W,q,J,E)));else DS(g,K,W,q,J,E)}if(U.length)K.issues.push({code:"unrecognized_keys",keys:U,input:q,inst:$});if(!A.length)return K;return Promise.all(A).then(()=>{return K})}var WJA=nA("$ZodObject",(A,q)=>{if(yK.init(A,q),!Object.getOwnPropertyDescriptor(q,"shape")?.get){let Y=q.shape;Object.defineProperty(q,"shape",{get:()=>{let X={...Y};return Object.defineProperty(q,"shape",{value:X}),X}})}let F=r2(()=>HJA(q));NF(A._zod,"propValues",()=>{let Y=q.shape,X={};for(let j in Y){let J=Y[j]._zod;if(J.values){X[j]??(X[j]=new Set);for(let E of J.values)X[j].add(E)}}return X});let Z=G5,$=q.catchall,U;A._zod.parse=(Y,X)=>{U??(U=F.value);let j=Y.value;if(!Z(j))return Y.issues.push({expected:"object",code:"invalid_type",input:j,inst:A}),Y;Y.value={};let J=[],E=U.shape;for(let W of U.keys){let g=E[W],L=g._zod.optin==="optional",M=g._zod.optout==="optional",O=g._zod.run({value:j[W],issues:[]},X);if(O instanceof Promise)J.push(O.then((_)=>DS(_,Y,W,j,L,M)));else DS(O,Y,W,j,L,M)}if(!$)return J.length?Promise.all(J).then(()=>Y):Y;return EJA(J,j,Y,X,F.value,A)}}),Xd=nA("$ZodObjectJIT",(A,q)=>{WJA.init(A,q);let K=A._zod.parse,F=r2(()=>HJA(q)),Z=(W)=>{let g=new NS(["shape","payload","ctx"]),L=F.value,M=(T)=>{let v=GS(T);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};g.write("const input = payload.value;");let O=Object.create(null),_=0;for(let T of L.keys)O[T]=`key_${_++}`;g.write("const newResult = {};");for(let T of L.keys){let v=O[T],y=GS(T),i=W[T],l=i?._zod?.optin==="optional",n=i?._zod?.optout==="optional";if(g.write(`const ${v} = ${M(T)};`),l&&n)g.write(`
|
|
@@ -1427,7 +1427,7 @@ and active MCP WebSocket clients.`,rtq=(A)=>{if(A===null||typeof A!=="object")re
|
|
|
1427
1427
|
usage: funnel update
|
|
1428
1428
|
|
|
1429
1429
|
Runs "bun i -g @interactive-inc/claude-funnel".`,S3A="@interactive-inc/claude-funnel",b3A=_6.createHandlers(tq("query",c.object({}),ttq),async(A)=>{let K=await new jY().attach(["bun","i","-g",S3A]);if(K!==0)throw new pK(500,{message:`update failed (exit ${K})`});return A.text(`updated ${S3A}`)});import{join as _YK}from"path";class XV{}class sKA{}class oKA extends sKA{constructor(){super();Object.freeze(this)}async fetch(A){let q=await globalThis.fetch(A.url,{method:A.method,headers:A.headers,body:A.body});return{status:q.status,ok:q.ok,text:()=>q.text(),json:()=>q.json()}}}var etq="https://discord.com/api/v10",Aeq=new oKA;class rKA extends XV{token;http;constructor(A){super();this.token=A.config.botToken,this.http=A.http??Aeq,Object.freeze(this)}async call(A){let q=(A.method||"GET").toUpperCase(),K=A.path.startsWith("/")?A.path:`/${A.path}`,F=A.body,Z=F!==null&&typeof F==="object"&&q!=="GET"&&Object.keys(F).length>0,$=await this.http.fetch({method:q,url:`${etq}${K}`,headers:{Authorization:`Bot ${this.token}`,"Content-Type":"application/json"},body:Z?JSON.stringify(A.body):void 0});if(!$.ok)throw Error(`Discord API failed (${$.status}): ${await $.text()}`);if($.status===204)return null;return await $.json()}}var tJ=MK(V1q(),1);class rJ{isAlive(){return!0}}class lYA{ownUserId;constructor(A){this.ownUserId=A.ownUserId}process(A){if(A.authorIsBot)return{skip:!0};let q=this.ownUserId?A.mentionedUserIds.includes(this.ownUserId):!1;return{skip:!1,content:JSON.stringify(A.raw),meta:{event_type:"discord",channel_id:A.channelId,user_id:A.authorId,mentioned:String(q),guild_id:A.guildId??""}}}}var y_6=new w$;class iYA extends rJ{config;logger;client=null;constructor(A){super();this.config=A.config,this.logger=A.logger??y_6}async start(A){let q=new tJ.Client({intents:[tJ.GatewayIntentBits.Guilds,tJ.GatewayIntentBits.GuildMessages,tJ.GatewayIntentBits.MessageContent,tJ.GatewayIntentBits.DirectMessages],partials:[tJ.Partials.Channel]});q.on("messageCreate",async(K)=>{let F=q.user?.id??"",Z=[...K.mentions.users.keys()];this.logger.info("discord messageCreate",{author:K.author.id,authorIsBot:String(K.author.bot),channelId:K.channelId,guildId:K.guildId??"",mentions:Z.join(","),ownUserId:F,mentioned:String(Z.includes(F))});let U=new lYA({ownUserId:F}).process({authorId:K.author.id,authorIsBot:K.author.bot,channelId:K.channelId,guildId:K.guildId,mentionedUserIds:Z,raw:K.toJSON()});if(U.skip){this.logger.info("discord skip",{reason:"bot author"});return}try{await A(U.content,U.meta)}catch(Y){this.logger.error("discord notify error",{error:Y instanceof Error?Y.message:String(Y)})}}),q.on("ready",(K)=>{this.logger.info("discord ready",{userId:K.user.id,tag:K.user.tag,guilds:String(K.guilds.cache.size)})}),q.on("error",(K)=>{this.logger.error("discord client error",{error:K instanceof Error?K.message:String(K)})}),await q.login(this.config.botToken),this.client=q}async stop(){if(!this.client)return;try{await this.client.destroy()}catch(A){this.logger.error("discord stop error",{error:A instanceof Error?A.message:String(A)})}finally{this.client=null}}isAlive(){return this.client!==null}}var u_6=new jY;class aYA extends XV{process;constructor(A={}){super();this.process=A.process??u_6,Object.freeze(this)}async call(A){let q=["api",A.path];if(A.method&&A.method.toLowerCase()!=="get")q.push("-X",A.method.toUpperCase());let K=A.body&&typeof A.body==="object"&&Object.keys(A.body).length>0;if(K)q.push("--input","-");let F=await this.process.run(["gh",...q],{input:K?JSON.stringify(A.body):void 0});if(F.exitCode!==0)throw Error(`gh api failed: ${F.stderr.trim()||F.stdout.trim()}`);try{return JSON.parse(F.stdout)}catch{return F.stdout}}}var c_6=c.object({id:c.string(),reason:c.string(),subject:c.object({type:c.string(),url:c.string(),title:c.string()}),repository:c.object({full_name:c.string()}),updated_at:c.string()}),m_6=c.array(c_6),p_6=new jY,l_6=new w$,i_6=1e4,a_6=5000;class dYA extends rJ{config;process;logger;now;seen=new Map;bootstrapped=!1;since;timer=null;constructor(A){super();this.config=A.config,this.process=A.process??p_6,this.logger=A.logger??l_6,this.now=A.now??(()=>new Date),this.since=this.now().toISOString()}async start(A){await this.pollOnce(A);let q=this.config.pollInterval??60;this.timer=setInterval(()=>void this.pollOnce(A),q*1000),this.timer.unref()}async stop(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}isAlive(){return this.timer!==null}async pollOnce(A){let q=this.now().toISOString(),K=new URLSearchParams({since:this.since,all:"false"});try{let F=await this.process.run(["gh","api",`/notifications?${K}`]);if(F.exitCode!==0){this.logger.error("gh poll failed",{stderr:F.stderr});return}let Z=m_6.safeParse(JSON.parse(F.stdout));if(!Z.success){this.logger.warn("gh response did not match schema",{error:Z.error.message});return}let $=Z.data;for(let U of $){if(this.seen.get(U.id)===U.updated_at)continue;if(this.seen.set(U.id,U.updated_at),!this.bootstrapped)continue;let Y={event_type:"gh",reason:U.reason,subject_type:U.subject.type,subject_url:U.subject.url,repository:U.repository.full_name,thread_id:U.id,updated_at:U.updated_at};await A(JSON.stringify(U),Y)}if(this.seen.size>i_6){let U=this.seen.size-a_6,Y=0;for(let X of this.seen.keys()){if(Y>=U)break;this.seen.delete(X),Y++}}this.since=q,this.bootstrapped=!0}catch(F){this.logger.error("gh poll error",{error:F instanceof Error?F.message:String(F)})}}}var fB=(A,q,K)=>{let F=new Set;for(let Z of A.split(",")){let[$,U]=Z.split("/"),Y=U?Number(U):1;if(!Number.isFinite(Y)||Y<=0)throw Error(`invalid cron step: "${U}"`);let X=q,j=K;if($==="*"||$===void 0||$==="")X=q,j=K;else if($.includes("-")){let[J,E]=$.split("-"),W=Number(J),g=Number(E);if(!Number.isFinite(W)||!Number.isFinite(g))throw Error(`invalid cron range: "${$}"`);X=W,j=g}else{let J=Number($);if(!Number.isFinite(J))throw Error(`invalid cron value: "${$}"`);X=J,j=U?K:J}if(X<q||j>K||X>j)throw Error(`cron value out of range: ${$} (must be ${q}-${K})`);for(let J=X;J<=j;J+=Y)F.add(J)}return{min:q,max:K,values:F}},iu=(A,q)=>{let K=A.trim().split(/\s+/);if(K.length!==5)throw Error(`cron must have 5 fields (got ${K.length}): "${A}"`);let[F,Z,$,U,Y]=K;if(!F||!Z||!$||!U||!Y)throw Error(`cron has empty fields: "${A}"`);let X=[{field:fB(F,0,59),value:q.getMinutes()},{field:fB(Z,0,23),value:q.getHours()},{field:fB($,1,31),value:q.getDate()},{field:fB(U,1,12),value:q.getMonth()+1},{field:fB(Y,0,6),value:q.getDay()}];for(let{field:j,value:J}of X)if(!j.values.has(J))return!1;return!0};var d_6=new w$,L1q=1440;class nYA extends rJ{config;lastFiredStore;logger;now;onFired;timer=null;stopped=!1;constructor(A){super();this.config=A.config,this.lastFiredStore=A.lastFiredStore,this.logger=A.logger??d_6,this.now=A.now??(()=>new Date),this.onFired=A.onFired??null}async start(A){this.stopped=!1;let q=()=>{if(this.stopped)return;let K=this.now(),F=60000-(K.getSeconds()*1000+K.getMilliseconds());this.timer=setTimeout(async()=>{if(this.stopped)return;await this.tick(A),q()},F),this.timer.unref()};await this.tick(A),q()}async stop(){if(this.stopped=!0,this.timer)clearTimeout(this.timer),this.timer=null}isAlive(){return!this.stopped&&this.timer!==null}async tick(A){let q=this.truncateToMinute(this.now()),K=this.lastFiredStore.load(),F=!1;for(let Z of this.config.entries){if(!Z.enabled)continue;if(await this.fireEntry(Z,q,K,A))F=!0}if(F)this.lastFiredStore.save(K)}async fireEntry(A,q,K,F){let Z=K.get(A.id),$=Z?new Date(Z.getTime()+60000):q;if($.getTime()>q.getTime())return!1;if(A.catchupPolicy==="skip"){try{if(!iu(A.cron,q))return!1}catch(Y){return this.logInvalidCron(A,Y),!1}return await this.notifyOne(A,q,F,!1),K.set(A.id,q),!0}if(A.catchupPolicy==="all"){let Y=this.findAllMatches(A.cron,$,q,A.id);if(Y.length===0)return!1;for(let X of Y)await this.notifyOne(A,X,F,X.getTime()!==q.getTime());return K.set(A.id,Y[Y.length-1]??q),!0}let U=this.findMostRecentMatch(A.cron,$,q,A.id);if(!U)return!1;return await this.notifyOne(A,U,F,U.getTime()!==q.getTime()),K.set(A.id,U),!0}async notifyOne(A,q,K,F){let Z={event_type:"schedule",schedule_id:A.id,cron:A.cron,fired_at:q.toISOString(),catchup_policy:A.catchupPolicy};if(F)Z.catchup="true";if(await K(A.prompt,Z),this.onFired)try{await this.onFired(A,q)}catch($){this.logger.error("schedule onFired callback failed",{connector:this.config.name,id:A.id,error:$ instanceof Error?$.message:String($)})}}findMostRecentMatch(A,q,K,F){let Z=Math.min(L1q,Math.floor((K.getTime()-q.getTime())/60000)+1);for(let $=0;$<Z;$++){let U=new Date(K.getTime()-$*60000);try{if(iu(A,U))return U}catch(Y){return this.logInvalidCron({id:F,cron:A},Y),null}}return null}findAllMatches(A,q,K,F){let Z=Math.min(L1q,Math.floor((K.getTime()-q.getTime())/60000)+1),$=[];for(let U=0;U<Z;U++){let Y=new Date(q.getTime()+U*60000);if(Y.getTime()>K.getTime())break;try{if(iu(A,Y))$.push(Y)}catch(X){return this.logInvalidCron({id:F,cron:A},X),[]}}return $}logInvalidCron(A,q){this.logger.error("invalid cron expression in schedule",{connector:this.config.name,id:A.id,cron:A.cron,error:q instanceof Error?q.message:String(q)})}truncateToMinute(A){let q=new Date(A.getTime());return q.setSeconds(0,0),q}}import{dirname as n_6}from"path";var s_6=new FY;class sYA{path;fs;constructor(A){this.path=A.path,this.fs=A.fs??s_6,Object.freeze(this)}load(){let A=new Map;if(!this.fs.existsSync(this.path))return A;let q=JSON.parse(this.fs.readFileSync(this.path));if(q===null||typeof q!=="object")return A;for(let[K,F]of Object.entries(q))if(typeof F==="string")A.set(K,new Date(F));return A}save(A){let q={};for(let[K,F]of A)q[K]=F.toISOString();this.fs.mkdirSync(n_6(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,`${JSON.stringify(q,null,2)}
|
|
1430
|
-
`)}}var kQq=MK(vQq(),1);var bb6=(A)=>{let q={};for(let[K,F]of Object.entries(A))q[K]=F;return q},vb6=(A)=>{if(!A||typeof A!=="object")return null;if(!("code"in A))return null;let q=A.code;if(typeof q!=="string"||!q.startsWith("slack_webapi_"))return null;if(!("data"in A))return null;let K=A.data;if(!K||typeof K!=="object")return null;return K};class P0A extends XV{client;constructor(A){super();this.client=A.client??new kQq.WebClient(A.config.botToken),Object.freeze(this)}async call(A){let q=A.body!==null&&typeof A.body==="object"?bb6(A.body):{};try{return await this.client.apiCall(A.path,q)}catch(K){let F=vb6(K);if(F)return F;throw K}}}var rp=MK(Xzq(),1);var qUK=new Set(["message","app_mention"]),KUK=new Set([void 0,"thread_broadcast","bot_message","file_share"]);var bj=(A,q)=>{let K=A[q];return typeof K==="string"?K:void 0};class w4A{ownBotUserId;ownBotId;now;dedup=new Map;constructor(A){this.ownBotUserId=A.ownBotUserId,this.ownBotId=A.ownBotId,this.now=A.now??(()=>Date.now())}process(A){let q=bj(A,"type");if(!q||!qUK.has(q))return{skip:!0};let K=bj(A,"subtype");if(!KUK.has(K))return{skip:!0};let F=bj(A,"channel")??"",Z=bj(A,"event_ts")??bj(A,"ts")??"",$=`${F}:${Z}`,U=this.now();if(this.dedup.has($))return{skip:!0};this.dedup.set($,U);for(let W of this.dedup.keys())if((this.dedup.get(W)??0)<U-1e4)this.dedup.delete(W);let Y=bj(A,"user"),X=bj(A,"bot_id");if(Y===this.ownBotUserId)return{skip:!0};if(X===this.ownBotId)return{skip:!0};let J=(bj(A,"text")??"").includes(`<@${this.ownBotUserId}>`),E=bj(A,"thread_ts")??bj(A,"ts")??"";return{skip:!1,content:JSON.stringify(A),meta:{event_type:"slack",channel_id:F,user_id:Y??"",mentioned:String(J),thread_ts:E},shouldReact:J,channel:F,timestamp:bj(A,"ts")??""}}}var FUK=c.object({event:c.record(c.string(),c.unknown()).optional()}),ZUK=new w$;class B4A extends rJ{config;logger;onAppCreated;preprocessEvent;app=null;constructor(A){super();this.config=A.config,this.logger=A.logger??ZUK,this.onAppCreated=A.onAppCreated??null,this.preprocessEvent=A.preprocessEvent??null}async start(A){let q=new rp.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:rp.LogLevel.ERROR}),K=await q.client.auth.test({token:this.config.botToken}),F=new w4A({ownBotUserId:K.user_id??"",ownBotId:K.bot_id??""}),Z=this.preprocessEvent;if(q.use(async($)=>{let U=FUK.safeParse($);if(!U.success||!U.data.event)return;let Y=U.data.event,X=Z?Z(Y):Y;if(X===null)return;let j=F.process(X);if(j.skip)return;if(j.shouldReact)try{await q.client.reactions.add({token:this.config.botToken,channel:j.channel,timestamp:j.timestamp,name:"eyes"})}catch{}
|
|
1430
|
+
`)}}var kQq=MK(vQq(),1);var bb6=(A)=>{let q={};for(let[K,F]of Object.entries(A))q[K]=F;return q},vb6=(A)=>{if(!A||typeof A!=="object")return null;if(!("code"in A))return null;let q=A.code;if(typeof q!=="string"||!q.startsWith("slack_webapi_"))return null;if(!("data"in A))return null;let K=A.data;if(!K||typeof K!=="object")return null;return K};class P0A extends XV{client;constructor(A){super();this.client=A.client??new kQq.WebClient(A.config.botToken),Object.freeze(this)}async call(A){let q=A.body!==null&&typeof A.body==="object"?bb6(A.body):{};try{return await this.client.apiCall(A.path,q)}catch(K){let F=vb6(K);if(F)return F;throw K}}}var rp=MK(Xzq(),1);var qUK=new Set(["message","app_mention"]),KUK=new Set([void 0,"thread_broadcast","bot_message","file_share"]);var bj=(A,q)=>{let K=A[q];return typeof K==="string"?K:void 0};class w4A{ownBotUserId;ownBotId;now;dedup=new Map;constructor(A){this.ownBotUserId=A.ownBotUserId,this.ownBotId=A.ownBotId,this.now=A.now??(()=>Date.now())}process(A){let q=bj(A,"type");if(!q||!qUK.has(q))return{skip:!0};let K=bj(A,"subtype");if(!KUK.has(K))return{skip:!0};let F=bj(A,"channel")??"",Z=bj(A,"event_ts")??bj(A,"ts")??"",$=`${F}:${Z}`,U=this.now();if(this.dedup.has($))return{skip:!0};this.dedup.set($,U);for(let W of this.dedup.keys())if((this.dedup.get(W)??0)<U-1e4)this.dedup.delete(W);let Y=bj(A,"user"),X=bj(A,"bot_id");if(Y===this.ownBotUserId)return{skip:!0};if(X===this.ownBotId)return{skip:!0};let J=(bj(A,"text")??"").includes(`<@${this.ownBotUserId}>`),E=bj(A,"thread_ts")??bj(A,"ts")??"";return{skip:!1,content:JSON.stringify(A),meta:{event_type:"slack",channel_id:F,user_id:Y??"",mentioned:String(J),thread_ts:E},shouldReact:J,channel:F,timestamp:bj(A,"ts")??""}}}var FUK=c.object({event:c.record(c.string(),c.unknown()).optional()}),ZUK=new w$;class B4A extends rJ{config;logger;onAppCreated;preprocessEvent;app=null;constructor(A){super();this.config=A.config,this.logger=A.logger??ZUK,this.onAppCreated=A.onAppCreated??null,this.preprocessEvent=A.preprocessEvent??null}async start(A){let q=new rp.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:rp.LogLevel.ERROR}),K=await q.client.auth.test({token:this.config.botToken}),F=new w4A({ownBotUserId:K.user_id??"",ownBotId:K.bot_id??""}),Z=this.preprocessEvent;if(q.use(async($)=>{let U=FUK.safeParse($);if(!U.success||!U.data.event)return;let Y=U.data.event,X=Z?Z(Y):Y;if(X===null)return;let j=F.process(X);if(j.skip)return;if(await A(j.content,j.meta),j.shouldReact)try{await q.client.reactions.add({token:this.config.botToken,channel:j.channel,timestamp:j.timestamp,name:"eyes"})}catch{}}),q.error(async($)=>{this.logger.error("Slack error",{error:$ instanceof Error?$.message:String($)})}),this.onAppCreated)await this.onAppCreated(q);await q.start(),this.app=q}async stop(){if(!this.app)return;try{await this.app.stop()}catch(A){this.logger.error("Slack stop error",{error:A instanceof Error?A.message:String(A)})}finally{this.app=null}}isAlive(){return this.app!==null}}import{homedir as $UK}from"os";import{dirname as UUK,join as Gzq}from"path";class hR{}var c8=Gzq($UK(),".funnel"),YUK=Gzq(c8,"settings.json"),QUK=new FY;class D4A extends hR{path;fs;constructor(A={}){super();this.path=A.path??YUK,this.fs=A.fs??QUK,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return{version:VJ,channels:[],profiles:[]};let A=this.fs.readFileSync(this.path),q=JSON.parse(A);if(this.looksLikeLegacy(q))throw Error(`legacy settings.json detected at ${this.path}. The schema changed (channel.connectors are now nested objects with ids; profile fields renamed). Migration is intentionally not provided. Back up and remove the old file:
|
|
1431
1431
|
mv ${this.path} ${this.path}.bak`);if(q&&typeof q==="object"&&"version"in q&&q.version!==VJ)throw Error(`unsupported settings.json version (${this.path}): expected ${VJ}, got ${String(q.version)}`);let K=Lk.safeParse(q);if(!K.success)throw Error(`invalid settings.json (${this.path}): ${K.error.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ")}`);return K.data}looksLikeLegacy(A){if(!A||typeof A!=="object")return!1;let q=A;if(Array.isArray(q.channels))for(let K of q.channels){if(!K||typeof K!=="object")continue;let F=K;if(Array.isArray(F.connectors)&&F.connectors.some((Z)=>typeof Z==="string"))return!0;if(!("id"in F)&&"name"in F)return!0}if(Array.isArray(q.connectors))return!0;if(Array.isArray(q.repositories))return!0;if(Array.isArray(q.profiles))for(let K of q.profiles){if(!K||typeof K!=="object")continue;let F=K;if("repository"in F||"envFiles"in F||"channel"in F&&!("channelId"in F))return!0}return!1}write(A){this.fs.mkdirSync(UUK(this.path),{recursive:!0});let q={...A,version:VJ};this.fs.writeFileSync(this.path,`${JSON.stringify(q,null,2)}
|
|
1432
1432
|
`)}}import{join as R4A}from"path";var XUK=new FY,GUK=new jY,jUK=new w$;class T4A{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor(A={}){this.fs=A.fs??XUK,this.process=A.process??GUK,this.logger=A.logger??jUK,this.dir=A.dir??c8,this.slackListenerOptions=A.slackListenerOptions??{},this.scheduleListenerOptions=A.scheduleListenerOptions??{},Object.freeze(this)}createListener(A,q){if(q.type==="slack")return new B4A({config:q,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(q.type==="gh")return new dYA({config:q,process:this.process,logger:this.logger});if(q.type==="discord")return new iYA({config:q,logger:this.logger});let K=new sYA({path:R4A(this.connectorDir(A,q.id),"state.json"),fs:this.fs});return new nYA({config:q,lastFiredStore:K,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter(A){if(A.type==="slack")return new P0A({config:A});if(A.type==="gh")return new aYA({process:this.process});if(A.type==="discord")return new rKA({config:A});return null}connectorDir(A,q){return R4A(this.dir,"channels",A,"connectors",q)}channelDir(A){return R4A(this.dir,"channels",A)}}function S4A(A){switch(A.type){case"slack":return[A.botToken,A.appToken];case"discord":return[A.botToken];case"gh":case"schedule":return[]}}function JUK(A,q){return A.type===q}function bL(A,q,K){let F=A.connectors.find((Z)=>Z.name===q);if(!F)throw Error(`connector "${q}" not found in channel "${A.name}"`);if(!JUK(F,K))throw Error(`connector "${q}" is type "${F.type}", not "${K}"`);return F}class yR{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class vL extends yR{now(){return new Date}}class uR{}class cR extends uR{generate(){return crypto.randomUUID()}}var HUK=new vL,EUK=new cR;class b4A{store;factory;profileChecker;clock;idGenerator;constructor(A){this.store=A.store,this.factory=A.factory,this.profileChecker=A.profileChecker,this.clock=A.clock??HUK,this.idGenerator=A.idGenerator??EUK,Object.freeze(this)}list(){return this.store.read().channels}get(A){return this.list().find((q)=>q.name===A)??null}getById(A){return this.list().find((q)=>q.id===A)??null}add(A){let q=this.store.read();if(q.channels.some((F)=>F.name===A.name))throw Error(`channel "${A.name}" already exists`);let K={id:this.idGenerator.generate(),name:A.name,delivery:A.delivery??"fanout",options:A.options??[],env:A.env??{},resume:A.resume??!0,connectors:[]};return q.channels.push(K),this.store.write(q),K}setDelivery(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.delivery=q,this.store.write(K)}setResume(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.resume=q,this.store.write(K)}setOptions(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.options=q,this.store.write(K)}setEnv(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.env=q,this.store.write(K)}remove(A){let q=this.store.read(),K=q.channels.findIndex((Z)=>Z.name===A);if(K<0)throw Error(`channel "${A}" not found`);let F=q.channels[K];if(F&&this.profileChecker.hasChannelRef(F.id))throw Error(`channel "${A}" is referenced by a profile`);q.channels.splice(K,1),this.store.write(q)}rename(A,q){let K=this.store.read(),F=K.channels.find((Z)=>Z.name===A);if(!F)throw Error(`channel "${A}" not found`);if(K.channels.some((Z)=>Z.name===q))throw Error(`channel "${q}" already exists`);F.name=q,this.store.write(K)}listConnectors(A){return this.requireChannel(this.store.read(),A).connectors}getConnector(A,q){let K=this.get(A);if(!K)return null;return K.connectors.find((F)=>F.name===q)??null}listAllConnectors(){let A=[];for(let q of this.list())for(let K of q.connectors)A.push({...K,channelId:q.id,channelName:q.name});return A}addConnector(A,q){let K=this.store.read(),F=this.requireChannel(K,A);if(F.connectors.some(($)=>$.name===q.name))throw Error(`connector "${q.name}" already exists in channel "${A}"`);let Z=this.fromInput(q);return this.assertNoTokenCollision(K,Z),F.connectors.push(Z),this.store.write(K),Z}fromInput(A){let q=this.idGenerator.generate(),K=this.clock.iso(),F=K,Z=K;switch(A.type){case"slack":return{id:q,type:"slack",name:A.name,botToken:A.botToken,appToken:A.appToken,createdAt:F,updatedAt:Z};case"gh":return{id:q,type:"gh",name:A.name,...A.pollInterval!==void 0?{pollInterval:A.pollInterval}:{},createdAt:F,updatedAt:Z};case"discord":return{id:q,type:"discord",name:A.name,botToken:A.botToken,createdAt:F,updatedAt:Z};case"schedule":return{id:q,type:"schedule",name:A.name,entries:A.entries??[],createdAt:F,updatedAt:Z}}}removeConnector(A,q){let K=this.store.read(),F=this.requireChannel(K,A),Z=F.connectors.findIndex(($)=>$.name===q);if(Z<0)throw Error(`connector "${q}" not found in channel "${A}"`);F.connectors.splice(Z,1),this.store.write(K)}renameConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=Z.connectors.find((U)=>U.name===q);if(!$)throw Error(`connector "${q}" not found in channel "${A}"`);if(Z.connectors.some((U)=>U.name===K))throw Error(`connector "${K}" already exists in channel "${A}"`);$.name=K,$.updatedAt=this.clock.iso(),this.store.write(F)}updateSlackConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"slack"),U={...$,botToken:K.botToken??$.botToken,appToken:K.appToken??$.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(F,U),Object.assign($,U),this.store.write(F)}updateGhConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"gh");if(K.pollInterval!==void 0)$.pollInterval=K.pollInterval;$.updatedAt=this.clock.iso(),this.store.write(F)}updateDiscordConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"discord"),U={...$,botToken:K.botToken??$.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(F,U),Object.assign($,U),this.store.write(F)}listScheduleEntries(A,q){let K=this.requireChannel(this.store.read(),A);return bL(K,q,"schedule").entries}addScheduleEntry(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"schedule"),U={id:K.id??this.idGenerator.generate(),cron:K.cron,prompt:K.prompt,enabled:K.enabled??!0,catchupPolicy:K.catchupPolicy??"latest"};return $.entries.push(U),$.updatedAt=this.clock.iso(),this.store.write(F),U}removeScheduleEntry(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"schedule"),U=$.entries.findIndex((Y)=>Y.id===K);if(U<0)throw Error(`schedule entry "${K}" not found`);$.entries.splice(U,1),$.updatedAt=this.clock.iso(),this.store.write(F)}async call(A,q,K){let F=this.getConnector(A,q);if(!F)throw Error(`connector "${q}" not found in channel "${A}"`);let Z=this.factory.createAdapter(F);if(!Z)throw Error(`connector type "${F.type}" does not support outbound calls`);return await Z.call(K)}createListener(A,q){let K=this.get(A);if(!K)return null;let F=K.connectors.find((Z)=>Z.name===q);if(!F)return null;return{config:F,channelId:K.id,listener:this.factory.createListener(K.id,F)}}createAllListeners(){let A=[];for(let q of this.list())for(let K of q.connectors)A.push({config:K,channelId:q.id,channelName:q.name,listener:this.factory.createListener(q.id,K)});return A}requireChannel(A,q){let K=A.channels.find((F)=>F.name===q);if(!K)throw Error(`channel "${q}" not found`);return K}assertNoTokenCollision(A,q){let K=S4A(q);if(K.length===0)return;for(let F of A.channels)for(let Z of F.connectors){if(Z.id===q.id)continue;for(let $ of S4A(Z))if(K.includes($))throw Error(`token already in use by connector "${Z.name}" in channel "${F.name}"`)}}}import{join as jzq}from"path";var WUK=new jY,gUK=new FY,VUK=new w$;class v4A{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor(A){this.channels=A.channels,this.mcp=A.mcp,this.gateway=A.gateway,this.sessions=A.sessions,this.process=A.process??WUK,this.fs=A.fs??gUK,this.logger=A.logger??VUK,this.pidDir=jzq(A.dir??c8,"claude"),Object.freeze(this)}async launch(A){let q=this.channels.get(A.channel)??this.channels.getById(A.channel);if(!q)throw Error(`channel "${A.channel}" not found`);if(A.profileName&&this.isRunning(A.profileName))throw Error(`profile "${A.profileName}" is already running`);let K=A.cwd??globalThis.process.cwd();if((A.installMcp??!0)&&!this.mcp.findInstalledName(K))this.mcp.install(K),this.logger.info("added funnel MCP to .mcp.json",{cwd:K});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if(A.profileName)this.writePidFile(A.profileName),this.installCleanup(A.profileName);let Z=q.resume?this.resolveSession(q.id,K,A.userArgs??[]):null,$=this.buildArgs(q.options,A.userArgs??[],K,Z),U=this.buildEnv(q.id,q.env);this.logger.info("claude launch",{channel:A.channel,channelId:q.id,cwd:K});try{return await this.process.attach(["claude",...$],{cwd:K,env:U,onSpawned:A.onSpawned})}finally{if(A.profileName)this.removePidFile(A.profileName)}}isRunning(A){let q=this.readPid(A);if(!q)return!1;return this.isProcessAlive(q)}pidPath(A){return jzq(this.pidDir,`${A}.pid`)}readPid(A){let q=this.pidPath(A);if(!this.fs.existsSync(q))return null;try{let K=this.fs.readFileSync(q).trim(),F=Number(K);if(!F||F<=0)return null;return F}catch{return null}}writePidFile(A){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath(A),String(globalThis.process.pid))}removePidFile(A){let q=this.pidPath(A);if(this.fs.existsSync(q))this.fs.unlink(q)}installCleanup(A){globalThis.process.once("exit",()=>this.removePidFile(A))}isProcessAlive(A){return this.process.isAlive(A)}buildArgs(A,q,K,F){let Z=[...A,...q];if(F!==null)if(F.mode==="resume")Z.push("--resume",F.id);else Z.push("--session-id",F.id);let $=this.mcp.findInstalledName(K);if($&&!Z.includes("--dangerously-load-development-channels")&&!Z.includes("--channels"))Z.push("--dangerously-load-development-channels",`server:${$}`);return Z}resolveSession(A,q,K){for(let Z of K){if(Z==="-c"||Z==="--continue")return null;if(Z==="--resume"||Z.startsWith("--resume="))return null;if(Z==="--session-id"||Z.startsWith("--session-id="))return null}let F=this.sessions.get(A,q);if(F!==null)return{id:F,mode:"resume"};return{id:this.sessions.create(A,q),mode:"new"}}buildEnv(A,q){let K={};for(let[F,Z]of Object.entries(q))K[F]=Z;for(let[F,Z]of Object.entries(globalThis.process.env))if(typeof Z==="string")K[F]=Z;return K.FUNNEL_CHANNEL_ID=A,K}}var LUK=384;class k4A extends G_{dirs;files;mtimes;modes;now;constructor(A={}){super();this.dirs=new Set(A.dirs??[]),this.files=new Map(Object.entries(A.files??{})),this.mtimes=new Map(Object.entries(A.mtimes??{})),this.modes=new Map(Object.entries(A.modes??{})),this.now=A.now??(()=>Date.now())}existsSync(A){return this.dirs.has(A)||this.files.has(A)}readFileSync(A){return this.files.get(A)??""}writeFileSync(A,q){this.files.set(A,q),this.touch(A)}writeSecretFileSync(A,q){this.files.set(A,q),this.modes.set(A,LUK),this.touch(A)}appendFileSync(A,q){let K=this.files.get(A)??"";this.files.set(A,K+q),this.touch(A)}unlink(A){this.files.delete(A),this.mtimes.delete(A),this.modes.delete(A)}mkdirSync(A,q){this.dirs.add(A)}readdirSync(A){let q=A.endsWith("/")?A:`${A}/`,K=[];for(let F of this.files.keys()){if(!F.startsWith(q))continue;let Z=F.slice(q.length);if(!Z.includes("/"))K.push(Z)}return K}statSync(A){let q=this.mtimes.get(A);if(q===void 0)throw Error(`not found: ${A}`);return{mtimeMs:q,mode:this.modes.get(A)??null}}setMtime(A,q){this.mtimes.set(A,q)}setMode(A,q){this.modes.set(A,q)}touch(A){if(!this.mtimes.has(A))this.mtimes.set(A,this.now());else this.mtimes.set(A,this.now())}}class C4A extends uR{counter=0;prefix;constructor(A={}){super();this.prefix=A.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as xUK}from"path";var OUK=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,MUK=(A)=>{if(A.length<2)return A;let q=A[0],K=A[A.length-1];if(q==='"'&&K==='"')return A.slice(1,-1);if(q==="'"&&K==="'")return A.slice(1,-1);return A};class f4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=xUK(A,N3A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q),F={};for(let Z of K.split(`
|
|
1433
1433
|
`)){let $=Z.trim();if($===""||$.startsWith("#"))continue;let U=$.match(OUK);if(!U)continue;let Y=U[1],X=U[2];if(!Y)continue;F[Y]=MUK(X??"")}return F}}import{join as zUK}from"path";class h4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=zUK(A,Df);if(!this.fs.existsSync(q))return null;let K=this.fs.readFileSync(q),F=(()=>{try{return JSON.parse(K)}catch($){let U=$ instanceof Error?$.message:String($);throw Error(`${Df} is not valid JSON: ${U}`)}})(),Z=Bf.safeParse(F);if(!Z.success)throw Error(`${Df} is invalid: ${Z.error.message}`);return Z.data}}var IUK=(A,q)=>{if(A.length!==q.length)return!1;for(let K=0;K<A.length;K++)if(A[K]!==q[K])return!1;return!0},PUK=(A,q)=>{let K=Object.keys(A);if(K.length!==Object.keys(q).length)return!1;for(let F of K)if(A[F]!==q[F])return!1;return!0};class y4A{channels;dotenv;prompter;env;constructor(A){this.channels=A.channels,this.dotenv=A.dotenv,this.prompter=A.prompter,this.env=A.env??process.env,Object.freeze(this)}async ensure(A,q){let K=this.channels.get(A.name),F=A.resume??!0;if(!K)this.channels.add({name:A.name,options:A.options??[],env:A.env??{},resume:F});else{let X=A.options??[],j=A.env??{};if(!IUK(K.options,X))this.channels.setOptions(A.name,X);if(!PUK(K.env,j))this.channels.setEnv(A.name,j);if(K.resume!==F)this.channels.setResume(A.name,F)}if(A.connectors===void 0)return{touched:[],removed:[]};let Z=this.dotenv.read(q),$=[],U=new Set;for(let X of A.connectors){let j=await this.ensureConnector(A.name,X,Z);$.push({name:j.name,changed:j.changed}),U.add(j.id)}let Y=this.removeExtras(A.name,U);return{touched:$,removed:Y}}async ensureConnector(A,q,K){if(q.type==="slack")return await this.ensureSlack(A,q,K);if(q.type==="discord")return await this.ensureDiscord(A,q,K);if(q.type==="gh")return this.ensureGh(A,q);return this.ensureSchedule(A,q)}async ensureSlack(A,q,K){let F=this.findExistingSlack(A,q.name),Z=await this.resolveField({literal:q.botToken,envVar:q.env?.botToken,dotenv:K,label:`${q.name}.botToken`,existing:F?.botToken}),$=await this.resolveField({literal:q.appToken,envVar:q.env?.appToken,dotenv:K,label:`${q.name}.appToken`,existing:F?.appToken});if(F){if(F.botToken!==Z||F.appToken!==$)return this.channels.updateSlackConnector(A,q.name,{botToken:Z,appToken:$}),{id:F.id,name:q.name,changed:!0};return{id:F.id,name:q.name,changed:!1}}let U=this.findSlackByToken(A,[Z,$]);if(U){if(this.channels.renameConnector(A,U.name,q.name),U.botToken!==Z||U.appToken!==$)this.channels.updateSlackConnector(A,q.name,{botToken:Z,appToken:$});return{id:U.id,name:q.name,changed:!0}}return{id:this.channels.addConnector(A,{type:"slack",name:q.name,botToken:Z,appToken:$}).id,name:q.name,changed:!0}}async ensureDiscord(A,q,K){let F=this.findExistingDiscord(A,q.name),Z=await this.resolveField({literal:q.botToken,envVar:q.env?.botToken,dotenv:K,label:`${q.name}.botToken`,existing:F?.botToken});if(F){if(F.botToken!==Z)return this.channels.updateDiscordConnector(A,q.name,{botToken:Z}),{id:F.id,name:q.name,changed:!0};return{id:F.id,name:q.name,changed:!1}}let $=this.findDiscordByToken(A,Z);if($){if(this.channels.renameConnector(A,$.name,q.name),$.botToken!==Z)this.channels.updateDiscordConnector(A,q.name,{botToken:Z});return{id:$.id,name:q.name,changed:!0}}return{id:this.channels.addConnector(A,{type:"discord",name:q.name,botToken:Z}).id,name:q.name,changed:!0}}ensureGh(A,q){let K=this.channels.getConnector(A,q.name);if(K&&K.type!=="gh")throw Error(`connector "${q.name}" exists in channel "${A}" with type "${K.type}", funnel.json declares "gh"`);if(K&&K.type==="gh"){if(q.pollInterval!==void 0&&K.pollInterval!==q.pollInterval)return this.channels.updateGhConnector(A,q.name,{pollInterval:q.pollInterval}),{id:K.id,name:q.name,changed:!0};return{id:K.id,name:q.name,changed:!1}}return{id:this.channels.addConnector(A,{type:"gh",name:q.name,...q.pollInterval!==void 0?{pollInterval:q.pollInterval}:{}}).id,name:q.name,changed:!0}}ensureSchedule(A,q){let K=this.channels.getConnector(A,q.name);if(K&&K.type!=="schedule")throw Error(`connector "${q.name}" exists in channel "${A}" with type "${K.type}", funnel.json declares "schedule"`);if(K&&K.type==="schedule")return{id:K.id,name:q.name,changed:!1};return{id:this.channels.addConnector(A,{type:"schedule",name:q.name}).id,name:q.name,changed:!0}}findExistingSlack(A,q){let K=this.channels.getConnector(A,q);if(!K)return null;if(K.type!=="slack")throw Error(`connector "${q}" exists in channel "${A}" with type "${K.type}", funnel.json declares "slack"`);return K}findExistingDiscord(A,q){let K=this.channels.getConnector(A,q);if(!K)return null;if(K.type!=="discord")throw Error(`connector "${q}" exists in channel "${A}" with type "${K.type}", funnel.json declares "discord"`);return K}findSlackByToken(A,q){let K=this.channels.get(A);if(!K)return null;for(let F of K.connectors){if(F.type!=="slack")continue;if(q.includes(F.botToken)||q.includes(F.appToken))return F}return null}findDiscordByToken(A,q){let K=this.channels.get(A);if(!K)return null;for(let F of K.connectors){if(F.type!=="discord")continue;if(F.botToken===q)return F}return null}removeExtras(A,q){let K=this.channels.get(A);if(!K)return[];let F=K.connectors.filter((Z)=>!q.has(Z.id));for(let Z of F)this.channels.removeConnector(A,Z.name);return F.map((Z)=>Z.name)}async resolveField(A){if(A.literal!==void 0&&A.envVar!==void 0)throw Error(`${A.label} is set both as a literal and as env.${A.label.split(".").pop()}; pick one`);if(A.literal!==void 0&&A.literal!=="")return A.literal;if(A.envVar!==void 0&&A.envVar!==""){let q=this.env[A.envVar];if(q)return q;let K=A.dotenv[A.envVar];if(K)return K;throw Error(`${A.label} references env var "${A.envVar}" but it is not set in process env or .env.local`)}if(A.existing)return A.existing;return await this.prompter.promptSecret(A.label)}}class u4A extends QV{file=null;entries=[];info(A,q){this.entries.push({level:"info",message:A,meta:q})}warn(A,q){this.entries.push({level:"warn",message:A,meta:q})}error(A,q){this.entries.push({level:"error",message:A,meta:q})}clear(){this.entries.length=0}}var Jzq={exitCode:0,stdout:"",stderr:""};class c4A extends ew{calls=[];killed=[];handler=()=>Jzq;syncHandler=()=>Jzq;aliveStub=null;listStub=null;on(A){return this.handler=A,this}onSync(A){return this.syncHandler=A,this}onIsAlive(A){return this.aliveStub=A,this}onListProcessesContaining(A){return this.listStub=A,this}async run(A,q={}){this.calls.push({kind:"run",command:A,options:q});let K=await this.handler(A);return{exitCode:K.exitCode??0,stdout:K.stdout??"",stderr:K.stderr??""}}runSync(A){this.calls.push({kind:"runSync",command:A});let q=this.syncHandler(A);return{exitCode:q.exitCode??0,stdout:q.stdout??"",stderr:q.stderr??""}}async attach(A,q={}){if(this.calls.push({kind:"attach",command:A,options:q}),q.onSpawned)q.onSpawned(1);return(await this.handler(A)).exitCode??0}detach(A,q={}){this.calls.push({kind:"detach",command:A,options:q})}kill(A,q="SIGTERM"){this.calls.push({kind:"kill",command:[String(A),q]}),this.killed.push({pid:A,signal:q})}isAlive(A){if(this.aliveStub)return this.aliveStub(A);let q=this.syncHandler(["ps","-p",String(A),"-o","state="]);if((q.exitCode??0)!==0)return!1;let K=(q.stdout??"").trim();if(!K)return!1;return!K.startsWith("Z")}listProcessesContaining(A){if(this.listStub)return this.listStub(A);return[]}}class m4A{store;constructor(A){this.store=A.store,Object.freeze(this)}list(){return this.store.read().profiles}get(A){return this.list().find((q)=>q.name===A)??null}getDefault(){return this.list()[0]??null}add(A){let q=this.store.read();if(q.profiles.some((K)=>K.name===A.name))throw Error(`profile "${A.name}" already exists`);if(!q.channels.some((K)=>K.id===A.channelId))throw Error(`channel id "${A.channelId}" not found`);q.profiles.push(A),this.store.write(q)}remove(A){let q=this.store.read(),K=q.profiles.findIndex((F)=>F.name===A);if(K<0)throw Error(`profile "${A}" not found`);q.profiles.splice(K,1),this.store.write(q)}rename(A,q){let K=this.store.read(),F=K.profiles.find((Z)=>Z.name===A);if(!F)throw Error(`profile "${A}" not found`);if(K.profiles.some((Z)=>Z.name===q))throw Error(`profile "${q}" already exists`);F.name=q,this.store.write(K)}asDefault(A){let q=this.store.read(),K=q.profiles.findIndex((Z)=>Z.name===A);if(K<0)throw Error(`profile "${A}" not found`);if(K===0)return;let[F]=q.profiles.splice(K,1);if(!F)return;q.profiles.unshift(F),this.store.write(q)}hasChannelRef(A){return this.store.read().profiles.some((q)=>q.channelId===A)}update(A,q){let K=this.store.read(),F=K.profiles.find((Z)=>Z.name===A);if(!F)throw Error(`profile "${A}" not found`);if(q.channelId!==void 0){if(!K.channels.some((Z)=>Z.id===q.channelId))throw Error(`channel id "${q.channelId}" not found`);F.channelId=q.channelId}if(q.path!==void 0)F.path=q.path;this.store.write(K)}}import{join as Hzq}from"path";var NUK=c.record(c.string(),c.string());class p4A{fs;idGenerator;dir;constructor(A){this.fs=A.fs,this.idGenerator=A.idGenerator,this.dir=A.dir,Object.freeze(this)}get(A,q){return this.readMap(A)[q]??null}create(A,q){let K=this.readMap(A),F=this.idGenerator.generate();return K[q]=F,this.writeMap(A,K),F}clear(A,q){let K=this.readMap(A);if(!(q in K))return;delete K[q],this.writeMap(A,K)}clearAll(A){let q=this.pathFor(A);if(this.fs.existsSync(q))this.fs.unlink(q)}readMap(A){let q=this.pathFor(A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q);try{let F=NUK.safeParse(JSON.parse(K));return F.success?F.data:{}}catch{return{}}}writeMap(A,q){let K=this.pathFor(A),F=this.channelDir(A);if(!this.fs.existsSync(F))this.fs.mkdirSync(F,{recursive:!0});this.fs.writeFileSync(K,`${JSON.stringify(q,null,2)}
|
package/dist/connectors/slack.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "../slack-connector-schema-
|
|
1
|
+
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "../slack-connector-schema-Bi2DyeZw.js";
|
|
2
2
|
export { FunnelSlackAdapter, FunnelSlackEventProcessor, FunnelSlackListener, slackConnectorSchema };
|
package/dist/gateway/daemon.js
CHANGED
|
@@ -543,7 +543,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
543
543
|
mv ${this.path} ${this.path}.bak`);if(x&&typeof x==="object"&&"version"in x&&x.version!==G2)throw Error(`unsupported settings.json version (${this.path}): expected ${G2}, got ${String(x.version)}`);let Y=bh.safeParse(x);if(!Y.success)throw Error(`invalid settings.json (${this.path}): ${Y.error.issues.map((Q)=>`${Q.path.join(".")}: ${Q.message}`).join(", ")}`);return Y.data}looksLikeLegacy($){if(!$||typeof $!=="object")return!1;let x=$;if(Array.isArray(x.channels))for(let Y of x.channels){if(!Y||typeof Y!=="object")continue;let Q=Y;if(Array.isArray(Q.connectors)&&Q.connectors.some((X)=>typeof X==="string"))return!0;if(!("id"in Q)&&"name"in Q)return!0}if(Array.isArray(x.connectors))return!0;if(Array.isArray(x.repositories))return!0;if(Array.isArray(x.profiles))for(let Y of x.profiles){if(!Y||typeof Y!=="object")continue;let Q=Y;if("repository"in Q||"envFiles"in Q||"channel"in Q&&!("channelId"in Q))return!0}return!1}write($){this.fs.mkdirSync($h1(this.path),{recursive:!0});let x={...$,version:G2};this.fs.writeFileSync(this.path,`${JSON.stringify(x,null,2)}
|
|
544
544
|
`)}}import{join as Fe0}from"path";class kY{}class QM{}class XM extends QM{constructor(){super();Object.freeze(this)}async fetch($){let x=await globalThis.fetch($.url,{method:$.method,headers:$.headers,body:$.body});return{status:x.status,ok:x.ok,text:()=>x.text(),json:()=>x.json()}}}var Qh1="https://discord.com/api/v10",Xh1=new XM;class zM extends kY{token;http;constructor($){super();this.token=$.config.botToken,this.http=$.http??Xh1,Object.freeze(this)}async call($){let x=($.method||"GET").toUpperCase(),Y=$.path.startsWith("/")?$.path:`/${$.path}`,Q=$.body,X=Q!==null&&typeof Q==="object"&&x!=="GET"&&Object.keys(Q).length>0,z=await this.http.fetch({method:x,url:`${Qh1}${Y}`,headers:{Authorization:`Bot ${this.token}`,"Content-Type":"application/json"},body:X?JSON.stringify($.body):void 0});if(!z.ok)throw Error(`Discord API failed (${z.status}): ${await z.text()}`);if(z.status===204)return null;return await z.json()}}var k2=YL(Dw1(),1);class f2{isAlive(){return!0}}class tR{ownUserId;constructor($){this.ownUserId=$.ownUserId}process($){if($.authorIsBot)return{skip:!0};let x=this.ownUserId?$.mentionedUserIds.includes(this.ownUserId):!1;return{skip:!1,content:JSON.stringify($.raw),meta:{event_type:"discord",channel_id:$.channelId,user_id:$.authorId,mentioned:String(x),guild_id:$.guildId??""}}}}import{appendFileSync as lJ0,mkdirSync as nJ0}from"fs";import{dirname as dJ0,join as aJ0}from"path";class jQ{}import{tmpdir as pJ0}from"os";import{join as iJ0}from"path";function dx(){let $=process.env.FUNNEL_TMP_DIR;if($&&$.length>0)return $;return iJ0(pJ0(),"funnel")}var sJ0=()=>aJ0(dx(),"funnel.log");class I6 extends jQ{file;now;constructor($={}){super();this.file=$.file??sJ0(),this.now=$.now??(()=>new Date),Object.freeze(this)}info($,x){this.write("info",$,x)}warn($,x){this.write("warn",$,x)}error($,x){this.write("error",$,x)}write($,x,Y){nJ0(dJ0(this.file),{recursive:!0});let Q={time:this.now().toISOString(),level:$,message:x,...Y?{meta:Y}:{}};lJ0(this.file,`${JSON.stringify(Q)}
|
|
545
545
|
`)}}var oJ0=new I6;class eR extends f2{config;logger;client=null;constructor($){super();this.config=$.config,this.logger=$.logger??oJ0}async start($){let x=new k2.Client({intents:[k2.GatewayIntentBits.Guilds,k2.GatewayIntentBits.GuildMessages,k2.GatewayIntentBits.MessageContent,k2.GatewayIntentBits.DirectMessages],partials:[k2.Partials.Channel]});x.on("messageCreate",async(Y)=>{let Q=x.user?.id??"",X=[...Y.mentions.users.keys()];this.logger.info("discord messageCreate",{author:Y.author.id,authorIsBot:String(Y.author.bot),channelId:Y.channelId,guildId:Y.guildId??"",mentions:X.join(","),ownUserId:Q,mentioned:String(X.includes(Q))});let Z=new tR({ownUserId:Q}).process({authorId:Y.author.id,authorIsBot:Y.author.bot,channelId:Y.channelId,guildId:Y.guildId,mentionedUserIds:X,raw:Y.toJSON()});if(Z.skip){this.logger.info("discord skip",{reason:"bot author"});return}try{await $(Z.content,Z.meta)}catch(K){this.logger.error("discord notify error",{error:K instanceof Error?K.message:String(K)})}}),x.on("ready",(Y)=>{this.logger.info("discord ready",{userId:Y.user.id,tag:Y.user.tag,guilds:String(Y.guilds.cache.size)})}),x.on("error",(Y)=>{this.logger.error("discord client error",{error:Y instanceof Error?Y.message:String(Y)})}),await x.login(this.config.botToken),this.client=x}async stop(){if(!this.client)return;try{await this.client.destroy()}catch($){this.logger.error("discord stop error",{error:$ instanceof Error?$.message:String($)})}finally{this.client=null}}isAlive(){return this.client!==null}}var rJ0=new M8;class $f extends kY{process;constructor($={}){super();this.process=$.process??rJ0,Object.freeze(this)}async call($){let x=["api",$.path];if($.method&&$.method.toLowerCase()!=="get")x.push("-X",$.method.toUpperCase());let Y=$.body&&typeof $.body==="object"&&Object.keys($.body).length>0;if(Y)x.push("--input","-");let Q=await this.process.run(["gh",...x],{input:Y?JSON.stringify($.body):void 0});if(Q.exitCode!==0)throw Error(`gh api failed: ${Q.stderr.trim()||Q.stdout.trim()}`);try{return JSON.parse(Q.stdout)}catch{return Q.stdout}}}var tJ0=y.object({id:y.string(),reason:y.string(),subject:y.object({type:y.string(),url:y.string(),title:y.string()}),repository:y.object({full_name:y.string()}),updated_at:y.string()}),eJ0=y.array(tJ0),$q0=new M8,xq0=new I6,Yq0=1e4,Qq0=5000;class xf extends f2{config;process;logger;now;seen=new Map;bootstrapped=!1;since;timer=null;constructor($){super();this.config=$.config,this.process=$.process??$q0,this.logger=$.logger??xq0,this.now=$.now??(()=>new Date),this.since=this.now().toISOString()}async start($){await this.pollOnce($);let x=this.config.pollInterval??60;this.timer=setInterval(()=>void this.pollOnce($),x*1000),this.timer.unref()}async stop(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}isAlive(){return this.timer!==null}async pollOnce($){let x=this.now().toISOString(),Y=new URLSearchParams({since:this.since,all:"false"});try{let Q=await this.process.run(["gh","api",`/notifications?${Y}`]);if(Q.exitCode!==0){this.logger.error("gh poll failed",{stderr:Q.stderr});return}let X=eJ0.safeParse(JSON.parse(Q.stdout));if(!X.success){this.logger.warn("gh response did not match schema",{error:X.error.message});return}let z=X.data;for(let Z of z){if(this.seen.get(Z.id)===Z.updated_at)continue;if(this.seen.set(Z.id,Z.updated_at),!this.bootstrapped)continue;let K={event_type:"gh",reason:Z.reason,subject_type:Z.subject.type,subject_url:Z.subject.url,repository:Z.repository.full_name,thread_id:Z.id,updated_at:Z.updated_at};await $(JSON.stringify(Z),K)}if(this.seen.size>Yq0){let Z=this.seen.size-Qq0,K=0;for(let W of this.seen.keys()){if(K>=Z)break;this.seen.delete(W),K++}}this.since=x,this.bootstrapped=!0}catch(Q){this.logger.error("gh poll error",{error:Q instanceof Error?Q.message:String(Q)})}}}var EW=($,x,Y)=>{let Q=new Set;for(let X of $.split(",")){let[z,Z]=X.split("/"),K=Z?Number(Z):1;if(!Number.isFinite(K)||K<=0)throw Error(`invalid cron step: "${Z}"`);let W=x,V=Y;if(z==="*"||z===void 0||z==="")W=x,V=Y;else if(z.includes("-")){let[w,U]=z.split("-"),H=Number(w),J=Number(U);if(!Number.isFinite(H)||!Number.isFinite(J))throw Error(`invalid cron range: "${z}"`);W=H,V=J}else{let w=Number(z);if(!Number.isFinite(w))throw Error(`invalid cron value: "${z}"`);W=w,V=Z?Y:w}if(W<x||V>Y||W>V)throw Error(`cron value out of range: ${z} (must be ${x}-${Y})`);for(let w=W;w<=V;w+=K)Q.add(w)}return{min:x,max:Y,values:Q}},xq=($,x)=>{let Y=$.trim().split(/\s+/);if(Y.length!==5)throw Error(`cron must have 5 fields (got ${Y.length}): "${$}"`);let[Q,X,z,Z,K]=Y;if(!Q||!X||!z||!Z||!K)throw Error(`cron has empty fields: "${$}"`);let W=[{field:EW(Q,0,59),value:x.getMinutes()},{field:EW(X,0,23),value:x.getHours()},{field:EW(z,1,31),value:x.getDate()},{field:EW(Z,1,12),value:x.getMonth()+1},{field:EW(K,0,6),value:x.getDay()}];for(let{field:V,value:w}of W)if(!V.values.has(w))return!1;return!0};var Xq0=new I6,Bw1=1440;class Yf extends f2{config;lastFiredStore;logger;now;onFired;timer=null;stopped=!1;constructor($){super();this.config=$.config,this.lastFiredStore=$.lastFiredStore,this.logger=$.logger??Xq0,this.now=$.now??(()=>new Date),this.onFired=$.onFired??null}async start($){this.stopped=!1;let x=()=>{if(this.stopped)return;let Y=this.now(),Q=60000-(Y.getSeconds()*1000+Y.getMilliseconds());this.timer=setTimeout(async()=>{if(this.stopped)return;await this.tick($),x()},Q),this.timer.unref()};await this.tick($),x()}async stop(){if(this.stopped=!0,this.timer)clearTimeout(this.timer),this.timer=null}isAlive(){return!this.stopped&&this.timer!==null}async tick($){let x=this.truncateToMinute(this.now()),Y=this.lastFiredStore.load(),Q=!1;for(let X of this.config.entries){if(!X.enabled)continue;if(await this.fireEntry(X,x,Y,$))Q=!0}if(Q)this.lastFiredStore.save(Y)}async fireEntry($,x,Y,Q){let X=Y.get($.id),z=X?new Date(X.getTime()+60000):x;if(z.getTime()>x.getTime())return!1;if($.catchupPolicy==="skip"){try{if(!xq($.cron,x))return!1}catch(K){return this.logInvalidCron($,K),!1}return await this.notifyOne($,x,Q,!1),Y.set($.id,x),!0}if($.catchupPolicy==="all"){let K=this.findAllMatches($.cron,z,x,$.id);if(K.length===0)return!1;for(let W of K)await this.notifyOne($,W,Q,W.getTime()!==x.getTime());return Y.set($.id,K[K.length-1]??x),!0}let Z=this.findMostRecentMatch($.cron,z,x,$.id);if(!Z)return!1;return await this.notifyOne($,Z,Q,Z.getTime()!==x.getTime()),Y.set($.id,Z),!0}async notifyOne($,x,Y,Q){let X={event_type:"schedule",schedule_id:$.id,cron:$.cron,fired_at:x.toISOString(),catchup_policy:$.catchupPolicy};if(Q)X.catchup="true";if(await Y($.prompt,X),this.onFired)try{await this.onFired($,x)}catch(z){this.logger.error("schedule onFired callback failed",{connector:this.config.name,id:$.id,error:z instanceof Error?z.message:String(z)})}}findMostRecentMatch($,x,Y,Q){let X=Math.min(Bw1,Math.floor((Y.getTime()-x.getTime())/60000)+1);for(let z=0;z<X;z++){let Z=new Date(Y.getTime()-z*60000);try{if(xq($,Z))return Z}catch(K){return this.logInvalidCron({id:Q,cron:$},K),null}}return null}findAllMatches($,x,Y,Q){let X=Math.min(Bw1,Math.floor((Y.getTime()-x.getTime())/60000)+1),z=[];for(let Z=0;Z<X;Z++){let K=new Date(x.getTime()+Z*60000);if(K.getTime()>Y.getTime())break;try{if(xq($,K))z.push(K)}catch(W){return this.logInvalidCron({id:Q,cron:$},W),[]}}return z}logInvalidCron($,x){this.logger.error("invalid cron expression in schedule",{connector:this.config.name,id:$.id,cron:$.cron,error:x instanceof Error?x.message:String(x)})}truncateToMinute($){let x=new Date($.getTime());return x.setSeconds(0,0),x}}import{dirname as zq0}from"path";var Zq0=new _8;class Qf{path;fs;constructor($){this.path=$.path,this.fs=$.fs??Zq0,Object.freeze(this)}load(){let $=new Map;if(!this.fs.existsSync(this.path))return $;let x=JSON.parse(this.fs.readFileSync(this.path));if(x===null||typeof x!=="object")return $;for(let[Y,Q]of Object.entries(x))if(typeof Q==="string")$.set(Y,new Date(Q));return $}save($){let x={};for(let[Y,Q]of $)x[Y]=Q.toISOString();this.fs.mkdirSync(zq0(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,`${JSON.stringify(x,null,2)}
|
|
546
|
-
`)}}var SD1=YL(TD1(),1);var iP0=($)=>{let x={};for(let[Y,Q]of Object.entries($))x[Y]=Q;return x},lP0=($)=>{if(!$||typeof $!=="object")return null;if(!("code"in $))return null;let x=$.code;if(typeof x!=="string"||!x.startsWith("slack_webapi_"))return null;if(!("data"in $))return null;let Y=$.data;if(!Y||typeof Y!=="object")return null;return Y};class Tk extends kY{client;constructor($){super();this.client=$.client??new SD1.WebClient($.config.botToken),Object.freeze(this)}async call($){let x=$.body!==null&&typeof $.body==="object"?iP0($.body):{};try{return await this.client.apiCall($.path,x)}catch(Y){let Q=lP0(Y);if(Q)return Q;throw Y}}}var KF=YL(Wc1(),1);var Hr0=new Set(["message","app_mention"]),Gr0=new Set([void 0,"thread_broadcast","bot_message","file_share"]);var J7=($,x)=>{let Y=$[x];return typeof Y==="string"?Y:void 0};class EC{ownBotUserId;ownBotId;now;dedup=new Map;constructor($){this.ownBotUserId=$.ownBotUserId,this.ownBotId=$.ownBotId,this.now=$.now??(()=>Date.now())}process($){let x=J7($,"type");if(!x||!Hr0.has(x))return{skip:!0};let Y=J7($,"subtype");if(!Gr0.has(Y))return{skip:!0};let Q=J7($,"channel")??"",X=J7($,"event_ts")??J7($,"ts")??"",z=`${Q}:${X}`,Z=this.now();if(this.dedup.has(z))return{skip:!0};this.dedup.set(z,Z);for(let H of this.dedup.keys())if((this.dedup.get(H)??0)<Z-1e4)this.dedup.delete(H);let K=J7($,"user"),W=J7($,"bot_id");if(K===this.ownBotUserId)return{skip:!0};if(W===this.ownBotId)return{skip:!0};let w=(J7($,"text")??"").includes(`<@${this.ownBotUserId}>`),U=J7($,"thread_ts")??J7($,"ts")??"";return{skip:!1,content:JSON.stringify($),meta:{event_type:"slack",channel_id:Q,user_id:K??"",mentioned:String(w),thread_ts:U},shouldReact:w,channel:Q,timestamp:J7($,"ts")??""}}}var Jr0=y.object({event:y.record(y.string(),y.unknown()).optional()}),qr0=new I6;class CC extends f2{config;logger;onAppCreated;preprocessEvent;app=null;constructor($){super();this.config=$.config,this.logger=$.logger??qr0,this.onAppCreated=$.onAppCreated??null,this.preprocessEvent=$.preprocessEvent??null}async start($){let x=new KF.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:KF.LogLevel.ERROR}),Y=await x.client.auth.test({token:this.config.botToken}),Q=new EC({ownBotUserId:Y.user_id??"",ownBotId:Y.bot_id??""}),X=this.preprocessEvent;if(x.use(async(z)=>{let Z=Jr0.safeParse(z);if(!Z.success||!Z.data.event)return;let K=Z.data.event,W=X?X(K):K;if(W===null)return;let V=Q.process(W);if(V.skip)return;if(V.shouldReact)try{await x.client.reactions.add({token:this.config.botToken,channel:V.channel,timestamp:V.timestamp,name:"eyes"})}catch{}await $(V.content,V.meta)}),x.error(async(z)=>{this.logger.error("Slack error",{error:z instanceof Error?z.message:String(z)})}),this.onAppCreated)await this.onAppCreated(x);await x.start(),this.app=x}async stop(){if(!this.app)return;try{await this.app.stop()}catch($){this.logger.error("Slack stop error",{error:$ instanceof Error?$.message:String($)})}finally{this.app=null}}isAlive(){return this.app!==null}}import{join as uC}from"path";var Dr0=new _8,Br0=new M8,Fr0=new I6;class yC{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor($={}){this.fs=$.fs??Dr0,this.process=$.process??Br0,this.logger=$.logger??Fr0,this.dir=$.dir??b8,this.slackListenerOptions=$.slackListenerOptions??{},this.scheduleListenerOptions=$.scheduleListenerOptions??{},Object.freeze(this)}createListener($,x){if(x.type==="slack")return new CC({config:x,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(x.type==="gh")return new xf({config:x,process:this.process,logger:this.logger});if(x.type==="discord")return new eR({config:x,logger:this.logger});let Y=new Qf({path:uC(this.connectorDir($,x.id),"state.json"),fs:this.fs});return new Yf({config:x,lastFiredStore:Y,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter($){if($.type==="slack")return new Tk({config:$});if($.type==="gh")return new $f({process:this.process});if($.type==="discord")return new zM({config:$});return null}connectorDir($,x){return uC(this.dir,"channels",$,"connectors",x)}channelDir($){return uC(this.dir,"channels",$)}}function mC($){switch($.type){case"slack":return[$.botToken,$.appToken];case"discord":return[$.botToken];case"gh":case"schedule":return[]}}function Lr0($,x){return $.type===x}function QX($,x,Y){let Q=$.connectors.find((X)=>X.name===x);if(!Q)throw Error(`connector "${x}" not found in channel "${$.name}"`);if(!Lr0(Q,Y))throw Error(`connector "${x}" is type "${Q.type}", not "${Y}"`);return Q}class CV{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class XX extends CV{now(){return new Date}}class uV{}class yV extends uV{generate(){return crypto.randomUUID()}}var Nr0=new XX,jr0=new yV;class hC{store;factory;profileChecker;clock;idGenerator;constructor($){this.store=$.store,this.factory=$.factory,this.profileChecker=$.profileChecker,this.clock=$.clock??Nr0,this.idGenerator=$.idGenerator??jr0,Object.freeze(this)}list(){return this.store.read().channels}get($){return this.list().find((x)=>x.name===$)??null}getById($){return this.list().find((x)=>x.id===$)??null}add($){let x=this.store.read();if(x.channels.some((Q)=>Q.name===$.name))throw Error(`channel "${$.name}" already exists`);let Y={id:this.idGenerator.generate(),name:$.name,delivery:$.delivery??"fanout",options:$.options??[],env:$.env??{},resume:$.resume??!0,connectors:[]};return x.channels.push(Y),this.store.write(x),Y}setDelivery($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.delivery=x,this.store.write(Y)}setResume($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.resume=x,this.store.write(Y)}setOptions($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.options=x,this.store.write(Y)}setEnv($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.env=x,this.store.write(Y)}remove($){let x=this.store.read(),Y=x.channels.findIndex((X)=>X.name===$);if(Y<0)throw Error(`channel "${$}" not found`);let Q=x.channels[Y];if(Q&&this.profileChecker.hasChannelRef(Q.id))throw Error(`channel "${$}" is referenced by a profile`);x.channels.splice(Y,1),this.store.write(x)}rename($,x){let Y=this.store.read(),Q=Y.channels.find((X)=>X.name===$);if(!Q)throw Error(`channel "${$}" not found`);if(Y.channels.some((X)=>X.name===x))throw Error(`channel "${x}" already exists`);Q.name=x,this.store.write(Y)}listConnectors($){return this.requireChannel(this.store.read(),$).connectors}getConnector($,x){let Y=this.get($);if(!Y)return null;return Y.connectors.find((Q)=>Q.name===x)??null}listAllConnectors(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({...Y,channelId:x.id,channelName:x.name});return $}addConnector($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);if(Q.connectors.some((z)=>z.name===x.name))throw Error(`connector "${x.name}" already exists in channel "${$}"`);let X=this.fromInput(x);return this.assertNoTokenCollision(Y,X),Q.connectors.push(X),this.store.write(Y),X}fromInput($){let x=this.idGenerator.generate(),Y=this.clock.iso(),Q=Y,X=Y;switch($.type){case"slack":return{id:x,type:"slack",name:$.name,botToken:$.botToken,appToken:$.appToken,createdAt:Q,updatedAt:X};case"gh":return{id:x,type:"gh",name:$.name,...$.pollInterval!==void 0?{pollInterval:$.pollInterval}:{},createdAt:Q,updatedAt:X};case"discord":return{id:x,type:"discord",name:$.name,botToken:$.botToken,createdAt:Q,updatedAt:X};case"schedule":return{id:x,type:"schedule",name:$.name,entries:$.entries??[],createdAt:Q,updatedAt:X}}}removeConnector($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$),X=Q.connectors.findIndex((z)=>z.name===x);if(X<0)throw Error(`connector "${x}" not found in channel "${$}"`);Q.connectors.splice(X,1),this.store.write(Y)}renameConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=X.connectors.find((Z)=>Z.name===x);if(!z)throw Error(`connector "${x}" not found in channel "${$}"`);if(X.connectors.some((Z)=>Z.name===Y))throw Error(`connector "${Y}" already exists in channel "${$}"`);z.name=Y,z.updatedAt=this.clock.iso(),this.store.write(Q)}updateSlackConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"slack"),Z={...z,botToken:Y.botToken??z.botToken,appToken:Y.appToken??z.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(Q,Z),Object.assign(z,Z),this.store.write(Q)}updateGhConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"gh");if(Y.pollInterval!==void 0)z.pollInterval=Y.pollInterval;z.updatedAt=this.clock.iso(),this.store.write(Q)}updateDiscordConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"discord"),Z={...z,botToken:Y.botToken??z.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(Q,Z),Object.assign(z,Z),this.store.write(Q)}listScheduleEntries($,x){let Y=this.requireChannel(this.store.read(),$);return QX(Y,x,"schedule").entries}addScheduleEntry($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"schedule"),Z={id:Y.id??this.idGenerator.generate(),cron:Y.cron,prompt:Y.prompt,enabled:Y.enabled??!0,catchupPolicy:Y.catchupPolicy??"latest"};return z.entries.push(Z),z.updatedAt=this.clock.iso(),this.store.write(Q),Z}removeScheduleEntry($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"schedule"),Z=z.entries.findIndex((K)=>K.id===Y);if(Z<0)throw Error(`schedule entry "${Y}" not found`);z.entries.splice(Z,1),z.updatedAt=this.clock.iso(),this.store.write(Q)}async call($,x,Y){let Q=this.getConnector($,x);if(!Q)throw Error(`connector "${x}" not found in channel "${$}"`);let X=this.factory.createAdapter(Q);if(!X)throw Error(`connector type "${Q.type}" does not support outbound calls`);return await X.call(Y)}createListener($,x){let Y=this.get($);if(!Y)return null;let Q=Y.connectors.find((X)=>X.name===x);if(!Q)return null;return{config:Q,channelId:Y.id,listener:this.factory.createListener(Y.id,Q)}}createAllListeners(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({config:Y,channelId:x.id,channelName:x.name,listener:this.factory.createListener(x.id,Y)});return $}requireChannel($,x){let Y=$.channels.find((Q)=>Q.name===x);if(!Y)throw Error(`channel "${x}" not found`);return Y}assertNoTokenCollision($,x){let Y=mC(x);if(Y.length===0)return;for(let Q of $.channels)for(let X of Q.connectors){if(X.id===x.id)continue;for(let z of mC(X))if(Y.includes(z))throw Error(`token already in use by connector "${X.name}" in channel "${Q.name}"`)}}}import{join as Vc1}from"path";var Pr0=new M8,Ir0=new _8,vr0=new I6;class gC{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor($){this.channels=$.channels,this.mcp=$.mcp,this.gateway=$.gateway,this.sessions=$.sessions,this.process=$.process??Pr0,this.fs=$.fs??Ir0,this.logger=$.logger??vr0,this.pidDir=Vc1($.dir??b8,"claude"),Object.freeze(this)}async launch($){let x=this.channels.get($.channel)??this.channels.getById($.channel);if(!x)throw Error(`channel "${$.channel}" not found`);if($.profileName&&this.isRunning($.profileName))throw Error(`profile "${$.profileName}" is already running`);let Y=$.cwd??globalThis.process.cwd();if(($.installMcp??!0)&&!this.mcp.findInstalledName(Y))this.mcp.install(Y),this.logger.info("added funnel MCP to .mcp.json",{cwd:Y});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if($.profileName)this.writePidFile($.profileName),this.installCleanup($.profileName);let X=x.resume?this.resolveSession(x.id,Y,$.userArgs??[]):null,z=this.buildArgs(x.options,$.userArgs??[],Y,X),Z=this.buildEnv(x.id,x.env);this.logger.info("claude launch",{channel:$.channel,channelId:x.id,cwd:Y});try{return await this.process.attach(["claude",...z],{cwd:Y,env:Z,onSpawned:$.onSpawned})}finally{if($.profileName)this.removePidFile($.profileName)}}isRunning($){let x=this.readPid($);if(!x)return!1;return this.isProcessAlive(x)}pidPath($){return Vc1(this.pidDir,`${$}.pid`)}readPid($){let x=this.pidPath($);if(!this.fs.existsSync(x))return null;try{let Y=this.fs.readFileSync(x).trim(),Q=Number(Y);if(!Q||Q<=0)return null;return Q}catch{return null}}writePidFile($){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath($),String(globalThis.process.pid))}removePidFile($){let x=this.pidPath($);if(this.fs.existsSync(x))this.fs.unlink(x)}installCleanup($){globalThis.process.once("exit",()=>this.removePidFile($))}isProcessAlive($){return this.process.isAlive($)}buildArgs($,x,Y,Q){let X=[...$,...x];if(Q!==null)if(Q.mode==="resume")X.push("--resume",Q.id);else X.push("--session-id",Q.id);let z=this.mcp.findInstalledName(Y);if(z&&!X.includes("--dangerously-load-development-channels")&&!X.includes("--channels"))X.push("--dangerously-load-development-channels",`server:${z}`);return X}resolveSession($,x,Y){for(let X of Y){if(X==="-c"||X==="--continue")return null;if(X==="--resume"||X.startsWith("--resume="))return null;if(X==="--session-id"||X.startsWith("--session-id="))return null}let Q=this.sessions.get($,x);if(Q!==null)return{id:Q,mode:"resume"};return{id:this.sessions.create($,x),mode:"new"}}buildEnv($,x){let Y={};for(let[Q,X]of Object.entries(x))Y[Q]=X;for(let[Q,X]of Object.entries(globalThis.process.env))if(typeof X==="string")Y[Q]=X;return Y.FUNNEL_CHANNEL_ID=$,Y}}var Mr0=384;class pC extends JK{dirs;files;mtimes;modes;now;constructor($={}){super();this.dirs=new Set($.dirs??[]),this.files=new Map(Object.entries($.files??{})),this.mtimes=new Map(Object.entries($.mtimes??{})),this.modes=new Map(Object.entries($.modes??{})),this.now=$.now??(()=>Date.now())}existsSync($){return this.dirs.has($)||this.files.has($)}readFileSync($){return this.files.get($)??""}writeFileSync($,x){this.files.set($,x),this.touch($)}writeSecretFileSync($,x){this.files.set($,x),this.modes.set($,Mr0),this.touch($)}appendFileSync($,x){let Y=this.files.get($)??"";this.files.set($,Y+x),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,x){this.dirs.add($)}readdirSync($){let x=$.endsWith("/")?$:`${$}/`,Y=[];for(let Q of this.files.keys()){if(!Q.startsWith(x))continue;let X=Q.slice(x.length);if(!X.includes("/"))Y.push(X)}return Y}statSync($){let x=this.mtimes.get($);if(x===void 0)throw Error(`not found: ${$}`);return{mtimeMs:x,mode:this.modes.get($)??null}}setMtime($,x){this.mtimes.set($,x)}setMode($,x){this.modes.set($,x)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class iC extends uV{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as Sr0}from"path";var _r0=y.object({botToken:y.string().optional(),appToken:y.string().optional()}).optional(),Or0=y.object({type:y.literal("slack"),name:y.string(),botToken:y.string().optional(),appToken:y.string().optional(),env:_r0}),br0=y.object({botToken:y.string().optional()}).optional(),Ar0=y.object({type:y.literal("discord"),name:y.string(),botToken:y.string().optional(),env:br0}),Rr0=y.object({type:y.literal("gh"),name:y.string(),pollInterval:y.number().int().positive().optional()}),fr0=y.object({type:y.literal("schedule"),name:y.string()}),kr0=y.discriminatedUnion("type",[Or0,Ar0,Rr0,fr0]),Tr0=y.object({name:y.string(),options:y.array(y.string()).optional(),env:y.record(y.string(),y.string()).optional(),resume:y.boolean().optional(),connectors:y.array(kr0).optional()}),wc1=y.object({$schema:y.string().optional(),channels:y.array(Tr0).min(1)}),WF="funnel.json",Uc1=".env.local";var cr0=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,Er0=($)=>{if($.length<2)return $;let x=$[0],Y=$[$.length-1];if(x==='"'&&Y==='"')return $.slice(1,-1);if(x==="'"&&Y==="'")return $.slice(1,-1);return $};class lC{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let x=Sr0($,Uc1);if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x),Q={};for(let X of Y.split(`
|
|
546
|
+
`)}}var SD1=YL(TD1(),1);var iP0=($)=>{let x={};for(let[Y,Q]of Object.entries($))x[Y]=Q;return x},lP0=($)=>{if(!$||typeof $!=="object")return null;if(!("code"in $))return null;let x=$.code;if(typeof x!=="string"||!x.startsWith("slack_webapi_"))return null;if(!("data"in $))return null;let Y=$.data;if(!Y||typeof Y!=="object")return null;return Y};class Tk extends kY{client;constructor($){super();this.client=$.client??new SD1.WebClient($.config.botToken),Object.freeze(this)}async call($){let x=$.body!==null&&typeof $.body==="object"?iP0($.body):{};try{return await this.client.apiCall($.path,x)}catch(Y){let Q=lP0(Y);if(Q)return Q;throw Y}}}var KF=YL(Wc1(),1);var Hr0=new Set(["message","app_mention"]),Gr0=new Set([void 0,"thread_broadcast","bot_message","file_share"]);var J7=($,x)=>{let Y=$[x];return typeof Y==="string"?Y:void 0};class EC{ownBotUserId;ownBotId;now;dedup=new Map;constructor($){this.ownBotUserId=$.ownBotUserId,this.ownBotId=$.ownBotId,this.now=$.now??(()=>Date.now())}process($){let x=J7($,"type");if(!x||!Hr0.has(x))return{skip:!0};let Y=J7($,"subtype");if(!Gr0.has(Y))return{skip:!0};let Q=J7($,"channel")??"",X=J7($,"event_ts")??J7($,"ts")??"",z=`${Q}:${X}`,Z=this.now();if(this.dedup.has(z))return{skip:!0};this.dedup.set(z,Z);for(let H of this.dedup.keys())if((this.dedup.get(H)??0)<Z-1e4)this.dedup.delete(H);let K=J7($,"user"),W=J7($,"bot_id");if(K===this.ownBotUserId)return{skip:!0};if(W===this.ownBotId)return{skip:!0};let w=(J7($,"text")??"").includes(`<@${this.ownBotUserId}>`),U=J7($,"thread_ts")??J7($,"ts")??"";return{skip:!1,content:JSON.stringify($),meta:{event_type:"slack",channel_id:Q,user_id:K??"",mentioned:String(w),thread_ts:U},shouldReact:w,channel:Q,timestamp:J7($,"ts")??""}}}var Jr0=y.object({event:y.record(y.string(),y.unknown()).optional()}),qr0=new I6;class CC extends f2{config;logger;onAppCreated;preprocessEvent;app=null;constructor($){super();this.config=$.config,this.logger=$.logger??qr0,this.onAppCreated=$.onAppCreated??null,this.preprocessEvent=$.preprocessEvent??null}async start($){let x=new KF.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:KF.LogLevel.ERROR}),Y=await x.client.auth.test({token:this.config.botToken}),Q=new EC({ownBotUserId:Y.user_id??"",ownBotId:Y.bot_id??""}),X=this.preprocessEvent;if(x.use(async(z)=>{let Z=Jr0.safeParse(z);if(!Z.success||!Z.data.event)return;let K=Z.data.event,W=X?X(K):K;if(W===null)return;let V=Q.process(W);if(V.skip)return;if(await $(V.content,V.meta),V.shouldReact)try{await x.client.reactions.add({token:this.config.botToken,channel:V.channel,timestamp:V.timestamp,name:"eyes"})}catch{}}),x.error(async(z)=>{this.logger.error("Slack error",{error:z instanceof Error?z.message:String(z)})}),this.onAppCreated)await this.onAppCreated(x);await x.start(),this.app=x}async stop(){if(!this.app)return;try{await this.app.stop()}catch($){this.logger.error("Slack stop error",{error:$ instanceof Error?$.message:String($)})}finally{this.app=null}}isAlive(){return this.app!==null}}import{join as uC}from"path";var Dr0=new _8,Br0=new M8,Fr0=new I6;class yC{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor($={}){this.fs=$.fs??Dr0,this.process=$.process??Br0,this.logger=$.logger??Fr0,this.dir=$.dir??b8,this.slackListenerOptions=$.slackListenerOptions??{},this.scheduleListenerOptions=$.scheduleListenerOptions??{},Object.freeze(this)}createListener($,x){if(x.type==="slack")return new CC({config:x,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(x.type==="gh")return new xf({config:x,process:this.process,logger:this.logger});if(x.type==="discord")return new eR({config:x,logger:this.logger});let Y=new Qf({path:uC(this.connectorDir($,x.id),"state.json"),fs:this.fs});return new Yf({config:x,lastFiredStore:Y,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter($){if($.type==="slack")return new Tk({config:$});if($.type==="gh")return new $f({process:this.process});if($.type==="discord")return new zM({config:$});return null}connectorDir($,x){return uC(this.dir,"channels",$,"connectors",x)}channelDir($){return uC(this.dir,"channels",$)}}function mC($){switch($.type){case"slack":return[$.botToken,$.appToken];case"discord":return[$.botToken];case"gh":case"schedule":return[]}}function Lr0($,x){return $.type===x}function QX($,x,Y){let Q=$.connectors.find((X)=>X.name===x);if(!Q)throw Error(`connector "${x}" not found in channel "${$.name}"`);if(!Lr0(Q,Y))throw Error(`connector "${x}" is type "${Q.type}", not "${Y}"`);return Q}class CV{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class XX extends CV{now(){return new Date}}class uV{}class yV extends uV{generate(){return crypto.randomUUID()}}var Nr0=new XX,jr0=new yV;class hC{store;factory;profileChecker;clock;idGenerator;constructor($){this.store=$.store,this.factory=$.factory,this.profileChecker=$.profileChecker,this.clock=$.clock??Nr0,this.idGenerator=$.idGenerator??jr0,Object.freeze(this)}list(){return this.store.read().channels}get($){return this.list().find((x)=>x.name===$)??null}getById($){return this.list().find((x)=>x.id===$)??null}add($){let x=this.store.read();if(x.channels.some((Q)=>Q.name===$.name))throw Error(`channel "${$.name}" already exists`);let Y={id:this.idGenerator.generate(),name:$.name,delivery:$.delivery??"fanout",options:$.options??[],env:$.env??{},resume:$.resume??!0,connectors:[]};return x.channels.push(Y),this.store.write(x),Y}setDelivery($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.delivery=x,this.store.write(Y)}setResume($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.resume=x,this.store.write(Y)}setOptions($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.options=x,this.store.write(Y)}setEnv($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);Q.env=x,this.store.write(Y)}remove($){let x=this.store.read(),Y=x.channels.findIndex((X)=>X.name===$);if(Y<0)throw Error(`channel "${$}" not found`);let Q=x.channels[Y];if(Q&&this.profileChecker.hasChannelRef(Q.id))throw Error(`channel "${$}" is referenced by a profile`);x.channels.splice(Y,1),this.store.write(x)}rename($,x){let Y=this.store.read(),Q=Y.channels.find((X)=>X.name===$);if(!Q)throw Error(`channel "${$}" not found`);if(Y.channels.some((X)=>X.name===x))throw Error(`channel "${x}" already exists`);Q.name=x,this.store.write(Y)}listConnectors($){return this.requireChannel(this.store.read(),$).connectors}getConnector($,x){let Y=this.get($);if(!Y)return null;return Y.connectors.find((Q)=>Q.name===x)??null}listAllConnectors(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({...Y,channelId:x.id,channelName:x.name});return $}addConnector($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$);if(Q.connectors.some((z)=>z.name===x.name))throw Error(`connector "${x.name}" already exists in channel "${$}"`);let X=this.fromInput(x);return this.assertNoTokenCollision(Y,X),Q.connectors.push(X),this.store.write(Y),X}fromInput($){let x=this.idGenerator.generate(),Y=this.clock.iso(),Q=Y,X=Y;switch($.type){case"slack":return{id:x,type:"slack",name:$.name,botToken:$.botToken,appToken:$.appToken,createdAt:Q,updatedAt:X};case"gh":return{id:x,type:"gh",name:$.name,...$.pollInterval!==void 0?{pollInterval:$.pollInterval}:{},createdAt:Q,updatedAt:X};case"discord":return{id:x,type:"discord",name:$.name,botToken:$.botToken,createdAt:Q,updatedAt:X};case"schedule":return{id:x,type:"schedule",name:$.name,entries:$.entries??[],createdAt:Q,updatedAt:X}}}removeConnector($,x){let Y=this.store.read(),Q=this.requireChannel(Y,$),X=Q.connectors.findIndex((z)=>z.name===x);if(X<0)throw Error(`connector "${x}" not found in channel "${$}"`);Q.connectors.splice(X,1),this.store.write(Y)}renameConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=X.connectors.find((Z)=>Z.name===x);if(!z)throw Error(`connector "${x}" not found in channel "${$}"`);if(X.connectors.some((Z)=>Z.name===Y))throw Error(`connector "${Y}" already exists in channel "${$}"`);z.name=Y,z.updatedAt=this.clock.iso(),this.store.write(Q)}updateSlackConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"slack"),Z={...z,botToken:Y.botToken??z.botToken,appToken:Y.appToken??z.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(Q,Z),Object.assign(z,Z),this.store.write(Q)}updateGhConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"gh");if(Y.pollInterval!==void 0)z.pollInterval=Y.pollInterval;z.updatedAt=this.clock.iso(),this.store.write(Q)}updateDiscordConnector($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"discord"),Z={...z,botToken:Y.botToken??z.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(Q,Z),Object.assign(z,Z),this.store.write(Q)}listScheduleEntries($,x){let Y=this.requireChannel(this.store.read(),$);return QX(Y,x,"schedule").entries}addScheduleEntry($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"schedule"),Z={id:Y.id??this.idGenerator.generate(),cron:Y.cron,prompt:Y.prompt,enabled:Y.enabled??!0,catchupPolicy:Y.catchupPolicy??"latest"};return z.entries.push(Z),z.updatedAt=this.clock.iso(),this.store.write(Q),Z}removeScheduleEntry($,x,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=QX(X,x,"schedule"),Z=z.entries.findIndex((K)=>K.id===Y);if(Z<0)throw Error(`schedule entry "${Y}" not found`);z.entries.splice(Z,1),z.updatedAt=this.clock.iso(),this.store.write(Q)}async call($,x,Y){let Q=this.getConnector($,x);if(!Q)throw Error(`connector "${x}" not found in channel "${$}"`);let X=this.factory.createAdapter(Q);if(!X)throw Error(`connector type "${Q.type}" does not support outbound calls`);return await X.call(Y)}createListener($,x){let Y=this.get($);if(!Y)return null;let Q=Y.connectors.find((X)=>X.name===x);if(!Q)return null;return{config:Q,channelId:Y.id,listener:this.factory.createListener(Y.id,Q)}}createAllListeners(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({config:Y,channelId:x.id,channelName:x.name,listener:this.factory.createListener(x.id,Y)});return $}requireChannel($,x){let Y=$.channels.find((Q)=>Q.name===x);if(!Y)throw Error(`channel "${x}" not found`);return Y}assertNoTokenCollision($,x){let Y=mC(x);if(Y.length===0)return;for(let Q of $.channels)for(let X of Q.connectors){if(X.id===x.id)continue;for(let z of mC(X))if(Y.includes(z))throw Error(`token already in use by connector "${X.name}" in channel "${Q.name}"`)}}}import{join as Vc1}from"path";var Pr0=new M8,Ir0=new _8,vr0=new I6;class gC{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor($){this.channels=$.channels,this.mcp=$.mcp,this.gateway=$.gateway,this.sessions=$.sessions,this.process=$.process??Pr0,this.fs=$.fs??Ir0,this.logger=$.logger??vr0,this.pidDir=Vc1($.dir??b8,"claude"),Object.freeze(this)}async launch($){let x=this.channels.get($.channel)??this.channels.getById($.channel);if(!x)throw Error(`channel "${$.channel}" not found`);if($.profileName&&this.isRunning($.profileName))throw Error(`profile "${$.profileName}" is already running`);let Y=$.cwd??globalThis.process.cwd();if(($.installMcp??!0)&&!this.mcp.findInstalledName(Y))this.mcp.install(Y),this.logger.info("added funnel MCP to .mcp.json",{cwd:Y});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if($.profileName)this.writePidFile($.profileName),this.installCleanup($.profileName);let X=x.resume?this.resolveSession(x.id,Y,$.userArgs??[]):null,z=this.buildArgs(x.options,$.userArgs??[],Y,X),Z=this.buildEnv(x.id,x.env);this.logger.info("claude launch",{channel:$.channel,channelId:x.id,cwd:Y});try{return await this.process.attach(["claude",...z],{cwd:Y,env:Z,onSpawned:$.onSpawned})}finally{if($.profileName)this.removePidFile($.profileName)}}isRunning($){let x=this.readPid($);if(!x)return!1;return this.isProcessAlive(x)}pidPath($){return Vc1(this.pidDir,`${$}.pid`)}readPid($){let x=this.pidPath($);if(!this.fs.existsSync(x))return null;try{let Y=this.fs.readFileSync(x).trim(),Q=Number(Y);if(!Q||Q<=0)return null;return Q}catch{return null}}writePidFile($){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath($),String(globalThis.process.pid))}removePidFile($){let x=this.pidPath($);if(this.fs.existsSync(x))this.fs.unlink(x)}installCleanup($){globalThis.process.once("exit",()=>this.removePidFile($))}isProcessAlive($){return this.process.isAlive($)}buildArgs($,x,Y,Q){let X=[...$,...x];if(Q!==null)if(Q.mode==="resume")X.push("--resume",Q.id);else X.push("--session-id",Q.id);let z=this.mcp.findInstalledName(Y);if(z&&!X.includes("--dangerously-load-development-channels")&&!X.includes("--channels"))X.push("--dangerously-load-development-channels",`server:${z}`);return X}resolveSession($,x,Y){for(let X of Y){if(X==="-c"||X==="--continue")return null;if(X==="--resume"||X.startsWith("--resume="))return null;if(X==="--session-id"||X.startsWith("--session-id="))return null}let Q=this.sessions.get($,x);if(Q!==null)return{id:Q,mode:"resume"};return{id:this.sessions.create($,x),mode:"new"}}buildEnv($,x){let Y={};for(let[Q,X]of Object.entries(x))Y[Q]=X;for(let[Q,X]of Object.entries(globalThis.process.env))if(typeof X==="string")Y[Q]=X;return Y.FUNNEL_CHANNEL_ID=$,Y}}var Mr0=384;class pC extends JK{dirs;files;mtimes;modes;now;constructor($={}){super();this.dirs=new Set($.dirs??[]),this.files=new Map(Object.entries($.files??{})),this.mtimes=new Map(Object.entries($.mtimes??{})),this.modes=new Map(Object.entries($.modes??{})),this.now=$.now??(()=>Date.now())}existsSync($){return this.dirs.has($)||this.files.has($)}readFileSync($){return this.files.get($)??""}writeFileSync($,x){this.files.set($,x),this.touch($)}writeSecretFileSync($,x){this.files.set($,x),this.modes.set($,Mr0),this.touch($)}appendFileSync($,x){let Y=this.files.get($)??"";this.files.set($,Y+x),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,x){this.dirs.add($)}readdirSync($){let x=$.endsWith("/")?$:`${$}/`,Y=[];for(let Q of this.files.keys()){if(!Q.startsWith(x))continue;let X=Q.slice(x.length);if(!X.includes("/"))Y.push(X)}return Y}statSync($){let x=this.mtimes.get($);if(x===void 0)throw Error(`not found: ${$}`);return{mtimeMs:x,mode:this.modes.get($)??null}}setMtime($,x){this.mtimes.set($,x)}setMode($,x){this.modes.set($,x)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class iC extends uV{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as Sr0}from"path";var _r0=y.object({botToken:y.string().optional(),appToken:y.string().optional()}).optional(),Or0=y.object({type:y.literal("slack"),name:y.string(),botToken:y.string().optional(),appToken:y.string().optional(),env:_r0}),br0=y.object({botToken:y.string().optional()}).optional(),Ar0=y.object({type:y.literal("discord"),name:y.string(),botToken:y.string().optional(),env:br0}),Rr0=y.object({type:y.literal("gh"),name:y.string(),pollInterval:y.number().int().positive().optional()}),fr0=y.object({type:y.literal("schedule"),name:y.string()}),kr0=y.discriminatedUnion("type",[Or0,Ar0,Rr0,fr0]),Tr0=y.object({name:y.string(),options:y.array(y.string()).optional(),env:y.record(y.string(),y.string()).optional(),resume:y.boolean().optional(),connectors:y.array(kr0).optional()}),wc1=y.object({$schema:y.string().optional(),channels:y.array(Tr0).min(1)}),WF="funnel.json",Uc1=".env.local";var cr0=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,Er0=($)=>{if($.length<2)return $;let x=$[0],Y=$[$.length-1];if(x==='"'&&Y==='"')return $.slice(1,-1);if(x==="'"&&Y==="'")return $.slice(1,-1);return $};class lC{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let x=Sr0($,Uc1);if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x),Q={};for(let X of Y.split(`
|
|
547
547
|
`)){let z=X.trim();if(z===""||z.startsWith("#"))continue;let Z=z.match(cr0);if(!Z)continue;let K=Z[1],W=Z[2];if(!K)continue;Q[K]=Er0(W??"")}return Q}}import{join as Cr0}from"path";class nC{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let x=Cr0($,WF);if(!this.fs.existsSync(x))return null;let Y=this.fs.readFileSync(x),Q=(()=>{try{return JSON.parse(Y)}catch(z){let Z=z instanceof Error?z.message:String(z);throw Error(`${WF} is not valid JSON: ${Z}`)}})(),X=wc1.safeParse(Q);if(!X.success)throw Error(`${WF} is invalid: ${X.error.message}`);return X.data}}var ur0=($,x)=>{if($.length!==x.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==x[Y])return!1;return!0},yr0=($,x)=>{let Y=Object.keys($);if(Y.length!==Object.keys(x).length)return!1;for(let Q of Y)if($[Q]!==x[Q])return!1;return!0};class dC{channels;dotenv;prompter;env;constructor($){this.channels=$.channels,this.dotenv=$.dotenv,this.prompter=$.prompter,this.env=$.env??process.env,Object.freeze(this)}async ensure($,x){let Y=this.channels.get($.name),Q=$.resume??!0;if(!Y)this.channels.add({name:$.name,options:$.options??[],env:$.env??{},resume:Q});else{let W=$.options??[],V=$.env??{};if(!ur0(Y.options,W))this.channels.setOptions($.name,W);if(!yr0(Y.env,V))this.channels.setEnv($.name,V);if(Y.resume!==Q)this.channels.setResume($.name,Q)}if($.connectors===void 0)return{touched:[],removed:[]};let X=this.dotenv.read(x),z=[],Z=new Set;for(let W of $.connectors){let V=await this.ensureConnector($.name,W,X);z.push({name:V.name,changed:V.changed}),Z.add(V.id)}let K=this.removeExtras($.name,Z);return{touched:z,removed:K}}async ensureConnector($,x,Y){if(x.type==="slack")return await this.ensureSlack($,x,Y);if(x.type==="discord")return await this.ensureDiscord($,x,Y);if(x.type==="gh")return this.ensureGh($,x);return this.ensureSchedule($,x)}async ensureSlack($,x,Y){let Q=this.findExistingSlack($,x.name),X=await this.resolveField({literal:x.botToken,envVar:x.env?.botToken,dotenv:Y,label:`${x.name}.botToken`,existing:Q?.botToken}),z=await this.resolveField({literal:x.appToken,envVar:x.env?.appToken,dotenv:Y,label:`${x.name}.appToken`,existing:Q?.appToken});if(Q){if(Q.botToken!==X||Q.appToken!==z)return this.channels.updateSlackConnector($,x.name,{botToken:X,appToken:z}),{id:Q.id,name:x.name,changed:!0};return{id:Q.id,name:x.name,changed:!1}}let Z=this.findSlackByToken($,[X,z]);if(Z){if(this.channels.renameConnector($,Z.name,x.name),Z.botToken!==X||Z.appToken!==z)this.channels.updateSlackConnector($,x.name,{botToken:X,appToken:z});return{id:Z.id,name:x.name,changed:!0}}return{id:this.channels.addConnector($,{type:"slack",name:x.name,botToken:X,appToken:z}).id,name:x.name,changed:!0}}async ensureDiscord($,x,Y){let Q=this.findExistingDiscord($,x.name),X=await this.resolveField({literal:x.botToken,envVar:x.env?.botToken,dotenv:Y,label:`${x.name}.botToken`,existing:Q?.botToken});if(Q){if(Q.botToken!==X)return this.channels.updateDiscordConnector($,x.name,{botToken:X}),{id:Q.id,name:x.name,changed:!0};return{id:Q.id,name:x.name,changed:!1}}let z=this.findDiscordByToken($,X);if(z){if(this.channels.renameConnector($,z.name,x.name),z.botToken!==X)this.channels.updateDiscordConnector($,x.name,{botToken:X});return{id:z.id,name:x.name,changed:!0}}return{id:this.channels.addConnector($,{type:"discord",name:x.name,botToken:X}).id,name:x.name,changed:!0}}ensureGh($,x){let Y=this.channels.getConnector($,x.name);if(Y&&Y.type!=="gh")throw Error(`connector "${x.name}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "gh"`);if(Y&&Y.type==="gh"){if(x.pollInterval!==void 0&&Y.pollInterval!==x.pollInterval)return this.channels.updateGhConnector($,x.name,{pollInterval:x.pollInterval}),{id:Y.id,name:x.name,changed:!0};return{id:Y.id,name:x.name,changed:!1}}return{id:this.channels.addConnector($,{type:"gh",name:x.name,...x.pollInterval!==void 0?{pollInterval:x.pollInterval}:{}}).id,name:x.name,changed:!0}}ensureSchedule($,x){let Y=this.channels.getConnector($,x.name);if(Y&&Y.type!=="schedule")throw Error(`connector "${x.name}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "schedule"`);if(Y&&Y.type==="schedule")return{id:Y.id,name:x.name,changed:!1};return{id:this.channels.addConnector($,{type:"schedule",name:x.name}).id,name:x.name,changed:!0}}findExistingSlack($,x){let Y=this.channels.getConnector($,x);if(!Y)return null;if(Y.type!=="slack")throw Error(`connector "${x}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "slack"`);return Y}findExistingDiscord($,x){let Y=this.channels.getConnector($,x);if(!Y)return null;if(Y.type!=="discord")throw Error(`connector "${x}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "discord"`);return Y}findSlackByToken($,x){let Y=this.channels.get($);if(!Y)return null;for(let Q of Y.connectors){if(Q.type!=="slack")continue;if(x.includes(Q.botToken)||x.includes(Q.appToken))return Q}return null}findDiscordByToken($,x){let Y=this.channels.get($);if(!Y)return null;for(let Q of Y.connectors){if(Q.type!=="discord")continue;if(Q.botToken===x)return Q}return null}removeExtras($,x){let Y=this.channels.get($);if(!Y)return[];let Q=Y.connectors.filter((X)=>!x.has(X.id));for(let X of Q)this.channels.removeConnector($,X.name);return Q.map((X)=>X.name)}async resolveField($){if($.literal!==void 0&&$.envVar!==void 0)throw Error(`${$.label} is set both as a literal and as env.${$.label.split(".").pop()}; pick one`);if($.literal!==void 0&&$.literal!=="")return $.literal;if($.envVar!==void 0&&$.envVar!==""){let x=this.env[$.envVar];if(x)return x;let Y=$.dotenv[$.envVar];if(Y)return Y;throw Error(`${$.label} references env var "${$.envVar}" but it is not set in process env or .env.local`)}if($.existing)return $.existing;return await this.prompter.promptSecret($.label)}}class aC extends jQ{file=null;entries=[];info($,x){this.entries.push({level:"info",message:$,meta:x})}warn($,x){this.entries.push({level:"warn",message:$,meta:x})}error($,x){this.entries.push({level:"error",message:$,meta:x})}clear(){this.entries.length=0}}import{join as Hc1}from"path";var Gc1="funnel",mr0="funnel",hr0=y.object({command:y.string().optional(),args:y.array(y.string()).optional()}),gr0=y.object({mcpServers:y.record(y.string(),hr0).optional()}),pr0=new _8;class sC{fs;constructor($={}){this.fs=$.fs??pr0,Object.freeze(this)}install($){if(!this.fs.existsSync($))throw Error(`repository does not exist: ${$}`);let x=this.readConfig($),Y=x.mcpServers??{},X=this.findServerName(Y)??mr0;Y[X]={command:Gc1,args:["mcp"]},this.writeConfig($,{...x,mcpServers:Y})}uninstall($){if(!this.fs.existsSync($))return;let x=this.readConfig($),Y=x.mcpServers??{},Q=this.findServerName(Y);if(!Q)return;let X={...Y};delete X[Q],this.writeConfig($,{...x,mcpServers:X})}findInstalledName($){let x=this.readConfig($);return this.findServerName(x.mcpServers??{})}findServerName($){for(let x of Object.entries($)){let Y=x[0];if(x[1]?.command===Gc1)return Y}return null}readConfig($){let x=Hc1($,".mcp.json");if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x).trim();if(!Y)return{};let Q;try{Q=JSON.parse(Y)}catch(z){throw Error(`invalid .mcp.json (${x}): ${z instanceof Error?z.message:String(z)}`)}let X=gr0.safeParse(Q);if(!X.success)throw Error(`invalid .mcp.json (${x}): ${X.error.message}`);return X.data}writeConfig($,x){let Y=Hc1($,".mcp.json");this.fs.writeFileSync(Y,`${JSON.stringify(x,null,2)}
|
|
548
548
|
`)}}var Jc1={exitCode:0,stdout:"",stderr:""};class oC extends GK{calls=[];killed=[];handler=()=>Jc1;syncHandler=()=>Jc1;aliveStub=null;listStub=null;on($){return this.handler=$,this}onSync($){return this.syncHandler=$,this}onIsAlive($){return this.aliveStub=$,this}onListProcessesContaining($){return this.listStub=$,this}async run($,x={}){this.calls.push({kind:"run",command:$,options:x});let Y=await this.handler($);return{exitCode:Y.exitCode??0,stdout:Y.stdout??"",stderr:Y.stderr??""}}runSync($){this.calls.push({kind:"runSync",command:$});let x=this.syncHandler($);return{exitCode:x.exitCode??0,stdout:x.stdout??"",stderr:x.stderr??""}}async attach($,x={}){if(this.calls.push({kind:"attach",command:$,options:x}),x.onSpawned)x.onSpawned(1);return(await this.handler($)).exitCode??0}detach($,x={}){this.calls.push({kind:"detach",command:$,options:x})}kill($,x="SIGTERM"){this.calls.push({kind:"kill",command:[String($),x]}),this.killed.push({pid:$,signal:x})}isAlive($){if(this.aliveStub)return this.aliveStub($);let x=this.syncHandler(["ps","-p",String($),"-o","state="]);if((x.exitCode??0)!==0)return!1;let Y=(x.stdout??"").trim();if(!Y)return!1;return!Y.startsWith("Z")}listProcessesContaining($){if(this.listStub)return this.listStub($);return[]}}class rC{store;constructor($){this.store=$.store,Object.freeze(this)}list(){return this.store.read().profiles}get($){return this.list().find((x)=>x.name===$)??null}getDefault(){return this.list()[0]??null}add($){let x=this.store.read();if(x.profiles.some((Y)=>Y.name===$.name))throw Error(`profile "${$.name}" already exists`);if(!x.channels.some((Y)=>Y.id===$.channelId))throw Error(`channel id "${$.channelId}" not found`);x.profiles.push($),this.store.write(x)}remove($){let x=this.store.read(),Y=x.profiles.findIndex((Q)=>Q.name===$);if(Y<0)throw Error(`profile "${$}" not found`);x.profiles.splice(Y,1),this.store.write(x)}rename($,x){let Y=this.store.read(),Q=Y.profiles.find((X)=>X.name===$);if(!Q)throw Error(`profile "${$}" not found`);if(Y.profiles.some((X)=>X.name===x))throw Error(`profile "${x}" already exists`);Q.name=x,this.store.write(Y)}asDefault($){let x=this.store.read(),Y=x.profiles.findIndex((X)=>X.name===$);if(Y<0)throw Error(`profile "${$}" not found`);if(Y===0)return;let[Q]=x.profiles.splice(Y,1);if(!Q)return;x.profiles.unshift(Q),this.store.write(x)}hasChannelRef($){return this.store.read().profiles.some((x)=>x.channelId===$)}update($,x){let Y=this.store.read(),Q=Y.profiles.find((X)=>X.name===$);if(!Q)throw Error(`profile "${$}" not found`);if(x.channelId!==void 0){if(!Y.channels.some((X)=>X.id===x.channelId))throw Error(`channel id "${x.channelId}" not found`);Q.channelId=x.channelId}if(x.path!==void 0)Q.path=x.path;this.store.write(Y)}}import{join as qc1}from"path";var ir0=y.record(y.string(),y.string());class tC{fs;idGenerator;dir;constructor($){this.fs=$.fs,this.idGenerator=$.idGenerator,this.dir=$.dir,Object.freeze(this)}get($,x){return this.readMap($)[x]??null}create($,x){let Y=this.readMap($),Q=this.idGenerator.generate();return Y[x]=Q,this.writeMap($,Y),Q}clear($,x){let Y=this.readMap($);if(!(x in Y))return;delete Y[x],this.writeMap($,Y)}clearAll($){let x=this.pathFor($);if(this.fs.existsSync(x))this.fs.unlink(x)}readMap($){let x=this.pathFor($);if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x);try{let Q=ir0.safeParse(JSON.parse(Y));return Q.success?Q.data:{}}catch{return{}}}writeMap($,x){let Y=this.pathFor($),Q=this.channelDir($);if(!this.fs.existsSync(Q))this.fs.mkdirSync(Q,{recursive:!0});this.fs.writeFileSync(Y,`${JSON.stringify(x,null,2)}
|
|
549
549
|
`)}channelDir($){return qc1(this.dir,"channels",$)}pathFor($){return qc1(this.channelDir($),"sessions.json")}}import{stderr as VF,stdin as e7}from"process";class eC{}var lr0="*",nr0="\r",Dc1=`
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { i as FunnelDiscordAdapter, n as FunnelDiscordListener, t as discordConn
|
|
|
2
2
|
import { i as FunnelConnectorListener, n as funnelTmpDir, r as FunnelLogger, t as NodeFunnelLogger } from "./node-logger-B97ZiGwj.js";
|
|
3
3
|
import { a as FunnelProcessRunner, i as NodeFunnelProcessRunner, n as FunnelGhListener, r as FunnelGhAdapter, t as ghConnectorSchema } from "./gh-connector-schema-CAC24s0r.js";
|
|
4
4
|
import { a as ScheduleStateStore, i as FunnelScheduleListener, n as scheduleConnectorSchema, o as NodeFunnelFileSystem, r as scheduleEntrySchema, s as FunnelFileSystem, t as scheduleCatchupPolicySchema } from "./schedule-connector-schema-BZpH6ZmR.js";
|
|
5
|
-
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "./slack-connector-schema-
|
|
5
|
+
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "./slack-connector-schema-Bi2DyeZw.js";
|
|
6
6
|
import { dirname, join, resolve } from "node:path";
|
|
7
7
|
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
8
8
|
import { homedir } from "node:os";
|
package/package.json
CHANGED
|
@@ -140,6 +140,7 @@ var FunnelSlackListener = class extends FunnelConnectorListener {
|
|
|
140
140
|
if (event === null) return;
|
|
141
141
|
const result = processor.process(event);
|
|
142
142
|
if (result.skip) return;
|
|
143
|
+
await notify(result.content, result.meta);
|
|
143
144
|
if (result.shouldReact) try {
|
|
144
145
|
await app.client.reactions.add({
|
|
145
146
|
token: this.config.botToken,
|
|
@@ -148,7 +149,6 @@ var FunnelSlackListener = class extends FunnelConnectorListener {
|
|
|
148
149
|
name: "eyes"
|
|
149
150
|
});
|
|
150
151
|
} catch {}
|
|
151
|
-
await notify(result.content, result.meta);
|
|
152
152
|
});
|
|
153
153
|
app.error(async (error) => {
|
|
154
154
|
this.logger.error("Slack error", { error: error instanceof Error ? error.message : String(error) });
|