@iflow-ai/iflow-cli 0.3.1 → 0.3.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/iflow.js CHANGED
@@ -737,7 +737,7 @@ Location: {{filePath}}
737
737
  \u672A\u6307\u5B9A\u641C\u7D22\u8DEF\u5F84\u6216\u5305\u542B\u6A21\u5F0F\u3002\u65E0\u5185\u5BB9\u53EF\u8BFB\u53D6\u6216\u8FDE\u63A5\u3002`,invalidParameters:"\u9519\u8BEF\uFF1A{{toolName}} \u7684\u53C2\u6570\u65E0\u6548\u3002\u539F\u56E0\uFF1A{{reason}}",parameterError:`## \u53C2\u6570\u9519\u8BEF
738
738
 
739
739
  {{error}}`,searchError:"\u6587\u4EF6\u641C\u7D22\u65F6\u51FA\u9519\uFF1A{{error}}",searchErrorInfo:"## \u6587\u4EF6\u641C\u7D22\u9519\u8BEF\n\n\u641C\u7D22\u6587\u4EF6\u65F6\u53D1\u751F\u9519\u8BEF\uFF1A\n```\n{{error}}\n```"},messages:{resultHeader:"ReadManyFiles \u7ED3\u679C\uFF08\u76EE\u6807\u76EE\u5F55\uFF1A`{{targetDir}}`\uFF09",filesReadSuccess:"\u6210\u529F\u8BFB\u53D6\u5E76\u8FDE\u63A5\u4E86 **{{count}} \u4E2A\u6587\u4EF6** \u7684\u5185\u5BB9\u3002",processedFiles:"\u5DF2\u5904\u7406\u7684\u6587\u4EF6\uFF1A",processedFilesLimited:"\u5DF2\u5904\u7406\u7684\u6587\u4EF6\uFF08\u663E\u793A\u524D 10 \u4E2A\uFF09\uFF1A",andMore:"\u2026\u8FD8\u6709 {{count}} \u4E2A\u3002",noFilesRead:"\u6839\u636E\u6761\u4EF6\u672A\u8BFB\u53D6\u548C\u8FDE\u63A5\u4EFB\u4F55\u6587\u4EF6\u3002",skippedItems:"\u5DF2\u8DF3\u8FC7 {{count}} \u4E2A\u9879\u76EE\uFF1A",skippedItemsLimited:"\u5DF2\u8DF3\u8FC7 {{count}} \u4E2A\u9879\u76EE\uFF08\u663E\u793A\u524D 5 \u4E2A\uFF09\uFF1A",noMatchingFiles:"\u672A\u627E\u5230\u7B26\u5408\u6761\u4EF6\u7684\u6587\u4EF6\u6216\u5168\u90E8\u88AB\u8DF3\u8FC7\u3002",usingPatterns:"\u4F7F\u7528\u6A21\u5F0F\uFF1A{{patterns}}\uFF08\u76EE\u6807\u76EE\u5F55\uFF1A{{targetDir}}\uFF09",willAttemptToRead:'\u5C06\u5C1D\u8BD5\u8BFB\u53D6\u5E76\u8FDE\u63A5\u6587\u4EF6 {{pathDesc}}\u3002{{excludeDesc}}\u3002\u6587\u4EF6\u7F16\u7801\uFF1A{{encoding}}\u3002\u5206\u9694\u7B26\uFF1A"{{separator}}"\u3002',excluding:"\u6392\u9664\uFF1A{{patterns}}",patternsLike:"\u7C7B\u4F3C {{patterns}} \u7684\u6A21\u5F0F",noneSpecified:"\u672A\u6307\u5B9A",includesFromGeminiIgnore:"\u5305\u542B\u6765\u81EA .geminiignore \u7684 {{count}} \u4E2A"}},exitPlanModeTool:{errors:{planRequired:'\u53C2\u6570"plan"\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002',validationError:"\u9A8C\u8BC1\u9519\u8BEF\uFF1A{{error}}",executionError:"\u6267\u884C\u9519\u8BEF\uFF1A{{error}}"},messages:{readyToCode:"\u51C6\u5907\u5F00\u59CB\u7F16\u5199\u4EE3\u7801\uFF0C\u8BA1\u5212\uFF1A{{plan}}",exitPlanMode:"\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F"}},mcpTool:{messages:{confirmExecution:"\u786E\u8BA4 MCP \u5DE5\u5177\u6267\u884C",mediaDataProvided:"[\u5DE5\u5177 '{{toolName}}' \u63D0\u4F9B\u4E86\u4EE5\u4E0B {{type}} \u6570\u636E\uFF0CMIME \u7C7B\u578B\uFF1A{{mimeType}}]",embeddedResourceProvided:"[\u5DE5\u5177 '{{toolName}}' \u63D0\u4F9B\u4E86\u4EE5\u4E0B\u5D4C\u5165\u5F0F\u8D44\u6E90\uFF0CMIME \u7C7B\u578B\uFF1A{{mimeType}}]",resourceLink:"\u8D44\u6E90\u94FE\u63A5\uFF1A{{title}} \u4F4D\u4E8E {{uri}}"},errors:{toolReportedError:"\u9519\u8BEF\uFF1AMCP \u5DE5\u5177 '{{toolName}}' \u62A5\u544A\u4E86\u4E00\u4E2A\u9519\u8BEF\u3002",parseResponseFailed:"[\u9519\u8BEF\uFF1A\u65E0\u6CD5\u89E3\u6790\u5DE5\u5177\u54CD\u5E94]"},display:{image:"[\u56FE\u7247\uFF1A{{mimeType}}]",audio:"[\u97F3\u9891\uFF1A{{mimeType}}]",resourceLink:"[\u94FE\u63A5\u5230 {{title}}\uFF1A{{uri}}]",embeddedResource:"[\u5D4C\u5165\u5F0F\u8D44\u6E90\uFF1A{{mimeType}}]",unknownType:"\u672A\u77E5\u7C7B\u578B",unknownContentType:"[\u672A\u77E5\u5185\u5BB9\u7C7B\u578B\uFF1A{{type}}]"}},mcpClient:{errors:{clientNotConnected:"\u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\u3002",noPromptsOrTools:"\u670D\u52A1\u5668\u4E0A\u672A\u627E\u5230\u63D0\u793A\u6216\u5DE5\u5177\u3002",failedToParseCommand:"\u65E0\u6CD5\u89E3\u6790 mcpServerCommand\uFF1A{{cmd}}",cannotConnect:"\u65E0\u6CD5\u8FDE\u63A5\u5230 '{{serverName}}' - \u670D\u52A1\u5668\u53EF\u80FD\u5DF2\u505C\u6B62\u6216 URL \u4E0D\u6B63\u786E",connectionFailed:"'{{serverName}}' \u8FDE\u63A5\u5931\u8D25\uFF1A{{error}}",checkSandbox:"\u68C0\u67E5\u6C99\u76D2\u53EF\u7528\u6027",noUrlConfigured:"\u672A\u4E3A Google \u51ED\u636E MCP \u670D\u52A1\u5668\u914D\u7F6E URL",httpTransportRequiresUrl:"HTTP \u4F20\u8F93\u9700\u8981 'httpUrl' \u6216 'url' \u5B57\u6BB5",stdioTransportRequiresCommand:"Stdio \u4F20\u8F93\u9700\u8981 'command' \u5B57\u6BB5",invalidConfiguration:"\u65E0\u6548\u914D\u7F6E\uFF1A\u7F3A\u5C11 httpUrl\uFF08\u7528\u4E8E Streamable HTTP\uFF09\u3001url\uFF08\u7528\u4E8E SSE\uFF09\u548C command\uFF08\u7528\u4E8E stdio\uFF09\u3002"}},ripgrepTool:{errors:{pathValidationFailed:"\u8DEF\u5F84\u9A8C\u8BC1\u5931\u8D25\uFF1A\u5C1D\u8BD5\u8BBF\u95EE\u7684\u8DEF\u5F84\u201C{{path}}\u201D\u5728\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E4B\u5916\uFF1A{{directories}}",pathNotDirectory:"\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55\uFF1A{{path}}",pathNotExist:"\u8DEF\u5F84\u4E0D\u5B58\u5728\uFF1A{{path}}",pathAccessFailed:"\u65E0\u6CD5\u8BBF\u95EE {{path}} \u7684\u8DEF\u5F84\u72B6\u6001\uFF1A{{error}}",searchFailed:"ripgrep \u641C\u7D22\u64CD\u4F5C\u65F6\u51FA\u9519\uFF1A{{error}}",searchFailedShort:"\u9519\u8BEF\uFF1A{{error}}",failedToStart:"\u65E0\u6CD5\u542F\u52A8 ripgrep\uFF1A{{error}}",ripgrepExited:"ripgrep \u4EE5\u9519\u8BEF\u4EE3\u7801 {{code}} \u9000\u51FA\uFF1A{{stderr}}"},messages:{noMatchesFound:"\u672A\u627E\u5230\u4E0E\u6A21\u5F0F\u201C{{pattern}}\u201D\u5339\u914D\u7684\u7ED3\u679C {{location}}{{filter}}\u3002",noMatchesFoundShort:"\u672A\u627E\u5230\u5339\u914D\u7ED3\u679C",matchesFound:"\u627E\u5230 {{count}} \u4E2A\u4E0E\u6A21\u5F0F\u201C{{pattern}}\u201D\u5339\u914D\u7684{{matchType}} {{location}}{{filter}}",foundMatches:"\u627E\u5230 {{count}} \u4E2A{{matchType}}",match:"\u5339\u914D",matches:"\u5339\u914D",filter:"\u8FC7\u6EE4\u5668",resultsLimited:"\u7ED3\u679C\u9650\u5236\u4E3A {{maxMatches}} \u4E2A\u5339\u914D\u9879\u4EE5\u63D0\u9AD8\u6027\u80FD",limited:"\u9650\u5236"}},taskTool:{messages:{taskAborted:"\u4EFB\u52A1\u5DF2\u4E2D\u6B62",taskAbortedByUser:"\u4EFB\u52A1\u88AB\u7528\u6237\u4E2D\u6B62\u3002",taskExecutionCancelled:"\u4EFB\u52A1\u6267\u884C\u5DF2\u53D6\u6D88\u3002",completedTask:"\u5DF2\u5B8C\u6210\u4EFB\u52A1\uFF1A{{description}}"}},toolRegistry:{warnings:{toolAlreadyRegistered:"\u540D\u4E3A\u201C{{toolName}}\u201D\u7684\u5DE5\u5177\u5DF2\u6CE8\u518C\u3002\u6B63\u5728\u8986\u76D6\u3002",toolWithNoName:"\u53D1\u73B0\u4E00\u4E2A\u6CA1\u6709\u540D\u79F0\u7684\u5DE5\u5177\u3002\u8DF3\u8FC7\u3002"},errors:{emptyDiscoveryCommand:"\u5DE5\u5177\u53D1\u73B0\u547D\u4EE4\u4E3A\u7A7A\u6216\u4EC5\u5305\u542B\u7A7A\u767D\u5B57\u7B26\u3002",outputSizeLimitExceeded:"\u5DE5\u5177\u53D1\u73B0\u547D\u4EE4\u8F93\u51FA\u8D85\u8FC7\u4E86 {{maxSize}} \u5B57\u8282\u7684\u5927\u5C0F\u9650\u5236\u3002",commandFailedWithCode:"\u547D\u4EE4\u4EE5\u9519\u8BEF\u4EE3\u7801 {{code}} \u5931\u8D25",discoveryCommandFailed:"\u5DE5\u5177\u53D1\u73B0\u547D\u4EE4\u4EE5\u9000\u51FA\u4EE3\u7801 {{code}} \u5931\u8D25",invalidDiscoveryOutput:"\u5DE5\u5177\u53D1\u73B0\u547D\u4EE4\u672A\u8FD4\u56DE JSON \u5DE5\u5177\u6570\u7EC4\u3002",discoveryCommandError:"\u5DE5\u5177\u53D1\u73B0\u547D\u4EE4\u201C{{cmd}}\u201D\u5931\u8D25\uFF1A"}},websocketClient:{errors:{transportClosed:"\u4F20\u8F93\u5DF2\u5173\u95ED",unauthorizedOAuth:"\u672A\u6388\u6743\uFF1A\u9700\u8981 OAuth",noAuthProvider:"\u672A\u914D\u7F6E\u8EAB\u4EFD\u9A8C\u8BC1\u63D0\u4F9B\u7A0B\u5E8F",clientInfoNotAvailable:"\u5BA2\u6237\u7AEF\u4FE1\u606F\u4E0D\u53EF\u7528",transportNotStarted:"\u4F20\u8F93\u672A\u542F\u52A8",websocketNotOpen:"WebSocket \u672A\u6253\u5F00"}},xinliuWebFetch:{errors:{noUrlFoundFallback:"\u9519\u8BEF\uFF1A\u5728\u5907\u7528\u65B9\u6848\u7684\u63D0\u793A\u4E2D\u672A\u627E\u5230 URL\u3002",noUrlFound:"\u9519\u8BEF\uFF1A\u5728\u63D0\u793A\u4E2D\u672A\u627E\u5230 URL\u3002",promptEmpty:"\u201Cprompt\u201D\u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u5FC5\u987B\u5305\u542B URL \u548C\u6307\u4EE4\u3002",noValidUrl:"\u201Cprompt\u201D\u5FC5\u987B\u5305\u542B\u81F3\u5C11\u4E00\u4E2A\u6709\u6548\u7684 URL\uFF08\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09\u3002",invalidParameters:"\u9519\u8BEF\uFF1A\u63D0\u4F9B\u7684\u53C2\u6570\u65E0\u6548\u3002\u539F\u56E0\uFF1A{{reason}}"},messages:{contentProcessedFallback:"{{url}} \u7684\u5185\u5BB9\u5DF2\u4F7F\u7528\u5907\u7528\u83B7\u53D6\u65B9\u5F0F\u5904\u7406\u3002",contentProcessedProxy:"\u5DF2\u901A\u8FC7\u4FE1\u6D41\u4EE3\u7406\u5904\u7406 {{url}} \u7684\u5185\u5BB9\u3002",contentProcessedSuccess:"\u5185\u5BB9\u5904\u7406\u6210\u529F"}},xinliuWebSearch:{errors:{invalidParameters:"\u9519\u8BEF\uFF1A\u63D0\u4F9B\u7684\u53C2\u6570\u65E0\u6548\u3002\u539F\u56E0\uFF1A{{reason}}",authNotSupported:"\u9519\u8BEF\uFF1A\u641C\u7D22\u529F\u80FD\u4EC5\u652F\u6301 iFlow \u767B\u5F55\u3002\u5F53\u524D\u8EAB\u4EFD\u9A8C\u8BC1\u6A21\u5F0F\u4E0D\u652F\u6301\u6B64\u529F\u80FD\u3002",searchFailed:"\u9519\u8BEF\uFF1A{{error}}",searchFailedShort:"\u6267\u884C\u7F51\u7EDC\u641C\u7D22\u65F6\u51FA\u9519\u3002",queryCannotBeEmpty:"'query' \u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A\u3002"},messages:{searchingWeb:'\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\uFF1A"{{query}}"',noResults:'\u672A\u627E\u5230\u67E5\u8BE2 "{{query}}" \u7684\u641C\u7D22\u7ED3\u679C\u6216\u4FE1\u606F',noResultsShort:"\u672A\u627E\u5230\u4FE1\u606F\u3002",searchResults:`"{{query}}" \u7684\u7F51\u7EDC\u641C\u7D22\u7ED3\u679C\uFF1A
740
- {{results}}`,searchResultsReturned:'\u5DF2\u8FD4\u56DE "{{query}}" \u7684\u641C\u7D22\u7ED3\u679C\u3002'}},modifiableTool:{errors:{deleteTempFile:"\u5220\u9664\u4E34\u65F6\u5DEE\u5F02\u6587\u4EF6\u65F6\u51FA\u9519\uFF1A{{path}}"}},openaiContentGenerator:{errors:{failedWriteDebugLog:"\u5199\u5165\u8C03\u8BD5\u65E5\u5FD7\u5931\u8D25\uFF1A",contextLengthExceeded:"\u60A8\u7684\u8F93\u5165\u8D85\u8FC7\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u957F\u5EA6\u3002\u8BF7\u68C0\u67E5 IFLOW.md \u6216\u60A8\u7684\u8F93\u5165\u662F\u5426\u8FC7\u957F\uFF0C\u7136\u540E\u8FD0\u884C /clear \u91CD\u65B0\u63D0\u95EE\u3002",httpError:"HTTP \u9519\u8BEF\uFF01\u72B6\u6001\uFF1A{{status}}\uFF0C\u54CD\u5E94\uFF1A{{body}} TraceID\uFF1A{{traceId}}",responseFormatError:"\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\u3002TraceID\uFF1A{{traceId}}",contentLengthExceed:"\u5185\u5BB9\u957F\u5EA6\u8D85\u51FA\u5927\u8BED\u8A00\u6A21\u578B\u9650\u5236\u3002",apiTokenExpired:"API Token \u5DF2\u8FC7\u671F\u3002API Token \u6709\u6548\u671F\u4E3A 7 \u5929\u3002\u60A8\u53EF\u4EE5\u5728 https://platform.iflow.cn/docs/api-key-management \u91CD\u7F6E\u60A8\u7684 token\u3002",invalidApiKey:"\u63D0\u4F9B\u7684 API \u5BC6\u94A5\u65E0\u6548",rateLimitReached:"\u60A8\u5DF2\u8FBE\u5230\u5E73\u53F0\u901F\u7387\u9650\u5236\uFF0C\u7CFB\u7EDF\u5C06\u91CD\u8BD5\u8BF7\u6C42",userCancel:"\u7528\u6237\u53D6\u6D88",invalidResponseFormat:"OpenAI \u54CD\u5E94\u683C\u5F0F\u65E0\u6548 - \u7F3A\u5C11\u6216\u7A7A\u7684 choices \u6570\u7EC4\u3002TraceID\uFF1A{{traceId}}",apiKeyError:"API \u5BC6\u94A5\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684 API \u5BC6\u94A5\u662F\u5426\u6B63\u786E\u6216\u4F7F\u7528 /auth \u91CD\u65B0\u767B\u5F55",generateDataError:"\u751F\u6210\u6570\u636E\u9519\u8BEF\uFF1A{{error}}",imageDataMissing:"\u56FE\u50CF\u6570\u636E\u7F3A\u5931",imageContentCannotParse:"\u65E0\u6CD5\u89E3\u6790\u56FE\u50CF\u5185\u5BB9\uFF1A{{error}}",embedContentFailed:"\u5D4C\u5165\u5185\u5BB9\u5931\u8D25\uFF1A{{error}}"},messages:{toolNotExecuted:"\u5DE5\u5177\u672A\u6267\u884C"}},extensionsCommand:{noActiveExtensions:"\u6CA1\u6709\u6FC0\u6D3B\u7684\u6269\u5C55\u3002",activeExtensions:"\u6FC0\u6D3B\u7684\u6269\u5C55"},statsCommand:{sessionStartUnavailable:"\u4F1A\u8BDD\u5F00\u59CB\u65F6\u95F4\u4E0D\u53EF\u7528\u3002",subCommands:{model:"\u663E\u793A\u6A21\u578B\u4F7F\u7528\u7EDF\u8BA1",tools:"\u663E\u793A\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1"}},toolsCommand:{couldNotRetrieveRegistry:"\u65E0\u6CD5\u83B7\u53D6\u5DE5\u5177\u6CE8\u518C\u8868\u3002",availableTools:"\u53EF\u7528\u7684 iFlow CLI \u5DE5\u5177\uFF1A",noToolsAvailable:"\u65E0\u53EF\u7528\u5DE5\u5177"},copyCommand:{noOutputInHistory:"\u5386\u53F2\u8BB0\u5F55\u4E2D\u65E0\u8F93\u51FA",lastOutputCopied:"\u4E0A\u6B21\u8F93\u51FA\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F",failedToCopy:"\u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25\u3002",noTextToCopy:"\u6700\u540E\u7684 AI \u8F93\u51FA\u4E0D\u5305\u542B\u53EF\u590D\u5236\u7684\u6587\u672C\u3002"},clearCommand:{clearingTerminalAndResetChat:"\u6B63\u5728\u6E05\u9664\u7EC8\u7AEF\u5E76\u91CD\u7F6E\u5BF9\u8BDD\u3002",clearingTerminal:"\u6B63\u5728\u6E05\u9664\u7EC8\u7AEF\u3002"},memoryCommand:{subCommands:{show:"\u663E\u793A\u5F53\u524D\u5185\u5B58\u5185\u5BB9\u3002",add:"\u5411\u5185\u5B58\u6DFB\u52A0\u5185\u5BB9\u3002",refresh:"\u4ECE\u6E90\u5237\u65B0\u5185\u5B58\u3002"},currentMemoryContent:`\u6765\u81EA {{fileCount}} \u4E2A\u6587\u4EF6\u7684\u5F53\u524D\u5185\u5B58\u5185\u5BB9\uFF1A
740
+ {{results}}`,searchResultsReturned:'\u5DF2\u8FD4\u56DE "{{query}}" \u7684\u641C\u7D22\u7ED3\u679C\u3002'}},modifiableTool:{errors:{deleteTempFile:"\u5220\u9664\u4E34\u65F6\u5DEE\u5F02\u6587\u4EF6\u65F6\u51FA\u9519\uFF1A{{path}}"}},openaiContentGenerator:{errors:{failedWriteDebugLog:"\u5199\u5165\u8C03\u8BD5\u65E5\u5FD7\u5931\u8D25\uFF1A",contextLengthExceeded:"\u60A8\u7684\u8F93\u5165\u8D85\u8FC7\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u957F\u5EA6\u3002\u8BF7\u68C0\u67E5 IFLOW.md \u6216\u60A8\u7684\u8F93\u5165\u662F\u5426\u8FC7\u957F\uFF0C\u7136\u540E\u8FD0\u884C /clear \u91CD\u65B0\u63D0\u95EE\u3002",httpError:"HTTP \u9519\u8BEF\uFF01\u72B6\u6001\uFF1A{{status}}\uFF0C\u54CD\u5E94\uFF1A{{body}} TraceID\uFF1A{{traceId}}",responseFormatError:"\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\u3002TraceID\uFF1A{{traceId}}",contentLengthExceed:"\u5185\u5BB9\u957F\u5EA6\u8D85\u51FA\u5927\u8BED\u8A00\u6A21\u578B\u9650\u5236\u3002",apiTokenExpired:"API Token \u5DF2\u8FC7\u671F\u3002API Token \u6709\u6548\u671F\u4E3A 7 \u5929\u3002\u60A8\u53EF\u4EE5\u5728 https://platform.iflow.cn/docs/api-key-management \u91CD\u7F6E\u60A8\u7684 token\u3002",invalidApiKey:"\u63D0\u4F9B\u7684 API \u5BC6\u94A5\u65E0\u6548",rateLimitReached:"\u60A8\u5DF2\u8FBE\u5230\u5E73\u53F0\u901F\u7387\u9650\u5236\uFF0C\u7CFB\u7EDF\u5C06\u91CD\u8BD5\u8BF7\u6C42",userCancel:"\u7528\u6237\u53D6\u6D88",invalidResponseFormat:"OpenAI \u54CD\u5E94\u683C\u5F0F\u65E0\u6548 - \u7F3A\u5C11\u6216\u7A7A\u7684 choices \u6570\u7EC4\u3002TraceID\uFF1A{{traceId}}",apiKeyError:"API \u5BC6\u94A5\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684 API \u5BC6\u94A5\u662F\u5426\u6B63\u786E\u6216\u4F7F\u7528 /auth \u91CD\u65B0\u767B\u5F55",generateDataError:"\u751F\u6210\u6570\u636E\u9519\u8BEF: {{error}}",imageDataMissing:"\u56FE\u50CF\u6570\u636E\u7F3A\u5931",imageContentCannotParse:"\u65E0\u6CD5\u89E3\u6790\u56FE\u50CF\u5185\u5BB9\uFF1A{{error}}",embedContentFailed:"\u5D4C\u5165\u5185\u5BB9\u5931\u8D25\uFF1A{{error}}"},messages:{toolNotExecuted:"\u5DE5\u5177\u672A\u6267\u884C"}},extensionsCommand:{noActiveExtensions:"\u6CA1\u6709\u6FC0\u6D3B\u7684\u6269\u5C55\u3002",activeExtensions:"\u6FC0\u6D3B\u7684\u6269\u5C55"},statsCommand:{sessionStartUnavailable:"\u4F1A\u8BDD\u5F00\u59CB\u65F6\u95F4\u4E0D\u53EF\u7528\u3002",subCommands:{model:"\u663E\u793A\u6A21\u578B\u4F7F\u7528\u7EDF\u8BA1",tools:"\u663E\u793A\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1"}},toolsCommand:{couldNotRetrieveRegistry:"\u65E0\u6CD5\u83B7\u53D6\u5DE5\u5177\u6CE8\u518C\u8868\u3002",availableTools:"\u53EF\u7528\u7684 iFlow CLI \u5DE5\u5177\uFF1A",noToolsAvailable:"\u65E0\u53EF\u7528\u5DE5\u5177"},copyCommand:{noOutputInHistory:"\u5386\u53F2\u8BB0\u5F55\u4E2D\u65E0\u8F93\u51FA",lastOutputCopied:"\u4E0A\u6B21\u8F93\u51FA\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F",failedToCopy:"\u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25\u3002",noTextToCopy:"\u6700\u540E\u7684 AI \u8F93\u51FA\u4E0D\u5305\u542B\u53EF\u590D\u5236\u7684\u6587\u672C\u3002"},clearCommand:{clearingTerminalAndResetChat:"\u6B63\u5728\u6E05\u9664\u7EC8\u7AEF\u5E76\u91CD\u7F6E\u5BF9\u8BDD\u3002",clearingTerminal:"\u6B63\u5728\u6E05\u9664\u7EC8\u7AEF\u3002"},memoryCommand:{subCommands:{show:"\u663E\u793A\u5F53\u524D\u5185\u5B58\u5185\u5BB9\u3002",add:"\u5411\u5185\u5B58\u6DFB\u52A0\u5185\u5BB9\u3002",refresh:"\u4ECE\u6E90\u5237\u65B0\u5185\u5B58\u3002"},currentMemoryContent:`\u6765\u81EA {{fileCount}} \u4E2A\u6587\u4EF6\u7684\u5F53\u524D\u5185\u5B58\u5185\u5BB9\uFF1A
741
741
 
742
742
  ---
743
743
  {{memoryContent}}
@@ -834,19 +834,19 @@ ${e}
834
834
  ${"=".repeat(80)}
835
835
  `;await tMt.appendFile(this.logFilePath,i,"utf-8")}catch(r){console.debug(k.t("openaiContentGenerator.errors.failedWriteDebugLog"),r)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);Vg(new Error(`${e}: ${n}`))}async generateContent(e){let r=nS.api;r.start("OpenAI-GenerateContent-Total");try{if((this.authType===$t.LOGIN_WITH_IFLOW||this.authType===$t.IFLOW)&&await OF()){this.authType===$t.LOGIN_WITH_IFLOW&&await phe();let{getCachedApiKey:g}=await Promise.resolve().then(()=>(_w(),cLe)),A=await g();A&&(this.apiKey=A)}let n=await this.convertToOpenAIMessages(e),i=Skt(n);if(this.config){let m=this.config.getConversationId();if(m)try{await EFe(this.config,m,{model:this.modelName,tool:i})}catch(g){this.logTelemetryFailure("Telemetry initialization failed",g)}}let o=this.convertToOpenAITools(e.config?.tools),s={model:this.modelName,messages:n};e.config?.temperature!==void 0&&(s.temperature=e.config.temperature);let a=this.config?.getContentGeneratorConfig?.();a?.thinking&&a.thinking.maxTokens>0?(C0e.configureThinkingRequest(this.modelName,s,a.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),a.thinking=null):C0e.configureNonThinkingRequest(this.modelName,s);let c=await this.calculateInputTokens(e),u=xFe(this.modelName,c);if(u<0)throw new Error(k.t("openaiContentGenerator.errors.contextLengthExceeded"));s.max_new_tokens=u,e.config?.topP!==void 0&&(s.top_p=e.config.topP),e.config?.stopSequences&&e.config.stopSequences.length>0&&(s.stop=e.config.stopSequences),o&&o.length>0&&(s.tools=o),await this.logToPromptFile(`INPUT REQUEST:
836
836
  ${JSON.stringify(s,null,2)}`);let d=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,f=await fetch(`${d}/chat/completions`,{signal:e.config?.abortSignal,method:"POST",headers:CFe({"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"user-agent":"iFlow-Cli","session-id":this.config?.getSessionId()||"","conversation-id":this.config?.getConversationId()||""}),body:JSON.stringify(s)});if(!f.ok){let m=await f.text();if(this.config)try{await u0e(this.config,new Error(m))}catch(g){this.logTelemetryFailure("Telemetry error recording failed",g)}throw new Error(k.t("openaiContentGenerator.errors.httpError",{status:f.status,body:m,traceId:f.headers.get("eagleeye-traceid")}))}let p;try{p=await f.json()}catch(m){throw Vg(m),new Error(k.t("openaiContentGenerator.errors.responseFormatError",{traceId:f.headers.get("eagleeye-traceid")}))}if(p.error_code&&(p.error_code===511||p.error_code===413))throw new Error(k.t("openaiContentGenerator.errors.contentLengthExceed"));if(p.error_code&&p.error_code===439)throw new Error(k.t("openaiContentGenerator.errors.apiTokenExpired"));if(p.msg&&(p.msg.includes("invalid apiKey")||p.msg.includes("Invalid apiKey")))throw new Error(k.t("openaiContentGenerator.errors.invalidApiKey"));if(p.status==="434"||p.status===434)throw new Error(k.t("openaiContentGenerator.errors.invalidApiKey"));if(p.status==="429"||p.error_code&&p.error_code===429)throw new Error(k.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(k.t("openaiContentGenerator.errors.userCancel"));if(!p||!p.choices||!Array.isArray(p.choices)||p.choices.length===0){let m=f.headers.get("eagleeye-traceid");throw new Error(k.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:m}))}await this.logToPromptFile(`API RESPONSE:
837
- ${JSON.stringify(p,null,2)}`),p.usage&&(this.lastUsageMetadata={total_tokens:p.usage.total_tokens,prompt_tokens:p.usage.prompt_tokens,completion_tokens:p.usage.completion_tokens});let h=await this.convertFromOpenAIResponse(p);if(this.config)try{await YK(this.config)}catch(m){this.logTelemetryFailure("Telemetry cleanup failed",m)}return h}catch(n){if(Vg(n),this.config&&!(n instanceof Error&&n.message==="user cancel"))try{await u0e(this.config,n instanceof Error?n:new Error(String(n)))}catch(i){this.logTelemetryFailure("Telemetry error recording failed",i)}throw n instanceof Error&&n.cause?.name?.includes("InvalidArgumentError")?new Error(k.t("openaiContentGenerator.errors.apiKeyError")):n instanceof Error&&n.message&&(n.message.includes("iFlow Login expired")||n.message.includes("Your API Token has expired")||n.message.includes("reached the platform rate limit")||n.message.includes("Your input has exceeded"))?new Error(n.message):new Error(k.t("openaiContentGenerator.errors.generateDataError",{error:n instanceof Error?n.message:String(n)}))}finally{r.end("OpenAI-GenerateContent-Total")}}async generateContentStream(e){let r=await this.generateContent(e);async function*n(){yield r}return n()}async countTokens(e,r=!1){let n=e.useCache??!0;if(!r&&this.lastUsageMetadata?.total_tokens)return{totalTokens:this.lastUsageMetadata.total_tokens};let i=this.extractTextFromRequest(e);return{totalTokens:Math.ceil(i.length/4)}}async calculateInputTokens(e){try{let r={model:this.modelName,contents:e.contents,config:{systemInstruction:e.config?.systemInstruction}};return(await this.countTokens(r)).totalTokens||0}catch{let n=this.extractTextFromRequest({model:this.modelName,contents:e.contents});return Math.ceil(n.length/4)}}async embedContent(e){try{let r=this.extractTextFromEmbedRequest(e),n=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,i=await fetch(`${n}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.modelName,input:r})});if(!i.ok){let s=await i.text();throw new Error(`HTTP error! status: ${i.status}, body: ${s}`)}return{embeddings:[{values:(await i.json()).data[0].embedding}]}}catch(r){throw Vg(r),new Error(k.t("openaiContentGenerator.errors.embedContentFailed",{error:r instanceof Error?r.message:String(r)}))}}async convertToOpenAIMessages(e){let r=[],n=new Set,i=new Map;if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o)if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];for(let c of a){if(c.functionCall){let u=c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;n.add(u)}if(c.functionResponse){let u=c.functionResponse.id||c.functionResponse.name||"",d=c.functionResponse.response?.output??(c.functionResponse.response?JSON.stringify(c.functionResponse.response):"");i.set(u,{role:"tool",tool_call_id:u,content:d})}}}for(let[s]of i)n.has(s)||i.delete(s)}if(e.config?.systemInstruction){let o=this.extractSystemInstruction(e.config.systemInstruction);o&&r.push({role:"system",content:o})}if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o){if(typeof s=="string"){r.push({role:"user",content:s});continue}if(typeof s=="object"&&s!==null&&"text"in s&&s.text){r.push({role:"user",content:s.text});continue}if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];if(s.role==="model"){let c={role:"assistant",content:"",tool_calls:[]};for(let u of a)if("text"in u&&u.text&&(c.content=u.text),u.functionCall){let d=u.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;c.tool_calls.push({id:d,function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})},type:"function"})}if((c.content||c.tool_calls.length>0)&&(c.tool_calls.length===0&&delete c.tool_calls,r.push(c),c.tool_calls&&c.tool_calls.length>0))for(let u of c.tool_calls){let d=i.get(u.id);d?r.push(d):r.push({role:"tool",tool_call_id:u.id,content:k.t("openaiContentGenerator.messages.toolNotExecuted")})}}else{let c=[];for(let u of a)if("text"in u&&u.text)c.push({type:"text",text:u.text});else if(u.inlineData){let d=u.inlineData;if(d.mimeType&&d.mimeType.startsWith("image/"))if(!(this.authType===$t.IFLOW||this.authType===$t.LOGIN_WITH_IFLOW||this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn"))&&rS.isMultimodalModel(this.modelName))r.push({role:"user",content:[{type:"image_url",image_url:{url:"data:"+d.mimeType+";base64,"+d.data}}]});else try{if(!d.data)throw new Error(k.t("openaiContentGenerator.errors.imageDataMissing"));let p=await this.multimodalHelper.generateImageDescription(d.data,d.mimeType);c.push({type:"text",text:`[Image Description]: ${p}`})}catch(p){Vg(p),c.push({type:"text",text:k.t("openaiContentGenerator.errors.imageContentCannotParse",{error:p instanceof Error?p.message:String(p)})})}}c.length>0&&r.push({role:"user",content:c})}}}}return r}createGeminiResponse(){let e=new t4;return e.candidates=[{content:{parts:[],role:"model"}}],e}async convertFromOpenAIResponse(e){let r=e.choices[0],n=this.createGeminiResponse(),i=n.candidates?.[0];if(r.message.reasoning_content&&i?.content?.parts&&i.content.parts.push({thought:!0,text:r.message.reasoning_content}),r.message.content&&r.message.content.trim()&&i?.content?.parts&&i.content.parts.push({text:r.message.content}),r.message.tool_calls)for(let o of r.message.tool_calls){let s;try{s=JSON.parse(o.function.arguments)}catch(a){if(Vg(a),this.baseUrl==="https://apis.iflow.cn/v1")try{s=await this.fixInvalidJsonWithQwen(o.function.arguments)}catch(c){Vg(c),console.error("Failed to fix JSON",c),s={}}else s={}}i?.content?.parts?.push({functionCall:{id:o.id,name:o.function.name,args:s}})}return i&&r.finish_reason!=="tool_calls"&&r.finish_reason&&(i.finishReason=this.mapFinishReason(r.finish_reason)),n.usageMetadata={promptTokenCount:e.usage?.prompt_tokens||0,candidatesTokenCount:e.usage?.completion_tokens||0,totalTokenCount:e.usage?.total_tokens||0},n}async fixInvalidJsonWithQwen(e){let r=`
837
+ ${JSON.stringify(p,null,2)}`),p.usage&&(this.lastUsageMetadata={total_tokens:p.usage.total_tokens,prompt_tokens:p.usage.prompt_tokens,completion_tokens:p.usage.completion_tokens});let h=await this.convertFromOpenAIResponse(p);if(this.config)try{await YK(this.config)}catch(m){this.logTelemetryFailure("Telemetry cleanup failed",m)}return h}catch(n){if(Vg(n),this.config&&!(n instanceof Error&&n.message==="user cancel")&&await u0e(this.config,n instanceof Error?n:new Error(String(n))),n instanceof Error&&n.cause?.name?.includes("InvalidArgumentError"))throw new Error(k.t("openaiContentGenerator.errors.apiKeyError"));if(n instanceof Error&&n.message&&(n.message.includes("iFlow Login expired")||n.message.includes("Your API Token has expired")||n.message.includes("reached the platform rate limit")||n.message.includes("Your input has exceeded")))throw new Error(n.message);let i="";throw n instanceof Error?i=n.cause?`${n.message}:${n.cause.message}`:n.message:i=String(n),new Error(k.t("openaiContentGenerator.errors.generateDataError",{error:i}),{cause:n})}finally{r.end("OpenAI-GenerateContent-Total")}}async generateContentStream(e){let r=await this.generateContent(e);async function*n(){yield r}return n()}async countTokens(e,r=!1){let n=e.useCache??!0;if(!r&&this.lastUsageMetadata?.total_tokens)return{totalTokens:this.lastUsageMetadata.total_tokens};let i=this.extractTextFromRequest(e);return{totalTokens:Math.ceil(i.length/4)}}async calculateInputTokens(e){try{let r={model:this.modelName,contents:e.contents,config:{systemInstruction:e.config?.systemInstruction}};return(await this.countTokens(r)).totalTokens||0}catch{let n=this.extractTextFromRequest({model:this.modelName,contents:e.contents});return Math.ceil(n.length/4)}}async embedContent(e){try{let r=this.extractTextFromEmbedRequest(e),n=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,i=await fetch(`${n}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.modelName,input:r})});if(!i.ok){let s=await i.text();throw new Error(`HTTP error! status: ${i.status}, body: ${s}`)}return{embeddings:[{values:(await i.json()).data[0].embedding}]}}catch(r){throw Vg(r),new Error(k.t("openaiContentGenerator.errors.embedContentFailed",{error:r instanceof Error?r.message:String(r)}))}}async convertToOpenAIMessages(e){let r=[],n=new Set,i=new Map;if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o)if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];for(let c of a){if(c.functionCall){let u=c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;n.add(u)}if(c.functionResponse){let u=c.functionResponse.id||c.functionResponse.name||"",d=c.functionResponse.response?.output??(c.functionResponse.response?JSON.stringify(c.functionResponse.response):"");i.set(u,{role:"tool",tool_call_id:u,content:d})}}}for(let[s]of i)n.has(s)||i.delete(s)}if(e.config?.systemInstruction){let o=this.extractSystemInstruction(e.config.systemInstruction);o&&r.push({role:"system",content:o})}if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o){if(typeof s=="string"){r.push({role:"user",content:s});continue}if(typeof s=="object"&&s!==null&&"text"in s&&s.text){r.push({role:"user",content:s.text});continue}if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];if(s.role==="model"){let c={role:"assistant",content:"",tool_calls:[]};for(let u of a)if("text"in u&&u.text&&(c.content=u.text),u.functionCall){let d=u.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;c.tool_calls.push({id:d,function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})},type:"function"})}if((c.content||c.tool_calls.length>0)&&(c.tool_calls.length===0&&delete c.tool_calls,r.push(c),c.tool_calls&&c.tool_calls.length>0))for(let u of c.tool_calls){let d=i.get(u.id);d?r.push(d):r.push({role:"tool",tool_call_id:u.id,content:k.t("openaiContentGenerator.messages.toolNotExecuted")})}}else{let c=[];for(let u of a)if("text"in u&&u.text)c.push({type:"text",text:u.text});else if(u.inlineData){let d=u.inlineData;if(d.mimeType&&d.mimeType.startsWith("image/"))if(!(this.authType===$t.IFLOW||this.authType===$t.LOGIN_WITH_IFLOW||this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn"))&&rS.isMultimodalModel(this.modelName))r.push({role:"user",content:[{type:"image_url",image_url:{url:"data:"+d.mimeType+";base64,"+d.data}}]});else try{if(!d.data)throw new Error(k.t("openaiContentGenerator.errors.imageDataMissing"));let p=await this.multimodalHelper.generateImageDescription(d.data,d.mimeType);c.push({type:"text",text:`[Image Description]: ${p}`})}catch(p){Vg(p),c.push({type:"text",text:k.t("openaiContentGenerator.errors.imageContentCannotParse",{error:p instanceof Error?p.message:String(p)})})}}c.length>0&&r.push({role:"user",content:c})}}}}return r}createGeminiResponse(){let e=new t4;return e.candidates=[{content:{parts:[],role:"model"}}],e}async convertFromOpenAIResponse(e){let r=e.choices[0],n=this.createGeminiResponse(),i=n.candidates?.[0];if(r.message.reasoning_content&&i?.content?.parts&&i.content.parts.push({thought:!0,text:r.message.reasoning_content}),r.message.content&&r.message.content.trim()&&i?.content?.parts&&i.content.parts.push({text:r.message.content}),r.message.tool_calls)for(let o of r.message.tool_calls){let s;try{s=JSON.parse(o.function.arguments)}catch(a){if(Vg(a),this.baseUrl==="https://apis.iflow.cn/v1")try{s=await this.fixInvalidJsonWithQwen(o.function.arguments)}catch(c){Vg(c),console.error("Failed to fix JSON",c),s={}}else s={}}i?.content?.parts?.push({functionCall:{id:o.id,name:o.function.name,args:s}})}return i&&r.finish_reason!=="tool_calls"&&r.finish_reason&&(i.finishReason=this.mapFinishReason(r.finish_reason)),n.usageMetadata={promptTokenCount:e.usage?.prompt_tokens||0,candidatesTokenCount:e.usage?.completion_tokens||0,totalTokenCount:e.usage?.total_tokens||0},n}async fixInvalidJsonWithQwen(e){let r=`
838
838
  \u4F60\u662F\u4E00\u4E2Ajson\u683C\u5F0F\u4F18\u5316\u4E13\u5BB6\uFF0C\u4F60\u7684\u5DE5\u4F5C\u662F\u5C06\u4E00\u4E32\u6587\u672C\uFF0C\u6839\u636Ejson schema\u7684\u5B9A\u4E49\u8F93\u51FA\u6210\u4E00\u4E2Avalid\u7684json
839
839
  \u8FD9\u4E2A\u662F\u9519\u8BEF\u7684json\u683C\u5F0F\uFF1A
840
840
  ${e}
841
841
 
842
- \u8BF7\u76F4\u63A5\u8F93\u51FA\u4E00\u4E2A\u6B63\u786E\u7684json\u683C\u5F0F\uFF1A`;try{let n=await fetch("https://apis.iflow.cn/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:"QWen3-4B",messages:[{role:"user",content:r}],temperature:.1,max_tokens:1e3})});if(!n.ok)throw new Error(`API error: ${n.status}`);let i=await n.json();if(!i||!i.choices||!Array.isArray(i.choices)||i.choices.length===0)throw new Error("Invalid response format - missing or empty choices array");let o=i.choices[0]?.message?.content;if(!o||typeof o!="string")throw new Error("Invalid response - missing or invalid message content");let s=o.trim();if(s.startsWith("```json")?s=s.replace(/^```json\s*/,"").replace(/\s*```$/,""):s.startsWith("```")&&(s=s.replace(/^```\s*/,"").replace(/\s*```$/,"")),!s)throw new Error("Fixed JSON is empty after processing");return JSON.parse(s)}catch(n){throw Vg(n),console.error("QWen JSON fix failed:",n),n}}extractTextFromRequest(e){let r="";if(e.contents){let n=Array.isArray(e.contents)?e.contents:[e.contents];for(let i of n)if(i&&typeof i=="object"&&"parts"in i&&i.parts){let o=Array.isArray(i.parts)?i.parts:[i.parts];for(let s of o)if(s&&typeof s=="object"&&"text"in s&&s.text)r+=s.text+" ";else if(s.functionResponse&&s.functionResponse.response)for(let[a,c]of Object.entries(s.functionResponse.response))c!=null&&(r+=String(c)+" ")}}return e.config?.systemInstruction&&(r+=e.config.systemInstruction),r.trim()}extractTextFromEmbedRequest(e){if(e.contents){let r=Array.isArray(e.contents)?e.contents:[e.contents];for(let n of r)if(typeof n=="object"&&n!==null&&"parts"in n&&n.parts){let i=Array.isArray(n.parts)?n.parts:[n.parts];for(let o of i)if(typeof o=="object"&&o!==null&&"text"in o&&o.text)return o.text}else{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null&&"text"in n&&n.text)return n.text}}return""}extractSystemInstruction(e){let r="";if(typeof e=="string")r=e;else if(Array.isArray(e)){for(let n of e)typeof n=="object"&&n!==null&&"text"in n&&n.text&&(r+=n.text+" ");r=r.trim()}else if(typeof e=="object"&&e!==null)if("parts"in e&&e.parts){let n=Array.isArray(e.parts)?e.parts:[e.parts];for(let i of n)typeof i=="object"&&i!==null&&"text"in i&&i.text&&(r+=i.text+" ");r=r.trim()}else"text"in e&&e.text&&(r=e.text);return r}convertToOpenAITools(e){if(!e||e.length===0)return[];let r=[];for(let n of e)if(n.functionDeclarations&&Array.isArray(n.functionDeclarations))for(let i of n.functionDeclarations)r.push({type:"function",function:{name:i.name||"",description:i.description,parameters:this.convertParameters(i.parameters||i.parametersJsonSchema)}});return r}convertParameters(e){if(!e)return;let r={STRING:"string",INTEGER:"integer",NUMBER:"number",BOOLEAN:"boolean",OBJECT:"object",ARRAY:"array",string:"string",integer:"integer",number:"number",boolean:"boolean",object:"object",array:"array"};if(typeof e=="object"&&e.type){if(typeof e.type=="string"&&(r[e.type]?e.type=r[e.type]:e.type=e.type.toLowerCase()),e.properties)for(let i in e.properties){let o=e.properties[i],s={};o.type&&(s.type=r[o.type]),o.description&&(s.description=o.description),e.properties[i]=s}return e.items&&(e.items=this.convertParameters(e.items)),e}let n=i=>{if(!i)return;let o={};if(i.type)switch(i.type){case"STRING":o.type="string";break;case"INTEGER":o.type="integer";break;case"NUMBER":o.type="number";break;case"BOOLEAN":o.type="boolean";break;case"OBJECT":o.type="object";break;case"ARRAY":o.type="array";break;default:o.type=i.type.toLowerCase()}if(o.type="object",i.description&&(o.description=i.description),i.enum&&(o.enum=i.enum),i.properties){o.properties={};for(let[s,a]of Object.entries(i.properties))o.properties[s]=n(a)}return i.items&&(o.items=n(i.items)),i.required&&(o.required=i.required),o};return n(e)}mapFinishReason(e){switch(e){case"stop":return bw.STOP;case"length":return bw.MAX_TOKENS;case"content_filter":return bw.SAFETY;case"tool_calls":return bw.MALFORMED_FUNCTION_CALL;default:return bw.OTHER}}convertResponseSchema(e){if(e)return e.type==="object"||e.type==="OBJECT"?{type:"json_schema",json_schema:{name:e.name||"",description:e.description||"",schema:this.convertSchemaToJsonSchema(e),strict:!0}}:{type:"json_schema",json_schema:{name:"response_schema",description:"Generated response schema",schema:this.convertSchemaToJsonSchema(e),strict:!0}}}convertSchemaToJsonSchema(e){if(!e)return{};let r={};if(e.type)switch(e.type){case"STRING":r.type="string";break;case"INTEGER":r.type="integer";break;case"NUMBER":r.type="number";break;case"BOOLEAN":r.type="boolean";break;case"OBJECT":r.type="object";break;case"ARRAY":r.type="array";break;default:r.type=typeof e.type=="string"?e.type.toLowerCase():e.type}if(e.description&&(r.description=e.description),e.enum&&(r.enum=e.enum),e.properties){r.properties={};for(let[n,i]of Object.entries(e.properties))r.properties[n]=this.convertSchemaToJsonSchema(i)}return e.items&&(r.items=this.convertSchemaToJsonSchema(e.items)),e.required&&(r.required=e.required),r.type==="object"&&!("additionalProperties"in r)&&(r.additionalProperties=!1),r}}});var C1,Xu,uU,dU,tX,nMt,l4=ae(()=>{"use strict";C1="Qwen3-Coder",Xu="Qwen3-Coder",uU="text-embedding-v1",dU="gemini-2.5-flash-lite",tX="https://apis.iflow.cn/v1",nMt="https://ducky.code.alibaba-inc.com/v1/openai"});async function QFe(t,e,r,n){if(e===$t.LOGIN_WITH_IFLOW){let i=await pD(e,r),o=await v5();if(!o)throw new Error("No API key found. Please re-authenticate.");let s=r.getContentGeneratorConfig();return new cU({model:r.getModel(),apiKey:o,baseUrl:s?.baseUrl||tX,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===$t.CLOUD_SHELL){let i=await pD(e,r),o=await ENt(i);return new U8(i,o.projectId,t,n,o.userTier)}throw new Error(`Unsupported authType: ${e}`)}var qFe=ae(()=>{"use strict";A3();_w();vNt();mhe();UFe();l4();});function QOn(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function I5(t){let e=QOn(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let i=`iflow_${t}`;if(process.env[i])return process.env[i];let o=`iflow_${e}`;if(process.env[o])return process.env[o]}function rX(){return I5("apiKey")}function nX(){return I5("baseUrl")||I5("url")}function iX(){return I5("modelName")||I5("model")}function iMt(t){let e=I5(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function oMt(t){let e=I5(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function sMt(t){let e=I5(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function b0e(){return!!(rX()||nX()||iX())}function GFe(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout"],i=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(o=>{let s=I5(o);s!==void 0&&(t[o]=s)}),r.forEach(o=>{let s=iMt(o);s!==void 0&&(t[o]=s)}),n.forEach(o=>{let s=oMt(o);s!==void 0&&(t[o]=s)}),i.forEach(o=>{let s=sMt(o);s!==void 0&&(t[o]=s)}),t}function qOn(){return{apiKey:rX(),baseUrl:nX(),model:iX()}}var HFe=ae(()=>{"use strict";});async function VFe(t,e,r){await OF()&&(await hhe()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted."));let i=process.env.GEMINI_API_KEY,o=process.env.GOOGLE_API_KEY,s=process.env.GOOGLE_CLOUD_PROJECT,a=process.env.GOOGLE_CLOUD_LOCATION,c=rX(),u=nX(),d=iX(),f=r?.apiKey||c,p=r?.baseUrl||u||GOn[e],h=t.getModel()||d||C1,m={model:h,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===$t.CLOUD_SHELL?m:e===$t.LOGIN_WITH_IFLOW?(m.baseUrl=p||tX,m.multimodalModelName="qwen3-vl-plus",f&&(m.apiKey=f),m):([...Wg,$t.OPENAI_COMPATIBLE].includes(e)&&f&&(m.apiKey=f,m.baseUrl=p,m.model=h),m)}async function WFe(t,e,r){let i={headers:{"User-Agent":`iFlowCLI/0.3.1 (${process.platform}; ${process.arch})`}};if(t.authType&&[...Wg,$t.IDEA_LAB].includes(t.authType)||t.authType===$t.OPENAI_COMPATIBLE)return new cU({...t,config:e});if(t.authType===$t.LOGIN_WITH_IFLOW||t.authType===$t.CLOUD_SHELL)return QFe(i,t.authType,e,r);if([...Wg,$t.OPENAI_COMPATIBLE].includes(t.authType)||t.authType===$t.USE_GEMINI||t.authType===$t.USE_VERTEX_AI)return new ihe({apiKey:t.apiKey===""?void 0:t.apiKey,vertexai:t.vertexai,httpOptions:i}).models;throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var $t,Wg,GOn,A3=ae(()=>{"use strict";il();qFe();l4();UFe();HFe();_w();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.USE_GEMINI="gemini-api-key",t.USE_VERTEX_AI="vertex-ai",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.AONE="aone",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})($t||($t={}));Wg=[$t.IFLOW,$t.AONE],GOn={[$t.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[$t.IFLOW]:tX,[$t.AONE]:nMt}});var x0e,aMt=ae(()=>{"use strict";x0e=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,i)=>n.name.localeCompare(i.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var po,zr,ho,mo,su=ae(()=>{"use strict";po=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,i,o,s,a=!0,c=!1,u=[]){this.name=e,this.displayName=r,this.description=n,this.icon=i,this.kind=o,this.parameterSchema=s,this.isOutputMarkdown=a,this.canUpdateOutput=c,this.aliases=u}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(zr||(zr={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(ho||(ho={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(mo||(mo={}))});function TD(t,e){let r=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(r.has(i))return"[Circular]";r.add(i)}return i},e)}var w0e=ae(()=>{"use strict";});var Ur,b1=ae(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed",t.HOOK_BLOCKED="hook_blocked"})(Ur||(Ur={}))});function HOn(t){return{text:t.text}}function VOn(t,e){return[{text:k.t("mcpTool.messages.mediaDataProvided",{toolName:e,type:t.type,mimeType:t.mimeType})},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function WOn(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:k.t("mcpTool.messages.embeddedResourceProvided",{toolName:e,mimeType:n})},{inlineData:{mimeType:n,data:r.blob}}]}return null}function $On(t){return{text:k.t("mcpTool.messages.resourceLink",{title:t.title||t.name,uri:t.uri})}}function jOn(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(o=>{switch(o.type){case"text":return HOn(o);case"image":case"audio":return VOn(o,n);case"resource":return WOn(o,n);case"resource_link":return $On(o);default:return null}}).filter(o=>o!==null):[{text:k.t("mcpTool.errors.parseResponseFailed")}]}function zOn(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return k.t("mcpTool.display.image",{mimeType:n.mimeType});case"audio":return k.t("mcpTool.display.audio",{mimeType:n.mimeType});case"resource_link":return k.t("mcpTool.display.resourceLink",{title:n.title||n.name,uri:n.uri});case"resource":return n.resource?.text?n.resource.text:k.t("mcpTool.display.embeddedResource",{mimeType:n.resource?.mimeType||k.t("mcpTool.display.unknownType")});default:return k.t("mcpTool.display.unknownContentType",{type:n.type})}}).join(`
842
+ \u8BF7\u76F4\u63A5\u8F93\u51FA\u4E00\u4E2A\u6B63\u786E\u7684json\u683C\u5F0F\uFF1A`;try{let n=await fetch("https://apis.iflow.cn/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:"QWen3-4B",messages:[{role:"user",content:r}],temperature:.1,max_tokens:1e3})});if(!n.ok)throw new Error(`API error: ${n.status}`);let i=await n.json();if(!i||!i.choices||!Array.isArray(i.choices)||i.choices.length===0)throw new Error("Invalid response format - missing or empty choices array");let o=i.choices[0]?.message?.content;if(!o||typeof o!="string")throw new Error("Invalid response - missing or invalid message content");let s=o.trim();if(s.startsWith("```json")?s=s.replace(/^```json\s*/,"").replace(/\s*```$/,""):s.startsWith("```")&&(s=s.replace(/^```\s*/,"").replace(/\s*```$/,"")),!s)throw new Error("Fixed JSON is empty after processing");return JSON.parse(s)}catch(n){throw Vg(n),console.error("QWen JSON fix failed:",n),n}}extractTextFromRequest(e){let r="";if(e.contents){let n=Array.isArray(e.contents)?e.contents:[e.contents];for(let i of n)if(i&&typeof i=="object"&&"parts"in i&&i.parts){let o=Array.isArray(i.parts)?i.parts:[i.parts];for(let s of o)if(s&&typeof s=="object"&&"text"in s&&s.text)r+=s.text+" ";else if(s.functionResponse&&s.functionResponse.response)for(let[a,c]of Object.entries(s.functionResponse.response))c!=null&&(r+=String(c)+" ")}}return e.config?.systemInstruction&&(r+=e.config.systemInstruction),r.trim()}extractTextFromEmbedRequest(e){if(e.contents){let r=Array.isArray(e.contents)?e.contents:[e.contents];for(let n of r)if(typeof n=="object"&&n!==null&&"parts"in n&&n.parts){let i=Array.isArray(n.parts)?n.parts:[n.parts];for(let o of i)if(typeof o=="object"&&o!==null&&"text"in o&&o.text)return o.text}else{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null&&"text"in n&&n.text)return n.text}}return""}extractSystemInstruction(e){let r="";if(typeof e=="string")r=e;else if(Array.isArray(e)){for(let n of e)typeof n=="object"&&n!==null&&"text"in n&&n.text&&(r+=n.text+" ");r=r.trim()}else if(typeof e=="object"&&e!==null)if("parts"in e&&e.parts){let n=Array.isArray(e.parts)?e.parts:[e.parts];for(let i of n)typeof i=="object"&&i!==null&&"text"in i&&i.text&&(r+=i.text+" ");r=r.trim()}else"text"in e&&e.text&&(r=e.text);return r}convertToOpenAITools(e){if(!e||e.length===0)return[];let r=[];for(let n of e)if(n.functionDeclarations&&Array.isArray(n.functionDeclarations))for(let i of n.functionDeclarations)r.push({type:"function",function:{name:i.name||"",description:i.description,parameters:this.convertParameters(i.parameters||i.parametersJsonSchema)}});return r}convertParameters(e){if(!e)return;let r={STRING:"string",INTEGER:"integer",NUMBER:"number",BOOLEAN:"boolean",OBJECT:"object",ARRAY:"array",string:"string",integer:"integer",number:"number",boolean:"boolean",object:"object",array:"array"};if(typeof e=="object"&&e.type){if(typeof e.type=="string"&&(r[e.type]?e.type=r[e.type]:e.type=e.type.toLowerCase()),e.properties)for(let i in e.properties){let o=e.properties[i],s={};o.type&&(s.type=r[o.type]),o.description&&(s.description=o.description),e.properties[i]=s}return e.items&&(e.items=this.convertParameters(e.items)),e}let n=i=>{if(!i)return;let o={};if(i.type)switch(i.type){case"STRING":o.type="string";break;case"INTEGER":o.type="integer";break;case"NUMBER":o.type="number";break;case"BOOLEAN":o.type="boolean";break;case"OBJECT":o.type="object";break;case"ARRAY":o.type="array";break;default:o.type=i.type.toLowerCase()}if(o.type="object",i.description&&(o.description=i.description),i.enum&&(o.enum=i.enum),i.properties){o.properties={};for(let[s,a]of Object.entries(i.properties))o.properties[s]=n(a)}return i.items&&(o.items=n(i.items)),i.required&&(o.required=i.required),o};return n(e)}mapFinishReason(e){switch(e){case"stop":return bw.STOP;case"length":return bw.MAX_TOKENS;case"content_filter":return bw.SAFETY;case"tool_calls":return bw.MALFORMED_FUNCTION_CALL;default:return bw.OTHER}}convertResponseSchema(e){if(e)return e.type==="object"||e.type==="OBJECT"?{type:"json_schema",json_schema:{name:e.name||"",description:e.description||"",schema:this.convertSchemaToJsonSchema(e),strict:!0}}:{type:"json_schema",json_schema:{name:"response_schema",description:"Generated response schema",schema:this.convertSchemaToJsonSchema(e),strict:!0}}}convertSchemaToJsonSchema(e){if(!e)return{};let r={};if(e.type)switch(e.type){case"STRING":r.type="string";break;case"INTEGER":r.type="integer";break;case"NUMBER":r.type="number";break;case"BOOLEAN":r.type="boolean";break;case"OBJECT":r.type="object";break;case"ARRAY":r.type="array";break;default:r.type=typeof e.type=="string"?e.type.toLowerCase():e.type}if(e.description&&(r.description=e.description),e.enum&&(r.enum=e.enum),e.properties){r.properties={};for(let[n,i]of Object.entries(e.properties))r.properties[n]=this.convertSchemaToJsonSchema(i)}return e.items&&(r.items=this.convertSchemaToJsonSchema(e.items)),e.required&&(r.required=e.required),r.type==="object"&&!("additionalProperties"in r)&&(r.additionalProperties=!1),r}}});var C1,Xu,uU,dU,tX,nMt,l4=ae(()=>{"use strict";C1="Qwen3-Coder",Xu="Qwen3-Coder",uU="text-embedding-v1",dU="gemini-2.5-flash-lite",tX="https://apis.iflow.cn/v1",nMt="https://ducky.code.alibaba-inc.com/v1/openai"});async function QFe(t,e,r,n){if(e===$t.LOGIN_WITH_IFLOW){let i=await pD(e,r),o=await v5();if(!o)throw new Error("No API key found. Please re-authenticate.");let s=r.getContentGeneratorConfig();return new cU({model:r.getModel(),apiKey:o,baseUrl:s?.baseUrl||tX,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===$t.CLOUD_SHELL){let i=await pD(e,r),o=await ENt(i);return new U8(i,o.projectId,t,n,o.userTier)}throw new Error(`Unsupported authType: ${e}`)}var qFe=ae(()=>{"use strict";A3();_w();vNt();mhe();UFe();l4();});function QOn(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function I5(t){let e=QOn(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let i=`iflow_${t}`;if(process.env[i])return process.env[i];let o=`iflow_${e}`;if(process.env[o])return process.env[o]}function rX(){return I5("apiKey")}function nX(){return I5("baseUrl")||I5("url")}function iX(){return I5("modelName")||I5("model")}function iMt(t){let e=I5(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function oMt(t){let e=I5(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function sMt(t){let e=I5(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function b0e(){return!!(rX()||nX()||iX())}function GFe(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout"],i=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(o=>{let s=I5(o);s!==void 0&&(t[o]=s)}),r.forEach(o=>{let s=iMt(o);s!==void 0&&(t[o]=s)}),n.forEach(o=>{let s=oMt(o);s!==void 0&&(t[o]=s)}),i.forEach(o=>{let s=sMt(o);s!==void 0&&(t[o]=s)}),t}function qOn(){return{apiKey:rX(),baseUrl:nX(),model:iX()}}var HFe=ae(()=>{"use strict";});async function VFe(t,e,r){await OF()&&(await hhe()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted."));let i=process.env.GEMINI_API_KEY,o=process.env.GOOGLE_API_KEY,s=process.env.GOOGLE_CLOUD_PROJECT,a=process.env.GOOGLE_CLOUD_LOCATION,c=rX(),u=nX(),d=iX(),f=r?.apiKey||c,p=r?.baseUrl||u||GOn[e],h=t.getModel()||d||C1,m={model:h,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===$t.CLOUD_SHELL?m:e===$t.LOGIN_WITH_IFLOW?(m.baseUrl=p||tX,m.multimodalModelName="qwen3-vl-plus",f&&(m.apiKey=f),m):([...Wg,$t.OPENAI_COMPATIBLE].includes(e)&&f&&(m.apiKey=f,m.baseUrl=p,m.model=h),m)}async function WFe(t,e,r){let i={headers:{"User-Agent":`iFlowCLI/0.3.2-beta.0 (${process.platform}; ${process.arch})`}};if(t.authType&&[...Wg,$t.IDEA_LAB].includes(t.authType)||t.authType===$t.OPENAI_COMPATIBLE)return new cU({...t,config:e});if(t.authType===$t.LOGIN_WITH_IFLOW||t.authType===$t.CLOUD_SHELL)return QFe(i,t.authType,e,r);if([...Wg,$t.OPENAI_COMPATIBLE].includes(t.authType)||t.authType===$t.USE_GEMINI||t.authType===$t.USE_VERTEX_AI)return new ihe({apiKey:t.apiKey===""?void 0:t.apiKey,vertexai:t.vertexai,httpOptions:i}).models;throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var $t,Wg,GOn,A3=ae(()=>{"use strict";il();qFe();l4();UFe();HFe();_w();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.USE_GEMINI="gemini-api-key",t.USE_VERTEX_AI="vertex-ai",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.AONE="aone",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})($t||($t={}));Wg=[$t.IFLOW,$t.AONE],GOn={[$t.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[$t.IFLOW]:tX,[$t.AONE]:nMt}});var x0e,aMt=ae(()=>{"use strict";x0e=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,i)=>n.name.localeCompare(i.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var po,zr,ho,mo,su=ae(()=>{"use strict";po=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,i,o,s,a=!0,c=!1,u=[]){this.name=e,this.displayName=r,this.description=n,this.icon=i,this.kind=o,this.parameterSchema=s,this.isOutputMarkdown=a,this.canUpdateOutput=c,this.aliases=u}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(zr||(zr={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(ho||(ho={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(mo||(mo={}))});function TD(t,e){let r=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(r.has(i))return"[Circular]";r.add(i)}return i},e)}var w0e=ae(()=>{"use strict";});var Ur,b1=ae(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed",t.HOOK_BLOCKED="hook_blocked"})(Ur||(Ur={}))});function HOn(t){return{text:t.text}}function VOn(t,e){return[{text:k.t("mcpTool.messages.mediaDataProvided",{toolName:e,type:t.type,mimeType:t.mimeType})},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function WOn(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:k.t("mcpTool.messages.embeddedResourceProvided",{toolName:e,mimeType:n})},{inlineData:{mimeType:n,data:r.blob}}]}return null}function $On(t){return{text:k.t("mcpTool.messages.resourceLink",{title:t.title||t.name,uri:t.uri})}}function jOn(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(o=>{switch(o.type){case"text":return HOn(o);case"image":case"audio":return VOn(o,n);case"resource":return WOn(o,n);case"resource_link":return $On(o);default:return null}}).filter(o=>o!==null):[{text:k.t("mcpTool.errors.parseResponseFailed")}]}function zOn(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return k.t("mcpTool.display.image",{mimeType:n.mimeType});case"audio":return k.t("mcpTool.display.audio",{mimeType:n.mimeType});case"resource_link":return k.t("mcpTool.display.resourceLink",{title:n.title||n.name,uri:n.uri});case"resource":return n.resource?.text?n.resource.text:k.t("mcpTool.display.embeddedResource",{mimeType:n.resource?.mimeType||k.t("mcpTool.display.unknownType")});default:return k.t("mcpTool.display.unknownContentType",{type:n.type})}}).join(`
843
843
  `):"```json\n"+JSON.stringify(t,null,2)+"\n```"}function lMt(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"_");return e.length>63&&(e=e.slice(0,28)+"___"+e.slice(-32)),e}var Th,oX=ae(()=>{"use strict";w0e();b1();su();il();Gn();Th=class t extends po{mcpTool;serverName;serverToolName;parameterSchemaJson;timeout;trust;static allowlist=new Set;constructor(e,r,n,i,o,s,a,c){super(c??lMt(n),`${n} (${r} MCP Server)`,i,ho.Hammer,mo.Other,{type:Pt.OBJECT},!0,!1),this.mcpTool=e,this.serverName=r,this.serverToolName=n,this.parameterSchemaJson=o,this.timeout=s,this.trust=a}asFullyQualifiedTool(){return new t(this.mcpTool,this.serverName,this.serverToolName,this.description,this.parameterSchemaJson,this.timeout,this.trust,`${this.serverName}__${this.serverToolName}`)}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchemaJson}}async shouldConfirmExecute(e,r){let n=this.serverName,i=`${this.serverName}.${this.serverToolName}`;return this.trust||t.allowlist.has(n)||t.allowlist.has(i)?!1:{type:"mcp",title:k.t("mcpTool.messages.confirmExecution"),serverName:this.serverName,toolName:this.serverToolName,toolDisplayName:this.name,onConfirm:async s=>{s===zr.ProceedAlwaysServer?t.allowlist.add(n):s===zr.ProceedAlwaysTool&&t.allowlist.add(i)}}}isMCPToolError(e){let n=e?.[0]?.functionResponse?.response;if(n){let i=n?.error,o=i?.isError;if(i&&(o===!0||o==="true"))return!0}return!1}async execute(e){let{callId:r,...n}=e,i=[{name:this.serverToolName,args:n}],o=await this.mcpTool.callTool(i);if(this.isMCPToolError(o)){let a=`MCP tool '${this.serverToolName}' reported tool error for function call: ${TD(i[0])} with response: ${TD(o)}`;return{llmContent:a,returnDisplay:k.t("mcpTool.errors.toolReportedError",{toolName:this.serverToolName}),error:{message:a,type:Ur.MCP_TOOL_ERROR}}}return{llmContent:jOn(o),returnDisplay:zOn(o)}}}});var uMt=D((PLo,cMt)=>{"use strict";cMt.exports=function(e){return e.map(function(r){return r===""?"''":r&&typeof r=="object"?r.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var AMt=D((LLo,gMt)=>{"use strict";var mMt="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",dMt=new RegExp("^"+mMt+"$"),fMt="|&;()<> \\t",YOn='"((\\\\"|[^"])*?)"',JOn="'((\\\\'|[^'])*?)'",KOn=/^#$/,pMt="'",hMt='"',$Fe="$",ID="",XOn=4294967296;for(jFe=0;jFe<4;jFe++)ID+=(XOn*Math.random()).toString(16);var jFe,ZOn=new RegExp("^"+ID);function ekn(t,e){for(var r=e.lastIndex,n=[],i;i=e.exec(t);)n.push(i),e.lastIndex===i.index&&(e.lastIndex+=1);return e.lastIndex=r,n}function tkn(t,e,r){var n=typeof t=="function"?t(r):t[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+ID+JSON.stringify(n)+ID:e+n}function rkn(t,e,r){r||(r={});var n=r.escape||"\\",i="(\\"+n+`['"`+fMt+`]|[^\\s'"`+fMt+"])+",o=new RegExp(["("+mMt+")","("+i+"|"+YOn+"|"+JOn+")+"].join("|"),"g"),s=ekn(t,o);if(s.length===0)return[];e||(e={});var a=!1;return s.map(function(c){var u=c[0];if(!u||a)return;if(dMt.test(u))return{op:u};var d=!1,f=!1,p="",h=!1,m;function g(){m+=1;var E,C,x=u.charAt(m);if(x==="{"){if(m+=1,u.charAt(m)==="}")throw new Error("Bad substitution: "+u.slice(m-2,m+1));if(E=u.indexOf("}",m),E<0)throw new Error("Bad substitution: "+u.slice(m));C=u.slice(m,E),m=E}else if(/[*@#?$!_-]/.test(x))C=x,m+=1;else{var T=u.slice(m);E=T.match(/[^\w\d_]/),E?(C=T.slice(0,E.index),m+=E.index-1):(C=T,m=u.length)}return tkn(e,"",C)}for(m=0;m<u.length;m++){var A=u.charAt(m);if(h=h||!d&&(A==="*"||A==="?"),f)p+=A,f=!1;else if(d)A===d?d=!1:d==pMt?p+=A:A===n?(m+=1,A=u.charAt(m),A===hMt||A===n||A===$Fe?p+=A:p+=n+A):A===$Fe?p+=g():p+=A;else if(A===hMt||A===pMt)d=A;else{if(dMt.test(A))return{op:u};if(KOn.test(A)){a=!0;var y={comment:t.slice(c.index+m+1)};return p.length?[p,y]:[y]}else A===n?f=!0:A===$Fe?p+=g():p+=A}}return h?{op:"glob",pattern:p}:p}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}gMt.exports=function(e,r,n){var i=rkn(e,r,n);return typeof r!="function"?i:i.reduce(function(o,s){if(typeof s=="object")return o.concat(s);var a=s.split(RegExp("("+ID+".*?"+ID+")","g"));return a.length===1?o.concat(a[0]):o.concat(a.filter(Boolean).map(function(c){return ZOn.test(c)?JSON.parse(c.split(ID)[1]):c}))},[])}});var S0e=D(zFe=>{"use strict";zFe.quote=uMt();zFe.parse=AMt()});var ws,YFe,nn,D5,sX=ae(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ws||(ws={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(YFe||(YFe={}));nn=ws.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),D5=t=>{switch(typeof t){case"undefined":return nn.undefined;case"string":return nn.string;case"number":return Number.isNaN(t)?nn.nan:nn.number;case"boolean":return nn.boolean;case"function":return nn.function;case"bigint":return nn.bigint;case"symbol":return nn.symbol;case"object":return Array.isArray(t)?nn.array:t===null?nn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?nn.promise:typeof Map<"u"&&t instanceof Map?nn.map:typeof Set<"u"&&t instanceof Set?nn.set:typeof Date<"u"&&t instanceof Date?nn.date:nn.object;default:return nn.unknown}}});var yr,nkn,$g,_0e=ae(()=>{sX();yr=ws.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),nkn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),$g=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ws.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};$g.create=t=>new $g(t)});var ikn,j8,JFe=ae(()=>{_0e();sX();ikn=(t,e)=>{let r;switch(t.code){case yr.invalid_type:t.received===nn.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case yr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ws.jsonStringifyReplacer)}`;break;case yr.unrecognized_keys:r=`Unrecognized key(s) in object: ${ws.joinValues(t.keys,", ")}`;break;case yr.invalid_union:r="Invalid input";break;case yr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ws.joinValues(t.options)}`;break;case yr.invalid_enum_value:r=`Invalid enum value. Expected ${ws.joinValues(t.options)}, received '${t.received}'`;break;case yr.invalid_arguments:r="Invalid function arguments";break;case yr.invalid_return_type:r="Invalid function return type";break;case yr.invalid_date:r="Invalid date";break;case yr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ws.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case yr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case yr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case yr.custom:r="Invalid input";break;case yr.invalid_intersection_types:r="Intersection results could not be merged";break;case yr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case yr.not_finite:r="Number must be finite";break;default:r=e.defaultError,ws.assertNever(t)}return{message:r}},j8=ikn});function okn(t){yMt=t}function fU(){return yMt}var yMt,T0e=ae(()=>{JFe();yMt=j8});function Yr(t,e){let r=fU(),n=aX({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===j8?void 0:j8].filter(i=>!!i)});t.common.issues.push(n)}var aX,skn,Ih,Di,DD,E0,I0e,D0e,iS,pU,KFe=ae(()=>{T0e();JFe();aX=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},skn=[];Ih=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return Di;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return Di;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},Di=Object.freeze({status:"aborted"}),DD=t=>({status:"dirty",value:t}),E0=t=>({status:"valid",value:t}),I0e=t=>t.status==="aborted",D0e=t=>t.status==="dirty",iS=t=>t.status==="valid",pU=t=>typeof Promise<"u"&&t instanceof Promise});var EMt=ae(()=>{});var Mn,vMt=ae(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Mn||(Mn={}))});function Mo(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}function wMt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function xkn(t){return new RegExp(`^${wMt(t)}$`)}function SMt(t){let e=`${xMt}T${wMt(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function wkn(t,e){return!!((e==="v4"||!e)&&gkn.test(t)||(e==="v6"||!e)&&ykn.test(t))}function Skn(t,e){if(!fkn.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function _kn(t,e){return!!((e==="v4"||!e)&&Akn.test(t)||(e==="v6"||!e)&&Ekn.test(t))}function Tkn(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}function hU(t){if(t instanceof jg){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=I3.create(hU(n))}return new jg({...t._def,shape:()=>e})}else return t instanceof J8?new J8({...t._def,type:hU(t.element)}):t instanceof I3?I3.create(hU(t.unwrap())):t instanceof B5?B5.create(hU(t.unwrap())):t instanceof R5?R5.create(t.items.map(e=>hU(e))):t}function ZFe(t,e){let r=D5(t),n=D5(e);if(t===e)return{valid:!0,data:t};if(r===nn.object&&n===nn.object){let i=ws.objectKeys(e),o=ws.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let c=ZFe(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===nn.array&&n===nn.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],c=ZFe(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===nn.date&&n===nn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function _Mt(t,e){return new QD({values:t,typeName:ki.ZodEnum,...Mo(e)})}function bMt(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function TMt(t,e={},r){return t?sS.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=bMt(e,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=bMt(e,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):sS.create()}var D3,CMt,Ko,akn,lkn,ckn,ukn,dkn,fkn,pkn,hkn,mkn,XFe,gkn,Akn,ykn,Ekn,vkn,Ckn,xMt,bkn,oS,RD,BD,ND,OD,mU,kD,MD,sS,Y8,c4,gU,J8,jg,PD,z8,R0e,LD,R5,B0e,AU,yU,N0e,FD,UD,QD,qD,aS,R3,I3,B5,GD,HD,EU,Ikn,lX,cX,VD,Dkn,ki,Rkn,IMt,DMt,Bkn,Nkn,RMt,Okn,kkn,Mkn,Pkn,Lkn,Fkn,Ukn,Qkn,qkn,Gkn,Hkn,Vkn,Wkn,$kn,jkn,zkn,Ykn,Jkn,Kkn,Xkn,Zkn,eMn,tMn,rMn,nMn,iMn,oMn,sMn,aMn,lMn,cMn,uMn,dMn,fMn,BMt=ae(()=>{_0e();T0e();vMt();KFe();sX();D3=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},CMt=(t,e)=>{if(iS(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new $g(t.common.issues);return this._error=r,this._error}}};Ko=class{get description(){return this._def.description}_getType(e){return D5(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:D5(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ih,ctx:{common:e.parent.common,data:e.data,parsedType:D5(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(pU(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D5(e)},i=this._parseSync({data:e,path:n.path,parent:n});return CMt(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D5(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return iS(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>iS(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D5(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(pU(i)?i:Promise.resolve(i));return CMt(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:yr.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new R3({schema:this,typeName:ki.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return I3.create(this,this._def)}nullable(){return B5.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return J8.create(this)}promise(){return aS.create(this,this._def)}or(e){return PD.create([this,e],this._def)}and(e){return LD.create(this,e,this._def)}transform(e){return new R3({...Mo(this._def),schema:this,typeName:ki.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new GD({...Mo(this._def),innerType:this,defaultValue:r,typeName:ki.ZodDefault})}brand(){return new lX({typeName:ki.ZodBranded,type:this,...Mo(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new HD({...Mo(this._def),innerType:this,catchValue:r,typeName:ki.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return cX.create(this,e)}readonly(){return VD.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},akn=/^c[^\s-]{8,}$/i,lkn=/^[0-9a-z]+$/,ckn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ukn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,dkn=/^[a-z0-9_-]{21}$/i,fkn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pkn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hkn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mkn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gkn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Akn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ykn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ekn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vkn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ckn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,xMt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",bkn=new RegExp(`^${xMt}$`);oS=class t extends Ko{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==nn.string){let o=this._getOrReturnCtx(e);return Yr(o,{code:yr.invalid_type,expected:nn.string,received:o.parsedType}),Di}let n=new Ih,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?Yr(i,{code:yr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Yr(i,{code:yr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")hkn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"email",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")XFe||(XFe=new RegExp(mkn,"u")),XFe.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"emoji",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ukn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"uuid",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")dkn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"nanoid",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")akn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"cuid",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")lkn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"cuid2",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ckn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"ulid",code:yr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Yr(i,{validation:"url",code:yr.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"regex",code:yr.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?SMt(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?bkn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?xkn(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?pkn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"duration",code:yr.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?wkn(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"ip",code:yr.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Skn(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"jwt",code:yr.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?_kn(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"cidr",code:yr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?vkn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"base64",code:yr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Ckn.test(e.data)||(i=this._getOrReturnCtx(e,i),Yr(i,{validation:"base64url",code:yr.invalid_string,message:o.message}),n.dirty()):ws.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:yr.invalid_string,...Mn.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Mn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Mn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Mn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Mn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Mn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Mn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Mn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Mn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Mn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Mn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Mn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Mn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Mn.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Mn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Mn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Mn.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Mn.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Mn.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Mn.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Mn.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Mn.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Mn.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Mn.errToObj(r)})}nonempty(e){return this.min(1,Mn.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};oS.create=t=>new oS({checks:[],typeName:ki.ZodString,coerce:t?.coerce??!1,...Mo(t)});RD=class t extends Ko{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==nn.number){let o=this._getOrReturnCtx(e);return Yr(o,{code:yr.invalid_type,expected:nn.number,received:o.parsedType}),Di}let n,i=new Ih;for(let o of this._def.checks)o.kind==="int"?ws.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Tkn(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.not_finite,message:o.message}),i.dirty()):ws.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Mn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Mn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Mn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Mn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Mn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Mn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Mn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Mn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Mn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Mn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Mn.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Mn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Mn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Mn.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ws.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};RD.create=t=>new RD({checks:[],typeName:ki.ZodNumber,coerce:t?.coerce||!1,...Mo(t)});BD=class t extends Ko{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==nn.bigint)return this._getInvalidInput(e);let n,i=new Ih;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Yr(n,{code:yr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ws.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Yr(r,{code:yr.invalid_type,expected:nn.bigint,received:r.parsedType}),Di}gte(e,r){return this.setLimit("min",e,!0,Mn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Mn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Mn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Mn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Mn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Mn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Mn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Mn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Mn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Mn.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};BD.create=t=>new BD({checks:[],typeName:ki.ZodBigInt,coerce:t?.coerce??!1,...Mo(t)});ND=class extends Ko{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==nn.boolean){let n=this._getOrReturnCtx(e);return Yr(n,{code:yr.invalid_type,expected:nn.boolean,received:n.parsedType}),Di}return E0(e.data)}};ND.create=t=>new ND({typeName:ki.ZodBoolean,coerce:t?.coerce||!1,...Mo(t)});OD=class t extends Ko{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==nn.date){let o=this._getOrReturnCtx(e);return Yr(o,{code:yr.invalid_type,expected:nn.date,received:o.parsedType}),Di}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return Yr(o,{code:yr.invalid_date}),Di}let n=new Ih,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),Yr(i,{code:yr.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ws.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Mn.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Mn.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};OD.create=t=>new OD({checks:[],coerce:t?.coerce||!1,typeName:ki.ZodDate,...Mo(t)});mU=class extends Ko{_parse(e){if(this._getType(e)!==nn.symbol){let n=this._getOrReturnCtx(e);return Yr(n,{code:yr.invalid_type,expected:nn.symbol,received:n.parsedType}),Di}return E0(e.data)}};mU.create=t=>new mU({typeName:ki.ZodSymbol,...Mo(t)});kD=class extends Ko{_parse(e){if(this._getType(e)!==nn.undefined){let n=this._getOrReturnCtx(e);return Yr(n,{code:yr.invalid_type,expected:nn.undefined,received:n.parsedType}),Di}return E0(e.data)}};kD.create=t=>new kD({typeName:ki.ZodUndefined,...Mo(t)});MD=class extends Ko{_parse(e){if(this._getType(e)!==nn.null){let n=this._getOrReturnCtx(e);return Yr(n,{code:yr.invalid_type,expected:nn.null,received:n.parsedType}),Di}return E0(e.data)}};MD.create=t=>new MD({typeName:ki.ZodNull,...Mo(t)});sS=class extends Ko{constructor(){super(...arguments),this._any=!0}_parse(e){return E0(e.data)}};sS.create=t=>new sS({typeName:ki.ZodAny,...Mo(t)});Y8=class extends Ko{constructor(){super(...arguments),this._unknown=!0}_parse(e){return E0(e.data)}};Y8.create=t=>new Y8({typeName:ki.ZodUnknown,...Mo(t)});c4=class extends Ko{_parse(e){let r=this._getOrReturnCtx(e);return Yr(r,{code:yr.invalid_type,expected:nn.never,received:r.parsedType}),Di}};c4.create=t=>new c4({typeName:ki.ZodNever,...Mo(t)});gU=class extends Ko{_parse(e){if(this._getType(e)!==nn.undefined){let n=this._getOrReturnCtx(e);return Yr(n,{code:yr.invalid_type,expected:nn.void,received:n.parsedType}),Di}return E0(e.data)}};gU.create=t=>new gU({typeName:ki.ZodVoid,...Mo(t)});J8=class t extends Ko{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==nn.array)return Yr(r,{code:yr.invalid_type,expected:nn.array,received:r.parsedType}),Di;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Yr(r,{code:s?yr.too_big:yr.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Yr(r,{code:yr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Yr(r,{code:yr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new D3(r,s,r.path,a)))).then(s=>Ih.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new D3(r,s,r.path,a)));return Ih.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Mn.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Mn.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Mn.toString(r)}})}nonempty(e){return this.min(1,e)}};J8.create=(t,e)=>new J8({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ki.ZodArray,...Mo(e)});jg=class t extends Ko{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ws.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==nn.object){let u=this._getOrReturnCtx(e);return Yr(u,{code:yr.invalid_type,expected:nn.object,received:u.parsedType}),Di}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof c4&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],f=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new D3(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof c4){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Yr(i,{code:yr.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let f=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new D3(i,f,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let f=await d.key,p=await d.value;u.push({key:f,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>Ih.mergeObjectSync(n,u)):Ih.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return Mn.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Mn.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ki.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ws.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ws.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return hU(this)}partial(e){let r={};for(let n of ws.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ws.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof I3;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return _Mt(ws.objectKeys(this.shape))}};jg.create=(t,e)=>new jg({shape:()=>t,unknownKeys:"strip",catchall:c4.create(),typeName:ki.ZodObject,...Mo(e)});jg.strictCreate=(t,e)=>new jg({shape:()=>t,unknownKeys:"strict",catchall:c4.create(),typeName:ki.ZodObject,...Mo(e)});jg.lazycreate=(t,e)=>new jg({shape:t,unknownKeys:"strip",catchall:c4.create(),typeName:ki.ZodObject,...Mo(e)});PD=class extends Ko{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new $g(a.ctx.common.issues));return Yr(r,{code:yr.invalid_union,unionErrors:s}),Di}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new $g(c));return Yr(r,{code:yr.invalid_union,unionErrors:a}),Di}}get options(){return this._def.options}};PD.create=(t,e)=>new PD({options:t,typeName:ki.ZodUnion,...Mo(e)});z8=t=>t instanceof FD?z8(t.schema):t instanceof R3?z8(t.innerType()):t instanceof UD?[t.value]:t instanceof QD?t.options:t instanceof qD?ws.objectValues(t.enum):t instanceof GD?z8(t._def.innerType):t instanceof kD?[void 0]:t instanceof MD?[null]:t instanceof I3?[void 0,...z8(t.unwrap())]:t instanceof B5?[null,...z8(t.unwrap())]:t instanceof lX||t instanceof VD?z8(t.unwrap()):t instanceof HD?z8(t._def.innerType):[],R0e=class t extends Ko{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==nn.object)return Yr(r,{code:yr.invalid_type,expected:nn.object,received:r.parsedType}),Di;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Yr(r,{code:yr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Di)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=z8(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:ki.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Mo(n)})}};LD=class extends Ko{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(I0e(o)||I0e(s))return Di;let a=ZFe(o.value,s.value);return a.valid?((D0e(o)||D0e(s))&&r.dirty(),{status:r.value,value:a.data}):(Yr(n,{code:yr.invalid_intersection_types}),Di)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};LD.create=(t,e,r)=>new LD({left:t,right:e,typeName:ki.ZodIntersection,...Mo(r)});R5=class t extends Ko{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==nn.array)return Yr(n,{code:yr.invalid_type,expected:nn.array,received:n.parsedType}),Di;if(n.data.length<this._def.items.length)return Yr(n,{code:yr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Di;!this._def.rest&&n.data.length>this._def.items.length&&(Yr(n,{code:yr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new D3(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Ih.mergeArray(r,s)):Ih.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};R5.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new R5({items:t,typeName:ki.ZodTuple,rest:null,...Mo(e)})};B0e=class t extends Ko{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==nn.object)return Yr(n,{code:yr.invalid_type,expected:nn.object,received:n.parsedType}),Di;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new D3(n,a,n.path,a)),value:s._parse(new D3(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ih.mergeObjectAsync(r,i):Ih.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ko?new t({keyType:e,valueType:r,typeName:ki.ZodRecord,...Mo(n)}):new t({keyType:oS.create(),valueType:e,typeName:ki.ZodRecord,...Mo(r)})}},AU=class extends Ko{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==nn.map)return Yr(n,{code:yr.invalid_type,expected:nn.map,received:n.parsedType}),Di;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new D3(n,a,n.path,[u,"key"])),value:o._parse(new D3(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return Di;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return Di;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};AU.create=(t,e,r)=>new AU({valueType:e,keyType:t,typeName:ki.ZodMap,...Mo(r)});yU=class t extends Ko{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==nn.set)return Yr(n,{code:yr.invalid_type,expected:nn.set,received:n.parsedType}),Di;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Yr(n,{code:yr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Yr(n,{code:yr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return Di;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new D3(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:Mn.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Mn.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};yU.create=(t,e)=>new yU({valueType:t,minSize:null,maxSize:null,typeName:ki.ZodSet,...Mo(e)});N0e=class t extends Ko{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==nn.function)return Yr(r,{code:yr.invalid_type,expected:nn.function,received:r.parsedType}),Di;function n(a,c){return aX({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fU(),j8].filter(u=>!!u),issueData:{code:yr.invalid_arguments,argumentsError:c}})}function i(a,c){return aX({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fU(),j8].filter(u=>!!u),issueData:{code:yr.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof aS){let a=this;return E0(async function(...c){let u=new $g([]),d=await a._def.args.parseAsync(c,o).catch(h=>{throw u.addIssue(n(c,h)),u}),f=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(f,o).catch(h=>{throw u.addIssue(i(f,h)),u})})}else{let a=this;return E0(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new $g([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),f=a._def.returns.safeParse(d,o);if(!f.success)throw new $g([i(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:R5.create(e).rest(Y8.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||R5.create([]).rest(Y8.create()),returns:r||Y8.create(),typeName:ki.ZodFunction,...Mo(n)})}},FD=class extends Ko{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};FD.create=(t,e)=>new FD({getter:t,typeName:ki.ZodLazy,...Mo(e)});UD=class extends Ko{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Yr(r,{received:r.data,code:yr.invalid_literal,expected:this._def.value}),Di}return{status:"valid",value:e.data}}get value(){return this._def.value}};UD.create=(t,e)=>new UD({value:t,typeName:ki.ZodLiteral,...Mo(e)});QD=class t extends Ko{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Yr(r,{expected:ws.joinValues(n),received:r.parsedType,code:yr.invalid_type}),Di}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Yr(r,{received:r.data,code:yr.invalid_enum_value,options:n}),Di}return E0(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};QD.create=_Mt;qD=class extends Ko{_parse(e){let r=ws.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==nn.string&&n.parsedType!==nn.number){let i=ws.objectValues(r);return Yr(n,{expected:ws.joinValues(i),received:n.parsedType,code:yr.invalid_type}),Di}if(this._cache||(this._cache=new Set(ws.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ws.objectValues(r);return Yr(n,{received:n.data,code:yr.invalid_enum_value,options:i}),Di}return E0(e.data)}get enum(){return this._def.values}};qD.create=(t,e)=>new qD({values:t,typeName:ki.ZodNativeEnum,...Mo(e)});aS=class extends Ko{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==nn.promise&&r.common.async===!1)return Yr(r,{code:yr.invalid_type,expected:nn.promise,received:r.parsedType}),Di;let n=r.parsedType===nn.promise?r.data:Promise.resolve(r.data);return E0(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};aS.create=(t,e)=>new aS({type:t,typeName:ki.ZodPromise,...Mo(e)});R3=class extends Ko{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ki.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{Yr(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return Di;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?Di:c.status==="dirty"?DD(c.value):r.value==="dirty"?DD(c.value):c});{if(r.value==="aborted")return Di;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?Di:a.status==="dirty"?DD(a.value):r.value==="dirty"?DD(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Di:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Di:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!iS(s))return Di;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>iS(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):Di);ws.assertNever(i)}};R3.create=(t,e,r)=>new R3({schema:t,typeName:ki.ZodEffects,effect:e,...Mo(r)});R3.createWithPreprocess=(t,e,r)=>new R3({schema:e,effect:{type:"preprocess",transform:t},typeName:ki.ZodEffects,...Mo(r)});I3=class extends Ko{_parse(e){return this._getType(e)===nn.undefined?E0(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I3.create=(t,e)=>new I3({innerType:t,typeName:ki.ZodOptional,...Mo(e)});B5=class extends Ko{_parse(e){return this._getType(e)===nn.null?E0(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};B5.create=(t,e)=>new B5({innerType:t,typeName:ki.ZodNullable,...Mo(e)});GD=class extends Ko{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===nn.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};GD.create=(t,e)=>new GD({innerType:t,typeName:ki.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Mo(e)});HD=class extends Ko{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return pU(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $g(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new $g(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};HD.create=(t,e)=>new HD({innerType:t,typeName:ki.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Mo(e)});EU=class extends Ko{_parse(e){if(this._getType(e)!==nn.nan){let n=this._getOrReturnCtx(e);return Yr(n,{code:yr.invalid_type,expected:nn.nan,received:n.parsedType}),Di}return{status:"valid",value:e.data}}};EU.create=t=>new EU({typeName:ki.ZodNaN,...Mo(t)});Ikn=Symbol("zod_brand"),lX=class extends Ko{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},cX=class t extends Ko{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Di:o.status==="dirty"?(r.dirty(),DD(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Di:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:ki.ZodPipeline})}},VD=class extends Ko{_parse(e){let r=this._def.innerType._parse(e),n=i=>(iS(i)&&(i.value=Object.freeze(i.value)),i);return pU(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};VD.create=(t,e)=>new VD({innerType:t,typeName:ki.ZodReadonly,...Mo(e)});Dkn={object:jg.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ki||(ki={}));Rkn=(t,e={message:`Input not instance of ${t.name}`})=>TMt(r=>r instanceof t,e),IMt=oS.create,DMt=RD.create,Bkn=EU.create,Nkn=BD.create,RMt=ND.create,Okn=OD.create,kkn=mU.create,Mkn=kD.create,Pkn=MD.create,Lkn=sS.create,Fkn=Y8.create,Ukn=c4.create,Qkn=gU.create,qkn=J8.create,Gkn=jg.create,Hkn=jg.strictCreate,Vkn=PD.create,Wkn=R0e.create,$kn=LD.create,jkn=R5.create,zkn=B0e.create,Ykn=AU.create,Jkn=yU.create,Kkn=N0e.create,Xkn=FD.create,Zkn=UD.create,eMn=QD.create,tMn=qD.create,rMn=aS.create,nMn=R3.create,iMn=I3.create,oMn=B5.create,sMn=R3.createWithPreprocess,aMn=cX.create,lMn=()=>IMt().optional(),cMn=()=>DMt().optional(),uMn=()=>RMt().optional(),dMn={string:(t=>oS.create({...t,coerce:!0})),number:(t=>RD.create({...t,coerce:!0})),boolean:(t=>ND.create({...t,coerce:!0})),bigint:(t=>BD.create({...t,coerce:!0})),date:(t=>OD.create({...t,coerce:!0}))},fMn=Di});var te={};Uf(te,{BRAND:()=>Ikn,DIRTY:()=>DD,EMPTY_PATH:()=>skn,INVALID:()=>Di,NEVER:()=>fMn,OK:()=>E0,ParseStatus:()=>Ih,Schema:()=>Ko,ZodAny:()=>sS,ZodArray:()=>J8,ZodBigInt:()=>BD,ZodBoolean:()=>ND,ZodBranded:()=>lX,ZodCatch:()=>HD,ZodDate:()=>OD,ZodDefault:()=>GD,ZodDiscriminatedUnion:()=>R0e,ZodEffects:()=>R3,ZodEnum:()=>QD,ZodError:()=>$g,ZodFirstPartyTypeKind:()=>ki,ZodFunction:()=>N0e,ZodIntersection:()=>LD,ZodIssueCode:()=>yr,ZodLazy:()=>FD,ZodLiteral:()=>UD,ZodMap:()=>AU,ZodNaN:()=>EU,ZodNativeEnum:()=>qD,ZodNever:()=>c4,ZodNull:()=>MD,ZodNullable:()=>B5,ZodNumber:()=>RD,ZodObject:()=>jg,ZodOptional:()=>I3,ZodParsedType:()=>nn,ZodPipeline:()=>cX,ZodPromise:()=>aS,ZodReadonly:()=>VD,ZodRecord:()=>B0e,ZodSchema:()=>Ko,ZodSet:()=>yU,ZodString:()=>oS,ZodSymbol:()=>mU,ZodTransformer:()=>R3,ZodTuple:()=>R5,ZodType:()=>Ko,ZodUndefined:()=>kD,ZodUnion:()=>PD,ZodUnknown:()=>Y8,ZodVoid:()=>gU,addIssueToContext:()=>Yr,any:()=>Lkn,array:()=>qkn,bigint:()=>Nkn,boolean:()=>RMt,coerce:()=>dMn,custom:()=>TMt,date:()=>Okn,datetimeRegex:()=>SMt,defaultErrorMap:()=>j8,discriminatedUnion:()=>Wkn,effect:()=>nMn,enum:()=>eMn,function:()=>Kkn,getErrorMap:()=>fU,getParsedType:()=>D5,instanceof:()=>Rkn,intersection:()=>$kn,isAborted:()=>I0e,isAsync:()=>pU,isDirty:()=>D0e,isValid:()=>iS,late:()=>Dkn,lazy:()=>Xkn,literal:()=>Zkn,makeIssue:()=>aX,map:()=>Ykn,nan:()=>Bkn,nativeEnum:()=>tMn,never:()=>Ukn,null:()=>Pkn,nullable:()=>oMn,number:()=>DMt,object:()=>Gkn,objectUtil:()=>YFe,oboolean:()=>uMn,onumber:()=>cMn,optional:()=>iMn,ostring:()=>lMn,pipeline:()=>aMn,preprocess:()=>sMn,promise:()=>rMn,quotelessJson:()=>nkn,record:()=>zkn,set:()=>Jkn,setErrorMap:()=>okn,strictObject:()=>Hkn,string:()=>IMt,symbol:()=>kkn,transformer:()=>nMn,tuple:()=>jkn,undefined:()=>Mkn,union:()=>Vkn,unknown:()=>Fkn,util:()=>ws,void:()=>Qkn});var eUe=ae(()=>{T0e();KFe();EMt();sX();BMt();_0e()});var lS=ae(()=>{eUe();eUe()});var vU,NMt,O0e,OMt,kMt,pMn,O3,zg,uX,N5,k3,k0e,MMt,M0e,PMt,LMt,FMt,dX,B3,UMt,QMt,cS,WD,P0e,fX,qMt,hMn,mMn,gMn,tUe,GMt,HMt,L0e,AMn,F0e,U0e,Q0e,VMt,WMt,rUe,$Mt,jMt,yMn,EMn,nUe,vMn,iUe,CMn,oUe,bMn,xMn,wMn,SMn,_Mn,TMn,IMn,pX,DMn,sUe,aUe,lUe,RMn,BMn,zMt,NMn,hX,OMn,kMn,MMn,PMn,cUe,q0e,fFo,LMn,FMn,YMt,UMn,QMn,qMn,GMn,HMn,VMn,WMn,$Mn,jMn,zMn,YMn,JMn,KMn,XMn,ZMn,ePn,tPn,uUe,rPn,G0e,nPn,iPn,pFo,hFo,mFo,gFo,AFo,yFo,N3,uS=ae(()=>{lS();vU="2025-06-18",NMt=[vU,"2025-03-26","2024-11-05","2024-10-07"],O0e="2.0",OMt=te.union([te.string(),te.number().int()]),kMt=te.string(),pMn=te.object({progressToken:te.optional(OMt)}).passthrough(),O3=te.object({_meta:te.optional(pMn)}).passthrough(),zg=te.object({method:te.string(),params:te.optional(O3)}),uX=te.object({_meta:te.optional(te.object({}).passthrough())}).passthrough(),N5=te.object({method:te.string(),params:te.optional(uX)}),k3=te.object({_meta:te.optional(te.object({}).passthrough())}).passthrough(),k0e=te.union([te.string(),te.number().int()]),MMt=te.object({jsonrpc:te.literal(O0e),id:k0e}).merge(zg).strict(),M0e=t=>MMt.safeParse(t).success,PMt=te.object({jsonrpc:te.literal(O0e)}).merge(N5).strict(),LMt=t=>PMt.safeParse(t).success,FMt=te.object({jsonrpc:te.literal(O0e),id:k0e,result:k3}).strict(),dX=t=>FMt.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(B3||(B3={}));UMt=te.object({jsonrpc:te.literal(O0e),id:k0e,error:te.object({code:te.number().int(),message:te.string(),data:te.optional(te.unknown())})}).strict(),QMt=t=>UMt.safeParse(t).success,cS=te.union([MMt,PMt,FMt,UMt]),WD=k3.strict(),P0e=N5.extend({method:te.literal("notifications/cancelled"),params:uX.extend({requestId:k0e,reason:te.string().optional()})}),fX=te.object({name:te.string(),title:te.optional(te.string())}).passthrough(),qMt=fX.extend({version:te.string()}),hMn=te.object({experimental:te.optional(te.object({}).passthrough()),sampling:te.optional(te.object({}).passthrough()),elicitation:te.optional(te.object({}).passthrough()),roots:te.optional(te.object({listChanged:te.optional(te.boolean())}).passthrough())}).passthrough(),mMn=zg.extend({method:te.literal("initialize"),params:O3.extend({protocolVersion:te.string(),capabilities:hMn,clientInfo:qMt})}),gMn=te.object({experimental:te.optional(te.object({}).passthrough()),logging:te.optional(te.object({}).passthrough()),completions:te.optional(te.object({}).passthrough()),prompts:te.optional(te.object({listChanged:te.optional(te.boolean())}).passthrough()),resources:te.optional(te.object({subscribe:te.optional(te.boolean()),listChanged:te.optional(te.boolean())}).passthrough()),tools:te.optional(te.object({listChanged:te.optional(te.boolean())}).passthrough())}).passthrough(),tUe=k3.extend({protocolVersion:te.string(),capabilities:gMn,serverInfo:qMt,instructions:te.optional(te.string())}),GMt=N5.extend({method:te.literal("notifications/initialized")}),HMt=t=>GMt.safeParse(t).success,L0e=zg.extend({method:te.literal("ping")}),AMn=te.object({progress:te.number(),total:te.optional(te.number()),message:te.optional(te.string())}).passthrough(),F0e=N5.extend({method:te.literal("notifications/progress"),params:uX.merge(AMn).extend({progressToken:OMt})}),U0e=zg.extend({params:O3.extend({cursor:te.optional(kMt)}).optional()}),Q0e=k3.extend({nextCursor:te.optional(kMt)}),VMt=te.object({uri:te.string(),mimeType:te.optional(te.string()),_meta:te.optional(te.object({}).passthrough())}).passthrough(),WMt=VMt.extend({text:te.string()}),rUe=te.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),$Mt=VMt.extend({blob:rUe}),jMt=fX.extend({uri:te.string(),description:te.optional(te.string()),mimeType:te.optional(te.string()),_meta:te.optional(te.object({}).passthrough())}),yMn=fX.extend({uriTemplate:te.string(),description:te.optional(te.string()),mimeType:te.optional(te.string()),_meta:te.optional(te.object({}).passthrough())}),EMn=U0e.extend({method:te.literal("resources/list")}),nUe=Q0e.extend({resources:te.array(jMt)}),vMn=U0e.extend({method:te.literal("resources/templates/list")}),iUe=Q0e.extend({resourceTemplates:te.array(yMn)}),CMn=zg.extend({method:te.literal("resources/read"),params:O3.extend({uri:te.string()})}),oUe=k3.extend({contents:te.array(te.union([WMt,$Mt]))}),bMn=N5.extend({method:te.literal("notifications/resources/list_changed")}),xMn=zg.extend({method:te.literal("resources/subscribe"),params:O3.extend({uri:te.string()})}),wMn=zg.extend({method:te.literal("resources/unsubscribe"),params:O3.extend({uri:te.string()})}),SMn=N5.extend({method:te.literal("notifications/resources/updated"),params:uX.extend({uri:te.string()})}),_Mn=te.object({name:te.string(),description:te.optional(te.string()),required:te.optional(te.boolean())}).passthrough(),TMn=fX.extend({description:te.optional(te.string()),arguments:te.optional(te.array(_Mn)),_meta:te.optional(te.object({}).passthrough())}),IMn=U0e.extend({method:te.literal("prompts/list")}),pX=Q0e.extend({prompts:te.array(TMn)}),DMn=zg.extend({method:te.literal("prompts/get"),params:O3.extend({name:te.string(),arguments:te.optional(te.record(te.string()))})}),sUe=te.object({type:te.literal("text"),text:te.string(),_meta:te.optional(te.object({}).passthrough())}).passthrough(),aUe=te.object({type:te.literal("image"),data:rUe,mimeType:te.string(),_meta:te.optional(te.object({}).passthrough())}).passthrough(),lUe=te.object({type:te.literal("audio"),data:rUe,mimeType:te.string(),_meta:te.optional(te.object({}).passthrough())}).passthrough(),RMn=te.object({type:te.literal("resource"),resource:te.union([WMt,$Mt]),_meta:te.optional(te.object({}).passthrough())}).passthrough(),BMn=jMt.extend({type:te.literal("resource_link")}),zMt=te.union([sUe,aUe,lUe,BMn,RMn]),NMn=te.object({role:te.enum(["user","assistant"]),content:zMt}).passthrough(),hX=k3.extend({description:te.optional(te.string()),messages:te.array(NMn)}),OMn=N5.extend({method:te.literal("notifications/prompts/list_changed")}),kMn=te.object({title:te.optional(te.string()),readOnlyHint:te.optional(te.boolean()),destructiveHint:te.optional(te.boolean()),idempotentHint:te.optional(te.boolean()),openWorldHint:te.optional(te.boolean())}).passthrough(),MMn=fX.extend({description:te.optional(te.string()),inputSchema:te.object({type:te.literal("object"),properties:te.optional(te.object({}).passthrough()),required:te.optional(te.array(te.string()))}).passthrough(),outputSchema:te.optional(te.object({type:te.literal("object"),properties:te.optional(te.object({}).passthrough()),required:te.optional(te.array(te.string()))}).passthrough()),annotations:te.optional(kMn),_meta:te.optional(te.object({}).passthrough())}),PMn=U0e.extend({method:te.literal("tools/list")}),cUe=Q0e.extend({tools:te.array(MMn)}),q0e=k3.extend({content:te.array(zMt).default([]),structuredContent:te.object({}).passthrough().optional(),isError:te.optional(te.boolean())}),fFo=q0e.or(k3.extend({toolResult:te.unknown()})),LMn=zg.extend({method:te.literal("tools/call"),params:O3.extend({name:te.string(),arguments:te.optional(te.record(te.unknown()))})}),FMn=N5.extend({method:te.literal("notifications/tools/list_changed")}),YMt=te.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),UMn=zg.extend({method:te.literal("logging/setLevel"),params:O3.extend({level:YMt})}),QMn=N5.extend({method:te.literal("notifications/message"),params:uX.extend({level:YMt,logger:te.optional(te.string()),data:te.unknown()})}),qMn=te.object({name:te.string().optional()}).passthrough(),GMn=te.object({hints:te.optional(te.array(qMn)),costPriority:te.optional(te.number().min(0).max(1)),speedPriority:te.optional(te.number().min(0).max(1)),intelligencePriority:te.optional(te.number().min(0).max(1))}).passthrough(),HMn=te.object({role:te.enum(["user","assistant"]),content:te.union([sUe,aUe,lUe])}).passthrough(),VMn=zg.extend({method:te.literal("sampling/createMessage"),params:O3.extend({messages:te.array(HMn),systemPrompt:te.optional(te.string()),includeContext:te.optional(te.enum(["none","thisServer","allServers"])),temperature:te.optional(te.number()),maxTokens:te.number().int(),stopSequences:te.optional(te.array(te.string())),metadata:te.optional(te.object({}).passthrough()),modelPreferences:te.optional(GMn)})}),WMn=k3.extend({model:te.string(),stopReason:te.optional(te.enum(["endTurn","stopSequence","maxTokens"]).or(te.string())),role:te.enum(["user","assistant"]),content:te.discriminatedUnion("type",[sUe,aUe,lUe])}),$Mn=te.object({type:te.literal("boolean"),title:te.optional(te.string()),description:te.optional(te.string()),default:te.optional(te.boolean())}).passthrough(),jMn=te.object({type:te.literal("string"),title:te.optional(te.string()),description:te.optional(te.string()),minLength:te.optional(te.number()),maxLength:te.optional(te.number()),format:te.optional(te.enum(["email","uri","date","date-time"]))}).passthrough(),zMn=te.object({type:te.enum(["number","integer"]),title:te.optional(te.string()),description:te.optional(te.string()),minimum:te.optional(te.number()),maximum:te.optional(te.number())}).passthrough(),YMn=te.object({type:te.literal("string"),title:te.optional(te.string()),description:te.optional(te.string()),enum:te.array(te.string()),enumNames:te.optional(te.array(te.string()))}).passthrough(),JMn=te.union([$Mn,jMn,zMn,YMn]),KMn=zg.extend({method:te.literal("elicitation/create"),params:O3.extend({message:te.string(),requestedSchema:te.object({type:te.literal("object"),properties:te.record(te.string(),JMn),required:te.optional(te.array(te.string()))}).passthrough()})}),XMn=k3.extend({action:te.enum(["accept","decline","cancel"]),content:te.optional(te.record(te.string(),te.unknown()))}),ZMn=te.object({type:te.literal("ref/resource"),uri:te.string()}).passthrough(),ePn=te.object({type:te.literal("ref/prompt"),name:te.string()}).passthrough(),tPn=zg.extend({method:te.literal("completion/complete"),params:O3.extend({ref:te.union([ePn,ZMn]),argument:te.object({name:te.string(),value:te.string()}).passthrough(),context:te.optional(te.object({arguments:te.optional(te.record(te.string(),te.string()))}))})}),uUe=k3.extend({completion:te.object({values:te.array(te.string()).max(100),total:te.optional(te.number().int()),hasMore:te.optional(te.boolean())}).passthrough()}),rPn=te.object({uri:te.string().startsWith("file://"),name:te.optional(te.string()),_meta:te.optional(te.object({}).passthrough())}).passthrough(),G0e=zg.extend({method:te.literal("roots/list")}),nPn=k3.extend({roots:te.array(rPn)}),iPn=N5.extend({method:te.literal("notifications/roots/list_changed")}),pFo=te.union([L0e,mMn,tPn,UMn,DMn,IMn,EMn,vMn,CMn,xMn,wMn,LMn,PMn]),hFo=te.union([P0e,F0e,GMt,iPn]),mFo=te.union([WD,WMn,XMn,nPn]),gFo=te.union([L0e,VMn,KMn,G0e]),AFo=te.union([P0e,F0e,QMn,SMn,bMn,FMn,OMn]),yFo=te.union([WD,tUe,uUe,hX,pX,nUe,iUe,oUe,q0e,cUe]),N3=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function JMt(t,e){return Object.entries(e).reduce((r,[n,i])=>(i&&typeof i=="object"?r[n]=r[n]?{...r[n],...i}:i:r[n]=i,r),{...t})}var oPn,H0e,KMt=ae(()=>{uS();oPn=6e4,H0e=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(P0e,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(F0e,r=>{this._onprogress(r)}),this.setRequestHandler(L0e,r=>({}))}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N3(B3.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};let s=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{s?.(c),this._onerror(c)};let a=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{a?.(c,u),dX(c)||QMt(c)?this._onresponse(c):M0e(c)?this._onrequest(c,u):LMt(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new N3(B3.ConnectionClosed,"Connection closed");for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i;let o=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,s=this._transport;if(o===void 0){s?.send({jsonrpc:"2.0",id:e.id,error:{code:B3.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c={signal:a.signal,sessionId:s?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,d,f)=>this.request(u,d,{...f,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>o(e,c)).then(u=>{if(!a.signal.aborted)return s?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var d;if(!a.signal.aborted)return s?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:B3.InternalError,message:(d=u.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){s(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),dX(e))n(e);else{let i=new N3(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}=n??{};return new Promise((a,c)=>{var u,d,f,p,h,m;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=n?.signal)===null||d===void 0||d.throwIfAborted();let g=this._requestMessageId++,A={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),A.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:g}});let y=x=>{var T;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(T=this._transport)===null||T===void 0||T.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(x)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(O=>this._onerror(new Error(`Failed to send cancellation: ${O}`))),c(x)};this._responseHandlers.set(g,x=>{var T;if(!(!((T=n?.signal)===null||T===void 0)&&T.aborted)){if(x instanceof Error)return c(x);try{let O=r.parse(x.result);a(O)}catch(O){c(O)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var x;y((x=n?.signal)===null||x===void 0?void 0:x.reason)});let E=(h=n?.timeout)!==null&&h!==void 0?h:oPn,C=()=>y(new N3(B3.RequestTimeout,"Request timed out",{timeout:E}));this._setupTimeout(g,E,n?.maxTotalTimeout,C,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(A,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(x=>{this._cleanupTimeout(g),c(x)})})}async notification(e,r){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(d=>this._onerror(d))});return}let a={...e,jsonrpc:"2.0"};await this._transport.send(a,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>Promise.resolve(r(e.parse(i),o)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}});var ZMt=D((V0e,XMt)=>{(function(t,e){typeof V0e=="object"&&typeof XMt<"u"?e(V0e):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(V0e,(function(t){"use strict";function e(){for(var et=arguments.length,He=Array(et),rt=0;rt<et;rt++)He[rt]=arguments[rt];if(He.length>1){He[0]=He[0].slice(0,-1);for(var pt=He.length-1,gt=1;gt<pt;++gt)He[gt]=He[gt].slice(1,-1);return He[pt]=He[pt].slice(1),He.join("")}else return He[0]}function r(et){return"(?:"+et+")"}function n(et){return et===void 0?"undefined":et===null?"null":Object.prototype.toString.call(et).split(" ").pop().split("]").shift().toLowerCase()}function i(et){return et.toUpperCase()}function o(et){return et!=null?et instanceof Array?et:typeof et.length!="number"||et.split||et.setInterval||et.call?[et]:Array.prototype.slice.call(et):[]}function s(et,He){var rt=et;if(He)for(var pt in He)rt[pt]=He[pt];return rt}function a(et){var He="[A-Za-z]",rt="[\\x0D]",pt="[0-9]",gt="[\\x22]",jt=e(pt,"[A-Fa-f]"),Cr="[\\x0A]",qr="[\\x20]",mn=r(r("%[EFef]"+jt+"%"+jt+jt+"%"+jt+jt)+"|"+r("%[89A-Fa-f]"+jt+"%"+jt+jt)+"|"+r("%"+jt+jt)),Ai="[\\:\\/\\?\\#\\[\\]\\@]",li="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",ji=e(Ai,li),zi=et?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Rn=et?"[\\uE000-\\uF8FF]":"[]",Ii=e(He,pt,"[\\-\\.\\_\\~]",zi),Wo=r(He+e(He,pt,"[\\+\\-\\.]")+"*"),vo=r(r(mn+"|"+e(Ii,li,"[\\:]"))+"*"),Ll=r(r("25[0-5]")+"|"+r("2[0-4]"+pt)+"|"+r("1"+pt+pt)+"|"+r("[1-9]"+pt)+"|"+pt),La=r(r("25[0-5]")+"|"+r("2[0-4]"+pt)+"|"+r("1"+pt+pt)+"|"+r("0?[1-9]"+pt)+"|0?0?"+pt),Fl=r(La+"\\."+La+"\\."+La+"\\."+La),co=r(jt+"{1,4}"),hc=r(r(co+"\\:"+co)+"|"+Fl),Fo=r(r(co+"\\:")+"{6}"+hc),Li=r("\\:\\:"+r(co+"\\:")+"{5}"+hc),Ad=r(r(co)+"?\\:\\:"+r(co+"\\:")+"{4}"+hc),mc=r(r(r(co+"\\:")+"{0,1}"+co)+"?\\:\\:"+r(co+"\\:")+"{3}"+hc),yd=r(r(r(co+"\\:")+"{0,2}"+co)+"?\\:\\:"+r(co+"\\:")+"{2}"+hc),Ed=r(r(r(co+"\\:")+"{0,3}"+co)+"?\\:\\:"+co+"\\:"+hc),Fa=r(r(r(co+"\\:")+"{0,4}"+co)+"?\\:\\:"+hc),Vs=r(r(r(co+"\\:")+"{0,5}"+co)+"?\\:\\:"+co),gc=r(r(r(co+"\\:")+"{0,6}"+co)+"?\\:\\:"),Pe=r([Fo,Li,Ad,mc,yd,Ed,Fa,Vs,gc].join("|")),Ue=r(r(Ii+"|"+mn)+"+"),st=r(Pe+"\\%25"+Ue),ft=r(Pe+r("\\%25|\\%(?!"+jt+"{2})")+Ue),Ct=r("[vV]"+jt+"+\\."+e(Ii,li,"[\\:]")+"+"),kt=r("\\["+r(ft+"|"+Pe+"|"+Ct)+"\\]"),ir=r(r(mn+"|"+e(Ii,li))+"*"),tr=r(kt+"|"+Fl+"(?!"+ir+")|"+ir),mr=r(pt+"*"),gr=r(r(vo+"@")+"?"+tr+r("\\:"+mr)+"?"),Sr=r(mn+"|"+e(Ii,li,"[\\:\\@]")),On=r(Sr+"*"),Zi=r(Sr+"+"),ns=r(r(mn+"|"+e(Ii,li,"[\\@]"))+"+"),Bi=r(r("\\/"+On)+"*"),ml=r("\\/"+r(Zi+Bi)+"?"),Ac=r(ns+Bi),Kd=r(Zi+Bi),gl="(?!"+Sr+")",qA=r(Bi+"|"+ml+"|"+Ac+"|"+Kd+"|"+gl),hp=r(r(Sr+"|"+e("[\\/\\?]",Rn))+"*"),fh=r(r(Sr+"|[\\/\\?]")+"*"),Cm=r(r("\\/\\/"+gr+Bi)+"|"+ml+"|"+Kd+"|"+gl),m6=r(Wo+"\\:"+Cm+r("\\?"+hp)+"?"+r("\\#"+fh)+"?"),X2=r(r("\\/\\/"+gr+Bi)+"|"+ml+"|"+Ac+"|"+gl),Su=r(X2+r("\\?"+hp)+"?"+r("\\#"+fh)+"?"),Sg=r(m6+"|"+Su),_u=r(Wo+"\\:"+Cm+r("\\?"+hp)+"?"),Xd="^("+Wo+")\\:"+r(r("\\/\\/("+r("("+vo+")@")+"?("+tr+")"+r("\\:("+mr+")")+"?)")+"?("+Bi+"|"+ml+"|"+Kd+"|"+gl+")")+r("\\?("+hp+")")+"?"+r("\\#("+fh+")")+"?$",bm="^(){0}"+r(r("\\/\\/("+r("("+vo+")@")+"?("+tr+")"+r("\\:("+mr+")")+"?)")+"?("+Bi+"|"+ml+"|"+Ac+"|"+gl+")")+r("\\?("+hp+")")+"?"+r("\\#("+fh+")")+"?$",d0="^("+Wo+")\\:"+r(r("\\/\\/("+r("("+vo+")@")+"?("+tr+")"+r("\\:("+mr+")")+"?)")+"?("+Bi+"|"+ml+"|"+Kd+"|"+gl+")")+r("\\?("+hp+")")+"?$",Tu="^"+r("\\#("+fh+")")+"?$",_g="^"+r("("+vo+")@")+"?("+tr+")"+r("\\:("+mr+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",He,pt,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ii,li),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ii,li),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ii,li),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ii,li),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ii,li,"[\\:\\@\\/\\?]",Rn),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ii,li,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ii,li),"g"),UNRESERVED:new RegExp(Ii,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ii,ji),"g"),PCT_ENCODED:new RegExp(mn,"g"),IPV4ADDRESS:new RegExp("^("+Fl+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Pe+")"+r(r("\\%25|\\%(?!"+jt+"{2})")+"("+Ue+")")+"?\\]?$")}}var c=a(!1),u=a(!0),d=(function(){function et(He,rt){var pt=[],gt=!0,jt=!1,Cr=void 0;try{for(var qr=He[Symbol.iterator](),mn;!(gt=(mn=qr.next()).done)&&(pt.push(mn.value),!(rt&&pt.length===rt));gt=!0);}catch(Ai){jt=!0,Cr=Ai}finally{try{!gt&&qr.return&&qr.return()}finally{if(jt)throw Cr}}return pt}return function(He,rt){if(Array.isArray(He))return He;if(Symbol.iterator in Object(He))return et(He,rt);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),f=function(et){if(Array.isArray(et)){for(var He=0,rt=Array(et.length);He<et.length;He++)rt[He]=et[He];return rt}else return Array.from(et)},p=2147483647,h=36,m=1,g=26,A=38,y=700,E=72,C=128,x="-",T=/^xn--/,O=/[^\0-\x7E]/,N=/[\x2E\u3002\uFF0E\uFF61]/g,U={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=h-m,M=Math.floor,B=String.fromCharCode;function F(et){throw new RangeError(U[et])}function L(et,He){for(var rt=[],pt=et.length;pt--;)rt[pt]=He(et[pt]);return rt}function R(et,He){var rt=et.split("@"),pt="";rt.length>1&&(pt=rt[0]+"@",et=rt[1]),et=et.replace(N,".");var gt=et.split("."),jt=L(gt,He).join(".");return pt+jt}function q(et){for(var He=[],rt=0,pt=et.length;rt<pt;){var gt=et.charCodeAt(rt++);if(gt>=55296&&gt<=56319&&rt<pt){var jt=et.charCodeAt(rt++);(jt&64512)==56320?He.push(((gt&1023)<<10)+(jt&1023)+65536):(He.push(gt),rt--)}else He.push(gt)}return He}var Q=function(He){return String.fromCodePoint.apply(String,f(He))},V=function(He){return He-48<10?He-22:He-65<26?He-65:He-97<26?He-97:h},H=function(He,rt){return He+22+75*(He<26)-((rt!=0)<<5)},J=function(He,rt,pt){var gt=0;for(He=pt?M(He/y):He>>1,He+=M(He/rt);He>w*g>>1;gt+=h)He=M(He/w);return M(gt+(w+1)*He/(He+A))},X=function(He){var rt=[],pt=He.length,gt=0,jt=C,Cr=E,qr=He.lastIndexOf(x);qr<0&&(qr=0);for(var mn=0;mn<qr;++mn)He.charCodeAt(mn)>=128&&F("not-basic"),rt.push(He.charCodeAt(mn));for(var Ai=qr>0?qr+1:0;Ai<pt;){for(var li=gt,ji=1,zi=h;;zi+=h){Ai>=pt&&F("invalid-input");var Rn=V(He.charCodeAt(Ai++));(Rn>=h||Rn>M((p-gt)/ji))&&F("overflow"),gt+=Rn*ji;var Ii=zi<=Cr?m:zi>=Cr+g?g:zi-Cr;if(Rn<Ii)break;var Wo=h-Ii;ji>M(p/Wo)&&F("overflow"),ji*=Wo}var vo=rt.length+1;Cr=J(gt-li,vo,li==0),M(gt/vo)>p-jt&&F("overflow"),jt+=M(gt/vo),gt%=vo,rt.splice(gt++,0,jt)}return String.fromCodePoint.apply(String,rt)},he=function(He){var rt=[];He=q(He);var pt=He.length,gt=C,jt=0,Cr=E,qr=!0,mn=!1,Ai=void 0;try{for(var li=He[Symbol.iterator](),ji;!(qr=(ji=li.next()).done);qr=!0){var zi=ji.value;zi<128&&rt.push(B(zi))}}catch(ft){mn=!0,Ai=ft}finally{try{!qr&&li.return&&li.return()}finally{if(mn)throw Ai}}var Rn=rt.length,Ii=Rn;for(Rn&&rt.push(x);Ii<pt;){var Wo=p,vo=!0,Ll=!1,La=void 0;try{for(var Fl=He[Symbol.iterator](),co;!(vo=(co=Fl.next()).done);vo=!0){var hc=co.value;hc>=gt&&hc<Wo&&(Wo=hc)}}catch(ft){Ll=!0,La=ft}finally{try{!vo&&Fl.return&&Fl.return()}finally{if(Ll)throw La}}var Fo=Ii+1;Wo-gt>M((p-jt)/Fo)&&F("overflow"),jt+=(Wo-gt)*Fo,gt=Wo;var Li=!0,Ad=!1,mc=void 0;try{for(var yd=He[Symbol.iterator](),Ed;!(Li=(Ed=yd.next()).done);Li=!0){var Fa=Ed.value;if(Fa<gt&&++jt>p&&F("overflow"),Fa==gt){for(var Vs=jt,gc=h;;gc+=h){var Pe=gc<=Cr?m:gc>=Cr+g?g:gc-Cr;if(Vs<Pe)break;var Ue=Vs-Pe,st=h-Pe;rt.push(B(H(Pe+Ue%st,0))),Vs=M(Ue/st)}rt.push(B(H(Vs,0))),Cr=J(jt,Fo,Ii==Rn),jt=0,++Ii}}}catch(ft){Ad=!0,mc=ft}finally{try{!Li&&yd.return&&yd.return()}finally{if(Ad)throw mc}}++jt,++gt}return rt.join("")},Ce=function(He){return R(He,function(rt){return T.test(rt)?X(rt.slice(4).toLowerCase()):rt})},ge=function(He){return R(He,function(rt){return O.test(rt)?"xn--"+he(rt):rt})},be={version:"2.1.0",ucs2:{decode:q,encode:Q},decode:X,encode:he,toASCII:ge,toUnicode:Ce},xe={};function se(et){var He=et.charCodeAt(0),rt=void 0;return He<16?rt="%0"+He.toString(16).toUpperCase():He<128?rt="%"+He.toString(16).toUpperCase():He<2048?rt="%"+(He>>6|192).toString(16).toUpperCase()+"%"+(He&63|128).toString(16).toUpperCase():rt="%"+(He>>12|224).toString(16).toUpperCase()+"%"+(He>>6&63|128).toString(16).toUpperCase()+"%"+(He&63|128).toString(16).toUpperCase(),rt}function me(et){for(var He="",rt=0,pt=et.length;rt<pt;){var gt=parseInt(et.substr(rt+1,2),16);if(gt<128)He+=String.fromCharCode(gt),rt+=3;else if(gt>=194&&gt<224){if(pt-rt>=6){var jt=parseInt(et.substr(rt+4,2),16);He+=String.fromCharCode((gt&31)<<6|jt&63)}else He+=et.substr(rt,6);rt+=6}else if(gt>=224){if(pt-rt>=9){var Cr=parseInt(et.substr(rt+4,2),16),qr=parseInt(et.substr(rt+7,2),16);He+=String.fromCharCode((gt&15)<<12|(Cr&63)<<6|qr&63)}else He+=et.substr(rt,9);rt+=9}else He+=et.substr(rt,3),rt+=3}return He}function ve(et,He){function rt(pt){var gt=me(pt);return gt.match(He.UNRESERVED)?gt:pt}return et.scheme&&(et.scheme=String(et.scheme).replace(He.PCT_ENCODED,rt).toLowerCase().replace(He.NOT_SCHEME,"")),et.userinfo!==void 0&&(et.userinfo=String(et.userinfo).replace(He.PCT_ENCODED,rt).replace(He.NOT_USERINFO,se).replace(He.PCT_ENCODED,i)),et.host!==void 0&&(et.host=String(et.host).replace(He.PCT_ENCODED,rt).toLowerCase().replace(He.NOT_HOST,se).replace(He.PCT_ENCODED,i)),et.path!==void 0&&(et.path=String(et.path).replace(He.PCT_ENCODED,rt).replace(et.scheme?He.NOT_PATH:He.NOT_PATH_NOSCHEME,se).replace(He.PCT_ENCODED,i)),et.query!==void 0&&(et.query=String(et.query).replace(He.PCT_ENCODED,rt).replace(He.NOT_QUERY,se).replace(He.PCT_ENCODED,i)),et.fragment!==void 0&&(et.fragment=String(et.fragment).replace(He.PCT_ENCODED,rt).replace(He.NOT_FRAGMENT,se).replace(He.PCT_ENCODED,i)),et}function ee(et){return et.replace(/^0*(.*)/,"$1")||"0"}function ce(et,He){var rt=et.match(He.IPV4ADDRESS)||[],pt=d(rt,2),gt=pt[1];return gt?gt.split(".").map(ee).join("."):et}function Y(et,He){var rt=et.match(He.IPV6ADDRESS)||[],pt=d(rt,3),gt=pt[1],jt=pt[2];if(gt){for(var Cr=gt.toLowerCase().split("::").reverse(),qr=d(Cr,2),mn=qr[0],Ai=qr[1],li=Ai?Ai.split(":").map(ee):[],ji=mn.split(":").map(ee),zi=He.IPV4ADDRESS.test(ji[ji.length-1]),Rn=zi?7:8,Ii=ji.length-Rn,Wo=Array(Rn),vo=0;vo<Rn;++vo)Wo[vo]=li[vo]||ji[Ii+vo]||"";zi&&(Wo[Rn-1]=ce(Wo[Rn-1],He));var Ll=Wo.reduce(function(Fo,Li,Ad){if(!Li||Li==="0"){var mc=Fo[Fo.length-1];mc&&mc.index+mc.length===Ad?mc.length++:Fo.push({index:Ad,length:1})}return Fo},[]),La=Ll.sort(function(Fo,Li){return Li.length-Fo.length})[0],Fl=void 0;if(La&&La.length>1){var co=Wo.slice(0,La.index),hc=Wo.slice(La.index+La.length);Fl=co.join(":")+"::"+hc.join(":")}else Fl=Wo.join(":");return jt&&(Fl+="%"+jt),Fl}else return et}var re=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,ue="".match(/(){0}/)[1]===void 0;function Z(et){var He=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},rt={},pt=He.iri!==!1?u:c;He.reference==="suffix"&&(et=(He.scheme?He.scheme+":":"")+"//"+et);var gt=et.match(re);if(gt){ue?(rt.scheme=gt[1],rt.userinfo=gt[3],rt.host=gt[4],rt.port=parseInt(gt[5],10),rt.path=gt[6]||"",rt.query=gt[7],rt.fragment=gt[8],isNaN(rt.port)&&(rt.port=gt[5])):(rt.scheme=gt[1]||void 0,rt.userinfo=et.indexOf("@")!==-1?gt[3]:void 0,rt.host=et.indexOf("//")!==-1?gt[4]:void 0,rt.port=parseInt(gt[5],10),rt.path=gt[6]||"",rt.query=et.indexOf("?")!==-1?gt[7]:void 0,rt.fragment=et.indexOf("#")!==-1?gt[8]:void 0,isNaN(rt.port)&&(rt.port=et.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?gt[4]:void 0)),rt.host&&(rt.host=Y(ce(rt.host,pt),pt)),rt.scheme===void 0&&rt.userinfo===void 0&&rt.host===void 0&&rt.port===void 0&&!rt.path&&rt.query===void 0?rt.reference="same-document":rt.scheme===void 0?rt.reference="relative":rt.fragment===void 0?rt.reference="absolute":rt.reference="uri",He.reference&&He.reference!=="suffix"&&He.reference!==rt.reference&&(rt.error=rt.error||"URI is not a "+He.reference+" reference.");var jt=xe[(He.scheme||rt.scheme||"").toLowerCase()];if(!He.unicodeSupport&&(!jt||!jt.unicodeSupport)){if(rt.host&&(He.domainHost||jt&&jt.domainHost))try{rt.host=be.toASCII(rt.host.replace(pt.PCT_ENCODED,me).toLowerCase())}catch(Cr){rt.error=rt.error||"Host's domain name can not be converted to ASCII via punycode: "+Cr}ve(rt,c)}else ve(rt,pt);jt&&jt.parse&&jt.parse(rt,He)}else rt.error=rt.error||"URI can not be parsed.";return rt}function $(et,He){var rt=He.iri!==!1?u:c,pt=[];return et.userinfo!==void 0&&(pt.push(et.userinfo),pt.push("@")),et.host!==void 0&&pt.push(Y(ce(String(et.host),rt),rt).replace(rt.IPV6ADDRESS,function(gt,jt,Cr){return"["+jt+(Cr?"%25"+Cr:"")+"]"})),(typeof et.port=="number"||typeof et.port=="string")&&(pt.push(":"),pt.push(String(et.port))),pt.length?pt.join(""):void 0}var j=/^\.\.?\//,Ee=/^\/\.(\/|$)/,de=/^\/\.\.(\/|$)/,z=/^\/?(?:.|\n)*?(?=\/|$)/;function Te(et){for(var He=[];et.length;)if(et.match(j))et=et.replace(j,"");else if(et.match(Ee))et=et.replace(Ee,"/");else if(et.match(de))et=et.replace(de,"/"),He.pop();else if(et==="."||et==="..")et="";else{var rt=et.match(z);if(rt){var pt=rt[0];et=et.slice(pt.length),He.push(pt)}else throw new Error("Unexpected dot segment condition")}return He.join("")}function Be(et){var He=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},rt=He.iri?u:c,pt=[],gt=xe[(He.scheme||et.scheme||"").toLowerCase()];if(gt&&gt.serialize&&gt.serialize(et,He),et.host&&!rt.IPV6ADDRESS.test(et.host)){if(He.domainHost||gt&&gt.domainHost)try{et.host=He.iri?be.toUnicode(et.host):be.toASCII(et.host.replace(rt.PCT_ENCODED,me).toLowerCase())}catch(qr){et.error=et.error||"Host's domain name can not be converted to "+(He.iri?"Unicode":"ASCII")+" via punycode: "+qr}}ve(et,rt),He.reference!=="suffix"&&et.scheme&&(pt.push(et.scheme),pt.push(":"));var jt=$(et,He);if(jt!==void 0&&(He.reference!=="suffix"&&pt.push("//"),pt.push(jt),et.path&&et.path.charAt(0)!=="/"&&pt.push("/")),et.path!==void 0){var Cr=et.path;!He.absolutePath&&(!gt||!gt.absolutePath)&&(Cr=Te(Cr)),jt===void 0&&(Cr=Cr.replace(/^\/\//,"/%2F")),pt.push(Cr)}return et.query!==void 0&&(pt.push("?"),pt.push(et.query)),et.fragment!==void 0&&(pt.push("#"),pt.push(et.fragment)),pt.join("")}function Oe(et,He){var rt=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},pt=arguments[3],gt={};return pt||(et=Z(Be(et,rt),rt),He=Z(Be(He,rt),rt)),rt=rt||{},!rt.tolerant&&He.scheme?(gt.scheme=He.scheme,gt.userinfo=He.userinfo,gt.host=He.host,gt.port=He.port,gt.path=Te(He.path||""),gt.query=He.query):(He.userinfo!==void 0||He.host!==void 0||He.port!==void 0?(gt.userinfo=He.userinfo,gt.host=He.host,gt.port=He.port,gt.path=Te(He.path||""),gt.query=He.query):(He.path?(He.path.charAt(0)==="/"?gt.path=Te(He.path):((et.userinfo!==void 0||et.host!==void 0||et.port!==void 0)&&!et.path?gt.path="/"+He.path:et.path?gt.path=et.path.slice(0,et.path.lastIndexOf("/")+1)+He.path:gt.path=He.path,gt.path=Te(gt.path)),gt.query=He.query):(gt.path=et.path,He.query!==void 0?gt.query=He.query:gt.query=et.query),gt.userinfo=et.userinfo,gt.host=et.host,gt.port=et.port),gt.scheme=et.scheme),gt.fragment=He.fragment,gt}function ke(et,He,rt){var pt=s({scheme:"null"},rt);return Be(Oe(Z(et,pt),Z(He,pt),pt,!0),pt)}function le(et,He){return typeof et=="string"?et=Be(Z(et,He),He):n(et)==="object"&&(et=Z(Be(et,He),He)),et}function Ie(et,He,rt){return typeof et=="string"?et=Be(Z(et,rt),rt):n(et)==="object"&&(et=Be(et,rt)),typeof He=="string"?He=Be(Z(He,rt),rt):n(He)==="object"&&(He=Be(He,rt)),et===He}function De(et,He){return et&&et.toString().replace(!He||!He.iri?c.ESCAPE:u.ESCAPE,se)}function Re(et,He){return et&&et.toString().replace(!He||!He.iri?c.PCT_ENCODED:u.PCT_ENCODED,me)}var Ge={scheme:"http",domainHost:!0,parse:function(He,rt){return He.host||(He.error=He.error||"HTTP URIs must have a host."),He},serialize:function(He,rt){var pt=String(He.scheme).toLowerCase()==="https";return(He.port===(pt?443:80)||He.port==="")&&(He.port=void 0),He.path||(He.path="/"),He}},Ke={scheme:"https",domainHost:Ge.domainHost,parse:Ge.parse,serialize:Ge.serialize};function tt(et){return typeof et.secure=="boolean"?et.secure:String(et.scheme).toLowerCase()==="wss"}var ut={scheme:"ws",domainHost:!0,parse:function(He,rt){var pt=He;return pt.secure=tt(pt),pt.resourceName=(pt.path||"/")+(pt.query?"?"+pt.query:""),pt.path=void 0,pt.query=void 0,pt},serialize:function(He,rt){if((He.port===(tt(He)?443:80)||He.port==="")&&(He.port=void 0),typeof He.secure=="boolean"&&(He.scheme=He.secure?"wss":"ws",He.secure=void 0),He.resourceName){var pt=He.resourceName.split("?"),gt=d(pt,2),jt=gt[0],Cr=gt[1];He.path=jt&&jt!=="/"?jt:void 0,He.query=Cr,He.resourceName=void 0}return He.fragment=void 0,He}},ht={scheme:"wss",domainHost:ut.domainHost,parse:ut.parse,serialize:ut.serialize},Jt={},wr=!0,br="[A-Za-z0-9\\-\\.\\_\\~"+(wr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",fr="[0-9A-Fa-f]",St=r(r("%[EFef]"+fr+"%"+fr+fr+"%"+fr+fr)+"|"+r("%[89A-Fa-f]"+fr+"%"+fr+fr)+"|"+r("%"+fr+fr)),vr="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Kt="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",Ft=e(Kt,'[\\"\\\\]'),er="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",nr=new RegExp(br,"g"),Ar=new RegExp(St,"g"),bn=new RegExp(e("[^]",vr,"[\\.]",'[\\"]',Ft),"g"),Vr=new RegExp(e("[^]",br,er),"g"),Fr=Vr;function Kr(et){var He=me(et);return He.match(nr)?He:et}var ai={scheme:"mailto",parse:function(He,rt){var pt=He,gt=pt.to=pt.path?pt.path.split(","):[];if(pt.path=void 0,pt.query){for(var jt=!1,Cr={},qr=pt.query.split("&"),mn=0,Ai=qr.length;mn<Ai;++mn){var li=qr[mn].split("=");switch(li[0]){case"to":for(var ji=li[1].split(","),zi=0,Rn=ji.length;zi<Rn;++zi)gt.push(ji[zi]);break;case"subject":pt.subject=Re(li[1],rt);break;case"body":pt.body=Re(li[1],rt);break;default:jt=!0,Cr[Re(li[0],rt)]=Re(li[1],rt);break}}jt&&(pt.headers=Cr)}pt.query=void 0;for(var Ii=0,Wo=gt.length;Ii<Wo;++Ii){var vo=gt[Ii].split("@");if(vo[0]=Re(vo[0]),rt.unicodeSupport)vo[1]=Re(vo[1],rt).toLowerCase();else try{vo[1]=be.toASCII(Re(vo[1],rt).toLowerCase())}catch(Ll){pt.error=pt.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ll}gt[Ii]=vo.join("@")}return pt},serialize:function(He,rt){var pt=He,gt=o(He.to);if(gt){for(var jt=0,Cr=gt.length;jt<Cr;++jt){var qr=String(gt[jt]),mn=qr.lastIndexOf("@"),Ai=qr.slice(0,mn).replace(Ar,Kr).replace(Ar,i).replace(bn,se),li=qr.slice(mn+1);try{li=rt.iri?be.toUnicode(li):be.toASCII(Re(li,rt).toLowerCase())}catch(Ii){pt.error=pt.error||"Email address's domain name can not be converted to "+(rt.iri?"Unicode":"ASCII")+" via punycode: "+Ii}gt[jt]=Ai+"@"+li}pt.path=gt.join(",")}var ji=He.headers=He.headers||{};He.subject&&(ji.subject=He.subject),He.body&&(ji.body=He.body);var zi=[];for(var Rn in ji)ji[Rn]!==Jt[Rn]&&zi.push(Rn.replace(Ar,Kr).replace(Ar,i).replace(Vr,se)+"="+ji[Rn].replace(Ar,Kr).replace(Ar,i).replace(Fr,se));return zi.length&&(pt.query=zi.join("&")),pt}},gi=/^([^\:]+)\:(.*)/,Nn={scheme:"urn",parse:function(He,rt){var pt=He.path&&He.path.match(gi),gt=He;if(pt){var jt=rt.scheme||gt.scheme||"urn",Cr=pt[1].toLowerCase(),qr=pt[2],mn=jt+":"+(rt.nid||Cr),Ai=xe[mn];gt.nid=Cr,gt.nss=qr,gt.path=void 0,Ai&&(gt=Ai.parse(gt,rt))}else gt.error=gt.error||"URN can not be parsed.";return gt},serialize:function(He,rt){var pt=rt.scheme||He.scheme||"urn",gt=He.nid,jt=pt+":"+(rt.nid||gt),Cr=xe[jt];Cr&&(He=Cr.serialize(He,rt));var qr=He,mn=He.nss;return qr.path=(gt||rt.nid)+":"+mn,qr}},lo=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,$i={scheme:"urn:uuid",parse:function(He,rt){var pt=He;return pt.uuid=pt.nss,pt.nss=void 0,!rt.tolerant&&(!pt.uuid||!pt.uuid.match(lo))&&(pt.error=pt.error||"UUID is not valid."),pt},serialize:function(He,rt){var pt=He;return pt.nss=(He.uuid||"").toLowerCase(),pt}};xe[Ge.scheme]=Ge,xe[Ke.scheme]=Ke,xe[ut.scheme]=ut,xe[ht.scheme]=ht,xe[ai.scheme]=ai,xe[Nn.scheme]=Nn,xe[$i.scheme]=$i,t.SCHEMES=xe,t.pctEncChar=se,t.pctDecChars=me,t.parse=Z,t.removeDotSegments=Te,t.serialize=Be,t.resolveComponents=Oe,t.resolve=ke,t.normalize=le,t.equal=Ie,t.escapeComponent=De,t.unescapeComponent=Re,Object.defineProperty(t,"__esModule",{value:!0})}))});var CU=D((bFo,ePt)=>{"use strict";ePt.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var rPt=D((xFo,tPt)=>{"use strict";tPt.exports=function(e){for(var r=0,n=e.length,i=0,o;i<n;)r++,o=e.charCodeAt(i++),o>=55296&&o<=56319&&i<n&&(o=e.charCodeAt(i),(o&64512)==56320&&i++);return r}});var $D=D((wFo,oPt)=>{"use strict";oPt.exports={copy:sPn,checkDataType:dUe,checkDataTypes:aPn,coerceToTypes:lPn,toHash:pUe,getProperty:hUe,escapeQuotes:mUe,equal:CU(),ucs2length:rPt(),varOccurences:dPn,varReplace:fPn,schemaHasRules:pPn,schemaHasRulesExcept:hPn,schemaUnknownRules:mPn,toQuotedString:fUe,getPathExpr:gPn,getPath:APn,getData:vPn,unescapeFragment:CPn,unescapeJsonPointer:AUe,escapeFragment:bPn,escapeJsonPointer:gUe};function sPn(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function dUe(t,e,r,n){var i=n?" !== ":" === ",o=n?" || ":" && ",s=n?"!":"",a=n?"":"!";switch(t){case"null":return e+i+"null";case"array":return s+"Array.isArray("+e+")";case"object":return"("+s+e+o+"typeof "+e+i+'"object"'+o+a+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+i+'"number"'+o+a+"("+e+" % 1)"+o+e+i+e+(r?o+s+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+i+'"'+t+'"'+(r?o+s+"isFinite("+e+")":"")+")";default:return"typeof "+e+i+'"'+t+'"'}}function aPn(t,e,r){switch(t.length){case 1:return dUe(t[0],e,r,!0);default:var n="",i=pUe(t);i.array&&i.object&&(n=i.null?"(":"(!"+e+" || ",n+="typeof "+e+' !== "object")',delete i.null,delete i.array,delete i.object),i.number&&delete i.integer;for(var o in i)n+=(n?" && ":"")+dUe(o,e,r,!0);return n}}var nPt=pUe(["string","number","integer","boolean","null"]);function lPn(t,e){if(Array.isArray(e)){for(var r=[],n=0;n<e.length;n++){var i=e[n];(nPt[i]||t==="array"&&i==="array")&&(r[r.length]=i)}if(r.length)return r}else{if(nPt[e])return[e];if(t==="array"&&e==="array")return["array"]}}function pUe(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var cPn=/^[a-z$_][a-z$_0-9]*$/i,uPn=/'|\\/g;function hUe(t){return typeof t=="number"?"["+t+"]":cPn.test(t)?"."+t:"['"+mUe(t)+"']"}function mUe(t){return t.replace(uPn,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function dPn(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function fPn(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function pPn(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function hPn(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var n in t)if(n!=r&&e[n])return!0}function mPn(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function fUe(t){return"'"+mUe(t)+"'"}function gPn(t,e,r,n){var i=r?"'/' + "+e+(n?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):n?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return iPt(t,i)}function APn(t,e,r){var n=fUe(r?"/"+gUe(e):hUe(e));return iPt(t,n)}var yPn=/^\/(?:[^~]|~0|~1)*$/,EPn=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vPn(t,e,r){var n,i,o,s;if(t==="")return"rootData";if(t[0]=="/"){if(!yPn.test(t))throw new Error("Invalid JSON-pointer: "+t);i=t,o="rootData"}else{if(s=t.match(EPn),!s)throw new Error("Invalid JSON-pointer: "+t);if(n=+s[1],i=s[2],i=="#"){if(n>=e)throw new Error("Cannot access property/index "+n+" levels up, current level is "+e);return r[e-n]}if(n>e)throw new Error("Cannot access data "+n+" levels up, current level is "+e);if(o="data"+(e-n||""),!i)return o}for(var a=o,c=i.split("/"),u=0;u<c.length;u++){var d=c[u];d&&(o+=hUe(AUe(d)),a+=" && "+o)}return a}function iPt(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function CPn(t){return AUe(decodeURIComponent(t))}function bPn(t){return encodeURIComponent(gUe(t))}function gUe(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function AUe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}});var yUe=D((SFo,sPt)=>{"use strict";var xPn=$D();sPt.exports=wPn;function wPn(t){xPn.copy(t,this)}});var lPt=D((_Fo,aPt)=>{"use strict";var dS=aPt.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};W0e(e,n,i,t,"",t)};dS.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0};dS.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};dS.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};dS.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function W0e(t,e,r,n,i,o,s,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,o,s,a,c,u);for(var d in n){var f=n[d];if(Array.isArray(f)){if(d in dS.arrayKeywords)for(var p=0;p<f.length;p++)W0e(t,e,r,f[p],i+"/"+d+"/"+p,o,i,d,n,p)}else if(d in dS.propsKeywords){if(f&&typeof f=="object")for(var h in f)W0e(t,e,r,f[h],i+"/"+d+"/"+SPn(h),o,i,d,n,h)}else(d in dS.keywords||t.allKeys&&!(d in dS.skipKeywords))&&W0e(t,e,r,f,i+"/"+d,o,i,d,n)}r(n,i,o,s,a,c,u)}}function SPn(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var K0e=D((TFo,fPt)=>{"use strict";var mX=ZMt(),cPt=CU(),Y0e=$D(),$0e=yUe(),_Pn=lPt();fPt.exports=pS;pS.normalizeId=fS;pS.fullPath=j0e;pS.url=z0e;pS.ids=BPn;pS.inlineRef=EUe;pS.schema=J0e;function pS(t,e,r){var n=this._refs[r];if(typeof n=="string")if(this._refs[n])n=this._refs[n];else return pS.call(this,t,e,n);if(n=n||this._schemas[r],n instanceof $0e)return EUe(n.schema,this._opts.inlineRefs)?n.schema:n.validate||this._compile(n);var i=J0e.call(this,e,r),o,s,a;return i&&(o=i.schema,e=i.root,a=i.baseId),o instanceof $0e?s=o.validate||t.call(this,o.schema,e,void 0,a):o!==void 0&&(s=EUe(o,this._opts.inlineRefs)?o:t.call(this,o,e,void 0,a)),s}function J0e(t,e){var r=mX.parse(e),n=dPt(r),i=j0e(this._getId(t.schema));if(Object.keys(t.schema).length===0||n!==i){var o=fS(n),s=this._refs[o];if(typeof s=="string")return TPn.call(this,t,s,r);if(s instanceof $0e)s.validate||this._compile(s),t=s;else if(s=this._schemas[o],s instanceof $0e){if(s.validate||this._compile(s),o==fS(e))return{schema:s,root:t,baseId:i};t=s}else return;if(!t.schema)return;i=j0e(this._getId(t.schema))}return uPt.call(this,r,i,t.schema,t)}function TPn(t,e,r){var n=J0e.call(this,t,e);if(n){var i=n.schema,o=n.baseId;t=n.root;var s=this._getId(i);return s&&(o=z0e(o,s)),uPt.call(this,r,o,i,t)}}var IPn=Y0e.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function uPt(t,e,r,n){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var i=t.fragment.split("/"),o=1;o<i.length;o++){var s=i[o];if(s){if(s=Y0e.unescapeFragment(s),r=r[s],r===void 0)break;var a;if(!IPn[s]&&(a=this._getId(r),a&&(e=z0e(e,a)),r.$ref)){var c=z0e(e,r.$ref),u=J0e.call(this,n,c);u&&(r=u.schema,n=u.root,e=u.baseId)}}}if(r!==void 0&&r!==n.schema)return{schema:r,root:n,baseId:e}}}var DPn=Y0e.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function EUe(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return vUe(t);if(e)return CUe(t)<=e}function vUe(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!vUe(e))return!1}else for(var n in t)if(n=="$ref"||(e=t[n],typeof e=="object"&&!vUe(e)))return!1;return!0}function CUe(t){var e=0,r;if(Array.isArray(t)){for(var n=0;n<t.length;n++)if(r=t[n],typeof r=="object"&&(e+=CUe(r)),e==1/0)return 1/0}else for(var i in t){if(i=="$ref")return 1/0;if(DPn[i])e++;else if(r=t[i],typeof r=="object"&&(e+=CUe(r)+1),e==1/0)return 1/0}return e}function j0e(t,e){e!==!1&&(t=fS(t));var r=mX.parse(t);return dPt(r)}function dPt(t){return mX.serialize(t).split("#")[0]+"#"}var RPn=/#\/?$/;function fS(t){return t?t.replace(RPn,""):""}function z0e(t,e){return e=fS(e),mX.resolve(t,e)}function BPn(t){var e=fS(this._getId(t)),r={"":e},n={"":j0e(e,!1)},i={},o=this;return _Pn(t,{allKeys:!0},function(s,a,c,u,d,f,p){if(a!==""){var h=o._getId(s),m=r[u],g=n[u]+"/"+d;if(p!==void 0&&(g+="/"+(typeof p=="number"?p:Y0e.escapeFragment(p))),typeof h=="string"){h=m=fS(m?mX.resolve(m,h):h);var A=o._refs[h];if(typeof A=="string"&&(A=o._refs[A]),A&&A.schema){if(!cPt(s,A.schema))throw new Error('id "'+h+'" resolves to more than one schema')}else if(h!=fS(g))if(h[0]=="#"){if(i[h]&&!cPt(s,i[h]))throw new Error('id "'+h+'" resolves to more than one schema');i[h]=s}else o._refs[h]=g}r[a]=m,n[a]=g}}),i}});var X0e=D((IFo,hPt)=>{"use strict";var bUe=K0e();hPt.exports={Validation:pPt(NPn),MissingRef:pPt(xUe)};function NPn(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}xUe.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function xUe(t,e,r){this.message=r||xUe.message(t,e),this.missingRef=bUe.url(t,e),this.missingSchema=bUe.normalizeId(bUe.fullPath(this.missingRef))}function pPt(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}});var wUe=D((DFo,mPt)=>{"use strict";mPt.exports=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,n=e.cmp&&(function(o){return function(s){return function(a,c){var u={key:a,value:s[a]},d={key:c,value:s[c]};return o(u,d)}}})(e.cmp),i=[];return(function o(s){if(s&&s.toJSON&&typeof s.toJSON=="function"&&(s=s.toJSON()),s!==void 0){if(typeof s=="number")return isFinite(s)?""+s:"null";if(typeof s!="object")return JSON.stringify(s);var a,c;if(Array.isArray(s)){for(c="[",a=0;a<s.length;a++)a&&(c+=","),c+=o(s[a])||"null";return c+"]"}if(s===null)return"null";if(i.indexOf(s)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=i.push(s)-1,d=Object.keys(s).sort(n&&n(s));for(c="",a=0;a<d.length;a++){var f=d[a],p=o(s[f]);p&&(c&&(c+=","),c+=JSON.stringify(f)+":"+p)}return i.splice(u,1),"{"+c+"}"}})(t)}});var SUe=D((RFo,gPt)=>{"use strict";gPt.exports=function(e,r,n){var i="",o=e.schema.$async===!0,s=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),a=e.self._getId(e.schema);if(e.opts.strictKeywords){var c=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(c){var u="unknown keyword: "+c;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(i+=" var validate = ",o&&(e.async=!0,i+="async "),i+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",a&&(e.opts.sourceCode||e.opts.processCode)&&(i+=" "+("/*# sourceURL="+a+" */")+" ")),typeof e.schema=="boolean"||!(s||e.schema.$ref)){var r="false schema",d=e.level,f=e.dataLevel,p=e.schema[r],h=e.schemaPath+e.util.getProperty(r),m=e.errSchemaPath+"/"+r,T=!e.opts.allErrors,U,g="data"+(f||""),x="valid"+d;if(e.schema===!1){e.isTop?T=!0:i+=" var "+x+" = false; ";var A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(U||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'boolean schema is false' "),e.opts.verbose&&(i+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),i+=" } "):i+=" {} ";var y=i;i=A.pop(),!e.compositeRule&&T?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?o?i+=" return data; ":i+=" validate.errors = null; return true; ":i+=" var "+x+" = true; ";return e.isTop&&(i+=" }; return validate; "),i}if(e.isTop){var E=e.isTop,d=e.level=0,f=e.dataLevel=0,g="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var C="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(C);else throw new Error(C)}i+=" var vErrors = null; ",i+=" var errors = 0; ",i+=" if (rootData === undefined) rootData = data; "}else{var d=e.level,f=e.dataLevel,g="data"+(f||"");if(a&&(e.baseId=e.resolve.url(e.baseId,a)),o&&!e.async)throw new Error("async schema in sync schema");i+=" var errs_"+d+" = errors;"}var x="valid"+d,T=!e.opts.allErrors,O="",N="",U,w=e.schema.type,M=Array.isArray(w);if(w&&e.opts.nullable&&e.schema.nullable===!0&&(M?w.indexOf("null")==-1&&(w=w.concat("null")):w!="null"&&(w=[w,"null"],M=!0)),M&&w.length==1&&(w=w[0],M=!1),e.schema.$ref&&s){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(s=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(i+=" "+e.RULES.all.$comment.code(e,"$comment")),w){if(e.opts.coerceTypes)var B=e.util.coerceToTypes(e.opts.coerceTypes,w);var F=e.RULES.types[w];if(B||M||F===!0||F&&!z(F)){var h=e.schemaPath+".type",m=e.errSchemaPath+"/type",h=e.schemaPath+".type",m=e.errSchemaPath+"/type",L=M?"checkDataTypes":"checkDataType";if(i+=" if ("+e.util[L](w,g,e.opts.strictNumbers,!0)+") { ",B){var R="dataType"+d,q="coerced"+d;i+=" var "+R+" = typeof "+g+"; var "+q+" = undefined; ",e.opts.coerceTypes=="array"&&(i+=" if ("+R+" == 'object' && Array.isArray("+g+") && "+g+".length == 1) { "+g+" = "+g+"[0]; "+R+" = typeof "+g+"; if ("+e.util.checkDataType(e.schema.type,g,e.opts.strictNumbers)+") "+q+" = "+g+"; } "),i+=" if ("+q+" !== undefined) ; ";var Q=B;if(Q)for(var V,H=-1,J=Q.length-1;H<J;)V=Q[H+=1],V=="string"?i+=" else if ("+R+" == 'number' || "+R+" == 'boolean') "+q+" = '' + "+g+"; else if ("+g+" === null) "+q+" = ''; ":V=="number"||V=="integer"?(i+=" else if ("+R+" == 'boolean' || "+g+" === null || ("+R+" == 'string' && "+g+" && "+g+" == +"+g+" ",V=="integer"&&(i+=" && !("+g+" % 1)"),i+=")) "+q+" = +"+g+"; "):V=="boolean"?i+=" else if ("+g+" === 'false' || "+g+" === 0 || "+g+" === null) "+q+" = false; else if ("+g+" === 'true' || "+g+" === 1) "+q+" = true; ":V=="null"?i+=" else if ("+g+" === '' || "+g+" === 0 || "+g+" === false) "+q+" = null; ":e.opts.coerceTypes=="array"&&V=="array"&&(i+=" else if ("+R+" == 'string' || "+R+" == 'number' || "+R+" == 'boolean' || "+g+" == null) "+q+" = ["+g+"]; ");i+=" else { ";var A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(U||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: { type: '",M?i+=""+w.join(","):i+=""+w,i+="' } ",e.opts.messages!==!1&&(i+=" , message: 'should be ",M?i+=""+w.join(","):i+=""+w,i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),i+=" } "):i+=" {} ";var y=i;i=A.pop(),!e.compositeRule&&T?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } if ("+q+" !== undefined) { ";var X=f?"data"+(f-1||""):"parentData",he=f?e.dataPathArr[f]:"parentDataProperty";i+=" "+g+" = "+q+"; ",f||(i+="if ("+X+" !== undefined)"),i+=" "+X+"["+he+"] = "+q+"; } "}else{var A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(U||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: { type: '",M?i+=""+w.join(","):i+=""+w,i+="' } ",e.opts.messages!==!1&&(i+=" , message: 'should be ",M?i+=""+w.join(","):i+=""+w,i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),i+=" } "):i+=" {} ";var y=i;i=A.pop(),!e.compositeRule&&T?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}i+=" } "}}if(e.schema.$ref&&!s)i+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",T&&(i+=" } if (errors === ",E?i+="0":i+="errs_"+d,i+=") { ",N+="}");else{var Ce=e.RULES;if(Ce){for(var F,ge=-1,be=Ce.length-1;ge<be;)if(F=Ce[ge+=1],z(F)){if(F.type&&(i+=" if ("+e.util.checkDataType(F.type,g,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(F.type=="object"&&e.schema.properties){var p=e.schema.properties,xe=Object.keys(p),se=xe;if(se)for(var me,ve=-1,ee=se.length-1;ve<ee;){me=se[ve+=1];var ce=p[me];if(ce.default!==void 0){var Y=g+e.util.getProperty(me);if(e.compositeRule){if(e.opts.strictDefaults){var C="default is ignored for: "+Y;if(e.opts.strictDefaults==="log")e.logger.warn(C);else throw new Error(C)}}else i+=" if ("+Y+" === undefined ",e.opts.useDefaults=="empty"&&(i+=" || "+Y+" === null || "+Y+" === '' "),i+=" ) "+Y+" = ",e.opts.useDefaults=="shared"?i+=" "+e.useDefault(ce.default)+" ":i+=" "+JSON.stringify(ce.default)+" ",i+="; "}}}else if(F.type=="array"&&Array.isArray(e.schema.items)){var re=e.schema.items;if(re){for(var ce,H=-1,ue=re.length-1;H<ue;)if(ce=re[H+=1],ce.default!==void 0){var Y=g+"["+H+"]";if(e.compositeRule){if(e.opts.strictDefaults){var C="default is ignored for: "+Y;if(e.opts.strictDefaults==="log")e.logger.warn(C);else throw new Error(C)}}else i+=" if ("+Y+" === undefined ",e.opts.useDefaults=="empty"&&(i+=" || "+Y+" === null || "+Y+" === '' "),i+=" ) "+Y+" = ",e.opts.useDefaults=="shared"?i+=" "+e.useDefault(ce.default)+" ":i+=" "+JSON.stringify(ce.default)+" ",i+="; "}}}}var Z=F.rules;if(Z){for(var $,j=-1,Ee=Z.length-1;j<Ee;)if($=Z[j+=1],Te($)){var de=$.code(e,$.keyword,F.type);de&&(i+=" "+de+" ",T&&(O+="}"))}}if(T&&(i+=" "+O+" ",O=""),F.type&&(i+=" } ",w&&w===F.type&&!B)){i+=" else { ";var h=e.schemaPath+".type",m=e.errSchemaPath+"/type",A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(U||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: { type: '",M?i+=""+w.join(","):i+=""+w,i+="' } ",e.opts.messages!==!1&&(i+=" , message: 'should be ",M?i+=""+w.join(","):i+=""+w,i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),i+=" } "):i+=" {} ";var y=i;i=A.pop(),!e.compositeRule&&T?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } "}T&&(i+=" if (errors === ",E?i+="0":i+="errs_"+d,i+=") { ",N+="}")}}}T&&(i+=" "+N+" "),E?(o?(i+=" if (errors === 0) return data; ",i+=" else throw new ValidationError(vErrors); "):(i+=" validate.errors = vErrors; ",i+=" return errors === 0; "),i+=" }; return validate;"):i+=" var "+x+" = errors === errs_"+d+";";function z(Oe){for(var ke=Oe.rules,le=0;le<ke.length;le++)if(Te(ke[le]))return!0}function Te(Oe){return e.schema[Oe.keyword]!==void 0||Oe.implements&&Be(Oe)}function Be(Oe){for(var ke=Oe.implements,le=0;le<ke.length;le++)if(e.schema[ke[le]]!==void 0)return!0}return i}});var CPt=D((BFo,vPt)=>{"use strict";var Z0e=K0e(),tme=$D(),yPt=X0e(),OPn=wUe(),APt=SUe(),kPn=tme.ucs2length,MPn=CU(),PPn=yPt.Validation;vPt.exports=_Ue;function _Ue(t,e,r,n){var i=this,o=this._opts,s=[void 0],a={},c=[],u={},d=[],f={},p=[];e=e||{schema:t,refVal:s,refs:a};var h=LPn.call(this,t,e,n),m=this._compilations[h.index];if(h.compiling)return m.callValidate=C;var g=this._formats,A=this.RULES;try{var y=x(t,e,r,n);m.validate=y;var E=m.callValidate;return E&&(E.schema=y.schema,E.errors=null,E.refs=y.refs,E.refVal=y.refVal,E.root=y.root,E.$async=y.$async,o.sourceCode&&(E.source=y.source)),y}finally{FPn.call(this,t,e,n)}function C(){var L=m.validate,R=L.apply(this,arguments);return C.errors=L.errors,R}function x(L,R,q,Q){var V=!R||R&&R.schema==L;if(R.schema!=e.schema)return _Ue.call(i,L,R,q,Q);var H=L.$async===!0,J=APt({isTop:!0,schema:L,isRoot:V,baseId:Q,root:R,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:yPt.MissingRef,RULES:A,validate:APt,util:tme,resolve:Z0e,resolveRef:T,usePattern:M,useDefault:B,useCustomRule:F,opts:o,formats:g,logger:i.logger,self:i});J=eme(s,qPn)+eme(c,UPn)+eme(d,QPn)+eme(p,GPn)+J,o.processCode&&(J=o.processCode(J,L));var X;try{var he=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",J);X=he(i,A,g,e,s,d,p,MPn,kPn,PPn),s[0]=X}catch(Ce){throw i.logger.error("Error compiling schema, function code:",J),Ce}return X.schema=L,X.errors=null,X.refs=a,X.refVal=s,X.root=V?X:R,H&&(X.$async=!0),o.sourceCode===!0&&(X.source={code:J,patterns:c,defaults:d}),X}function T(L,R,q){R=Z0e.url(L,R);var Q=a[R],V,H;if(Q!==void 0)return V=s[Q],H="refVal["+Q+"]",w(V,H);if(!q&&e.refs){var J=e.refs[R];if(J!==void 0)return V=e.refVal[J],H=O(R,V),w(V,H)}H=O(R);var X=Z0e.call(i,x,e,R);if(X===void 0){var he=r&&r[R];he&&(X=Z0e.inlineRef(he,o.inlineRefs)?he:_Ue.call(i,he,e,r,L))}if(X===void 0)N(R);else return U(R,X),w(X,H)}function O(L,R){var q=s.length;return s[q]=R,a[L]=q,"refVal"+q}function N(L){delete a[L]}function U(L,R){var q=a[L];s[q]=R}function w(L,R){return typeof L=="object"||typeof L=="boolean"?{code:R,schema:L,inline:!0}:{code:R,$async:L&&!!L.$async}}function M(L){var R=u[L];return R===void 0&&(R=u[L]=c.length,c[R]=L),"pattern"+R}function B(L){switch(typeof L){case"boolean":case"number":return""+L;case"string":return tme.toQuotedString(L);case"object":if(L===null)return"null";var R=OPn(L),q=f[R];return q===void 0&&(q=f[R]=d.length,d[q]=L),"default"+q}}function F(L,R,q,Q){if(i._opts.validateSchema!==!1){var V=L.definition.dependencies;if(V&&!V.every(function(se){return Object.prototype.hasOwnProperty.call(q,se)}))throw new Error("parent schema must have all required keywords: "+V.join(","));var H=L.definition.validateSchema;if(H){var J=H(R);if(!J){var X="keyword schema is invalid: "+i.errorsText(H.errors);if(i._opts.validateSchema=="log")i.logger.error(X);else throw new Error(X)}}}var he=L.definition.compile,Ce=L.definition.inline,ge=L.definition.macro,be;if(he)be=he.call(i,R,q,Q);else if(ge)be=ge.call(i,R,q,Q),o.validateSchema!==!1&&i.validateSchema(be,!0);else if(Ce)be=Ce.call(i,Q,L.keyword,R,q);else if(be=L.definition.validate,!be)return;if(be===void 0)throw new Error('custom keyword "'+L.keyword+'"failed to compile');var xe=p.length;return p[xe]=be,{code:"customRule"+xe,validate:be}}}function LPn(t,e,r){var n=EPt.call(this,t,e,r);return n>=0?{index:n,compiling:!0}:(n=this._compilations.length,this._compilations[n]={schema:t,root:e,baseId:r},{index:n,compiling:!1})}function FPn(t,e,r){var n=EPt.call(this,t,e,r);n>=0&&this._compilations.splice(n,1)}function EPt(t,e,r){for(var n=0;n<this._compilations.length;n++){var i=this._compilations[n];if(i.schema==t&&i.root==e&&i.baseId==r)return n}return-1}function UPn(t,e){return"var pattern"+t+" = new RegExp("+tme.toQuotedString(e[t])+");"}function QPn(t){return"var default"+t+" = defaults["+t+"];"}function qPn(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function GPn(t){return"var customRule"+t+" = customRules["+t+"];"}function eme(t,e){if(!t.length)return"";for(var r="",n=0;n<t.length;n++)r+=e(n,t);return r}});var xPt=D((NFo,bPt)=>{"use strict";var rme=bPt.exports=function(){this._cache={}};rme.prototype.put=function(e,r){this._cache[e]=r};rme.prototype.get=function(e){return this._cache[e]};rme.prototype.del=function(e){delete this._cache[e]};rme.prototype.clear=function(){this._cache={}}});var MPt=D((OFo,kPt)=>{"use strict";var HPn=$D(),VPn=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,WPn=[0,31,28,31,30,31,30,31,31,30,31,30,31],$Pn=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,wPt=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,jPn=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,zPn=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,SPt=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,_Pt=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,TPt=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,IPt=/^(?:\/(?:[^~/]|~0|~1)*)*$/,DPt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,RPt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;kPt.exports=nme;function nme(t){return t=t=="full"?"full":"fast",HPn.copy(nme[t])}nme.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":SPt,url:_Pt,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:wPt,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:OPt,uuid:TPt,"json-pointer":IPt,"json-pointer-uri-fragment":DPt,"relative-json-pointer":RPt};nme.full={date:BPt,time:NPt,"date-time":KPn,uri:ZPn,"uri-reference":zPn,"uri-template":SPt,url:_Pt,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:wPt,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:OPt,uuid:TPt,"json-pointer":IPt,"json-pointer-uri-fragment":DPt,"relative-json-pointer":RPt};function YPn(t){return t%4===0&&(t%100!==0||t%400===0)}function BPt(t){var e=t.match(VPn);if(!e)return!1;var r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&YPn(r)?29:WPn[n])}function NPt(t,e){var r=t.match($Pn);if(!r)return!1;var n=r[1],i=r[2],o=r[3],s=r[5];return(n<=23&&i<=59&&o<=59||n==23&&i==59&&o==60)&&(!e||s)}var JPn=/t|\s/i;function KPn(t){var e=t.split(JPn);return e.length==2&&BPt(e[0])&&NPt(e[1],!0)}var XPn=/\/|:/;function ZPn(t){return XPn.test(t)&&jPn.test(t)}var eLn=/[^\\]\\Z/;function OPt(t){if(eLn.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var LPt=D((kFo,PPt)=>{"use strict";PPt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(s||""),f="valid"+o,p,h;if(a=="#"||a=="#/")e.isRoot?(p=e.async,h="validate"):(p=e.root.schema.$async===!0,h="root.refVal[0]");else{var m=e.resolveRef(e.baseId,a,e.isRoot);if(m===void 0){var g=e.MissingRefError.message(e.baseId,a);if(e.opts.missingRefs=="fail"){e.logger.error(g);var A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { ref: '"+e.util.escapeQuotes(a)+"' } ",e.opts.messages!==!1&&(i+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(a)+"' "),e.opts.verbose&&(i+=" , schema: "+e.util.toQuotedString(a)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var y=i;i=A.pop(),!e.compositeRule&&u?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(i+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(g),u&&(i+=" if (true) { ");else throw new e.MissingRefError(e.baseId,a,g)}else if(m.inline){var E=e.util.copy(e);E.level++;var C="valid"+E.level;E.schema=m.schema,E.schemaPath="",E.errSchemaPath=a;var x=e.validate(E).replace(/validate\.schema/g,m.code);i+=" "+x+" ",u&&(i+=" if ("+C+") { ")}else p=m.$async===!0||e.async&&m.$async!==!1,h=m.code}if(h){var A=A||[];A.push(i),i="",e.opts.passContext?i+=" "+h+".call(this, ":i+=" "+h+"( ",i+=" "+d+", (dataPath || '')",e.errorPath!='""'&&(i+=" + "+e.errorPath);var T=s?"data"+(s-1||""):"parentData",O=s?e.dataPathArr[s]:"parentDataProperty";i+=" , "+T+" , "+O+", rootData) ";var N=i;if(i=A.pop(),p){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(i+=" var "+f+"; "),i+=" try { await "+N+"; ",u&&(i+=" "+f+" = true; "),i+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(i+=" "+f+" = false; "),i+=" } ",u&&(i+=" if ("+f+") { ")}else i+=" if (!"+N+") { if (vErrors === null) vErrors = "+h+".errors; else vErrors = vErrors.concat("+h+".errors); errors = vErrors.length; } ",u&&(i+=" else { ")}return i}});var UPt=D((MFo,FPt)=>{"use strict";FPt.exports=function(e,r,n){var i=" ",o=e.schema[r],s=e.schemaPath+e.util.getProperty(r),a=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u=e.util.copy(e),d="";u.level++;var f="valid"+u.level,p=u.baseId,h=!0,m=o;if(m)for(var g,A=-1,y=m.length-1;A<y;)g=m[A+=1],(e.opts.strictKeywords?typeof g=="object"&&Object.keys(g).length>0||g===!1:e.util.schemaHasRules(g,e.RULES.all))&&(h=!1,u.schema=g,u.schemaPath=s+"["+A+"]",u.errSchemaPath=a+"/"+A,i+=" "+e.validate(u)+" ",u.baseId=p,c&&(i+=" if ("+f+") { ",d+="}"));return c&&(h?i+=" if (true) { ":i+=" "+d.slice(0,-1)+" "),i}});var qPt=D((PFo,QPt)=>{"use strict";QPt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h="errs__"+o,m=e.util.copy(e),g="";m.level++;var A="valid"+m.level,y=a.every(function(U){return e.opts.strictKeywords?typeof U=="object"&&Object.keys(U).length>0||U===!1:e.util.schemaHasRules(U,e.RULES.all)});if(y){var E=m.baseId;i+=" var "+h+" = errors; var "+p+" = false; ";var C=e.compositeRule;e.compositeRule=m.compositeRule=!0;var x=a;if(x)for(var T,O=-1,N=x.length-1;O<N;)T=x[O+=1],m.schema=T,m.schemaPath=c+"["+O+"]",m.errSchemaPath=u+"/"+O,i+=" "+e.validate(m)+" ",m.baseId=E,i+=" "+p+" = "+p+" || "+A+"; if (!"+p+") { ",g+="}";e.compositeRule=m.compositeRule=C,i+=" "+g+" if (!"+p+") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),i+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(i+=" } ")}else d&&(i+=" if (true) { ");return i}});var HPt=D((LFo,GPt)=>{"use strict";GPt.exports=function(e,r,n){var i=" ",o=e.schema[r],s=e.errSchemaPath+"/"+r,a=!e.opts.allErrors,c=e.util.toQuotedString(o);return e.opts.$comment===!0?i+=" console.log("+c+");":typeof e.opts.$comment=="function"&&(i+=" self._opts.$comment("+c+", "+e.util.toQuotedString(s)+", validate.root.schema);"),i}});var WPt=D((FFo,VPt)=>{"use strict";VPt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,m;h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",m="schema"+o):m=a,h||(i+=" var schema"+o+" = validate.schema"+c+";"),i+="var "+p+" = equal("+f+", schema"+o+"); if (!"+p+") { ";var g=g||[];g.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+o+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be equal to constant' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var A=i;return i=g.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+A+"]); ":i+=" validate.errors = ["+A+"]; return false; ":i+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" }",d&&(i+=" else { "),i}});var jPt=D((UFo,$Pt)=>{"use strict";$Pt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h="errs__"+o,m=e.util.copy(e),g="";m.level++;var A="valid"+m.level,y="i"+o,E=m.dataLevel=e.dataLevel+1,C="data"+E,x=e.baseId,T=e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all);if(i+="var "+h+" = errors;var "+p+";",T){var O=e.compositeRule;e.compositeRule=m.compositeRule=!0,m.schema=a,m.schemaPath=c,m.errSchemaPath=u,i+=" var "+A+" = false; for (var "+y+" = 0; "+y+" < "+f+".length; "+y+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers,!0);var N=f+"["+y+"]";m.dataPathArr[E]=y;var U=e.validate(m);m.baseId=x,e.util.varOccurences(U,C)<2?i+=" "+e.util.varReplace(U,C,N)+" ":i+=" var "+C+" = "+N+"; "+U+" ",i+=" if ("+A+") break; } ",e.compositeRule=m.compositeRule=O,i+=" "+g+" if (!"+A+") {"}else i+=" if ("+f+".length == 0) {";var w=w||[];w.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should contain a valid item' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var M=i;return i=w.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+M+"]); ":i+=" validate.errors = ["+M+"]; return false; ":i+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { ",T&&(i+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(i+=" } "),i}});var YPt=D((QFo,zPt)=>{"use strict";zPt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="errs__"+o,h=e.util.copy(e),m="";h.level++;var g="valid"+h.level,A={},y={},E=e.opts.ownProperties;for(O in a)if(O!="__proto__"){var C=a[O],x=Array.isArray(C)?y:A;x[O]=C}i+="var "+p+" = errors;";var T=e.errorPath;i+="var missing"+o+";";for(var O in y)if(x=y[O],x.length){if(i+=" if ( "+f+e.util.getProperty(O)+" !== undefined ",E&&(i+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(O)+"') "),d){i+=" && ( ";var N=x;if(N)for(var U,w=-1,M=N.length-1;w<M;){U=N[w+=1],w&&(i+=" || ");var B=e.util.getProperty(U),F=f+B;i+=" ( ( "+F+" === undefined ",E&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(U)+"') "),i+=") && (missing"+o+" = "+e.util.toQuotedString(e.opts.jsonPointers?U:B)+") ) "}i+=")) { ";var L="missing"+o,R="' + "+L+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(T,L,!0):T+" + "+L);var q=q||[];q.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(O)+"', missingProperty: '"+R+"', depsCount: "+x.length+", deps: '"+e.util.escapeQuotes(x.length==1?x[0]:x.join(", "))+"' } ",e.opts.messages!==!1&&(i+=" , message: 'should have ",x.length==1?i+="property "+e.util.escapeQuotes(x[0]):i+="properties "+e.util.escapeQuotes(x.join(", ")),i+=" when property "+e.util.escapeQuotes(O)+" is present' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var Q=i;i=q.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+Q+"]); ":i+=" validate.errors = ["+Q+"]; return false; ":i+=" var err = "+Q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{i+=" ) { ";var V=x;if(V)for(var U,H=-1,J=V.length-1;H<J;){U=V[H+=1];var B=e.util.getProperty(U),R=e.util.escapeQuotes(U),F=f+B;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(T,U,e.opts.jsonPointers)),i+=" if ( "+F+" === undefined ",E&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(U)+"') "),i+=") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(O)+"', missingProperty: '"+R+"', depsCount: "+x.length+", deps: '"+e.util.escapeQuotes(x.length==1?x[0]:x.join(", "))+"' } ",e.opts.messages!==!1&&(i+=" , message: 'should have ",x.length==1?i+="property "+e.util.escapeQuotes(x[0]):i+="properties "+e.util.escapeQuotes(x.join(", ")),i+=" when property "+e.util.escapeQuotes(O)+" is present' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}i+=" } ",d&&(m+="}",i+=" else { ")}e.errorPath=T;var X=h.baseId;for(var O in A){var C=A[O];(e.opts.strictKeywords?typeof C=="object"&&Object.keys(C).length>0||C===!1:e.util.schemaHasRules(C,e.RULES.all))&&(i+=" "+g+" = true; if ( "+f+e.util.getProperty(O)+" !== undefined ",E&&(i+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(O)+"') "),i+=") { ",h.schema=C,h.schemaPath=c+e.util.getProperty(O),h.errSchemaPath=u+"/"+e.util.escapeFragment(O),i+=" "+e.validate(h)+" ",h.baseId=X,i+=" } ",d&&(i+=" if ("+g+") { ",m+="}"))}return d&&(i+=" "+m+" if ("+p+" == errors) {"),i}});var KPt=D((qFo,JPt)=>{"use strict";JPt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,m;h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",m="schema"+o):m=a;var g="i"+o,A="schema"+o;h||(i+=" var "+A+" = validate.schema"+c+";"),i+="var "+p+";",h&&(i+=" if (schema"+o+" === undefined) "+p+" = true; else if (!Array.isArray(schema"+o+")) "+p+" = false; else {"),i+=""+p+" = false;for (var "+g+"=0; "+g+"<"+A+".length; "+g+"++) if (equal("+f+", "+A+"["+g+"])) { "+p+" = true; break; }",h&&(i+=" } "),i+=" if (!"+p+") { ";var y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+o+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var E=i;return i=y.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+E+"]); ":i+=" validate.errors = ["+E+"]; return false; ":i+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" }",d&&(i+=" else { "),i}});var ZPt=D((GFo,XPt)=>{"use strict";XPt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||"");if(e.opts.format===!1)return d&&(i+=" if (true) { "),i;var p=e.opts.$data&&a&&a.$data,h;p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a;var m=e.opts.unknownFormats,g=Array.isArray(m);if(p){var A="format"+o,y="isObject"+o,E="formatType"+o;i+=" var "+A+" = formats["+h+"]; var "+y+" = typeof "+A+" == 'object' && !("+A+" instanceof RegExp) && "+A+".validate; var "+E+" = "+y+" && "+A+".type || 'string'; if ("+y+") { ",e.async&&(i+=" var async"+o+" = "+A+".async; "),i+=" "+A+" = "+A+".validate; } if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'string') || "),i+=" (",m!="ignore"&&(i+=" ("+h+" && !"+A+" ",g&&(i+=" && self._opts.unknownFormats.indexOf("+h+") == -1 "),i+=") || "),i+=" ("+A+" && "+E+" == '"+n+"' && !(typeof "+A+" == 'function' ? ",e.async?i+=" (async"+o+" ? await "+A+"("+f+") : "+A+"("+f+")) ":i+=" "+A+"("+f+") ",i+=" : "+A+".test("+f+"))))) {"}else{var A=e.formats[a];if(!A){if(m=="ignore")return e.logger.warn('unknown format "'+a+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(i+=" if (true) { "),i;if(g&&m.indexOf(a)>=0)return d&&(i+=" if (true) { "),i;throw new Error('unknown format "'+a+'" is used in schema at path "'+e.errSchemaPath+'"')}var y=typeof A=="object"&&!(A instanceof RegExp)&&A.validate,E=y&&A.type||"string";if(y){var C=A.async===!0;A=A.validate}if(E!=n)return d&&(i+=" if (true) { "),i;if(C){if(!e.async)throw new Error("async format in sync schema");var x="formats"+e.util.getProperty(a)+".validate";i+=" if (!(await "+x+"("+f+"))) { "}else{i+=" if (! ";var x="formats"+e.util.getProperty(a);y&&(x+=".validate"),typeof A=="function"?i+=" "+x+"("+f+") ":i+=" "+x+".test("+f+") ",i+=") { "}}var T=T||[];T.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",p?i+=""+h:i+=""+e.util.toQuotedString(a),i+=" } ",e.opts.messages!==!1&&(i+=` , message: 'should match format "`,p?i+="' + "+h+" + '":i+=""+e.util.escapeQuotes(a),i+=`"' `),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+e.util.toQuotedString(a),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var O=i;return i=T.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+O+"]); ":i+=" validate.errors = ["+O+"]; return false; ":i+=" var err = "+O+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",d&&(i+=" else { "),i}});var tLt=D((HFo,eLt)=>{"use strict";eLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h="errs__"+o,m=e.util.copy(e);m.level++;var g="valid"+m.level,A=e.schema.then,y=e.schema.else,E=A!==void 0&&(e.opts.strictKeywords?typeof A=="object"&&Object.keys(A).length>0||A===!1:e.util.schemaHasRules(A,e.RULES.all)),C=y!==void 0&&(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all)),x=m.baseId;if(E||C){var T;m.createErrors=!1,m.schema=a,m.schemaPath=c,m.errSchemaPath=u,i+=" var "+h+" = errors; var "+p+" = true; ";var O=e.compositeRule;e.compositeRule=m.compositeRule=!0,i+=" "+e.validate(m)+" ",m.baseId=x,m.createErrors=!0,i+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=m.compositeRule=O,E?(i+=" if ("+g+") { ",m.schema=e.schema.then,m.schemaPath=e.schemaPath+".then",m.errSchemaPath=e.errSchemaPath+"/then",i+=" "+e.validate(m)+" ",m.baseId=x,i+=" "+p+" = "+g+"; ",E&&C?(T="ifClause"+o,i+=" var "+T+" = 'then'; "):T="'then'",i+=" } ",C&&(i+=" else { ")):i+=" if (!"+g+") { ",C&&(m.schema=e.schema.else,m.schemaPath=e.schemaPath+".else",m.errSchemaPath=e.errSchemaPath+"/else",i+=" "+e.validate(m)+" ",m.baseId=x,i+=" "+p+" = "+g+"; ",E&&C?(T="ifClause"+o,i+=" var "+T+" = 'else'; "):T="'else'",i+=" } "),i+=" if (!"+p+") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+T+" } ",e.opts.messages!==!1&&(i+=` , message: 'should match "' + `+T+` + '" schema' `),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),i+=" } ",d&&(i+=" else { ")}else d&&(i+=" if (true) { ");return i}});var nLt=D((VFo,rLt)=>{"use strict";rLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h="errs__"+o,m=e.util.copy(e),g="";m.level++;var A="valid"+m.level,y="i"+o,E=m.dataLevel=e.dataLevel+1,C="data"+E,x=e.baseId;if(i+="var "+h+" = errors;var "+p+";",Array.isArray(a)){var T=e.schema.additionalItems;if(T===!1){i+=" "+p+" = "+f+".length <= "+a.length+"; ";var O=u;u=e.errSchemaPath+"/additionalItems",i+=" if (!"+p+") { ";var N=N||[];N.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+a.length+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have more than "+a.length+" items' "),e.opts.verbose&&(i+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var U=i;i=N.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+U+"]); ":i+=" validate.errors = ["+U+"]; return false; ":i+=" var err = "+U+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",u=O,d&&(g+="}",i+=" else { ")}var w=a;if(w){for(var M,B=-1,F=w.length-1;B<F;)if(M=w[B+=1],e.opts.strictKeywords?typeof M=="object"&&Object.keys(M).length>0||M===!1:e.util.schemaHasRules(M,e.RULES.all)){i+=" "+A+" = true; if ("+f+".length > "+B+") { ";var L=f+"["+B+"]";m.schema=M,m.schemaPath=c+"["+B+"]",m.errSchemaPath=u+"/"+B,m.errorPath=e.util.getPathExpr(e.errorPath,B,e.opts.jsonPointers,!0),m.dataPathArr[E]=B;var R=e.validate(m);m.baseId=x,e.util.varOccurences(R,C)<2?i+=" "+e.util.varReplace(R,C,L)+" ":i+=" var "+C+" = "+L+"; "+R+" ",i+=" } ",d&&(i+=" if ("+A+") { ",g+="}")}}if(typeof T=="object"&&(e.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:e.util.schemaHasRules(T,e.RULES.all))){m.schema=T,m.schemaPath=e.schemaPath+".additionalItems",m.errSchemaPath=e.errSchemaPath+"/additionalItems",i+=" "+A+" = true; if ("+f+".length > "+a.length+") { for (var "+y+" = "+a.length+"; "+y+" < "+f+".length; "+y+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers,!0);var L=f+"["+y+"]";m.dataPathArr[E]=y;var R=e.validate(m);m.baseId=x,e.util.varOccurences(R,C)<2?i+=" "+e.util.varReplace(R,C,L)+" ":i+=" var "+C+" = "+L+"; "+R+" ",d&&(i+=" if (!"+A+") break; "),i+=" } } ",d&&(i+=" if ("+A+") { ",g+="}")}}else if(e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all)){m.schema=a,m.schemaPath=c,m.errSchemaPath=u,i+=" for (var "+y+" = 0; "+y+" < "+f+".length; "+y+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers,!0);var L=f+"["+y+"]";m.dataPathArr[E]=y;var R=e.validate(m);m.baseId=x,e.util.varOccurences(R,C)<2?i+=" "+e.util.varReplace(R,C,L)+" ":i+=" var "+C+" = "+L+"; "+R+" ",d&&(i+=" if (!"+A+") break; "),i+=" }"}return d&&(i+=" "+g+" if ("+h+" == errors) {"),i}});var TUe=D((WFo,iLt)=>{"use strict";iLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,x,f="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a;var m=r=="maximum",g=m?"exclusiveMaximum":"exclusiveMinimum",A=e.schema[g],y=e.opts.$data&&A&&A.$data,E=m?"<":">",C=m?">":"<",x=void 0;if(!(p||typeof a=="number"||a===void 0))throw new Error(r+" must be number");if(!(y||A===void 0||typeof A=="number"||typeof A=="boolean"))throw new Error(g+" must be number or boolean");if(y){var T=e.util.getData(A.$data,s,e.dataPathArr),O="exclusive"+o,N="exclType"+o,U="exclIsNumber"+o,w="op"+o,M="' + "+w+" + '";i+=" var schemaExcl"+o+" = "+T+"; ",T="schemaExcl"+o,i+=" var "+O+"; var "+N+" = typeof "+T+"; if ("+N+" != 'boolean' && "+N+" != 'undefined' && "+N+" != 'number') { ";var x=g,B=B||[];B.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(x||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: '"+g+" should be boolean' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var F=i;i=B.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+F+"]); ":i+=" validate.errors = ["+F+"]; return false; ":i+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" "+N+" == 'number' ? ( ("+O+" = "+h+" === undefined || "+T+" "+E+"= "+h+") ? "+f+" "+C+"= "+T+" : "+f+" "+C+" "+h+" ) : ( ("+O+" = "+T+" === true) ? "+f+" "+C+"= "+h+" : "+f+" "+C+" "+h+" ) || "+f+" !== "+f+") { var op"+o+" = "+O+" ? '"+E+"' : '"+E+"='; ",a===void 0&&(x=g,u=e.errSchemaPath+"/"+g,h=T,p=y)}else{var U=typeof A=="number",M=E;if(U&&p){var w="'"+M+"'";i+=" if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" ( "+h+" === undefined || "+A+" "+E+"= "+h+" ? "+f+" "+C+"= "+A+" : "+f+" "+C+" "+h+" ) || "+f+" !== "+f+") { "}else{U&&a===void 0?(O=!0,x=g,u=e.errSchemaPath+"/"+g,h=A,C+="="):(U&&(h=Math[m?"min":"max"](A,a)),A===(U?h:!0)?(O=!0,x=g,u=e.errSchemaPath+"/"+g,C+="="):(O=!1,M+="="));var w="'"+M+"'";i+=" if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" "+f+" "+C+" "+h+" || "+f+" !== "+f+") { "}}x=x||r;var B=B||[];B.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(x||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+w+", limit: "+h+", exclusive: "+O+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be "+M+" ",p?i+="' + "+h:i+=""+h+"'"),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var F=i;return i=B.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+F+"]); ":i+=" validate.errors = ["+F+"]; return false; ":i+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",d&&(i+=" else { "),i}});var IUe=D(($Fo,oLt)=>{"use strict";oLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,g,f="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");var m=r=="maxItems"?">":"<";i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" "+f+".length "+m+" "+h+") { ";var g=r,A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(g||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have ",r=="maxItems"?i+="more":i+="fewer",i+=" than ",p?i+="' + "+h+" + '":i+=""+a,i+=" items' "),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var y=i;return i=A.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",d&&(i+=" else { "),i}});var DUe=D((jFo,sLt)=>{"use strict";sLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,g,f="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");var m=r=="maxLength"?">":"<";i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),e.opts.unicode===!1?i+=" "+f+".length ":i+=" ucs2length("+f+") ",i+=" "+m+" "+h+") { ";var g=r,A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(g||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT be ",r=="maxLength"?i+="longer":i+="shorter",i+=" than ",p?i+="' + "+h+" + '":i+=""+a,i+=" characters' "),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var y=i;return i=A.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",d&&(i+=" else { "),i}});var RUe=D((zFo,aLt)=>{"use strict";aLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,g,f="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");var m=r=="maxProperties"?">":"<";i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" Object.keys("+f+").length "+m+" "+h+") { ";var g=r,A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(g||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have ",r=="maxProperties"?i+="more":i+="fewer",i+=" than ",p?i+="' + "+h+" + '":i+=""+a,i+=" properties' "),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var y=i;return i=A.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",d&&(i+=" else { "),i}});var cLt=D((YFo,lLt)=>{"use strict";lLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");i+="var division"+o+";if (",p&&(i+=" "+h+" !== undefined && ( typeof "+h+" != 'number' || "),i+=" (division"+o+" = "+f+" / "+h+", ",e.opts.multipleOfPrecision?i+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":i+=" division"+o+" !== parseInt(division"+o+") ",i+=" ) ",p&&(i+=" ) "),i+=" ) { ";var m=m||[];m.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be multiple of ",p?i+="' + "+h:i+=""+h+"'"),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var g=i;return i=m.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",d&&(i+=" else { "),i}});var dLt=D((JFo,uLt)=>{"use strict";uLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="errs__"+o,h=e.util.copy(e);h.level++;var m="valid"+h.level;if(e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all)){h.schema=a,h.schemaPath=c,h.errSchemaPath=u,i+=" var "+p+" = errors; ";var g=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1;var A;h.opts.allErrors&&(A=h.opts.allErrors,h.opts.allErrors=!1),i+=" "+e.validate(h)+" ",h.createErrors=!0,A&&(h.opts.allErrors=A),e.compositeRule=h.compositeRule=g,i+=" if ("+m+") { ";var y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should NOT be valid' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var E=i;i=y.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+E+"]); ":i+=" validate.errors = ["+E+"]; return false; ":i+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } ",e.opts.allErrors&&(i+=" } ")}else i+=" var err = ",e.createErrors!==!1?(i+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should NOT be valid' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(i+=" if (false) { ");return i}});var pLt=D((KFo,fLt)=>{"use strict";fLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h="errs__"+o,m=e.util.copy(e),g="";m.level++;var A="valid"+m.level,y=m.baseId,E="prevValid"+o,C="passingSchemas"+o;i+="var "+h+" = errors , "+E+" = false , "+p+" = false , "+C+" = null; ";var x=e.compositeRule;e.compositeRule=m.compositeRule=!0;var T=a;if(T)for(var O,N=-1,U=T.length-1;N<U;)O=T[N+=1],(e.opts.strictKeywords?typeof O=="object"&&Object.keys(O).length>0||O===!1:e.util.schemaHasRules(O,e.RULES.all))?(m.schema=O,m.schemaPath=c+"["+N+"]",m.errSchemaPath=u+"/"+N,i+=" "+e.validate(m)+" ",m.baseId=y):i+=" var "+A+" = true; ",N&&(i+=" if ("+A+" && "+E+") { "+p+" = false; "+C+" = ["+C+", "+N+"]; } else { ",g+="}"),i+=" if ("+A+") { "+p+" = "+E+" = true; "+C+" = "+N+"; }";return e.compositeRule=m.compositeRule=x,i+=""+g+"if (!"+p+") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+C+" } ",e.opts.messages!==!1&&(i+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),i+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(i+=" } "),i}});var mLt=D((XFo,hLt)=>{"use strict";hLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a;var m=p?"(new RegExp("+h+"))":e.usePattern(a);i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'string') || "),i+=" !"+m+".test("+f+") ) { ";var g=g||[];g.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",p?i+=""+h:i+=""+e.util.toQuotedString(a),i+=" } ",e.opts.messages!==!1&&(i+=` , message: 'should match pattern "`,p?i+="' + "+h+" + '":i+=""+e.util.escapeQuotes(a),i+=`"' `),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+e.util.toQuotedString(a),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var A=i;return i=g.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+A+"]); ":i+=" validate.errors = ["+A+"]; return false; ":i+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",d&&(i+=" else { "),i}});var ALt=D((ZFo,gLt)=>{"use strict";gLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="errs__"+o,h=e.util.copy(e),m="";h.level++;var g="valid"+h.level,A="key"+o,y="idx"+o,E=h.dataLevel=e.dataLevel+1,C="data"+E,x="dataProperties"+o,T=Object.keys(a||{}).filter(H),O=e.schema.patternProperties||{},N=Object.keys(O).filter(H),U=e.schema.additionalProperties,w=T.length||N.length,M=U===!1,B=typeof U=="object"&&Object.keys(U).length,F=e.opts.removeAdditional,L=M||B||F,R=e.opts.ownProperties,q=e.baseId,Q=e.schema.required;if(Q&&!(e.opts.$data&&Q.$data)&&Q.length<e.opts.loopRequired)var V=e.util.toHash(Q);function H(Re){return Re!=="__proto__"}if(i+="var "+p+" = errors;var "+g+" = true;",R&&(i+=" var "+x+" = undefined;"),L){if(R?i+=" "+x+" = "+x+" || Object.keys("+f+"); for (var "+y+"=0; "+y+"<"+x+".length; "+y+"++) { var "+A+" = "+x+"["+y+"]; ":i+=" for (var "+A+" in "+f+") { ",w){if(i+=" var isAdditional"+o+" = !(false ",T.length)if(T.length>8)i+=" || validate.schema"+c+".hasOwnProperty("+A+") ";else{var J=T;if(J)for(var X,he=-1,Ce=J.length-1;he<Ce;)X=J[he+=1],i+=" || "+A+" == "+e.util.toQuotedString(X)+" "}if(N.length){var ge=N;if(ge)for(var be,xe=-1,se=ge.length-1;xe<se;)be=ge[xe+=1],i+=" || "+e.usePattern(be)+".test("+A+") "}i+=" ); if (isAdditional"+o+") { "}if(F=="all")i+=" delete "+f+"["+A+"]; ";else{var me=e.errorPath,ve="' + "+A+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers)),M)if(F)i+=" delete "+f+"["+A+"]; ";else{i+=" "+g+" = false; ";var ee=u;u=e.errSchemaPath+"/additionalProperties";var ce=ce||[];ce.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+ve+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is an invalid additional property":i+="should NOT have additional properties",i+="' "),e.opts.verbose&&(i+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var Y=i;i=ce.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+Y+"]); ":i+=" validate.errors = ["+Y+"]; return false; ":i+=" var err = "+Y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=ee,d&&(i+=" break; ")}else if(B)if(F=="failing"){i+=" var "+p+" = errors; ";var re=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=U,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers);var ue=f+"["+A+"]";h.dataPathArr[E]=A;var Z=e.validate(h);h.baseId=q,e.util.varOccurences(Z,C)<2?i+=" "+e.util.varReplace(Z,C,ue)+" ":i+=" var "+C+" = "+ue+"; "+Z+" ",i+=" if (!"+g+") { errors = "+p+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+f+"["+A+"]; } ",e.compositeRule=h.compositeRule=re}else{h.schema=U,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers);var ue=f+"["+A+"]";h.dataPathArr[E]=A;var Z=e.validate(h);h.baseId=q,e.util.varOccurences(Z,C)<2?i+=" "+e.util.varReplace(Z,C,ue)+" ":i+=" var "+C+" = "+ue+"; "+Z+" ",d&&(i+=" if (!"+g+") break; ")}e.errorPath=me}w&&(i+=" } "),i+=" } ",d&&(i+=" if ("+g+") { ",m+="}")}var $=e.opts.useDefaults&&!e.compositeRule;if(T.length){var j=T;if(j)for(var X,Ee=-1,de=j.length-1;Ee<de;){X=j[Ee+=1];var z=a[X];if(e.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:e.util.schemaHasRules(z,e.RULES.all)){var Te=e.util.getProperty(X),ue=f+Te,Be=$&&z.default!==void 0;h.schema=z,h.schemaPath=c+Te,h.errSchemaPath=u+"/"+e.util.escapeFragment(X),h.errorPath=e.util.getPath(e.errorPath,X,e.opts.jsonPointers),h.dataPathArr[E]=e.util.toQuotedString(X);var Z=e.validate(h);if(h.baseId=q,e.util.varOccurences(Z,C)<2){Z=e.util.varReplace(Z,C,ue);var Oe=ue}else{var Oe=C;i+=" var "+C+" = "+ue+"; "}if(Be)i+=" "+Z+" ";else{if(V&&V[X]){i+=" if ( "+Oe+" === undefined ",R&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(X)+"') "),i+=") { "+g+" = false; ";var me=e.errorPath,ee=u,ke=e.util.escapeQuotes(X);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(me,X,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var ce=ce||[];ce.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+ke+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+ke+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var Y=i;i=ce.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+Y+"]); ":i+=" validate.errors = ["+Y+"]; return false; ":i+=" var err = "+Y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=ee,e.errorPath=me,i+=" } else { "}else d?(i+=" if ( "+Oe+" === undefined ",R&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(X)+"') "),i+=") { "+g+" = true; } else { "):(i+=" if ("+Oe+" !== undefined ",R&&(i+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(X)+"') "),i+=" ) { ");i+=" "+Z+" } "}}d&&(i+=" if ("+g+") { ",m+="}")}}if(N.length){var le=N;if(le)for(var be,Ie=-1,De=le.length-1;Ie<De;){be=le[Ie+=1];var z=O[be];if(e.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:e.util.schemaHasRules(z,e.RULES.all)){h.schema=z,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(be),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(be),R?i+=" "+x+" = "+x+" || Object.keys("+f+"); for (var "+y+"=0; "+y+"<"+x+".length; "+y+"++) { var "+A+" = "+x+"["+y+"]; ":i+=" for (var "+A+" in "+f+") { ",i+=" if ("+e.usePattern(be)+".test("+A+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers);var ue=f+"["+A+"]";h.dataPathArr[E]=A;var Z=e.validate(h);h.baseId=q,e.util.varOccurences(Z,C)<2?i+=" "+e.util.varReplace(Z,C,ue)+" ":i+=" var "+C+" = "+ue+"; "+Z+" ",d&&(i+=" if (!"+g+") break; "),i+=" } ",d&&(i+=" else "+g+" = true; "),i+=" } ",d&&(i+=" if ("+g+") { ",m+="}")}}}return d&&(i+=" "+m+" if ("+p+" == errors) {"),i}});var ELt=D((eUo,yLt)=>{"use strict";yLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="errs__"+o,h=e.util.copy(e),m="";h.level++;var g="valid"+h.level;if(i+="var "+p+" = errors;",e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all)){h.schema=a,h.schemaPath=c,h.errSchemaPath=u;var A="key"+o,y="idx"+o,E="i"+o,C="' + "+A+" + '",x=h.dataLevel=e.dataLevel+1,T="data"+x,O="dataProperties"+o,N=e.opts.ownProperties,U=e.baseId;N&&(i+=" var "+O+" = undefined; "),N?i+=" "+O+" = "+O+" || Object.keys("+f+"); for (var "+y+"=0; "+y+"<"+O+".length; "+y+"++) { var "+A+" = "+O+"["+y+"]; ":i+=" for (var "+A+" in "+f+") { ",i+=" var startErrs"+o+" = errors; ";var w=A,M=e.compositeRule;e.compositeRule=h.compositeRule=!0;var B=e.validate(h);h.baseId=U,e.util.varOccurences(B,T)<2?i+=" "+e.util.varReplace(B,T,w)+" ":i+=" var "+T+" = "+w+"; "+B+" ",e.compositeRule=h.compositeRule=M,i+=" if (!"+g+") { for (var "+E+"=startErrs"+o+"; "+E+"<errors; "+E+"++) { vErrors["+E+"].propertyName = "+A+"; } var err = ",e.createErrors!==!1?(i+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+C+"' } ",e.opts.messages!==!1&&(i+=" , message: 'property name \\'"+C+"\\' is invalid' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),d&&(i+=" break; "),i+=" } }"}return d&&(i+=" "+m+" if ("+p+" == errors) {"),i}});var CLt=D((tUo,vLt)=>{"use strict";vLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,m;h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",m="schema"+o):m=a;var g="schema"+o;if(!h)if(a.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var A=[],y=a;if(y)for(var E,C=-1,x=y.length-1;C<x;){E=y[C+=1];var T=e.schema.properties[E];T&&(e.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:e.util.schemaHasRules(T,e.RULES.all))||(A[A.length]=E)}}else var A=a;if(h||A.length){var O=e.errorPath,N=h||A.length>=e.opts.loopRequired,U=e.opts.ownProperties;if(d)if(i+=" var missing"+o+"; ",N){h||(i+=" var "+g+" = validate.schema"+c+"; ");var w="i"+o,M="schema"+o+"["+w+"]",B="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(O,M,e.opts.jsonPointers)),i+=" var "+p+" = true; ",h&&(i+=" if (schema"+o+" === undefined) "+p+" = true; else if (!Array.isArray(schema"+o+")) "+p+" = false; else {"),i+=" for (var "+w+" = 0; "+w+" < "+g+".length; "+w+"++) { "+p+" = "+f+"["+g+"["+w+"]] !== undefined ",U&&(i+=" && Object.prototype.hasOwnProperty.call("+f+", "+g+"["+w+"]) "),i+="; if (!"+p+") break; } ",h&&(i+=" } "),i+=" if (!"+p+") { ";var F=F||[];F.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+B+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+B+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var L=i;i=F.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+L+"]); ":i+=" validate.errors = ["+L+"]; return false; ":i+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { "}else{i+=" if ( ";var R=A;if(R)for(var q,w=-1,Q=R.length-1;w<Q;){q=R[w+=1],w&&(i+=" || ");var V=e.util.getProperty(q),H=f+V;i+=" ( ( "+H+" === undefined ",U&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(q)+"') "),i+=") && (missing"+o+" = "+e.util.toQuotedString(e.opts.jsonPointers?q:V)+") ) "}i+=") { ";var M="missing"+o,B="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(O,M,!0):O+" + "+M);var F=F||[];F.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+B+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+B+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var L=i;i=F.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+L+"]); ":i+=" validate.errors = ["+L+"]; return false; ":i+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { "}else if(N){h||(i+=" var "+g+" = validate.schema"+c+"; ");var w="i"+o,M="schema"+o+"["+w+"]",B="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(O,M,e.opts.jsonPointers)),h&&(i+=" if ("+g+" && !Array.isArray("+g+")) { var err = ",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+B+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+B+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+g+" !== undefined) { "),i+=" for (var "+w+" = 0; "+w+" < "+g+".length; "+w+"++) { if ("+f+"["+g+"["+w+"]] === undefined ",U&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", "+g+"["+w+"]) "),i+=") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+B+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+B+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(i+=" } ")}else{var J=A;if(J)for(var q,X=-1,he=J.length-1;X<he;){q=J[X+=1];var V=e.util.getProperty(q),B=e.util.escapeQuotes(q),H=f+V;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(O,q,e.opts.jsonPointers)),i+=" if ( "+H+" === undefined ",U&&(i+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(q)+"') "),i+=") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+B+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+B+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=O}else d&&(i+=" if (true) {");return i}});var xLt=D((rUo,bLt)=>{"use strict";bLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,m;if(h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",m="schema"+o):m=a,(a||h)&&e.opts.uniqueItems!==!1){h&&(i+=" var "+p+"; if ("+m+" === false || "+m+" === undefined) "+p+" = true; else if (typeof "+m+" != 'boolean') "+p+" = false; else { "),i+=" var i = "+f+".length , "+p+" = true , j; if (i > 1) { ";var g=e.schema.items&&e.schema.items.type,A=Array.isArray(g);if(!g||g=="object"||g=="array"||A&&(g.indexOf("object")>=0||g.indexOf("array")>=0))i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+f+"[i], "+f+"[j])) { "+p+" = false; break outer; } } } ";else{i+=" var itemIndices = {}, item; for (;i--;) { var item = "+f+"[i]; ";var y="checkDataType"+(A?"s":"");i+=" if ("+e.util[y](g,"item",e.opts.strictNumbers,!0)+") continue; ",A&&(i+=` if (typeof item == 'string') item = '"' + item; `),i+=" if (typeof itemIndices[item] == 'number') { "+p+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}i+=" } ",h&&(i+=" } "),i+=" if (!"+p+") { ";var E=E||[];E.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",h?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var C=i;i=E.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+C+"]); ":i+=" validate.errors = ["+C+"]; return false; ":i+=" var err = "+C+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",d&&(i+=" else { ")}else d&&(i+=" if (true) { ");return i}});var SLt=D((nUo,wLt)=>{"use strict";wLt.exports={$ref:LPt(),allOf:UPt(),anyOf:qPt(),$comment:HPt(),const:WPt(),contains:jPt(),dependencies:YPt(),enum:KPt(),format:ZPt(),if:tLt(),items:nLt(),maximum:TUe(),minimum:TUe(),maxItems:IUe(),minItems:IUe(),maxLength:DUe(),minLength:DUe(),maxProperties:RUe(),minProperties:RUe(),multipleOf:cLt(),not:dLt(),oneOf:pLt(),pattern:mLt(),properties:ALt(),propertyNames:ELt(),required:CLt(),uniqueItems:xLt(),validate:SUe()}});var ILt=D((iUo,TLt)=>{"use strict";var _Lt=SLt(),BUe=$D().toHash;TLt.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],n=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],i=["number","integer","string","array","object","boolean","null"];return e.all=BUe(r),e.types=BUe(i),e.forEach(function(o){o.rules=o.rules.map(function(s){var a;if(typeof s=="object"){var c=Object.keys(s)[0];a=s[c],s=c,a.forEach(function(d){r.push(d),e.all[d]=!0})}r.push(s);var u=e.all[s]={keyword:s,code:_Lt[s],implements:a};return u}),e.all.$comment={keyword:"$comment",code:_Lt.$comment},o.type&&(e.types[o.type]=o)}),e.keywords=BUe(r.concat(n)),e.custom={},e}});var BLt=D((oUo,RLt)=>{"use strict";var DLt=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];RLt.exports=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var n=e[r].split("/"),i=t,o;for(o=1;o<n.length;o++)i=i[n[o]];for(o=0;o<DLt.length;o++){var s=DLt[o],a=i[s];a&&(i[s]={anyOf:[a,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t}});var kLt=D((sUo,OLt)=>{"use strict";var tLn=X0e().MissingRef;OLt.exports=NLt;function NLt(t,e,r){var n=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var i=o(t).then(function(){var a=n._addSchema(t,void 0,e);return a.validate||s(a)});return r&&i.then(function(a){r(null,a)},r),i;function o(a){var c=a.$schema;return c&&!n.getSchema(c)?NLt.call(n,{$ref:c},!0):Promise.resolve()}function s(a){try{return n._compile(a)}catch(u){if(u instanceof tLn)return c(u);throw u}function c(u){var d=u.missingSchema;if(h(d))throw new Error("Schema "+d+" is loaded but "+u.missingRef+" cannot be resolved");var f=n._loadingSchemas[d];return f||(f=n._loadingSchemas[d]=n._opts.loadSchema(d),f.then(p,p)),f.then(function(m){if(!h(d))return o(m).then(function(){h(d)||n.addSchema(m,d,void 0,e)})}).then(function(){return s(a)});function p(){delete n._loadingSchemas[d]}function h(m){return n._refs[m]||n._schemas[m]}}}}});var PLt=D((aUo,MLt)=>{"use strict";MLt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,p="data"+(s||""),h="valid"+o,m="errs__"+o,g=e.opts.$data&&a&&a.$data,A;g?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",A="schema"+o):A=a;var y=this,E="definition"+o,C=y.definition,x="",T,O,N,U,w;if(g&&C.$data){w="keywordValidate"+o;var M=C.validateSchema;i+=" var "+E+" = RULES.custom['"+r+"'].definition; var "+w+" = "+E+".validate;"}else{if(U=e.useCustomRule(y,a,e.schema,e),!U)return;A="validate.schema"+c,w=U.code,T=C.compile,O=C.inline,N=C.macro}var B=w+".errors",F="i"+o,L="ruleErr"+o,R=C.async;if(R&&!e.async)throw new Error("async keyword in sync schema");if(O||N||(i+=""+B+" = null;"),i+="var "+m+" = errors;var "+h+";",g&&C.$data&&(x+="}",i+=" if ("+A+" === undefined) { "+h+" = true; } else { ",M&&(x+="}",i+=" "+h+" = "+E+".validateSchema("+A+"); if ("+h+") { ")),O)C.statements?i+=" "+U.validate+" ":i+=" "+h+" = "+U.validate+"; ";else if(N){var q=e.util.copy(e),x="";q.level++;var Q="valid"+q.level;q.schema=U.validate,q.schemaPath="";var V=e.compositeRule;e.compositeRule=q.compositeRule=!0;var H=e.validate(q).replace(/validate\.schema/g,w);e.compositeRule=q.compositeRule=V,i+=" "+H}else{var J=J||[];J.push(i),i="",i+=" "+w+".call( ",e.opts.passContext?i+="this":i+="self",T||C.schema===!1?i+=" , "+p+" ":i+=" , "+A+" , "+p+" , validate.schema"+e.schemaPath+" ",i+=" , (dataPath || '')",e.errorPath!='""'&&(i+=" + "+e.errorPath);var X=s?"data"+(s-1||""):"parentData",he=s?e.dataPathArr[s]:"parentDataProperty";i+=" , "+X+" , "+he+" , rootData ) ";var Ce=i;i=J.pop(),C.errors===!1?(i+=" "+h+" = ",R&&(i+="await "),i+=""+Ce+"; "):R?(B="customErrors"+o,i+=" var "+B+" = null; try { "+h+" = await "+Ce+"; } catch (e) { "+h+" = false; if (e instanceof ValidationError) "+B+" = e.errors; else throw e; } "):i+=" "+B+" = null; "+h+" = "+Ce+"; "}if(C.modifying&&(i+=" if ("+X+") "+p+" = "+X+"["+he+"];"),i+=""+x,C.valid)d&&(i+=" if (true) { ");else{i+=" if ( ",C.valid===void 0?(i+=" !",N?i+=""+Q:i+=""+h):i+=" "+!C.valid+" ",i+=") { ",f=y.keyword;var J=J||[];J.push(i),i="";var J=J||[];J.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+y.keyword+"' } ",e.opts.messages!==!1&&(i+=` , message: 'should pass "`+y.keyword+`" keyword validation' `),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ";var ge=i;i=J.pop(),!e.compositeRule&&d?e.async?i+=" throw new ValidationError(["+ge+"]); ":i+=" validate.errors = ["+ge+"]; return false; ":i+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var be=i;i=J.pop(),O?C.errors?C.errors!="full"&&(i+=" for (var "+F+"="+m+"; "+F+"<errors; "+F+"++) { var "+L+" = vErrors["+F+"]; if ("+L+".dataPath === undefined) "+L+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+L+".schemaPath === undefined) { "+L+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+L+".schema = "+A+"; "+L+".data = "+p+"; "),i+=" } "):C.errors===!1?i+=" "+be+" ":(i+=" if ("+m+" == errors) { "+be+" } else { for (var "+F+"="+m+"; "+F+"<errors; "+F+"++) { var "+L+" = vErrors["+F+"]; if ("+L+".dataPath === undefined) "+L+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+L+".schemaPath === undefined) { "+L+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+L+".schema = "+A+"; "+L+".data = "+p+"; "),i+=" } } "):N?(i+=" var err = ",e.createErrors!==!1?(i+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+y.keyword+"' } ",e.opts.messages!==!1&&(i+=` , message: 'should pass "`+y.keyword+`" keyword validation' `),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; ")):C.errors===!1?i+=" "+be+" ":(i+=" if (Array.isArray("+B+")) { if (vErrors === null) vErrors = "+B+"; else vErrors = vErrors.concat("+B+"); errors = vErrors.length; for (var "+F+"="+m+"; "+F+"<errors; "+F+"++) { var "+L+" = vErrors["+F+"]; if ("+L+".dataPath === undefined) "+L+".dataPath = (dataPath || '') + "+e.errorPath+"; "+L+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(i+=" "+L+".schema = "+A+"; "+L+".data = "+p+"; "),i+=" } } else { "+be+" } "),i+=" } ",d&&(i+=" else { ")}return i}});var NUe=D((lUo,rLn)=>{rLn.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ULt=D((cUo,FLt)=>{"use strict";var LLt=NUe();FLt.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:LLt.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:LLt.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}});var qLt=D((uUo,QLt)=>{"use strict";var nLn=/^[a-z_$][a-z0-9_$-]*$/i,iLn=PLt(),oLn=ULt();QLt.exports={add:sLn,get:aLn,remove:lLn,validate:OUe};function sLn(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!nLn.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var n=e.type;if(Array.isArray(n))for(var i=0;i<n.length;i++)s(t,n[i],e);else s(t,n,e);var o=e.metaSchema;o&&(e.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(o,!0))}r.keywords[t]=r.all[t]=!0;function s(a,c,u){for(var d,f=0;f<r.length;f++){var p=r[f];if(p.type==c){d=p;break}}d||(d={type:c,rules:[]},r.push(d));var h={keyword:a,definition:u,custom:!0,code:iLn,implements:u.implements};d.rules.push(h),r.custom[a]=h}return this}function aLn(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function lLn(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var n=e[r].rules,i=0;i<n.length;i++)if(n[i].keyword==t){n.splice(i,1);break}return this}function OUe(t,e){OUe.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(oLn,!0);if(r(t))return!0;if(OUe.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}});var GLt=D((dUo,cLn)=>{cLn.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var XLt=D((fUo,KLt)=>{"use strict";var VLt=CPt(),jD=K0e(),uLn=xPt(),WLt=yUe(),dLn=wUe(),fLn=MPt(),pLn=ILt(),$Lt=BLt(),jLt=$D();KLt.exports=Zu;Zu.prototype.validate=mLn;Zu.prototype.compile=gLn;Zu.prototype.addSchema=ALn;Zu.prototype.addMetaSchema=yLn;Zu.prototype.validateSchema=ELn;Zu.prototype.getSchema=CLn;Zu.prototype.removeSchema=xLn;Zu.prototype.addFormat=BLn;Zu.prototype.errorsText=RLn;Zu.prototype._addSchema=wLn;Zu.prototype._compile=SLn;Zu.prototype.compileAsync=kLt();var sme=qLt();Zu.prototype.addKeyword=sme.add;Zu.prototype.getKeyword=sme.get;Zu.prototype.removeKeyword=sme.remove;Zu.prototype.validateKeyword=sme.validate;var zLt=X0e();Zu.ValidationError=zLt.Validation;Zu.MissingRefError=zLt.MissingRef;Zu.$dataMetaSchema=$Lt;var ome="http://json-schema.org/draft-07/schema",HLt=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],hLn=["/properties"];function Zu(t){if(!(this instanceof Zu))return new Zu(t);t=this._opts=jLt.copy(t)||{},LLn(this),this._schemas={},this._refs={},this._fragments={},this._formats=fLn(t.format),this._cache=t.cache||new uLn,this._loadingSchemas={},this._compilations=[],this.RULES=pLn(),this._getId=_Ln(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=dLn),this._metaOpts=PLn(this),t.formats&&kLn(this),t.keywords&&MLn(this),NLn(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),OLn(this)}function mLn(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var n=this._addSchema(t);r=n.validate||this._compile(n)}var i=r(e);return r.$async!==!0&&(this.errors=r.errors),i}function gLn(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function ALn(t,e,r,n){if(Array.isArray(t)){for(var i=0;i<t.length;i++)this.addSchema(t[i],void 0,r,n);return this}var o=this._getId(t);if(o!==void 0&&typeof o!="string")throw new Error("schema id must be string");return e=jD.normalizeId(e||o),JLt(this,e),this._schemas[e]=this._addSchema(t,r,n,!0),this}function yLn(t,e,r){return this.addSchema(t,e,r,!0),this}function ELn(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||vLn(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var n=this.validate(r,t);if(!n&&e){var i="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(i);else throw new Error(i)}return n}function vLn(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(ome)?ome:void 0,t._opts.defaultMeta}function CLn(t){var e=YLt(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return bLn(this,t)}}function bLn(t,e){var r=jD.schema.call(t,{schema:{}},e);if(r){var n=r.schema,i=r.root,o=r.baseId,s=VLt.call(t,n,i,void 0,o);return t._fragments[e]=new WLt({ref:e,fragment:!0,schema:n,root:i,baseId:o,validate:s}),s}}function YLt(t,e){return e=jD.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function xLn(t){if(t instanceof RegExp)return ime(this,this._schemas,t),ime(this,this._refs,t),this;switch(typeof t){case"undefined":return ime(this,this._schemas),ime(this,this._refs),this._cache.clear(),this;case"string":var e=YLt(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,n=r?r(t):t;this._cache.del(n);var i=this._getId(t);i&&(i=jD.normalizeId(i),delete this._schemas[i],delete this._refs[i])}return this}function ime(t,e,r){for(var n in e){var i=e[n];!i.meta&&(!r||r.test(n))&&(t._cache.del(i.cacheKey),delete e[n])}}function wLn(t,e,r,n){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var i=this._opts.serialize,o=i?i(t):t,s=this._cache.get(o);if(s)return s;n=n||this._opts.addUsedSchema!==!1;var a=jD.normalizeId(this._getId(t));a&&n&&JLt(this,a);var c=this._opts.validateSchema!==!1&&!e,u;c&&!(u=a&&a==jD.normalizeId(t.$schema))&&this.validateSchema(t,!0);var d=jD.ids.call(this,t),f=new WLt({id:a,schema:t,localRefs:d,cacheKey:o,meta:r});return a[0]!="#"&&n&&(this._refs[a]=f),this._cache.put(o,f),c&&u&&this.validateSchema(t,!0),f}function SLn(t,e){if(t.compiling)return t.validate=i,i.schema=t.schema,i.errors=null,i.root=e||i,t.schema.$async===!0&&(i.$async=!0),i;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var n;try{n=VLt.call(this,t.schema,e,t.localRefs)}catch(o){throw delete t.validate,o}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=n,t.refs=n.refs,t.refVal=n.refVal,t.root=n.root,n;function i(){var o=t.validate,s=o.apply(this,arguments);return i.errors=o.errors,s}}function _Ln(t){switch(t.schemaId){case"auto":return DLn;case"id":return TLn;default:return ILn}}function TLn(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function ILn(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function DLn(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function RLn(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,n=e.dataVar===void 0?"data":e.dataVar,i="",o=0;o<t.length;o++){var s=t[o];s&&(i+=n+s.dataPath+" "+s.message+r)}return i.slice(0,-r.length)}function BLn(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function NLn(t){var e;if(t._opts.$data&&(e=GLt(),t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=NUe();t._opts.$data&&(r=$Lt(r,hLn)),t.addMetaSchema(r,ome,!0),t._refs["http://json-schema.org/schema"]=ome}}function OLn(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function kLn(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function MLn(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function JLt(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function PLn(t){for(var e=jLt.copy(t._opts),r=0;r<HLt.length;r++)delete e[HLt[r]];return e}function LLn(t){var e=t._opts.logger;if(e===!1)t.logger={log:kUe,warn:kUe,error:kUe};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function kUe(){}});var ZLt,x1,bU=ae(()=>{KMt();uS();ZLt=Fe(XLt(),1),x1=class extends H0e{constructor(e,r){var n;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._ajv=new ZLt.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=JMt(this._capabilities,e)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:vU,capabilities:this._capabilities,clientInfo:this._clientInfo}},tUe,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!NMt.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,i,o,s;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},WD,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},uUe,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},WD,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},hX,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},pX,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},nUe,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},iUe,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},oUe,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},WD,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},WD,r)}async callTool(e,r=q0e,n){let i=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!i.structuredContent&&!i.isError)throw new N3(B3.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{if(!o(i.structuredContent))throw new N3(B3.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(o.errors)}`)}catch(s){throw s instanceof N3?s:new N3(B3.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return i}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema)try{let n=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},cUe,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}});var iFt=D((gUo,nFt)=>{nFt.exports=rFt;rFt.sync=ULn;var eFt=ye("fs");function FLn(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var i=r[n].toLowerCase();if(i&&t.substr(-i.length).toLowerCase()===i)return!0}return!1}function tFt(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:FLn(e,r)}function rFt(t,e,r){eFt.stat(t,function(n,i){r(n,n?!1:tFt(i,t,e))})}function ULn(t,e){return tFt(eFt.statSync(t),t,e)}});var cFt=D((AUo,lFt)=>{lFt.exports=sFt;sFt.sync=QLn;var oFt=ye("fs");function sFt(t,e,r){oFt.stat(t,function(n,i){r(n,n?!1:aFt(i,e))})}function QLn(t,e){return aFt(oFt.statSync(t),e)}function aFt(t,e){return t.isFile()&&qLn(t,e)}function qLn(t,e){var r=t.mode,n=t.uid,i=t.gid,o=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),s=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),d=a|c,f=r&u||r&c&&i===s||r&a&&n===o||r&d&&o===0;return f}});var dFt=D((EUo,uFt)=>{var yUo=ye("fs"),ame;process.platform==="win32"||global.TESTING_WINDOWS?ame=iFt():ame=cFt();uFt.exports=MUe;MUe.sync=GLn;function MUe(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,i){MUe(t,e||{},function(o,s){o?i(o):n(s)})})}ame(t,e||{},function(n,i){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,i=!1),r(n,i)})}function GLn(t,e){try{return ame.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var yFt=D((vUo,AFt)=>{var xU=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",fFt=ye("path"),HLn=xU?";":":",pFt=dFt(),hFt=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),mFt=(t,e)=>{let r=e.colon||HLn,n=t.match(/\//)||xU&&t.match(/\\/)?[""]:[...xU?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],i=xU?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=xU?i.split(r):[""];return xU&&t.indexOf(".")!==-1&&o[0]!==""&&o.unshift(""),{pathEnv:n,pathExt:o,pathExtExe:i}},gFt=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:i,pathExtExe:o}=mFt(t,e),s=[],a=u=>new Promise((d,f)=>{if(u===n.length)return e.all&&s.length?d(s):f(hFt(t));let p=n[u],h=/^".*"$/.test(p)?p.slice(1,-1):p,m=fFt.join(h,t),g=!h&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;d(c(g,u,0))}),c=(u,d,f)=>new Promise((p,h)=>{if(f===i.length)return p(a(d+1));let m=i[f];pFt(u+m,{pathExt:o},(g,A)=>{if(!g&&A)if(e.all)s.push(u+m);else return p(u+m);return p(c(u,d,f+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},VLn=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:i}=mFt(t,e),o=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=fFt.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let f=0;f<n.length;f++){let p=d+n[f];try{if(pFt.sync(p,{pathExt:i}))if(e.all)o.push(p);else return p}catch{}}}if(e.all&&o.length)return o;if(e.nothrow)return null;throw hFt(t)};AFt.exports=gFt;gFt.sync=VLn});var vFt=D((CUo,PUe)=>{"use strict";var EFt=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};PUe.exports=EFt;PUe.exports.default=EFt});var wFt=D((bUo,xFt)=>{"use strict";var CFt=ye("path"),WLn=yFt(),$Ln=vFt();function bFt(t,e){let r=t.options.env||process.env,n=process.cwd(),i=t.options.cwd!=null,o=i&&process.chdir!==void 0&&!process.chdir.disabled;if(o)try{process.chdir(t.options.cwd)}catch{}let s;try{s=WLn.sync(t.command,{path:r[$Ln({env:r})],pathExt:e?CFt.delimiter:void 0})}catch{}finally{o&&process.chdir(n)}return s&&(s=CFt.resolve(i?t.options.cwd:"",s)),s}function jLn(t){return bFt(t)||bFt(t,!0)}xFt.exports=jLn});var SFt=D((xUo,FUe)=>{"use strict";var LUe=/([()\][%!^"`<>&|;, *?])/g;function zLn(t){return t=t.replace(LUe,"^$1"),t}function YLn(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(LUe,"^$1"),e&&(t=t.replace(LUe,"^$1")),t}FUe.exports.command=zLn;FUe.exports.argument=YLn});var TFt=D((wUo,_Ft)=>{"use strict";_Ft.exports=/^#!(.*)/});var DFt=D((SUo,IFt)=>{"use strict";var JLn=TFt();IFt.exports=(t="")=>{let e=t.match(JLn);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),i=r.split("/").pop();return i==="env"?n:n?`${i} ${n}`:i}});var BFt=D((_Uo,RFt)=>{"use strict";var UUe=ye("fs"),KLn=DFt();function XLn(t){let r=Buffer.alloc(150),n;try{n=UUe.openSync(t,"r"),UUe.readSync(n,r,0,150,0),UUe.closeSync(n)}catch{}return KLn(r.toString())}RFt.exports=XLn});var MFt=D((TUo,kFt)=>{"use strict";var ZLn=ye("path"),NFt=wFt(),OFt=SFt(),eFn=BFt(),tFn=process.platform==="win32",rFn=/\.(?:com|exe)$/i,nFn=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function iFn(t){t.file=NFt(t);let e=t.file&&eFn(t.file);return e?(t.args.unshift(t.file),t.command=e,NFt(t)):t.file}function oFn(t){if(!tFn)return t;let e=iFn(t),r=!rFn.test(e);if(t.options.forceShell||r){let n=nFn.test(e);t.command=ZLn.normalize(t.command),t.command=OFt.command(t.command),t.args=t.args.map(o=>OFt.argument(o,n));let i=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${i}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function sFn(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:oFn(n)}kFt.exports=sFn});var FFt=D((IUo,LFt)=>{"use strict";var QUe=process.platform==="win32";function qUe(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function aFn(t,e){if(!QUe)return;let r=t.emit;t.emit=function(n,i){if(n==="exit"){let o=PFt(i,e);if(o)return r.call(t,"error",o)}return r.apply(t,arguments)}}function PFt(t,e){return QUe&&t===1&&!e.file?qUe(e.original,"spawn"):null}function lFn(t,e){return QUe&&t===1&&!e.file?qUe(e.original,"spawnSync"):null}LFt.exports={hookChildProcess:aFn,verifyENOENT:PFt,verifyENOENTSync:lFn,notFoundError:qUe}});var qFt=D((DUo,wU)=>{"use strict";var UFt=ye("child_process"),GUe=MFt(),HUe=FFt();function QFt(t,e,r){let n=GUe(t,e,r),i=UFt.spawn(n.command,n.args,n.options);return HUe.hookChildProcess(i,n),i}function cFn(t,e,r){let n=GUe(t,e,r),i=UFt.spawnSync(n.command,n.args,n.options);return i.error=i.error||HUe.verifyENOENTSync(i.status,n),i}wU.exports=QFt;wU.exports.spawn=QFt;wU.exports.sync=cFn;wU.exports._parse=GUe;wU.exports._enoent=HUe});function uFn(t){return cS.parse(JSON.parse(t))}function GFt(t){return JSON.stringify(t)+`
844
844
  `}var lme,HFt=ae(()=>{uS();lme=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
845
845
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),uFn(r)}clear(){this._buffer=void 0}}});import cme from"node:process";import{PassThrough as dFn}from"node:stream";function pFn(){let t={};for(let e of fFn){let r=cme.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}function hFn(){return"type"in cme}var VFt,fFn,SU,VUe=ae(()=>{VFt=Fe(qFt(),1);HFt();fFn=cme.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];SU=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new lme,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new dFn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var n,i,o,s,a;this._process=(0,VFt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...pFn(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:cme.platform==="win32"&&hFn(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,d;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(c),(d=this.onerror)===null||d===void 0||d.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(o=this._process.stdin)===null||o===void 0||o.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(s=this._process.stdout)===null||s===void 0||s.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(a=this._process.stdout)===null||a===void 0||a.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=GFt(e);this._process.stdin.write(i)?r():this._process.stdin.once("drain",r)})}}});function WUe(t){}function dme(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=WUe,onError:r=WUe,onRetry:n=WUe,onComment:i}=t,o="",s=!0,a,c="",u="";function d(g){let A=s?g.replace(/^\xEF\xBB\xBF/,""):g,[y,E]=mFn(`${o}${A}`);for(let C of y)f(C);o=E,s=!1}function f(g){if(g===""){h();return}if(g.startsWith(":")){i&&i(g.slice(g.startsWith(": ")?2:1));return}let A=g.indexOf(":");if(A!==-1){let y=g.slice(0,A),E=g[A+1]===" "?2:1,C=g.slice(A+E);p(y,C,g);return}p(g,"",g)}function p(g,A,y){switch(g){case"event":u=A;break;case"data":c=`${c}${A}
846
846
  `;break;case"id":a=A.includes("\0")?void 0:A;break;case"retry":/^\d+$/.test(A)?n(parseInt(A,10)):r(new ume(`Invalid \`retry\` value: "${A}"`,{type:"invalid-retry",value:A,line:y}));break;default:r(new ume(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:A,line:y}));break}}function h(){c.length>0&&e({id:a,event:u||void 0,data:c.endsWith(`
847
847
  `)?c.slice(0,-1):c}),a=void 0,c="",u=""}function m(g={}){o&&g.consume&&f(o),s=!0,a=void 0,c="",u="",o=""}return{feed:d,reset:m}}function mFn(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
848
848
  `,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?i===t.length-1?s=-1:s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
849
- `&&n++}}return[e,r]}var ume,$Ue=ae(()=>{ume=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function gFn(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function jUe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(jUe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${jUe(t.cause)}`:t.message:`${t}`}function WFt(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function AFn(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var pme,jFt,tQe,Ss,Hf,au,K8,Yg,zD,_U,fme,hme,yX,DU,EX,hS,TU,RU,IU,gX,u4,zUe,YUe,JUe,$Ft,KUe,XUe,AX,ZUe,eQe,YD,zFt=ae(()=>{$Ue();pme=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(WFt(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(WFt(this),r)}};jFt=t=>{throw TypeError(t)},tQe=(t,e,r)=>e.has(t)||jFt("Cannot "+r),Ss=(t,e,r)=>(tQe(t,e,"read from private field"),r?r.call(t):e.get(t)),Hf=(t,e,r)=>e.has(t)?jFt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),au=(t,e,r,n)=>(tQe(t,e,"write to private field"),e.set(t,r),r),K8=(t,e,r)=>(tQe(t,e,"access private method"),r),YD=class extends EventTarget{constructor(e,r){var n,i;super(),Hf(this,u4),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Hf(this,Yg),Hf(this,zD),Hf(this,_U),Hf(this,fme),Hf(this,hme),Hf(this,yX),Hf(this,DU),Hf(this,EX,null),Hf(this,hS),Hf(this,TU),Hf(this,RU,null),Hf(this,IU,null),Hf(this,gX,null),Hf(this,YUe,async o=>{var s;Ss(this,TU).reset();let{body:a,redirected:c,status:u,headers:d}=o;if(u===204){K8(this,u4,AX).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?au(this,_U,new URL(o.url)):au(this,_U,void 0),u!==200){K8(this,u4,AX).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){K8(this,u4,AX).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Ss(this,Yg)===this.CLOSED)return;au(this,Yg,this.OPEN);let f=new Event("open");if((s=Ss(this,gX))==null||s.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){K8(this,u4,AX).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=a.getReader(),m=!0;do{let{done:g,value:A}=await h.read();A&&Ss(this,TU).feed(p.decode(A,{stream:!g})),g&&(m=!1,Ss(this,TU).reset(),K8(this,u4,ZUe).call(this))}while(m)}),Hf(this,JUe,o=>{au(this,hS,void 0),!(o.name==="AbortError"||o.type==="aborted")&&K8(this,u4,ZUe).call(this,jUe(o))}),Hf(this,KUe,o=>{typeof o.id=="string"&&au(this,EX,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ss(this,_U)?Ss(this,_U).origin:Ss(this,zD).origin,lastEventId:o.id||""});Ss(this,IU)&&(!o.event||o.event==="message")&&Ss(this,IU).call(this,s),this.dispatchEvent(s)}),Hf(this,XUe,o=>{au(this,yX,o)}),Hf(this,eQe,()=>{au(this,DU,void 0),Ss(this,Yg)===this.CONNECTING&&K8(this,u4,zUe).call(this)});try{if(e instanceof URL)au(this,zD,e);else if(typeof e=="string")au(this,zD,new URL(e,AFn()));else throw new Error("Invalid URL")}catch{throw gFn("An invalid or illegal string was specified")}au(this,TU,dme({onEvent:Ss(this,KUe),onRetry:Ss(this,XUe)})),au(this,Yg,this.CONNECTING),au(this,yX,3e3),au(this,hme,(n=r?.fetch)!=null?n:globalThis.fetch),au(this,fme,(i=r?.withCredentials)!=null?i:!1),K8(this,u4,zUe).call(this)}get readyState(){return Ss(this,Yg)}get url(){return Ss(this,zD).href}get withCredentials(){return Ss(this,fme)}get onerror(){return Ss(this,RU)}set onerror(e){au(this,RU,e)}get onmessage(){return Ss(this,IU)}set onmessage(e){au(this,IU,e)}get onopen(){return Ss(this,gX)}set onopen(e){au(this,gX,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ss(this,DU)&&clearTimeout(Ss(this,DU)),Ss(this,Yg)!==this.CLOSED&&(Ss(this,hS)&&Ss(this,hS).abort(),au(this,Yg,this.CLOSED),au(this,hS,void 0))}};Yg=new WeakMap,zD=new WeakMap,_U=new WeakMap,fme=new WeakMap,hme=new WeakMap,yX=new WeakMap,DU=new WeakMap,EX=new WeakMap,hS=new WeakMap,TU=new WeakMap,RU=new WeakMap,IU=new WeakMap,gX=new WeakMap,u4=new WeakSet,zUe=function(){au(this,Yg,this.CONNECTING),au(this,hS,new AbortController),Ss(this,hme)(Ss(this,zD),K8(this,u4,$Ft).call(this)).then(Ss(this,YUe)).catch(Ss(this,JUe))},YUe=new WeakMap,JUe=new WeakMap,$Ft=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ss(this,EX)?{"Last-Event-ID":Ss(this,EX)}:void 0},cache:"no-store",signal:(t=Ss(this,hS))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KUe=new WeakMap,XUe=new WeakMap,AX=function(t,e){var r;Ss(this,Yg)!==this.CLOSED&&au(this,Yg,this.CLOSED);let n=new pme("error",{code:e,message:t});(r=Ss(this,RU))==null||r.call(this,n),this.dispatchEvent(n)},ZUe=function(t,e){var r;if(Ss(this,Yg)===this.CLOSED)return;au(this,Yg,this.CONNECTING);let n=new pme("error",{code:e,message:t});(r=Ss(this,RU))==null||r.call(this,n),this.dispatchEvent(n),au(this,DU,setTimeout(Ss(this,eQe),Ss(this,yX)))},eQe=new WeakMap,YD.CONNECTING=0,YD.OPEN=1,YD.CLOSED=2});async function yFn(t){return(await rQe).getRandomValues(new Uint8Array(t))}async function EFn(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await yFn(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function vFn(t){return await EFn(t)}async function CFn(t){let e=await(await rQe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function nQe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await vFn(t),r=await CFn(e);return{code_verifier:e,code_challenge:r}}var rQe,YFt=ae(()=>{rQe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var Rp,JFt,iQe,bFn,KFt,oQe,XFt,xFn,wFn,ZFt,qUo,GUo,sQe=ae(()=>{lS();Rp=te.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:te.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),te.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),JFt=te.object({resource:te.string().url(),authorization_servers:te.array(Rp).optional(),jwks_uri:te.string().url().optional(),scopes_supported:te.array(te.string()).optional(),bearer_methods_supported:te.array(te.string()).optional(),resource_signing_alg_values_supported:te.array(te.string()).optional(),resource_name:te.string().optional(),resource_documentation:te.string().optional(),resource_policy_uri:te.string().url().optional(),resource_tos_uri:te.string().url().optional(),tls_client_certificate_bound_access_tokens:te.boolean().optional(),authorization_details_types_supported:te.array(te.string()).optional(),dpop_signing_alg_values_supported:te.array(te.string()).optional(),dpop_bound_access_tokens_required:te.boolean().optional()}).passthrough(),iQe=te.object({issuer:te.string(),authorization_endpoint:Rp,token_endpoint:Rp,registration_endpoint:Rp.optional(),scopes_supported:te.array(te.string()).optional(),response_types_supported:te.array(te.string()),response_modes_supported:te.array(te.string()).optional(),grant_types_supported:te.array(te.string()).optional(),token_endpoint_auth_methods_supported:te.array(te.string()).optional(),token_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),service_documentation:Rp.optional(),revocation_endpoint:Rp.optional(),revocation_endpoint_auth_methods_supported:te.array(te.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),introspection_endpoint:te.string().optional(),introspection_endpoint_auth_methods_supported:te.array(te.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),code_challenge_methods_supported:te.array(te.string()).optional()}).passthrough(),bFn=te.object({issuer:te.string(),authorization_endpoint:Rp,token_endpoint:Rp,userinfo_endpoint:Rp.optional(),jwks_uri:Rp,registration_endpoint:Rp.optional(),scopes_supported:te.array(te.string()).optional(),response_types_supported:te.array(te.string()),response_modes_supported:te.array(te.string()).optional(),grant_types_supported:te.array(te.string()).optional(),acr_values_supported:te.array(te.string()).optional(),subject_types_supported:te.array(te.string()),id_token_signing_alg_values_supported:te.array(te.string()),id_token_encryption_alg_values_supported:te.array(te.string()).optional(),id_token_encryption_enc_values_supported:te.array(te.string()).optional(),userinfo_signing_alg_values_supported:te.array(te.string()).optional(),userinfo_encryption_alg_values_supported:te.array(te.string()).optional(),userinfo_encryption_enc_values_supported:te.array(te.string()).optional(),request_object_signing_alg_values_supported:te.array(te.string()).optional(),request_object_encryption_alg_values_supported:te.array(te.string()).optional(),request_object_encryption_enc_values_supported:te.array(te.string()).optional(),token_endpoint_auth_methods_supported:te.array(te.string()).optional(),token_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),display_values_supported:te.array(te.string()).optional(),claim_types_supported:te.array(te.string()).optional(),claims_supported:te.array(te.string()).optional(),service_documentation:te.string().optional(),claims_locales_supported:te.array(te.string()).optional(),ui_locales_supported:te.array(te.string()).optional(),claims_parameter_supported:te.boolean().optional(),request_parameter_supported:te.boolean().optional(),request_uri_parameter_supported:te.boolean().optional(),require_request_uri_registration:te.boolean().optional(),op_policy_uri:Rp.optional(),op_tos_uri:Rp.optional()}).passthrough(),KFt=bFn.merge(iQe.pick({code_challenge_methods_supported:!0})),oQe=te.object({access_token:te.string(),id_token:te.string().optional(),token_type:te.string(),expires_in:te.number().optional(),scope:te.string().optional(),refresh_token:te.string().optional()}).strip(),XFt=te.object({error:te.string(),error_description:te.string().optional(),error_uri:te.string().optional()}),xFn=te.object({redirect_uris:te.array(Rp),token_endpoint_auth_method:te.string().optional(),grant_types:te.array(te.string()).optional(),response_types:te.array(te.string()).optional(),client_name:te.string().optional(),client_uri:Rp.optional(),logo_uri:Rp.optional(),scope:te.string().optional(),contacts:te.array(te.string()).optional(),tos_uri:Rp.optional(),policy_uri:te.string().optional(),jwks_uri:Rp.optional(),jwks:te.any().optional(),software_id:te.string().optional(),software_version:te.string().optional(),software_statement:te.string().optional()}).strip(),wFn=te.object({client_id:te.string(),client_secret:te.string().optional(),client_id_issued_at:te.number().optional(),client_secret_expires_at:te.number().optional()}).strip(),ZFt=xFn.merge(wFn),qUo=te.object({error:te.string(),error_description:te.string().optional()}).strip(),GUo=te.object({token:te.string(),token_type_hint:te.string().optional()}).strip()});function eUt(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function tUt({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var rUt=ae(()=>{});var lf,vX,JD,KD,XD,CX,bX,xX,X8,wX,SX,_X,TX,IX,DX,RX,BX,nUt,iUt=ae(()=>{lf=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},vX=class extends lf{};vX.errorCode="invalid_request";JD=class extends lf{};JD.errorCode="invalid_client";KD=class extends lf{};KD.errorCode="invalid_grant";XD=class extends lf{};XD.errorCode="unauthorized_client";CX=class extends lf{};CX.errorCode="unsupported_grant_type";bX=class extends lf{};bX.errorCode="invalid_scope";xX=class extends lf{};xX.errorCode="access_denied";X8=class extends lf{};X8.errorCode="server_error";wX=class extends lf{};wX.errorCode="temporarily_unavailable";SX=class extends lf{};SX.errorCode="unsupported_response_type";_X=class extends lf{};_X.errorCode="unsupported_token_type";TX=class extends lf{};TX.errorCode="invalid_token";IX=class extends lf{};IX.errorCode="method_not_allowed";DX=class extends lf{};DX.errorCode="too_many_requests";RX=class extends lf{};RX.errorCode="invalid_client_metadata";BX=class extends lf{};BX.errorCode="insufficient_scope";nUt={[vX.errorCode]:vX,[JD.errorCode]:JD,[KD.errorCode]:KD,[XD.errorCode]:XD,[CX.errorCode]:CX,[bX.errorCode]:bX,[xX.errorCode]:xX,[X8.errorCode]:X8,[wX.errorCode]:wX,[SX.errorCode]:SX,[_X.errorCode]:_X,[TX.errorCode]:TX,[IX.errorCode]:IX,[DX.errorCode]:DX,[RX.errorCode]:RX,[BX.errorCode]:BX}});function sUt(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function aUt(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":SFn(i,o,r);return;case"client_secret_post":_Fn(i,o,n);return;case"none":TFn(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function SFn(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function _Fn(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function TFn(t,e){e.set("client_id",t)}async function lQe(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=XFt.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=nUt[i]||X8;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new X8(i)}}async function mS(t,e){var r,n;try{return await aQe(t,e)}catch(i){if(i instanceof JD||i instanceof XD)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await aQe(t,e);if(i instanceof KD)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await aQe(t,e);throw i}}async function aQe(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await DFn(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=e);let c=await IFn(e,t,s),u=await kFn(a,{fetchFn:o}),d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let g=await PFn(a,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(g),d=g}if(r!==void 0){let g=await t.codeVerifier(),A=await uQe(a,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:g,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(A),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let g=await dQe(a,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof lf)||g instanceof X8))throw g}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:m}=await MFn(a,{metadata:u,clientInformation:d,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(h),"REDIRECT"}async function IFn(t,e,r){let n=eUt(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!tUt({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function NX(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return;let o=/resource_metadata="([^"]*)"/.exec(e);if(o)try{return new URL(o[1])}catch{return}}async function DFn(t,e,r=fetch){let n=await NFn(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return JFt.parse(await n.json())}async function cQe(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?cQe(t,void 0,r):void 0;throw n}}function RFn(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function oUt(t,e,r=fetch){return await cQe(t,{"MCP-Protocol-Version":e},r)}function BFn(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function NFn(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:vU,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let d=RFn(e,s.pathname);c=new URL(d,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),c.search=s.search}let u=await oUt(c,a,r);if(!n?.metadataUrl&&BFn(u,s.pathname)){let d=new URL(`/.well-known/${e}`,s);u=await oUt(d,a,r)}return u}function OFn(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function kFn(t,{fetchFn:e=fetch,protocolVersion:r=vU}={}){var n;let i={"MCP-Protocol-Version":r},o=OFn(t);for(let{url:s,type:a}of o){let c=await cQe(s,i,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}if(a==="oauth")return iQe.parse(await c.json());{let u=KFt.parse(await c.json());if(!(!((n=u.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${s}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function MFn(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a="code",c="S256",u;if(e){if(u=new URL(e.authorization_endpoint),!e.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else u=new URL("/authorize",t);let d=await nQe(),f=d.code_verifier,p=d.code_challenge;return u.searchParams.set("response_type",a),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",p),u.searchParams.set("code_challenge_method",c),u.searchParams.set("redirect_uri",String(n)),o&&u.searchParams.set("state",o),i&&u.searchParams.set("scope",i),i?.includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:f}}async function uQe(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var u;let d="authorization_code",f=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:d,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(p,h,t,e);else{let g=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],A=sUt(r,g);aUt(A,r,p,h)}s&&h.set("resource",s.href);let m=await(c??fetch)(f,{method:"POST",headers:p,body:h});if(!m.ok)throw await lQe(m);return oQe.parse(await m.json())}async function dQe(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),f=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(d,f,t,e);else{let h=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],m=sUt(r,h);aUt(m,r,d,f)}i&&f.set("resource",i.href);let p=await(s??fetch)(u,{method:"POST",headers:d,body:f});if(!p.ok)throw await lQe(p);return oQe.parse({refresh_token:n,...await p.json()})}async function PFn(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await lQe(o);return ZFt.parse(await o.json())}var Jg,mme=ae(()=>{YFt();uS();sQe();sQe();rUt();iUt();Jg=class extends Error{constructor(e){super(e??"Unauthorized")}}});var fQe,BU,lUt=ae(()=>{zFt();uS();mme();fQe=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},BU=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Jg("No auth provider");let r;try{r=await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Jg;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new YD(this._url.href,{...this._eventSourceInit,fetch:async(a,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let d=await i(a,{...c,headers:u});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=NX(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var c;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let u=new fQe(a.code,a.message,a);s(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var c;let u=a;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){s(d),(c=this.onerror)===null||c===void 0||c.call(this,d),this.close();return}o()}),this._eventSource.onmessage=a=>{var c,u;let d=a,f;try{f=cS.parse(JSON.parse(d.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,f)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Jg("No auth provider");if(await mS(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,s);if(!a.ok){if(a.status===401&&this._authProvider){if(this._resourceMetadataUrl=NX(a),await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg;return this.send(e)}let c=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${c}`)}}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}});var gme,cUt=ae(()=>{$Ue();gme=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=dme({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}}});var LFn,OX,gS,pQe=ae(()=>{uS();mme();cUt();LFn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},OX=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},gS=class{constructor(e,r){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:LFn}async _authThenStart(){var e;if(!this._authProvider)throw new Jg("No auth provider");let r;try{r=await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Jg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new OX(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s;(async()=>{var c,u,d,f;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new gme).getReader();for(;;){let{value:h,done:m}=await p.read();if(m)break;if(h.id&&(s=h.id,i?.(h.id)),!h.event||h.event==="message")try{let g=cS.parse(JSON.parse(h.data));o!==void 0&&dX(g)&&(g.id=o),(c=this.onmessage)===null||c===void 0||c.call(this,g)}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g)}}}catch(p){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(h){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Jg("No auth provider");if(await mS(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s;try{let{resumptionToken:a,onresumptiontoken:c}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:M0e(e)?e.id:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,d),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){if(f.status===401&&this._authProvider){if(this._resourceMetadataUrl=NX(f),await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg;return this.send(e)}let A=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${A}`)}if(f.status===202){HMt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let m=(Array.isArray(e)?e:[e]).filter(A=>"method"in A&&"id"in A&&A.id!==void 0).length>0,g=f.headers.get("content-type");if(m)if(g?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:c},!1);else if(g?.includes("application/json")){let A=await f.json(),y=Array.isArray(A)?A.map(E=>cS.parse(E)):[cS.parse(A)];for(let E of y)(o=this.onmessage)===null||o===void 0||o.call(this,E)}else throw new OX(-1,`Unexpected content type: ${g}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!s.ok&&s.status!==405)throw new OX(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as FFn}from"node:fs/promises";var kX,MX,ZD,hQe=ae(()=>{"use strict";_L();mme();Gn();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(kX||(kX={}));MX=class extends Error{code;constructor(e,r){super(r),this.code=e}},ZD=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||b8.default}async start(){if(this._isClosed)throw new Error(k.t("websocketClient.errors.transportClosed"));let e=null;if(this._authProvider)try{let i=await this._authProvider.tokens();i?.access_token&&(e=i.access_token)}catch(i){try{let o=await this._authProvider.clientInformation();if(o){let s=await this._authProvider.tokens();if(s?.refresh_token){let a=await dQe(this._url,{clientInformation:o,refreshToken:s.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(a),a?.access_token&&(e=a.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error(k.t("websocketClient.errors.unauthorizedOAuth"))}throw i}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((i,o)=>{try{let s={headers:r};this._websocket=new this._WebSocket(n.toString(),s),this._websocket.on("open",()=>{i()}),this._websocket.on("error",a=>{let c=a.code!==void 0?a.code:void 0;o(new MX(c,`WebSocket error: ${a.message}`))}),this._websocket.on("message",async a=>{try{let c=a.toString(),u=JSON.parse(c);if(this._specialIds.has(Number(u.id))||u.type==="welcome")return;this.onmessage?.(await this._transformResponse(u))}catch(c){this.onerror?.(new Error(`Failed to parse WebSocket message: ${c instanceof Error?c.message:String(c)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(s){o(new MX(void 0,`Failed to create WebSocket: ${s}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(k.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),i=await uQe(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(i)}else throw new Error(k.t("websocketClient.errors.clientInfoNotAvailable"))}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===b8.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(k.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(k.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==b8.default.OPEN)throw new Error(k.t("websocketClient.errors.websocketNotOpen"));try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new MX(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:kX.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.3.1",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:i}=r||{};return{type:kX.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{originalText:await FFn(n,"utf8"),modifiedText:i}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:kX.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",i=>{try{let o=JSON.parse(i.toString());Number(o.id)===e&&(this._specialIds.delete(e),o.payload.success?r(o.payload.data.text):n(o.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var uUt,Ame,dUt=ae(()=>{"use strict";uUt=Fe(AK(),1);Gn();Ame=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error(k.t("mcp.auth.scopesRequired"));this.auth=new uUt.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error(k.t("mcp.auth.failedToGetAccessToken"));return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as UFn}from"node:child_process";import{promisify as QFn}from"node:util";import{platform as qFn}from"node:os";import{URL as GFn}from"node:url";function HFn(t){let e;try{e=new GFn(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function pUt(t){HFn(t);let e=qFn(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let i={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await fUt(r,n,i)}catch(o){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let s=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let a of s)try{await fUt(a,[t],i);return}catch{continue}}throw new Error(`Failed to open browser: ${o instanceof Error?o.message:"Unknown error"}`)}}var fUt,hUt=ae(()=>{"use strict";fUt=QFn(UFn)});function cs(t){return t instanceof Error&&"code"in t}function sr(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function mQe(t){if(t&&typeof t=="object"&&"response"in t){let r=VFn(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new Eme(r.error.message);case 401:return new AS(r.error.message);case 403:return new yme(r.error.message);default:}}return t}function VFn(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var yme,AS,Eme,lu=ae(()=>{"use strict";yme=class extends Error{},AS=class extends Error{},Eme=class extends Error{}});import{promises as NU}from"node:fs";import*as vme from"node:path";import*as mUt from"node:os";var Bp,Cme=ae(()=>{"use strict";lu();Gn();Bp=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=mUt.homedir();return vme.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=vme.dirname(this.getTokenFilePath());await NU.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await NU.readFile(r,"utf-8"),i=JSON.parse(n);for(let o of i)e.set(o.serverName,o)}catch(r){r.code!=="ENOENT"&&console.error(k.t("mcp.tokenStorage.errors.failedToLoadTokens",{error:sr(r)}))}return e}static async saveToken(e,r,n,i,o){await this.ensureConfigDir();let s=await this.loadTokens(),a={serverName:e,token:r,clientId:n,tokenUrl:i,mcpServerUrl:o,updatedAt:Date.now()};s.set(e,a);let c=Array.from(s.values()),u=this.getTokenFilePath();try{await NU.writeFile(u,JSON.stringify(c,null,2),{mode:384})}catch(d){throw console.error(k.t("mcp.tokenStorage.errors.failedToSaveToken",{error:sr(d)})),d}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),i=this.getTokenFilePath();try{n.length===0?await NU.unlink(i):await NU.writeFile(i,JSON.stringify(n,null,2),{mode:384})}catch(o){console.error(k.t("mcp.tokenStorage.errors.failedToRemoveToken",{error:sr(o)}))}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await NU.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(k.t("mcp.tokenStorage.errors.failedToClearTokens",{error:sr(e)}))}}}});var Np,bme=ae(()=>{"use strict";lu();Gn();Np=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${sr(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${sr(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);if(a){let c=this.metadataToOAuthConfig(a);return a.registration_endpoint&&console.log(k.t("mcp.oauth.discovery.dynamicRegistrationSupported"),a.registration_endpoint),c}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let i=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(i){let o=this.metadataToOAuthConfig(i);return i.registration_endpoint&&console.log(k.t("mcp.oauth.discovery.dynamicRegistrationSupported"),i.registration_endpoint),o}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${sr(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(k.t("mcp.oauth.discovery.foundResourceMetadataUri",{uri:r}));let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let i=n.authorization_servers[0],o=new URL("/.well-known/oauth-authorization-server",i).toString(),s=await this.fetchAuthorizationServerMetadata(o);return s?(console.log(k.t("mcp.oauth.discovery.configDiscoveredFromWwwAuth")),this.metadataToOAuthConfig(s)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as gUt from"node:http";import*as PX from"node:crypto";import{URL as gQe}from"node:url";var w1,AQe=ae(()=>{"use strict";hUt();Cme();lu();bme();Gn();w1=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let i={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let s=await o.text();throw new Error(k.t("mcp.auth.clientRegistrationFailed",{status:o.status,statusText:o.statusText,error:s}))}return await o.json()}static async discoverOAuthFromMCPServer(e){let r=Np.extractBaseUrl(e);return Np.discoverOAuthConfig(r)}static generatePKCEParams(){let e=PX.randomBytes(32).toString("base64url"),r=PX.createHash("sha256").update(e).digest("base64url"),n=PX.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let i=gUt.createServer(async(o,s)=>{try{let a=new gQe(o.url,`http://localhost:${this.REDIRECT_PORT}`);if(a.pathname!==this.REDIRECT_PATH){s.writeHead(404),s.end(k.t("mcp.ui.notFound"));return}let c=a.searchParams.get("code"),u=a.searchParams.get("state"),d=a.searchParams.get("error");if(d){s.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),s.end(`
849
+ `&&n++}}return[e,r]}var ume,$Ue=ae(()=>{ume=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function gFn(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function jUe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(jUe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${jUe(t.cause)}`:t.message:`${t}`}function WFt(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function AFn(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var pme,jFt,tQe,Ss,Hf,au,K8,Yg,zD,_U,fme,hme,yX,DU,EX,hS,TU,RU,IU,gX,u4,zUe,YUe,JUe,$Ft,KUe,XUe,AX,ZUe,eQe,YD,zFt=ae(()=>{$Ue();pme=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(WFt(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(WFt(this),r)}};jFt=t=>{throw TypeError(t)},tQe=(t,e,r)=>e.has(t)||jFt("Cannot "+r),Ss=(t,e,r)=>(tQe(t,e,"read from private field"),r?r.call(t):e.get(t)),Hf=(t,e,r)=>e.has(t)?jFt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),au=(t,e,r,n)=>(tQe(t,e,"write to private field"),e.set(t,r),r),K8=(t,e,r)=>(tQe(t,e,"access private method"),r),YD=class extends EventTarget{constructor(e,r){var n,i;super(),Hf(this,u4),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Hf(this,Yg),Hf(this,zD),Hf(this,_U),Hf(this,fme),Hf(this,hme),Hf(this,yX),Hf(this,DU),Hf(this,EX,null),Hf(this,hS),Hf(this,TU),Hf(this,RU,null),Hf(this,IU,null),Hf(this,gX,null),Hf(this,YUe,async o=>{var s;Ss(this,TU).reset();let{body:a,redirected:c,status:u,headers:d}=o;if(u===204){K8(this,u4,AX).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?au(this,_U,new URL(o.url)):au(this,_U,void 0),u!==200){K8(this,u4,AX).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){K8(this,u4,AX).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Ss(this,Yg)===this.CLOSED)return;au(this,Yg,this.OPEN);let f=new Event("open");if((s=Ss(this,gX))==null||s.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){K8(this,u4,AX).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=a.getReader(),m=!0;do{let{done:g,value:A}=await h.read();A&&Ss(this,TU).feed(p.decode(A,{stream:!g})),g&&(m=!1,Ss(this,TU).reset(),K8(this,u4,ZUe).call(this))}while(m)}),Hf(this,JUe,o=>{au(this,hS,void 0),!(o.name==="AbortError"||o.type==="aborted")&&K8(this,u4,ZUe).call(this,jUe(o))}),Hf(this,KUe,o=>{typeof o.id=="string"&&au(this,EX,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ss(this,_U)?Ss(this,_U).origin:Ss(this,zD).origin,lastEventId:o.id||""});Ss(this,IU)&&(!o.event||o.event==="message")&&Ss(this,IU).call(this,s),this.dispatchEvent(s)}),Hf(this,XUe,o=>{au(this,yX,o)}),Hf(this,eQe,()=>{au(this,DU,void 0),Ss(this,Yg)===this.CONNECTING&&K8(this,u4,zUe).call(this)});try{if(e instanceof URL)au(this,zD,e);else if(typeof e=="string")au(this,zD,new URL(e,AFn()));else throw new Error("Invalid URL")}catch{throw gFn("An invalid or illegal string was specified")}au(this,TU,dme({onEvent:Ss(this,KUe),onRetry:Ss(this,XUe)})),au(this,Yg,this.CONNECTING),au(this,yX,3e3),au(this,hme,(n=r?.fetch)!=null?n:globalThis.fetch),au(this,fme,(i=r?.withCredentials)!=null?i:!1),K8(this,u4,zUe).call(this)}get readyState(){return Ss(this,Yg)}get url(){return Ss(this,zD).href}get withCredentials(){return Ss(this,fme)}get onerror(){return Ss(this,RU)}set onerror(e){au(this,RU,e)}get onmessage(){return Ss(this,IU)}set onmessage(e){au(this,IU,e)}get onopen(){return Ss(this,gX)}set onopen(e){au(this,gX,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ss(this,DU)&&clearTimeout(Ss(this,DU)),Ss(this,Yg)!==this.CLOSED&&(Ss(this,hS)&&Ss(this,hS).abort(),au(this,Yg,this.CLOSED),au(this,hS,void 0))}};Yg=new WeakMap,zD=new WeakMap,_U=new WeakMap,fme=new WeakMap,hme=new WeakMap,yX=new WeakMap,DU=new WeakMap,EX=new WeakMap,hS=new WeakMap,TU=new WeakMap,RU=new WeakMap,IU=new WeakMap,gX=new WeakMap,u4=new WeakSet,zUe=function(){au(this,Yg,this.CONNECTING),au(this,hS,new AbortController),Ss(this,hme)(Ss(this,zD),K8(this,u4,$Ft).call(this)).then(Ss(this,YUe)).catch(Ss(this,JUe))},YUe=new WeakMap,JUe=new WeakMap,$Ft=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ss(this,EX)?{"Last-Event-ID":Ss(this,EX)}:void 0},cache:"no-store",signal:(t=Ss(this,hS))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KUe=new WeakMap,XUe=new WeakMap,AX=function(t,e){var r;Ss(this,Yg)!==this.CLOSED&&au(this,Yg,this.CLOSED);let n=new pme("error",{code:e,message:t});(r=Ss(this,RU))==null||r.call(this,n),this.dispatchEvent(n)},ZUe=function(t,e){var r;if(Ss(this,Yg)===this.CLOSED)return;au(this,Yg,this.CONNECTING);let n=new pme("error",{code:e,message:t});(r=Ss(this,RU))==null||r.call(this,n),this.dispatchEvent(n),au(this,DU,setTimeout(Ss(this,eQe),Ss(this,yX)))},eQe=new WeakMap,YD.CONNECTING=0,YD.OPEN=1,YD.CLOSED=2});async function yFn(t){return(await rQe).getRandomValues(new Uint8Array(t))}async function EFn(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await yFn(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function vFn(t){return await EFn(t)}async function CFn(t){let e=await(await rQe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function nQe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await vFn(t),r=await CFn(e);return{code_verifier:e,code_challenge:r}}var rQe,YFt=ae(()=>{rQe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var Rp,JFt,iQe,bFn,KFt,oQe,XFt,xFn,wFn,ZFt,qUo,GUo,sQe=ae(()=>{lS();Rp=te.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:te.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),te.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),JFt=te.object({resource:te.string().url(),authorization_servers:te.array(Rp).optional(),jwks_uri:te.string().url().optional(),scopes_supported:te.array(te.string()).optional(),bearer_methods_supported:te.array(te.string()).optional(),resource_signing_alg_values_supported:te.array(te.string()).optional(),resource_name:te.string().optional(),resource_documentation:te.string().optional(),resource_policy_uri:te.string().url().optional(),resource_tos_uri:te.string().url().optional(),tls_client_certificate_bound_access_tokens:te.boolean().optional(),authorization_details_types_supported:te.array(te.string()).optional(),dpop_signing_alg_values_supported:te.array(te.string()).optional(),dpop_bound_access_tokens_required:te.boolean().optional()}).passthrough(),iQe=te.object({issuer:te.string(),authorization_endpoint:Rp,token_endpoint:Rp,registration_endpoint:Rp.optional(),scopes_supported:te.array(te.string()).optional(),response_types_supported:te.array(te.string()),response_modes_supported:te.array(te.string()).optional(),grant_types_supported:te.array(te.string()).optional(),token_endpoint_auth_methods_supported:te.array(te.string()).optional(),token_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),service_documentation:Rp.optional(),revocation_endpoint:Rp.optional(),revocation_endpoint_auth_methods_supported:te.array(te.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),introspection_endpoint:te.string().optional(),introspection_endpoint_auth_methods_supported:te.array(te.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),code_challenge_methods_supported:te.array(te.string()).optional()}).passthrough(),bFn=te.object({issuer:te.string(),authorization_endpoint:Rp,token_endpoint:Rp,userinfo_endpoint:Rp.optional(),jwks_uri:Rp,registration_endpoint:Rp.optional(),scopes_supported:te.array(te.string()).optional(),response_types_supported:te.array(te.string()),response_modes_supported:te.array(te.string()).optional(),grant_types_supported:te.array(te.string()).optional(),acr_values_supported:te.array(te.string()).optional(),subject_types_supported:te.array(te.string()),id_token_signing_alg_values_supported:te.array(te.string()),id_token_encryption_alg_values_supported:te.array(te.string()).optional(),id_token_encryption_enc_values_supported:te.array(te.string()).optional(),userinfo_signing_alg_values_supported:te.array(te.string()).optional(),userinfo_encryption_alg_values_supported:te.array(te.string()).optional(),userinfo_encryption_enc_values_supported:te.array(te.string()).optional(),request_object_signing_alg_values_supported:te.array(te.string()).optional(),request_object_encryption_alg_values_supported:te.array(te.string()).optional(),request_object_encryption_enc_values_supported:te.array(te.string()).optional(),token_endpoint_auth_methods_supported:te.array(te.string()).optional(),token_endpoint_auth_signing_alg_values_supported:te.array(te.string()).optional(),display_values_supported:te.array(te.string()).optional(),claim_types_supported:te.array(te.string()).optional(),claims_supported:te.array(te.string()).optional(),service_documentation:te.string().optional(),claims_locales_supported:te.array(te.string()).optional(),ui_locales_supported:te.array(te.string()).optional(),claims_parameter_supported:te.boolean().optional(),request_parameter_supported:te.boolean().optional(),request_uri_parameter_supported:te.boolean().optional(),require_request_uri_registration:te.boolean().optional(),op_policy_uri:Rp.optional(),op_tos_uri:Rp.optional()}).passthrough(),KFt=bFn.merge(iQe.pick({code_challenge_methods_supported:!0})),oQe=te.object({access_token:te.string(),id_token:te.string().optional(),token_type:te.string(),expires_in:te.number().optional(),scope:te.string().optional(),refresh_token:te.string().optional()}).strip(),XFt=te.object({error:te.string(),error_description:te.string().optional(),error_uri:te.string().optional()}),xFn=te.object({redirect_uris:te.array(Rp),token_endpoint_auth_method:te.string().optional(),grant_types:te.array(te.string()).optional(),response_types:te.array(te.string()).optional(),client_name:te.string().optional(),client_uri:Rp.optional(),logo_uri:Rp.optional(),scope:te.string().optional(),contacts:te.array(te.string()).optional(),tos_uri:Rp.optional(),policy_uri:te.string().optional(),jwks_uri:Rp.optional(),jwks:te.any().optional(),software_id:te.string().optional(),software_version:te.string().optional(),software_statement:te.string().optional()}).strip(),wFn=te.object({client_id:te.string(),client_secret:te.string().optional(),client_id_issued_at:te.number().optional(),client_secret_expires_at:te.number().optional()}).strip(),ZFt=xFn.merge(wFn),qUo=te.object({error:te.string(),error_description:te.string().optional()}).strip(),GUo=te.object({token:te.string(),token_type_hint:te.string().optional()}).strip()});function eUt(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function tUt({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var rUt=ae(()=>{});var lf,vX,JD,KD,XD,CX,bX,xX,X8,wX,SX,_X,TX,IX,DX,RX,BX,nUt,iUt=ae(()=>{lf=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},vX=class extends lf{};vX.errorCode="invalid_request";JD=class extends lf{};JD.errorCode="invalid_client";KD=class extends lf{};KD.errorCode="invalid_grant";XD=class extends lf{};XD.errorCode="unauthorized_client";CX=class extends lf{};CX.errorCode="unsupported_grant_type";bX=class extends lf{};bX.errorCode="invalid_scope";xX=class extends lf{};xX.errorCode="access_denied";X8=class extends lf{};X8.errorCode="server_error";wX=class extends lf{};wX.errorCode="temporarily_unavailable";SX=class extends lf{};SX.errorCode="unsupported_response_type";_X=class extends lf{};_X.errorCode="unsupported_token_type";TX=class extends lf{};TX.errorCode="invalid_token";IX=class extends lf{};IX.errorCode="method_not_allowed";DX=class extends lf{};DX.errorCode="too_many_requests";RX=class extends lf{};RX.errorCode="invalid_client_metadata";BX=class extends lf{};BX.errorCode="insufficient_scope";nUt={[vX.errorCode]:vX,[JD.errorCode]:JD,[KD.errorCode]:KD,[XD.errorCode]:XD,[CX.errorCode]:CX,[bX.errorCode]:bX,[xX.errorCode]:xX,[X8.errorCode]:X8,[wX.errorCode]:wX,[SX.errorCode]:SX,[_X.errorCode]:_X,[TX.errorCode]:TX,[IX.errorCode]:IX,[DX.errorCode]:DX,[RX.errorCode]:RX,[BX.errorCode]:BX}});function sUt(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function aUt(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":SFn(i,o,r);return;case"client_secret_post":_Fn(i,o,n);return;case"none":TFn(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function SFn(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function _Fn(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function TFn(t,e){e.set("client_id",t)}async function lQe(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=XFt.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=nUt[i]||X8;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new X8(i)}}async function mS(t,e){var r,n;try{return await aQe(t,e)}catch(i){if(i instanceof JD||i instanceof XD)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await aQe(t,e);if(i instanceof KD)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await aQe(t,e);throw i}}async function aQe(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await DFn(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=e);let c=await IFn(e,t,s),u=await kFn(a,{fetchFn:o}),d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let g=await PFn(a,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(g),d=g}if(r!==void 0){let g=await t.codeVerifier(),A=await uQe(a,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:g,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(A),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let g=await dQe(a,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof lf)||g instanceof X8))throw g}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:m}=await MFn(a,{metadata:u,clientInformation:d,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(h),"REDIRECT"}async function IFn(t,e,r){let n=eUt(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!tUt({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function NX(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return;let o=/resource_metadata="([^"]*)"/.exec(e);if(o)try{return new URL(o[1])}catch{return}}async function DFn(t,e,r=fetch){let n=await NFn(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return JFt.parse(await n.json())}async function cQe(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?cQe(t,void 0,r):void 0;throw n}}function RFn(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function oUt(t,e,r=fetch){return await cQe(t,{"MCP-Protocol-Version":e},r)}function BFn(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function NFn(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:vU,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let d=RFn(e,s.pathname);c=new URL(d,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),c.search=s.search}let u=await oUt(c,a,r);if(!n?.metadataUrl&&BFn(u,s.pathname)){let d=new URL(`/.well-known/${e}`,s);u=await oUt(d,a,r)}return u}function OFn(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function kFn(t,{fetchFn:e=fetch,protocolVersion:r=vU}={}){var n;let i={"MCP-Protocol-Version":r},o=OFn(t);for(let{url:s,type:a}of o){let c=await cQe(s,i,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}if(a==="oauth")return iQe.parse(await c.json());{let u=KFt.parse(await c.json());if(!(!((n=u.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${s}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function MFn(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a="code",c="S256",u;if(e){if(u=new URL(e.authorization_endpoint),!e.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else u=new URL("/authorize",t);let d=await nQe(),f=d.code_verifier,p=d.code_challenge;return u.searchParams.set("response_type",a),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",p),u.searchParams.set("code_challenge_method",c),u.searchParams.set("redirect_uri",String(n)),o&&u.searchParams.set("state",o),i&&u.searchParams.set("scope",i),i?.includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:f}}async function uQe(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var u;let d="authorization_code",f=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:d,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(p,h,t,e);else{let g=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],A=sUt(r,g);aUt(A,r,p,h)}s&&h.set("resource",s.href);let m=await(c??fetch)(f,{method:"POST",headers:p,body:h});if(!m.ok)throw await lQe(m);return oQe.parse(await m.json())}async function dQe(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),f=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(d,f,t,e);else{let h=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],m=sUt(r,h);aUt(m,r,d,f)}i&&f.set("resource",i.href);let p=await(s??fetch)(u,{method:"POST",headers:d,body:f});if(!p.ok)throw await lQe(p);return oQe.parse({refresh_token:n,...await p.json()})}async function PFn(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await lQe(o);return ZFt.parse(await o.json())}var Jg,mme=ae(()=>{YFt();uS();sQe();sQe();rUt();iUt();Jg=class extends Error{constructor(e){super(e??"Unauthorized")}}});var fQe,BU,lUt=ae(()=>{zFt();uS();mme();fQe=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},BU=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Jg("No auth provider");let r;try{r=await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Jg;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new YD(this._url.href,{...this._eventSourceInit,fetch:async(a,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let d=await i(a,{...c,headers:u});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=NX(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var c;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let u=new fQe(a.code,a.message,a);s(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var c;let u=a;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){s(d),(c=this.onerror)===null||c===void 0||c.call(this,d),this.close();return}o()}),this._eventSource.onmessage=a=>{var c,u;let d=a,f;try{f=cS.parse(JSON.parse(d.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,f)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Jg("No auth provider");if(await mS(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,s);if(!a.ok){if(a.status===401&&this._authProvider){if(this._resourceMetadataUrl=NX(a),await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg;return this.send(e)}let c=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${c}`)}}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}});var gme,cUt=ae(()=>{$Ue();gme=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=dme({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}}});var LFn,OX,gS,pQe=ae(()=>{uS();mme();cUt();LFn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},OX=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},gS=class{constructor(e,r){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:LFn}async _authThenStart(){var e;if(!this._authProvider)throw new Jg("No auth provider");let r;try{r=await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Jg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new OX(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s;(async()=>{var c,u,d,f;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new gme).getReader();for(;;){let{value:h,done:m}=await p.read();if(m)break;if(h.id&&(s=h.id,i?.(h.id)),!h.event||h.event==="message")try{let g=cS.parse(JSON.parse(h.data));o!==void 0&&dX(g)&&(g.id=o),(c=this.onmessage)===null||c===void 0||c.call(this,g)}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g)}}}catch(p){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(h){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Jg("No auth provider");if(await mS(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s;try{let{resumptionToken:a,onresumptiontoken:c}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:M0e(e)?e.id:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,d),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){if(f.status===401&&this._authProvider){if(this._resourceMetadataUrl=NX(f),await mS(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Jg;return this.send(e)}let A=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${A}`)}if(f.status===202){HMt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let m=(Array.isArray(e)?e:[e]).filter(A=>"method"in A&&"id"in A&&A.id!==void 0).length>0,g=f.headers.get("content-type");if(m)if(g?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:c},!1);else if(g?.includes("application/json")){let A=await f.json(),y=Array.isArray(A)?A.map(E=>cS.parse(E)):[cS.parse(A)];for(let E of y)(o=this.onmessage)===null||o===void 0||o.call(this,E)}else throw new OX(-1,`Unexpected content type: ${g}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!s.ok&&s.status!==405)throw new OX(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as FFn}from"node:fs/promises";var kX,MX,ZD,hQe=ae(()=>{"use strict";_L();mme();Gn();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(kX||(kX={}));MX=class extends Error{code;constructor(e,r){super(r),this.code=e}},ZD=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||b8.default}async start(){if(this._isClosed)throw new Error(k.t("websocketClient.errors.transportClosed"));let e=null;if(this._authProvider)try{let i=await this._authProvider.tokens();i?.access_token&&(e=i.access_token)}catch(i){try{let o=await this._authProvider.clientInformation();if(o){let s=await this._authProvider.tokens();if(s?.refresh_token){let a=await dQe(this._url,{clientInformation:o,refreshToken:s.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(a),a?.access_token&&(e=a.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error(k.t("websocketClient.errors.unauthorizedOAuth"))}throw i}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((i,o)=>{try{let s={headers:r};this._websocket=new this._WebSocket(n.toString(),s),this._websocket.on("open",()=>{i()}),this._websocket.on("error",a=>{let c=a.code!==void 0?a.code:void 0;o(new MX(c,`WebSocket error: ${a.message}`))}),this._websocket.on("message",async a=>{try{let c=a.toString(),u=JSON.parse(c);if(this._specialIds.has(Number(u.id))||u.type==="welcome")return;this.onmessage?.(await this._transformResponse(u))}catch(c){this.onerror?.(new Error(`Failed to parse WebSocket message: ${c instanceof Error?c.message:String(c)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(s){o(new MX(void 0,`Failed to create WebSocket: ${s}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(k.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),i=await uQe(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(i)}else throw new Error(k.t("websocketClient.errors.clientInfoNotAvailable"))}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===b8.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(k.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(k.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==b8.default.OPEN)throw new Error(k.t("websocketClient.errors.websocketNotOpen"));try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new MX(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:kX.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.3.2-beta.0",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:i}=r||{};return{type:kX.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{originalText:await FFn(n,"utf8"),modifiedText:i}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:kX.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",i=>{try{let o=JSON.parse(i.toString());Number(o.id)===e&&(this._specialIds.delete(e),o.payload.success?r(o.payload.data.text):n(o.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var uUt,Ame,dUt=ae(()=>{"use strict";uUt=Fe(AK(),1);Gn();Ame=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error(k.t("mcp.auth.scopesRequired"));this.auth=new uUt.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error(k.t("mcp.auth.failedToGetAccessToken"));return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as UFn}from"node:child_process";import{promisify as QFn}from"node:util";import{platform as qFn}from"node:os";import{URL as GFn}from"node:url";function HFn(t){let e;try{e=new GFn(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function pUt(t){HFn(t);let e=qFn(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let i={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await fUt(r,n,i)}catch(o){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let s=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let a of s)try{await fUt(a,[t],i);return}catch{continue}}throw new Error(`Failed to open browser: ${o instanceof Error?o.message:"Unknown error"}`)}}var fUt,hUt=ae(()=>{"use strict";fUt=QFn(UFn)});function cs(t){return t instanceof Error&&"code"in t}function sr(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function mQe(t){if(t&&typeof t=="object"&&"response"in t){let r=VFn(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new Eme(r.error.message);case 401:return new AS(r.error.message);case 403:return new yme(r.error.message);default:}}return t}function VFn(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var yme,AS,Eme,lu=ae(()=>{"use strict";yme=class extends Error{},AS=class extends Error{},Eme=class extends Error{}});import{promises as NU}from"node:fs";import*as vme from"node:path";import*as mUt from"node:os";var Bp,Cme=ae(()=>{"use strict";lu();Gn();Bp=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=mUt.homedir();return vme.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=vme.dirname(this.getTokenFilePath());await NU.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await NU.readFile(r,"utf-8"),i=JSON.parse(n);for(let o of i)e.set(o.serverName,o)}catch(r){r.code!=="ENOENT"&&console.error(k.t("mcp.tokenStorage.errors.failedToLoadTokens",{error:sr(r)}))}return e}static async saveToken(e,r,n,i,o){await this.ensureConfigDir();let s=await this.loadTokens(),a={serverName:e,token:r,clientId:n,tokenUrl:i,mcpServerUrl:o,updatedAt:Date.now()};s.set(e,a);let c=Array.from(s.values()),u=this.getTokenFilePath();try{await NU.writeFile(u,JSON.stringify(c,null,2),{mode:384})}catch(d){throw console.error(k.t("mcp.tokenStorage.errors.failedToSaveToken",{error:sr(d)})),d}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),i=this.getTokenFilePath();try{n.length===0?await NU.unlink(i):await NU.writeFile(i,JSON.stringify(n,null,2),{mode:384})}catch(o){console.error(k.t("mcp.tokenStorage.errors.failedToRemoveToken",{error:sr(o)}))}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await NU.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(k.t("mcp.tokenStorage.errors.failedToClearTokens",{error:sr(e)}))}}}});var Np,bme=ae(()=>{"use strict";lu();Gn();Np=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${sr(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${sr(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);if(a){let c=this.metadataToOAuthConfig(a);return a.registration_endpoint&&console.log(k.t("mcp.oauth.discovery.dynamicRegistrationSupported"),a.registration_endpoint),c}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let i=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(i){let o=this.metadataToOAuthConfig(i);return i.registration_endpoint&&console.log(k.t("mcp.oauth.discovery.dynamicRegistrationSupported"),i.registration_endpoint),o}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${sr(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(k.t("mcp.oauth.discovery.foundResourceMetadataUri",{uri:r}));let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let i=n.authorization_servers[0],o=new URL("/.well-known/oauth-authorization-server",i).toString(),s=await this.fetchAuthorizationServerMetadata(o);return s?(console.log(k.t("mcp.oauth.discovery.configDiscoveredFromWwwAuth")),this.metadataToOAuthConfig(s)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as gUt from"node:http";import*as PX from"node:crypto";import{URL as gQe}from"node:url";var w1,AQe=ae(()=>{"use strict";hUt();Cme();lu();bme();Gn();w1=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let i={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let s=await o.text();throw new Error(k.t("mcp.auth.clientRegistrationFailed",{status:o.status,statusText:o.statusText,error:s}))}return await o.json()}static async discoverOAuthFromMCPServer(e){let r=Np.extractBaseUrl(e);return Np.discoverOAuthConfig(r)}static generatePKCEParams(){let e=PX.randomBytes(32).toString("base64url"),r=PX.createHash("sha256").update(e).digest("base64url"),n=PX.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let i=gUt.createServer(async(o,s)=>{try{let a=new gQe(o.url,`http://localhost:${this.REDIRECT_PORT}`);if(a.pathname!==this.REDIRECT_PATH){s.writeHead(404),s.end(k.t("mcp.ui.notFound"));return}let c=a.searchParams.get("code"),u=a.searchParams.get("state"),d=a.searchParams.get("error");if(d){s.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),s.end(`
850
850
  <html>
851
851
  <body>
852
852
  <h1>${k.t("mcp.ui.authenticationFailed")}</h1>
@@ -1593,7 +1593,7 @@ ${g}`:""),stdout:m,stderr:g,exitCode:w,signal:M,error:y,aborted:i.aborted,pid:u.
1593
1593
  1. Wrap the entire path in double quotes: "path with spaces"
1594
1594
  2. Wrap the entire path in single quotes: 'path with spaces'
1595
1595
  3. Use backslash to escape each space: path\\ with\\ spaces
1596
- `;return woe.platform()==="win32"?`This tool executes a given windows shell command as \`cmd.exe /c <command>\`. Command can start background processes using \`start /b\`.${e}${t}`:`This tool executes a given shell command as \`bash -c <command>\`. Command can start background processes using \`&\`. Command is executed as a subprocess that leads its own process group. Command process group can be terminated as \`kill -- -PGID\` or signaled as \`kill -s SIGNAL -- -PGID\`.${e}${t}`}function XUi(){let t="\n*** WARNING: Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons.";return woe.platform()==="win32"?"Exact command to execute as `cmd.exe /c <command>`"+t:"Exact bash command to execute as `bash -c <command>`"+t}var Vut,pu,Soe=ae(()=>{"use strict";Gn();su();b1();il();x0();lu();xxr();Fut();Qut();Hut();Vut=1e3,pu=class t extends po{config;static Name="run_shell_command";allowlist=new Set;static ExecutionError=class extends Error{type;constructor(e,r){super(r),this.type=e,this.name="ShellToolExecutionError"}};constructor(e){super(t.Name,"Shell",KUi(),ho.Terminal,mo.Execute,{type:Pt.OBJECT,properties:{command:{type:Pt.STRING,description:XUi()},description:{type:Pt.STRING,description:"Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks."},directory:{type:Pt.STRING,description:"(OPTIONAL) Directory to run the command in, if not the project root directory. Must be relative to the project root directory and must already exist."}},required:["command"]},!1,!0,["shell","Shell","bash","Bash","exec","Exec","run","Run","runShellCommand","RunShellCommand"]),this.config=e}getDescription(e){let r=`${e.command}`;return e.directory&&(r+=` [in ${e.directory}]`),e.description&&(r+=` (${e.description.replace(/\n/g," ")})`),r}validateToolParams(e){let r=Gut(e.command,this.config);if(!r.allowed)return r.reason?r.reason:(console.error("Unexpected: isCommandAllowed returned false without a reason"),k.t("shellTool.errors.commandNotAllowed",{command:e.command}));let n=Wa.validate(this.schema.parameters,e);if(n)return n;if(!e.command.trim())return k.t("shellTool.errors.commandEmpty");if(Gve(e.command).length===0)return k.t("shellTool.errors.couldNotIdentifyCommand");if(e.directory){if($ve.isAbsolute(e.directory))return k.t("shellTool.errors.directoryAbsolute",{directory:e.directory});let o=this.config.getWorkspaceContext().getDirectories().filter(s=>$ve.basename(s)===e.directory);if(o.length===0)return k.t("shellTool.errors.directoryNotRegistered",{directory:e.directory});if(o.length>1)return k.t("shellTool.errors.directoryAmbiguous",{directory:e.directory})}return null}async shouldConfirmExecute(e,r){if(this.validateToolParams(e))return!1;let n=Hve(e.command),o=[...new Set(Gve(n))].filter(a=>!this.allowlist.has(a));return o.length===0?!1:{type:"exec",title:"Confirm Shell Command",command:e.command,rootCommand:o.join(", "),onConfirm:async a=>{a===zr.ProceedAlways&&o.forEach(c=>this.allowlist.add(c))}}}async execute(e,r,n,i){let o=Hve(e.command),s=this.validateToolParams({...e,command:o});if(s)return{llmContent:s,returnDisplay:s,error:{message:s,type:Ur.INVALID_TOOL_PARAMS}};if(r.aborted)return{llmContent:k.t("shellTool.messages.commandCancelled"),returnDisplay:k.t("shellTool.messages.commandCancelled"),error:{message:k.t("shellTool.messages.commandCancelled"),type:Ur.EXECUTION_FAILED}};let a=woe.platform()==="win32",c=`shell_pgrep_${JUi.randomBytes(6).toString("hex")}.tmp`,u=$ve.join(woe.tmpdir(),c);try{let d=a?o:(()=>{let U=o.trim();return U.endsWith("&")||(U+=";"),`{ ${U} }; __code=$?; pgrep -g 0 >${u} 2>&1; exit $__code;`})(),f=$ve.resolve(this.config.getTargetDir(),e.directory||""),p="",h="",m=Date.now(),g=!1,A=this.config.getShouldUseNodePtyShell(),y={...this.config.getShellExecutionConfig(),...i??{}},{result:E}=T9.execute(d,f,U=>{if(!n)return;let w="",M=!1;switch(U.type){case"data":if(g)break;U.stream==="stdout"?p+=U.chunk:h+=U.chunk,w=p+(h?`
1596
+ `;return woe.platform()==="win32"?`This tool executes a given windows shell command as \`cmd.exe /c <command>\`. Command can start background processes using \`start /b\`.${e}${t}`:`This tool executes a given shell command as \`bash -c <command>\`. Command can start background processes using \`&\`. Command is executed as a subprocess that leads its own process group. Command process group can be terminated as \`kill -- -PGID\` or signaled as \`kill -s SIGNAL -- -PGID\`.${e}${t}`}function XUi(){let t="\n*** WARNING: Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons.";return woe.platform()==="win32"?"Exact command to execute as `cmd.exe /c <command>`"+t:"Exact bash command to execute as `bash -c <command>`"+t}var Vut,pu,Soe=ae(()=>{"use strict";Gn();su();b1();il();x0();lu();xxr();Fut();Qut();Hut();Vut=1e3,pu=class t extends po{config;static Name="run_shell_command";allowlist=new Set;static ExecutionError=class extends Error{type;constructor(e,r){super(r),this.type=e,this.name="ShellToolExecutionError"}};constructor(e){super(t.Name,"Shell Command",KUi(),ho.Terminal,mo.Execute,{type:Pt.OBJECT,properties:{command:{type:Pt.STRING,description:XUi()},description:{type:Pt.STRING,description:"Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks."},directory:{type:Pt.STRING,description:"(OPTIONAL) Directory to run the command in, if not the project root directory. Must be relative to the project root directory and must already exist."}},required:["command"]},!1,!0,["shell","Shell","bash","Bash","exec","Exec","run","Run","runShellCommand","RunShellCommand"]),this.config=e}getDescription(e){let r=`${e.command}`;return e.directory&&(r+=` [in ${e.directory}]`),e.description&&(r+=` (${e.description.replace(/\n/g," ")})`),r}validateToolParams(e){let r=Gut(e.command,this.config);if(!r.allowed)return r.reason?r.reason:(console.error("Unexpected: isCommandAllowed returned false without a reason"),k.t("shellTool.errors.commandNotAllowed",{command:e.command}));let n=Wa.validate(this.schema.parameters,e);if(n)return n;if(!e.command.trim())return k.t("shellTool.errors.commandEmpty");if(Gve(e.command).length===0)return k.t("shellTool.errors.couldNotIdentifyCommand");if(e.directory){if($ve.isAbsolute(e.directory))return k.t("shellTool.errors.directoryAbsolute",{directory:e.directory});let o=this.config.getWorkspaceContext().getDirectories().filter(s=>$ve.basename(s)===e.directory);if(o.length===0)return k.t("shellTool.errors.directoryNotRegistered",{directory:e.directory});if(o.length>1)return k.t("shellTool.errors.directoryAmbiguous",{directory:e.directory})}return null}async shouldConfirmExecute(e,r){if(this.validateToolParams(e))return!1;let n=Hve(e.command),o=[...new Set(Gve(n))].filter(a=>!this.allowlist.has(a));return o.length===0?!1:{type:"exec",title:"Confirm Shell Command",command:e.command,rootCommand:o.join(", "),onConfirm:async a=>{a===zr.ProceedAlways&&o.forEach(c=>this.allowlist.add(c))}}}async execute(e,r,n,i){let o=Hve(e.command),s=this.validateToolParams({...e,command:o});if(s)return{llmContent:s,returnDisplay:s,error:{message:s,type:Ur.INVALID_TOOL_PARAMS}};if(r.aborted)return{llmContent:k.t("shellTool.messages.commandCancelled"),returnDisplay:k.t("shellTool.messages.commandCancelled"),error:{message:k.t("shellTool.messages.commandCancelled"),type:Ur.EXECUTION_FAILED}};let a=woe.platform()==="win32",c=`shell_pgrep_${JUi.randomBytes(6).toString("hex")}.tmp`,u=$ve.join(woe.tmpdir(),c);try{let d=a?o:(()=>{let U=o.trim();return U.endsWith("&")||(U+=";"),`{ ${U} }; __code=$?; pgrep -g 0 >${u} 2>&1; exit $__code;`})(),f=$ve.resolve(this.config.getTargetDir(),e.directory||""),p="",h="",m=Date.now(),g=!1,A=this.config.getShouldUseNodePtyShell(),y={...this.config.getShellExecutionConfig(),...i??{}},{result:E}=T9.execute(d,f,U=>{if(!n)return;let w="",M=!1;switch(U.type){case"data":if(g)break;U.stream==="stdout"?p+=U.chunk:h+=U.chunk,w=p+(h?`
1597
1597
  ${h}`:""),Date.now()-m>Vut&&(M=!0);break;case"binary_detected":g=!0,w="[Binary output detected. Halting stream...]",M=!0;break;case"binary_progress":g=!0,w=`[Receiving binary output... ${Uut(U.bytesReceived)} received]`,Date.now()-m>Vut&&(M=!0);break;default:throw new Error("An unhandled ShellOutputEvent was found.")}M&&(n(w),m=Date.now())},r,this.config.getShellTimeout(),A,y),C=await E,x=[];if(woe.platform()!=="win32")if(Wve.existsSync(u)){let U=Wve.readFileSync(u,"utf8").split(YUi).filter(Boolean);for(let w of U){/^\d+$/.test(w)||console.error(`pgrep: ${w}`);let M=Number(w);M!==C.pid&&x.push(M)}}else r.aborted||C.error?.message?.includes("timed out after")||console.error("missing pgrep output");let T="";if(C.aborted)T=k.t("shellTool.messages.commandCancelled"),C.output.trim()?T+=` Below is the output (on stdout and stderr) before it was cancelled:
1598
1598
  ${C.output}`:T+=" There was no output before it was cancelled.";else{let U=C.error?C.error.message.replace(d,e.command):"(none)";T=[`Command: ${e.command}`,`Directory: ${e.directory||"(root)"}`,`Stdout: ${C.stdout||"(empty)"}`,`Stderr: ${C.stderr||"(empty)"}`,`Error: ${U}`,`Exit Code: ${C.exitCode??"(none)"}`,`Signal: ${C.signal??"(none)"}`,`Background PIDs: ${x.length?x.join(", "):"(none)"}`,`Process Group PGID: ${C.pid??"(none)"}`].join(`
1599
1599
  `)}let O="";this.config.getDebugMode()?O=T:C.output.trim()?O=C.output:C.aborted?O=k.t("shellTool.messages.commandCancelled"):C.signal?O=`Command terminated by signal: ${C.signal}`:C.error?O=k.t("shellTool.errors.commandFailed",{error:sr(C.error)}):C.exitCode!==null&&C.exitCode!==0&&(O=`Command exited with code: ${C.exitCode}`);let N=this.config.getSummarizeToolOutputConfig();return N&&N[this.name]?{llmContent:await bxr(T,this.config.getGeminiClient(),r,N[this.name].tokenBudget),returnDisplay:O,...C.error||C.exitCode!==0||C.signal?{error:{message:C.error?C.error.message:C.signal?`Command terminated by signal: ${C.signal}`:`Command exited with code: ${C.exitCode}`,type:Ur.EXECUTION_FAILED}}:{}}:{llmContent:T,returnDisplay:O,...C.error||C.exitCode!==0||C.signal?{error:{message:C.error?C.error.message:C.signal?`Command terminated by signal: ${C.signal}`:`Command exited with code: ${C.exitCode}`,type:Ur.EXECUTION_FAILED}}:{}}}finally{Wve.existsSync(u)&&Wve.unlinkSync(u)}}}});var I9,Fwr=ae(()=>{I9=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}}});function Uwr(t){return/^[0-9A-Fa-f]$/.test(t)}function E_(t){return t>="0"&&t<="9"}function Qwr(t){return t>=" "}function _oe(t){return`,:[]/{}()
@@ -3734,7 +3734,7 @@ ${n}`:i.hookAdditionalContext=n,i}static standardizeToolResponse(e,r,n,i){let o=
3734
3734
  `)||"SubagentStop hooks prevented subagent from ending",suggestions:i}}static extractSubagentContext(e,r){let n={timestamp:new Date().toISOString()};return e&&(e.subagent_type&&(n.subagent_type=e.subagent_type),e.description&&(n.description=e.description),e.prompt&&(n.prompt=e.prompt)),r&&(n.success=!r.error,r.error&&(n.error={message:r.error.message,type:r.error.type}),r.summary&&(n.summary=r.summary),r.llmContent&&(n.content_preview=this.extractContentPreview(r.llmContent))),n}static extractContentPreview(e){if(typeof e=="string")return e.substring(0,500)+(e.length>500?"...":"");if(Array.isArray(e)){let r=e.filter(n=>typeof n=="string"||n&&typeof n.text=="string").map(n=>typeof n=="string"?n:n.text).join(" ");return r.substring(0,500)+(r.length>500?"...":"")}if(e&&typeof e=="object"){if(e.text)return e.text.substring(0,500)+(e.text.length>500?"...":"");try{let r=JSON.stringify(e,null,2);return r.substring(0,500)+(r.length>500?"...":"")}catch{return"[Complex object]"}}return"[No content]"}}});var _le,HKr=ae(()=>{"use strict";Yy();wE();Gn();_le=class{manager;eventType=on.SetUpEnvironment;configs=[];constructor(e){this.manager=e}async execute(e,r){let n=this.getHookConfigs();if(!n||n.length===0)return[];let i=[];for(let o of n)try{let s=await Ra.execute(o.hooks,e,r);if(i.push(...s),Ra.wouldBlock(s))break}catch(s){console.warn(k.t("hooks.hookExecutionFailed"),s),i.push({success:!1,exitCode:1,stdout:"",stderr:`Hook execution failed: ${s}`,blocked:!1,duration:0})}return i}getHookConfigs(){return this.configs}setConfigs(e){this.configs=e}async executeForEnvironment(e,r,n){let i={session_id:n.sessionId,transcript_path:n.transcriptPath,cwd:n.cwd,hook_event_name:on.SetUpEnvironment,current_env_parts:JSON.stringify(e),env_context:r};return await this.execute(i,n)}hasHooks(){return this.getHookConfigs().length>0}validateConfigs(e){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.matcher!==void 0&&r.push(`SetUpEnvironment[${n}]: matcher is not supported for SetUpEnvironment hooks`),(!i.hooks||!Array.isArray(i.hooks)||i.hooks.length===0)&&r.push(`SetUpEnvironment[${n}]: hooks must be a non-empty array`),i.hooks){let o=Ra.validateCommands(i.hooks);r.push(...o.map(s=>`SetUpEnvironment[${n}]: ${s}`))}}return r}static parseHookOutputToParts(e){let r=e.trim();return r?[{text:r}]:[]}static applyHookResults(e,r){let n=r.filter(o=>o.success&&o.stdout.trim());if(n.length===0)return e;let i=n[n.length-1];return this.parseHookOutputToParts(i.stdout)}static createEnvironmentContext(e,r,n,i){return{platform:e,date:r,workspace_directories:n,folder_structure:i}}}});var VKr={};Uf(VKr,{SessionStartHook:()=>eM});var eM,I_e=ae(()=>{"use strict";Yy();wE();Gn();eM=class{manager;eventType=on.SessionStart;configs=[];constructor(e){this.manager=e}async execute(e,r){let n=this.getHookConfigs();if(!n||n.length===0)return[];let i=[],{source:o}=e;for(let s of n)if(this.shouldExecuteHook(o,s))try{let a=await Ra.execute(s.hooks,e,r);i.push(...a)}catch(a){console.warn(k.t("hooks.hookExecutionFailed"),a),i.push({success:!1,exitCode:1,stdout:"",stderr:`Hook execution failed: ${a}`,blocked:!1,duration:0})}return i}shouldExecuteHook(e,r){return r.matcher?r.matcher===e||r.matcher==="*":!0}getHookConfigs(){return this.configs}setConfigs(e){this.configs=e}hasHooks(){return this.configs.length>0}getMatchingConfigs(e){return this.getHookConfigs().filter(n=>this.shouldExecuteHook(e,n))}validateConfigs(e){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.matcher!==void 0&&typeof i.matcher!="string"&&r.push(`SessionStart[${n}]: matcher must be a string`),(!i.hooks||!Array.isArray(i.hooks)||i.hooks.length===0)&&r.push(`SessionStart[${n}]: hooks must be a non-empty array`),i.hooks){let o=Ra.validateCommands(i.hooks);r.push(...o.map(s=>`SessionStart[${n}]: ${s}`))}}return r}static collectAdditionalContext(e){let r=[];for(let n of e)if(n.hookSpecificOutput?.hookEventName==="SessionStart"){let i=n.hookSpecificOutput;i.additionalContext&&r.push(i.additionalContext)}return r.join(`
3735
3735
  `)}}});var bj,A6t=ae(()=>{"use strict";Yy();wE();Gn();bj=class{manager;eventType=on.SessionEnd;configs=[];constructor(e){this.manager=e}async execute(e,r){let n=this.getHookConfigs();if(!n||n.length===0)return[];let i=[],{reason:o}=e;for(let s of n)if(this.shouldExecuteHook(o,s))try{let a=await Ra.execute(s.hooks,e,r);i.push(...a)}catch(a){console.warn(k.t("hooks.hookExecutionFailed"),a),i.push({success:!1,exitCode:1,stdout:"",stderr:`Hook execution failed: ${a}`,blocked:!1,duration:0})}return i}shouldExecuteHook(e,r){return r.matcher?r.matcher===e||r.matcher==="*":!0}getHookConfigs(){return this.configs}setConfigs(e){this.configs=e}hasHooks(){return this.configs.length>0}getMatchingConfigs(e){return this.getHookConfigs().filter(n=>this.shouldExecuteHook(e,n))}validateConfigs(e){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.matcher!==void 0&&typeof i.matcher!="string"&&r.push(`SessionEnd[${n}]: matcher must be a string`),(!i.hooks||!Array.isArray(i.hooks)||i.hooks.length===0)&&r.push(`SessionEnd[${n}]: hooks must be a non-empty array`),i.hooks){let o=Ra.validateCommands(i.hooks);r.push(...o.map(s=>`SessionEnd[${n}]: ${s}`))}}return r}}});var yT,y6t=ae(()=>{"use strict";Yy();wE();Gn();yT=class{manager;eventType=on.UserPromptSubmit;configs=[];constructor(e){this.manager=e}async execute(e,r){let n=this.getHookConfigs();if(!n||n.length===0)return[];let i=[],{prompt:o}=e;for(let s of n)if(this.shouldExecuteHook(o,s))try{let a=await Ra.execute(s.hooks,e,r);if(i.push(...a),this.shouldBlock(a))break}catch(a){console.warn(k.t("hooks.hookExecutionFailed"),a),i.push({success:!1,exitCode:1,stdout:"",stderr:`Hook execution failed: ${a}`,blocked:!1,duration:0})}return i}shouldExecuteHook(e,r){return!r.matcher||r.matcher==="*"?!0:e.toLowerCase().includes(r.matcher.toLowerCase())}getHookConfigs(){return this.configs}setConfigs(e){this.configs=e}hasHooks(){return this.configs.length>0}shouldBlock(e){for(let r of e){if(r.hookSpecificOutput?.hookEventName==="UserPromptSubmit")return r.exitCode===2||r.blocked;if(r.blocked||r.decision==="block"||r.exitCode===2)return!0}return!1}getBlockingReason(e){for(let r of e)if(r.exitCode===2||r.blocked||r.decision==="block")return r.stderr||r.reason||"Hook blocked prompt execution"}static collectAdditionalContext(e){let r=[];for(let n of e)if(n.hookSpecificOutput?.hookEventName==="UserPromptSubmit"){let i=n.hookSpecificOutput;i.additionalContext&&r.push(i.additionalContext)}return r.join(`
3736
3736
  `)}getMatchingConfigs(e){return this.getHookConfigs().filter(n=>this.shouldExecuteHook(e,n))}validateConfigs(e){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.matcher!==void 0&&typeof i.matcher!="string"&&r.push(`UserPromptSubmit[${n}]: matcher must be a string`),(!i.hooks||!Array.isArray(i.hooks)||i.hooks.length===0)&&r.push(`UserPromptSubmit[${n}]: hooks must be a non-empty array`),i.hooks){let o=Ra.validateCommands(i.hooks);r.push(...o.map(s=>`UserPromptSubmit[${n}]: ${s}`))}}return r}}});var WKr={};Uf(WKr,{NotificationHook:()=>tM});var tM,D_e=ae(()=>{"use strict";Yy();wE();Gn();tM=class{manager;eventType=on.Notification;configs=[];constructor(e){this.manager=e}async execute(e,r){let n=this.getHookConfigs();if(!n||n.length===0)return[];let i=[],{message:o}=e;for(let s of n)if(this.shouldExecuteHook(o,s))try{let a=await Ra.execute(s.hooks,e,r);i.push(...a)}catch(a){console.warn(k.t("hooks.hookExecutionFailed"),a),i.push({success:!1,exitCode:1,stdout:"",stderr:`Hook execution failed: ${a}`,blocked:!1,duration:0})}return i}shouldExecuteHook(e,r){return!r.matcher||r.matcher==="*"?!0:e.toLowerCase().includes(r.matcher.toLowerCase())}getHookConfigs(){return this.configs}setConfigs(e){this.configs=e}hasHooks(){return this.configs.length>0}shouldBlock(e){return!1}getDisplayMessages(e){let r=[];for(let n of e){if(n.hookSpecificOutput?.hookEventName==="Notification"){let i=n.hookSpecificOutput;if(i.displayMessage){r.push(i.displayMessage);continue}}(n.exitCode===2&&n.stderr||!n.success&&n.stderr)&&r.push(n.stderr)}return r}static collectDisplayMessages(e){let r=[];for(let n of e){if(n.hookSpecificOutput?.hookEventName==="Notification"){let i=n.hookSpecificOutput;if(i.displayMessage){r.push(i.displayMessage);continue}}(n.exitCode===2&&n.stderr||!n.success&&n.stderr)&&r.push(n.stderr)}return r.join(`
3737
- `)}getMatchingConfigs(e){return this.getHookConfigs().filter(n=>this.shouldExecuteHook(e,n))}validateConfigs(e){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.matcher!==void 0&&typeof i.matcher!="string"&&r.push(`Notification[${n}]: matcher must be a string`),(!i.hooks||!Array.isArray(i.hooks)||i.hooks.length===0)&&r.push(`Notification[${n}]: hooks must be a non-empty array`),i.hooks){let o=Ra.validateCommands(i.hooks);r.push(...o.map(s=>`Notification[${n}]: ${s}`))}}return r}}});var cx,$Kr=ae(()=>{"use strict";Yy();c6t();Gn();p6t();h6t();m6t();g6t();HKr();I_e();A6t();y6t();D_e();cx=class{configLoader;config={};handlers=new Map;enabled=!0;toolRegistry;constructor(e={},r){this.configLoader=new gj(e),this.toolRegistry=r,this.initializeHandlers(),this.initialize()}initializeHandlers(){this.handlers.set(on.PreToolUse,new yj(this)),this.handlers.set(on.PostToolUse,new Ej(this)),this.handlers.set(on.Stop,new vj(this)),this.handlers.set(on.SubagentStop,new Cj(this)),this.handlers.set(on.SetUpEnvironment,new _le(this)),this.handlers.set(on.SessionStart,new eM(this)),this.handlers.set(on.SessionEnd,new bj(this)),this.handlers.set(on.UserPromptSubmit,new yT(this)),this.handlers.set(on.Notification,new tM(this))}async initialize(){try{this.config=await this.configLoader.loadConfig();let e=this.configLoader.validateConfig(this.config);e.length>0&&console.warn(k.t("hooks.configurationErrors"),e),this.updateHandlerConfigs()}catch(e){console.warn(k.t("hooks.configLoadFailed"),e),this.config={}}}updateHandlerConfigs(){let e=this.handlers.get(on.PreToolUse);e&&this.config.PreToolUse&&e.setConfigs(this.config.PreToolUse);let r=this.handlers.get(on.PostToolUse);r&&this.config.PostToolUse&&r.setConfigs(this.config.PostToolUse);let n=this.handlers.get(on.Stop);n&&this.config.Stop&&n.setConfigs(this.config.Stop);let i=this.handlers.get(on.SubagentStop);i&&this.config.SubagentStop&&i.setConfigs(this.config.SubagentStop);let o=this.handlers.get(on.SetUpEnvironment);o&&this.config.SetUpEnvironment&&o.setConfigs(this.config.SetUpEnvironment);let s=this.handlers.get(on.SessionStart);s&&this.config.SessionStart&&s.setConfigs(this.config.SessionStart);let a=this.handlers.get(on.SessionEnd);a&&this.config.SessionEnd&&a.setConfigs(this.config.SessionEnd);let c=this.handlers.get(on.UserPromptSubmit);c&&this.config.UserPromptSubmit&&c.setConfigs(this.config.UserPromptSubmit);let u=this.handlers.get(on.Notification);u&&this.config.Notification&&u.setConfigs(this.config.Notification)}async executePreToolUse(e,r,n,i=[]){if(!this.enabled||!this.config.PreToolUse)return[];let o=this.toolRegistry?.getTool(e),s=o?.description||"",a=o?.schema?{...o.schema}:{},c={session_id:n.sessionId,transcript_path:n.transcriptPath,cwd:n.cwd,hook_event_name:on.PreToolUse,tool_name:e,tool_name_alias:i,tool_input:r,tool_desc:s,tool_schema:a},u=this.handlers.get(on.PreToolUse);return u?await u.execute(c,n):[]}async executePostToolUse(e,r,n,i,o=[]){if(!this.enabled||!this.config.PostToolUse)return[];let s=this.toolRegistry?.getTool(e),a=s?.description||"",c=s?.schema?{...s.schema.parameters}:{},u={session_id:i.sessionId,transcript_path:i.transcriptPath,cwd:i.cwd,hook_event_name:on.PostToolUse,tool_name:e,tool_name_alias:o,tool_input:r,tool_response:n,tool_desc:a,tool_schema:c},d=this.handlers.get(on.PostToolUse);return d?await d.execute(u,i):[]}async executeStop(e){if(!this.enabled||!this.config.Stop)return[];let r={session_id:e.sessionId,transcript_path:e.transcriptPath,cwd:e.cwd,hook_event_name:on.Stop,stop_hook_active:!0},n=this.handlers.get(on.Stop);return n?await n.execute(r,e):[]}async executeSubagentStop(e){if(!this.enabled||!this.config.SubagentStop)return[];let r={session_id:e.sessionId,transcript_path:e.transcriptPath,cwd:e.cwd,hook_event_name:on.SubagentStop,stop_hook_active:!0},n=this.handlers.get(on.SubagentStop);return n?await n.execute(r,e):[]}async wouldPreToolUseBlock(e,r,n,i=[]){return(await this.executePreToolUse(e,r,n,i)).some(s=>s.blocked)}async wouldStopBlock(e){return(await this.executeStop(e)).some(n=>n.blocked)}async wouldSubagentStopBlock(e){return(await this.executeSubagentStop(e)).some(n=>n.blocked)}async executeSetUpEnvironment(e,r,n){if(!this.enabled||!this.config.SetUpEnvironment)return e;let i=this.handlers.get(on.SetUpEnvironment);if(!i)return e;try{let o=await i.executeForEnvironment(e,r,n);return _le.applyHookResults(e,o)}catch(o){return console.warn(k.t("hooks.hookExecutionFailed"),o),e}}hasSetUpEnvironmentHooks(){return this.handlers.get(on.SetUpEnvironment)?.hasHooks()||!1}async executeSessionStart(e,r){if(!this.enabled||!this.config.SessionStart)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.SessionStart,source:e},i=this.handlers.get(on.SessionStart);return i?await i.execute(n,r):[]}async executeSessionEnd(e,r){if(!this.enabled||!this.config.SessionEnd)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.SessionEnd,reason:e},i=this.handlers.get(on.SessionEnd);return i?await i.execute(n,r):[]}async executeUserPromptSubmit(e,r){if(!this.enabled||!this.config.UserPromptSubmit)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.UserPromptSubmit,prompt:e},i=this.handlers.get(on.UserPromptSubmit);return i?await i.execute(n,r):[]}async executeNotification(e,r){if(!this.enabled||!this.config.Notification)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.Notification,message:e},i=this.handlers.get(on.Notification);return i?await i.execute(n,r):[]}hasSessionStartHooks(){return this.handlers.get(on.SessionStart)?.hasHooks()||!1}hasSessionEndHooks(){return this.handlers.get(on.SessionEnd)?.hasHooks()||!1}hasUserPromptSubmitHooks(){return this.handlers.get(on.UserPromptSubmit)?.hasHooks()||!1}async wouldUserPromptSubmitBlock(e,r){return(await this.executeUserPromptSubmit(e,r)).some(i=>i.blocked||i.exitCode===2)}hasNotificationHooks(){return this.handlers.get(on.Notification)?.hasHooks()||!1}getStatus(){return{enabled:this.enabled,configLoaded:Object.keys(this.config).length>0,hasPreToolUse:!!this.config.PreToolUse?.length,hasPostToolUse:!!this.config.PostToolUse?.length,hasStop:!!this.config.Stop?.length,hasSubagentStop:!!this.config.SubagentStop?.length,hasSessionStart:!!this.config.SessionStart?.length,hasSessionEnd:!!this.config.SessionEnd?.length,hasUserPromptSubmit:!!this.config.UserPromptSubmit?.length,hasNotification:!!this.config.Notification?.length}}setEnabled(e){this.enabled=e}async reloadConfig(){await this.initialize()}getConfig(){return{...this.config}}async getConfigPaths(){return await this.configLoader.checkConfigFiles()}watchConfig(e){return this.configLoader.watchConfig(async r=>{this.config=r;let n=this.configLoader.validateConfig(this.config);n.length>0&&console.warn(k.t("hooks.configurationErrors"),n),e&&e()})}static createExecutionContext(e,r,n,i){return{sessionId:e,transcriptPath:r,cwd:n||process.cwd(),projectDir:i}}}});var E6t=ae(()=>{"use strict";Yy();$Kr();c6t();wE();p6t();h6t();m6t();g6t();I_e();A6t();y6t();D_e();T_e();d6t();f6t();});import*as ux from"fs";import*as dx from"path";import*as v6t from"process";var R_e,jKr=ae(()=>{"use strict";lu();R_e=class{directories=new Set;initialDirectories;onDirectoriesChangedListeners=new Set;constructor(e,r=[]){this.addDirectory(e);for(let n of r)this.addDirectory(n);this.initialDirectories=new Set(this.directories)}onDirectoriesChanged(e){return this.onDirectoriesChangedListeners.add(e),()=>{this.onDirectoriesChangedListeners.delete(e)}}notifyDirectoriesChanged(){for(let e of[...this.onDirectoriesChangedListeners])try{e()}catch(r){console.error("Error in WorkspaceContext listener:",r)}}addDirectory(e,r=v6t.cwd()){try{let n=this.resolveAndValidateDir(e,r);if(this.directories.has(n))return;this.directories.add(n),this.notifyDirectoriesChanged()}catch(n){console.warn(`[WARN] Skipping unreadable directory: ${e} (${n instanceof Error?n.message:String(n)})`)}}resolveAndValidateDir(e,r=v6t.cwd()){let n=dx.isAbsolute(e)?e:dx.resolve(r,e);if(!ux.existsSync(n))throw new Error(`Directory does not exist: ${n}`);if(!ux.statSync(n).isDirectory())throw new Error(`Path is not a directory: ${n}`);return ux.realpathSync(n)}getDirectories(){return Array.from(this.directories)}getInitialDirectories(){return Array.from(this.initialDirectories)}setDirectories(e){let r=new Set;for(let n of e)r.add(this.resolveAndValidateDir(n));(r.size!==this.directories.size||![...r].every(n=>this.directories.has(n)))&&(this.directories=r,this.notifyDirectoriesChanged())}isPathWithinWorkspace(e){try{let r=this.fullyResolvedPath(e);for(let n of this.directories)if(this.isPathWithinRoot(r,n))return!0;return!1}catch{return!1}}fullyResolvedPath(e){try{return ux.realpathSync(e)}catch(r){if(cs(r)&&r.code==="ENOENT"&&r.path&&!this.isFileSymlink(r.path))return r.path;throw r}}isPathWithinRoot(e,r){let n=dx.relative(r,e);return!n.startsWith(`..${dx.sep}`)&&n!==".."&&!dx.isAbsolute(n)}isFileSymlink(e){try{return!ux.readlinkSync(e).endsWith("/")}catch{return!1}}}});import zKr from"node:fs/promises";var Tle,C6t=ae(()=>{"use strict";Tle=class{async readTextFile(e){return zKr.readFile(e,"utf-8")}async writeTextFile(e,r){await zKr.writeFile(e,r,"utf-8")}}});import*as B_e from"node:path";import YKr from"node:process";var jn,mj,ob,Ile,qX,Dle,Fm=ae(()=>{"use strict";A3();aMt();SQe();yZ();$7();AH();E6r();uie();lO();Soe();cV();mve();vV();Jve();Ywr();tdt();yft();dzr();pV();U7e();pzr();nle();Y3t();qyt();n6t();Ou();b_();i6t();l4();Xae();o6t();aV();E6t();jKr();C6t();(function(t){t.DEFAULT="default",t.AUTO_EDIT="autoEdit",t.YOLO="yolo",t.PLAN="plan"})(jn||(jn={}));mj={respectGitIgnore:!1,respectGeminiIgnore:!0},ob={respectGitIgnore:!0,respectGeminiIgnore:!0},Ile=class{command;args;env;cwd;url;httpUrl;headers;tcp;type;timeout;trust;description;includeTools;excludeTools;extensionName;oauth;authProviderType;constructor(e,r,n,i,o,s,a,c,u,d,f,p,h,m,g,A,y){this.command=e,this.args=r,this.env=n,this.cwd=i,this.url=o,this.httpUrl=s,this.headers=a,this.tcp=c,this.type=u,this.timeout=d,this.trust=f,this.description=p,this.includeTools=h,this.excludeTools=m,this.extensionName=g,this.oauth=A,this.authProviderType=y}};(function(t){t.DYNAMIC_DISCOVERY="dynamic_discovery",t.GOOGLE_CREDENTIALS="google_credentials"})(qX||(qX={}));Dle=class t{toolRegistry;promptRegistry;sessionId;fileSystemService;conversationId;contentGeneratorConfig;embeddingModel;sandbox;targetDir;workspaceContext;debugMode;question;fullContext;coreTools;excludeTools;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;userMemory;geminiMdFileCount;approvalMode;showMemoryUsage;accessibility;telemetrySettings;usageStatisticsEnabled;systemReminderSettings;geminiClient;pendingHistoryRestore;fileFiltering;fileDiscoveryService=null;gitService=void 0;checkpointing;proxy;cwd;bugCommand;model;extensionContextFilePaths;noBrowser;inFallbackMode=!1;maxSessionTurns;listExtensions;_extensions;_blockedMcpServers;flashFallbackHandler;quotaErrorOccurred=!1;searchApiKey;apiKey;summarizeToolOutput;experimentalAcp=!1;acpPort;parallelTasksCount;agentCoreSystemPrompt;agentColor;hookManager;hookManagerEnabled;compressionTokenThreshold;useRipgrep;tokensLimit;skipNextSpeakerCheck;shellTimeout;budgetMaxTokens;budgetTimeout;ideClient;historyManager;isNonInteractive;disableTelemetry;enableBuildInTask;cna;language;outputStyleName;shouldUseNodePtyShell;shellExecutionConfig;constructor(e){this.cna=e.cna,this.language=e.language,this.sessionId=e.sessionId,this.embeddingModel=e.embeddingModel??uU,this.sandbox=e.sandbox,this.targetDir=B_e.resolve(e.targetDir),this.fileSystemService=new Tle,this.workspaceContext=new R_e(this.targetDir,e.includeDirectories??[]),this.debugMode=e.debugMode,this.ideClient=tO.getInstance(),this.question=e.question,this.fullContext=e.fullContext??!1,this.coreTools=e.coreTools,this.excludeTools=e.excludeTools,this.toolDiscoveryCommand=e.toolDiscoveryCommand,this.toolCallCommand=e.toolCallCommand,this.mcpServerCommand=e.mcpServerCommand,this.mcpServers=e.mcpServers,this.userMemory=e.userMemory??"",this.geminiMdFileCount=e.geminiMdFileCount??0,this.approvalMode=e.approvalMode??jn.DEFAULT,this.showMemoryUsage=e.showMemoryUsage??!1,this.accessibility=e.accessibility??{},this.telemetrySettings={enabled:e.telemetry?.enabled??!1,target:e.telemetry?.target??w_e,otlpEndpoint:e.telemetry?.otlpEndpoint??S_e,logPrompts:e.telemetry?.logPrompts??!0,outfile:e.telemetry?.outfile},this.usageStatisticsEnabled=e.usageStatisticsEnabled??!0,this.systemReminderSettings={enabled:e.systemReminder?.enabled??!0,eventTypes:e.systemReminder?.eventTypes??Object.values(xn),maxRemindersPerSession:e.systemReminder?.maxRemindersPerSession??10,telemetryEnabled:e.systemReminder?.telemetryEnabled??!0},this.fileFiltering={respectGitIgnore:e.fileFiltering?.respectGitIgnore??!0,respectGeminiIgnore:e.fileFiltering?.respectGeminiIgnore??!0,enableRecursiveFileSearch:e.fileFiltering?.enableRecursiveFileSearch??!0},this.checkpointing=e.checkpointing??!1,this.proxy=e.proxy,this.cwd=e.cwd??YKr.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.model=e.model,this.extensionContextFilePaths=e.extensionContextFilePaths??[],this.maxSessionTurns=e.maxSessionTurns??-1,this.experimentalAcp=e.experimentalAcp??!1,this.acpPort=e.acpPort,this.listExtensions=e.listExtensions??!1,this._extensions=e.extensions??[],this._blockedMcpServers=e.blockedMcpServers??[],this.noBrowser=e.noBrowser??!1,this.summarizeToolOutput=e.summarizeToolOutput,this.searchApiKey=e.searchApiKey,this.apiKey=e.apiKey,this.parallelTasksCount=e.parallelTasksCount??1,this.hookManagerEnabled=e.hookManager!==!1,this.compressionTokenThreshold=e.compressionTokenThreshold??.8,this.useRipgrep=e.useRipgrep??!0,this.budgetMaxTokens=e.maxTokens,this.budgetTimeout=e.timeout,this.tokensLimit=e.tokensLimit,this.skipNextSpeakerCheck=e.skipNextSpeakerCheck??!0,this.shellTimeout=e.shellTimeout??120*1e3,this.historyManager=e.historyManager,this.isNonInteractive=e.isNonInteractive??!1,this.disableTelemetry=e.disableTelemetry??!1,this.enableBuildInTask=e.enableBuildInTask??"true",this.outputStyleName=e.outputStyle,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??!0,this.shellExecutionConfig=e.shellExecutionConfig??{},e.contextFileName&&dV(e.contextFileName),e.hookManager!==!1&&(this.hookManager=new cx),this.telemetrySettings.enabled&&y7e(this),this.getUsageStatisticsEnabled()?rp.getInstance(this)?.logStartSessionEvent(new xV(this)):console.log("Data collection is disabled.")}async initialize(){this.getFileService(),this.getCheckpointingEnabled()&&await this.getGitService(),this.promptRegistry=new x0e,this.toolRegistry=await this.createToolRegistry(),this.hookManagerEnabled&&(this.hookManager=new cx({},this.toolRegistry))}async refreshAuth(e,r){if(this.contentGeneratorConfig?.authType===$t.LOGIN_WITH_IFLOW&&e!==$t.LOGIN_WITH_IFLOW){let{clearCachedCredentialFile:i}=await Promise.resolve().then(()=>(_w(),cLe));await i()}let n=r?.modelName||this.model;this.setModel(n),this.contentGeneratorConfig=await VFe(this,e,r),r?.modelName&&r.modelName!==this.model&&(this.model=r.modelName),r?.searchApiKey&&(this.searchApiKey=r.searchApiKey),this.geminiClient=new ex(this),await this.geminiClient.initialize(this.contentGeneratorConfig),this.inFallbackMode=!1}getSessionId(){return this.sessionId}getCna(){return this.cna}getLanguage(){return this.language}setSessionId(e){this.sessionId=e}getConversationId(){return this.conversationId}setConversationId(e){this.conversationId=e}getContentGeneratorConfig(){return this.contentGeneratorConfig}getModel(){return this.contentGeneratorConfig?.model||this.model}setModel(e){this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e)}getFileSystemService(){return this.fileSystemService}setFileSystemService(e){this.fileSystemService=e}async setIdeModeAndSyncConnection(e){this.isNonInteractive||(e?await this.ideClient.connect():await this.ideClient.disconnect())}getIdeClient(){return this.ideClient}isInFallbackMode(){return this.inFallbackMode}setFallbackMode(e){this.inFallbackMode=e}setFlashFallbackHandler(e){this.flashFallbackHandler=e}getMaxSessionTurns(){return this.maxSessionTurns}getBudgetMaxTokens(){return this.budgetMaxTokens}getBudgetTimeout(){return this.budgetTimeout}setQuotaErrorOccurred(e){this.quotaErrorOccurred=e}getQuotaErrorOccurred(){return this.quotaErrorOccurred}getSearchApiKey(){if(this.searchApiKey)return this.searchApiKey;if(this.isIFlowService())return this.contentGeneratorConfig?.apiKey}isMultimodalEnabled(){return!0}getMultimodalModelName(){if(this.isIFlowService())return"qwen3-vl-plus"}getEmbeddingModel(){return this.embeddingModel}getCompressionTokenThreshold(){return this.compressionTokenThreshold}getHistoryManager(){return this.historyManager}getTokensLimit(){return this.tokensLimit}getSandbox(){return this.sandbox}isRestrictiveSandbox(){let e=this.getSandbox(),r=YKr.env.SEATBELT_PROFILE;return!!e&&e.command==="sandbox-exec"&&!!r&&r.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getProjectRoot(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return Promise.resolve(this.toolRegistry)}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getFullContext(){return this.fullContext}getCoreTools(){return this.coreTools}getExcludeTools(){return this.excludeTools}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}getMcpServers(){return this.mcpServers}addMcpServer(e,r){this.mcpServers||(this.mcpServers={}),this.mcpServers[e]=r}removeMcpServer(e){this.mcpServers&&e in this.mcpServers&&delete this.mcpServers[e]}getUserMemory(){return this.userMemory}setUserMemory(e){this.userMemory=e}getGeminiMdFileCount(){return this.geminiMdFileCount}setGeminiMdFileCount(e){this.geminiMdFileCount=e}setGeminiClient(e){this.geminiClient=e}getApprovalMode(){return this.approvalMode}setApprovalMode(e){this.approvalMode=e}getShowMemoryUsage(){return this.showMemoryUsage}getAccessibility(){return this.accessibility}getTelemetryEnabled(){return this.telemetrySettings.enabled??!1}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??!0}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??S_e}getTelemetryTarget(){return this.telemetrySettings.target??w_e}getTelemetryOutfile(){return this.telemetrySettings.outfile}getSystemReminderEnabled(){return this.systemReminderSettings.enabled}getSystemReminderEventTypes(){return this.systemReminderSettings.eventTypes}getSystemReminderMaxRemindersPerSession(){return this.systemReminderSettings.maxRemindersPerSession}getSystemReminderTelemetryEnabled(){return this.systemReminderSettings.telemetryEnabled}getGeminiClient(){return this.geminiClient}setPendingHistoryRestore(e){this.pendingHistoryRestore=e}getPendingHistoryRestore(){return this.pendingHistoryRestore}clearPendingHistoryRestore(){this.pendingHistoryRestore=void 0}getIFlowDir(){return B_e.join(this.targetDir,Ip)}getProjectTempDir(){return Mm(this.getProjectRoot())}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectGeminiIgnore(){return this.fileFiltering.respectGeminiIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectGeminiIgnore:this.fileFiltering.respectGeminiIgnore}}getCheckpointingEnabled(){return this.checkpointing}getProxy(){return this.proxy}getAuthType(){return this.contentGeneratorConfig?.authType}getApiKey(){return this.contentGeneratorConfig?.apiKey}getBaseUrl(){return this.contentGeneratorConfig?.baseUrl}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new Gk(this.targetDir)),this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}isIFlowService(){let e=this.getAuthType(),r=this.getBaseUrl();return e===$t.IFLOW||e===$t.LOGIN_WITH_IFLOW||r!==void 0&&r.toLowerCase().includes("apis.iflow.cn")}getExtensionContextFilePaths(){return this.extensionContextFilePaths}getExperimentalAcp(){return this.experimentalAcp}getAcpPort(){return this.acpPort}getListExtensions(){return this.listExtensions}getExtensions(){return this._extensions}getBlockedMcpServers(){return this._blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!Sle()}getSummarizeToolOutputConfig(){return this.summarizeToolOutput}getAgentCoreSystemPrompt(){return this.agentCoreSystemPrompt}setAgentCoreSystemPrompt(e){this.agentCoreSystemPrompt=e}getAgentColor(){return this.agentColor}setAgentColor(e){this.agentColor=e}hasAgentCoreSystemPrompt(){return this.agentCoreSystemPrompt!==void 0&&this.agentCoreSystemPrompt!==""}async getGitService(){return this.gitService||(this.gitService=new sx(this.targetDir),await this.gitService.initialize()),this.gitService}getHookManager(){return this.hookManager}getUseRipgrep(){return this.useRipgrep}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellTimeout(){return this.shellTimeout}getDisableTelemetry(){return this.disableTelemetry}getOutputStyle(){return this.outputStyleName}setOutputStyle(e){this.outputStyleName=e,this.geminiClient&&this.geminiClient.isInitialized()&&this.geminiClient.resetChat().catch(r=>{console.warn("Failed to reset chat after output style change:",r)})}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getShellExecutionConfig(){return{...this.shellExecutionConfig}}async refreshMemory(){let{memoryContent:e,fileCount:r}=await Kk(this.getWorkingDir(),this.getDebugMode(),this.getFileService(),this.getExtensionContextFilePaths());return this.setUserMemory(e),this.setGeminiMdFileCount(r),{memoryContent:e,fileCount:r}}getAll(){return{sessionId:this.sessionId,embeddingModel:this.embeddingModel,sandbox:this.sandbox,targetDir:this.targetDir,debugMode:this.debugMode,question:this.question,fullContext:this.fullContext,coreTools:this.coreTools,excludeTools:this.excludeTools,toolDiscoveryCommand:this.toolDiscoveryCommand,toolCallCommand:this.toolCallCommand,mcpServerCommand:this.mcpServerCommand,mcpServers:this.mcpServers,userMemory:this.userMemory,geminiMdFileCount:this.geminiMdFileCount,approvalMode:this.approvalMode,showMemoryUsage:this.showMemoryUsage,contextFileName:void 0,accessibility:this.accessibility,telemetry:this.telemetrySettings,usageStatisticsEnabled:this.usageStatisticsEnabled,fileFiltering:this.fileFiltering,checkpointing:this.checkpointing,proxy:this.proxy,cwd:this.cwd,fileDiscoveryService:this.fileDiscoveryService,bugCommand:this.bugCommand,model:this.model,extensionContextFilePaths:this.extensionContextFilePaths,maxSessionTurns:this.maxSessionTurns,listExtensions:this.listExtensions,noBrowser:this.noBrowser,searchApiKey:this.searchApiKey,apiKey:this.apiKey,parallelTasksCount:this.parallelTasksCount,compressionTokenThreshold:this.compressionTokenThreshold,useRipgrep:this.useRipgrep,skipNextSpeakerCheck:this.skipNextSpeakerCheck,shellTimeout:this.shellTimeout,disableTelemetry:this.disableTelemetry,enableBuildInTask:this.enableBuildInTask,outputStyle:this.outputStyleName}}async createToolRegistry(){let e=new HX(this),r=(n,...i)=>{let o=n.name,s=n.Name||o,a=this.getCoreTools(),c=this.getExcludeTools(),u=!1;a===void 0?u=!0:u=a.some(d=>d===o||d===s||d.startsWith(`${o}(`)||d.startsWith(`${s}(`)),(c?.includes(o)||c?.includes(s))&&(u=!1),u&&e.registerTool(new n(...i))};return r(ib,this),r(Lc,this),this.getUseRipgrep()?r(lEe,this):r(W1,this),r($1,this),r(Af,this),r(ld,this),r(Q7e,this),r(V7e,this),r(aO,this),r(pu,this),r(h_),r(qk,this),r($l,this),r(X4,this),r(CV,this),r(iA,this),r(Kve),await e.discoverAllTools(this.isNonInteractive),e}async clone(){let e=this.getAll(),r={sessionId:e.sessionId,embeddingModel:e.embeddingModel,sandbox:e.sandbox?{...e.sandbox}:void 0,targetDir:e.targetDir,debugMode:e.debugMode,question:e.question,fullContext:e.fullContext,coreTools:e.coreTools?[...e.coreTools]:void 0,excludeTools:e.excludeTools?[...e.excludeTools]:void 0,toolDiscoveryCommand:e.toolDiscoveryCommand,toolCallCommand:e.toolCallCommand,mcpServerCommand:e.mcpServerCommand,mcpServers:e.mcpServers?JSON.parse(JSON.stringify(e.mcpServers)):void 0,userMemory:e.userMemory,geminiMdFileCount:e.geminiMdFileCount,approvalMode:e.approvalMode,showMemoryUsage:e.showMemoryUsage,contextFileName:e.contextFileName,accessibility:e.accessibility?{...e.accessibility}:void 0,telemetry:e.telemetry?{...e.telemetry}:void 0,usageStatisticsEnabled:e.usageStatisticsEnabled,fileFiltering:e.fileFiltering?{...e.fileFiltering}:void 0,checkpointing:e.checkpointing,proxy:e.proxy,cwd:e.cwd,fileDiscoveryService:e.fileDiscoveryService,bugCommand:e.bugCommand?{...e.bugCommand}:void 0,model:e.model,extensionContextFilePaths:e.extensionContextFilePaths?[...e.extensionContextFilePaths]:[],maxSessionTurns:e.maxSessionTurns,experimentalAcp:e.experimentalAcp,listExtensions:e.listExtensions,extensions:this.getExtensions()?this.getExtensions().map(i=>({...i})):[],blockedMcpServers:this.getBlockedMcpServers()?this.getBlockedMcpServers().map(i=>({...i})):[],noBrowser:e.noBrowser,summarizeToolOutput:this.getSummarizeToolOutputConfig()?JSON.parse(JSON.stringify(this.getSummarizeToolOutputConfig())):void 0,searchApiKey:e.searchApiKey,parallelTasksCount:e.parallelTasksCount,ideClient:this.getIdeClient(),compressionTokenThreshold:e.compressionTokenThreshold,useRipgrep:e.useRipgrep,skipNextSpeakerCheck:e.skipNextSpeakerCheck,shellTimeout:e.shellTimeout,disableTelemetry:e.disableTelemetry,outputStyle:e.outputStyle},n=new t(r);if(await n.initialize(),this.getContentGeneratorConfig())try{n.setModel(this.model),n.contentGeneratorConfig=this.contentGeneratorConfig,n.searchApiKey=this.searchApiKey,n.inFallbackMode=!1}catch(i){console.warn("Failed to clone auth configuration:",i)}return n.setFallbackMode(this.isInFallbackMode()),n.setQuotaErrorOccurred(this.getQuotaErrorOccurred()),n}}});import JKr from"node:path";import{promises as fx}from"node:fs";var q2o,xj,rM,KKr=ae(()=>{"use strict";Ou();q2o="logs.json";(function(t){t.USER="user"})(xj||(xj={}));rM=class{iFlowDir;logFilePath;sessionId;messageId=0;initialized=!1;logs=[];constructor(e){this.sessionId=e}async _readLogFile(){if(!this.logFilePath)throw new Error("Log file path not set during read attempt.");try{let e=await fx.readFile(this.logFilePath,"utf-8"),r=JSON.parse(e);return Array.isArray(r)?r.filter(n=>typeof n.sessionId=="string"&&typeof n.messageId=="number"&&typeof n.timestamp=="string"&&typeof n.type=="string"&&typeof n.message=="string"):(console.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`),await this._backupCorruptedLogFile("malformed_array"),[])}catch(e){if(e.code==="ENOENT")return[];if(e instanceof SyntaxError)return console.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`,e),await this._backupCorruptedLogFile("invalid_json"),[];throw console.debug(`Failed to read or parse log file ${this.logFilePath}:`,e),e}}async _backupCorruptedLogFile(e){if(!this.logFilePath)return;let r=`${this.logFilePath}.${e}.${Date.now()}.bak`;try{await fx.rename(this.logFilePath,r),console.debug(`Backed up corrupted log file to ${r}`)}catch{}}async initialize(){if(!this.initialized){this.iFlowDir=Mm(process.cwd()),this.logFilePath=JKr.join(this.iFlowDir,q2o);try{await fx.mkdir(this.iFlowDir,{recursive:!0});let e=!0;try{await fx.access(this.logFilePath)}catch{e=!1}this.logs=await this._readLogFile(),!e&&this.logs.length===0&&await fx.writeFile(this.logFilePath,"[]","utf-8");let r=this.logs.filter(n=>n.sessionId===this.sessionId);this.messageId=r.length>0?Math.max(...r.map(n=>n.messageId))+1:0,this.initialized=!0}catch(e){console.error("Failed to initialize logger:",e),this.initialized=!1}}}async _updateLogFile(e){if(!this.logFilePath)throw console.debug("Log file path not set. Cannot persist log entry."),new Error("Log file path not set during update attempt.");let r;try{r=await this._readLogFile()}catch(s){throw console.debug("Critical error reading log file before append:",s),s}let n=r.filter(s=>s.sessionId===e.sessionId),i=n.length>0?Math.max(...n.map(s=>s.messageId))+1:0;if(e.messageId=i,r.some(s=>s.sessionId===e.sessionId&&s.messageId===e.messageId&&s.timestamp===e.timestamp&&s.message===e.message))return console.debug(`Duplicate log entry detected and skipped: session ${e.sessionId}, messageId ${e.messageId}`),this.logs=r,null;r.push(e);try{return await fx.writeFile(this.logFilePath,JSON.stringify(r,null,2),"utf-8"),this.logs=r,e}catch(s){throw console.debug("Error writing to log file:",s),s}}async getPreviousUserMessages(){return this.initialized?this.logs.filter(e=>e.type===xj.USER).sort((e,r)=>{let n=new Date(e.timestamp).getTime();return new Date(r.timestamp).getTime()-n}).map(e=>e.message):[]}async logMessage(e,r){if(!this.initialized||this.sessionId===void 0){console.debug("Logger not initialized or session ID missing. Cannot log message.");return}let n={sessionId:this.sessionId,messageId:this.messageId,type:e,message:r,timestamp:new Date().toISOString()};try{let i=await this._updateLogFile(n);i&&(this.messageId=i.messageId+1)}catch{}}_checkpointPath(e){if(!e.length)throw new Error("No checkpoint tag specified.");if(!this.iFlowDir)throw new Error("Checkpoint file path not set.");let r=e.replace(/[^a-zA-Z0-9-_]/g,"");return r||(r="default"),JKr.join(this.iFlowDir,`checkpoint-${r}.json`)}async saveCheckpoint(e,r){if(!this.initialized){console.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");return}let n=this._checkpointPath(r);try{await fx.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(i){console.error("Error writing to checkpoint file:",i)}}async loadCheckpoint(e){if(!this.initialized)return console.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint."),[];let r=this._checkpointPath(e);try{let n=await fx.readFile(r,"utf-8"),i=JSON.parse(n);return Array.isArray(i)?i:(console.warn(`Checkpoint file at ${r} is not a valid JSON array. Returning empty checkpoint.`),[])}catch(n){return console.error(`Failed to read or parse checkpoint file ${r}:`,n),[]}}async deleteCheckpoint(e){if(!this.initialized||!this.iFlowDir)return console.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint."),!1;let r=this._checkpointPath(e);try{return await fx.unlink(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw console.error(`Failed to delete checkpoint file ${r}:`,n),n}}close(){this.initialized=!1,this.logFilePath=void 0,this.logs=[],this.sessionId=void 0,this.messageId=0}}});function G2o(t){return vve(t,{verbose:!0})}var XKr=ae(()=>{"use strict";yct();});function ZKr(t,e,r,n){let i=e===Ur.HOOK_BLOCKED,a=`${i?"\u{1F6A8} CRITICAL":"\u26A0\uFE0F IMPORTANT"}: The tool "${t}" has ${i?"BEEN BLOCKED":"FAILED"}. `;switch(e){case Ur.FILE_NOT_FOUND:a+="The file or directory does not exist. ";break;case Ur.PERMISSION_DENIED:a+="You do not have permission to access this resource. ";break;case Ur.HOOK_BLOCKED:a+="The operation was blocked by a user-configured hook. ";break;case Ur.EXECUTION_FAILED:a+="The command execution failed. ";break;case Ur.INVALID_TOOL_PARAMS:a+="The parameters provided were invalid. ";break;case Ur.FILE_WRITE_FAILURE:a+="Failed to write to the file. ";break;case Ur.READ_CONTENT_FAILURE:a+="Failed to read the file content. ";break;default:a+="An error occurred during execution. "}return a+=`Error: "${r}". `,a+=`
3737
+ `)}getMatchingConfigs(e){return this.getHookConfigs().filter(n=>this.shouldExecuteHook(e,n))}validateConfigs(e){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.matcher!==void 0&&typeof i.matcher!="string"&&r.push(`Notification[${n}]: matcher must be a string`),(!i.hooks||!Array.isArray(i.hooks)||i.hooks.length===0)&&r.push(`Notification[${n}]: hooks must be a non-empty array`),i.hooks){let o=Ra.validateCommands(i.hooks);r.push(...o.map(s=>`Notification[${n}]: ${s}`))}}return r}}});var cx,$Kr=ae(()=>{"use strict";Yy();c6t();Gn();p6t();h6t();m6t();g6t();HKr();I_e();A6t();y6t();D_e();cx=class{configLoader;config={};handlers=new Map;enabled=!0;toolRegistry;constructor(e={},r){this.configLoader=new gj(e),this.toolRegistry=r,this.initializeHandlers(),this.initialize()}initializeHandlers(){this.handlers.set(on.PreToolUse,new yj(this)),this.handlers.set(on.PostToolUse,new Ej(this)),this.handlers.set(on.Stop,new vj(this)),this.handlers.set(on.SubagentStop,new Cj(this)),this.handlers.set(on.SetUpEnvironment,new _le(this)),this.handlers.set(on.SessionStart,new eM(this)),this.handlers.set(on.SessionEnd,new bj(this)),this.handlers.set(on.UserPromptSubmit,new yT(this)),this.handlers.set(on.Notification,new tM(this))}async initialize(){try{this.config=await this.configLoader.loadConfig();let e=this.configLoader.validateConfig(this.config);e.length>0&&console.warn(k.t("hooks.configurationErrors"),e),this.updateHandlerConfigs()}catch(e){console.warn(k.t("hooks.configLoadFailed"),e),this.config={}}}updateHandlerConfigs(){let e=this.handlers.get(on.PreToolUse);e&&this.config.PreToolUse&&e.setConfigs(this.config.PreToolUse);let r=this.handlers.get(on.PostToolUse);r&&this.config.PostToolUse&&r.setConfigs(this.config.PostToolUse);let n=this.handlers.get(on.Stop);n&&this.config.Stop&&n.setConfigs(this.config.Stop);let i=this.handlers.get(on.SubagentStop);i&&this.config.SubagentStop&&i.setConfigs(this.config.SubagentStop);let o=this.handlers.get(on.SetUpEnvironment);o&&this.config.SetUpEnvironment&&o.setConfigs(this.config.SetUpEnvironment);let s=this.handlers.get(on.SessionStart);s&&this.config.SessionStart&&s.setConfigs(this.config.SessionStart);let a=this.handlers.get(on.SessionEnd);a&&this.config.SessionEnd&&a.setConfigs(this.config.SessionEnd);let c=this.handlers.get(on.UserPromptSubmit);c&&this.config.UserPromptSubmit&&c.setConfigs(this.config.UserPromptSubmit);let u=this.handlers.get(on.Notification);u&&this.config.Notification&&u.setConfigs(this.config.Notification)}async executePreToolUse(e,r,n,i=[]){if(!this.enabled||!this.config.PreToolUse)return[];let o=this.toolRegistry?.getTool(e),s=o?.description||"",a=o?.schema?{...o.schema}:{},c={session_id:n.sessionId,transcript_path:n.transcriptPath,cwd:n.cwd,hook_event_name:on.PreToolUse,tool_name:e,tool_name_alias:i,tool_input:r,tool_desc:s,tool_schema:a},u=this.handlers.get(on.PreToolUse);return u?await u.execute(c,n):[]}async executePostToolUse(e,r,n,i,o=[]){if(!this.enabled||!this.config.PostToolUse)return[];let s=this.toolRegistry?.getTool(e),a=s?.description||"",c=s?.schema?{...s.schema.parameters}:{},u={session_id:i.sessionId,transcript_path:i.transcriptPath,cwd:i.cwd,hook_event_name:on.PostToolUse,tool_name:e,tool_name_alias:o,tool_input:r,tool_response:n,tool_desc:a,tool_schema:c},d=this.handlers.get(on.PostToolUse);return d?await d.execute(u,i):[]}async executeStop(e){if(!this.enabled||!this.config.Stop)return[];let r={session_id:e.sessionId,transcript_path:e.transcriptPath,cwd:e.cwd,hook_event_name:on.Stop,stop_hook_active:!0},n=this.handlers.get(on.Stop);return n?await n.execute(r,e):[]}async executeSubagentStop(e){if(!this.enabled||!this.config.SubagentStop)return[];let r={session_id:e.sessionId,transcript_path:e.transcriptPath,cwd:e.cwd,hook_event_name:on.SubagentStop,stop_hook_active:!0},n=this.handlers.get(on.SubagentStop);return n?await n.execute(r,e):[]}async wouldPreToolUseBlock(e,r,n,i=[]){return(await this.executePreToolUse(e,r,n,i)).some(s=>s.blocked)}async wouldStopBlock(e){return(await this.executeStop(e)).some(n=>n.blocked)}async wouldSubagentStopBlock(e){return(await this.executeSubagentStop(e)).some(n=>n.blocked)}async executeSetUpEnvironment(e,r,n){if(!this.enabled||!this.config.SetUpEnvironment)return e;let i=this.handlers.get(on.SetUpEnvironment);if(!i)return e;try{let o=await i.executeForEnvironment(e,r,n);return _le.applyHookResults(e,o)}catch(o){return console.warn(k.t("hooks.hookExecutionFailed"),o),e}}hasSetUpEnvironmentHooks(){return this.handlers.get(on.SetUpEnvironment)?.hasHooks()||!1}async executeSessionStart(e,r){if(!this.enabled||!this.config.SessionStart)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.SessionStart,source:e},i=this.handlers.get(on.SessionStart);return i?await i.execute(n,r):[]}async executeSessionEnd(e,r){if(!this.enabled||!this.config.SessionEnd)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.SessionEnd,reason:e},i=this.handlers.get(on.SessionEnd);return i?await i.execute(n,r):[]}async executeUserPromptSubmit(e,r){if(!this.enabled||!this.config.UserPromptSubmit)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.UserPromptSubmit,prompt:e},i=this.handlers.get(on.UserPromptSubmit);return i?await i.execute(n,r):[]}async executeNotification(e,r){if(!this.enabled||!this.config.Notification)return[];let n={session_id:r.sessionId,transcript_path:r.transcriptPath,cwd:r.cwd,hook_event_name:on.Notification,message:e},i=this.handlers.get(on.Notification);return i?await i.execute(n,r):[]}hasSessionStartHooks(){return this.handlers.get(on.SessionStart)?.hasHooks()||!1}hasSessionEndHooks(){return this.handlers.get(on.SessionEnd)?.hasHooks()||!1}hasUserPromptSubmitHooks(){return this.handlers.get(on.UserPromptSubmit)?.hasHooks()||!1}async wouldUserPromptSubmitBlock(e,r){return(await this.executeUserPromptSubmit(e,r)).some(i=>i.blocked||i.exitCode===2)}hasNotificationHooks(){return this.handlers.get(on.Notification)?.hasHooks()||!1}getStatus(){return{enabled:this.enabled,configLoaded:Object.keys(this.config).length>0,hasPreToolUse:!!this.config.PreToolUse?.length,hasPostToolUse:!!this.config.PostToolUse?.length,hasStop:!!this.config.Stop?.length,hasSubagentStop:!!this.config.SubagentStop?.length,hasSessionStart:!!this.config.SessionStart?.length,hasSessionEnd:!!this.config.SessionEnd?.length,hasUserPromptSubmit:!!this.config.UserPromptSubmit?.length,hasNotification:!!this.config.Notification?.length}}setEnabled(e){this.enabled=e}async reloadConfig(){await this.initialize()}getConfig(){return{...this.config}}async getConfigPaths(){return await this.configLoader.checkConfigFiles()}watchConfig(e){return this.configLoader.watchConfig(async r=>{this.config=r;let n=this.configLoader.validateConfig(this.config);n.length>0&&console.warn(k.t("hooks.configurationErrors"),n),e&&e()})}static createExecutionContext(e,r,n,i){return{sessionId:e,transcriptPath:r,cwd:n||process.cwd(),projectDir:i}}}});var E6t=ae(()=>{"use strict";Yy();$Kr();c6t();wE();p6t();h6t();m6t();g6t();I_e();A6t();y6t();D_e();T_e();d6t();f6t();});import*as ux from"fs";import*as dx from"path";import*as v6t from"process";var R_e,jKr=ae(()=>{"use strict";lu();R_e=class{directories=new Set;initialDirectories;onDirectoriesChangedListeners=new Set;constructor(e,r=[]){this.addDirectory(e);for(let n of r)this.addDirectory(n);this.initialDirectories=new Set(this.directories)}onDirectoriesChanged(e){return this.onDirectoriesChangedListeners.add(e),()=>{this.onDirectoriesChangedListeners.delete(e)}}notifyDirectoriesChanged(){for(let e of[...this.onDirectoriesChangedListeners])try{e()}catch(r){console.error("Error in WorkspaceContext listener:",r)}}addDirectory(e,r=v6t.cwd()){try{let n=this.resolveAndValidateDir(e,r);if(this.directories.has(n))return;this.directories.add(n),this.notifyDirectoriesChanged()}catch(n){console.warn(`[WARN] Skipping unreadable directory: ${e} (${n instanceof Error?n.message:String(n)})`)}}resolveAndValidateDir(e,r=v6t.cwd()){let n=dx.isAbsolute(e)?e:dx.resolve(r,e);if(!ux.existsSync(n))throw new Error(`Directory does not exist: ${n}`);if(!ux.statSync(n).isDirectory())throw new Error(`Path is not a directory: ${n}`);return ux.realpathSync(n)}getDirectories(){return Array.from(this.directories)}getInitialDirectories(){return Array.from(this.initialDirectories)}setDirectories(e){let r=new Set;for(let n of e)r.add(this.resolveAndValidateDir(n));(r.size!==this.directories.size||![...r].every(n=>this.directories.has(n)))&&(this.directories=r,this.notifyDirectoriesChanged())}isPathWithinWorkspace(e){try{let r=this.fullyResolvedPath(e);for(let n of this.directories)if(this.isPathWithinRoot(r,n))return!0;return!1}catch{return!1}}fullyResolvedPath(e){try{return ux.realpathSync(e)}catch(r){if(cs(r)&&r.code==="ENOENT"&&r.path&&!this.isFileSymlink(r.path))return r.path;throw r}}isPathWithinRoot(e,r){let n=dx.relative(r,e);return!n.startsWith(`..${dx.sep}`)&&n!==".."&&!dx.isAbsolute(n)}isFileSymlink(e){try{return!ux.readlinkSync(e).endsWith("/")}catch{return!1}}}});import zKr from"node:fs/promises";var Tle,C6t=ae(()=>{"use strict";Tle=class{async readTextFile(e){return zKr.readFile(e,"utf-8")}async writeTextFile(e,r){await zKr.writeFile(e,r,"utf-8")}}});import*as B_e from"node:path";import YKr from"node:process";var jn,mj,ob,Ile,qX,Dle,Fm=ae(()=>{"use strict";A3();aMt();SQe();yZ();$7();AH();E6r();uie();lO();Soe();cV();mve();vV();Jve();Ywr();tdt();yft();dzr();pV();U7e();pzr();nle();Y3t();qyt();n6t();Ou();b_();i6t();l4();Xae();o6t();aV();E6t();jKr();C6t();(function(t){t.DEFAULT="default",t.AUTO_EDIT="autoEdit",t.YOLO="yolo",t.PLAN="plan"})(jn||(jn={}));mj={respectGitIgnore:!1,respectGeminiIgnore:!0},ob={respectGitIgnore:!0,respectGeminiIgnore:!0},Ile=class{command;args;env;cwd;url;httpUrl;headers;tcp;type;timeout;trust;description;includeTools;excludeTools;extensionName;oauth;authProviderType;constructor(e,r,n,i,o,s,a,c,u,d,f,p,h,m,g,A,y){this.command=e,this.args=r,this.env=n,this.cwd=i,this.url=o,this.httpUrl=s,this.headers=a,this.tcp=c,this.type=u,this.timeout=d,this.trust=f,this.description=p,this.includeTools=h,this.excludeTools=m,this.extensionName=g,this.oauth=A,this.authProviderType=y}};(function(t){t.DYNAMIC_DISCOVERY="dynamic_discovery",t.GOOGLE_CREDENTIALS="google_credentials"})(qX||(qX={}));Dle=class t{toolRegistry;promptRegistry;sessionId;fileSystemService;conversationId;contentGeneratorConfig;embeddingModel;sandbox;targetDir;workspaceContext;debugMode;question;fullContext;coreTools;excludeTools;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;userMemory;geminiMdFileCount;approvalMode;showMemoryUsage;accessibility;telemetrySettings;usageStatisticsEnabled;systemReminderSettings;geminiClient;pendingHistoryRestore;fileFiltering;fileDiscoveryService=null;gitService=void 0;checkpointing;proxy;cwd;bugCommand;model;extensionContextFilePaths;noBrowser;inFallbackMode=!1;maxSessionTurns;listExtensions;_extensions;_blockedMcpServers;flashFallbackHandler;quotaErrorOccurred=!1;searchApiKey;apiKey;summarizeToolOutput;experimentalAcp=!1;acpPort;parallelTasksCount;agentCoreSystemPrompt;agentColor;hookManager;hookManagerEnabled;compressionTokenThreshold;useRipgrep;tokensLimit;skipNextSpeakerCheck;shellTimeout;budgetMaxTokens;budgetTimeout;ideClient;historyManager;isNonInteractive;disableTelemetry;enableBuildInTask;cna;language;outputStyleName;shouldUseNodePtyShell;shellExecutionConfig;constructor(e){this.cna=e.cna,this.language=e.language,this.sessionId=e.sessionId,this.embeddingModel=e.embeddingModel??uU,this.sandbox=e.sandbox,this.targetDir=B_e.resolve(e.targetDir),this.fileSystemService=new Tle,this.workspaceContext=new R_e(this.targetDir,e.includeDirectories??[]),this.debugMode=e.debugMode,this.ideClient=tO.getInstance(),this.question=e.question,this.fullContext=e.fullContext??!1,this.coreTools=e.coreTools,this.excludeTools=e.excludeTools,this.toolDiscoveryCommand=e.toolDiscoveryCommand,this.toolCallCommand=e.toolCallCommand,this.mcpServerCommand=e.mcpServerCommand,this.mcpServers=e.mcpServers,this.userMemory=e.userMemory??"",this.geminiMdFileCount=e.geminiMdFileCount??0,this.approvalMode=e.approvalMode??jn.DEFAULT,this.showMemoryUsage=e.showMemoryUsage??!1,this.accessibility=e.accessibility??{},this.telemetrySettings={enabled:e.telemetry?.enabled??!1,target:e.telemetry?.target??w_e,otlpEndpoint:e.telemetry?.otlpEndpoint??S_e,logPrompts:e.telemetry?.logPrompts??!0,outfile:e.telemetry?.outfile},this.usageStatisticsEnabled=e.usageStatisticsEnabled??!0,this.systemReminderSettings={enabled:e.systemReminder?.enabled??!0,eventTypes:e.systemReminder?.eventTypes??Object.values(xn),maxRemindersPerSession:e.systemReminder?.maxRemindersPerSession??10,telemetryEnabled:e.systemReminder?.telemetryEnabled??!0},this.fileFiltering={respectGitIgnore:e.fileFiltering?.respectGitIgnore??!0,respectGeminiIgnore:e.fileFiltering?.respectGeminiIgnore??!0,enableRecursiveFileSearch:e.fileFiltering?.enableRecursiveFileSearch??!0},this.checkpointing=e.checkpointing??!1,this.proxy=e.proxy,this.cwd=e.cwd??YKr.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.model=e.model,this.extensionContextFilePaths=e.extensionContextFilePaths??[],this.maxSessionTurns=e.maxSessionTurns??-1,this.experimentalAcp=e.experimentalAcp??!1,this.acpPort=e.acpPort,this.listExtensions=e.listExtensions??!1,this._extensions=e.extensions??[],this._blockedMcpServers=e.blockedMcpServers??[],this.noBrowser=e.noBrowser??!1,this.summarizeToolOutput=e.summarizeToolOutput,this.searchApiKey=e.searchApiKey,this.apiKey=e.apiKey,this.parallelTasksCount=e.parallelTasksCount??1,this.hookManagerEnabled=e.hookManager!==!1,this.compressionTokenThreshold=e.compressionTokenThreshold??.8,this.useRipgrep=e.useRipgrep??!0,this.budgetMaxTokens=e.maxTokens,this.budgetTimeout=e.timeout,this.tokensLimit=e.tokensLimit,this.skipNextSpeakerCheck=e.skipNextSpeakerCheck??!0,this.shellTimeout=e.shellTimeout??120*1e3,this.historyManager=e.historyManager,this.isNonInteractive=e.isNonInteractive??!1,this.disableTelemetry=e.disableTelemetry??!1,this.enableBuildInTask=e.enableBuildInTask??"true",this.outputStyleName=e.outputStyle,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??!0,this.shellExecutionConfig=e.shellExecutionConfig??{},e.contextFileName&&dV(e.contextFileName),e.hookManager!==!1&&(this.hookManager=new cx),this.telemetrySettings.enabled&&y7e(this),this.getUsageStatisticsEnabled()?rp.getInstance(this)?.logStartSessionEvent(new xV(this)):console.log("Data collection is disabled.")}async initialize(){this.getFileService(),this.getCheckpointingEnabled()&&await this.getGitService(),this.promptRegistry=new x0e,this.toolRegistry=await this.createToolRegistry(),this.hookManagerEnabled&&(this.hookManager=new cx({},this.toolRegistry))}async refreshAuth(e,r){if(this.contentGeneratorConfig?.authType===$t.LOGIN_WITH_IFLOW&&e!==$t.LOGIN_WITH_IFLOW){let{clearCachedCredentialFile:i}=await Promise.resolve().then(()=>(_w(),cLe));await i()}let n=r?.modelName||this.model;if(this.setModel(n),this.contentGeneratorConfig=await VFe(this,e,r),r?.modelName&&r.modelName!==this.model&&(this.model=r.modelName),r?.searchApiKey&&(this.searchApiKey=r.searchApiKey),this.geminiClient&&this.geminiClient.isInitialized()){let i=this.geminiClient.getHistory();this.setPendingHistoryRestore(i)}this.geminiClient=new ex(this),await this.geminiClient.initialize(this.contentGeneratorConfig),this.inFallbackMode=!1}getSessionId(){return this.sessionId}getCna(){return this.cna}getLanguage(){return this.language}setSessionId(e){this.sessionId=e}getConversationId(){return this.conversationId}setConversationId(e){this.conversationId=e}getContentGeneratorConfig(){return this.contentGeneratorConfig}getModel(){return this.contentGeneratorConfig?.model||this.model}setModel(e){this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e)}getFileSystemService(){return this.fileSystemService}setFileSystemService(e){this.fileSystemService=e}async setIdeModeAndSyncConnection(e){this.isNonInteractive||(e?await this.ideClient.connect():await this.ideClient.disconnect())}getIdeClient(){return this.ideClient}isInFallbackMode(){return this.inFallbackMode}setFallbackMode(e){this.inFallbackMode=e}setFlashFallbackHandler(e){this.flashFallbackHandler=e}getMaxSessionTurns(){return this.maxSessionTurns}getBudgetMaxTokens(){return this.budgetMaxTokens}getBudgetTimeout(){return this.budgetTimeout}setQuotaErrorOccurred(e){this.quotaErrorOccurred=e}getQuotaErrorOccurred(){return this.quotaErrorOccurred}getSearchApiKey(){if(this.searchApiKey)return this.searchApiKey;if(this.isIFlowService())return this.contentGeneratorConfig?.apiKey}isMultimodalEnabled(){return!0}getMultimodalModelName(){if(this.isIFlowService())return"qwen3-vl-plus"}getEmbeddingModel(){return this.embeddingModel}getCompressionTokenThreshold(){return this.compressionTokenThreshold}getHistoryManager(){return this.historyManager}getTokensLimit(){return this.tokensLimit}getSandbox(){return this.sandbox}isRestrictiveSandbox(){let e=this.getSandbox(),r=YKr.env.SEATBELT_PROFILE;return!!e&&e.command==="sandbox-exec"&&!!r&&r.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getProjectRoot(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return Promise.resolve(this.toolRegistry)}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getFullContext(){return this.fullContext}getCoreTools(){return this.coreTools}getExcludeTools(){return this.excludeTools}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}getMcpServers(){return this.mcpServers}addMcpServer(e,r){this.mcpServers||(this.mcpServers={}),this.mcpServers[e]=r}removeMcpServer(e){this.mcpServers&&e in this.mcpServers&&delete this.mcpServers[e]}getUserMemory(){return this.userMemory}setUserMemory(e){this.userMemory=e}getGeminiMdFileCount(){return this.geminiMdFileCount}setGeminiMdFileCount(e){this.geminiMdFileCount=e}setGeminiClient(e){this.geminiClient=e}getApprovalMode(){return this.approvalMode}setApprovalMode(e){this.approvalMode=e}getShowMemoryUsage(){return this.showMemoryUsage}getAccessibility(){return this.accessibility}getTelemetryEnabled(){return this.telemetrySettings.enabled??!1}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??!0}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??S_e}getTelemetryTarget(){return this.telemetrySettings.target??w_e}getTelemetryOutfile(){return this.telemetrySettings.outfile}getSystemReminderEnabled(){return this.systemReminderSettings.enabled}getSystemReminderEventTypes(){return this.systemReminderSettings.eventTypes}getSystemReminderMaxRemindersPerSession(){return this.systemReminderSettings.maxRemindersPerSession}getSystemReminderTelemetryEnabled(){return this.systemReminderSettings.telemetryEnabled}getGeminiClient(){return this.geminiClient}setPendingHistoryRestore(e){this.pendingHistoryRestore=e}getPendingHistoryRestore(){return this.pendingHistoryRestore}clearPendingHistoryRestore(){this.pendingHistoryRestore=void 0}getIFlowDir(){return B_e.join(this.targetDir,Ip)}getProjectTempDir(){return Mm(this.getProjectRoot())}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectGeminiIgnore(){return this.fileFiltering.respectGeminiIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectGeminiIgnore:this.fileFiltering.respectGeminiIgnore}}getCheckpointingEnabled(){return this.checkpointing}getProxy(){return this.proxy}getAuthType(){return this.contentGeneratorConfig?.authType}getApiKey(){return this.contentGeneratorConfig?.apiKey}getBaseUrl(){return this.contentGeneratorConfig?.baseUrl}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new Gk(this.targetDir)),this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}isIFlowService(){let e=this.getAuthType(),r=this.getBaseUrl();return e===$t.IFLOW||e===$t.LOGIN_WITH_IFLOW||r!==void 0&&r.toLowerCase().includes("apis.iflow.cn")}getExtensionContextFilePaths(){return this.extensionContextFilePaths}getExperimentalAcp(){return this.experimentalAcp}getAcpPort(){return this.acpPort}getListExtensions(){return this.listExtensions}getExtensions(){return this._extensions}getBlockedMcpServers(){return this._blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!Sle()}getSummarizeToolOutputConfig(){return this.summarizeToolOutput}getAgentCoreSystemPrompt(){return this.agentCoreSystemPrompt}setAgentCoreSystemPrompt(e){this.agentCoreSystemPrompt=e}getAgentColor(){return this.agentColor}setAgentColor(e){this.agentColor=e}hasAgentCoreSystemPrompt(){return this.agentCoreSystemPrompt!==void 0&&this.agentCoreSystemPrompt!==""}async getGitService(){return this.gitService||(this.gitService=new sx(this.targetDir),await this.gitService.initialize()),this.gitService}getHookManager(){return this.hookManager}getUseRipgrep(){return this.useRipgrep}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellTimeout(){return this.shellTimeout}getDisableTelemetry(){return this.disableTelemetry}getOutputStyle(){return this.outputStyleName}setOutputStyle(e){this.outputStyleName=e,this.geminiClient&&this.geminiClient.isInitialized()&&this.geminiClient.resetChat().catch(r=>{console.warn("Failed to reset chat after output style change:",r)})}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getShellExecutionConfig(){return{...this.shellExecutionConfig}}async refreshMemory(){let{memoryContent:e,fileCount:r}=await Kk(this.getWorkingDir(),this.getDebugMode(),this.getFileService(),this.getExtensionContextFilePaths());return this.setUserMemory(e),this.setGeminiMdFileCount(r),{memoryContent:e,fileCount:r}}getAll(){return{sessionId:this.sessionId,embeddingModel:this.embeddingModel,sandbox:this.sandbox,targetDir:this.targetDir,debugMode:this.debugMode,question:this.question,fullContext:this.fullContext,coreTools:this.coreTools,excludeTools:this.excludeTools,toolDiscoveryCommand:this.toolDiscoveryCommand,toolCallCommand:this.toolCallCommand,mcpServerCommand:this.mcpServerCommand,mcpServers:this.mcpServers,userMemory:this.userMemory,geminiMdFileCount:this.geminiMdFileCount,approvalMode:this.approvalMode,showMemoryUsage:this.showMemoryUsage,contextFileName:void 0,accessibility:this.accessibility,telemetry:this.telemetrySettings,usageStatisticsEnabled:this.usageStatisticsEnabled,fileFiltering:this.fileFiltering,checkpointing:this.checkpointing,proxy:this.proxy,cwd:this.cwd,fileDiscoveryService:this.fileDiscoveryService,bugCommand:this.bugCommand,model:this.model,extensionContextFilePaths:this.extensionContextFilePaths,maxSessionTurns:this.maxSessionTurns,listExtensions:this.listExtensions,noBrowser:this.noBrowser,searchApiKey:this.searchApiKey,apiKey:this.apiKey,parallelTasksCount:this.parallelTasksCount,compressionTokenThreshold:this.compressionTokenThreshold,useRipgrep:this.useRipgrep,skipNextSpeakerCheck:this.skipNextSpeakerCheck,shellTimeout:this.shellTimeout,disableTelemetry:this.disableTelemetry,enableBuildInTask:this.enableBuildInTask,outputStyle:this.outputStyleName}}async createToolRegistry(){let e=new HX(this),r=(n,...i)=>{let o=n.name,s=n.Name||o,a=this.getCoreTools(),c=this.getExcludeTools(),u=!1;a===void 0?u=!0:u=a.some(d=>d===o||d===s||d.startsWith(`${o}(`)||d.startsWith(`${s}(`)),(c?.includes(o)||c?.includes(s))&&(u=!1),u&&e.registerTool(new n(...i))};return r(ib,this),r(Lc,this),this.getUseRipgrep()?r(lEe,this):r(W1,this),r($1,this),r(Af,this),r(ld,this),r(Q7e,this),r(V7e,this),r(aO,this),r(pu,this),r(h_),r(qk,this),r($l,this),r(X4,this),r(CV,this),r(iA,this),r(Kve),await e.discoverAllTools(this.isNonInteractive),e}async clone(){let e=this.getAll(),r={sessionId:e.sessionId,embeddingModel:e.embeddingModel,sandbox:e.sandbox?{...e.sandbox}:void 0,targetDir:e.targetDir,debugMode:e.debugMode,question:e.question,fullContext:e.fullContext,coreTools:e.coreTools?[...e.coreTools]:void 0,excludeTools:e.excludeTools?[...e.excludeTools]:void 0,toolDiscoveryCommand:e.toolDiscoveryCommand,toolCallCommand:e.toolCallCommand,mcpServerCommand:e.mcpServerCommand,mcpServers:e.mcpServers?JSON.parse(JSON.stringify(e.mcpServers)):void 0,userMemory:e.userMemory,geminiMdFileCount:e.geminiMdFileCount,approvalMode:e.approvalMode,showMemoryUsage:e.showMemoryUsage,contextFileName:e.contextFileName,accessibility:e.accessibility?{...e.accessibility}:void 0,telemetry:e.telemetry?{...e.telemetry}:void 0,usageStatisticsEnabled:e.usageStatisticsEnabled,fileFiltering:e.fileFiltering?{...e.fileFiltering}:void 0,checkpointing:e.checkpointing,proxy:e.proxy,cwd:e.cwd,fileDiscoveryService:e.fileDiscoveryService,bugCommand:e.bugCommand?{...e.bugCommand}:void 0,model:e.model,extensionContextFilePaths:e.extensionContextFilePaths?[...e.extensionContextFilePaths]:[],maxSessionTurns:e.maxSessionTurns,experimentalAcp:e.experimentalAcp,listExtensions:e.listExtensions,extensions:this.getExtensions()?this.getExtensions().map(i=>({...i})):[],blockedMcpServers:this.getBlockedMcpServers()?this.getBlockedMcpServers().map(i=>({...i})):[],noBrowser:e.noBrowser,summarizeToolOutput:this.getSummarizeToolOutputConfig()?JSON.parse(JSON.stringify(this.getSummarizeToolOutputConfig())):void 0,searchApiKey:e.searchApiKey,parallelTasksCount:e.parallelTasksCount,ideClient:this.getIdeClient(),compressionTokenThreshold:e.compressionTokenThreshold,useRipgrep:e.useRipgrep,skipNextSpeakerCheck:e.skipNextSpeakerCheck,shellTimeout:e.shellTimeout,disableTelemetry:e.disableTelemetry,outputStyle:e.outputStyle},n=new t(r);if(await n.initialize(),this.getContentGeneratorConfig())try{n.setModel(this.model),n.contentGeneratorConfig=this.contentGeneratorConfig,n.searchApiKey=this.searchApiKey,n.inFallbackMode=!1}catch(i){console.warn("Failed to clone auth configuration:",i)}return n.setFallbackMode(this.isInFallbackMode()),n.setQuotaErrorOccurred(this.getQuotaErrorOccurred()),n}}});import JKr from"node:path";import{promises as fx}from"node:fs";var q2o,xj,rM,KKr=ae(()=>{"use strict";Ou();q2o="logs.json";(function(t){t.USER="user"})(xj||(xj={}));rM=class{iFlowDir;logFilePath;sessionId;messageId=0;initialized=!1;logs=[];constructor(e){this.sessionId=e}async _readLogFile(){if(!this.logFilePath)throw new Error("Log file path not set during read attempt.");try{let e=await fx.readFile(this.logFilePath,"utf-8"),r=JSON.parse(e);return Array.isArray(r)?r.filter(n=>typeof n.sessionId=="string"&&typeof n.messageId=="number"&&typeof n.timestamp=="string"&&typeof n.type=="string"&&typeof n.message=="string"):(console.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`),await this._backupCorruptedLogFile("malformed_array"),[])}catch(e){if(e.code==="ENOENT")return[];if(e instanceof SyntaxError)return console.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`,e),await this._backupCorruptedLogFile("invalid_json"),[];throw console.debug(`Failed to read or parse log file ${this.logFilePath}:`,e),e}}async _backupCorruptedLogFile(e){if(!this.logFilePath)return;let r=`${this.logFilePath}.${e}.${Date.now()}.bak`;try{await fx.rename(this.logFilePath,r),console.debug(`Backed up corrupted log file to ${r}`)}catch{}}async initialize(){if(!this.initialized){this.iFlowDir=Mm(process.cwd()),this.logFilePath=JKr.join(this.iFlowDir,q2o);try{await fx.mkdir(this.iFlowDir,{recursive:!0});let e=!0;try{await fx.access(this.logFilePath)}catch{e=!1}this.logs=await this._readLogFile(),!e&&this.logs.length===0&&await fx.writeFile(this.logFilePath,"[]","utf-8");let r=this.logs.filter(n=>n.sessionId===this.sessionId);this.messageId=r.length>0?Math.max(...r.map(n=>n.messageId))+1:0,this.initialized=!0}catch(e){console.error("Failed to initialize logger:",e),this.initialized=!1}}}async _updateLogFile(e){if(!this.logFilePath)throw console.debug("Log file path not set. Cannot persist log entry."),new Error("Log file path not set during update attempt.");let r;try{r=await this._readLogFile()}catch(s){throw console.debug("Critical error reading log file before append:",s),s}let n=r.filter(s=>s.sessionId===e.sessionId),i=n.length>0?Math.max(...n.map(s=>s.messageId))+1:0;if(e.messageId=i,r.some(s=>s.sessionId===e.sessionId&&s.messageId===e.messageId&&s.timestamp===e.timestamp&&s.message===e.message))return console.debug(`Duplicate log entry detected and skipped: session ${e.sessionId}, messageId ${e.messageId}`),this.logs=r,null;r.push(e);try{return await fx.writeFile(this.logFilePath,JSON.stringify(r,null,2),"utf-8"),this.logs=r,e}catch(s){throw console.debug("Error writing to log file:",s),s}}async getPreviousUserMessages(){return this.initialized?this.logs.filter(e=>e.type===xj.USER).sort((e,r)=>{let n=new Date(e.timestamp).getTime();return new Date(r.timestamp).getTime()-n}).map(e=>e.message):[]}async logMessage(e,r){if(!this.initialized||this.sessionId===void 0){console.debug("Logger not initialized or session ID missing. Cannot log message.");return}let n={sessionId:this.sessionId,messageId:this.messageId,type:e,message:r,timestamp:new Date().toISOString()};try{let i=await this._updateLogFile(n);i&&(this.messageId=i.messageId+1)}catch{}}_checkpointPath(e){if(!e.length)throw new Error("No checkpoint tag specified.");if(!this.iFlowDir)throw new Error("Checkpoint file path not set.");let r=e.replace(/[^a-zA-Z0-9-_]/g,"");return r||(r="default"),JKr.join(this.iFlowDir,`checkpoint-${r}.json`)}async saveCheckpoint(e,r){if(!this.initialized){console.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");return}let n=this._checkpointPath(r);try{await fx.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(i){console.error("Error writing to checkpoint file:",i)}}async loadCheckpoint(e){if(!this.initialized)return console.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint."),[];let r=this._checkpointPath(e);try{let n=await fx.readFile(r,"utf-8"),i=JSON.parse(n);return Array.isArray(i)?i:(console.warn(`Checkpoint file at ${r} is not a valid JSON array. Returning empty checkpoint.`),[])}catch(n){return console.error(`Failed to read or parse checkpoint file ${r}:`,n),[]}}async deleteCheckpoint(e){if(!this.initialized||!this.iFlowDir)return console.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint."),!1;let r=this._checkpointPath(e);try{return await fx.unlink(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw console.error(`Failed to delete checkpoint file ${r}:`,n),n}}close(){this.initialized=!1,this.logFilePath=void 0,this.logs=[],this.sessionId=void 0,this.messageId=0}}});function G2o(t){return vve(t,{verbose:!0})}var XKr=ae(()=>{"use strict";yct();});function ZKr(t,e,r,n){let i=e===Ur.HOOK_BLOCKED,a=`${i?"\u{1F6A8} CRITICAL":"\u26A0\uFE0F IMPORTANT"}: The tool "${t}" has ${i?"BEEN BLOCKED":"FAILED"}. `;switch(e){case Ur.FILE_NOT_FOUND:a+="The file or directory does not exist. ";break;case Ur.PERMISSION_DENIED:a+="You do not have permission to access this resource. ";break;case Ur.HOOK_BLOCKED:a+="The operation was blocked by a user-configured hook. ";break;case Ur.EXECUTION_FAILED:a+="The command execution failed. ";break;case Ur.INVALID_TOOL_PARAMS:a+="The parameters provided were invalid. ";break;case Ur.FILE_WRITE_FAILURE:a+="Failed to write to the file. ";break;case Ur.READ_CONTENT_FAILURE:a+="Failed to read the file content. ";break;default:a+="An error occurred during execution. "}return a+=`Error: "${r}". `,a+=`
3738
3738
 
3739
3739
  \u26A0\uFE0F This operation DID NOT succeed. `,a+="DO NOT proceed as if it was successful. ",n&&(a+=`
3740
3740
 
@@ -4118,7 +4118,7 @@ ${de.description}`:de.subject||de.description||"Thinking...",[]),ue=(0,Aa.useCal
4118
4118
  `,e-1);return{line:r===-1?0:t.slice(0,r+1).match(/\n/g).length,column:e-r-1}}function J6t(t,e,{oneBased:r=!1}={}){if(typeof t!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(e))throw new TypeError("Index parameter should be an integer");if(e<0||e>t.length)throw new RangeError("Index out of bounds");let n=IAo(t,e);return r?{line:n.line+1,column:n.column+1}:n}var DAo=t=>`\\u{${t.codePointAt(0).toString(16)}}`,K6t=class t extends Error{name="JSONError";fileName;#e;#t;#r;#n;#o;constructor(e){if(typeof e=="string")super(),this.#r=e;else{let{jsonParseError:r,fileName:n,input:i}=e;super(void 0,{cause:r}),this.#e=i,this.#t=r,this.fileName=n}Error.captureStackTrace?.(this,t)}get message(){this.#r??=`${BAo(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
4119
4119
 
4120
4120
  ${e}
4121
- `:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=RAo(r,this.#t.message);if(n)return(0,atn.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#o??=this.#i(!1),this.#o}},RAo=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:J6t(t,Number(n),{oneBased:!0})},BAo=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${DAo(n)})`);function X6t(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new K6t({jsonParseError:n,fileName:r,input:t})}}var irn=Fe(rrn(),1);import{fileURLToPath as D3o}from"node:url";function nrn(t){return t instanceof URL?D3o(t):t}var N3o=t=>B3o.resolve(nrn(t)??".","package.json"),O3o=(t,e)=>{let r=typeof t=="string"?X6t(t):t;return e&&(0,irn.default)(r),r};async function orn({cwd:t,normalize:e=!0}={}){let r=await R3o.readFile(N3o(t),"utf8");return O3o(r,e)}async function srn(t){let e=await Pen("package.json",t);if(e)return{packageJson:await orn({...t,cwd:k3o.dirname(e)}),path:e}}import{fileURLToPath as M3o}from"url";import P3o from"path";var L3o=M3o(import.meta.url),F3o=P3o.dirname(L3o),dTe;async function Wj(){if(dTe)return dTe;let t=await srn({cwd:F3o});if(t)return dTe=t.packageJson,dTe}async function wT(){let t=await Wj();return"0.3.1"}Cs();Nt();import fM from"node:process";var arn={name:"about",description:k.t("command.about"),kind:"built-in",action:async t=>{let e=fM.platform,r=k.t("aboutCommand.noSandbox");fM.env.SANDBOX&&fM.env.SANDBOX!=="sandbox-exec"?r=fM.env.SANDBOX:fM.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${fM.env.SEATBELT_PROFILE||k.t("aboutCommand.unknown")})`);let n=t.services.config?.getModel()||k.t("aboutCommand.unknown"),i=await wT(),o=t.services.settings.merged.selectedAuthType||"",s=fM.env.GOOGLE_CLOUD_PROJECT||"",a={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s};t.ui.addItem(a,Date.now())}};Nt();Nt();Cs();var pTe="\x1B[32m";var crn="\x1B[31m",ST="\x1B[36m",s0="\x1B[90m";var tl="\x1B[0m";function fTe(t,e,r,n=!1){let i="";if(t.length===0)return i="\u{1F534} ",`${i}${e}
4121
+ `:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=RAo(r,this.#t.message);if(n)return(0,atn.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#o??=this.#i(!1),this.#o}},RAo=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:J6t(t,Number(n),{oneBased:!0})},BAo=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${DAo(n)})`);function X6t(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new K6t({jsonParseError:n,fileName:r,input:t})}}var irn=Fe(rrn(),1);import{fileURLToPath as D3o}from"node:url";function nrn(t){return t instanceof URL?D3o(t):t}var N3o=t=>B3o.resolve(nrn(t)??".","package.json"),O3o=(t,e)=>{let r=typeof t=="string"?X6t(t):t;return e&&(0,irn.default)(r),r};async function orn({cwd:t,normalize:e=!0}={}){let r=await R3o.readFile(N3o(t),"utf8");return O3o(r,e)}async function srn(t){let e=await Pen("package.json",t);if(e)return{packageJson:await orn({...t,cwd:k3o.dirname(e)}),path:e}}import{fileURLToPath as M3o}from"url";import P3o from"path";var L3o=M3o(import.meta.url),F3o=P3o.dirname(L3o),dTe;async function Wj(){if(dTe)return dTe;let t=await srn({cwd:F3o});if(t)return dTe=t.packageJson,dTe}async function wT(){let t=await Wj();return"0.3.2-beta.0"}Cs();Nt();import fM from"node:process";var arn={name:"about",description:k.t("command.about"),kind:"built-in",action:async t=>{let e=fM.platform,r=k.t("aboutCommand.noSandbox");fM.env.SANDBOX&&fM.env.SANDBOX!=="sandbox-exec"?r=fM.env.SANDBOX:fM.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${fM.env.SEATBELT_PROFILE||k.t("aboutCommand.unknown")})`);let n=t.services.config?.getModel()||k.t("aboutCommand.unknown"),i=await wT(),o=t.services.settings.merged.selectedAuthType||"",s=fM.env.GOOGLE_CLOUD_PROJECT||"",a={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s};t.ui.addItem(a,Date.now())}};Nt();Nt();Cs();var pTe="\x1B[32m";var crn="\x1B[31m",ST="\x1B[36m",s0="\x1B[90m";var tl="\x1B[0m";function fTe(t,e,r,n=!1){let i="";if(t.length===0)return i="\u{1F534} ",`${i}${e}
4122
4122
  ${crn}${k.t("agentsCommand.list.noAgentsFound")}${tl}
4123
4123
  `;i="\u{1F7E2} ";let o=`${i}${e}
4124
4124
  `;for(let s of t)n?o+=U3o(s):o+=`${pTe}- ${s.agentType}${tl}
@@ -4161,7 +4161,7 @@ ${s0}${k.t("agentsCommand.list.builtinAgents")}${tl}
4161
4161
  ${s0}${k.t("agentsCommand.list.generalPurpose")}
4162
4162
  ${tl}`;let c=n.length+i.length;t.ui.addItem({type:"info",text:`${pTe}${k.t("agentsCommand.refresh.success",{count:c})}${tl}
4163
4163
 
4164
- ${pTe}${a.trim()}${tl}`},Date.now())}catch(e){let r=sr(e);t.ui.addItem({type:"error",text:`${crn}${k.t("agentsCommand.refresh.error",{error:r})}${tl}`},Date.now())}}},{name:"online",description:k.t("agentsCommand.subCommands.online"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agents-online"})},{name:"install",description:k.t("agentsCommand.subCommands.install"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agent-install"})}]};Nt();var drn={name:"auth",description:k.t("command.auth"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"auth"})};dD();import Ex from"node:process";import Q3o from"node:os";Cs();Nt();var $j="7a68daf3 (local modifications)";Nt();async function q3o(t,e){let r="https://apis.iflow.cn/v1/bug/report",i={content:JSON.stringify(t,null,2)},o={"Content-Type":"application/json"};e&&(o.Authorization=`Bearer ${e}`);try{let s=await fetch(r,{method:"POST",headers:o,body:JSON.stringify(i)});if(s.ok){let a=await s.json();return console.log("Bug report data sent successfully to endpoint"),a.success&&a.data?a.data:(console.warn("Unexpected response format from endpoint:",a),null)}else return console.warn(`Failed to send bug report to endpoint: ${s.status} ${s.statusText}`),null}catch(s){return console.warn("Failed to send bug report to endpoint:",s),null}}var frn={name:"bug",description:k.t("command.bug"),kind:"built-in",action:async(t,e)=>{let r=(e||"").trim(),{config:n}=t.services,i=_D(),o=`${Ex.platform} ${Ex.version}`,s=k.t("bugCommand.noSandbox");Ex.env.SANDBOX&&Ex.env.SANDBOX!=="sandbox-exec"?s=Ex.env.SANDBOX.replace(/^iflow-(?:code-)?/,""):Ex.env.SANDBOX==="sandbox-exec"&&(s=`sandbox-exec (${Ex.env.SEATBELT_PROFILE||"unknown"})`);let a=n?.getModel()||k.t("bugCommand.unknown"),c=await wT(),u=_j(Ex.memoryUsage().rss),d=i.getInMemoryErrors(),f=k.t("bugCommand.noRecentErrors");d.length>0&&(f=d.slice(-3).map(O=>k.t("bugCommand.errorWithTimestamp",{timestamp:O.timestamp,error:O.error})).join(`
4164
+ ${pTe}${a.trim()}${tl}`},Date.now())}catch(e){let r=sr(e);t.ui.addItem({type:"error",text:`${crn}${k.t("agentsCommand.refresh.error",{error:r})}${tl}`},Date.now())}}},{name:"online",description:k.t("agentsCommand.subCommands.online"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agents-online"})},{name:"install",description:k.t("agentsCommand.subCommands.install"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agent-install"})}]};Nt();var drn={name:"auth",description:k.t("command.auth"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"auth"})};dD();import Ex from"node:process";import Q3o from"node:os";Cs();Nt();var $j="049d93f3 (local modifications)";Nt();async function q3o(t,e){let r="https://apis.iflow.cn/v1/bug/report",i={content:JSON.stringify(t,null,2)},o={"Content-Type":"application/json"};e&&(o.Authorization=`Bearer ${e}`);try{let s=await fetch(r,{method:"POST",headers:o,body:JSON.stringify(i)});if(s.ok){let a=await s.json();return console.log("Bug report data sent successfully to endpoint"),a.success&&a.data?a.data:(console.warn("Unexpected response format from endpoint:",a),null)}else return console.warn(`Failed to send bug report to endpoint: ${s.status} ${s.statusText}`),null}catch(s){return console.warn("Failed to send bug report to endpoint:",s),null}}var frn={name:"bug",description:k.t("command.bug"),kind:"built-in",action:async(t,e)=>{let r=(e||"").trim(),{config:n}=t.services,i=_D(),o=`${Ex.platform} ${Ex.version}`,s=k.t("bugCommand.noSandbox");Ex.env.SANDBOX&&Ex.env.SANDBOX!=="sandbox-exec"?s=Ex.env.SANDBOX.replace(/^iflow-(?:code-)?/,""):Ex.env.SANDBOX==="sandbox-exec"&&(s=`sandbox-exec (${Ex.env.SEATBELT_PROFILE||"unknown"})`);let a=n?.getModel()||k.t("bugCommand.unknown"),c=await wT(),u=_j(Ex.memoryUsage().rss),d=i.getInMemoryErrors(),f=k.t("bugCommand.noRecentErrors");d.length>0&&(f=d.slice(-3).map(O=>k.t("bugCommand.errorWithTimestamp",{timestamp:O.timestamp,error:O.error})).join(`
4165
4165
 
4166
4166
  `));let p=Q3o.userInfo().username,h=T=>{if(!p)return T;let O=new RegExp(`/${p}/`,"g");return T.replace(O,"/user/")},m=`CLI Version: ${c}
4167
4167
  Git Commit: ${$j}
@@ -5095,7 +5095,7 @@ ${L.detailContext||L.description}
5095
5095
 
5096
5096
  iFlow CLI - Launch an interactive CLI, use -p/--prompt for non-interactive mode`).command("$0","Launch iFlow CLI",r=>r.option("model",{alias:"m",type:"string",description:"Model",default:cp.env.modelName||cp.env.MODELNAME||cp.env.MODEL_NAME||cp.env.model_name||cp.env.model||cp.env.MODEL}).option("prompt",{alias:"p",type:"string",description:"Prompt. Appended to input on stdin (if any)."}).option("prompt-interactive",{alias:"i",type:"string",description:"Execute the provided prompt and continue in interactive mode"}).option("continue",{alias:"c",type:"boolean",description:"Start the application and load the most recent conversation from current directory",default:!1}).option("resume",{alias:"r",description:"Resume conversation from a specific session file. If no session ID is provided, shows interactive session selector.",coerce:n=>n===!0?!0:n}).option("sandbox",{alias:"s",type:"boolean",description:"Run in sandbox?"}).option("sandbox-image",{type:"string",description:"Sandbox image URI."}).option("debug",{alias:"d",type:"boolean",description:"Run in debug mode?",default:!1}).option("all-files",{alias:["a"],type:"boolean",description:"Include ALL files in context?",default:!1}).option("all_files",{type:"boolean",description:"Include ALL files in context?",default:!1}).deprecateOption("all_files","Use --all-files instead. We will be removing --all_files in the coming weeks.").option("show-memory-usage",{type:"boolean",description:"Show memory usage in status bar",default:!1}).option("show_memory_usage",{type:"boolean",description:"Show memory usage in status bar",default:!1}).deprecateOption("show_memory_usage","Use --show-memory-usage instead. We will be removing --show_memory_usage in the coming weeks.").option("yolo",{alias:"y",type:"boolean",description:"Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?",default:!0}).option("telemetry",{type:"boolean",description:"Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own."}).option("telemetry-target",{type:"string",choices:["local","gcp"],description:"Set the telemetry target (local or gcp). Overrides settings files."}).option("telemetry-otlp-endpoint",{type:"string",description:"Set the OTLP endpoint for telemetry. Overrides environment variables and settings files."}).option("telemetry-log-prompts",{type:"boolean",description:"Enable or disable logging of user prompts for telemetry. Overrides settings files."}).option("telemetry-outfile",{type:"string",description:"Redirect all telemetry output to the specified file."}).option("checkpointing",{alias:"c",type:"boolean",description:"Enables checkpointing of file edits",default:!1}).option("experimental-acp",{type:"boolean",description:"Starts the agent in ACP mode"}).option("port",{type:"number",description:"Port number for ACP server (used with --experimental-acp)"}).option("allowed-mcp-server-names",{type:"array",string:!0,description:"Allowed MCP server names"}).option("include-directories",{alias:"add-dir",type:"array",string:!0,description:"Additional directories to include in the workspace (comma-separated or multiple --include-directories)",coerce:n=>n.flatMap(i=>i.split(",").map(o=>o.trim()))}).option("max-turns",{type:"number",description:"Maximum number of model calls (assistant rounds) before terminating"}).option("max_turns",{type:"number",description:"Maximum number of model calls (assistant rounds) before terminating"}).deprecateOption("max_turns","Use --max-turns instead. We will be removing --max_turns in the coming weeks.").option("max-tokens",{type:"number",description:"Maximum total token usage (input + output) before terminating"}).option("max_tokens",{type:"number",description:"Maximum total token usage (input + output) before terminating"}).deprecateOption("max_tokens","Use --max-tokens instead. We will be removing --max_tokens in the coming weeks.").option("timeout",{type:"number",description:"Maximum execution time in seconds before terminating"}).option("output-file",{alias:"o",type:"string",description:"Output file path to save execution information (non-interactive mode only)"}).option("output_file",{type:"string",description:"Output file path to save execution information (non-interactive mode only)"}).deprecateOption("output_file","Use --output-file instead. We will be removing --output_file in the coming weeks.").check(n=>{if(n.prompt&&n.promptInteractive)throw new Error("Cannot use both --prompt (-p) and --prompt-interactive (-i) together");if(n.maxTurns!==void 0&&n.maxTurns!==null&&typeof n.maxTurns=="number"&&n.maxTurns<=0)throw new Error("--max-turns must be a positive number");if(n.max_turns!==void 0&&n.max_turns!==null&&typeof n.max_turns=="number"&&n.max_turns<=0)throw new Error("--max_turns must be a positive number");if(n.maxTokens!==void 0&&n.maxTokens!==null&&typeof n.maxTokens=="number"&&n.maxTokens<=0)throw new Error("--max-tokens must be a positive number");if(n.max_tokens!==void 0&&n.max_tokens!==null&&typeof n.max_tokens=="number"&&n.max_tokens<=0)throw new Error("--max_tokens must be a positive number");if(n.timeout!==void 0&&n.timeout!==null&&typeof n.timeout=="number"&&n.timeout<=0)throw new Error("--timeout must be a positive number");return!0})).command(zcn).command(H5t).command(W5t).command(wun).version(await wT()).alias("v","version").help().alias("h","help").strict().demandCommand(0,0);t.wrap(t.terminalWidth());let e=await t.parse();return e._.length>0&&e._[0]==="mcp"&&cp.exit(0),e._.length>0&&e._[0]==="workflow"&&cp.exit(0),e}async function J5t(t,e,r,n,i=[],o="tree",s){let a=j5t.realpathSync(z5t.resolve(t)),c=j5t.realpathSync(z5t.resolve(i8o())),d=a===c?"":t;return e&&Y5t.debug(`CLI: Delegating hierarchical memory load to server for CWD: ${t} (memoryImportFormat: ${o})`),Kk(d,e,r,i,o,s,n.memoryDiscoveryMaxDirs)}async function qM(t,e,r,n,i=cp.cwd()){let o=n.debug||[cp.env.DEBUG,cp.env.DEBUG_MODE].some(x=>x==="true"||x==="1")||!1,s=t.memoryImportFormat||"tree",a=Dcn(e,n.extensions||[]),c=e.filter((x,T)=>a[T].isActive);t.contextFileName?dV(t.contextFileName):dV(fV());let u=c.flatMap(x=>x.contextFiles),d=new Gk(i),f={...mj,...t.fileFiltering};TFe(t.errorLog);let{memoryContent:p,fileCount:h}=await J5t(i,o,d,t,u,s,f),m=o8o(t,c),g=s8o(t,c),A=[];if(!n.allowedMcpServerNames){if(t.allowMCPServers){let x=new Set(t.allowMCPServers.filter(Boolean));x.size>0&&(m=Object.fromEntries(Object.entries(m).filter(([T])=>x.has(T))))}if(t.excludeMCPServers){let x=new Set(t.excludeMCPServers.filter(Boolean));x.size>0&&(m=Object.fromEntries(Object.entries(m).filter(([T])=>!x.has(T))))}}if(n.allowedMcpServerNames){let x=new Set(n.allowedMcpServerNames.filter(Boolean));x.size>0?m=Object.fromEntries(Object.entries(m).filter(([T,O])=>{let N=x.has(T);return N||A.push({name:T,extensionName:O.extensionName||""}),N})):(A.push(...Object.entries(m).map(([T,O])=>({name:T,extensionName:O.extensionName||""}))),m={})}let y=await Qcn(t,n),E=new ip,C=!1;try{await E.initialize(),C=!0}catch(x){Y5t.error("History manager initialization failed. History features will be disabled.",x)}return new Dle({cna:t.cna,language:t.language,sessionId:r,embeddingModel:uU,sandbox:y,targetDir:i||cp.cwd(),includeDirectories:t.includeDirectories||n.includeDirectories,debugMode:o,question:n.promptInteractive||n.prompt||"",fullContext:n.allFiles||n.all_files||!1,coreTools:t.coreTools||void 0,excludeTools:g,toolDiscoveryCommand:t.toolDiscoveryCommand,toolCallCommand:t.toolCallCommand,mcpServerCommand:t.mcpServerCommand,mcpServers:m,userMemory:p,geminiMdFileCount:h,approvalMode:t.approvalMode||(n.yolo?jn.YOLO:jn.DEFAULT),showMemoryUsage:n.showMemoryUsage||n.show_memory_usage||t.showMemoryUsage||!1,accessibility:t.accessibility,telemetry:{enabled:n.telemetry??t.telemetry?.enabled,target:n.telemetryTarget??t.telemetry?.target,otlpEndpoint:n.telemetryOtlpEndpoint??cp.env.OTEL_EXPORTER_OTLP_ENDPOINT??t.telemetry?.otlpEndpoint,logPrompts:n.telemetryLogPrompts??t.telemetry?.logPrompts,outfile:n.telemetryOutfile??t.telemetry?.outfile},usageStatisticsEnabled:t.usageStatisticsEnabled??!0,fileFiltering:{respectGitIgnore:t.fileFiltering?.respectGitIgnore,respectGeminiIgnore:t.fileFiltering?.respectGeminiIgnore,enableRecursiveFileSearch:t.fileFiltering?.enableRecursiveFileSearch},checkpointing:n.checkpointing||t.checkpointing?.enabled,proxy:n.proxy||cp.env.HTTPS_PROXY||cp.env.https_proxy||cp.env.HTTP_PROXY||cp.env.http_proxy,cwd:i,fileDiscoveryService:d,bugCommand:t.bugCommand,model:t.modelName||n.model,extensionContextFilePaths:u,maxSessionTurns:n.maxTurns||n.max_turns||(t.maxSessionTurns??-1),experimentalAcp:n.experimentalAcp||!1,acpPort:n.port,listExtensions:n.listExtensions||!1,extensions:a,blockedMcpServers:A,noBrowser:!!cp.env.NO_BROWSER,summarizeToolOutput:t.toolSummarizationSettings,searchApiKey:t.searchApiKey,hookManager:t.hookManager??!0,compressionTokenThreshold:t.compressionTokenThreshold,maxTokens:n.maxTokens||n.max_tokens,timeout:n.timeout,tokensLimit:t.tokensLimit,skipNextSpeakerCheck:t.skipNextSpeakerCheck??!0,shellTimeout:t.shellTimeout,historyManager:C?E:void 0,isNonInteractive:!!n.prompt&&!n.promptInteractive&&!n.continue&&!n.resume||n.experimentalAcp,disableTelemetry:t.disableTelemetry??!1,enableBuildInTask:t.enableBuildInTask,outputStyle:t.outputStyle,shouldUseNodePtyShell:t.enableInteractiveShell??!1})}function o8o(t,e){let r={...t.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([i,o])=>{if(r[i]){Y5t.warn(`Skipping extension MCP config for server with key "${i}" as it already exists.`);return}r[i]={...o,extensionName:n.config.name}});return r}function s8o(t,e){let r=new Set(t.excludeTools||[]);for(let n of e)for(let i of n.config.excludeTools||[])r.add(i);return[...r]}await Br();ln();ri();var Hu=Fe(_t(),1);var Sun=["tips.fileInclusion","tips.shellExecution","tips.chatHistory","tips.clearScreen","tips.contextCompression","tips.toolsOverview","tips.fileRestore","tips.sessionStats","tips.shellToggle","tips.memoryManagement","tips.themeCustomization","tips.mcpServers"],a8o=Sun[Math.floor(Math.random()*Sun.length)],_un=({config:t})=>{let e=t.getGeminiMdFileCount(),{t:r}=zt();return(0,Hu.jsxs)(fe,{flexDirection:"column",children:[(0,Hu.jsx)(K,{color:pe.Foreground,children:r("tips.header")}),(0,Hu.jsx)(K,{color:pe.Foreground,children:r("tips.basicUsage")}),(0,Hu.jsx)(K,{color:pe.Foreground,children:r("tips.bestPractices")}),e===0&&(0,Hu.jsx)(K,{color:pe.Foreground,children:(0,Hu.jsx)(o3,{i18nKey:"tips.fileConfiguration",tOptions:{interpolation:{escapeValue:!1}},components:{fileName:(0,Hu.jsx)(K,{bold:!0,color:pe.AccentPurple,children:"IFLOW.md"}),command:(0,Hu.jsx)(K,{bold:!0,color:pe.AccentBlue,children:"/init"})}})}),(0,Hu.jsxs)(K,{color:pe.Foreground,children:[e===0?"4.":"3."," ",(0,Hu.jsx)(o3,{i18nKey:"tips.helpCommand",tOptions:{interpolation:{escapeValue:!1}},components:{command:(0,Hu.jsx)(K,{bold:!0,color:pe.AccentBlue,children:"/help"})}})]}),(0,Hu.jsxs)(K,{color:pe.Foreground,children:[e===0?"5.":"4."," ",(0,Hu.jsx)(o3,{i18nKey:"tips.yoloMode",tOptions:{interpolation:{escapeValue:!1}},components:{mode:(0,Hu.jsx)(K,{bold:!0,color:pe.AccentRed,children:"Yolo"}),keyCombination:(0,Hu.jsx)(K,{bold:!0,color:pe.AccentPurple,children:"ctrl+y"})}})]}),(0,Hu.jsxs)(K,{color:pe.Foreground,children:[e===0?"6.":"5."," ",(0,Hu.jsx)(o3,{i18nKey:"tips.documentation",tOptions:{interpolation:{escapeValue:!1}},components:{commandDocs:(0,Hu.jsx)(K,{bold:!0,color:pe.AccentPurple,children:"/docs"}),commandDemo:(0,Hu.jsx)(K,{color:pe.AccentPurple,children:"/demo"})}})]}),(0,Hu.jsx)(K,{children:" "}),(0,Hu.jsxs)(K,{color:pe.Foreground,children:["\u203B ",r("tips.randomLabel"),": ",r(a8o)]})]})};import l8o from"util";var HIe=class{originalConsoleLog=console.log;originalConsoleWarn=console.warn;originalConsoleError=console.error;originalConsoleDebug=console.debug;params;constructor(e){this.params=e}patch(){console.log=this.patchConsoleMethod("log",this.originalConsoleLog),console.warn=this.patchConsoleMethod("warn",this.originalConsoleWarn),console.error=this.patchConsoleMethod("error",this.originalConsoleError),console.debug=this.patchConsoleMethod("debug",this.originalConsoleDebug)}cleanup=()=>{console.log=this.originalConsoleLog,console.warn=this.originalConsoleWarn,console.error=this.originalConsoleError,console.debug=this.originalConsoleDebug};formatArgs=e=>l8o.format(...e);patchConsoleMethod=(e,r)=>(...n)=>{this.params.debugMode&&r.apply(console,n),(e!=="debug"||this.params.debugMode)&&this.params.onNewMessage({type:e,content:this.formatArgs(n),count:1})}};Nt();import{promises as c8o}from"fs";import{join as u8o}from"path";var d8o=[];function Dce(t){d8o.push(t)}async function Tun(){let t=Mm(process.cwd()),e=u8o(t,"checkpoints");try{await c8o.rm(e,{recursive:!0,force:!0})}catch{}}await Br();ln();ri();var OE=Fe(_t(),1);var K5t=({messages:t,maxHeight:e,width:r})=>{let{t:n}=zt();return t.length===0?null:(0,OE.jsxs)(fe,{flexDirection:"column",marginTop:1,borderStyle:"round",borderColor:pe.Gray,paddingX:1,width:r,children:[(0,OE.jsx)(fe,{marginBottom:1,children:(0,OE.jsxs)(K,{bold:!0,color:pe.Foreground,children:[n("detailedMessagesDisplay.title")," ",(0,OE.jsxs)(K,{color:pe.Gray,children:["(",n("detailedMessagesDisplay.closeHint"),")"]})]})}),(0,OE.jsx)(l0,{maxHeight:e,maxWidth:r-4,children:t.map((o,s)=>{let a=pe.Foreground,c="\u2139";switch(o.type){case"warn":a=pe.AccentYellow,c="\u26A0";break;case"error":a=pe.AccentRed,c="\u2716";break;case"debug":a=pe.Gray,c="\u1F50D";break;case"log":default:break}return(0,OE.jsxs)(fe,{flexDirection:"row",children:[(0,OE.jsxs)(K,{color:a,children:[c," "]}),(0,OE.jsxs)(K,{color:a,wrap:"wrap",children:[o.content,o.count&&o.count>1&&(0,OE.jsxs)(K,{color:pe.Gray,children:[" (x",o.count,")"]})]})]},s)})})]})};await Br();ln();var $2=Fe(_t(),1);var Iun=({text:t,content:e})=>{let i=t.startsWith("/"),o=i?pe.AccentPurple:pe.Gray,s=i?pe.AccentPurple:pe.Gray,c=Dj(t).displayText;return e&&e.length>0?e.some(u=>u&&typeof u=="object"&&"functionResponse"in u)?void 0:(0,$2.jsxs)(fe,{borderStyle:"round",borderColor:pe.Gray,flexDirection:"row",paddingX:2,paddingY:0,marginY:1,alignSelf:"flex-start",children:[(0,$2.jsx)(fe,{width:2,children:(0,$2.jsx)(K,{color:pe.Gray,children:"> "})}),(0,$2.jsx)(fe,{flexGrow:1,flexDirection:"row",children:e.map((u,d)=>{if(typeof u=="string"){let f=Dj(u);return(0,$2.jsx)(K,{wrap:"wrap",color:pe.Gray,children:f.displayText},d)}else if(u&&typeof u=="object"&&"text"in u){let f=Dj(u.text);return(0,$2.jsx)(K,{wrap:"wrap",color:pe.Gray,children:f.displayText},d)}else if(u&&typeof u=="object"&&"inlineData"in u)return(0,$2.jsx)(K,{color:pe.Gray,children:" [Image] "},d);return null})})]}):(0,$2.jsxs)(fe,{borderStyle:"round",borderColor:s,flexDirection:"row",paddingX:2,paddingY:0,marginY:1,alignSelf:"flex-start",children:[(0,$2.jsx)(fe,{width:2,children:(0,$2.jsx)(K,{color:o,children:"> "})}),(0,$2.jsx)(fe,{flexGrow:1,children:(0,$2.jsx)(K,{wrap:"wrap",color:o,children:c})})]})};await Br();ln();var Rce=Fe(_t(),1);var Dun=({text:t})=>{let e=t.startsWith("!")?t.substring(1):t;return(0,Rce.jsxs)(fe,{children:[(0,Rce.jsx)(K,{color:pe.AccentCyan,children:"$ "}),(0,Rce.jsx)(K,{children:e})]})};await Br();var Nce=Fe(Qt(),1);await Br();ln();import{EOL as h8o}from"node:os";var tvt=Fe(Qt(),1);await Br();ln();var Nun=Fe(Qt(),1);await Br();ln();e3();var bg=Fe(_t(),1);var X5t=2,Z5t=1,evt=2,f8o=1,Run=3,Bun=4,p8o=({text:t})=>{let e=[],r=0,n=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>)/g,i;for(;(i=n.exec(t))!==null;){i.index>r&&e.push((0,bg.jsx)(K,{children:t.slice(r,i.index)},`t-${r}`));let o=i[0],s=null,a=`m-${i.index}`;try{if(o.startsWith("**")&&o.endsWith("**")&&o.length>X5t*2)s=(0,bg.jsx)(K,{bold:!0,children:o.slice(X5t,-X5t)},a);else if(o.length>Z5t*2&&(o.startsWith("*")&&o.endsWith("*")||o.startsWith("_")&&o.endsWith("_"))&&!/\w/.test(t.substring(i.index-1,i.index))&&!/\w/.test(t.substring(n.lastIndex,n.lastIndex+1))&&!/\S[./\\]/.test(t.substring(i.index-2,i.index))&&!/[./\\]\S/.test(t.substring(n.lastIndex,n.lastIndex+2)))s=(0,bg.jsx)(K,{italic:!0,children:o.slice(Z5t,-Z5t)},a);else if(o.startsWith("~~")&&o.endsWith("~~")&&o.length>evt*2)s=(0,bg.jsx)(K,{strikethrough:!0,children:o.slice(evt,-evt)},a);else if(o.startsWith("`")&&o.endsWith("`")&&o.length>f8o){let c=o.match(/^(`+)(.+?)\1$/s);c&&c[2]&&(s=(0,bg.jsx)(K,{color:pe.AccentPurple,children:c[2]},a))}else if(o.startsWith("[")&&o.includes("](")&&o.endsWith(")")){let c=o.match(/\[(.*?)\]\((.*?)\)/);if(c){let u=c[1],d=c[2];s=(0,bg.jsxs)(K,{children:[u,(0,bg.jsxs)(K,{color:pe.AccentBlue,children:[" (",d,")"]})]},a)}}else o.startsWith("<u>")&&o.endsWith("</u>")&&o.length>Run+Bun-1&&(s=(0,bg.jsx)(K,{underline:!0,children:o.slice(Run,-Bun)},a))}catch(c){console.error("Error parsing inline markdown part:",o,c),s=null}e.push(s??(0,bg.jsx)(K,{children:o},a)),r=n.lastIndex}return r<t.length&&e.push((0,bg.jsx)(K,{children:t.slice(r)},`t-${r}`)),(0,bg.jsx)(bg.Fragment,{children:e.filter(o=>o!==null)})},NA=Nun.default.memo(p8o),_z=t=>{let e=t.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1");return Ki(e)};var kE=Fe(_t(),1);var Oun=({headers:t,rows:e,terminalWidth:r})=>{let n=t.map((d,f)=>{let p=_z(d),h=Math.max(...e.map(m=>_z(m[f]||"")));return Math.max(p,h)+2}),i=n.reduce((d,f)=>d+f+1,1),o=i>r?r/i:1,s=n.map(d=>Math.floor(d*o)),a=(d,f,p=!1)=>{let h=Math.max(0,f-2),m=_z(d),g=d;if(m>h)if(h<=3)g=d.substring(0,Math.min(d.length,h));else{let E=0,C=d.length,x=d;for(;E<=C;){let T=Math.floor((E+C)/2),O=d.substring(0,T);_z(O)<=h-3?(x=O,E=T+1):C=T-1}g=x+"..."}let A=_z(g),y=Math.max(0,h-A);return(0,kE.jsxs)(K,{children:[p?(0,kE.jsx)(K,{bold:!0,color:pe.AccentCyan,children:(0,kE.jsx)(NA,{text:g})}):(0,kE.jsx)(NA,{text:g})," ".repeat(y)]})},c=d=>{let p={top:{left:"\u250C",middle:"\u252C",right:"\u2510",horizontal:"\u2500"},middle:{left:"\u251C",middle:"\u253C",right:"\u2524",horizontal:"\u2500"},bottom:{left:"\u2514",middle:"\u2534",right:"\u2518",horizontal:"\u2500"}}[d],h=s.map(g=>p.horizontal.repeat(g)),m=p.left+h.join(p.middle)+p.right;return(0,kE.jsx)(K,{children:m})},u=(d,f=!1)=>{let p=d.map((h,m)=>{let g=s[m]||0;return a(h||"",g,f)});return(0,kE.jsxs)(K,{children:["\u2502"," ",p.map((h,m)=>(0,kE.jsxs)(tvt.default.Fragment,{children:[h,m<p.length-1?" \u2502 ":""]},m))," ","\u2502"]})};return(0,kE.jsxs)(fe,{flexDirection:"column",marginY:1,children:[c("top"),u(t,!0),c("middle"),e.map((d,f)=>(0,kE.jsx)(tvt.default.Fragment,{children:u(d)},f)),c("bottom")]})};var Vi=Fe(_t(),1);var m8o=1,Bce=1,g8o=1,A8o=1,y8o=({text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})=>{if(!t)return(0,Vi.jsx)(Vi.Fragment,{});let i=t.split(h8o),o=/^ *(#{1,4}) +(.*)/,s=/^ *(`{3,}|~{3,}) *(\w*?) *$/,a=/^([ \t]*)([-*+]) +(.*)/,c=/^([ \t]*)(\d+)\. +(.*)/,u=/^ *([-*_] *){3,} *$/,d=/^\s*\|(.+)\|\s*$/,f=/^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/,p=[],h=!1,m=!0,g=[],A=null,y="",E=!1,C=[],x=[];function T(O){O&&(p.push(O),m=!1)}return i.forEach((O,N)=>{let U=`line-${N}`;if(h){let Q=O.match(s);Q&&Q[1].startsWith(y[0])&&Q[1].length>=y.length?(T((0,Vi.jsx)(kun,{content:g,lang:A,isPending:e,availableTerminalHeight:r,terminalWidth:n},U)),h=!1,g=[],A=null,y=""):g.push(O);return}let w=O.match(s),M=O.match(o),B=O.match(a),F=O.match(c),L=O.match(u),R=O.match(d),q=O.match(f);if(w)h=!0,y=w[1],A=w[2]||null;else if(R&&!E)N+1<i.length&&i[N+1].match(f)?(E=!0,x=R[1].split("|").map(Q=>Q.trim()),C=[]):T((0,Vi.jsx)(fe,{children:(0,Vi.jsx)(K,{wrap:"wrap",children:(0,Vi.jsx)(NA,{text:O})})},U));else if(!(E&&q))if(E&&R){let Q=R[1].split("|").map(V=>V.trim());for(;Q.length<x.length;)Q.push("");Q.length>x.length&&(Q.length=x.length),C.push(Q)}else if(E&&!R)x.length>0&&C.length>0&&T((0,Vi.jsx)(Pun,{headers:x,rows:C,terminalWidth:n},`table-${p.length}`)),E=!1,C=[],x=[],O.trim().length>0&&T((0,Vi.jsx)(fe,{children:(0,Vi.jsx)(K,{wrap:"wrap",children:(0,Vi.jsx)(NA,{text:O})})},U));else if(L)T((0,Vi.jsx)(fe,{children:(0,Vi.jsx)(K,{dimColor:!0,children:"---"})},U));else if(M){let Q=M[1].length,V=M[2],H=null;switch(Q){case 1:H=(0,Vi.jsx)(K,{bold:!0,color:pe.AccentCyan,children:(0,Vi.jsx)(NA,{text:V})});break;case 2:H=(0,Vi.jsx)(K,{bold:!0,color:pe.AccentBlue,children:(0,Vi.jsx)(NA,{text:V})});break;case 3:H=(0,Vi.jsx)(K,{bold:!0,children:(0,Vi.jsx)(NA,{text:V})});break;case 4:H=(0,Vi.jsx)(K,{italic:!0,color:pe.Gray,children:(0,Vi.jsx)(NA,{text:V})});break;default:H=(0,Vi.jsx)(K,{children:(0,Vi.jsx)(NA,{text:V})});break}H&&T((0,Vi.jsx)(fe,{children:H},U))}else if(B){let Q=B[1],V=B[2],H=B[3];T((0,Vi.jsx)(Mun,{itemText:H,type:"ul",marker:V,leadingWhitespace:Q},U))}else if(F){let Q=F[1],V=F[2],H=F[3];T((0,Vi.jsx)(Mun,{itemText:H,type:"ol",marker:V,leadingWhitespace:Q},U))}else O.trim().length===0&&!h?m||(p.push((0,Vi.jsx)(fe,{height:m8o},`spacer-${N}`)),m=!0):T((0,Vi.jsx)(fe,{children:(0,Vi.jsx)(K,{wrap:"wrap",children:(0,Vi.jsx)(NA,{text:O})})},U))}),h&&T((0,Vi.jsx)(kun,{content:g,lang:A,isPending:e,availableTerminalHeight:r,terminalWidth:n},"line-eof")),E&&x.length>0&&C.length>0&&T((0,Vi.jsx)(Pun,{headers:x,rows:C,terminalWidth:n},`table-${p.length}`)),(0,Vi.jsx)(Vi.Fragment,{children:p})},E8o=({content:t,lang:e,isPending:r,availableTerminalHeight:n,terminalWidth:i})=>{if(r&&n!==void 0){let u=Math.max(0,n-2);if(t.length>u){if(u<1)return(0,Vi.jsx)(fe,{paddingLeft:Bce,children:(0,Vi.jsx)(K,{color:pe.Gray,children:"... code is being written ..."})});let d=t.slice(0,u),f=SM(d.join(`
5097
5097
  `),e,n,i-Bce);return(0,Vi.jsxs)(fe,{paddingLeft:Bce,flexDirection:"column",children:[f,(0,Vi.jsx)(K,{color:pe.Gray,children:"... generating more ..."})]})}}let a=t.join(`
5098
- `),c=SM(a,e,n,i-Bce);return(0,Vi.jsx)(fe,{paddingLeft:Bce,flexDirection:"column",width:i,flexShrink:0,children:c})},kun=Nce.default.memo(E8o),v8o=({itemText:t,type:e,marker:r,leadingWhitespace:n=""})=>{let i=e==="ol"?`${r}. `:`${r} `,o=i.length,s=n.length;return(0,Vi.jsxs)(fe,{paddingLeft:s+g8o,flexDirection:"row",children:[(0,Vi.jsx)(fe,{width:o,children:(0,Vi.jsx)(K,{children:i})}),(0,Vi.jsx)(fe,{flexGrow:A8o,children:(0,Vi.jsx)(K,{wrap:"wrap",children:(0,Vi.jsx)(NA,{text:t})})})]})},Mun=Nce.default.memo(v8o),C8o=({headers:t,rows:e,terminalWidth:r})=>(0,Vi.jsx)(Oun,{headers:t,rows:e,terminalWidth:r}),Pun=Nce.default.memo(C8o),FT=Nce.default.memo(y8o);ln();var GM=Fe(_t(),1);var Lun=({text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})=>(0,GM.jsxs)(fe,{flexDirection:"row",children:[(0,GM.jsx)(fe,{width:2,children:(0,GM.jsx)(K,{color:pe.AccentPurple,children:"\u2726 "})}),(0,GM.jsx)(fe,{flexGrow:1,flexDirection:"column",children:(0,GM.jsx)(FT,{text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})})]});await Br();ln();var HM=Fe(_t(),1);var Fun=({text:t})=>(0,HM.jsxs)(fe,{flexDirection:"row",marginTop:1,children:[(0,HM.jsx)(fe,{width:2,children:(0,HM.jsx)(K,{color:pe.AccentYellow,children:"\u2139 "})}),(0,HM.jsx)(fe,{flexGrow:1,children:(0,HM.jsx)(K,{wrap:"wrap",color:pe.AccentYellow,children:t})})]});await Br();ln();var VM=Fe(_t(),1);var Uun=({text:t})=>(0,VM.jsxs)(fe,{flexDirection:"row",marginBottom:1,children:[(0,VM.jsx)(fe,{width:2,children:(0,VM.jsx)(K,{color:pe.AccentRed,children:"\u2715 "})}),(0,VM.jsx)(fe,{flexGrow:1,children:(0,VM.jsx)(K,{wrap:"wrap",color:pe.AccentRed,children:t})})]});var Kun=Fe(Qt(),1);await Br();Cs();var qun=Fe(Qt(),1);await Br();Cs();ln();var Jl=Fe(_t(),1);var b8o=1,x8o=5,Gun=3,w8o=2,Qun=1e6,S8o=["write_file","replace","multi_edit",Sj],_8o=10,VIe=({callId:t,name:e,description:r,resultDisplay:n,status:i,confirmationDetails:o,availableTerminalHeight:s,terminalWidth:a,emphasis:c="medium",renderOutputAsMarkdown:u=!0,subAgentState:d,config:f,taskTool:p,displayMarginTop:h=1,isTaskAbbreviated:m=!0})=>{let g=s?Math.max(s-b8o-x8o,w8o+1):void 0,A=S8o.includes(e),y=m?_8o:void 0;(g||A)&&(u=!1);let E=a-3;return typeof n=="string"&&n.length>Qun&&(n="..."+n.slice(-Qun)),(0,Jl.jsxs)(fe,{paddingX:1,paddingY:0,flexDirection:"column",children:[(0,Jl.jsxs)(fe,{minHeight:1,children:[(0,Jl.jsx)(T8o,{status:i}),(0,Jl.jsx)(I8o,{name:e,status:i,description:r,emphasis:c}),c==="high"&&(0,Jl.jsx)(D8o,{})]}),n&&(0,Jl.jsx)(fe,{paddingLeft:Gun,width:"100%",marginTop:h,children:(0,Jl.jsxs)(fe,{flexDirection:"column",children:[typeof n=="string"&&u&&(0,Jl.jsx)(fe,{flexDirection:"column",children:(0,Jl.jsx)(FT,{text:n,isPending:!1,availableTerminalHeight:g,terminalWidth:E})}),typeof n=="string"&&!u&&(0,Jl.jsx)(l0,{maxHeight:A?y:g,maxWidth:E,overflowDirection:"top",children:(0,Jl.jsx)(fe,{children:(0,Jl.jsx)(K,{wrap:"wrap",children:n})})}),typeof n!="string"&&(0,Jl.jsx)(NC,{diffContent:n.fileDiff,filename:n.fileName,availableTerminalHeight:A?y:g,terminalWidth:E,truncateToLastLines:A})]})})]})},T8o=({status:t})=>(0,Jl.jsxs)(fe,{minWidth:Gun,children:[t==="Pending"&&(0,Jl.jsx)(K,{color:pe.AccentGreen,children:"o"}),t==="Executing"&&(0,Jl.jsx)(rz,{spinnerType:"toggle",nonRespondingDisplay:"\u22B7"}),t==="Success"&&(0,Jl.jsx)(K,{color:pe.AccentGreen,children:"\u2705"}),t==="Confirming"&&(0,Jl.jsx)(K,{color:pe.AccentYellow,children:"?"}),t==="Canceled"&&(0,Jl.jsx)(K,{color:pe.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,Jl.jsx)(K,{color:pe.AccentRed,bold:!0,children:"x"})]}),I8o=({name:t,description:e,status:r,emphasis:n})=>{let i=qun.default.useMemo(()=>{switch(n){case"high":return pe.Foreground;case"medium":return pe.Foreground;case"low":return pe.Gray;default:return n}},[n]);return(0,Jl.jsx)(fe,{children:(0,Jl.jsxs)(K,{wrap:"truncate-end",strikethrough:r==="Canceled",children:[(0,Jl.jsx)(K,{color:i,bold:!0,children:t})," ",(0,Jl.jsx)(K,{color:pe.Gray,children:e})]})})},D8o=()=>(0,Jl.jsxs)(K,{color:pe.Foreground,wrap:"truncate",children:[" ","\u2190"]});var $un=Fe(Qt(),1);await Br();Cs();ln();var ME=Fe(Qt(),1);await Br();Nt();ln();var B8o=Fe(Qt(),1);await Br();Nt();Cs();var R8o={blue:"#3B82F6",green:"#3CA84B",yellow:"#D5A40A",purple:"#8B5CF6",orange:"#f97316",brown:"#92400e",red:"#DD4C4C"};function rvt(t){return R8o[t]||"#3B82F6"}function nvt(t){return"#ffffff"}var Hun=Fe(_t(),1);function N8o(t,e){try{if(e?.getToolRegistry){let r=e.getToolRegistry().getTool(t);if(r?.Name)return"\x1B[36m"+r.Name+"\x1B[0m"}}catch{}return"\x1B[36m"+t.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")+"\x1B[0m"}function UT(t){if(!t||typeof t!="string")return t;let e=[process.cwd()+"/","/home/","/usr/"],r=t;for(let n of e)if(r.startsWith(n)){r=r.substring(n.length);break}if(r.length>60){let n=r.split("/");if(n.length>3)return`.../${n.slice(-2).join("/")}`}return r}function O8o(t){let e=t.request.name,r=t.request.args;try{switch(e){case"google_web_search":case"web_search":if(r?.query)return` "${r.query}"`;break;case"todo_write":if(r?.todos){let n=r.todos;if(typeof r.todos=="string"){let i=r.todos.trim();if(i.startsWith("[")&&i.endsWith("]"))try{let o=r.todos;o=o.replace(/'/g,'"').replace(/(\w+):/g,'"$1":').replace(/:\s*"(\w+)"/g,': "$1"'),n=JSON.parse(o)}catch{let s=r.todos.replace(/\\n/g,`
5098
+ `),c=SM(a,e,n,i-Bce);return(0,Vi.jsx)(fe,{paddingLeft:Bce,flexDirection:"column",width:i,flexShrink:0,children:c})},kun=Nce.default.memo(E8o),v8o=({itemText:t,type:e,marker:r,leadingWhitespace:n=""})=>{let i=e==="ol"?`${r}. `:`${r} `,o=i.length,s=n.length;return(0,Vi.jsxs)(fe,{paddingLeft:s+g8o,flexDirection:"row",children:[(0,Vi.jsx)(fe,{width:o,children:(0,Vi.jsx)(K,{children:i})}),(0,Vi.jsx)(fe,{flexGrow:A8o,children:(0,Vi.jsx)(K,{wrap:"wrap",children:(0,Vi.jsx)(NA,{text:t})})})]})},Mun=Nce.default.memo(v8o),C8o=({headers:t,rows:e,terminalWidth:r})=>(0,Vi.jsx)(Oun,{headers:t,rows:e,terminalWidth:r}),Pun=Nce.default.memo(C8o),FT=Nce.default.memo(y8o);ln();var GM=Fe(_t(),1);var Lun=({text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})=>(0,GM.jsxs)(fe,{flexDirection:"row",children:[(0,GM.jsx)(fe,{width:2,children:(0,GM.jsx)(K,{color:pe.AccentPurple,children:"\u2726 "})}),(0,GM.jsx)(fe,{flexGrow:1,flexDirection:"column",children:(0,GM.jsx)(FT,{text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})})]});await Br();ln();var HM=Fe(_t(),1);var Fun=({text:t})=>(0,HM.jsxs)(fe,{flexDirection:"row",marginTop:1,children:[(0,HM.jsx)(fe,{width:2,children:(0,HM.jsx)(K,{color:pe.AccentYellow,children:"\u2139 "})}),(0,HM.jsx)(fe,{flexGrow:1,children:(0,HM.jsx)(K,{wrap:"wrap",color:pe.AccentYellow,children:t})})]});await Br();ln();var VM=Fe(_t(),1);var Uun=({text:t})=>(0,VM.jsxs)(fe,{flexDirection:"row",marginBottom:1,children:[(0,VM.jsx)(fe,{width:2,children:(0,VM.jsx)(K,{color:pe.AccentRed,children:"\u2715 "})}),(0,VM.jsx)(fe,{flexGrow:1,children:(0,VM.jsx)(K,{wrap:"wrap",color:pe.AccentRed,children:t})})]});var Kun=Fe(Qt(),1);await Br();Cs();var qun=Fe(Qt(),1);await Br();Cs();ln();var Jl=Fe(_t(),1);var b8o=1,x8o=5,Gun=3,w8o=2,Qun=1e6,S8o=["write_file","replace","multi_edit","run_shell_command",Sj],_8o=10,VIe=({callId:t,name:e,description:r,resultDisplay:n,status:i,confirmationDetails:o,availableTerminalHeight:s,terminalWidth:a,emphasis:c="medium",renderOutputAsMarkdown:u=!0,subAgentState:d,config:f,taskTool:p,displayMarginTop:h=1,isTaskAbbreviated:m=!0})=>{let g=s?Math.max(s-b8o-x8o,w8o+1):void 0,A=S8o.includes(e),y=m?_8o:void 0;(g||A)&&(u=!1);let E=a-3;return typeof n=="string"&&n.length>Qun&&(n="..."+n.slice(-Qun)),(0,Jl.jsxs)(fe,{paddingX:1,paddingY:0,flexDirection:"column",children:[(0,Jl.jsxs)(fe,{minHeight:1,children:[(0,Jl.jsx)(T8o,{status:i}),(0,Jl.jsx)(I8o,{name:e,status:i,description:r,emphasis:c}),c==="high"&&(0,Jl.jsx)(D8o,{})]}),n&&(0,Jl.jsx)(fe,{paddingLeft:Gun,width:"100%",marginTop:h,children:(0,Jl.jsxs)(fe,{flexDirection:"column",children:[typeof n=="string"&&u&&(0,Jl.jsx)(fe,{flexDirection:"column",children:(0,Jl.jsx)(FT,{text:n,isPending:!1,availableTerminalHeight:g,terminalWidth:E})}),typeof n=="string"&&!u&&(0,Jl.jsx)(l0,{maxHeight:A?y:g,maxWidth:E,overflowDirection:"top",children:(0,Jl.jsx)(fe,{children:(0,Jl.jsx)(K,{wrap:"wrap",children:n})})}),typeof n!="string"&&(0,Jl.jsx)(NC,{diffContent:n.fileDiff,filename:n.fileName,availableTerminalHeight:A?y:g,terminalWidth:E,truncateToLastLines:A})]})})]})},T8o=({status:t})=>(0,Jl.jsxs)(fe,{minWidth:Gun,children:[t==="Pending"&&(0,Jl.jsx)(K,{color:pe.AccentGreen,children:"o"}),t==="Executing"&&(0,Jl.jsx)(rz,{spinnerType:"toggle",nonRespondingDisplay:"\u22B7"}),t==="Success"&&(0,Jl.jsx)(K,{color:pe.AccentGreen,children:"\u2705"}),t==="Confirming"&&(0,Jl.jsx)(K,{color:pe.AccentYellow,children:"?"}),t==="Canceled"&&(0,Jl.jsx)(K,{color:pe.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,Jl.jsx)(K,{color:pe.AccentRed,bold:!0,children:"x"})]}),I8o=({name:t,description:e,status:r,emphasis:n})=>{let i=qun.default.useMemo(()=>{switch(n){case"high":return pe.Foreground;case"medium":return pe.Foreground;case"low":return pe.Gray;default:return n}},[n]);return(0,Jl.jsx)(fe,{children:(0,Jl.jsxs)(K,{wrap:"truncate-end",strikethrough:r==="Canceled",children:[(0,Jl.jsx)(K,{color:i,bold:!0,children:t})," ",(0,Jl.jsx)(K,{color:pe.Gray,children:e})]})})},D8o=()=>(0,Jl.jsxs)(K,{color:pe.Foreground,wrap:"truncate",children:[" ","\u2190"]});var $un=Fe(Qt(),1);await Br();Cs();ln();var ME=Fe(Qt(),1);await Br();Nt();ln();var B8o=Fe(Qt(),1);await Br();Nt();Cs();var R8o={blue:"#3B82F6",green:"#3CA84B",yellow:"#D5A40A",purple:"#8B5CF6",orange:"#f97316",brown:"#92400e",red:"#DD4C4C"};function rvt(t){return R8o[t]||"#3B82F6"}function nvt(t){return"#ffffff"}var Hun=Fe(_t(),1);function N8o(t,e){try{if(e?.getToolRegistry){let r=e.getToolRegistry().getTool(t);if(r?.Name)return"\x1B[36m"+r.Name+"\x1B[0m"}}catch{}return"\x1B[36m"+t.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")+"\x1B[0m"}function UT(t){if(!t||typeof t!="string")return t;let e=[process.cwd()+"/","/home/","/usr/"],r=t;for(let n of e)if(r.startsWith(n)){r=r.substring(n.length);break}if(r.length>60){let n=r.split("/");if(n.length>3)return`.../${n.slice(-2).join("/")}`}return r}function O8o(t){let e=t.request.name,r=t.request.args;try{switch(e){case"google_web_search":case"web_search":if(r?.query)return` "${r.query}"`;break;case"todo_write":if(r?.todos){let n=r.todos;if(typeof r.todos=="string"){let i=r.todos.trim();if(i.startsWith("[")&&i.endsWith("]"))try{let o=r.todos;o=o.replace(/'/g,'"').replace(/(\w+):/g,'"$1":').replace(/:\s*"(\w+)"/g,': "$1"'),n=JSON.parse(o)}catch{let s=r.todos.replace(/\\n/g,`
5099
5099
  `);return`Update Todos: ${s.length>100?s.slice(0,100)+"...":s}`}else{let o=r.todos.replace(/\\n/g,`
5100
5100
  `);return`Update Todos: ${o.length>100?o.slice(0,100)+"...":o}`}}if(Array.isArray(n))return`Update Todos
5101
5101
  ${n.map(o=>{let s="\u2610";return o.status==="completed"?s="\u2705":o.status==="in_progress"&&(s="\u26A1"),`${s} ${o.content||o.task}`}).join(`
@@ -5205,7 +5205,7 @@ ${k.t("gemini.errors.criticalUnhandledRejection")}
5205
5205
  =========================================
5206
5206
  ${k.t("gemini.errors.reason",{reason:e})}${e instanceof Error&&e.stack?`
5207
5207
  ${k.t("gemini.errors.stackTrace")}
5208
- ${e.stack}`:""}`;Ds.emit("log-error",n),t||(t=!0,Ds.emit("open-debug-console"))})}function LSo(){console.log(k.t("gemini.crashDiagnosticsEnabled")),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:"production",SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.3.1"}},r=`crash-${Date.now()}-${process.pid}.json`,n=TSo.join(process.cwd(),r);try{NSo.writeFileSync(n,JSON.stringify(e,null,2)),console.error(k.t("gemini.crashDetected",{crashFilePath:n})),console.error(k.t("gemini.coreDumpWillBeGenerated"))}catch(i){console.error(k.t("gemini.failedToWriteCrashFile"),i)}process.abort()}),process.on("warning",t=>{console.warn(k.t("gemini.debug.nodejsWarning"),{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error(k.t("gemini.debug.unhandledPromiseRejectionDetected"),{reason:t,promise:e.toString()})})}async function egn(){PSo();let t=process.cwd(),e=bl(t);if(!e.user.settings.cna){let p=await c0e();p&&e.setValue("User","cna",p)}if(await Tun(),e.errors.length>0){for(let p of e.errors){let h=k.t("gemini.errorInFile",{path:p.path,message:p.message});process.env.NO_COLOR||(h=`\x1B[31m${h}\x1B[0m`),console.error(h),console.error(k.t("gemini.pleaseFixFileAndTryAgain",{path:p.path}))}process.exit(1)}let r=await GIe();(!!r.prompt&&!r.promptInteractive&&!r.continue&&!r.resume||r.experimentalAcp)&&(process.env.IFLOW_NON_INTERACTIVE="true");let i=LT(t),o=await qM(e.merged,i,o0.generateSessionId(),r);if(k.changeLanguage(o.getLanguage()),o.getDebugMode()&&LSo(),RSo.setDefaultResultOrder(OSo(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error(k.t("gemini.errors.promptInteractiveFlagNotSupported")),process.exit(1)),o.getListExtensions()){console.debug(k.t("gemini.installedExtensions"));for(let p of i)console.debug(`- ${p.config.name}`);process.exit(0)}if(r._&&r._[0]==="agent"){let{agentCommand:p}=await Promise.resolve().then(()=>($5t(),Cun)),h=(await Promise.resolve().then(()=>(x8t(),b8t))).default;await h().scriptName("iflow").command(p).help().version(!1).parse(),process.exit(0)}if(r._&&r._[0]==="commands"){let{commandsCommand:p}=await Promise.resolve().then(()=>(V5t(),lun)),h=(await Promise.resolve().then(()=>(x8t(),b8t))).default;await h().scriptName("iflow").command(p).help().version(!1).parse(),process.exit(0)}if(e.merged.selectedAuthType||process.env.CLOUD_SHELL==="true"&&e.setValue("User","selectedAuthType",$t.CLOUD_SHELL),jsn(o.getDebugMode()),await o.initialize(),Ma.loadCustomThemes(e.merged.customThemes),e.merged.theme&&(Ma.setActiveTheme(e.merged.theme)||console.warn(k.t("gemini.themeNotFound",{theme:e.merged.theme}))),!process.env.SANDBOX){let p=e.merged.autoConfigureMaxOldSpaceSize?kSo(o):[],h=o.getSandbox();if(h){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let m=TM(e.merged.selectedAuthType);if(m)throw new Error(m);await o.refreshAuth(e.merged.selectedAuthType,{apiKey:e.merged.apiKey,baseUrl:e.merged.baseUrl,modelName:e.merged.modelName})}catch(m){console.error(k.t("gemini.errorAuthenticating"),m),process.exit(1)}await Dfn(h,p,o),process.exit(0)}else p.length>0&&(await MSo(p),process.exit(0))}if(e.merged.selectedAuthType===$t.LOGIN_WITH_IFLOW&&o.isBrowserLaunchSuppressed()&&await pD(e.merged.selectedAuthType,o),o.getExperimentalAcp())return o.getAcpPort()?await dmn(o,e,i,r,o.getAcpPort()):imn(o,e,i,r);let s=o.getQuestion(),a=[...await Rfn(),...await Nfn(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume||process.stdin.isTTY&&s?.length===0){console.clear();let p=await wT();Zmn(Xmn(t),e);try{await o.setIdeModeAndSyncConnection(!0)}catch(E){console.error(k.t("gemini.failedToConnectToIdeServer"),E)}let h,m=async()=>{try{if(console.clear(),Zmn(Xmn(t),e),h)try{h.unmount(),await new Promise(x=>process.nextTick(x))}catch(x){console.error(k.t("gemini.errorDuringUnmount"),x)}let{executeSessionStartHooks:E}=await Promise.resolve().then(()=>(mM(),hM)),C=await E(o,"resume");h=pfe((0,lue.jsx)(w8t.default.StrictMode,{children:(0,lue.jsx)(Tvt,{instance:()=>h,config:o,settings:e,startupWarnings:a,version:p,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,fgMode:!0,sessionStartContext:C})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1})}catch(E){console.error(k.t("gemini.errorDuringResume"),E)}};process.on("SIGCONT",m),Dce(()=>{process.off("SIGCONT",m)});let g="startup";(r.continue||r.resume)&&(g="resume");let{executeSessionStartHooks:A}=await Promise.resolve().then(()=>(mM(),hM)),y=await A(o,g);h=pfe((0,lue.jsx)(w8t.default.StrictMode,{children:(0,lue.jsx)(Tvt,{instance:()=>h,config:o,settings:e,startupWarnings:a,version:p,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,sessionStartContext:y})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1}),e.merged.disableAutoUpdate||J0n().then(E=>{$dn(E,e,o.getProjectRoot())}).catch(E=>{o.getDebugMode()&&console.error(k.t("gemini.updateCheckFailed"),E)}),Dce(()=>h.unmount());return}!process.stdin.isTTY&&!s&&(s+=await Sfn()),s||(console.error(k.t("gemini.noInputProvidedViaStdin")),process.exit(1));let u=Math.random().toString(16).slice(2);rj(o,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:s,prompt_id:u,auth_type:o.getContentGeneratorConfig()?.authType,prompt_length:s.length});let d=await FSo(o,i,e,r),f=r.outputFile||r.output_file;await kfn(d,s,u,f),process.exit(0)}function Zmn(t,e){if(!e.merged.hideWindowTitle){let r=(process.env.CLI_TITLE||`iFlow - ${t}`).replace(/[\x00-\x1F\x7F]/g,"");process.stdout.write(`\x1B]2;${r}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}async function FSo(t,e,r,n){let i=t;if(t.getApprovalMode()!==jn.YOLO){let o=r.merged.excludeTools||[],s=[pu.Name,Af.Name,ld.Name],a=[...new Set([...o,...s])],c={...r.merged,excludeTools:a},u={...n};i=await qM(c,e,t.getSessionId(),u),await i.initialize()}return await USo(r.merged.selectedAuthType,i,r)}async function USo(t,e,r){!t&&!process.env.GEMINI_API_KEY&&!b0e()&&(console.error(k.t("gemini.pleaseSetAuthMethod",{userSettingsPath:cM})),process.exit(1)),t||(b0e()?t=$t.IFLOW:t=$t.IFLOW);let n=TM(t);return n!=null&&(console.error(n),process.exit(1)),await e.refreshAuth(t,{apiKey:r.merged.apiKey,baseUrl:r.merged.baseUrl,modelName:r.merged.modelName}),e}egn().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
5208
+ ${e.stack}`:""}`;Ds.emit("log-error",n),t||(t=!0,Ds.emit("open-debug-console"))})}function LSo(){console.log(k.t("gemini.crashDiagnosticsEnabled")),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:"production",SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.3.2-beta.0"}},r=`crash-${Date.now()}-${process.pid}.json`,n=TSo.join(process.cwd(),r);try{NSo.writeFileSync(n,JSON.stringify(e,null,2)),console.error(k.t("gemini.crashDetected",{crashFilePath:n})),console.error(k.t("gemini.coreDumpWillBeGenerated"))}catch(i){console.error(k.t("gemini.failedToWriteCrashFile"),i)}process.abort()}),process.on("warning",t=>{console.warn(k.t("gemini.debug.nodejsWarning"),{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error(k.t("gemini.debug.unhandledPromiseRejectionDetected"),{reason:t,promise:e.toString()})})}async function egn(){PSo();let t=process.cwd(),e=bl(t);if(!e.user.settings.cna){let p=await c0e();p&&e.setValue("User","cna",p)}if(await Tun(),e.errors.length>0){for(let p of e.errors){let h=k.t("gemini.errorInFile",{path:p.path,message:p.message});process.env.NO_COLOR||(h=`\x1B[31m${h}\x1B[0m`),console.error(h),console.error(k.t("gemini.pleaseFixFileAndTryAgain",{path:p.path}))}process.exit(1)}let r=await GIe();(!!r.prompt&&!r.promptInteractive&&!r.continue&&!r.resume||r.experimentalAcp)&&(process.env.IFLOW_NON_INTERACTIVE="true");let i=LT(t),o=await qM(e.merged,i,o0.generateSessionId(),r);if(k.changeLanguage(o.getLanguage()),o.getDebugMode()&&LSo(),RSo.setDefaultResultOrder(OSo(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error(k.t("gemini.errors.promptInteractiveFlagNotSupported")),process.exit(1)),o.getListExtensions()){console.debug(k.t("gemini.installedExtensions"));for(let p of i)console.debug(`- ${p.config.name}`);process.exit(0)}if(r._&&r._[0]==="agent"){let{agentCommand:p}=await Promise.resolve().then(()=>($5t(),Cun)),h=(await Promise.resolve().then(()=>(x8t(),b8t))).default;await h().scriptName("iflow").command(p).help().version(!1).parse(),process.exit(0)}if(r._&&r._[0]==="commands"){let{commandsCommand:p}=await Promise.resolve().then(()=>(V5t(),lun)),h=(await Promise.resolve().then(()=>(x8t(),b8t))).default;await h().scriptName("iflow").command(p).help().version(!1).parse(),process.exit(0)}if(e.merged.selectedAuthType||process.env.CLOUD_SHELL==="true"&&e.setValue("User","selectedAuthType",$t.CLOUD_SHELL),jsn(o.getDebugMode()),await o.initialize(),Ma.loadCustomThemes(e.merged.customThemes),e.merged.theme&&(Ma.setActiveTheme(e.merged.theme)||console.warn(k.t("gemini.themeNotFound",{theme:e.merged.theme}))),!process.env.SANDBOX){let p=e.merged.autoConfigureMaxOldSpaceSize?kSo(o):[],h=o.getSandbox();if(h){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let m=TM(e.merged.selectedAuthType);if(m)throw new Error(m);await o.refreshAuth(e.merged.selectedAuthType,{apiKey:e.merged.apiKey,baseUrl:e.merged.baseUrl,modelName:e.merged.modelName})}catch(m){console.error(k.t("gemini.errorAuthenticating"),m),process.exit(1)}await Dfn(h,p,o),process.exit(0)}else p.length>0&&(await MSo(p),process.exit(0))}if(e.merged.selectedAuthType===$t.LOGIN_WITH_IFLOW&&o.isBrowserLaunchSuppressed()&&await pD(e.merged.selectedAuthType,o),o.getExperimentalAcp())return o.getAcpPort()?await dmn(o,e,i,r,o.getAcpPort()):imn(o,e,i,r);let s=o.getQuestion(),a=[...await Rfn(),...await Nfn(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume||process.stdin.isTTY&&s?.length===0){console.clear();let p=await wT();Zmn(Xmn(t),e);try{await o.setIdeModeAndSyncConnection(!0)}catch(E){console.error(k.t("gemini.failedToConnectToIdeServer"),E)}let h,m=async()=>{try{if(console.clear(),Zmn(Xmn(t),e),h)try{h.unmount(),await new Promise(x=>process.nextTick(x))}catch(x){console.error(k.t("gemini.errorDuringUnmount"),x)}let{executeSessionStartHooks:E}=await Promise.resolve().then(()=>(mM(),hM)),C=await E(o,"resume");h=pfe((0,lue.jsx)(w8t.default.StrictMode,{children:(0,lue.jsx)(Tvt,{instance:()=>h,config:o,settings:e,startupWarnings:a,version:p,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,fgMode:!0,sessionStartContext:C})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1})}catch(E){console.error(k.t("gemini.errorDuringResume"),E)}};process.on("SIGCONT",m),Dce(()=>{process.off("SIGCONT",m)});let g="startup";(r.continue||r.resume)&&(g="resume");let{executeSessionStartHooks:A}=await Promise.resolve().then(()=>(mM(),hM)),y=await A(o,g);h=pfe((0,lue.jsx)(w8t.default.StrictMode,{children:(0,lue.jsx)(Tvt,{instance:()=>h,config:o,settings:e,startupWarnings:a,version:p,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,sessionStartContext:y})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1}),e.merged.disableAutoUpdate||J0n().then(E=>{$dn(E,e,o.getProjectRoot())}).catch(E=>{o.getDebugMode()&&console.error(k.t("gemini.updateCheckFailed"),E)}),Dce(()=>h.unmount());return}!process.stdin.isTTY&&!s&&(s+=await Sfn()),s||(console.error(k.t("gemini.noInputProvidedViaStdin")),process.exit(1));let u=Math.random().toString(16).slice(2);rj(o,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:s,prompt_id:u,auth_type:o.getContentGeneratorConfig()?.authType,prompt_length:s.length});let d=await FSo(o,i,e,r),f=r.outputFile||r.output_file;await kfn(d,s,u,f),process.exit(0)}function Zmn(t,e){if(!e.merged.hideWindowTitle){let r=(process.env.CLI_TITLE||`iFlow - ${t}`).replace(/[\x00-\x1F\x7F]/g,"");process.stdout.write(`\x1B]2;${r}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}async function FSo(t,e,r,n){let i=t;if(t.getApprovalMode()!==jn.YOLO){let o=r.merged.excludeTools||[],s=[pu.Name,Af.Name,ld.Name],a=[...new Set([...o,...s])],c={...r.merged,excludeTools:a},u={...n};i=await qM(c,e,t.getSessionId(),u),await i.initialize()}return await USo(r.merged.selectedAuthType,i,r)}async function USo(t,e,r){!t&&!process.env.GEMINI_API_KEY&&!b0e()&&(console.error(k.t("gemini.pleaseSetAuthMethod",{userSettingsPath:cM})),process.exit(1)),t||(b0e()?t=$t.IFLOW:t=$t.IFLOW);let n=TM(t);return n!=null&&(console.error(n),process.exit(1)),await e.refreshAuth(t,{apiKey:r.merged.apiKey,baseUrl:r.merged.baseUrl,modelName:r.merged.modelName}),e}egn().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
5209
5209
  /**
5210
5210
  * @license
5211
5211
  * Copyright 2025 Google LLC