blink 0.1.55 → 0.1.57

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.
@@ -1513,13 +1513,7 @@ The structure MUST be as follows:
1513
1513
  **Decision Rules (apply in order):**
1514
1514
  1. **Model Continues:** If your last response explicitly states an immediate next action *you* intend to take (e.g., "Next, I will...", "Now I'll process...", "Moving on to analyze...", indicates an intended tool call that didn't execute), OR if the response seems clearly incomplete (cut off mid-thought without a natural conclusion), then the **'model'** should speak next.
1515
1515
  2. **Question to User:** If your last response ends with a direct question specifically addressed *to the user*, then the **'user'** should speak next.
1516
- 3. **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next.`}]}];try{let parsedResponse=await geminiClient.generateJson(contents,RESPONSE_SCHEMA,abortSignal,DEFAULT_GEMINI_FLASH_MODEL);return parsedResponse&&parsedResponse.next_speaker&&[`user`,`model`].includes(parsedResponse.next_speaker)?parsedResponse:null}catch(error$22){return console.warn(`Failed to talk to Gemini endpoint when seeing if conversation should continue.`,error$22),null}}var require_levenshtein=__commonJSMin(((exports,module)=>{(function(){var collator;try{collator=typeof Intl<`u`&&Intl.Collator!==void 0?Intl.Collator(`generic`,{sensitivity:`base`}):null}catch(err){console.log(`Collator could not be initialized and wouldn't be used`)}var prevRow=[],str2Char=[],Levenshtein={get:function(str1,str2,options$1){var useCollator=options$1&&collator&&options$1.useCollator,str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i$4,j$2,tmp;for(i$4=0;i$4<str2Len;++i$4)prevRow[i$4]=i$4,str2Char[i$4]=str2.charCodeAt(i$4);prevRow[str2Len]=str2Len;var strCmp;if(useCollator)for(i$4=0;i$4<str1Len;++i$4){for(nextCol=i$4+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=collator.compare(str1.charAt(i$4),String.fromCharCode(str2Char[j$2]))===0,nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}else for(i$4=0;i$4<str1Len;++i$4){for(nextCol=i$4+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=str1.charCodeAt(i$4)===str2Char[j$2],nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}return nextCol}};typeof define<`u`&&define!==null&&define.amd?define(function(){return Levenshtein}):module!=null&&exports!==void 0&&module.exports===exports?module.exports=Levenshtein:typeof self<`u`&&typeof self.postMessage==`function`&&typeof self.importScripts==`function`?self.Levenshtein=Levenshtein:typeof window<`u`&&window!==null&&(window.Levenshtein=Levenshtein)})()})),import_levenshtein=__toESM(require_levenshtein(),1),ChatRecordingService=class{conversationFile=null;cachedLastConvData=null;sessionId;projectHash;queuedThoughts=[];queuedTokens=null;config;constructor(config){this.config=config,this.sessionId=config.getSessionId(),this.projectHash=getProjectHash(config.getProjectRoot())}initialize(resumedSessionData){try{if(resumedSessionData)this.conversationFile=resumedSessionData.filePath,this.sessionId=resumedSessionData.conversation.sessionId,this.updateConversation(conversation=>{conversation.sessionId=this.sessionId}),this.cachedLastConvData=null;else{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`);fs.mkdirSync(chatsDir,{recursive:!0});let timestamp=new Date().toISOString().slice(0,16).replace(/:/g,`-`),filename=`session-${timestamp}-${this.sessionId.slice(0,8)}.json`;this.conversationFile=path.join(chatsDir,filename),this.writeConversation({sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]})}this.queuedThoughts=[],this.queuedTokens=null}catch(error$22){throw console.error(`Error initializing chat recording service:`,error$22),error$22}}getLastMessage(conversation){return conversation.messages.at(-1)}newMessage(type,content){return{id:randomUUID$1(),timestamp:new Date().toISOString(),type,content}}recordMessage(message){if(this.conversationFile)try{this.updateConversation(conversation=>{let msg=this.newMessage(message.type,message.content);msg.type===`gemini`?(conversation.messages.push({...msg,thoughts:this.queuedThoughts,tokens:this.queuedTokens,model:this.config.getModel()}),this.queuedThoughts=[],this.queuedTokens=null):conversation.messages.push(msg)})}catch(error$22){throw console.error(`Error saving message:`,error$22),error$22}}recordThought(thought){if(this.conversationFile)try{this.queuedThoughts.push({...thought,timestamp:new Date().toISOString()})}catch(error$22){throw console.error(`Error saving thought:`,error$22),error$22}}recordMessageTokens(respUsageMetadata){if(this.conversationFile)try{let tokens={input:respUsageMetadata.promptTokenCount??0,output:respUsageMetadata.candidatesTokenCount??0,cached:respUsageMetadata.cachedContentTokenCount??0,thoughts:respUsageMetadata.thoughtsTokenCount??0,tool:respUsageMetadata.toolUsePromptTokenCount??0,total:respUsageMetadata.totalTokenCount??0};this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);lastMsg&&lastMsg.type===`gemini`&&!lastMsg.tokens?(lastMsg.tokens=tokens,this.queuedTokens=null):this.queuedTokens=tokens})}catch(error$22){throw console.error(`Error updating message tokens:`,error$22),error$22}}recordToolCalls(toolCalls){if(!this.conversationFile)return;let toolRegistry=this.config.getToolRegistry(),enrichedToolCalls=toolCalls.map(toolCall=>{let toolInstance=toolRegistry.getTool(toolCall.name);return{...toolCall,displayName:toolInstance?.displayName||toolCall.name,description:toolInstance?.description||``,renderOutputAsMarkdown:toolInstance?.isOutputMarkdown||!1}});try{this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);if(!lastMsg||lastMsg.type!==`gemini`||this.queuedThoughts.length>0){let newMsg={...this.newMessage(`gemini`,``),type:`gemini`,toolCalls:enrichedToolCalls,thoughts:this.queuedThoughts,model:this.config.getModel()};this.queuedThoughts.length>0&&(newMsg.thoughts=this.queuedThoughts,this.queuedThoughts=[]),this.queuedTokens&&(newMsg.tokens=this.queuedTokens,this.queuedTokens=null),conversation.messages.push(newMsg)}else{lastMsg.toolCalls||(lastMsg.toolCalls=[]),lastMsg.toolCalls=lastMsg.toolCalls.map(toolCall=>{let incomingToolCall=toolCalls.find(tc=>tc.id===toolCall.id);return incomingToolCall?{...toolCall,...incomingToolCall}:toolCall});for(let toolCall of enrichedToolCalls){let existingToolCall=lastMsg.toolCalls.find(tc=>tc.id===toolCall.id);existingToolCall||lastMsg.toolCalls.push(toolCall)}}})}catch(error$22){throw console.error(`Error adding tool call to message:`,error$22),error$22}}readConversation(){try{return this.cachedLastConvData=fs.readFileSync(this.conversationFile,`utf8`),JSON.parse(this.cachedLastConvData)}catch(error$22){if(error$22.code!==`ENOENT`)throw console.error(`Error reading conversation file:`,error$22),error$22;return{sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]}}}writeConversation(conversation){try{if(!this.conversationFile||conversation.messages.length===0)return;if(this.cachedLastConvData!==JSON.stringify(conversation,null,2)){conversation.lastUpdated=new Date().toISOString();let newContent=JSON.stringify(conversation,null,2);this.cachedLastConvData=newContent,fs.writeFileSync(this.conversationFile,newContent)}}catch(error$22){throw console.error(`Error writing conversation file:`,error$22),error$22}}updateConversation(updateFn){let conversation=this.readConversation();updateFn(conversation),this.writeConversation(conversation)}deleteSession(sessionId$1){try{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`),sessionPath=path.join(chatsDir,`${sessionId$1}.json`);fs.unlinkSync(sessionPath)}catch(error$22){throw console.error(`Error deleting session:`,error$22),error$22}}};init_esm$1();
1517
- /**
1518
- * @license
1519
- * Copyright 2025 Google LLC
1520
- * SPDX-License-Identifier: Apache-2.0
1521
- */
1522
- var TelemetryTarget;(function(TelemetryTarget$1){TelemetryTarget$1.GCP=`gcp`,TelemetryTarget$1.LOCAL=`local`})(TelemetryTarget||(TelemetryTarget={}));const DEFAULT_TELEMETRY_TARGET=TelemetryTarget.LOCAL,DEFAULT_OTLP_ENDPOINT=`http://localhost:4317`;async function handleFallback(config,failedModel,authType,error$22){if(authType!==AuthType.LOGIN_WITH_GOOGLE)return null;let fallbackModel=DEFAULT_GEMINI_FLASH_MODEL;if(failedModel===fallbackModel)return null;let fallbackModelHandler=config.fallbackModelHandler;if(typeof fallbackModelHandler!=`function`)return null;try{let intent=await fallbackModelHandler(failedModel,fallbackModel,error$22);switch(intent){case`retry`:return activateFallbackMode(config,authType),!0;case`stop`:return activateFallbackMode(config,authType),!1;case`auth`:return!1;default:throw Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`)}}catch(handlerError){return console.error(`Fallback UI handler failed:`,handlerError),null}}function activateFallbackMode(config,authType){config.isInFallbackMode()||(config.setFallbackMode(!0),authType&&logFlashFallback(config,new FlashFallbackEvent(authType)))}function partListUnionToString(value){return partToString(value,{verbose:!0})}var StreamEventType;(function(StreamEventType$1){StreamEventType$1.CHUNK=`chunk`,StreamEventType$1.RETRY=`retry`})(StreamEventType||(StreamEventType={}));const INVALID_CONTENT_RETRY_OPTIONS={maxAttempts:3,initialDelayMs:500};function isValidResponse(response){if(response.candidates===void 0||response.candidates.length===0)return!1;let content=response.candidates[0]?.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0||!part.thought&&part.text!==void 0&&part.text===``)return!1;return!0}function validateHistory(history){for(let content of history)if(content.role!==`user`&&content.role!==`model`)throw Error(`Role must be user or model, but got ${content.role}.`)}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i$4=0;for(;i$4<length;)if(comprehensiveHistory[i$4].role===`user`)curatedHistory.push(comprehensiveHistory[i$4]),i$4++;else{let modelOutput=[],isValid=!0;for(;i$4<length&&comprehensiveHistory[i$4].role===`model`;)modelOutput.push(comprehensiveHistory[i$4]),isValid&&!isValidContent(comprehensiveHistory[i$4])&&(isValid=!1),i$4++;isValid&&curatedHistory.push(...modelOutput)}return curatedHistory}var EmptyStreamError=class extends Error{constructor(message){super(message),this.name=`EmptyStreamError`}},GeminiChat=class{config;generationConfig;history;sendPromise=Promise.resolve();chatRecordingService;constructor(config,generationConfig={},history=[]){this.config=config,this.generationConfig=generationConfig,this.history=history,validateHistory(history),this.chatRecordingService=new ChatRecordingService(config),this.chatRecordingService.initialize()}setSystemInstruction(sysInstr){this.generationConfig.systemInstruction=sysInstr}async sendMessageStream(params,prompt_id){await this.sendPromise;let streamDoneResolver,streamDonePromise=new Promise(resolve$9=>{streamDoneResolver=resolve$9});this.sendPromise=streamDonePromise;let userContent=createUserContent(params.message);if(!isFunctionResponse(userContent)){let userMessage=Array.isArray(params.message)?params.message:[params.message],userMessageContent=partListUnionToString(toParts(userMessage));this.chatRecordingService.recordMessage({type:`user`,content:userMessageContent})}this.history.push(userContent);let requestContents=this.getHistory(!0),self$1=this;return(async function*(){try{let lastError=Error(`Request failed after all retries.`);for(let attempt=0;attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts;attempt++)try{attempt>0&&(yield{type:StreamEventType.RETRY});let stream$8=await self$1.makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent);for await(let chunk$1 of stream$8)yield{type:StreamEventType.CHUNK,value:chunk$1};lastError=null;break}catch(error$22){lastError=error$22;let isContentError=error$22 instanceof EmptyStreamError;if(isContentError&&attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts-1){logContentRetry(self$1.config,new ContentRetryEvent(attempt,`EmptyStreamError`,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs)),await new Promise(res=>setTimeout(res,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs*(attempt+1)));continue}break}if(lastError)throw lastError instanceof EmptyStreamError&&logContentRetryFailure(self$1.config,new ContentRetryFailureEvent(INVALID_CONTENT_RETRY_OPTIONS.maxAttempts,`EmptyStreamError`)),self$1.history[self$1.history.length-1]===userContent&&self$1.history.pop(),lastError}finally{streamDoneResolver()}})()}async makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent){let currentAttemptModel,apiCall=()=>{let modelToUse=this.config.isInFallbackMode()?DEFAULT_GEMINI_FLASH_MODEL:this.config.getModel();if(currentAttemptModel=modelToUse,this.config.getQuotaErrorOccurred()&&modelToUse===DEFAULT_GEMINI_FLASH_MODEL)throw Error(`Please submit a new query to continue with the Flash model.`);return this.config.getContentGenerator().generateContentStream({model:modelToUse,contents:requestContents,config:{...this.generationConfig,...params.config}},prompt_id)},onPersistent429Callback=async(authType,error$22)=>currentAttemptModel?await handleFallback(this.config,currentAttemptModel,authType,error$22):null,streamResponse=await retryWithBackoff(apiCall,{shouldRetry:error$22=>{if(error$22 instanceof Error&&error$22.message){if(isSchemaDepthError(error$22.message))return!1;if(error$22.message.includes(`429`)||error$22.message.match(/5\d{2}/))return!0}return!1},onPersistent429:onPersistent429Callback,authType:this.config.getContentGeneratorConfig()?.authType});return this.processStreamResponse(streamResponse,userContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}clearHistory(){this.history=[]}addHistory(content){this.history.push(content)}setHistory(history){this.history=history}stripThoughtsFromHistory(){this.history=this.history.map(content=>{let newContent={...content};return newContent.parts&&(newContent.parts=newContent.parts.map(part=>{if(part&&typeof part==`object`&&`thoughtSignature`in part){let newPart={...part};return delete newPart.thoughtSignature,newPart}return part})),newContent})}setTools(tools){this.generationConfig.tools=tools}async maybeIncludeSchemaDepthContext(error$22){if(isSchemaDepthError(error$22.message)||isInvalidArgumentError(error$22.message)){let tools=this.config.getToolRegistry().getAllTools(),cyclicSchemaTools=[];for(let tool$1 of tools)(tool$1.schema.parametersJsonSchema&&hasCycleInSchema(tool$1.schema.parametersJsonSchema)||tool$1.schema.parameters&&hasCycleInSchema(tool$1.schema.parameters))&&cyclicSchemaTools.push(tool$1.displayName);if(cyclicSchemaTools.length>0){let extraDetails=`
1516
+ 3. **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next.`}]}];try{let parsedResponse=await geminiClient.generateJson(contents,RESPONSE_SCHEMA,abortSignal,DEFAULT_GEMINI_FLASH_MODEL);return parsedResponse&&parsedResponse.next_speaker&&[`user`,`model`].includes(parsedResponse.next_speaker)?parsedResponse:null}catch(error$22){return console.warn(`Failed to talk to Gemini endpoint when seeing if conversation should continue.`,error$22),null}}var require_levenshtein=__commonJSMin(((exports,module)=>{(function(){var collator;try{collator=typeof Intl<`u`&&Intl.Collator!==void 0?Intl.Collator(`generic`,{sensitivity:`base`}):null}catch(err){console.log(`Collator could not be initialized and wouldn't be used`)}var prevRow=[],str2Char=[],Levenshtein={get:function(str1,str2,options$1){var useCollator=options$1&&collator&&options$1.useCollator,str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i$4,j$2,tmp;for(i$4=0;i$4<str2Len;++i$4)prevRow[i$4]=i$4,str2Char[i$4]=str2.charCodeAt(i$4);prevRow[str2Len]=str2Len;var strCmp;if(useCollator)for(i$4=0;i$4<str1Len;++i$4){for(nextCol=i$4+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=collator.compare(str1.charAt(i$4),String.fromCharCode(str2Char[j$2]))===0,nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}else for(i$4=0;i$4<str1Len;++i$4){for(nextCol=i$4+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=str1.charCodeAt(i$4)===str2Char[j$2],nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}return nextCol}};typeof define<`u`&&define!==null&&define.amd?define(function(){return Levenshtein}):module!=null&&exports!==void 0&&module.exports===exports?module.exports=Levenshtein:typeof self<`u`&&typeof self.postMessage==`function`&&typeof self.importScripts==`function`?self.Levenshtein=Levenshtein:typeof window<`u`&&window!==null&&(window.Levenshtein=Levenshtein)})()})),import_levenshtein=__toESM(require_levenshtein(),1),ChatRecordingService=class{conversationFile=null;cachedLastConvData=null;sessionId;projectHash;queuedThoughts=[];queuedTokens=null;config;constructor(config){this.config=config,this.sessionId=config.getSessionId(),this.projectHash=getProjectHash(config.getProjectRoot())}initialize(resumedSessionData){try{if(resumedSessionData)this.conversationFile=resumedSessionData.filePath,this.sessionId=resumedSessionData.conversation.sessionId,this.updateConversation(conversation=>{conversation.sessionId=this.sessionId}),this.cachedLastConvData=null;else{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`);fs.mkdirSync(chatsDir,{recursive:!0});let timestamp=new Date().toISOString().slice(0,16).replace(/:/g,`-`),filename=`session-${timestamp}-${this.sessionId.slice(0,8)}.json`;this.conversationFile=path.join(chatsDir,filename),this.writeConversation({sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]})}this.queuedThoughts=[],this.queuedTokens=null}catch(error$22){throw console.error(`Error initializing chat recording service:`,error$22),error$22}}getLastMessage(conversation){return conversation.messages.at(-1)}newMessage(type,content){return{id:randomUUID$1(),timestamp:new Date().toISOString(),type,content}}recordMessage(message){if(this.conversationFile)try{this.updateConversation(conversation=>{let msg=this.newMessage(message.type,message.content);msg.type===`gemini`?(conversation.messages.push({...msg,thoughts:this.queuedThoughts,tokens:this.queuedTokens,model:this.config.getModel()}),this.queuedThoughts=[],this.queuedTokens=null):conversation.messages.push(msg)})}catch(error$22){throw console.error(`Error saving message:`,error$22),error$22}}recordThought(thought){if(this.conversationFile)try{this.queuedThoughts.push({...thought,timestamp:new Date().toISOString()})}catch(error$22){throw console.error(`Error saving thought:`,error$22),error$22}}recordMessageTokens(respUsageMetadata){if(this.conversationFile)try{let tokens={input:respUsageMetadata.promptTokenCount??0,output:respUsageMetadata.candidatesTokenCount??0,cached:respUsageMetadata.cachedContentTokenCount??0,thoughts:respUsageMetadata.thoughtsTokenCount??0,tool:respUsageMetadata.toolUsePromptTokenCount??0,total:respUsageMetadata.totalTokenCount??0};this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);lastMsg&&lastMsg.type===`gemini`&&!lastMsg.tokens?(lastMsg.tokens=tokens,this.queuedTokens=null):this.queuedTokens=tokens})}catch(error$22){throw console.error(`Error updating message tokens:`,error$22),error$22}}recordToolCalls(toolCalls){if(!this.conversationFile)return;let toolRegistry=this.config.getToolRegistry(),enrichedToolCalls=toolCalls.map(toolCall=>{let toolInstance=toolRegistry.getTool(toolCall.name);return{...toolCall,displayName:toolInstance?.displayName||toolCall.name,description:toolInstance?.description||``,renderOutputAsMarkdown:toolInstance?.isOutputMarkdown||!1}});try{this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);if(!lastMsg||lastMsg.type!==`gemini`||this.queuedThoughts.length>0){let newMsg={...this.newMessage(`gemini`,``),type:`gemini`,toolCalls:enrichedToolCalls,thoughts:this.queuedThoughts,model:this.config.getModel()};this.queuedThoughts.length>0&&(newMsg.thoughts=this.queuedThoughts,this.queuedThoughts=[]),this.queuedTokens&&(newMsg.tokens=this.queuedTokens,this.queuedTokens=null),conversation.messages.push(newMsg)}else{lastMsg.toolCalls||(lastMsg.toolCalls=[]),lastMsg.toolCalls=lastMsg.toolCalls.map(toolCall=>{let incomingToolCall=toolCalls.find(tc=>tc.id===toolCall.id);return incomingToolCall?{...toolCall,...incomingToolCall}:toolCall});for(let toolCall of enrichedToolCalls){let existingToolCall=lastMsg.toolCalls.find(tc=>tc.id===toolCall.id);existingToolCall||lastMsg.toolCalls.push(toolCall)}}})}catch(error$22){throw console.error(`Error adding tool call to message:`,error$22),error$22}}readConversation(){try{return this.cachedLastConvData=fs.readFileSync(this.conversationFile,`utf8`),JSON.parse(this.cachedLastConvData)}catch(error$22){if(error$22.code!==`ENOENT`)throw console.error(`Error reading conversation file:`,error$22),error$22;return{sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]}}}writeConversation(conversation){try{if(!this.conversationFile||conversation.messages.length===0)return;if(this.cachedLastConvData!==JSON.stringify(conversation,null,2)){conversation.lastUpdated=new Date().toISOString();let newContent=JSON.stringify(conversation,null,2);this.cachedLastConvData=newContent,fs.writeFileSync(this.conversationFile,newContent)}}catch(error$22){throw console.error(`Error writing conversation file:`,error$22),error$22}}updateConversation(updateFn){let conversation=this.readConversation();updateFn(conversation),this.writeConversation(conversation)}deleteSession(sessionId$1){try{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`),sessionPath=path.join(chatsDir,`${sessionId$1}.json`);fs.unlinkSync(sessionPath)}catch(error$22){throw console.error(`Error deleting session:`,error$22),error$22}}},TelemetryTarget;(function(TelemetryTarget$1){TelemetryTarget$1.GCP=`gcp`,TelemetryTarget$1.LOCAL=`local`})(TelemetryTarget||(TelemetryTarget={}));const DEFAULT_TELEMETRY_TARGET=TelemetryTarget.LOCAL,DEFAULT_OTLP_ENDPOINT=`http://localhost:4317`;async function handleFallback(config,failedModel,authType,error$22){if(authType!==AuthType.LOGIN_WITH_GOOGLE)return null;let fallbackModel=DEFAULT_GEMINI_FLASH_MODEL;if(failedModel===fallbackModel)return null;let fallbackModelHandler=config.fallbackModelHandler;if(typeof fallbackModelHandler!=`function`)return null;try{let intent=await fallbackModelHandler(failedModel,fallbackModel,error$22);switch(intent){case`retry`:return activateFallbackMode(config,authType),!0;case`stop`:return activateFallbackMode(config,authType),!1;case`auth`:return!1;default:throw Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`)}}catch(handlerError){return console.error(`Fallback UI handler failed:`,handlerError),null}}function activateFallbackMode(config,authType){config.isInFallbackMode()||(config.setFallbackMode(!0),authType&&logFlashFallback(config,new FlashFallbackEvent(authType)))}function partListUnionToString(value){return partToString(value,{verbose:!0})}var StreamEventType;(function(StreamEventType$1){StreamEventType$1.CHUNK=`chunk`,StreamEventType$1.RETRY=`retry`})(StreamEventType||(StreamEventType={}));const INVALID_CONTENT_RETRY_OPTIONS={maxAttempts:3,initialDelayMs:500};function isValidResponse(response){if(response.candidates===void 0||response.candidates.length===0)return!1;let content=response.candidates[0]?.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0||!part.thought&&part.text!==void 0&&part.text===``)return!1;return!0}function validateHistory(history){for(let content of history)if(content.role!==`user`&&content.role!==`model`)throw Error(`Role must be user or model, but got ${content.role}.`)}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i$4=0;for(;i$4<length;)if(comprehensiveHistory[i$4].role===`user`)curatedHistory.push(comprehensiveHistory[i$4]),i$4++;else{let modelOutput=[],isValid=!0;for(;i$4<length&&comprehensiveHistory[i$4].role===`model`;)modelOutput.push(comprehensiveHistory[i$4]),isValid&&!isValidContent(comprehensiveHistory[i$4])&&(isValid=!1),i$4++;isValid&&curatedHistory.push(...modelOutput)}return curatedHistory}var EmptyStreamError=class extends Error{constructor(message){super(message),this.name=`EmptyStreamError`}},GeminiChat=class{config;generationConfig;history;sendPromise=Promise.resolve();chatRecordingService;constructor(config,generationConfig={},history=[]){this.config=config,this.generationConfig=generationConfig,this.history=history,validateHistory(history),this.chatRecordingService=new ChatRecordingService(config),this.chatRecordingService.initialize()}setSystemInstruction(sysInstr){this.generationConfig.systemInstruction=sysInstr}async sendMessageStream(params,prompt_id){await this.sendPromise;let streamDoneResolver,streamDonePromise=new Promise(resolve$9=>{streamDoneResolver=resolve$9});this.sendPromise=streamDonePromise;let userContent=createUserContent(params.message);if(!isFunctionResponse(userContent)){let userMessage=Array.isArray(params.message)?params.message:[params.message],userMessageContent=partListUnionToString(toParts(userMessage));this.chatRecordingService.recordMessage({type:`user`,content:userMessageContent})}this.history.push(userContent);let requestContents=this.getHistory(!0),self$1=this;return(async function*(){try{let lastError=Error(`Request failed after all retries.`);for(let attempt=0;attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts;attempt++)try{attempt>0&&(yield{type:StreamEventType.RETRY});let stream$8=await self$1.makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent);for await(let chunk$1 of stream$8)yield{type:StreamEventType.CHUNK,value:chunk$1};lastError=null;break}catch(error$22){lastError=error$22;let isContentError=error$22 instanceof EmptyStreamError;if(isContentError&&attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts-1){logContentRetry(self$1.config,new ContentRetryEvent(attempt,`EmptyStreamError`,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs)),await new Promise(res=>setTimeout(res,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs*(attempt+1)));continue}break}if(lastError)throw lastError instanceof EmptyStreamError&&logContentRetryFailure(self$1.config,new ContentRetryFailureEvent(INVALID_CONTENT_RETRY_OPTIONS.maxAttempts,`EmptyStreamError`)),self$1.history[self$1.history.length-1]===userContent&&self$1.history.pop(),lastError}finally{streamDoneResolver()}})()}async makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent){let currentAttemptModel,apiCall=()=>{let modelToUse=this.config.isInFallbackMode()?DEFAULT_GEMINI_FLASH_MODEL:this.config.getModel();if(currentAttemptModel=modelToUse,this.config.getQuotaErrorOccurred()&&modelToUse===DEFAULT_GEMINI_FLASH_MODEL)throw Error(`Please submit a new query to continue with the Flash model.`);return this.config.getContentGenerator().generateContentStream({model:modelToUse,contents:requestContents,config:{...this.generationConfig,...params.config}},prompt_id)},onPersistent429Callback=async(authType,error$22)=>currentAttemptModel?await handleFallback(this.config,currentAttemptModel,authType,error$22):null,streamResponse=await retryWithBackoff(apiCall,{shouldRetry:error$22=>{if(error$22 instanceof Error&&error$22.message){if(isSchemaDepthError(error$22.message))return!1;if(error$22.message.includes(`429`)||error$22.message.match(/5\d{2}/))return!0}return!1},onPersistent429:onPersistent429Callback,authType:this.config.getContentGeneratorConfig()?.authType});return this.processStreamResponse(streamResponse,userContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}clearHistory(){this.history=[]}addHistory(content){this.history.push(content)}setHistory(history){this.history=history}stripThoughtsFromHistory(){this.history=this.history.map(content=>{let newContent={...content};return newContent.parts&&(newContent.parts=newContent.parts.map(part=>{if(part&&typeof part==`object`&&`thoughtSignature`in part){let newPart={...part};return delete newPart.thoughtSignature,newPart}return part})),newContent})}setTools(tools){this.generationConfig.tools=tools}async maybeIncludeSchemaDepthContext(error$22){if(isSchemaDepthError(error$22.message)||isInvalidArgumentError(error$22.message)){let tools=this.config.getToolRegistry().getAllTools(),cyclicSchemaTools=[];for(let tool$1 of tools)(tool$1.schema.parametersJsonSchema&&hasCycleInSchema(tool$1.schema.parametersJsonSchema)||tool$1.schema.parameters&&hasCycleInSchema(tool$1.schema.parameters))&&cyclicSchemaTools.push(tool$1.displayName);if(cyclicSchemaTools.length>0){let extraDetails=`
1523
1517
 
1524
1518
  This error was probably caused by cyclic schema references in one of the following tools, try disabling them with excludeTools:
1525
1519
 
package/dist/cli/index.js CHANGED
@@ -17,6 +17,6 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
18
  - ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;if(o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),!f.killed){let e=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];e.forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})})}let p=this._exitCallback;f.on(`close`,e=>{e=e??1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`}),t=e.filter(e=>e.conflictsWith.length>0);t.forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,i=e.slice();function a(e){return e.length>1&&e[0]===`-`}let o=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,s=null;for(;i.length;){let e=i.shift();if(e===`--`){r===n&&r.push(e),r.push(...i);break}if(s&&(!a(e)||o(e))){this.emit(`option:${s.name()}`,e);continue}if(s=null,a(e)){let t=this._findOption(e);if(t){if(t.required){let e=i.shift();e===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;i.length>0&&(!a(i[0])||o(i[0]))&&(e=i.shift()),this.emit(`option:${t.name()}`,e)}else this.emit(`option:${t.name()}`);s=t.variadic?t:null;continue}}if(e.length>2&&e[0]===`-`&&e[1]!==`-`){let t=this._findOption(`-${e[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,e.slice(2)):(this.emit(`option:${t.name()}`),i.unshift(`-${e.slice(2)}`));continue}}if(/^--[^=]+=/.test(e)){let t=e.indexOf(`=`),n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(r===t&&a(e)&&!(this.commands.length===0&&o(e))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(e)){t.push(e),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(e),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){r.push(e),i.length>0&&r.push(...i);break}r.push(e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
19
19
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName(),i=this.getOptionValueSource(r);return i===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=this.parent?` for '${this.name()}'`:``,i=`error: too many arguments${r}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||`-V, --version`,n=n||`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,i;t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth());let a=e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e));return{error:t,write:a,hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
20
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption(),n=t&&e.find(e=>t.is(e));n&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=h,exports.useColor=_})),A=e((exports=>{let{Argument:t}=T(),{Command:n}=k(),{CommanderError:r,InvalidArgumentError:i}=w(),{Help:a}=E(),{Option:o}=D();exports.program=new n,exports.createCommand=e=>new n(e),exports.createOption=(e,t)=>new o(e,t),exports.createArgument=(e,n)=>new t(e,n),exports.Command=n,exports.Option=o,exports.Argument=t,exports.Help=a,exports.CommanderError=r,exports.InvalidArgumentError=i,exports.InvalidOptionArgumentError=i})),j=n(A(),1);const{program:M,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:L,InvalidOptionArgumentError:R,Command:z,Argument:B,Option:V,Help:H}=j.default;var U=`0.1.55`;async function W(e){e||(e=process.cwd());let t=o(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var G=n(a(),1);async function K(e,t){e||(e=process.cwd());let n=await c(),r=new s({authToken:n}),a=await i(e,`package.json`);if(!a)throw Error(`package.json not found`);let m=await S(a,`utf-8`),w=JSON.parse(m),T=g(a),E=_(T,`.blink`,`config.json`),D={};if(v(E)){let e=await S(E,`utf-8`);D=JSON.parse(e)}let O;if(D?.organizationId)try{let e=await r.organizations.get(D.organizationId);O=e.name}catch(e){D.organizationId=void 0}if(!D?.organizationId){let e=await r.organizations.list();if(e.length===1){let t=e[0];D.organizationId=t.id,O=t.name}else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;D.organizationId=t,O=e.find(e=>e.id===t).name}}if(!D.organizationId)throw Error(`Developer error: No organization ID found.`);let k;if(D?.agentId)try{let e=await r.agents.get(D.agentId);k=e.name}catch(e){D.agentId=void 0}if(!D?.agentId)try{let e=await r.organizations.agents.get({organization_id:D.organizationId,agent_name:w.name});D.agentId=e.id,k=e.name}catch(e){let t=await r.agents.create({name:w.name,organization_id:D.organizationId});D.agentId=t.id,k=t.name}if(!D.agentId)throw Error(`Developer error: No agent ID found.`);await y(g(E),{recursive:!0}),await x(E,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...D},null,2),`utf-8`);let A=o(T),j;if(await A.build({cwd:T,entry:A.entry,outdir:A.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{j=e}}),!j)throw Error(`Failed to build agent`);if(`error`in j)throw Error(j.error.message);let M={},N=await b(j.outdir);for(let e of N)M[_(j.outdir,e)]=e;let P=_(e,`README.md`);await q(P)&&(M[P]=`README.md`);let F=[],I=Object.keys(M).length,L=0,R=0;for(let[e,t]of Object.entries(M)){let n=await C(e),i=n.size;Y(`${l.dim(`[${L+1}/${I}]`)} Uploading ${t} (${J(i)})...`);let a=await S(e),o=await r.files.upload(new File([a],t));F.push({path:t,id:o.id}),L+=1,R+=i}Y(`${l.dim(`[${L}/${I}]`)} Uploaded files (${J(R)}).`),process.stdout.write(`
20
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption(),n=t&&e.find(e=>t.is(e));n&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=h,exports.useColor=_})),A=e((exports=>{let{Argument:t}=T(),{Command:n}=k(),{CommanderError:r,InvalidArgumentError:i}=w(),{Help:a}=E(),{Option:o}=D();exports.program=new n,exports.createCommand=e=>new n(e),exports.createOption=(e,t)=>new o(e,t),exports.createArgument=(e,n)=>new t(e,n),exports.Command=n,exports.Option=o,exports.Argument=t,exports.Help=a,exports.CommanderError=r,exports.InvalidArgumentError=i,exports.InvalidOptionArgumentError=i})),j=n(A(),1);const{program:M,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:L,InvalidOptionArgumentError:R,Command:z,Argument:B,Option:V,Help:H}=j.default;var U=`0.1.57`;async function W(e){e||(e=process.cwd());let t=o(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var G=n(a(),1);async function K(e,t){e||(e=process.cwd());let n=await c(),r=new s({authToken:n}),a=await i(e,`package.json`);if(!a)throw Error(`package.json not found`);let m=await S(a,`utf-8`),w=JSON.parse(m),T=g(a),E=_(T,`.blink`,`config.json`),D={};if(v(E)){let e=await S(E,`utf-8`);D=JSON.parse(e)}let O;if(D?.organizationId)try{let e=await r.organizations.get(D.organizationId);O=e.name}catch(e){D.organizationId=void 0}if(!D?.organizationId){let e=await r.organizations.list();if(e.length===1){let t=e[0];D.organizationId=t.id,O=t.name}else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;D.organizationId=t,O=e.find(e=>e.id===t).name}}if(!D.organizationId)throw Error(`Developer error: No organization ID found.`);let k;if(D?.agentId)try{let e=await r.agents.get(D.agentId);k=e.name}catch(e){D.agentId=void 0}if(!D?.agentId)try{let e=await r.organizations.agents.get({organization_id:D.organizationId,agent_name:w.name});D.agentId=e.id,k=e.name}catch(e){let t=await r.agents.create({name:w.name,organization_id:D.organizationId});D.agentId=t.id,k=t.name}if(!D.agentId)throw Error(`Developer error: No agent ID found.`);await y(g(E),{recursive:!0}),await x(E,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...D},null,2),`utf-8`);let A=o(T),j=await new Promise((e,t)=>{A.build({cwd:T,entry:A.entry,outdir:A.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!j)throw Error(`Failed to build agent`);if(`error`in j)throw Error(j.error.message);let M={},N=await b(j.outdir);for(let e of N)M[_(j.outdir,e)]=e;let P=_(e,`README.md`);await q(P)&&(M[P]=`README.md`);let F=[],I=Object.keys(M).length,L=0,R=0;for(let[e,t]of Object.entries(M)){let n=await C(e),i=n.size;Y(`${l.dim(`[${L+1}/${I}]`)} Uploading ${t} (${J(i)})...`);let a=await S(e),o=await r.files.upload(new File([a],t));F.push({path:t,id:o.id}),L+=1,R+=i}Y(`${l.dim(`[${L}/${I}]`)} Uploaded files (${J(R)}).`),process.stdout.write(`
21
21
  `);let z=_(e,`.env.local`),B=[];if(await q(z)){let e=(0,G.parse)(await S(z,`utf-8`));B=Object.keys(e)}let V=[],H=await r.agents.env.list({agent_id:D.agentId});V=H.map(e=>e.key);let U=_(e,`.env.production`);if(await q(U)){let e=(0,G.parse)(await S(U,`utf-8`)),t=Object.entries(e),n=t.length,i=0;for(let[e,a]of t){let t=await r.agents.env.create({agent_id:D.agentId,key:e,value:a,target:[`production`,`preview`],secret:!0,upsert:!0});V.push(t.key),i+=1,Y(`${l.dim(`[${i}/${n}]`)} Updating environment variable: ${e} ${l.dim(`(.env.production)`)}`)}Y(`${l.dim(`[${i}/${n}]`)} Updated environment variables! ${l.dim(`(.env.production)`)}`),process.stdout.write(`
22
- `)}let W=B.filter(e=>!V.includes(e));if(W.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of W)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let K=await r.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:h(j.entry),files:F,message:t?.message}),X=`https://blink.so/${O}/${k}/deployments/${K.number}`;console.log(`Deployed:`,X);let Z=u();Z.start(`Waiting for deployment to be live...`);try{for(;;){let e=await r.agents.deployments.get({agent_id:D.agentId,deployment_id:K.id});if(e.status===`success`){let t=`Deployment successful.`;e.target===`production`&&(t+=` All chats will use this deployment!`),Z.stop(t);break}if(e.status===`failed`){let t=`Deployment failed.`;e.error_message&&(t+=` ${e.error_message}`),Z.stop(t),console.log(`Read logs for details:`,X);return}await new Promise(e=>setTimeout(e,500))}}catch(e){Z.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,X);return}}const q=async e=>{try{return await C(e),!0}catch(e){return!1}};function J(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/Math.pow(t,r);return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function Y(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>m()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(U).action(()=>{M.outputHelp()});const X=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(X(()=>import(`./init-x07jlFqm.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(X(()=>import(`./dev-Kje8z9kN.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(K),M.command(`build [directory]`).description(`Build your agent for production.`).action(W),M.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),M.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(X(()=>import(`./connect-BHyGYU8L.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(X(()=>import(`./chat-CvTLq5E0.js`))),M.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(X(()=>import(`./login-KHDcJ0iZ.js`))),M.parse(process.argv);export{};
22
+ `)}let W=B.filter(e=>!V.includes(e));if(W.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of W)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let K=await r.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:h(j.entry),files:F,message:t?.message}),X=`https://blink.so/${O}/${k}/deployments/${K.number}`;console.log(`Deployed:`,X);let Z=u();Z.start(`Waiting for deployment to be live...`);try{for(;;){let e=await r.agents.deployments.get({agent_id:D.agentId,deployment_id:K.id});if(e.status===`success`){let t=`Deployment successful.`;e.target===`production`&&(t+=` All chats will use this deployment!`),Z.stop(t);break}if(e.status===`failed`){let t=`Deployment failed.`;e.error_message&&(t+=` ${e.error_message}`),Z.stop(t),console.log(`Read logs for details:`,X);return}await new Promise(e=>setTimeout(e,500))}}catch(e){Z.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,X);return}}const q=async e=>{try{return await C(e),!0}catch(e){return!1}};function J(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/Math.pow(t,r);return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function Y(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>m()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(U).action(()=>{M.outputHelp()});const X=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(X(()=>import(`./init-x07jlFqm.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(X(()=>import(`./dev-AdCRPYXi.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(K),M.command(`build [directory]`).description(`Build your agent for production.`).action(W),M.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),M.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(X(()=>import(`./connect-BHyGYU8L.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(X(()=>import(`./chat-CvTLq5E0.js`))),M.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(X(()=>import(`./login-KHDcJ0iZ.js`))),M.parse(process.argv);export{};
@@ -0,0 +1 @@
1
+ var e=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof C?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},o=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),v=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},y=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,x)):e,b=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return y(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=y(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=y(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},ee=b,te=(e,t)=>b(e,t,!0),x=decodeURIComponent,S=e=>p(e,x),C=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?S(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?S(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return ee(this.url,e)}queries(e){return te(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await n(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ne={Stringify:1,BeforeStream:2,Stream:3},re=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},w=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>w(e,t,!1,r,i))).then(()=>i[0]));return n?re(await o,a):o},ie=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),E=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new C(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,T(ie,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?w(e,ne.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},D=`ALL`,O=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],k=`Can not add a route since the matcher is already built.`,A=class extends Error{},oe=`__COMPOSED_HANDLER`,se=e=>e.text(`404 Not Found`,404),j=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},M=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...ae,O];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(D,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new M({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=se;errorHandler=j;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===j?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[oe]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(D,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new E(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},N=`[^/]+`,P=`.*`,F=`(?:|/.*)`,I=Symbol(),ce=new Set(`.\\+*[^]$()`);function le(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===P||e===F?1:t===P||t===F?-1:e===N?1:t===N?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var L=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw I;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,P]:[``,``,N]:a===`/*`?[``,``,F]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||N;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw I;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==P&&e!==F))throw I;if(i)return;c=this.#children[t]=new L,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==P&&e!==F))throw I;if(i)return;c=this.#children[a]=new L}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(le),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ce.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ue=class{#context={varIndex:0};#root=new L;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},R=[],de=[/^$/,[],Object.create(null)],z=Object.create(null);function B(e){return z[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function V(){z=Object.create(null)}function H(e){let t=new ue,n=[];if(e.length===0)return de;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),R]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===I?new A(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(B(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[D]:Object.create(null)},this.#routes={[D]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(k);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[D]).forEach(n=>{t[e][n]=[...t[D][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=B(t);e===D?Object.keys(r).forEach(e=>{r[e][t]||=U(r[e],t)||U(r[D],t)||[]}):r[e][t]||=U(r[e],t)||U(r[D],t)||[],Object.keys(r).forEach(t=>{(e===D||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===D||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=v(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===D||e===o)&&(i[o][c]||=[...U(r[o],c)||U(r[D],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){V();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[D],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],R];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===D;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==D&&t.push(...Object.keys(r[D]).map(e=>[e,r[D][e]])):(n||=!0,t.push(...i))}),n?H(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(k);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof A)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new G,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[D],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=s(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(e,t,n){let r=v(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},K=class extends M{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=/^[\w!#$%&'*.^`|~+-]+$/,ge=/^[ !#-:<-[\]-~]*$/,q=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!he.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),ge.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,x),t))break}return r},_e=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=q(r,e);return i[e]}if(!r)return{};let i=q(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ve=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},ye=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,be=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,xe=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!ye.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(be.test(a)||xe.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await ve(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=_e(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new K,Se=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Ce=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),we=new K().route(`/storage`,Se).route(`/chat`,Ce);var Te=we;module.exports=Te;
@@ -0,0 +1,196 @@
1
+ import * as hono_types0 from "hono/types";
2
+ import * as hono_hono_base0 from "hono/hono-base";
3
+ import { UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
4
+
5
+ //#region src/api/chat.d.ts
6
+ interface Chat {
7
+ readonly id: string;
8
+ }
9
+ type ChatBehavior = "enqueue" | "interrupt" | "append";
10
+ interface Message<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes, TOOLS extends UITools = UITools> {
11
+ readonly role: UIMessage["role"];
12
+ readonly parts: UIMessagePart<DATA_TYPES, TOOLS>[];
13
+ readonly metadata?: METADATA;
14
+ }
15
+ //#endregion
16
+ //#region src/http/api.d.ts
17
+ /**
18
+ * APIBindings are functions that will be invoked by the agent.
19
+ */
20
+ type APIBindings = {
21
+ storage: {
22
+ kv: {
23
+ get: (key: string) => Promise<string | undefined>;
24
+ set: (key: string, value: string) => Promise<void>;
25
+ del: (key: string) => Promise<void>;
26
+ };
27
+ };
28
+ chat: {
29
+ upsert: (id: string) => Promise<Chat>;
30
+ sendMessages: (id: string, options: {
31
+ messages: Message[];
32
+ behavior: ChatBehavior;
33
+ }) => Promise<void>;
34
+ };
35
+ };
36
+ /**
37
+ * To implement your own API bindings, you can use Hono's
38
+ * `createServerAdapter` to create a server that will
39
+ * handle requests to the API.
40
+ *
41
+ * ```ts
42
+ * const server = createHTTPServer(
43
+ * createServerAdapter((req) => {
44
+ * return api.fetch(req, <your-bindings>);
45
+ * })
46
+ * );
47
+ * server.listen(options.port);
48
+ * ```
49
+ */
50
+ declare const api: hono_hono_base0.HonoBase<{
51
+ Bindings: APIBindings;
52
+ }, hono_types0.BlankSchema | hono_types0.MergeSchemaPath<{
53
+ "/kv/:key": {
54
+ $get: {
55
+ input: {
56
+ param: {
57
+ key: string;
58
+ };
59
+ };
60
+ output: {
61
+ error: string;
62
+ };
63
+ outputFormat: "json";
64
+ status: 400;
65
+ } | {
66
+ input: {
67
+ param: {
68
+ key: string;
69
+ };
70
+ };
71
+ output: {
72
+ value: string | undefined;
73
+ };
74
+ outputFormat: "json";
75
+ status: 200;
76
+ };
77
+ };
78
+ } & {
79
+ "/kv/:key": {
80
+ $post: {
81
+ input: {
82
+ json: {
83
+ value: string;
84
+ };
85
+ } & {
86
+ param: {
87
+ key: string;
88
+ };
89
+ };
90
+ output: {
91
+ error: string;
92
+ };
93
+ outputFormat: "json";
94
+ status: 400;
95
+ } | {
96
+ input: {
97
+ json: {
98
+ value: string;
99
+ };
100
+ } & {
101
+ param: {
102
+ key: string;
103
+ };
104
+ };
105
+ output: null;
106
+ outputFormat: "body";
107
+ status: 204;
108
+ };
109
+ };
110
+ } & {
111
+ "/kv/:key": {
112
+ $delete: {
113
+ input: {
114
+ param: {
115
+ key: string;
116
+ };
117
+ };
118
+ output: {
119
+ error: string;
120
+ };
121
+ outputFormat: "json";
122
+ status: 400;
123
+ } | {
124
+ input: {
125
+ param: {
126
+ key: string;
127
+ };
128
+ };
129
+ output: null;
130
+ outputFormat: "body";
131
+ status: 204;
132
+ };
133
+ };
134
+ }, "/storage"> | hono_types0.MergeSchemaPath<{
135
+ "/:id": {
136
+ $post: {
137
+ input: {
138
+ param: {
139
+ id: string;
140
+ };
141
+ };
142
+ output: {
143
+ error: string;
144
+ };
145
+ outputFormat: "json";
146
+ status: 400;
147
+ } | {
148
+ input: {
149
+ param: {
150
+ id: string;
151
+ };
152
+ };
153
+ output: {
154
+ id: string;
155
+ };
156
+ outputFormat: "json";
157
+ status: 200;
158
+ };
159
+ };
160
+ } & {
161
+ "/:id/sendMessages": {
162
+ $post: {
163
+ input: {
164
+ json: {
165
+ messages: Message[];
166
+ behavior: ChatBehavior;
167
+ };
168
+ } & {
169
+ param: {
170
+ id: string;
171
+ };
172
+ };
173
+ output: {
174
+ error: string;
175
+ };
176
+ outputFormat: "json";
177
+ status: 400;
178
+ } | {
179
+ input: {
180
+ json: {
181
+ messages: Message[];
182
+ behavior: ChatBehavior;
183
+ };
184
+ } & {
185
+ param: {
186
+ id: string;
187
+ };
188
+ };
189
+ output: null;
190
+ outputFormat: "body";
191
+ status: 204;
192
+ };
193
+ };
194
+ }, "/chat">, "/">;
195
+ //#endregion
196
+ export { APIBindings, api as default };
@@ -0,0 +1,196 @@
1
+ import * as hono_types0 from "hono/types";
2
+ import * as hono_hono_base0 from "hono/hono-base";
3
+ import { UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
4
+
5
+ //#region src/api/chat.d.ts
6
+ interface Chat {
7
+ readonly id: string;
8
+ }
9
+ type ChatBehavior = "enqueue" | "interrupt" | "append";
10
+ interface Message<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes, TOOLS extends UITools = UITools> {
11
+ readonly role: UIMessage["role"];
12
+ readonly parts: UIMessagePart<DATA_TYPES, TOOLS>[];
13
+ readonly metadata?: METADATA;
14
+ }
15
+ //#endregion
16
+ //#region src/http/api.d.ts
17
+ /**
18
+ * APIBindings are functions that will be invoked by the agent.
19
+ */
20
+ type APIBindings = {
21
+ storage: {
22
+ kv: {
23
+ get: (key: string) => Promise<string | undefined>;
24
+ set: (key: string, value: string) => Promise<void>;
25
+ del: (key: string) => Promise<void>;
26
+ };
27
+ };
28
+ chat: {
29
+ upsert: (id: string) => Promise<Chat>;
30
+ sendMessages: (id: string, options: {
31
+ messages: Message[];
32
+ behavior: ChatBehavior;
33
+ }) => Promise<void>;
34
+ };
35
+ };
36
+ /**
37
+ * To implement your own API bindings, you can use Hono's
38
+ * `createServerAdapter` to create a server that will
39
+ * handle requests to the API.
40
+ *
41
+ * ```ts
42
+ * const server = createHTTPServer(
43
+ * createServerAdapter((req) => {
44
+ * return api.fetch(req, <your-bindings>);
45
+ * })
46
+ * );
47
+ * server.listen(options.port);
48
+ * ```
49
+ */
50
+ declare const api: hono_hono_base0.HonoBase<{
51
+ Bindings: APIBindings;
52
+ }, hono_types0.BlankSchema | hono_types0.MergeSchemaPath<{
53
+ "/kv/:key": {
54
+ $get: {
55
+ input: {
56
+ param: {
57
+ key: string;
58
+ };
59
+ };
60
+ output: {
61
+ error: string;
62
+ };
63
+ outputFormat: "json";
64
+ status: 400;
65
+ } | {
66
+ input: {
67
+ param: {
68
+ key: string;
69
+ };
70
+ };
71
+ output: {
72
+ value: string | undefined;
73
+ };
74
+ outputFormat: "json";
75
+ status: 200;
76
+ };
77
+ };
78
+ } & {
79
+ "/kv/:key": {
80
+ $post: {
81
+ input: {
82
+ json: {
83
+ value: string;
84
+ };
85
+ } & {
86
+ param: {
87
+ key: string;
88
+ };
89
+ };
90
+ output: {
91
+ error: string;
92
+ };
93
+ outputFormat: "json";
94
+ status: 400;
95
+ } | {
96
+ input: {
97
+ json: {
98
+ value: string;
99
+ };
100
+ } & {
101
+ param: {
102
+ key: string;
103
+ };
104
+ };
105
+ output: null;
106
+ outputFormat: "body";
107
+ status: 204;
108
+ };
109
+ };
110
+ } & {
111
+ "/kv/:key": {
112
+ $delete: {
113
+ input: {
114
+ param: {
115
+ key: string;
116
+ };
117
+ };
118
+ output: {
119
+ error: string;
120
+ };
121
+ outputFormat: "json";
122
+ status: 400;
123
+ } | {
124
+ input: {
125
+ param: {
126
+ key: string;
127
+ };
128
+ };
129
+ output: null;
130
+ outputFormat: "body";
131
+ status: 204;
132
+ };
133
+ };
134
+ }, "/storage"> | hono_types0.MergeSchemaPath<{
135
+ "/:id": {
136
+ $post: {
137
+ input: {
138
+ param: {
139
+ id: string;
140
+ };
141
+ };
142
+ output: {
143
+ error: string;
144
+ };
145
+ outputFormat: "json";
146
+ status: 400;
147
+ } | {
148
+ input: {
149
+ param: {
150
+ id: string;
151
+ };
152
+ };
153
+ output: {
154
+ id: string;
155
+ };
156
+ outputFormat: "json";
157
+ status: 200;
158
+ };
159
+ };
160
+ } & {
161
+ "/:id/sendMessages": {
162
+ $post: {
163
+ input: {
164
+ json: {
165
+ messages: Message[];
166
+ behavior: ChatBehavior;
167
+ };
168
+ } & {
169
+ param: {
170
+ id: string;
171
+ };
172
+ };
173
+ output: {
174
+ error: string;
175
+ };
176
+ outputFormat: "json";
177
+ status: 400;
178
+ } | {
179
+ input: {
180
+ json: {
181
+ messages: Message[];
182
+ behavior: ChatBehavior;
183
+ };
184
+ } & {
185
+ param: {
186
+ id: string;
187
+ };
188
+ };
189
+ output: null;
190
+ outputFormat: "body";
191
+ status: 204;
192
+ };
193
+ };
194
+ }, "/chat">, "/">;
195
+ //#endregion
196
+ export { APIBindings, api as default };
@@ -0,0 +1 @@
1
+ var e=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof C?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},o=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),v=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},y=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,x)):e,b=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return y(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=y(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=y(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},ee=b,te=(e,t)=>b(e,t,!0),x=decodeURIComponent,S=e=>p(e,x),C=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?S(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?S(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return ee(this.url,e)}queries(e){return te(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await n(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ne={Stringify:1,BeforeStream:2,Stream:3},re=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},w=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>w(e,t,!1,r,i))).then(()=>i[0]));return n?re(await o,a):o},ie=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),E=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new C(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,T(ie,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?w(e,ne.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},D=`ALL`,O=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],k=`Can not add a route since the matcher is already built.`,A=class extends Error{},oe=`__COMPOSED_HANDLER`,se=e=>e.text(`404 Not Found`,404),j=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},M=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...ae,O];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(D,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new M({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=se;errorHandler=j;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===j?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[oe]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(D,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new E(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},N=`[^/]+`,P=`.*`,F=`(?:|/.*)`,I=Symbol(),ce=new Set(`.\\+*[^]$()`);function le(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===P||e===F?1:t===P||t===F?-1:e===N?1:t===N?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var L=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw I;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,P]:[``,``,N]:a===`/*`?[``,``,F]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||N;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw I;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==P&&e!==F))throw I;if(i)return;c=this.#children[t]=new L,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==P&&e!==F))throw I;if(i)return;c=this.#children[a]=new L}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(le),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ce.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ue=class{#context={varIndex:0};#root=new L;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},R=[],de=[/^$/,[],Object.create(null)],z=Object.create(null);function B(e){return z[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function V(){z=Object.create(null)}function H(e){let t=new ue,n=[];if(e.length===0)return de;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),R]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===I?new A(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(B(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[D]:Object.create(null)},this.#routes={[D]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(k);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[D]).forEach(n=>{t[e][n]=[...t[D][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=B(t);e===D?Object.keys(r).forEach(e=>{r[e][t]||=U(r[e],t)||U(r[D],t)||[]}):r[e][t]||=U(r[e],t)||U(r[D],t)||[],Object.keys(r).forEach(t=>{(e===D||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===D||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=v(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===D||e===o)&&(i[o][c]||=[...U(r[o],c)||U(r[D],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){V();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[D],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],R];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===D;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==D&&t.push(...Object.keys(r[D]).map(e=>[e,r[D][e]])):(n||=!0,t.push(...i))}),n?H(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(k);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof A)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new G,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[D],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=s(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(e,t,n){let r=v(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},K=class extends M{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=/^[\w!#$%&'*.^`|~+-]+$/,ge=/^[ !#-:<-[\]-~]*$/,q=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!he.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),ge.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,x),t))break}return r},_e=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=q(r,e);return i[e]}if(!r)return{};let i=q(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ve=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},ye=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,be=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,xe=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!ye.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(be.test(a)||xe.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await ve(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=_e(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new K,Se=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Ce=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),we=new K().route(`/storage`,Se).route(`/chat`,Ce);var Te=we;export{Te as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "0.1.55",
3
+ "version": "0.1.57",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,6 +22,11 @@
22
22
  "import": "./dist/http/index.js",
23
23
  "require": "./dist/http/index.cjs"
24
24
  },
25
+ "./http/api": {
26
+ "types": "./dist/http/api.d.ts",
27
+ "import": "./dist/http/api.js",
28
+ "require": "./dist/http/api.cjs"
29
+ },
25
30
  "./build": {
26
31
  "types": "./dist/build/index.d.ts",
27
32
  "import": "./dist/build/index.js",